summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTobias Markmann <tm@ayena.de>2016-03-31 14:57:35 (GMT)
committerTobias Markmann <tm@ayena.de>2016-03-31 14:57:35 (GMT)
commitcfbdb43d2cadd40aa87338d41548e4bf89e146e6 (patch)
tree18d94153a302445196fc0c18586abf44a1ce4a38
parent1d545a4a7fb877f021508094b88c1f17b30d8b4e (diff)
downloadswift-cfbdb43d2cadd40aa87338d41548e4bf89e146e6.zip
swift-cfbdb43d2cadd40aa87338d41548e4bf89e146e6.tar.bz2
Convert tabs to 4 spaces for all source files
Removed trailing spaces and whitespace on empty lines in the process. Changed CheckTabs.py tool to disallow hard tabs in source files. Test-Information: Manually checked 30 random files that the conversion worked as expected. Change-Id: I874f99d617bd3d2bb55f02d58f22f58f9b094480
-rwxr-xr-xBuildTools/CheckTabs.py36
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp32
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp14
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp30
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp72
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp130
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp146
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp174
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp86
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h20
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h50
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h12
-rw-r--r--Limber/Server/ServerFromClientSession.cpp150
-rw-r--r--Limber/Server/ServerFromClientSession.h84
-rw-r--r--Limber/Server/ServerSession.h14
-rw-r--r--Limber/Server/ServerStanzaRouter.cpp78
-rw-r--r--Limber/Server/ServerStanzaRouter.h20
-rw-r--r--Limber/Server/SimpleUserRegistry.cpp6
-rw-r--r--Limber/Server/SimpleUserRegistry.h18
-rw-r--r--Limber/Server/UnitTest/ServerStanzaRouterTest.cpp262
-rw-r--r--Limber/Server/UserRegistry.h12
-rw-r--r--Limber/main.cpp130
-rw-r--r--QA/Checker/IO.cpp80
-rw-r--r--QA/Checker/checker.cpp118
-rw-r--r--QA/UnitTest/template/FooTest.cpp20
-rw-r--r--Slimber/CLI/DummyMenulet.h34
-rw-r--r--Slimber/CLI/main.cpp12
-rw-r--r--Slimber/Cocoa/CocoaController.mm14
-rw-r--r--Slimber/Cocoa/CocoaMenulet.h34
-rw-r--r--Slimber/Cocoa/CocoaMenulet.mm86
-rw-r--r--Slimber/Cocoa/main.mm8
-rw-r--r--Slimber/FileVCardCollection.cpp30
-rw-r--r--Slimber/FileVCardCollection.h16
-rw-r--r--Slimber/LinkLocalPresenceManager.cpp120
-rw-r--r--Slimber/LinkLocalPresenceManager.h44
-rw-r--r--Slimber/MainController.cpp144
-rw-r--r--Slimber/MainController.h48
-rw-r--r--Slimber/Menulet.h20
-rw-r--r--Slimber/MenuletController.cpp56
-rw-r--r--Slimber/MenuletController.h44
-rw-r--r--Slimber/Qt/QtAboutDialog.cpp44
-rw-r--r--Slimber/Qt/QtAboutDialog.h4
-rw-r--r--Slimber/Qt/QtMenulet.h100
-rw-r--r--Slimber/Qt/main.cpp22
-rw-r--r--Slimber/Server.cpp658
-rw-r--r--Slimber/Server.h194
-rw-r--r--Slimber/ServerError.h42
-rw-r--r--Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp466
-rw-r--r--Slimber/UnitTest/MenuletControllerTest.cpp278
-rw-r--r--Slimber/VCardCollection.h12
-rw-r--r--Sluift/Completer.h10
-rw-r--r--Sluift/Console.cpp418
-rw-r--r--Sluift/Console.h36
-rw-r--r--Sluift/EditlineTerminal.cpp68
-rw-r--r--Sluift/EditlineTerminal.h20
-rw-r--r--Sluift/ElementConvertors/BodyConvertor.cpp20
-rw-r--r--Sluift/ElementConvertors/BodyConvertor.h16
-rw-r--r--Sluift/ElementConvertors/CommandConvertor.cpp322
-rw-r--r--Sluift/ElementConvertors/CommandConvertor.h20
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.cpp318
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.h20
-rw-r--r--Sluift/ElementConvertors/DefaultElementConvertor.cpp10
-rw-r--r--Sluift/ElementConvertors/DefaultElementConvertor.h14
-rw-r--r--Sluift/ElementConvertors/DelayConvertor.cpp40
-rw-r--r--Sluift/ElementConvertors/DelayConvertor.h14
-rw-r--r--Sluift/ElementConvertors/DiscoInfoConvertor.cpp174
-rw-r--r--Sluift/ElementConvertors/DiscoInfoConvertor.h16
-rw-r--r--Sluift/ElementConvertors/DiscoItemsConvertor.cpp84
-rw-r--r--Sluift/ElementConvertors/DiscoItemsConvertor.h14
-rw-r--r--Sluift/ElementConvertors/ElementConvertors.ipp78
-rw-r--r--Sluift/ElementConvertors/FormConvertor.cpp650
-rw-r--r--Sluift/ElementConvertors/FormConvertor.h14
-rw-r--r--Sluift/ElementConvertors/ForwardedConvertor.cpp76
-rw-r--r--Sluift/ElementConvertors/ForwardedConvertor.h24
-rw-r--r--Sluift/ElementConvertors/IQConvertor.cpp80
-rw-r--r--Sluift/ElementConvertors/IQConvertor.h26
-rw-r--r--Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp42
-rw-r--r--Sluift/ElementConvertors/IsodeIQDelegationConvertor.h22
-rw-r--r--Sluift/ElementConvertors/MAMFinConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/MAMFinConvertor.h22
-rw-r--r--Sluift/ElementConvertors/MAMQueryConvertor.cpp108
-rw-r--r--Sluift/ElementConvertors/MAMQueryConvertor.h22
-rw-r--r--Sluift/ElementConvertors/MAMResultConvertor.cpp80
-rw-r--r--Sluift/ElementConvertors/MAMResultConvertor.h22
-rw-r--r--Sluift/ElementConvertors/MessageConvertor.cpp100
-rw-r--r--Sluift/ElementConvertors/MessageConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PresenceConvertor.cpp124
-rw-r--r--Sluift/ElementConvertors/PresenceConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp120
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp92
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubConfigureConvertor.cpp42
-rw-r--r--Sluift/ElementConvertors/PubSubConfigureConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubCreateConvertor.cpp58
-rw-r--r--Sluift/ElementConvertors/PubSubCreateConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubDefaultConvertor.cpp88
-rw-r--r--Sluift/ElementConvertors/PubSubDefaultConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubEventAssociateConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp84
-rw-r--r--Sluift/ElementConvertors/PubSubEventCollectionConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp58
-rw-r--r--Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubEventConvertor.cpp18
-rw-r--r--Sluift/ElementConvertors/PubSubEventConvertor.h20
-rw-r--r--Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp58
-rw-r--r--Sluift/ElementConvertors/PubSubEventDeleteConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemConvertor.cpp140
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp156
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubEventPurgeConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubEventRedirectConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubEventRetractConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp148
-rw-r--r--Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubItemConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/PubSubItemConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubItemsConvertor.cpp128
-rw-r--r--Sluift/ElementConvertors/PubSubItemsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOptionsConvertor.cpp94
-rw-r--r--Sluift/ElementConvertors/PubSubOptionsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp120
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp88
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp62
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp42
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp58
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp88
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubPublishConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/PubSubPublishConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubRetractConvertor.cpp112
-rw-r--r--Sluift/ElementConvertors/PubSubRetractConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp78
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp32
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h18
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp162
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp92
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h22
-rw-r--r--Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp72
-rw-r--r--Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h18
-rw-r--r--Sluift/ElementConvertors/RawXMLElementConvertor.cpp24
-rw-r--r--Sluift/ElementConvertors/RawXMLElementConvertor.h18
-rw-r--r--Sluift/ElementConvertors/ResultSetConvertor.cpp172
-rw-r--r--Sluift/ElementConvertors/ResultSetConvertor.h18
-rw-r--r--Sluift/ElementConvertors/SecurityLabelConvertor.cpp134
-rw-r--r--Sluift/ElementConvertors/SecurityLabelConvertor.h18
-rw-r--r--Sluift/ElementConvertors/SoftwareVersionConvertor.cpp48
-rw-r--r--Sluift/ElementConvertors/SoftwareVersionConvertor.h14
-rw-r--r--Sluift/ElementConvertors/StanzaConvertor.h128
-rw-r--r--Sluift/ElementConvertors/StatusConvertor.cpp20
-rw-r--r--Sluift/ElementConvertors/StatusConvertor.h14
-rw-r--r--Sluift/ElementConvertors/StatusShowConvertor.cpp82
-rw-r--r--Sluift/ElementConvertors/StatusShowConvertor.h18
-rw-r--r--Sluift/ElementConvertors/SubjectConvertor.cpp20
-rw-r--r--Sluift/ElementConvertors/SubjectConvertor.h16
-rw-r--r--Sluift/ElementConvertors/UserLocationConvertor.cpp456
-rw-r--r--Sluift/ElementConvertors/UserLocationConvertor.h18
-rw-r--r--Sluift/ElementConvertors/UserTuneConvertor.cpp156
-rw-r--r--Sluift/ElementConvertors/UserTuneConvertor.h18
-rw-r--r--Sluift/ElementConvertors/VCardConvertor.cpp1202
-rw-r--r--Sluift/ElementConvertors/VCardConvertor.h14
-rw-r--r--Sluift/ElementConvertors/VCardUpdateConvertor.cpp20
-rw-r--r--Sluift/ElementConvertors/VCardUpdateConvertor.h14
-rw-r--r--Sluift/GenericLuaElementConvertor.h72
-rw-r--r--Sluift/Helpers.cpp92
-rw-r--r--Sluift/Helpers.h8
-rw-r--r--Sluift/ITunesInterface.h46
-rw-r--r--Sluift/ITunesInterface.mm44
-rw-r--r--Sluift/Lua/Check.cpp60
-rw-r--r--Sluift/Lua/Check.h22
-rw-r--r--Sluift/Lua/Debug.h30
-rw-r--r--Sluift/Lua/Exception.h16
-rw-r--r--Sluift/Lua/FunctionRegistration.cpp2
-rw-r--r--Sluift/Lua/FunctionRegistration.h44
-rw-r--r--Sluift/Lua/FunctionRegistry.cpp52
-rw-r--r--Sluift/Lua/FunctionRegistry.h64
-rw-r--r--Sluift/Lua/LuaUtils.cpp294
-rw-r--r--Sluift/Lua/LuaUtils.h48
-rw-r--r--Sluift/Lua/Value.cpp80
-rw-r--r--Sluift/Lua/Value.h82
-rw-r--r--Sluift/LuaElementConvertor.h34
-rw-r--r--Sluift/LuaElementConvertors.cpp142
-rw-r--r--Sluift/LuaElementConvertors.h66
-rw-r--r--Sluift/Response.cpp106
-rw-r--r--Sluift/Response.h40
-rw-r--r--Sluift/SluiftClient.cpp222
-rw-r--r--Sluift/SluiftClient.h204
-rw-r--r--Sluift/SluiftComponent.cpp164
-rw-r--r--Sluift/SluiftComponent.h158
-rw-r--r--Sluift/SluiftGlobals.h30
-rw-r--r--Sluift/StandardTerminal.cpp20
-rw-r--r--Sluift/StandardTerminal.h16
-rw-r--r--Sluift/Terminal.h34
-rw-r--r--Sluift/UnitTest/TokenizeTest.cpp76
-rw-r--r--Sluift/Watchdog.cpp56
-rw-r--r--Sluift/Watchdog.h30
-rw-r--r--Sluift/client.cpp1178
-rw-r--r--Sluift/component.cpp680
-rw-r--r--Sluift/globals.h6
-rw-r--r--Sluift/main.cpp250
-rw-r--r--Sluift/sluift.cpp622
-rw-r--r--Sluift/tokenize.cpp126
-rw-r--r--Sluift/tokenize.h6
-rw-r--r--SwifTools/Application/ApplicationPathProvider.cpp34
-rw-r--r--SwifTools/Application/ApplicationPathProvider.h34
-rw-r--r--SwifTools/Application/CocoaApplication.h16
-rw-r--r--SwifTools/Application/CocoaApplication.mm14
-rw-r--r--SwifTools/Application/MacOSXApplicationPathProvider.cpp22
-rw-r--r--SwifTools/Application/MacOSXApplicationPathProvider.h22
-rw-r--r--SwifTools/Application/PlatformApplicationPathProvider.h6
-rw-r--r--SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp62
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.cpp62
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.h22
-rw-r--r--SwifTools/Application/WindowsApplicationPathProvider.cpp24
-rw-r--r--SwifTools/Application/WindowsApplicationPathProvider.h22
-rw-r--r--SwifTools/AutoUpdater/AutoUpdater.h10
-rw-r--r--SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp10
-rw-r--r--SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h12
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdater.h20
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdater.mm24
-rw-r--r--SwifTools/Cocoa/CocoaAction.mm18
-rw-r--r--SwifTools/Cocoa/CocoaUtil.h40
-rw-r--r--SwifTools/CrashReporter.cpp50
-rw-r--r--SwifTools/CrashReporter.h14
-rw-r--r--SwifTools/Dock/Dock.h12
-rw-r--r--SwifTools/Dock/MacOSXDock.h14
-rw-r--r--SwifTools/Dock/MacOSXDock.mm10
-rw-r--r--SwifTools/Dock/NullDock.h12
-rw-r--r--SwifTools/Dock/WindowsDock.h52
-rw-r--r--SwifTools/HunspellChecker.cpp52
-rw-r--r--SwifTools/HunspellChecker.h20
-rw-r--r--SwifTools/Idle/ActualIdleDetector.cpp16
-rw-r--r--SwifTools/Idle/ActualIdleDetector.h26
-rw-r--r--SwifTools/Idle/DummyIdleQuerier.h14
-rw-r--r--SwifTools/Idle/IdleDetector.h60
-rw-r--r--SwifTools/Idle/IdleQuerier.h10
-rw-r--r--SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp14
-rw-r--r--SwifTools/Idle/MacOSXIdleQuerier.cpp22
-rw-r--r--SwifTools/Idle/MacOSXIdleQuerier.h14
-rw-r--r--SwifTools/Idle/PlatformIdleQuerier.cpp12
-rw-r--r--SwifTools/Idle/PlatformIdleQuerier.h20
-rw-r--r--SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp296
-rw-r--r--SwifTools/Idle/WindowsIdleQuerier.cpp16
-rw-r--r--SwifTools/Idle/WindowsIdleQuerier.h10
-rw-r--r--SwifTools/Idle/XSSIdleQuerier.cpp38
-rw-r--r--SwifTools/Idle/XSSIdleQuerier.h22
-rw-r--r--SwifTools/LastLineTracker.cpp24
-rw-r--r--SwifTools/LastLineTracker.h18
-rw-r--r--SwifTools/Linkify.cpp160
-rw-r--r--SwifTools/Linkify.h28
-rw-r--r--SwifTools/MacOSXChecker.h16
-rw-r--r--SwifTools/MacOSXChecker.mm50
-rw-r--r--SwifTools/Notifier/GNTPNotifier.cpp88
-rw-r--r--SwifTools/Notifier/GNTPNotifier.h46
-rw-r--r--SwifTools/Notifier/GrowlNotifier.h54
-rw-r--r--SwifTools/Notifier/GrowlNotifier.mm130
-rw-r--r--SwifTools/Notifier/GrowlNotifierDelegate.h8
-rw-r--r--SwifTools/Notifier/GrowlNotifierDelegate.mm8
-rw-r--r--SwifTools/Notifier/LoggingNotifier.h32
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifier.h22
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifier.mm98
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifierDelegate.h2
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifierDelegate.mm6
-rw-r--r--SwifTools/Notifier/Notifier.cpp40
-rw-r--r--SwifTools/Notifier/Notifier.h70
-rw-r--r--SwifTools/Notifier/NullNotifier.h14
-rw-r--r--SwifTools/Notifier/SnarlNotifier.cpp74
-rw-r--r--SwifTools/Notifier/SnarlNotifier.h48
-rw-r--r--SwifTools/Notifier/TogglableNotifier.h100
-rw-r--r--SwifTools/Notifier/Win32NotifierWindow.h12
-rw-r--r--SwifTools/SpellChecker.h28
-rw-r--r--SwifTools/SpellCheckerFactory.cpp16
-rw-r--r--SwifTools/SpellCheckerFactory.h12
-rw-r--r--SwifTools/SpellParser.cpp76
-rw-r--r--SwifTools/SpellParser.h26
-rw-r--r--SwifTools/TabComplete.cpp60
-rw-r--r--SwifTools/TabComplete.h22
-rw-r--r--SwifTools/URIHandler/MacOSXURIHandler.h20
-rw-r--r--SwifTools/URIHandler/MacOSXURIHandler.mm54
-rw-r--r--SwifTools/URIHandler/NullURIHandler.h14
-rw-r--r--SwifTools/URIHandler/URIHandler.h12
-rw-r--r--SwifTools/URIHandler/UnitTest/XMPPURITest.cpp312
-rw-r--r--SwifTools/URIHandler/XMPPURI.cpp138
-rw-r--r--SwifTools/URIHandler/XMPPURI.h116
-rw-r--r--SwifTools/UnitTest/LastLineTrackerTest.cpp92
-rw-r--r--SwifTools/UnitTest/LinkifyTest.cpp448
-rw-r--r--SwifTools/UnitTest/SpellParserTest.cpp64
-rw-r--r--SwifTools/UnitTest/TabCompleteTest.cpp486
-rw-r--r--Swift/Controllers/AdHocController.cpp12
-rw-r--r--Swift/Controllers/AdHocController.h12
-rw-r--r--Swift/Controllers/AdHocManager.cpp96
-rw-r--r--Swift/Controllers/AdHocManager.h30
-rw-r--r--Swift/Controllers/BlockListController.cpp256
-rw-r--r--Swift/Controllers/BlockListController.h30
-rw-r--r--Swift/Controllers/CertificateMemoryStorageFactory.h24
-rw-r--r--Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h64
-rw-r--r--Swift/Controllers/Chat/ChatController.cpp696
-rw-r--r--Swift/Controllers/Chat/ChatController.h192
-rw-r--r--Swift/Controllers/Chat/ChatControllerBase.cpp562
-rw-r--r--Swift/Controllers/Chat/ChatControllerBase.h194
-rw-r--r--Swift/Controllers/Chat/ChatMessageParser.cpp346
-rw-r--r--Swift/Controllers/Chat/ChatMessageParser.h22
-rw-r--r--Swift/Controllers/Chat/ChatsManager.cpp1594
-rw-r--r--Swift/Controllers/Chat/ChatsManager.h310
-rw-r--r--Swift/Controllers/Chat/MUCController.cpp1796
-rw-r--r--Swift/Controllers/Chat/MUCController.h308
-rw-r--r--Swift/Controllers/Chat/MUCSearchController.cpp228
-rw-r--r--Swift/Controllers/Chat/MUCSearchController.h198
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp516
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp1592
-rw-r--r--Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp998
-rw-r--r--Swift/Controllers/Chat/UnitTest/MockChatListWindow.h28
-rw-r--r--Swift/Controllers/Chat/UserSearchController.cpp564
-rw-r--r--Swift/Controllers/Chat/UserSearchController.h132
-rw-r--r--Swift/Controllers/ChatMessageSummarizer.cpp52
-rw-r--r--Swift/Controllers/ChatMessageSummarizer.h8
-rw-r--r--Swift/Controllers/ConnectionSettings.h54
-rw-r--r--Swift/Controllers/Contact.cpp74
-rw-r--r--Swift/Controllers/Contact.h24
-rw-r--r--Swift/Controllers/ContactEditController.cpp124
-rw-r--r--Swift/Controllers/ContactEditController.h66
-rw-r--r--Swift/Controllers/ContactProvider.h6
-rw-r--r--Swift/Controllers/ContactSuggester.cpp62
-rw-r--r--Swift/Controllers/ContactSuggester.h40
-rw-r--r--Swift/Controllers/ContactsFromXMPPRoster.cpp18
-rw-r--r--Swift/Controllers/ContactsFromXMPPRoster.h18
-rw-r--r--Swift/Controllers/DummySoundPlayer.h8
-rw-r--r--Swift/Controllers/DummySystemTray.h12
-rw-r--r--Swift/Controllers/EventNotifier.cpp74
-rw-r--r--Swift/Controllers/EventNotifier.h50
-rw-r--r--Swift/Controllers/EventWindowController.cpp52
-rw-r--r--Swift/Controllers/EventWindowController.h24
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferController.cpp172
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferController.h68
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferOverview.cpp82
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferOverview.h28
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp18
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferProgressInfo.h14
-rw-r--r--Swift/Controllers/FileTransferListController.cpp34
-rw-r--r--Swift/Controllers/FileTransferListController.h14
-rw-r--r--Swift/Controllers/HighlightAction.cpp52
-rw-r--r--Swift/Controllers/HighlightAction.h118
-rw-r--r--Swift/Controllers/HighlightEditorController.cpp30
-rw-r--r--Swift/Controllers/HighlightEditorController.h40
-rw-r--r--Swift/Controllers/HighlightManager.cpp114
-rw-r--r--Swift/Controllers/HighlightManager.h112
-rw-r--r--Swift/Controllers/HighlightRule.cpp212
-rw-r--r--Swift/Controllers/HighlightRule.h112
-rw-r--r--Swift/Controllers/Highlighter.cpp32
-rw-r--r--Swift/Controllers/Highlighter.h32
-rw-r--r--Swift/Controllers/HistoryController.cpp26
-rw-r--r--Swift/Controllers/HistoryController.h32
-rw-r--r--Swift/Controllers/HistoryViewController.cpp530
-rw-r--r--Swift/Controllers/HistoryViewController.h84
-rw-r--r--Swift/Controllers/Intl.h2
-rw-r--r--Swift/Controllers/MainController.cpp1402
-rw-r--r--Swift/Controllers/MainController.h326
-rw-r--r--Swift/Controllers/PresenceNotifier.cpp168
-rw-r--r--Swift/Controllers/PresenceNotifier.h78
-rw-r--r--Swift/Controllers/PreviousStatusStore.cpp46
-rw-r--r--Swift/Controllers/PreviousStatusStore.h22
-rw-r--r--Swift/Controllers/ProfileController.cpp126
-rw-r--r--Swift/Controllers/ProfileController.h62
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.cpp62
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.h28
-rw-r--r--Swift/Controllers/Roster/ContactRosterItem.cpp120
-rw-r--r--Swift/Controllers/Roster/ContactRosterItem.h126
-rw-r--r--Swift/Controllers/Roster/FuzzyRosterFilter.h30
-rw-r--r--Swift/Controllers/Roster/GroupRosterItem.cpp304
-rw-r--r--Swift/Controllers/Roster/GroupRosterItem.h58
-rw-r--r--Swift/Controllers/Roster/ItemOperations/AppearOffline.h20
-rw-r--r--Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h28
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h30
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetAvatar.h30
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetBlockingState.h48
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetMUC.h34
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetName.h30
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetPresence.h28
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetVCard.h30
-rw-r--r--Swift/Controllers/Roster/LeastCommonSubsequence.h170
-rw-r--r--Swift/Controllers/Roster/OfflineRosterFilter.h12
-rw-r--r--Swift/Controllers/Roster/Roster.cpp364
-rw-r--r--Swift/Controllers/Roster/Roster.h74
-rw-r--r--Swift/Controllers/Roster/RosterController.cpp516
-rw-r--r--Swift/Controllers/Roster/RosterController.h186
-rw-r--r--Swift/Controllers/Roster/RosterFilter.h6
-rw-r--r--Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp54
-rw-r--r--Swift/Controllers/Roster/RosterGroupExpandinessPersister.h24
-rw-r--r--Swift/Controllers/Roster/RosterItem.cpp20
-rw-r--r--Swift/Controllers/Roster/RosterItem.h24
-rw-r--r--Swift/Controllers/Roster/RosterVCardProvider.cpp14
-rw-r--r--Swift/Controllers/Roster/RosterVCardProvider.h28
-rw-r--r--Swift/Controllers/Roster/TableRoster.cpp278
-rw-r--r--Swift/Controllers/Roster/TableRoster.h132
-rw-r--r--Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp558
-rw-r--r--Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp684
-rw-r--r--Swift/Controllers/Roster/UnitTest/RosterTest.cpp248
-rw-r--r--Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp126
-rw-r--r--Swift/Controllers/SettingConstants.h192
-rw-r--r--Swift/Controllers/Settings/DummySettingsProvider.h76
-rw-r--r--Swift/Controllers/Settings/SettingsProvider.h102
-rw-r--r--Swift/Controllers/Settings/SettingsProviderHierachy.cpp120
-rw-r--r--Swift/Controllers/Settings/SettingsProviderHierachy.h56
-rw-r--r--Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp118
-rw-r--r--Swift/Controllers/Settings/XMLSettingsProvider.cpp114
-rw-r--r--Swift/Controllers/Settings/XMLSettingsProvider.h68
-rw-r--r--Swift/Controllers/ShowProfileController.cpp72
-rw-r--r--Swift/Controllers/ShowProfileController.h42
-rw-r--r--Swift/Controllers/SoundEventController.cpp38
-rw-r--r--Swift/Controllers/SoundEventController.h36
-rw-r--r--Swift/Controllers/SoundPlayer.h12
-rw-r--r--Swift/Controllers/StatusCache.cpp118
-rw-r--r--Swift/Controllers/StatusCache.h36
-rw-r--r--Swift/Controllers/StatusTracker.cpp56
-rw-r--r--Swift/Controllers/StatusTracker.h24
-rw-r--r--Swift/Controllers/StatusUtil.cpp20
-rw-r--r--Swift/Controllers/StatusUtil.h2
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.cpp122
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.h38
-rw-r--r--Swift/Controllers/Storages/CapsFileStorage.cpp10
-rw-r--r--Swift/Controllers/Storages/CapsFileStorage.h20
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorage.cpp60
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorage.h28
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorageFactory.h28
-rw-r--r--Swift/Controllers/Storages/CertificateMemoryStorage.cpp14
-rw-r--r--Swift/Controllers/Storages/CertificateMemoryStorage.h16
-rw-r--r--Swift/Controllers/Storages/CertificateStorage.h12
-rw-r--r--Swift/Controllers/Storages/CertificateStorageFactory.h14
-rw-r--r--Swift/Controllers/Storages/CertificateStorageTrustChecker.h36
-rw-r--r--Swift/Controllers/Storages/FileStorages.cpp36
-rw-r--r--Swift/Controllers/Storages/FileStorages.h80
-rw-r--r--Swift/Controllers/Storages/FileStoragesFactory.h22
-rw-r--r--Swift/Controllers/Storages/MemoryStoragesFactory.h22
-rw-r--r--Swift/Controllers/Storages/RosterFileStorage.cpp4
-rw-r--r--Swift/Controllers/Storages/RosterFileStorage.h16
-rw-r--r--Swift/Controllers/Storages/StoragesFactory.h14
-rw-r--r--Swift/Controllers/Storages/VCardFileStorage.cpp150
-rw-r--r--Swift/Controllers/Storages/VCardFileStorage.h40
-rw-r--r--Swift/Controllers/SystemTray.h14
-rw-r--r--Swift/Controllers/SystemTrayController.cpp28
-rw-r--r--Swift/Controllers/SystemTrayController.h26
-rw-r--r--Swift/Controllers/Translator.cpp8
-rw-r--r--Swift/Controllers/Translator.h22
-rw-r--r--Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h16
-rw-r--r--Swift/Controllers/UIEvents/AddContactUIEvent.h42
-rw-r--r--Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h16
-rw-r--r--Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h18
-rw-r--r--Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h18
-rw-r--r--Swift/Controllers/UIEvents/InviteToMUCUIEvent.h48
-rw-r--r--Swift/Controllers/UIEvents/JoinMUCUIEvent.h40
-rw-r--r--Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h12
-rw-r--r--Swift/Controllers/UIEvents/RenameGroupUIEvent.h28
-rw-r--r--Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h18
-rw-r--r--Swift/Controllers/UIEvents/RequestAdHocUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h18
-rw-r--r--Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h20
-rw-r--r--Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h38
-rw-r--r--Swift/Controllers/UIEvents/RequestChatUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h22
-rw-r--r--Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/RequestHistoryUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h60
-rw-r--r--Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h22
-rw-r--r--Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h8
-rw-r--r--Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/SendFileUIEvent.h38
-rw-r--r--Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h16
-rw-r--r--Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/UIEvent.h10
-rw-r--r--Swift/Controllers/UIEvents/UIEventStream.h14
-rw-r--r--Swift/Controllers/UIInterfaces/AdHocCommandWindow.h12
-rw-r--r--Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h10
-rw-r--r--Swift/Controllers/UIInterfaces/BlockListEditorWidget.h24
-rw-r--r--Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindow.h154
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/ChatWindow.h456
-rw-r--r--Swift/Controllers/UIInterfaces/ChatWindowFactory.h20
-rw-r--r--Swift/Controllers/UIInterfaces/ContactEditWindow.h26
-rw-r--r--Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h10
-rw-r--r--Swift/Controllers/UIInterfaces/EventWindow.h24
-rw-r--r--Swift/Controllers/UIInterfaces/EventWindowFactory.h18
-rw-r--r--Swift/Controllers/UIInterfaces/FileTransferListWidget.h8
-rw-r--r--Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h4
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWidget.h14
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWindow.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HistoryWindow.h38
-rw-r--r--Swift/Controllers/UIInterfaces/HistoryWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/JoinMUCWindow.h16
-rw-r--r--Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/LoginWindow.h44
-rw-r--r--Swift/Controllers/UIInterfaces/LoginWindowFactory.h28
-rw-r--r--Swift/Controllers/UIInterfaces/MUCSearchWindow.h22
-rw-r--r--Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/MainWindow.h64
-rw-r--r--Swift/Controllers/UIInterfaces/MainWindowFactory.h18
-rw-r--r--Swift/Controllers/UIInterfaces/ProfileWindow.h30
-rw-r--r--Swift/Controllers/UIInterfaces/ProfileWindowFactory.h10
-rw-r--r--Swift/Controllers/UIInterfaces/UIFactory.h42
-rw-r--r--Swift/Controllers/UIInterfaces/UserSearchWindow.h72
-rw-r--r--Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/WhiteboardWindow.h20
-rw-r--r--Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h14
-rw-r--r--Swift/Controllers/UIInterfaces/XMLConsoleWidget.h16
-rw-r--r--Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h12
-rw-r--r--Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp202
-rw-r--r--Swift/Controllers/UnitTest/ContactSuggesterTest.cpp204
-rw-r--r--Swift/Controllers/UnitTest/HighlightRuleTest.cpp484
-rw-r--r--Swift/Controllers/UnitTest/MockChatWindow.h196
-rw-r--r--Swift/Controllers/UnitTest/MockMainWindow.h38
-rw-r--r--Swift/Controllers/UnitTest/MockMainWindowFactory.h24
-rw-r--r--Swift/Controllers/UnitTest/PresenceNotifierTest.cpp520
-rw-r--r--Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp40
-rw-r--r--Swift/Controllers/WhiteboardManager.cpp224
-rw-r--r--Swift/Controllers/WhiteboardManager.h62
-rw-r--r--Swift/Controllers/XMLConsoleController.cpp32
-rw-r--r--Swift/Controllers/XMLConsoleController.h40
-rw-r--r--Swift/Controllers/XMPPEvents/ErrorEvent.h22
-rw-r--r--Swift/Controllers/XMPPEvents/EventController.cpp72
-rw-r--r--Swift/Controllers/XMPPEvents/EventController.h34
-rw-r--r--Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h20
-rw-r--r--Swift/Controllers/XMPPEvents/MUCInviteEvent.h44
-rw-r--r--Swift/Controllers/XMPPEvents/MessageEvent.h46
-rw-r--r--Swift/Controllers/XMPPEvents/StanzaEvent.h28
-rw-r--r--Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h52
-rw-r--r--Swift/Controllers/XMPPURIController.cpp22
-rw-r--r--Swift/Controllers/XMPPURIController.h30
-rw-r--r--Swift/QtUI/ApplicationTest/main.cpp44
-rw-r--r--Swift/QtUI/CAPICertificateSelector.cpp114
-rw-r--r--Swift/QtUI/CAPICertificateSelector.h4
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.cpp184
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.h42
-rw-r--r--Swift/QtUI/ChatList/ChatListGroupItem.h58
-rw-r--r--Swift/QtUI/ChatList/ChatListItem.h20
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.cpp24
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.h30
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.cpp228
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.h66
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.cpp26
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.h32
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp50
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.h30
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.cpp248
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.h84
-rw-r--r--Swift/QtUI/ChatSnippet.cpp116
-rw-r--r--Swift/QtUI/ChatSnippet.h100
-rw-r--r--Swift/QtUI/ChatView/main.cpp260
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.h28
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.mm32
-rw-r--r--Swift/QtUI/CocoaUIHelpers.h2
-rw-r--r--Swift/QtUI/CocoaUIHelpers.mm34
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.cpp106
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.h32
-rw-r--r--Swift/QtUI/EventViewer/EventModel.cpp126
-rw-r--r--Swift/QtUI/EventViewer/EventModel.h30
-rw-r--r--Swift/QtUI/EventViewer/EventView.cpp2
-rw-r--r--Swift/QtUI/EventViewer/EventView.h10
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.cpp128
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.h28
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.cpp140
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.h42
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.cpp70
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.h24
-rw-r--r--Swift/QtUI/EventViewer/main.cpp26
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.cpp62
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.h18
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp96
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.h22
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp30
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h18
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchItem.h10
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.cpp104
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.h34
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp12
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.h22
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchServiceItem.h34
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp238
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.h74
-rw-r--r--Swift/QtUI/MessageSnippet.cpp54
-rw-r--r--Swift/QtUI/MessageSnippet.h26
-rw-r--r--Swift/QtUI/NotifierTest/NotifierTest.cpp10
-rw-r--r--Swift/QtUI/QtAboutWidget.cpp98
-rw-r--r--Swift/QtUI/QtAboutWidget.h14
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.cpp222
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.h74
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp46
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.h30
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.cpp22
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.h18
-rw-r--r--Swift/QtUI/QtAffiliationEditor.cpp78
-rw-r--r--Swift/QtUI/QtAffiliationEditor.h36
-rw-r--r--Swift/QtUI/QtAvatarWidget.cpp146
-rw-r--r--Swift/QtUI/QtAvatarWidget.h64
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.cpp290
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.h48
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.cpp94
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.h26
-rw-r--r--Swift/QtUI/QtCachedImageScaler.cpp38
-rw-r--r--Swift/QtUI/QtCachedImageScaler.h10
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.cpp178
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.h28
-rw-r--r--Swift/QtUI/QtChatTabs.cpp618
-rw-r--r--Swift/QtUI/QtChatTabs.h114
-rw-r--r--Swift/QtUI/QtChatTabsBase.h8
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp98
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h28
-rw-r--r--Swift/QtUI/QtChatTheme.cpp88
-rw-r--r--Swift/QtUI/QtChatTheme.h54
-rw-r--r--Swift/QtUI/QtChatView.cpp2
-rw-r--r--Swift/QtUI/QtChatView.h76
-rw-r--r--Swift/QtUI/QtChatWindow.cpp1270
-rw-r--r--Swift/QtUI/QtChatWindow.h398
-rw-r--r--Swift/QtUI/QtChatWindowFactory.cpp88
-rw-r--r--Swift/QtUI/QtChatWindowFactory.h48
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.cpp4
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.h8
-rw-r--r--Swift/QtUI/QtClickableLabel.cpp2
-rw-r--r--Swift/QtUI/QtClickableLabel.h16
-rw-r--r--Swift/QtUI/QtClosableLineEdit.cpp48
-rw-r--r--Swift/QtUI/QtClosableLineEdit.h22
-rw-r--r--Swift/QtUI/QtColorToolButton.cpp30
-rw-r--r--Swift/QtUI/QtColorToolButton.h36
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.cpp260
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.h42
-rw-r--r--Swift/QtUI/QtContactEditWidget.cpp248
-rw-r--r--Swift/QtUI/QtContactEditWidget.h64
-rw-r--r--Swift/QtUI/QtContactEditWindow.cpp102
-rw-r--r--Swift/QtUI/QtContactEditWindow.h42
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.cpp38
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.h8
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.cpp22
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.h20
-rw-r--r--Swift/QtUI/QtElidingLabel.cpp56
-rw-r--r--Swift/QtUI/QtElidingLabel.h34
-rw-r--r--Swift/QtUI/QtEmoticonCell.cpp14
-rw-r--r--Swift/QtUI/QtEmoticonCell.h26
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.cpp50
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.h26
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.cpp152
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.h46
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.cpp94
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.h30
-rw-r--r--Swift/QtUI/QtFormResultItemModel.cpp80
-rw-r--r--Swift/QtUI/QtFormResultItemModel.h28
-rw-r--r--Swift/QtUI/QtFormWidget.cpp374
-rw-r--r--Swift/QtUI/QtFormWidget.h26
-rw-r--r--Swift/QtUI/QtHighlightEditor.cpp782
-rw-r--r--Swift/QtUI/QtHighlightEditor.h90
-rw-r--r--Swift/QtUI/QtHistoryWindow.cpp312
-rw-r--r--Swift/QtUI/QtHistoryWindow.h114
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.cpp66
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.h112
-rw-r--r--Swift/QtUI/QtLineEdit.cpp8
-rw-r--r--Swift/QtUI/QtLineEdit.h18
-rw-r--r--Swift/QtUI/QtLoginWindow.cpp750
-rw-r--r--Swift/QtUI/QtLoginWindow.h156
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.cpp62
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.h38
-rw-r--r--Swift/QtUI/QtMainWindow.cpp496
-rw-r--r--Swift/QtUI/QtMainWindow.h154
-rw-r--r--Swift/QtUI/QtNameWidget.cpp114
-rw-r--r--Swift/QtUI/QtNameWidget.h66
-rw-r--r--Swift/QtUI/QtPlainChatView.cpp598
-rw-r--r--Swift/QtUI/QtPlainChatView.h216
-rw-r--r--Swift/QtUI/QtProfileWindow.cpp174
-rw-r--r--Swift/QtUI/QtProfileWindow.h50
-rw-r--r--Swift/QtUI/QtResourceHelper.cpp20
-rw-r--r--Swift/QtUI/QtRosterHeader.cpp152
-rw-r--r--Swift/QtUI/QtRosterHeader.h72
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.cpp66
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.h14
-rw-r--r--Swift/QtUI/QtSettingsProvider.cpp120
-rw-r--r--Swift/QtUI/QtSettingsProvider.h44
-rw-r--r--Swift/QtUI/QtSingleWindow.cpp60
-rw-r--r--Swift/QtUI/QtSingleWindow.h46
-rw-r--r--Swift/QtUI/QtSoundPlayer.cpp32
-rw-r--r--Swift/QtUI/QtSoundPlayer.h24
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.cpp20
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.h14
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.cpp120
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.h40
-rw-r--r--Swift/QtUI/QtStatusWidget.cpp424
-rw-r--r--Swift/QtUI/QtStatusWidget.h98
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.cpp98
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.h36
-rw-r--r--Swift/QtUI/QtSwift.cpp332
-rw-r--r--Swift/QtUI/QtSwift.h118
-rw-r--r--Swift/QtUI/QtSystemTray.cpp86
-rw-r--r--Swift/QtUI/QtSystemTray.h60
-rw-r--r--Swift/QtUI/QtTabWidget.cpp4
-rw-r--r--Swift/QtUI/QtTabWidget.h16
-rw-r--r--Swift/QtUI/QtTabbable.cpp58
-rw-r--r--Swift/QtUI/QtTabbable.h46
-rw-r--r--Swift/QtUI/QtTextEdit.cpp290
-rw-r--r--Swift/QtUI/QtTextEdit.h86
-rw-r--r--Swift/QtUI/QtTranslator.h14
-rw-r--r--Swift/QtUI/QtUIFactory.cpp150
-rw-r--r--Swift/QtUI/QtUIFactory.h122
-rw-r--r--Swift/QtUI/QtUISettingConstants.h24
-rw-r--r--Swift/QtUI/QtURIHandler.cpp18
-rw-r--r--Swift/QtUI/QtURIHandler.h12
-rw-r--r--Swift/QtUI/QtURLValidator.cpp8
-rw-r--r--Swift/QtUI/QtURLValidator.h12
-rw-r--r--Swift/QtUI/QtUtilities.cpp20
-rw-r--r--Swift/QtUI/QtUtilities.h14
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.cpp32
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.h18
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp50
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h18
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp38
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp104
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.h40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp234
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.h72
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp106
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h36
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp50
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h64
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp172
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h122
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp14
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h20
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp78
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp172
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h44
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp120
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp24
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp122
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp26
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp60
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.h30
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp666
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.h82
-rw-r--r--Swift/QtUI/QtWebKitChatView.cpp1344
-rw-r--r--Swift/QtUI/QtWebKitChatView.h328
-rw-r--r--Swift/QtUI/QtWebView.cpp102
-rw-r--r--Swift/QtUI/QtWebView.h44
-rw-r--r--Swift/QtUI/QtWin32NotifierWindow.h26
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.cpp116
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.h36
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.cpp168
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.h44
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.cpp164
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.h26
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.cpp210
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.h52
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.cpp74
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.h20
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.cpp208
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.h20
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.cpp300
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.h92
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.cpp66
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.h36
-rw-r--r--Swift/QtUI/Roster/RosterModel.cpp332
-rw-r--r--Swift/QtUI/Roster/RosterModel.h102
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.cpp260
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.h10
-rw-r--r--Swift/QtUI/Roster/main.cpp88
-rw-r--r--Swift/QtUI/SystemMessageSnippet.cpp20
-rw-r--r--Swift/QtUI/SystemMessageSnippet.h22
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.cpp218
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.h50
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.cpp748
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.h94
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.cpp188
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.h86
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.cpp34
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.h20
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.cpp140
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.h72
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.cpp80
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.h34
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp274
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.h56
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp20
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h36
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp32
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h24
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp108
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h62
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp50
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.h30
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp32
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.h22
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.cpp888
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.h160
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.cpp72
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.h24
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.cpp86
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.h46
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.cpp46
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.h30
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.cpp150
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.h36
-rw-r--r--Swift/QtUI/Whiteboard/GView.cpp970
-rw-r--r--Swift/QtUI/Whiteboard/GView.h102
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp730
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.h106
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.cpp84
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.h44
-rw-r--r--Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h336
-rw-r--r--Swift/QtUI/WinUIHelpers.cpp66
-rw-r--r--Swift/QtUI/WinUIHelpers.h2
-rw-r--r--Swift/QtUI/WindowsNotifier.cpp40
-rw-r--r--Swift/QtUI/WindowsNotifier.h30
-rw-r--r--Swift/QtUI/main.cpp96
-rw-r--r--Swift/QtUI/swift-open-uri.cpp26
-rw-r--r--Swiften/AdHoc/OutgoingAdHocCommandSession.cpp100
-rw-r--r--Swiften/AdHoc/OutgoingAdHocCommandSession.h138
-rw-r--r--Swiften/Avatars/AvatarManager.h16
-rw-r--r--Swiften/Avatars/AvatarManagerImpl.cpp56
-rw-r--r--Swiften/Avatars/AvatarManagerImpl.h56
-rw-r--r--Swiften/Avatars/AvatarMemoryStorage.h52
-rw-r--r--Swiften/Avatars/AvatarProvider.h14
-rw-r--r--Swiften/Avatars/AvatarStorage.h22
-rw-r--r--Swiften/Avatars/CombinedAvatarProvider.cpp60
-rw-r--r--Swiften/Avatars/CombinedAvatarProvider.h24
-rw-r--r--Swiften/Avatars/DummyAvatarManager.h32
-rw-r--r--Swiften/Avatars/NullAvatarManager.h18
-rw-r--r--Swiften/Avatars/OfflineAvatarManager.cpp10
-rw-r--r--Swiften/Avatars/OfflineAvatarManager.h20
-rw-r--r--Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp214
-rw-r--r--Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp690
-rw-r--r--Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp288
-rw-r--r--Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp360
-rw-r--r--Swiften/Avatars/VCardAvatarManager.cpp58
-rw-r--r--Swiften/Avatars/VCardAvatarManager.h34
-rw-r--r--Swiften/Avatars/VCardUpdateAvatarManager.cpp108
-rw-r--r--Swiften/Avatars/VCardUpdateAvatarManager.h52
-rw-r--r--Swiften/Base/API.h8
-rw-r--r--Swiften/Base/Algorithm.h276
-rw-r--r--Swiften/Base/Atomic.h50
-rw-r--r--Swiften/Base/BoostRandomGenerator.cpp8
-rw-r--r--Swiften/Base/BoostRandomGenerator.h14
-rw-r--r--Swiften/Base/ByteArray.cpp44
-rw-r--r--Swiften/Base/ByteArray.h46
-rw-r--r--Swiften/Base/Concat.h112
-rw-r--r--Swiften/Base/DateTime.cpp36
-rw-r--r--Swiften/Base/DateTime.h26
-rw-r--r--Swiften/Base/Debug.cpp234
-rw-r--r--Swiften/Base/Debug.h6
-rw-r--r--Swiften/Base/Error.h12
-rw-r--r--Swiften/Base/FileSize.cpp16
-rw-r--r--Swiften/Base/IDGenerator.cpp4
-rw-r--r--Swiften/Base/IDGenerator.h10
-rw-r--r--Swiften/Base/Listenable.h74
-rw-r--r--Swiften/Base/Log.cpp26
-rw-r--r--Swiften/Base/Log.h52
-rw-r--r--Swiften/Base/Path.cpp8
-rw-r--r--Swiften/Base/Path.h22
-rw-r--r--Swiften/Base/Paths.cpp38
-rw-r--r--Swiften/Base/Paths.h8
-rw-r--r--Swiften/Base/RandomGenerator.h18
-rw-r--r--Swiften/Base/Regex.cpp30
-rw-r--r--Swiften/Base/Regex.h6
-rw-r--r--Swiften/Base/SafeAllocator.cpp10
-rw-r--r--Swiften/Base/SafeAllocator.h42
-rw-r--r--Swiften/Base/SafeByteArray.cpp12
-rw-r--r--Swiften/Base/SafeByteArray.h62
-rw-r--r--Swiften/Base/SafeString.h32
-rw-r--r--Swiften/Base/SimpleIDGenerator.cpp34
-rw-r--r--Swiften/Base/SimpleIDGenerator.h22
-rw-r--r--Swiften/Base/StartStopper.h24
-rw-r--r--Swiften/Base/String.cpp200
-rw-r--r--Swiften/Base/String.h58
-rw-r--r--Swiften/Base/URL.cpp278
-rw-r--r--Swiften/Base/URL.h124
-rw-r--r--Swiften/Base/UnitTest/ByteArrayTest.cpp56
-rw-r--r--Swiften/Base/UnitTest/DateTimeTest.cpp46
-rw-r--r--Swiften/Base/UnitTest/IDGeneratorTest.cpp42
-rw-r--r--Swiften/Base/UnitTest/PathTest.cpp24
-rw-r--r--Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp42
-rw-r--r--Swiften/Base/UnitTest/StringTest.cpp168
-rw-r--r--Swiften/Base/UnitTest/URLTest.cpp192
-rw-r--r--Swiften/Base/WindowsRegistry.h90
-rw-r--r--Swiften/Base/boost_bsignals.h2
-rw-r--r--Swiften/Base/format.h24
-rw-r--r--Swiften/Base/sleep.cpp10
-rw-r--r--Swiften/Base/sleep.h2
-rw-r--r--Swiften/Chat/ChatStateNotifier.cpp74
-rw-r--r--Swiften/Chat/ChatStateNotifier.h66
-rw-r--r--Swiften/Chat/ChatStateTracker.cpp30
-rw-r--r--Swiften/Chat/ChatStateTracker.h20
-rw-r--r--Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp292
-rw-r--r--Swiften/Client/BlockList.cpp8
-rw-r--r--Swiften/Client/BlockList.h42
-rw-r--r--Swiften/Client/BlockListImpl.cpp68
-rw-r--r--Swiften/Client/BlockListImpl.h50
-rw-r--r--Swiften/Client/Client.cpp172
-rw-r--r--Swiften/Client/Client.h384
-rw-r--r--Swiften/Client/ClientBlockListManager.cpp174
-rw-r--r--Swiften/Client/ClientBlockListManager.h66
-rw-r--r--Swiften/Client/ClientError.h90
-rw-r--r--Swiften/Client/ClientOptions.h290
-rw-r--r--Swiften/Client/ClientSession.cpp776
-rw-r--r--Swiften/Client/ClientSession.h356
-rw-r--r--Swiften/Client/ClientSessionStanzaChannel.cpp110
-rw-r--r--Swiften/Client/ClientSessionStanzaChannel.h62
-rw-r--r--Swiften/Client/ClientXMLTracer.cpp46
-rw-r--r--Swiften/Client/ClientXMLTracer.h26
-rw-r--r--Swiften/Client/CoreClient.cpp706
-rw-r--r--Swiften/Client/CoreClient.h438
-rw-r--r--Swiften/Client/DummyNickManager.h18
-rw-r--r--Swiften/Client/DummyStanzaChannel.h150
-rw-r--r--Swiften/Client/MemoryStorages.cpp34
-rw-r--r--Swiften/Client/MemoryStorages.h44
-rw-r--r--Swiften/Client/NickManager.h14
-rw-r--r--Swiften/Client/NickManagerImpl.cpp32
-rw-r--r--Swiften/Client/NickManagerImpl.h30
-rw-r--r--Swiften/Client/NickResolver.cpp76
-rw-r--r--Swiften/Client/NickResolver.h48
-rw-r--r--Swiften/Client/StanzaChannel.h24
-rw-r--r--Swiften/Client/Storages.h36
-rw-r--r--Swiften/Client/UnitTest/BlockListImplTest.cpp138
-rw-r--r--Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp328
-rw-r--r--Swiften/Client/UnitTest/ClientSessionTest.cpp1560
-rw-r--r--Swiften/Client/UnitTest/NickResolverTest.cpp256
-rw-r--r--Swiften/Client/XMLBeautifier.cpp132
-rw-r--r--Swiften/Client/XMLBeautifier.h40
-rw-r--r--Swiften/Component/Component.cpp10
-rw-r--r--Swiften/Component/Component.h40
-rw-r--r--Swiften/Component/ComponentConnector.cpp114
-rw-r--r--Swiften/Component/ComponentConnector.h68
-rw-r--r--Swiften/Component/ComponentError.h32
-rw-r--r--Swiften/Component/ComponentHandshakeGenerator.cpp14
-rw-r--r--Swiften/Component/ComponentHandshakeGenerator.h10
-rw-r--r--Swiften/Component/ComponentSession.cpp130
-rw-r--r--Swiften/Component/ComponentSession.h128
-rw-r--r--Swiften/Component/ComponentSessionStanzaChannel.cpp74
-rw-r--r--Swiften/Component/ComponentSessionStanzaChannel.h70
-rw-r--r--Swiften/Component/ComponentXMLTracer.cpp16
-rw-r--r--Swiften/Component/ComponentXMLTracer.h14
-rw-r--r--Swiften/Component/CoreComponent.cpp216
-rw-r--r--Swiften/Component/CoreComponent.h150
-rw-r--r--Swiften/Component/UnitTest/ComponentConnectorTest.cpp368
-rw-r--r--Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp44
-rw-r--r--Swiften/Component/UnitTest/ComponentSessionTest.cpp390
-rw-r--r--Swiften/Compress/UnitTest/ZLibCompressorTest.cpp34
-rw-r--r--Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp112
-rw-r--r--Swiften/Compress/ZLibCodecompressor.cpp48
-rw-r--r--Swiften/Compress/ZLibCodecompressor.h20
-rw-r--r--Swiften/Compress/ZLibCodecompressor_Private.h6
-rw-r--r--Swiften/Compress/ZLibCompressor.cpp10
-rw-r--r--Swiften/Compress/ZLibCompressor.h16
-rw-r--r--Swiften/Compress/ZLibDecompressor.cpp10
-rw-r--r--Swiften/Compress/ZLibDecompressor.h12
-rw-r--r--Swiften/Compress/ZLibException.h8
-rw-r--r--Swiften/Config/swiften-config.cpp174
-rw-r--r--Swiften/Crypto/CommonCryptoCryptoProvider.cpp186
-rw-r--r--Swiften/Crypto/CommonCryptoCryptoProvider.h20
-rw-r--r--Swiften/Crypto/CryptoProvider.h34
-rw-r--r--Swiften/Crypto/Hash.h14
-rw-r--r--Swiften/Crypto/OpenSSLCryptoProvider.cpp190
-rw-r--r--Swiften/Crypto/OpenSSLCryptoProvider.h20
-rw-r--r--Swiften/Crypto/PlatformCryptoProvider.cpp10
-rw-r--r--Swiften/Crypto/PlatformCryptoProvider.h8
-rw-r--r--Swiften/Crypto/UnitTest/CryptoProviderTest.cpp176
-rw-r--r--Swiften/Crypto/WindowsCryptoProvider.cpp328
-rw-r--r--Swiften/Crypto/WindowsCryptoProvider.h26
-rw-r--r--Swiften/Disco/CapsInfoGenerator.cpp64
-rw-r--r--Swiften/Disco/CapsInfoGenerator.h20
-rw-r--r--Swiften/Disco/CapsManager.cpp90
-rw-r--r--Swiften/Disco/CapsManager.h64
-rw-r--r--Swiften/Disco/CapsMemoryStorage.h44
-rw-r--r--Swiften/Disco/CapsProvider.h14
-rw-r--r--Swiften/Disco/CapsStorage.h12
-rw-r--r--Swiften/Disco/ClientDiscoManager.cpp26
-rw-r--r--Swiften/Disco/ClientDiscoManager.h112
-rw-r--r--Swiften/Disco/DiscoInfoResponder.cpp38
-rw-r--r--Swiften/Disco/DiscoInfoResponder.h26
-rw-r--r--Swiften/Disco/DiscoServiceWalker.cpp188
-rw-r--r--Swiften/Disco/DiscoServiceWalker.h86
-rw-r--r--Swiften/Disco/DummyEntityCapsProvider.cpp10
-rw-r--r--Swiften/Disco/DummyEntityCapsProvider.h14
-rw-r--r--Swiften/Disco/EntityCapsManager.cpp96
-rw-r--r--Swiften/Disco/EntityCapsManager.h54
-rw-r--r--Swiften/Disco/EntityCapsProvider.h34
-rw-r--r--Swiften/Disco/FeatureOracle.cpp112
-rw-r--r--Swiften/Disco/FeatureOracle.h42
-rw-r--r--Swiften/Disco/GetDiscoInfoRequest.h44
-rw-r--r--Swiften/Disco/GetDiscoItemsRequest.h44
-rw-r--r--Swiften/Disco/JIDDiscoInfoResponder.cpp52
-rw-r--r--Swiften/Disco/JIDDiscoInfoResponder.h42
-rw-r--r--Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp116
-rw-r--r--Swiften/Disco/UnitTest/CapsManagerTest.cpp526
-rw-r--r--Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp152
-rw-r--r--Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp336
-rw-r--r--Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp196
-rw-r--r--Swiften/Elements/AuthChallenge.h30
-rw-r--r--Swiften/Elements/AuthFailure.h10
-rw-r--r--Swiften/Elements/AuthRequest.h66
-rw-r--r--Swiften/Elements/AuthResponse.h34
-rw-r--r--Swiften/Elements/AuthSuccess.h24
-rw-r--r--Swiften/Elements/BlockListPayload.h26
-rw-r--r--Swiften/Elements/BlockPayload.h26
-rw-r--r--Swiften/Elements/Body.h26
-rw-r--r--Swiften/Elements/Bytestreams.h66
-rw-r--r--Swiften/Elements/CapsInfo.h88
-rw-r--r--Swiften/Elements/CarbonsDisable.cpp4
-rw-r--r--Swiften/Elements/CarbonsDisable.h12
-rw-r--r--Swiften/Elements/CarbonsEnable.cpp4
-rw-r--r--Swiften/Elements/CarbonsEnable.h12
-rw-r--r--Swiften/Elements/CarbonsPrivate.cpp4
-rw-r--r--Swiften/Elements/CarbonsPrivate.h12
-rw-r--r--Swiften/Elements/CarbonsReceived.cpp16
-rw-r--r--Swiften/Elements/CarbonsReceived.h20
-rw-r--r--Swiften/Elements/CarbonsSent.cpp18
-rw-r--r--Swiften/Elements/CarbonsSent.h20
-rw-r--r--Swiften/Elements/ChatState.h26
-rw-r--r--Swiften/Elements/Command.h130
-rw-r--r--Swiften/Elements/ComponentHandshake.h28
-rw-r--r--Swiften/Elements/CompressFailure.h8
-rw-r--r--Swiften/Elements/CompressRequest.h26
-rw-r--r--Swiften/Elements/Compressed.h8
-rw-r--r--Swiften/Elements/ContainerPayload.h34
-rw-r--r--Swiften/Elements/Delay.h24
-rw-r--r--Swiften/Elements/DeliveryReceipt.h26
-rw-r--r--Swiften/Elements/DeliveryReceiptRequest.h8
-rw-r--r--Swiften/Elements/DiscoInfo.cpp34
-rw-r--r--Swiften/Elements/DiscoInfo.h192
-rw-r--r--Swiften/Elements/DiscoItems.h88
-rw-r--r--Swiften/Elements/Element.h14
-rw-r--r--Swiften/Elements/EnableStreamManagement.h8
-rw-r--r--Swiften/Elements/ErrorPayload.h142
-rw-r--r--Swiften/Elements/Form.cpp64
-rw-r--r--Swiften/Elements/Form.h206
-rw-r--r--Swiften/Elements/FormField.cpp14
-rw-r--r--Swiften/Elements/FormField.h242
-rw-r--r--Swiften/Elements/FormPage.cpp24
-rw-r--r--Swiften/Elements/FormPage.h50
-rw-r--r--Swiften/Elements/FormReportedRef.h8
-rw-r--r--Swiften/Elements/FormSection.cpp24
-rw-r--r--Swiften/Elements/FormSection.h50
-rw-r--r--Swiften/Elements/FormText.cpp4
-rw-r--r--Swiften/Elements/FormText.h20
-rw-r--r--Swiften/Elements/Forwarded.h26
-rw-r--r--Swiften/Elements/HashElement.h60
-rw-r--r--Swiften/Elements/IBB.h180
-rw-r--r--Swiften/Elements/IQ.cpp80
-rw-r--r--Swiften/Elements/IQ.h84
-rw-r--r--Swiften/Elements/Idle.h40
-rw-r--r--Swiften/Elements/InBandRegistrationPayload.h346
-rw-r--r--Swiften/Elements/IsodeIQDelegation.h30
-rw-r--r--Swiften/Elements/JingleContentPayload.h162
-rw-r--r--Swiften/Elements/JingleDescription.h8
-rw-r--r--Swiften/Elements/JingleFileTransferDescription.h24
-rw-r--r--Swiften/Elements/JingleFileTransferFileInfo.h196
-rw-r--r--Swiften/Elements/JingleFileTransferHash.h18
-rw-r--r--Swiften/Elements/JingleIBBTransportPayload.h64
-rw-r--r--Swiften/Elements/JinglePayload.h292
-rw-r--r--Swiften/Elements/JingleS5BTransportPayload.h204
-rw-r--r--Swiften/Elements/JingleTransportPayload.h26
-rw-r--r--Swiften/Elements/Last.h16
-rw-r--r--Swiften/Elements/MAMFin.h88
-rw-r--r--Swiften/Elements/MAMQuery.h34
-rw-r--r--Swiften/Elements/MAMResult.h22
-rw-r--r--Swiften/Elements/MUCAdminPayload.h20
-rw-r--r--Swiften/Elements/MUCDestroyPayload.h42
-rw-r--r--Swiften/Elements/MUCInvitationPayload.h124
-rw-r--r--Swiften/Elements/MUCItem.h14
-rw-r--r--Swiften/Elements/MUCOccupant.cpp12
-rw-r--r--Swiften/Elements/MUCOccupant.h50
-rw-r--r--Swiften/Elements/MUCOwnerPayload.h34
-rw-r--r--Swiften/Elements/MUCPayload.h114
-rw-r--r--Swiften/Elements/MUCUserPayload.h112
-rw-r--r--Swiften/Elements/Message.h118
-rw-r--r--Swiften/Elements/Nickname.h26
-rw-r--r--Swiften/Elements/Payload.h18
-rw-r--r--Swiften/Elements/Presence.cpp24
-rw-r--r--Swiften/Elements/Presence.h84
-rw-r--r--Swiften/Elements/Priority.h26
-rw-r--r--Swiften/Elements/PrivateStorage.h26
-rw-r--r--Swiften/Elements/ProtocolHeader.h60
-rw-r--r--Swiften/Elements/PubSub.h10
-rw-r--r--Swiften/Elements/PubSubAffiliation.h72
-rw-r--r--Swiften/Elements/PubSubAffiliations.h64
-rw-r--r--Swiften/Elements/PubSubConfigure.h30
-rw-r--r--Swiften/Elements/PubSubCreate.h56
-rw-r--r--Swiften/Elements/PubSubDefault.h66
-rw-r--r--Swiften/Elements/PubSubError.h182
-rw-r--r--Swiften/Elements/PubSubEvent.h10
-rw-r--r--Swiften/Elements/PubSubEventAssociate.h30
-rw-r--r--Swiften/Elements/PubSubEventCollection.h74
-rw-r--r--Swiften/Elements/PubSubEventConfiguration.h56
-rw-r--r--Swiften/Elements/PubSubEventDelete.h56
-rw-r--r--Swiften/Elements/PubSubEventDisassociate.h30
-rw-r--r--Swiften/Elements/PubSubEventItem.h100
-rw-r--r--Swiften/Elements/PubSubEventItems.h90
-rw-r--r--Swiften/Elements/PubSubEventPayload.h8
-rw-r--r--Swiften/Elements/PubSubEventPurge.h30
-rw-r--r--Swiften/Elements/PubSubEventRedirect.h30
-rw-r--r--Swiften/Elements/PubSubEventRetract.h30
-rw-r--r--Swiften/Elements/PubSubEventSubscription.h122
-rw-r--r--Swiften/Elements/PubSubItem.h64
-rw-r--r--Swiften/Elements/PubSubItems.h100
-rw-r--r--Swiften/Elements/PubSubOptions.h92
-rw-r--r--Swiften/Elements/PubSubOwnerAffiliation.h72
-rw-r--r--Swiften/Elements/PubSubOwnerAffiliations.h64
-rw-r--r--Swiften/Elements/PubSubOwnerConfigure.h56
-rw-r--r--Swiften/Elements/PubSubOwnerDefault.h30
-rw-r--r--Swiften/Elements/PubSubOwnerDelete.h56
-rw-r--r--Swiften/Elements/PubSubOwnerPayload.h8
-rw-r--r--Swiften/Elements/PubSubOwnerPubSub.h10
-rw-r--r--Swiften/Elements/PubSubOwnerPurge.h30
-rw-r--r--Swiften/Elements/PubSubOwnerRedirect.h30
-rw-r--r--Swiften/Elements/PubSubOwnerSubscription.h68
-rw-r--r--Swiften/Elements/PubSubOwnerSubscriptions.h64
-rw-r--r--Swiften/Elements/PubSubPayload.h8
-rw-r--r--Swiften/Elements/PubSubPublish.h64
-rw-r--r--Swiften/Elements/PubSubRetract.h82
-rw-r--r--Swiften/Elements/PubSubSubscribe.h74
-rw-r--r--Swiften/Elements/PubSubSubscribeOptions.h30
-rw-r--r--Swiften/Elements/PubSubSubscription.h122
-rw-r--r--Swiften/Elements/PubSubSubscriptions.h64
-rw-r--r--Swiften/Elements/PubSubUnsubscribe.h74
-rw-r--r--Swiften/Elements/RawXMLPayload.h24
-rw-r--r--Swiften/Elements/Replace.h26
-rw-r--r--Swiften/Elements/ResourceBind.h50
-rw-r--r--Swiften/Elements/ResultSet.h58
-rw-r--r--Swiften/Elements/RosterItemExchangePayload.h104
-rw-r--r--Swiften/Elements/RosterItemPayload.h72
-rw-r--r--Swiften/Elements/RosterPayload.cpp16
-rw-r--r--Swiften/Elements/RosterPayload.h46
-rw-r--r--Swiften/Elements/S5BProxyRequest.h54
-rw-r--r--Swiften/Elements/SearchPayload.h154
-rw-r--r--Swiften/Elements/SecurityLabel.h118
-rw-r--r--Swiften/Elements/SecurityLabelsCatalog.h140
-rw-r--r--Swiften/Elements/SoftwareVersion.h78
-rw-r--r--Swiften/Elements/Stanza.cpp56
-rw-r--r--Swiften/Elements/Stanza.h150
-rw-r--r--Swiften/Elements/StanzaAck.cpp4
-rw-r--r--Swiften/Elements/StanzaAck.h34
-rw-r--r--Swiften/Elements/StanzaAckRequest.h4
-rw-r--r--Swiften/Elements/StartSession.h8
-rw-r--r--Swiften/Elements/StartTLSFailure.h8
-rw-r--r--Swiften/Elements/StartTLSRequest.h8
-rw-r--r--Swiften/Elements/Status.h26
-rw-r--r--Swiften/Elements/StatusShow.h68
-rw-r--r--Swiften/Elements/Storage.h94
-rw-r--r--Swiften/Elements/StreamError.h94
-rw-r--r--Swiften/Elements/StreamFeatures.cpp4
-rw-r--r--Swiften/Elements/StreamFeatures.h176
-rw-r--r--Swiften/Elements/StreamInitiation.h106
-rw-r--r--Swiften/Elements/StreamInitiationFileInfo.h156
-rw-r--r--Swiften/Elements/StreamManagementEnabled.h50
-rw-r--r--Swiften/Elements/StreamManagementFailed.h8
-rw-r--r--Swiften/Elements/StreamResume.h50
-rw-r--r--Swiften/Elements/StreamResumed.h50
-rw-r--r--Swiften/Elements/StreamType.h10
-rw-r--r--Swiften/Elements/Subject.h26
-rw-r--r--Swiften/Elements/TLSProceed.h8
-rw-r--r--Swiften/Elements/Thread.cpp34
-rw-r--r--Swiften/Elements/Thread.h24
-rw-r--r--Swiften/Elements/ToplevelElement.h12
-rw-r--r--Swiften/Elements/UnblockPayload.h26
-rw-r--r--Swiften/Elements/UnitTest/FormTest.cpp54
-rw-r--r--Swiften/Elements/UnitTest/IQTest.cpp74
-rw-r--r--Swiften/Elements/UnitTest/StanzaTest.cpp416
-rw-r--r--Swiften/Elements/UnknownElement.h8
-rw-r--r--Swiften/Elements/UserLocation.h374
-rw-r--r--Swiften/Elements/UserTune.h146
-rw-r--r--Swiften/Elements/VCard.cpp18
-rw-r--r--Swiften/Elements/VCard.h548
-rw-r--r--Swiften/Elements/VCardUpdate.h16
-rw-r--r--Swiften/Elements/Version.h22
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardColor.cpp80
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardColor.h30
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h26
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardElement.h30
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h32
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h122
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h66
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h26
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardLineElement.h84
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardOperation.h74
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h80
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardRectElement.h122
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardTextElement.h82
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h48
-rw-r--r--Swiften/Elements/WhiteboardPayload.h96
-rw-r--r--Swiften/Entity/Entity.cpp20
-rw-r--r--Swiften/Entity/Entity.h58
-rw-r--r--Swiften/Entity/GenericPayloadPersister.h38
-rw-r--r--Swiften/Entity/PayloadPersister.cpp50
-rw-r--r--Swiften/Entity/PayloadPersister.h26
-rw-r--r--Swiften/EventLoop/BoostASIOEventLoop.cpp20
-rw-r--r--Swiften/EventLoop/BoostASIOEventLoop.h24
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEvent.h4
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEvent.mm14
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEventLoop.h24
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEventLoop.mm32
-rw-r--r--Swiften/EventLoop/DummyEventLoop.cpp22
-rw-r--r--Swiften/EventLoop/DummyEventLoop.h22
-rw-r--r--Swiften/EventLoop/Event.cpp18
-rw-r--r--Swiften/EventLoop/Event.h22
-rw-r--r--Swiften/EventLoop/EventLoop.cpp114
-rw-r--r--Swiften/EventLoop/EventLoop.h94
-rw-r--r--Swiften/EventLoop/EventOwner.h8
-rw-r--r--Swiften/EventLoop/Qt/QtEventLoop.h82
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.cpp44
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.h48
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.cpp36
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.h48
-rw-r--r--Swiften/EventLoop/UnitTest/EventLoopTest.cpp136
-rw-r--r--Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp76
-rw-r--r--Swiften/Examples/BenchTool/BenchTool.cpp58
-rw-r--r--Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp114
-rw-r--r--Swiften/Examples/LinkLocalTool/main.cpp58
-rw-r--r--Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp126
-rw-r--r--Swiften/Examples/NetworkTool/main.cpp106
-rw-r--r--Swiften/Examples/ParserTester/ParserTester.cpp72
-rw-r--r--Swiften/Examples/SendFile/ReceiveFile.cpp180
-rw-r--r--Swiften/Examples/SendFile/SendFile.cpp204
-rw-r--r--Swiften/Examples/SendMessage/SendMessage.cpp104
-rw-r--r--Swiften/FileTransfer/ByteArrayReadBytestream.cpp24
-rw-r--r--Swiften/FileTransfer/ByteArrayReadBytestream.h34
-rw-r--r--Swiften/FileTransfer/ByteArrayWriteBytestream.h30
-rw-r--r--Swiften/FileTransfer/BytestreamException.h10
-rw-r--r--Swiften/FileTransfer/BytestreamsRequest.h30
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.cpp366
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.h172
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp96
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h68
-rw-r--r--Swiften/FileTransfer/FailingTransportSession.h18
-rw-r--r--Swiften/FileTransfer/FileReadBytestream.cpp32
-rw-r--r--Swiften/FileTransfer/FileReadBytestream.h20
-rw-r--r--Swiften/FileTransfer/FileTransfer.cpp10
-rw-r--r--Swiften/FileTransfer/FileTransfer.h128
-rw-r--r--Swiften/FileTransfer/FileTransferError.h32
-rw-r--r--Swiften/FileTransfer/FileTransferManager.cpp12
-rw-r--r--Swiften/FileTransfer/FileTransferManager.h50
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.cpp238
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.h136
-rw-r--r--Swiften/FileTransfer/FileTransferOptions.h82
-rw-r--r--Swiften/FileTransfer/FileTransferTransporter.h84
-rw-r--r--Swiften/FileTransfer/FileTransferTransporterFactory.h32
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.cpp48
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.h20
-rw-r--r--Swiften/FileTransfer/IBBReceiveSession.cpp152
-rw-r--r--Swiften/FileTransfer/IBBReceiveSession.h86
-rw-r--r--Swiften/FileTransfer/IBBReceiveTransportSession.cpp6
-rw-r--r--Swiften/FileTransfer/IBBReceiveTransportSession.h18
-rw-r--r--Swiften/FileTransfer/IBBRequest.h20
-rw-r--r--Swiften/FileTransfer/IBBSendSession.cpp128
-rw-r--r--Swiften/FileTransfer/IBBSendSession.h82
-rw-r--r--Swiften/FileTransfer/IBBSendTransportSession.cpp8
-rw-r--r--Swiften/FileTransfer/IBBSendTransportSession.h18
-rw-r--r--Swiften/FileTransfer/IncomingFileTransfer.h40
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.cpp68
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.h56
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.cpp564
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.h210
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp60
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h36
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.cpp338
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.h130
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp262
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h74
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransfer.h14
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.cpp60
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.h74
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp540
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.h186
-rw-r--r--Swiften/FileTransfer/ReadBytestream.h32
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp96
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h66
-rw-r--r--Swiften/FileTransfer/S5BTransportSession.h78
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp392
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.h98
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp270
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h84
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp72
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h34
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp16
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.h28
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.cpp54
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.h40
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp330
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerManager.h148
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp28
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h20
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp16
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h20
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp264
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.h128
-rw-r--r--Swiften/FileTransfer/StreamInitiationRequest.h30
-rw-r--r--Swiften/FileTransfer/TransportSession.h16
-rw-r--r--Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h64
-rw-r--r--Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h312
-rw-r--r--Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp294
-rw-r--r--Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp414
-rw-r--r--Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp372
-rw-r--r--Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp434
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp506
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp374
-rw-r--r--Swiften/FileTransfer/WriteBytestream.h24
-rw-r--r--Swiften/History/HistoryMessage.h100
-rw-r--r--Swiften/History/HistoryStorage.h28
-rw-r--r--Swiften/History/SQLiteHistoryStorage.cpp616
-rw-r--r--Swiften/History/SQLiteHistoryStorage.h48
-rw-r--r--Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp194
-rw-r--r--Swiften/IDN/ICUConverter.cpp244
-rw-r--r--Swiften/IDN/ICUConverter.h12
-rw-r--r--Swiften/IDN/IDNConverter.h34
-rw-r--r--Swiften/IDN/LibIDNConverter.cpp92
-rw-r--r--Swiften/IDN/LibIDNConverter.h12
-rw-r--r--Swiften/IDN/PlatformIDNConverter.cpp6
-rw-r--r--Swiften/IDN/PlatformIDNConverter.h8
-rw-r--r--Swiften/IDN/UTF8Validator.h98
-rw-r--r--Swiften/IDN/UnitTest/IDNConverterTest.cpp72
-rw-r--r--Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp64
-rw-r--r--Swiften/JID/JID.cpp418
-rw-r--r--Swiften/JID/JID.h362
-rw-r--r--Swiften/JID/UnitTest/JIDTest.cpp706
-rw-r--r--Swiften/Jingle/AbstractJingleSessionListener.cpp14
-rw-r--r--Swiften/Jingle/AbstractJingleSessionListener.h22
-rw-r--r--Swiften/Jingle/FakeJingleSession.cpp28
-rw-r--r--Swiften/Jingle/FakeJingleSession.h166
-rw-r--r--Swiften/Jingle/IncomingJingleSessionHandler.h10
-rw-r--r--Swiften/Jingle/Jingle.h22
-rw-r--r--Swiften/Jingle/JingleContentID.h32
-rw-r--r--Swiften/Jingle/JingleResponder.cpp70
-rw-r--r--Swiften/Jingle/JingleResponder.h24
-rw-r--r--Swiften/Jingle/JingleSession.cpp6
-rw-r--r--Swiften/Jingle/JingleSession.h64
-rw-r--r--Swiften/Jingle/JingleSessionImpl.cpp262
-rw-r--r--Swiften/Jingle/JingleSessionImpl.h68
-rw-r--r--Swiften/Jingle/JingleSessionListener.h48
-rw-r--r--Swiften/Jingle/JingleSessionManager.cpp34
-rw-r--r--Swiften/Jingle/JingleSessionManager.h68
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp70
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h32
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp48
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h66
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h26
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp138
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h66
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp4
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h22
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp76
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h32
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h94
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp156
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h72
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp14
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h46
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h80
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h92
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h86
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h18
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDQuerier.h36
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h16
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h14
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h30
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDServiceID.h104
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h24
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp144
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h128
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp4
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h30
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h36
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h28
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h26
-rw-r--r--Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp12
-rw-r--r--Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h20
-rw-r--r--Swiften/LinkLocal/IncomingLinkLocalSession.cpp64
-rw-r--r--Swiften/LinkLocal/IncomingLinkLocalSession.h54
-rw-r--r--Swiften/LinkLocal/LinkLocalConnector.cpp74
-rw-r--r--Swiften/LinkLocal/LinkLocalConnector.h78
-rw-r--r--Swiften/LinkLocal/LinkLocalService.cpp32
-rw-r--r--Swiften/LinkLocal/LinkLocalService.h72
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceBrowser.cpp178
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceBrowser.h86
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceInfo.cpp184
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceInfo.h70
-rw-r--r--Swiften/LinkLocal/OutgoingLinkLocalSession.cpp36
-rw-r--r--Swiften/LinkLocal/OutgoingLinkLocalSession.h52
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp236
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp772
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp88
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp102
-rw-r--r--Swiften/MUC/MUC.h130
-rw-r--r--Swiften/MUC/MUCBookmark.h142
-rw-r--r--Swiften/MUC/MUCBookmarkManager.cpp150
-rw-r--r--Swiften/MUC/MUCBookmarkManager.h62
-rw-r--r--Swiften/MUC/MUCImpl.cpp658
-rw-r--r--Swiften/MUC/MUCImpl.h204
-rw-r--r--Swiften/MUC/MUCManager.cpp2
-rw-r--r--Swiften/MUC/MUCManager.h28
-rw-r--r--Swiften/MUC/MUCRegistry.cpp6
-rw-r--r--Swiften/MUC/MUCRegistry.h20
-rw-r--r--Swiften/MUC/UnitTest/MUCTest.cpp496
-rw-r--r--Swiften/MUC/UnitTest/MockMUC.cpp32
-rw-r--r--Swiften/MUC/UnitTest/MockMUC.h124
-rw-r--r--Swiften/Network/BOSHConnection.cpp528
-rw-r--r--Swiften/Network/BOSHConnection.h184
-rw-r--r--Swiften/Network/BOSHConnectionPool.cpp418
-rw-r--r--Swiften/Network/BOSHConnectionPool.h124
-rw-r--r--Swiften/Network/BoostConnection.cpp194
-rw-r--r--Swiften/Network/BoostConnection.h110
-rw-r--r--Swiften/Network/BoostConnectionFactory.cpp2
-rw-r--r--Swiften/Network/BoostConnectionFactory.h18
-rw-r--r--Swiften/Network/BoostConnectionServer.cpp118
-rw-r--r--Swiften/Network/BoostConnectionServer.h54
-rw-r--r--Swiften/Network/BoostConnectionServerFactory.cpp4
-rw-r--r--Swiften/Network/BoostConnectionServerFactory.h20
-rw-r--r--Swiften/Network/BoostIOServiceThread.cpp30
-rw-r--r--Swiften/Network/BoostIOServiceThread.h42
-rw-r--r--Swiften/Network/BoostNetworkFactories.cpp52
-rw-r--r--Swiften/Network/BoostNetworkFactories.h158
-rw-r--r--Swiften/Network/BoostTimer.cpp60
-rw-r--r--Swiften/Network/BoostTimer.h42
-rw-r--r--Swiften/Network/BoostTimerFactory.cpp2
-rw-r--r--Swiften/Network/BoostTimerFactory.h20
-rw-r--r--Swiften/Network/CachingDomainNameResolver.cpp8
-rw-r--r--Swiften/Network/CachingDomainNameResolver.h20
-rw-r--r--Swiften/Network/ChainedConnector.cpp106
-rw-r--r--Swiften/Network/ChainedConnector.h68
-rw-r--r--Swiften/Network/Connection.h56
-rw-r--r--Swiften/Network/ConnectionFactory.h12
-rw-r--r--Swiften/Network/ConnectionServer.h26
-rw-r--r--Swiften/Network/ConnectionServerFactory.h16
-rw-r--r--Swiften/Network/Connector.cpp270
-rw-r--r--Swiften/Network/Connector.h94
-rw-r--r--Swiften/Network/DomainNameAddressQuery.h14
-rw-r--r--Swiften/Network/DomainNameResolveError.h8
-rw-r--r--Swiften/Network/DomainNameResolver.h18
-rw-r--r--Swiften/Network/DomainNameServiceQuery.cpp58
-rw-r--r--Swiften/Network/DomainNameServiceQuery.h32
-rw-r--r--Swiften/Network/DummyConnection.cpp6
-rw-r--r--Swiften/Network/DummyConnection.h48
-rw-r--r--Swiften/Network/DummyConnectionFactory.h12
-rw-r--r--Swiften/Network/DummyConnectionServer.h36
-rw-r--r--Swiften/Network/DummyConnectionServerFactory.h18
-rw-r--r--Swiften/Network/DummyTimerFactory.cpp62
-rw-r--r--Swiften/Network/DummyTimerFactory.h22
-rw-r--r--Swiften/Network/EnvironmentProxyProvider.cpp34
-rw-r--r--Swiften/Network/EnvironmentProxyProvider.h20
-rw-r--r--Swiften/Network/FakeConnection.cpp66
-rw-r--r--Swiften/Network/FakeConnection.h74
-rw-r--r--Swiften/Network/GConfProxyProvider.cpp48
-rw-r--r--Swiften/Network/GConfProxyProvider.h20
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.cpp220
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.h52
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp6
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnectionFactory.h38
-rw-r--r--Swiften/Network/HTTPTrafficFilter.h18
-rw-r--r--Swiften/Network/HostAddress.cpp48
-rw-r--r--Swiften/Network/HostAddress.h40
-rw-r--r--Swiften/Network/HostAddressPort.cpp6
-rw-r--r--Swiften/Network/HostAddressPort.h54
-rw-r--r--Swiften/Network/HostNameOrAddress.cpp20
-rw-r--r--Swiften/Network/HostNameOrAddress.h4
-rw-r--r--Swiften/Network/MacOSXProxyProvider.cpp114
-rw-r--r--Swiften/Network/MacOSXProxyProvider.h12
-rw-r--r--Swiften/Network/MiniUPnPInterface.cpp136
-rw-r--r--Swiften/Network/MiniUPnPInterface.h24
-rw-r--r--Swiften/Network/NATPMPInterface.cpp186
-rw-r--r--Swiften/Network/NATPMPInterface.h24
-rw-r--r--Swiften/Network/NATPortMapping.h68
-rw-r--r--Swiften/Network/NATTraversalForwardPortRequest.h14
-rw-r--r--Swiften/Network/NATTraversalGetPublicIPRequest.h14
-rw-r--r--Swiften/Network/NATTraversalInterface.h16
-rw-r--r--Swiften/Network/NATTraversalRemovePortForwardingRequest.h44
-rw-r--r--Swiften/Network/NATTraverser.h20
-rw-r--r--Swiften/Network/NetworkEnvironment.cpp22
-rw-r--r--Swiften/Network/NetworkEnvironment.h12
-rw-r--r--Swiften/Network/NetworkFactories.h64
-rw-r--r--Swiften/Network/NetworkInterface.h52
-rw-r--r--Swiften/Network/NullNATTraversalInterface.h30
-rw-r--r--Swiften/Network/NullNATTraverser.cpp66
-rw-r--r--Swiften/Network/NullNATTraverser.h20
-rw-r--r--Swiften/Network/NullProxyProvider.cpp4
-rw-r--r--Swiften/Network/NullProxyProvider.h12
-rw-r--r--Swiften/Network/PlatformDomainNameAddressQuery.cpp76
-rw-r--r--Swiften/Network/PlatformDomainNameAddressQuery.h40
-rw-r--r--Swiften/Network/PlatformDomainNameQuery.h28
-rw-r--r--Swiften/Network/PlatformDomainNameResolver.cpp66
-rw-r--r--Swiften/Network/PlatformDomainNameResolver.h52
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.cpp244
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.h28
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.cpp238
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.h76
-rw-r--r--Swiften/Network/PlatformNetworkEnvironment.h8
-rw-r--r--Swiften/Network/PlatformProxyProvider.h6
-rw-r--r--Swiften/Network/ProxiedConnection.cpp136
-rw-r--r--Swiften/Network/ProxiedConnection.h96
-rw-r--r--Swiften/Network/ProxyProvider.h14
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnection.cpp174
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnection.h50
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp2
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnectionFactory.h26
-rw-r--r--Swiften/Network/SolarisNetworkEnvironment.cpp384
-rw-r--r--Swiften/Network/SolarisNetworkEnvironment.h8
-rw-r--r--Swiften/Network/StaticDomainNameResolver.cpp132
-rw-r--r--Swiften/Network/StaticDomainNameResolver.h78
-rw-r--r--Swiften/Network/TLSConnection.cpp72
-rw-r--r--Swiften/Network/TLSConnection.h66
-rw-r--r--Swiften/Network/TLSConnectionFactory.cpp2
-rw-r--r--Swiften/Network/TLSConnectionFactory.h22
-rw-r--r--Swiften/Network/Timer.h48
-rw-r--r--Swiften/Network/TimerFactory.h10
-rwxr-xr-xSwiften/Network/UnboundDomainNameResolver.cpp350
-rwxr-xr-xSwiften/Network/UnboundDomainNameResolver.h48
-rw-r--r--Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp860
-rw-r--r--Swiften/Network/UnitTest/BOSHConnectionTest.cpp540
-rw-r--r--Swiften/Network/UnitTest/ChainedConnectorTest.cpp320
-rw-r--r--Swiften/Network/UnitTest/ConnectorTest.cpp704
-rw-r--r--Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp102
-rw-r--r--Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp784
-rw-r--r--Swiften/Network/UnitTest/HostAddressTest.cpp72
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.cpp60
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.h4
-rw-r--r--Swiften/Network/UnixProxyProvider.cpp48
-rw-r--r--Swiften/Network/UnixProxyProvider.h22
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.cpp74
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.h8
-rw-r--r--Swiften/Network/WindowsProxyProvider.cpp146
-rw-r--r--Swiften/Network/WindowsProxyProvider.h22
-rw-r--r--Swiften/Parser/Attribute.h34
-rw-r--r--Swiften/Parser/AttributeMap.cpp50
-rw-r--r--Swiften/Parser/AttributeMap.h72
-rw-r--r--Swiften/Parser/AuthChallengeParser.cpp12
-rw-r--r--Swiften/Parser/AuthChallengeParser.h20
-rw-r--r--Swiften/Parser/AuthFailureParser.h8
-rw-r--r--Swiften/Parser/AuthRequestParser.cpp18
-rw-r--r--Swiften/Parser/AuthRequestParser.h20
-rw-r--r--Swiften/Parser/AuthResponseParser.cpp12
-rw-r--r--Swiften/Parser/AuthResponseParser.h20
-rw-r--r--Swiften/Parser/AuthSuccessParser.cpp12
-rw-r--r--Swiften/Parser/AuthSuccessParser.h20
-rw-r--r--Swiften/Parser/BOSHBodyExtractor.cpp216
-rw-r--r--Swiften/Parser/BOSHBodyExtractor.h38
-rw-r--r--Swiften/Parser/ComponentHandshakeParser.cpp12
-rw-r--r--Swiften/Parser/ComponentHandshakeParser.h20
-rw-r--r--Swiften/Parser/CompressFailureParser.h8
-rw-r--r--Swiften/Parser/CompressParser.cpp22
-rw-r--r--Swiften/Parser/CompressParser.h24
-rw-r--r--Swiften/Parser/CompressedParser.h8
-rw-r--r--Swiften/Parser/ElementParser.h16
-rw-r--r--Swiften/Parser/EnableStreamManagementParser.h8
-rw-r--r--Swiften/Parser/EnumParser.h38
-rw-r--r--Swiften/Parser/ExpatParser.cpp82
-rw-r--r--Swiften/Parser/ExpatParser.h20
-rw-r--r--Swiften/Parser/GenericElementParser.h48
-rw-r--r--Swiften/Parser/GenericPayloadParser.h54
-rw-r--r--Swiften/Parser/GenericPayloadParserFactory.h46
-rw-r--r--Swiften/Parser/GenericPayloadParserFactory2.h52
-rw-r--r--Swiften/Parser/GenericPayloadTreeParser.h70
-rw-r--r--Swiften/Parser/GenericStanzaParser.h44
-rw-r--r--Swiften/Parser/IQParser.cpp42
-rw-r--r--Swiften/Parser/IQParser.h12
-rw-r--r--Swiften/Parser/LibXMLParser.cpp114
-rw-r--r--Swiften/Parser/LibXMLParser.h28
-rw-r--r--Swiften/Parser/MessageParser.cpp42
-rw-r--r--Swiften/Parser/MessageParser.h12
-rw-r--r--Swiften/Parser/PayloadParser.h68
-rw-r--r--Swiften/Parser/PayloadParserFactory.h34
-rw-r--r--Swiften/Parser/PayloadParserFactoryCollection.cpp14
-rw-r--r--Swiften/Parser/PayloadParserFactoryCollection.h24
-rw-r--r--Swiften/Parser/PayloadParsers/BlockParser.h44
-rw-r--r--Swiften/Parser/PayloadParsers/BodyParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/BodyParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/BytestreamsParser.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/BytestreamsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/CapsInfoParser.cpp14
-rw-r--r--Swiften/Parser/PayloadParsers/CapsInfoParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsDisableParser.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsDisableParser.h16
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsEnableParser.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsEnableParser.h16
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsPrivateParser.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h16
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsSentParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/ChatStateParser.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/ChatStateParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/ChatStateParserFactory.h28
-rw-r--r--Swiften/Parser/PayloadParsers/CommandParser.cpp210
-rw-r--r--Swiften/Parser/PayloadParsers/CommandParser.h60
-rw-r--r--Swiften/Parser/PayloadParsers/DelayParser.cpp20
-rw-r--r--Swiften/Parser/PayloadParsers/DelayParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/DeliveryReceiptParser.cpp18
-rw-r--r--Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/DiscoInfoParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/DiscoItemsParser.cpp24
-rw-r--r--Swiften/Parser/PayloadParsers/DiscoItemsParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/ErrorParser.cpp236
-rw-r--r--Swiften/Parser/PayloadParsers/ErrorParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/ErrorParserFactory.h28
-rw-r--r--Swiften/Parser/PayloadParsers/FormParser.cpp456
-rw-r--r--Swiften/Parser/PayloadParsers/FormParser.h60
-rw-r--r--Swiften/Parser/PayloadParsers/FormParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/ForwardedParser.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/ForwardedParser.h46
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp168
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h16
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.cpp90
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/IdleParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/IdleParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp192
-rw-r--r--Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp118
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp50
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp92
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp46
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h16
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.cpp192
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.cpp138
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp148
-rw-r--r--Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/LastParser.cpp20
-rw-r--r--Swiften/Parser/PayloadParsers/LastParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/MAMFinParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/MAMFinParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/MAMQueryParser.cpp90
-rw-r--r--Swiften/Parser/PayloadParsers/MAMQueryParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/MAMResultParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/MAMResultParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp16
-rw-r--r--Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCItemParser.cpp104
-rw-r--r--Swiften/Parser/PayloadParsers/MUCItemParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp48
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h28
-rw-r--r--Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp72
-rw-r--r--Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h16
-rw-r--r--Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h26
-rw-r--r--Swiften/Parser/PayloadParsers/NicknameParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/NicknameParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/PriorityParser.cpp24
-rw-r--r--Swiften/Parser/PayloadParsers/PriorityParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp48
-rw-r--r--Swiften/Parser/PayloadParsers/PrivateStorageParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h30
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp56
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubConfigureParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubCreateParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubDefaultParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp160
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventParser.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp84
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemParser.cpp60
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp78
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp74
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOptionsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp56
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp52
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubParser.cpp154
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubPublishParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubRetractParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp44
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp84
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp68
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp16
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h20
-rw-r--r--Swiften/Parser/PayloadParsers/ReplaceParser.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/ReplaceParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/ResourceBindParser.cpp40
-rw-r--r--Swiften/Parser/PayloadParsers/ResourceBindParser.h24
-rw-r--r--Swiften/Parser/PayloadParsers/ResultSetParser.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/ResultSetParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/RosterParser.cpp148
-rw-r--r--Swiften/Parser/PayloadParsers/RosterParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp156
-rw-r--r--Swiften/Parser/PayloadParsers/SearchPayloadParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h8
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp86
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/SoftwareVersionParser.cpp30
-rw-r--r--Swiften/Parser/PayloadParsers/SoftwareVersionParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/StartSessionParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/StatusParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/StatusParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/StatusShowParser.cpp40
-rw-r--r--Swiften/Parser/PayloadParsers/StatusShowParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/StorageParser.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/StorageParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp164
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationParser.h48
-rw-r--r--Swiften/Parser/PayloadParsers/SubjectParser.cpp16
-rw-r--r--Swiften/Parser/PayloadParsers/SubjectParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/ThreadParser.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/ThreadParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp98
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp204
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp118
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp152
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp48
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp76
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp420
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp188
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp40
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp36
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp1172
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp204
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp30
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp144
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h2
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h82
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp150
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp42
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp34
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp36
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp96
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/RosterParserTest.cpp164
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp326
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp88
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp44
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/StatusParserTest.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp110
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/StorageParserTest.cpp136
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp102
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp154
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp74
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp368
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp28
-rw-r--r--Swiften/Parser/PayloadParsers/UserLocationParser.cpp156
-rw-r--r--Swiften/Parser/PayloadParsers/UserLocationParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/UserTuneParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/UserTuneParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/VCardParser.cpp510
-rw-r--r--Swiften/Parser/PayloadParsers/VCardParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp18
-rw-r--r--Swiften/Parser/PayloadParsers/VCardUpdateParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/WhiteboardParser.cpp536
-rw-r--r--Swiften/Parser/PayloadParsers/WhiteboardParser.h32
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.cpp4
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.h10
-rw-r--r--Swiften/Parser/PresenceParser.cpp66
-rw-r--r--Swiften/Parser/PresenceParser.h12
-rw-r--r--Swiften/Parser/SerializingParser.cpp38
-rw-r--r--Swiften/Parser/SerializingParser.h22
-rw-r--r--Swiften/Parser/StanzaAckParser.cpp20
-rw-r--r--Swiften/Parser/StanzaAckParser.h16
-rw-r--r--Swiften/Parser/StanzaAckRequestParser.h8
-rw-r--r--Swiften/Parser/StanzaParser.cpp102
-rw-r--r--Swiften/Parser/StanzaParser.h52
-rw-r--r--Swiften/Parser/StartTLSFailureParser.h8
-rw-r--r--Swiften/Parser/StartTLSParser.h8
-rw-r--r--Swiften/Parser/StreamErrorParser.cpp172
-rw-r--r--Swiften/Parser/StreamErrorParser.h28
-rw-r--r--Swiften/Parser/StreamFeaturesParser.cpp116
-rw-r--r--Swiften/Parser/StreamFeaturesParser.h32
-rw-r--r--Swiften/Parser/StreamManagementEnabledParser.cpp16
-rw-r--r--Swiften/Parser/StreamManagementEnabledParser.h24
-rw-r--r--Swiften/Parser/StreamManagementFailedParser.h8
-rw-r--r--Swiften/Parser/StreamResumeParser.cpp26
-rw-r--r--Swiften/Parser/StreamResumeParser.h24
-rw-r--r--Swiften/Parser/StreamResumedParser.cpp26
-rw-r--r--Swiften/Parser/StreamResumedParser.h24
-rw-r--r--Swiften/Parser/TLSProceedParser.h8
-rw-r--r--Swiften/Parser/Tree/NullParserElement.h12
-rw-r--r--Swiften/Parser/Tree/ParserElement.cpp22
-rw-r--r--Swiften/Parser/Tree/ParserElement.h60
-rw-r--r--Swiften/Parser/Tree/TreeReparser.cpp44
-rw-r--r--Swiften/Parser/Tree/TreeReparser.h10
-rw-r--r--Swiften/Parser/UnitTest/AttributeMapTest.cpp102
-rw-r--r--Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp172
-rw-r--r--Swiften/Parser/UnitTest/ElementParserTester.h2
-rw-r--r--Swiften/Parser/UnitTest/EnumParserTest.cpp38
-rw-r--r--Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp76
-rw-r--r--Swiften/Parser/UnitTest/IQParserTest.cpp78
-rw-r--r--Swiften/Parser/UnitTest/MessageParserTest.cpp92
-rw-r--r--Swiften/Parser/UnitTest/ParserTester.h66
-rw-r--r--Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp168
-rw-r--r--Swiften/Parser/UnitTest/PresenceParserTest.cpp134
-rw-r--r--Swiften/Parser/UnitTest/SerializingParserTest.cpp74
-rw-r--r--Swiften/Parser/UnitTest/StanzaAckParserTest.cpp50
-rw-r--r--Swiften/Parser/UnitTest/StanzaParserTest.cpp380
-rw-r--r--Swiften/Parser/UnitTest/StanzaParserTester.h2
-rw-r--r--Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp180
-rw-r--r--Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp32
-rw-r--r--Swiften/Parser/UnitTest/XMLParserTest.cpp548
-rw-r--r--Swiften/Parser/UnitTest/XMPPParserTest.cpp324
-rw-r--r--Swiften/Parser/UnknownElementParser.h8
-rw-r--r--Swiften/Parser/UnknownPayloadParser.h20
-rw-r--r--Swiften/Parser/XMLParser.h24
-rw-r--r--Swiften/Parser/XMLParserClient.h14
-rw-r--r--Swiften/Parser/XMLParserFactory.h14
-rw-r--r--Swiften/Parser/XMPPParser.cpp270
-rw-r--r--Swiften/Parser/XMPPParser.h78
-rw-r--r--Swiften/Parser/XMPPParserClient.h18
-rw-r--r--Swiften/Presence/DirectedPresenceSender.cpp60
-rw-r--r--Swiften/Presence/DirectedPresenceSender.h28
-rw-r--r--Swiften/Presence/PayloadAddingPresenceSender.cpp44
-rw-r--r--Swiften/Presence/PayloadAddingPresenceSender.h70
-rw-r--r--Swiften/Presence/PresenceOracle.cpp324
-rw-r--r--Swiften/Presence/PresenceOracle.h106
-rw-r--r--Swiften/Presence/PresenceSender.h12
-rw-r--r--Swiften/Presence/StanzaChannelPresenceSender.cpp4
-rw-r--r--Swiften/Presence/StanzaChannelPresenceSender.h18
-rw-r--r--Swiften/Presence/SubscriptionManager.cpp42
-rw-r--r--Swiften/Presence/SubscriptionManager.h58
-rw-r--r--Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp268
-rw-r--r--Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp182
-rw-r--r--Swiften/Presence/UnitTest/PresenceOracleTest.cpp448
-rw-r--r--Swiften/PubSub/PubSubManager.h22
-rw-r--r--Swiften/PubSub/PubSubManagerImpl.cpp16
-rw-r--r--Swiften/PubSub/PubSubManagerImpl.h38
-rw-r--r--Swiften/PubSub/PubSubUtil.h34
-rw-r--r--Swiften/QA/ClientTest/ClientTest.cpp114
-rw-r--r--Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp40
-rw-r--r--Swiften/QA/DNSSDTest/DNSSDTest.cpp228
-rw-r--r--Swiften/QA/FileTransferTest/FileTransferTest.cpp672
-rw-r--r--Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp384
-rwxr-xr-xSwiften/QA/NetworkTest/BoostConnectionTest.cpp276
-rw-r--r--Swiften/QA/NetworkTest/DomainNameResolverTest.cpp410
-rw-r--r--Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp38
-rw-r--r--Swiften/QA/ReconnectTest/ReconnectTest.cpp78
-rw-r--r--Swiften/QA/StorageTest/FileReadBytestreamTest.cpp78
-rw-r--r--Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp54
-rw-r--r--Swiften/QA/StorageTest/VCardFileStorageTest.cpp182
-rw-r--r--Swiften/QA/TLSTest/CertificateErrorTest.cpp364
-rw-r--r--Swiften/QA/TLSTest/CertificateTest.cpp146
-rw-r--r--Swiften/Queries/DummyIQChannel.h28
-rw-r--r--Swiften/Queries/GenericRequest.h120
-rw-r--r--Swiften/Queries/GetResponder.h14
-rw-r--r--Swiften/Queries/IQChannel.h18
-rw-r--r--Swiften/Queries/IQHandler.h12
-rw-r--r--Swiften/Queries/IQRouter.cpp80
-rw-r--r--Swiften/Queries/IQRouter.h126
-rw-r--r--Swiften/Queries/PubSubRequest.h94
-rw-r--r--Swiften/Queries/RawRequest.h58
-rw-r--r--Swiften/Queries/Request.cpp108
-rw-r--r--Swiften/Queries/Request.h168
-rw-r--r--Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h20
-rw-r--r--Swiften/Queries/Requests/GetPrivateStorageRequest.h52
-rw-r--r--Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h28
-rw-r--r--Swiften/Queries/Requests/GetSoftwareVersionRequest.h28
-rw-r--r--Swiften/Queries/Requests/SetPrivateStorageRequest.h40
-rw-r--r--Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h30
-rw-r--r--Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp174
-rw-r--r--Swiften/Queries/Responder.h242
-rw-r--r--Swiften/Queries/Responders/SoftwareVersionResponder.cpp10
-rw-r--r--Swiften/Queries/Responders/SoftwareVersionResponder.h24
-rw-r--r--Swiften/Queries/SetResponder.h14
-rw-r--r--Swiften/Queries/UnitTest/IQRouterTest.cpp274
-rw-r--r--Swiften/Queries/UnitTest/RequestTest.cpp684
-rw-r--r--Swiften/Queries/UnitTest/ResponderTest.cpp258
-rw-r--r--Swiften/Roster/GetRosterRequest.h32
-rw-r--r--Swiften/Roster/RosterMemoryStorage.cpp8
-rw-r--r--Swiften/Roster/RosterMemoryStorage.h20
-rw-r--r--Swiften/Roster/RosterPushResponder.h34
-rw-r--r--Swiften/Roster/RosterStorage.h12
-rw-r--r--Swiften/Roster/SetRosterRequest.h36
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp668
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp166
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp20
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h76
-rw-r--r--Swiften/Roster/XMPPRoster.h152
-rw-r--r--Swiften/Roster/XMPPRosterController.cpp106
-rw-r--r--Swiften/Roster/XMPPRosterController.h52
-rw-r--r--Swiften/Roster/XMPPRosterImpl.cpp112
-rw-r--r--Swiften/Roster/XMPPRosterImpl.h44
-rw-r--r--Swiften/Roster/XMPPRosterItem.h70
-rw-r--r--Swiften/SASL/ClientAuthenticator.h72
-rw-r--r--Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp128
-rw-r--r--Swiften/SASL/DIGESTMD5ClientAuthenticator.h36
-rw-r--r--Swiften/SASL/DIGESTMD5Properties.cpp188
-rw-r--r--Swiften/SASL/DIGESTMD5Properties.h28
-rw-r--r--Swiften/SASL/EXTERNALClientAuthenticator.cpp12
-rw-r--r--Swiften/SASL/EXTERNALClientAuthenticator.h16
-rw-r--r--Swiften/SASL/PLAINClientAuthenticator.cpp4
-rw-r--r--Swiften/SASL/PLAINClientAuthenticator.h12
-rw-r--r--Swiften/SASL/PLAINMessage.cpp46
-rw-r--r--Swiften/SASL/PLAINMessage.h48
-rw-r--r--Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp266
-rw-r--r--Swiften/SASL/SCRAMSHA1ClientAuthenticator.h72
-rw-r--r--Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp96
-rw-r--r--Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp76
-rw-r--r--Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp30
-rw-r--r--Swiften/SASL/UnitTest/PLAINMessageTest.cpp98
-rw-r--r--Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp304
-rw-r--r--Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp284
-rw-r--r--Swiften/SASL/WindowsAuthentication.cpp502
-rw-r--r--Swiften/SASL/WindowsAuthentication.h280
-rw-r--r--Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp318
-rw-r--r--Swiften/SASL/WindowsGSSAPIClientAuthenticator.h176
-rw-r--r--Swiften/SASL/WindowsServicePrincipalName.cpp104
-rw-r--r--Swiften/SASL/WindowsServicePrincipalName.h94
-rw-r--r--Swiften/Serializer/AuthChallengeSerializer.cpp24
-rw-r--r--Swiften/Serializer/AuthChallengeSerializer.h10
-rw-r--r--Swiften/Serializer/AuthFailureSerializer.h16
-rw-r--r--Swiften/Serializer/AuthRequestSerializer.cpp24
-rw-r--r--Swiften/Serializer/AuthRequestSerializer.h10
-rw-r--r--Swiften/Serializer/AuthResponseSerializer.cpp26
-rw-r--r--Swiften/Serializer/AuthResponseSerializer.h10
-rw-r--r--Swiften/Serializer/AuthSuccessSerializer.cpp24
-rw-r--r--Swiften/Serializer/AuthSuccessSerializer.h10
-rw-r--r--Swiften/Serializer/ComponentHandshakeSerializer.cpp4
-rw-r--r--Swiften/Serializer/ComponentHandshakeSerializer.h10
-rw-r--r--Swiften/Serializer/CompressFailureSerializer.h16
-rw-r--r--Swiften/Serializer/CompressRequestSerializer.cpp6
-rw-r--r--Swiften/Serializer/CompressRequestSerializer.h12
-rw-r--r--Swiften/Serializer/ElementSerializer.h12
-rw-r--r--Swiften/Serializer/EnableStreamManagementSerializer.h16
-rw-r--r--Swiften/Serializer/GenericElementSerializer.h16
-rw-r--r--Swiften/Serializer/GenericPayloadSerializer.h22
-rw-r--r--Swiften/Serializer/GenericStanzaSerializer.h34
-rw-r--r--Swiften/Serializer/IQSerializer.h34
-rw-r--r--Swiften/Serializer/MessageSerializer.cpp30
-rw-r--r--Swiften/Serializer/MessageSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializerCollection.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializerCollection.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/BlockSerializer.h36
-rw-r--r--Swiften/Serializer/PayloadSerializers/BodySerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp10
-rw-r--r--Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp124
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/DelaySerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp6
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp94
-rw-r--r--Swiften/Serializer/PayloadSerializers/ErrorSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.cpp322
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.h28
-rw-r--r--Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp50
-rw-r--r--Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp166
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp58
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/IdleSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp132
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp88
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp10
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp74
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp204
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h32
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp114
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h26
-rw-r--r--Swiften/Serializer/PayloadSerializers/LastSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp10
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp40
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h100
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp64
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp76
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp6
-rw-r--r--Swiften/Serializer/PayloadSerializers/NicknameSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrioritySerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp32
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp168
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp14
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp14
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h24
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp40
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp36
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp14
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h24
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp56
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp44
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp60
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp44
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp72
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h38
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp60
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/StatusSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h44
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp58
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp56
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp84
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/SubjectSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/ThreadSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp66
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp212
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp72
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp82
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp50
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp562
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp186
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp36
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp88
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp196
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp742
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp70
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp80
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp76
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp38
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h12
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp62
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp54
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp84
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp26
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp144
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp72
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp168
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp316
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp86
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp102
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp78
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp96
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp94
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp142
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp72
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp260
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp142
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp52
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp448
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp12
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h10
-rw-r--r--Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp364
-rw-r--r--Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h46
-rw-r--r--Swiften/Serializer/PresenceSerializer.cpp26
-rw-r--r--Swiften/Serializer/PresenceSerializer.h18
-rw-r--r--Swiften/Serializer/StanzaAckRequestSerializer.h16
-rw-r--r--Swiften/Serializer/StanzaAckSerializer.h24
-rw-r--r--Swiften/Serializer/StanzaSerializer.cpp64
-rw-r--r--Swiften/Serializer/StanzaSerializer.h32
-rw-r--r--Swiften/Serializer/StartTLSFailureSerializer.h16
-rw-r--r--Swiften/Serializer/StartTLSRequestSerializer.h16
-rw-r--r--Swiften/Serializer/StreamErrorSerializer.cpp76
-rw-r--r--Swiften/Serializer/StreamErrorSerializer.h10
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.cpp74
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.h10
-rw-r--r--Swiften/Serializer/StreamManagementEnabledSerializer.cpp18
-rw-r--r--Swiften/Serializer/StreamManagementEnabledSerializer.h10
-rw-r--r--Swiften/Serializer/StreamManagementFailedSerializer.h16
-rw-r--r--Swiften/Serializer/StreamResumeSerializer.cpp14
-rw-r--r--Swiften/Serializer/StreamResumeSerializer.h10
-rw-r--r--Swiften/Serializer/StreamResumedSerializer.cpp14
-rw-r--r--Swiften/Serializer/StreamResumedSerializer.h10
-rw-r--r--Swiften/Serializer/TLSProceedSerializer.h16
-rw-r--r--Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp90
-rw-r--r--Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp98
-rw-r--r--Swiften/Serializer/XML/XMLElement.cpp68
-rw-r--r--Swiften/Serializer/XML/XMLElement.h24
-rw-r--r--Swiften/Serializer/XML/XMLNode.h10
-rw-r--r--Swiften/Serializer/XML/XMLRawTextNode.h20
-rw-r--r--Swiften/Serializer/XML/XMLTextNode.h42
-rw-r--r--Swiften/Serializer/XMPPSerializer.cpp108
-rw-r--r--Swiften/Serializer/XMPPSerializer.h38
-rw-r--r--Swiften/Session/BOSHSessionStream.cpp192
-rw-r--r--Swiften/Session/BOSHSessionStream.h140
-rw-r--r--Swiften/Session/BasicSessionStream.cpp210
-rw-r--r--Swiften/Session/BasicSessionStream.h126
-rw-r--r--Swiften/Session/Session.cpp130
-rw-r--r--Swiften/Session/Session.h186
-rw-r--r--Swiften/Session/SessionStream.h136
-rw-r--r--Swiften/Session/SessionTracer.cpp16
-rw-r--r--Swiften/Session/SessionTracer.h14
-rw-r--r--Swiften/StreamManagement/StanzaAckRequester.cpp32
-rw-r--r--Swiften/StreamManagement/StanzaAckRequester.h32
-rw-r--r--Swiften/StreamManagement/StanzaAckResponder.cpp4
-rw-r--r--Swiften/StreamManagement/StanzaAckResponder.h22
-rw-r--r--Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp278
-rw-r--r--Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp148
-rw-r--r--Swiften/StreamStack/CompressionLayer.h64
-rw-r--r--Swiften/StreamStack/ConnectionLayer.cpp6
-rw-r--r--Swiften/StreamStack/ConnectionLayer.h24
-rw-r--r--Swiften/StreamStack/DummyStreamLayer.h28
-rw-r--r--Swiften/StreamStack/HighLayer.cpp8
-rw-r--r--Swiften/StreamStack/HighLayer.h38
-rw-r--r--Swiften/StreamStack/LowLayer.cpp4
-rw-r--r--Swiften/StreamStack/LowLayer.h40
-rw-r--r--Swiften/StreamStack/StreamLayer.h8
-rw-r--r--Swiften/StreamStack/StreamStack.cpp18
-rw-r--r--Swiften/StreamStack/StreamStack.h60
-rw-r--r--Swiften/StreamStack/TLSLayer.cpp26
-rw-r--r--Swiften/StreamStack/TLSLayer.h44
-rw-r--r--Swiften/StreamStack/UnitTest/StreamStackTest.cpp302
-rw-r--r--Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp230
-rw-r--r--Swiften/StreamStack/WhitespacePingLayer.cpp32
-rw-r--r--Swiften/StreamStack/WhitespacePingLayer.h48
-rw-r--r--Swiften/StreamStack/XMPPLayer.cpp92
-rw-r--r--Swiften/StreamStack/XMPPLayer.h92
-rw-r--r--Swiften/StringCodecs/Base64.cpp150
-rw-r--r--Swiften/StringCodecs/Base64.h12
-rw-r--r--Swiften/StringCodecs/Hexify.cpp76
-rw-r--r--Swiften/StringCodecs/Hexify.h12
-rw-r--r--Swiften/StringCodecs/PBKDF2.h32
-rw-r--r--Swiften/StringCodecs/SHA1_Windows.cpp128
-rw-r--r--Swiften/StringCodecs/SHA1_Windows.h38
-rw-r--r--Swiften/StringCodecs/UnitTest/Base64Test.cpp94
-rw-r--r--Swiften/StringCodecs/UnitTest/HexifyTest.cpp38
-rw-r--r--Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp48
-rw-r--r--Swiften/TLS/BlindCertificateTrustChecker.h28
-rw-r--r--Swiften/TLS/CAPICertificate.cpp570
-rw-r--r--Swiften/TLS/CAPICertificate.h60
-rw-r--r--Swiften/TLS/Certificate.cpp18
-rw-r--r--Swiften/TLS/Certificate.h40
-rw-r--r--Swiften/TLS/CertificateFactory.h10
-rw-r--r--Swiften/TLS/CertificateTrustChecker.h32
-rw-r--r--Swiften/TLS/CertificateVerificationError.h58
-rw-r--r--Swiften/TLS/CertificateWithKey.h14
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp140
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.h108
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h12
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.cpp496
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.h50
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp18
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.h16
-rw-r--r--Swiften/TLS/PKCS12Certificate.h82
-rw-r--r--Swiften/TLS/PlatformTLSFactories.cpp34
-rw-r--r--Swiften/TLS/PlatformTLSFactories.h24
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificate.cpp284
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificate.h140
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificateFactory.h12
-rw-r--r--Swiften/TLS/Schannel/SchannelContext.cpp1080
-rw-r--r--Swiften/TLS/Schannel/SchannelContext.h122
-rw-r--r--Swiften/TLS/Schannel/SchannelContextFactory.cpp14
-rw-r--r--Swiften/TLS/Schannel/SchannelContextFactory.h22
-rw-r--r--Swiften/TLS/Schannel/SchannelUtil.h814
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificate.h34
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificate.mm164
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h12
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContext.h60
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContext.mm778
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp14
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContextFactory.h20
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.cpp124
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.h26
-rw-r--r--Swiften/TLS/SimpleCertificate.h126
-rw-r--r--Swiften/TLS/TLSContext.cpp4
-rw-r--r--Swiften/TLS/TLSContext.h34
-rw-r--r--Swiften/TLS/TLSContextFactory.h18
-rw-r--r--Swiften/TLS/TLSError.h28
-rw-r--r--Swiften/TLS/TLSOptions.h22
-rw-r--r--Swiften/TLS/UnitTest/CertificateTest.cpp18
-rw-r--r--Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp290
-rw-r--r--Swiften/VCards/GetVCardRequest.h20
-rw-r--r--Swiften/VCards/SetVCardRequest.h20
-rw-r--r--Swiften/VCards/UnitTest/VCardManagerTest.cpp366
-rw-r--r--Swiften/VCards/VCardManager.cpp80
-rw-r--r--Swiften/VCards/VCardManager.h76
-rw-r--r--Swiften/VCards/VCardMemoryStorage.h68
-rw-r--r--Swiften/VCards/VCardStorage.cpp14
-rw-r--r--Swiften/VCards/VCardStorage.h26
-rw-r--r--Swiften/Whiteboard/IncomingWhiteboardSession.cpp70
-rw-r--r--Swiften/Whiteboard/IncomingWhiteboardSession.h24
-rw-r--r--Swiften/Whiteboard/OutgoingWhiteboardSession.cpp68
-rw-r--r--Swiften/Whiteboard/OutgoingWhiteboardSession.h32
-rw-r--r--Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp1302
-rw-r--r--Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp200
-rw-r--r--Swiften/Whiteboard/WhiteboardClient.cpp216
-rw-r--r--Swiften/Whiteboard/WhiteboardClient.h42
-rw-r--r--Swiften/Whiteboard/WhiteboardResponder.cpp40
-rw-r--r--Swiften/Whiteboard/WhiteboardResponder.h20
-rw-r--r--Swiften/Whiteboard/WhiteboardServer.cpp72
-rw-r--r--Swiften/Whiteboard/WhiteboardServer.h16
-rw-r--r--Swiften/Whiteboard/WhiteboardSession.cpp84
-rw-r--r--Swiften/Whiteboard/WhiteboardSession.h70
-rw-r--r--Swiften/Whiteboard/WhiteboardSessionManager.cpp184
-rw-r--r--Swiften/Whiteboard/WhiteboardSessionManager.h66
-rw-r--r--Swiften/Whiteboard/WhiteboardTransformer.cpp404
-rw-r--r--Swiften/Whiteboard/WhiteboardTransformer.h26
2437 files changed, 103802 insertions, 103814 deletions
diff --git a/BuildTools/CheckTabs.py b/BuildTools/CheckTabs.py
index e2029b0..f0ec0ab 100755
--- a/BuildTools/CheckTabs.py
+++ b/BuildTools/CheckTabs.py
@@ -5,27 +5,15 @@ import os, sys
foundExpandedTabs = False
filename = sys.argv[1]
-if (filename.endswith(".cpp") or filename.endswith(".h") or filename.endswith(".py") or filename.endswith("SConscript") or filename.endswith("SConscript.boot") or filename.endswith("SConstruct")) and not "3rdParty" in filename :
- file = open(filename, "r")
- contents = []
- contentsChanged = False
- for line in file.readlines() :
- newline = ""
- previousChar = None
- pastInitialSpace = False
- for char in line :
- if not pastInitialSpace :
- if char == ' ' and previousChar == ' ' :
- contentsChanged = True
- previousChar = '\t'
- continue
- pastInitialSpace = (char != ' ')
- if previousChar :
- newline += previousChar
- previousChar = char
- if previousChar :
- newline += previousChar
- contents.append(newline)
- file.close()
- if contentsChanged :
- sys.exit(-1)
+if (filename.endswith(".cpp") or filename.endswith(".h") or filename.endswith(".c") or filename.endswith(".mm") or filename.endswith(".ipp") or filename.endswith(".hpp") or filename.endswith(".py") or filename.endswith("SConscript") or filename.endswith("SConscript.boot") or filename.endswith("SConstruct")) and not "3rdParty" in filename :
+ file = open(filename, "r")
+ contents = []
+ contentsChanged = False
+ for line in file.readlines() :
+ if "\t" in line:
+ print("File %s contains hard tabs. This is not allowed." % filename)
+ file.close()
+ sys.exit(-1)
+ file.close()
+ if contentsChanged :
+ sys.exit(-1)
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp
index 912ba07..9a7301a 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp
@@ -9,23 +9,23 @@
using namespace Swift;
int main(int, char**) {
- // Set up the event loop and network classes
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ // Set up the event loop and network classes
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- Client client("echobot@wonderland.lit", "mypass", &networkFactories);
- client.setAlwaysTrustCertificates();
- client.onConnected.connect([&] {
- std::cout << "Connected" << std::endl;
- });
- client.onMessageReceived.connect([&] (Message::ref message) {
- message->setTo(message->getFrom());
- message->setFrom(JID());
- client.sendMessage(message);
- });
- client.connect();
+ Client client("echobot@wonderland.lit", "mypass", &networkFactories);
+ client.setAlwaysTrustCertificates();
+ client.onConnected.connect([&] {
+ std::cout << "Connected" << std::endl;
+ });
+ client.onMessageReceived.connect([&] (Message::ref message) {
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client.sendMessage(message);
+ });
+ client.connect();
- eventLoop.run();
+ eventLoop.run();
- return 0;
+ return 0;
}
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp
index 15d1a77..6e04eee 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp
@@ -9,14 +9,14 @@
using namespace Swift;
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- Client client("echobot@wonderland.lit", "mypass", &networkFactories);
- client.setAlwaysTrustCertificates();
- client.connect();
+ Client client("echobot@wonderland.lit", "mypass", &networkFactories);
+ client.setAlwaysTrustCertificates();
+ client.connect();
- eventLoop.run();
+ eventLoop.run();
- return 0;
+ return 0;
}
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp
index 1cec06c..d928db8 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp
@@ -19,28 +19,28 @@ void handleConnected();
void handleMessageReceived(Message::ref message);
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- client = new Client("echobot@wonderland.lit", "mypass", &networkFactories);
- client->setAlwaysTrustCertificates();
- client->onConnected.connect(&handleConnected);
- client->onMessageReceived.connect(bind(&handleMessageReceived, _1));
- client->connect();
+ client = new Client("echobot@wonderland.lit", "mypass", &networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onConnected.connect(&handleConnected);
+ client->onMessageReceived.connect(bind(&handleMessageReceived, _1));
+ client->connect();
- eventLoop.run();
+ eventLoop.run();
- delete client;
- return 0;
+ delete client;
+ return 0;
}
void handleConnected() {
- std::cout << "Connected" << std::endl;
+ std::cout << "Connected" << std::endl;
}
void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(JID());
- client->sendMessage(message);
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client->sendMessage(message);
}
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp
index 4cba31f..470753d 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp
@@ -14,45 +14,45 @@ using namespace Swift;
using namespace boost;
class EchoBot {
- public:
- EchoBot(NetworkFactories* networkFactories) {
- client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
- client->setAlwaysTrustCertificates();
- client->onConnected.connect(bind(&EchoBot::handleConnected, this));
- client->onMessageReceived.connect(
- bind(&EchoBot::handleMessageReceived, this, _1));
- tracer = new ClientXMLTracer(client);
- client->connect();
- }
-
- ~EchoBot() {
- delete tracer;
- delete client;
- }
-
- private:
- void handleConnected() {
- std::cout << "Connected" << std::endl;
- }
-
- void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(JID());
- client->sendMessage(message);
- }
-
- private:
- Client* client;
- ClientXMLTracer* tracer;
+ public:
+ EchoBot(NetworkFactories* networkFactories) {
+ client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onConnected.connect(bind(&EchoBot::handleConnected, this));
+ client->onMessageReceived.connect(
+ bind(&EchoBot::handleMessageReceived, this, _1));
+ tracer = new ClientXMLTracer(client);
+ client->connect();
+ }
+
+ ~EchoBot() {
+ delete tracer;
+ delete client;
+ }
+
+ private:
+ void handleConnected() {
+ std::cout << "Connected" << std::endl;
+ }
+
+ void handleMessageReceived(Message::ref message) {
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client->sendMessage(message);
+ }
+
+ private:
+ Client* client;
+ ClientXMLTracer* tracer;
};
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- EchoBot bot(&networkFactories);
+ EchoBot bot(&networkFactories);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp
index b5537c9..9ab7864 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp
@@ -15,80 +15,80 @@ using namespace Swift;
using namespace boost;
//...
class EchoBot {
- public:
- EchoBot(NetworkFactories* networkFactories) {
- //...
- client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
- client->setAlwaysTrustCertificates();
- client->onConnected.connect(bind(&EchoBot::handleConnected, this));
- client->onMessageReceived.connect(
- bind(&EchoBot::handleMessageReceived, this, _1));
- //...
- client->onPresenceReceived.connect(
- bind(&EchoBot::handlePresenceReceived, this, _1));
- //...
- tracer = new ClientXMLTracer(client);
- client->connect();
- //...
- }
+ public:
+ EchoBot(NetworkFactories* networkFactories) {
+ //...
+ client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onConnected.connect(bind(&EchoBot::handleConnected, this));
+ client->onMessageReceived.connect(
+ bind(&EchoBot::handleMessageReceived, this, _1));
+ //...
+ client->onPresenceReceived.connect(
+ bind(&EchoBot::handlePresenceReceived, this, _1));
+ //...
+ tracer = new ClientXMLTracer(client);
+ client->connect();
+ //...
+ }
- //...
- ~EchoBot() {
- delete tracer;
- delete client;
- }
-
- private:
- //...
- void handlePresenceReceived(Presence::ref presence) {
- // Automatically approve subscription requests
- if (presence->getType() == Presence::Subscribe) {
- Presence::ref response = Presence::create();
- response->setTo(presence->getFrom());
- response->setType(Presence::Subscribed);
- client->sendPresence(response);
- }
- }
+ //...
+ ~EchoBot() {
+ delete tracer;
+ delete client;
+ }
- void handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ private:
+ //...
+ void handlePresenceReceived(Presence::ref presence) {
+ // Automatically approve subscription requests
+ if (presence->getType() == Presence::Subscribe) {
+ Presence::ref response = Presence::create();
+ response->setTo(presence->getFrom());
+ response->setType(Presence::Subscribed);
+ client->sendPresence(response);
+ }
+ }
- void handleRosterReceived(ErrorPayload::ref error) {
- if (error) {
- std::cerr << "Error receiving roster. Continuing anyway.";
- }
- // Send initial available presence
- client->sendPresence(Presence::create("Send me a message"));
- }
- //...
-
- void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(JID());
- client->sendMessage(message);
- }
+ void handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- private:
- Client* client;
- ClientXMLTracer* tracer;
- //...
+ void handleRosterReceived(ErrorPayload::ref error) {
+ if (error) {
+ std::cerr << "Error receiving roster. Continuing anyway.";
+ }
+ // Send initial available presence
+ client->sendPresence(Presence::create("Send me a message"));
+ }
+ //...
+
+ void handleMessageReceived(Message::ref message) {
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client->sendMessage(message);
+ }
+
+ private:
+ Client* client;
+ ClientXMLTracer* tracer;
+ //...
};
//...
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- EchoBot bot(&networkFactories);
+ EchoBot bot(&networkFactories);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
//...
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp
index 811887e..3475a6c 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp
@@ -15,88 +15,88 @@ using namespace Swift;
using namespace boost;
//...
class EchoBot {
- public:
- EchoBot(NetworkFactories* networkFactories) {
- //...
- client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
- client->setAlwaysTrustCertificates();
- client->onConnected.connect(bind(&EchoBot::handleConnected, this));
- client->onMessageReceived.connect(
- bind(&EchoBot::handleMessageReceived, this, _1));
- client->onPresenceReceived.connect(
- bind(&EchoBot::handlePresenceReceived, this, _1));
- tracer = new ClientXMLTracer(client);
- //...
- softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter());
- softwareVersionResponder->setVersion("EchoBot", "1.0");
- softwareVersionResponder->start();
- //...
- client->connect();
- //...
- }
+ public:
+ EchoBot(NetworkFactories* networkFactories) {
+ //...
+ client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onConnected.connect(bind(&EchoBot::handleConnected, this));
+ client->onMessageReceived.connect(
+ bind(&EchoBot::handleMessageReceived, this, _1));
+ client->onPresenceReceived.connect(
+ bind(&EchoBot::handlePresenceReceived, this, _1));
+ tracer = new ClientXMLTracer(client);
+ //...
+ softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter());
+ softwareVersionResponder->setVersion("EchoBot", "1.0");
+ softwareVersionResponder->start();
+ //...
+ client->connect();
+ //...
+ }
- ~EchoBot() {
- softwareVersionResponder->stop();
- delete softwareVersionResponder;
- //...
- delete tracer;
- delete client;
- //...
- }
- //...
-
- private:
- void handlePresenceReceived(Presence::ref presence) {
- // Automatically approve subscription requests
- if (presence->getType() == Presence::Subscribe) {
- Presence::ref response = Presence::create();
- response->setTo(presence->getFrom());
- response->setType(Presence::Subscribed);
- client->sendPresence(response);
- }
- }
+ ~EchoBot() {
+ softwareVersionResponder->stop();
+ delete softwareVersionResponder;
+ //...
+ delete tracer;
+ delete client;
+ //...
+ }
+ //...
- void handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ private:
+ void handlePresenceReceived(Presence::ref presence) {
+ // Automatically approve subscription requests
+ if (presence->getType() == Presence::Subscribe) {
+ Presence::ref response = Presence::create();
+ response->setTo(presence->getFrom());
+ response->setType(Presence::Subscribed);
+ client->sendPresence(response);
+ }
+ }
- void handleRosterReceived(ErrorPayload::ref error) {
- if (error) {
- std::cerr << "Error receiving roster. Continuing anyway.";
- }
- // Send initial available presence
- client->sendPresence(Presence::create("Send me a message"));
- }
-
- void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(JID());
- client->sendMessage(message);
- }
+ void handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- //...
- private:
- //...
- Client* client;
- ClientXMLTracer* tracer;
- //...
- SoftwareVersionResponder* softwareVersionResponder;
+ void handleRosterReceived(ErrorPayload::ref error) {
+ if (error) {
+ std::cerr << "Error receiving roster. Continuing anyway.";
+ }
+ // Send initial available presence
+ client->sendPresence(Presence::create("Send me a message"));
+ }
+
+ void handleMessageReceived(Message::ref message) {
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client->sendMessage(message);
+ }
+
+ //...
+ private:
+ //...
+ Client* client;
+ ClientXMLTracer* tracer;
+ //...
+ SoftwareVersionResponder* softwareVersionResponder;
};
//...
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- EchoBot bot(&networkFactories);
+ EchoBot bot(&networkFactories);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
//...
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp
index b3239c8..b1a1c37 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp
@@ -20,104 +20,104 @@ using namespace boost;
#include "EchoPayloadSerializer.h"
class EchoBot {
- public:
- EchoBot(NetworkFactories* networkFactories) {
- //...
- client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
- client->setAlwaysTrustCertificates();
- client->onConnected.connect(bind(&EchoBot::handleConnected, this));
- client->onMessageReceived.connect(
- bind(&EchoBot::handleMessageReceived, this, _1));
- client->onPresenceReceived.connect(
- bind(&EchoBot::handlePresenceReceived, this, _1));
- tracer = new ClientXMLTracer(client);
+ public:
+ EchoBot(NetworkFactories* networkFactories) {
+ //...
+ client = new Client("echobot@wonderland.lit", "mypass", networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onConnected.connect(bind(&EchoBot::handleConnected, this));
+ client->onMessageReceived.connect(
+ bind(&EchoBot::handleMessageReceived, this, _1));
+ client->onPresenceReceived.connect(
+ bind(&EchoBot::handlePresenceReceived, this, _1));
+ tracer = new ClientXMLTracer(client);
- softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter());
- softwareVersionResponder->setVersion("EchoBot", "1.0");
- softwareVersionResponder->start();
- //...
- client->addPayloadParserFactory(&echoPayloadParserFactory);
- client->addPayloadSerializer(&echoPayloadSerializer);
- //...
- client->connect();
- //...
- }
+ softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter());
+ softwareVersionResponder->setVersion("EchoBot", "1.0");
+ softwareVersionResponder->start();
+ //...
+ client->addPayloadParserFactory(&echoPayloadParserFactory);
+ client->addPayloadSerializer(&echoPayloadSerializer);
+ //...
+ client->connect();
+ //...
+ }
- ~EchoBot() {
- client->removePayloadSerializer(&echoPayloadSerializer);
- client->removePayloadParserFactory(&echoPayloadParserFactory);
- //...
- softwareVersionResponder->stop();
- delete softwareVersionResponder;
- delete tracer;
- delete client;
- //...
- }
- //...
-
- private:
- void handlePresenceReceived(Presence::ref presence) {
- // Automatically approve subscription requests
- if (presence->getType() == Presence::Subscribe) {
- Presence::ref response = Presence::create();
- response->setTo(presence->getFrom());
- response->setType(Presence::Subscribed);
- client->sendPresence(response);
- }
- }
+ ~EchoBot() {
+ client->removePayloadSerializer(&echoPayloadSerializer);
+ client->removePayloadParserFactory(&echoPayloadParserFactory);
+ //...
+ softwareVersionResponder->stop();
+ delete softwareVersionResponder;
+ delete tracer;
+ delete client;
+ //...
+ }
+ //...
- void handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ private:
+ void handlePresenceReceived(Presence::ref presence) {
+ // Automatically approve subscription requests
+ if (presence->getType() == Presence::Subscribe) {
+ Presence::ref response = Presence::create();
+ response->setTo(presence->getFrom());
+ response->setType(Presence::Subscribed);
+ client->sendPresence(response);
+ }
+ }
- void handleRosterReceived(ErrorPayload::ref error) {
- if (error) {
- std::cerr << "Error receiving roster. Continuing anyway.";
- }
- // Send initial available presence
- client->sendPresence(Presence::create("Send me a message"));
- }
+ void handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- //...
- void handleMessageReceived(Message::ref message) {
- //...
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(JID());
- //...
- if (!message->getPayload<EchoPayload>()) {
- boost::shared_ptr<EchoPayload> echoPayload = boost::make_shared<EchoPayload>();
- echoPayload->setMessage("This is an echoed message");
- message->addPayload(echoPayload);
- client->sendMessage(message);
- }
- }
- //...
+ void handleRosterReceived(ErrorPayload::ref error) {
+ if (error) {
+ std::cerr << "Error receiving roster. Continuing anyway.";
+ }
+ // Send initial available presence
+ client->sendPresence(Presence::create("Send me a message"));
+ }
- //...
- private:
- //...
- Client* client;
- ClientXMLTracer* tracer;
- SoftwareVersionResponder* softwareVersionResponder;
- //...
- EchoPayloadParserFactory echoPayloadParserFactory;
- EchoPayloadSerializer echoPayloadSerializer;
+ //...
+ void handleMessageReceived(Message::ref message) {
+ //...
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ //...
+ if (!message->getPayload<EchoPayload>()) {
+ boost::shared_ptr<EchoPayload> echoPayload = boost::make_shared<EchoPayload>();
+ echoPayload->setMessage("This is an echoed message");
+ message->addPayload(echoPayload);
+ client->sendMessage(message);
+ }
+ }
+ //...
+
+ //...
+ private:
+ //...
+ Client* client;
+ ClientXMLTracer* tracer;
+ SoftwareVersionResponder* softwareVersionResponder;
+ //...
+ EchoPayloadParserFactory echoPayloadParserFactory;
+ EchoPayloadSerializer echoPayloadSerializer;
};
//...
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- EchoBot bot(&networkFactories);
+ EchoBot bot(&networkFactories);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
//...
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp
index c827b94..16d7e4e 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp
@@ -14,56 +14,56 @@ using namespace Swift;
using namespace boost;
class EchoComponent {
- public:
- EchoComponent(NetworkFactories* networkFactories) : jid("echo.wonderland.lit") {
- component = new Component(jid, "EchoSecret", networkFactories);
- component->onConnected.connect(bind(&EchoComponent::handleConnected, this));
- component->onMessageReceived.connect(
- bind(&EchoComponent::handleMessageReceived, this, _1));
- component->onPresenceReceived.connect(
- bind(&EchoComponent::handlePresenceReceived, this, _1));
- tracer = new ComponentXMLTracer(component);
- component->connect("wonderland.lit", 5347);
- }
+ public:
+ EchoComponent(NetworkFactories* networkFactories) : jid("echo.wonderland.lit") {
+ component = new Component(jid, "EchoSecret", networkFactories);
+ component->onConnected.connect(bind(&EchoComponent::handleConnected, this));
+ component->onMessageReceived.connect(
+ bind(&EchoComponent::handleMessageReceived, this, _1));
+ component->onPresenceReceived.connect(
+ bind(&EchoComponent::handlePresenceReceived, this, _1));
+ tracer = new ComponentXMLTracer(component);
+ component->connect("wonderland.lit", 5347);
+ }
- ~EchoComponent() {
- delete tracer;
- delete component;
- }
-
- private:
- void handlePresenceReceived(Presence::ref presence) {
- // Automatically approve subscription requests
- if (presence->getType() == Presence::Subscribe) {
- Presence::ref response = Presence::create();
- response->setTo(presence->getFrom());
- response->setType(Presence::Subscribed);
- component->sendPresence(response);
- }
- }
+ ~EchoComponent() {
+ delete tracer;
+ delete component;
+ }
- void handleConnected() {
- }
+ private:
+ void handlePresenceReceived(Presence::ref presence) {
+ // Automatically approve subscription requests
+ if (presence->getType() == Presence::Subscribe) {
+ Presence::ref response = Presence::create();
+ response->setTo(presence->getFrom());
+ response->setType(Presence::Subscribed);
+ component->sendPresence(response);
+ }
+ }
- void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(jid);
- component->sendMessage(message);
- }
+ void handleConnected() {
+ }
- private:
- JID jid;
- Component* component;
- ComponentXMLTracer* tracer;
+ void handleMessageReceived(Message::ref message) {
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(jid);
+ component->sendMessage(message);
+ }
+
+ private:
+ JID jid;
+ Component* component;
+ ComponentXMLTracer* tracer;
};
int main(int, char**) {
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories(&eventLoop);
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories(&eventLoop);
- EchoComponent bot(&networkFactories);
+ EchoComponent bot(&networkFactories);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h
index c93b78b..1e5fc98 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h
@@ -10,17 +10,17 @@
//...
class EchoPayload : public Swift::Payload {
- public:
- EchoPayload() {}
+ public:
+ EchoPayload() {}
- const std::string& getMessage() const {
- return message;
- }
+ const std::string& getMessage() const {
+ return message;
+ }
- void setMessage(const std::string& message) {
- this->message = message;
- }
+ void setMessage(const std::string& message) {
+ this->message = message;
+ }
- private:
- std::string message;
+ private:
+ std::string message;
};
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h
index 9d66204..48d08bd 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h
@@ -10,32 +10,32 @@
#include "EchoPayload.h"
class EchoPayloadParser : public Swift::GenericPayloadParser<EchoPayload> {
- public:
- EchoPayloadParser() : currentDepth(0) {}
-
- void handleStartElement(
- const std::string& /* element */, const std::string& /* ns */, const AttributeMap&) {
- currentDepth++;
- }
-
- void handleEndElement(const std::string& /* element */, const std::string& /* ns */) {
- currentDepth--;
- if (currentDepth == 0) {
- getPayloadInternal()->setMessage(currentText);
- }
- }
-
- void handleCharacterData(const std::string& data) {
- currentText += data;
- }
-
- private:
- int currentDepth;
- std::string currentText;
+ public:
+ EchoPayloadParser() : currentDepth(0) {}
+
+ void handleStartElement(
+ const std::string& /* element */, const std::string& /* ns */, const AttributeMap&) {
+ currentDepth++;
+ }
+
+ void handleEndElement(const std::string& /* element */, const std::string& /* ns */) {
+ currentDepth--;
+ if (currentDepth == 0) {
+ getPayloadInternal()->setMessage(currentText);
+ }
+ }
+
+ void handleCharacterData(const std::string& data) {
+ currentText += data;
+ }
+
+ private:
+ int currentDepth;
+ std::string currentText;
};
class EchoPayloadParserFactory : public Swift::GenericPayloadParserFactory<EchoPayloadParser> {
- public:
- EchoPayloadParserFactory() :
- GenericPayloadParserFactory<EchoPayloadParser>("echo", "http://swift.im/echo") {}
+ public:
+ EchoPayloadParserFactory() :
+ GenericPayloadParserFactory<EchoPayloadParser>("echo", "http://swift.im/echo") {}
};
diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h
index abc4760..91440d0 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h
@@ -10,10 +10,10 @@
#include "EchoPayload.h"
class EchoPayloadSerializer : public Swift::GenericPayloadSerializer<EchoPayload> {
- public:
- std::string serializePayload(boost::shared_ptr<EchoPayload> payload) const {
- XMLElement element("echo", "http://swift.im/protocol/echo");
- element.addNode(XMLTextNode::ref(new XMLTextNode(payload->getMessage())));
- return element.serialize();
- }
+ public:
+ std::string serializePayload(boost::shared_ptr<EchoPayload> payload) const {
+ XMLElement element("echo", "http://swift.im/protocol/echo");
+ element.addNode(XMLTextNode::ref(new XMLTextNode(payload->getMessage())));
+ return element.serialize();
+ }
};
diff --git a/Limber/Server/ServerFromClientSession.cpp b/Limber/Server/ServerFromClientSession.cpp
index ab596a1..e8d0769 100644
--- a/Limber/Server/ServerFromClientSession.cpp
+++ b/Limber/Server/ServerFromClientSession.cpp
@@ -26,95 +26,95 @@
namespace Swift {
ServerFromClientSession::ServerFromClientSession(
- const std::string& id,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory,
- UserRegistry* userRegistry) :
- Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
- id_(id),
- userRegistry_(userRegistry),
- authenticated_(false),
- initialized(false),
- allowSASLEXTERNAL(false) {
+ const std::string& id,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ UserRegistry* userRegistry) :
+ Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
+ id_(id),
+ userRegistry_(userRegistry),
+ authenticated_(false),
+ initialized(false),
+ allowSASLEXTERNAL(false) {
}
void ServerFromClientSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- if (isInitialized()) {
- onElementReceived(element);
- }
- else {
- if (AuthRequest* authRequest = dynamic_cast<AuthRequest*>(element.get())) {
- if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) {
- if (authRequest->getMechanism() == "EXTERNAL") {
- getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
- authenticated_ = true;
- getXMPPLayer()->resetParser();
- }
- else {
- PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray(""));
- if (userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), plainMessage.getPassword())) {
- getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
- user_ = plainMessage.getAuthenticationID();
- authenticated_ = true;
- getXMPPLayer()->resetParser();
- }
- else {
- getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
- finishSession(AuthenticationFailedError);
- }
- }
- }
- else {
- getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
- finishSession(NoSupportedAuthMechanismsError);
- }
- }
- else if (IQ* iq = dynamic_cast<IQ*>(element.get())) {
- if (boost::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
- setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource()));
- boost::shared_ptr<ResourceBind> resultResourceBind(new ResourceBind());
- resultResourceBind->setJID(getRemoteJID());
- getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind));
- }
- else if (iq->getPayload<StartSession>()) {
- getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID()));
- setInitialized();
- }
- }
- }
+ if (isInitialized()) {
+ onElementReceived(element);
+ }
+ else {
+ if (AuthRequest* authRequest = dynamic_cast<AuthRequest*>(element.get())) {
+ if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) {
+ if (authRequest->getMechanism() == "EXTERNAL") {
+ getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
+ authenticated_ = true;
+ getXMPPLayer()->resetParser();
+ }
+ else {
+ PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray(""));
+ if (userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), plainMessage.getPassword())) {
+ getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
+ user_ = plainMessage.getAuthenticationID();
+ authenticated_ = true;
+ getXMPPLayer()->resetParser();
+ }
+ else {
+ getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
+ finishSession(AuthenticationFailedError);
+ }
+ }
+ }
+ else {
+ getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
+ finishSession(NoSupportedAuthMechanismsError);
+ }
+ }
+ else if (IQ* iq = dynamic_cast<IQ*>(element.get())) {
+ if (boost::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
+ setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource()));
+ boost::shared_ptr<ResourceBind> resultResourceBind(new ResourceBind());
+ resultResourceBind->setJID(getRemoteJID());
+ getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind));
+ }
+ else if (iq->getPayload<StartSession>()) {
+ getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID()));
+ setInitialized();
+ }
+ }
+ }
}
void ServerFromClientSession::handleStreamStart(const ProtocolHeader& incomingHeader) {
- setLocalJID(JID("", incomingHeader.getTo()));
- ProtocolHeader header;
- header.setFrom(incomingHeader.getTo());
- header.setID(id_);
- getXMPPLayer()->writeHeader(header);
+ setLocalJID(JID("", incomingHeader.getTo()));
+ ProtocolHeader header;
+ header.setFrom(incomingHeader.getTo());
+ header.setID(id_);
+ getXMPPLayer()->writeHeader(header);
- boost::shared_ptr<StreamFeatures> features(new StreamFeatures());
- if (!authenticated_) {
- features->addAuthenticationMechanism("PLAIN");
- if (allowSASLEXTERNAL) {
- features->addAuthenticationMechanism("EXTERNAL");
- }
- }
- else {
- features->setHasResourceBind();
- features->setHasSession();
- }
- getXMPPLayer()->writeElement(features);
+ boost::shared_ptr<StreamFeatures> features(new StreamFeatures());
+ if (!authenticated_) {
+ features->addAuthenticationMechanism("PLAIN");
+ if (allowSASLEXTERNAL) {
+ features->addAuthenticationMechanism("EXTERNAL");
+ }
+ }
+ else {
+ features->setHasResourceBind();
+ features->setHasSession();
+ }
+ getXMPPLayer()->writeElement(features);
}
void ServerFromClientSession::setInitialized() {
- initialized = true;
- onSessionStarted();
+ initialized = true;
+ onSessionStarted();
}
void ServerFromClientSession::setAllowSASLEXTERNAL() {
- allowSASLEXTERNAL = true;
+ allowSASLEXTERNAL = true;
}
}
diff --git a/Limber/Server/ServerFromClientSession.h b/Limber/Server/ServerFromClientSession.h
index 7d6907c..34d4f18 100644
--- a/Limber/Server/ServerFromClientSession.h
+++ b/Limber/Server/ServerFromClientSession.h
@@ -18,46 +18,46 @@
#include <Swiften/Session/Session.h>
namespace Swift {
- class ProtocolHeader;
- class ToplevelElement;
- class Stanza;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
- class StreamStack;
- class UserRegistry;
- class XMPPLayer;
- class ConnectionLayer;
- class Connection;
- class XMLParserFactory;
-
- class ServerFromClientSession : public Session {
- public:
- ServerFromClientSession(
- const std::string& id,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory,
- UserRegistry* userRegistry);
-
- boost::signal<void ()> onSessionStarted;
- void setAllowSASLEXTERNAL();
-
- private:
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamStart(const ProtocolHeader& header);
-
- void setInitialized();
- bool isInitialized() const {
- return initialized;
- }
-
- private:
- std::string id_;
- UserRegistry* userRegistry_;
- bool authenticated_;
- bool initialized;
- bool allowSASLEXTERNAL;
- std::string user_;
- };
+ class ProtocolHeader;
+ class ToplevelElement;
+ class Stanza;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+ class StreamStack;
+ class UserRegistry;
+ class XMPPLayer;
+ class ConnectionLayer;
+ class Connection;
+ class XMLParserFactory;
+
+ class ServerFromClientSession : public Session {
+ public:
+ ServerFromClientSession(
+ const std::string& id,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ UserRegistry* userRegistry);
+
+ boost::signal<void ()> onSessionStarted;
+ void setAllowSASLEXTERNAL();
+
+ private:
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader& header);
+
+ void setInitialized();
+ bool isInitialized() const {
+ return initialized;
+ }
+
+ private:
+ std::string id_;
+ UserRegistry* userRegistry_;
+ bool authenticated_;
+ bool initialized;
+ bool allowSASLEXTERNAL;
+ std::string user_;
+ };
}
diff --git a/Limber/Server/ServerSession.h b/Limber/Server/ServerSession.h
index 4296e16..9b784ac 100644
--- a/Limber/Server/ServerSession.h
+++ b/Limber/Server/ServerSession.h
@@ -11,13 +11,13 @@
#include <Swiften/Elements/Stanza.h>
namespace Swift {
- class ServerSession {
- public:
- virtual ~ServerSession();
+ class ServerSession {
+ public:
+ virtual ~ServerSession();
- virtual const JID& getJID() const = 0;
- virtual int getPriority() const = 0;
+ virtual const JID& getJID() const = 0;
+ virtual int getPriority() const = 0;
- virtual void sendStanza(boost::shared_ptr<Stanza>) = 0;
- };
+ virtual void sendStanza(boost::shared_ptr<Stanza>) = 0;
+ };
}
diff --git a/Limber/Server/ServerStanzaRouter.cpp b/Limber/Server/ServerStanzaRouter.cpp
index d0896a0..3ab88e1 100644
--- a/Limber/Server/ServerStanzaRouter.cpp
+++ b/Limber/Server/ServerStanzaRouter.cpp
@@ -16,61 +16,61 @@
namespace Swift {
namespace {
- struct PriorityLessThan {
- bool operator()(const ServerSession* s1, const ServerSession* s2) const {
- return s1->getPriority() < s2->getPriority();
- }
- };
+ struct PriorityLessThan {
+ bool operator()(const ServerSession* s1, const ServerSession* s2) const {
+ return s1->getPriority() < s2->getPriority();
+ }
+ };
- struct HasJID {
- HasJID(const JID& jid) : jid(jid) {}
- bool operator()(const ServerSession* session) const {
- return session->getJID().equals(jid, JID::WithResource);
- }
- JID jid;
- };
+ struct HasJID {
+ HasJID(const JID& jid) : jid(jid) {}
+ bool operator()(const ServerSession* session) const {
+ return session->getJID().equals(jid, JID::WithResource);
+ }
+ JID jid;
+ };
}
ServerStanzaRouter::ServerStanzaRouter() {
}
bool ServerStanzaRouter::routeStanza(boost::shared_ptr<Stanza> stanza) {
- JID to = stanza->getTo();
- assert(to.isValid());
+ JID to = stanza->getTo();
+ assert(to.isValid());
- // For a full JID, first try to route to a session with the full JID
- if (!to.isBare()) {
- std::vector<ServerSession*>::const_iterator i = std::find_if(clientSessions_.begin(), clientSessions_.end(), HasJID(to));
- if (i != clientSessions_.end()) {
- (*i)->sendStanza(stanza);
- return true;
- }
- }
+ // For a full JID, first try to route to a session with the full JID
+ if (!to.isBare()) {
+ std::vector<ServerSession*>::const_iterator i = std::find_if(clientSessions_.begin(), clientSessions_.end(), HasJID(to));
+ if (i != clientSessions_.end()) {
+ (*i)->sendStanza(stanza);
+ return true;
+ }
+ }
- // Look for candidate sessions
- to = to.toBare();
- std::vector<ServerSession*> candidateSessions;
- for (std::vector<ServerSession*>::const_iterator i = clientSessions_.begin(); i != clientSessions_.end(); ++i) {
- if ((*i)->getJID().equals(to, JID::WithoutResource) && (*i)->getPriority() >= 0) {
- candidateSessions.push_back(*i);
- }
- }
- if (candidateSessions.empty()) {
- return false;
- }
+ // Look for candidate sessions
+ to = to.toBare();
+ std::vector<ServerSession*> candidateSessions;
+ for (std::vector<ServerSession*>::const_iterator i = clientSessions_.begin(); i != clientSessions_.end(); ++i) {
+ if ((*i)->getJID().equals(to, JID::WithoutResource) && (*i)->getPriority() >= 0) {
+ candidateSessions.push_back(*i);
+ }
+ }
+ if (candidateSessions.empty()) {
+ return false;
+ }
- // Find the session with the highest priority
- std::vector<ServerSession*>::const_iterator i = std::max_element(clientSessions_.begin(), clientSessions_.end(), PriorityLessThan());
- (*i)->sendStanza(stanza);
- return true;
+ // Find the session with the highest priority
+ std::vector<ServerSession*>::const_iterator i = std::max_element(clientSessions_.begin(), clientSessions_.end(), PriorityLessThan());
+ (*i)->sendStanza(stanza);
+ return true;
}
void ServerStanzaRouter::addClientSession(ServerSession* clientSession) {
- clientSessions_.push_back(clientSession);
+ clientSessions_.push_back(clientSession);
}
void ServerStanzaRouter::removeClientSession(ServerSession* clientSession) {
- erase(clientSessions_, clientSession);
+ erase(clientSessions_, clientSession);
}
}
diff --git a/Limber/Server/ServerStanzaRouter.h b/Limber/Server/ServerStanzaRouter.h
index a9cc494..174f509 100644
--- a/Limber/Server/ServerStanzaRouter.h
+++ b/Limber/Server/ServerStanzaRouter.h
@@ -14,18 +14,18 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class ServerSession;
+ class ServerSession;
- class ServerStanzaRouter {
- public:
- ServerStanzaRouter();
+ class ServerStanzaRouter {
+ public:
+ ServerStanzaRouter();
- bool routeStanza(boost::shared_ptr<Stanza>);
+ bool routeStanza(boost::shared_ptr<Stanza>);
- void addClientSession(ServerSession*);
- void removeClientSession(ServerSession*);
+ void addClientSession(ServerSession*);
+ void removeClientSession(ServerSession*);
- private:
- std::vector<ServerSession*> clientSessions_;
- };
+ private:
+ std::vector<ServerSession*> clientSessions_;
+ };
}
diff --git a/Limber/Server/SimpleUserRegistry.cpp b/Limber/Server/SimpleUserRegistry.cpp
index dd6c112..4f39030 100644
--- a/Limber/Server/SimpleUserRegistry.cpp
+++ b/Limber/Server/SimpleUserRegistry.cpp
@@ -12,12 +12,12 @@ SimpleUserRegistry::SimpleUserRegistry() {
}
bool SimpleUserRegistry::isValidUserPassword(const JID& user, const SafeByteArray& password) const {
- std::map<JID,SafeByteArray>::const_iterator i = users.find(user);
- return i != users.end() ? i->second == password : false;
+ std::map<JID,SafeByteArray>::const_iterator i = users.find(user);
+ return i != users.end() ? i->second == password : false;
}
void SimpleUserRegistry::addUser(const JID& user, const std::string& password) {
- users.insert(std::make_pair(user, createSafeByteArray(password)));
+ users.insert(std::make_pair(user, createSafeByteArray(password)));
}
}
diff --git a/Limber/Server/SimpleUserRegistry.h b/Limber/Server/SimpleUserRegistry.h
index 8287a14..9963b2c 100644
--- a/Limber/Server/SimpleUserRegistry.h
+++ b/Limber/Server/SimpleUserRegistry.h
@@ -14,16 +14,16 @@
#include <Limber/Server/UserRegistry.h>
namespace Swift {
-
- class SimpleUserRegistry : public UserRegistry {
- public:
- SimpleUserRegistry();
- virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const;
- void addUser(const JID& user, const std::string& password);
+ class SimpleUserRegistry : public UserRegistry {
+ public:
+ SimpleUserRegistry();
- private:
- std::map<JID, SafeByteArray> users;
- };
+ virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const;
+ void addUser(const JID& user, const std::string& password);
+
+ private:
+ std::map<JID, SafeByteArray> users;
+ };
}
diff --git a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
index 2e7293b..a234038 100644
--- a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
+++ b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
@@ -15,137 +15,137 @@
using namespace Swift;
class ServerStanzaRouterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ServerStanzaRouterTest);
- CPPUNIT_TEST(testRouteStanza_FullJID);
- CPPUNIT_TEST(testRouteStanza_FullJIDWithNegativePriority);
- CPPUNIT_TEST(testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession);
- CPPUNIT_TEST(testRouteStanza_BareJIDWithoutMatchingSession);
- CPPUNIT_TEST(testRouteStanza_BareJIDWithMultipleSessions);
- CPPUNIT_TEST(testRouteStanza_BareJIDWithOnlyNegativePriorities);
- CPPUNIT_TEST(testRouteStanza_BareJIDWithChangingPresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- ServerStanzaRouterTest() {}
-
- void setUp() {
- }
-
- void tearDown() {
- }
-
- void testRouteStanza_FullJID() {
- ServerStanzaRouter testling;
- MockServerSession session1(JID("foo@bar.com/Bla"), 0);
- testling.addClientSession(&session1);
- MockServerSession session2(JID("foo@bar.com/Baz"), 0);
- testling.addClientSession(&session2);
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz"));
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
- }
-
- void testRouteStanza_FullJIDWithNegativePriority() {
- ServerStanzaRouter testling;
- MockServerSession session1(JID("foo@bar.com/Bla"), -1);
- testling.addClientSession(&session1);
- MockServerSession session2(JID("foo@bar.com/Baz"), 0);
- testling.addClientSession(&session2);
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com/Bla"));
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session1.sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session2.sentStanzas.size()));
- }
-
- void testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession() {
- ServerStanzaRouter testling;
- MockServerSession session(JID("foo@bar.com/Bla"), 0);
- testling.addClientSession(&session);
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz"));
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session.sentStanzas.size()));
- }
-
- void testRouteStanza_BareJIDWithoutMatchingSession() {
- ServerStanzaRouter testling;
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
-
- CPPUNIT_ASSERT(!result);
- }
-
- void testRouteStanza_BareJIDWithMultipleSessions() {
- ServerStanzaRouter testling;
- MockServerSession session1(JID("foo@bar.com/Bla"), 1);
- testling.addClientSession(&session1);
- MockServerSession session2(JID("foo@bar.com/Baz"), 8);
- testling.addClientSession(&session2);
- MockServerSession session3(JID("foo@bar.com/Bar"), 5);
- testling.addClientSession(&session3);
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session3.sentStanzas.size()));
- }
-
- void testRouteStanza_BareJIDWithOnlyNegativePriorities() {
- ServerStanzaRouter testling;
- MockServerSession session(JID("foo@bar.com/Bla"), -1);
- testling.addClientSession(&session);
-
- bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
-
- CPPUNIT_ASSERT(!result);
- }
-
- void testRouteStanza_BareJIDWithChangingPresence() {
- ServerStanzaRouter testling;
- MockServerSession session1(JID("foo@bar.com/Baz"), 8);
- testling.addClientSession(&session1);
- MockServerSession session2(JID("foo@bar.com/Bar"), 5);
- testling.addClientSession(&session2);
-
- session1.priority = 3;
- session2.priority = 4;
- bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
- }
-
- private:
- boost::shared_ptr<Message> createMessageTo(const std::string& recipient) {
- boost::shared_ptr<Message> message(new Message());
- message->setTo(JID(recipient));
- return message;
- }
-
- class MockServerSession : public ServerSession {
- public:
- MockServerSession(const JID& jid, int priority) : jid(jid), priority(priority) {}
-
- virtual const JID& getJID() const { return jid; }
- virtual int getPriority() const { return priority; }
-
- virtual void sendStanza(boost::shared_ptr<Stanza> stanza) {
- sentStanzas.push_back(stanza);
- }
-
- JID jid;
- int priority;
- std::vector< boost::shared_ptr<Stanza> > sentStanzas;
- };
+ CPPUNIT_TEST_SUITE(ServerStanzaRouterTest);
+ CPPUNIT_TEST(testRouteStanza_FullJID);
+ CPPUNIT_TEST(testRouteStanza_FullJIDWithNegativePriority);
+ CPPUNIT_TEST(testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession);
+ CPPUNIT_TEST(testRouteStanza_BareJIDWithoutMatchingSession);
+ CPPUNIT_TEST(testRouteStanza_BareJIDWithMultipleSessions);
+ CPPUNIT_TEST(testRouteStanza_BareJIDWithOnlyNegativePriorities);
+ CPPUNIT_TEST(testRouteStanza_BareJIDWithChangingPresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ ServerStanzaRouterTest() {}
+
+ void setUp() {
+ }
+
+ void tearDown() {
+ }
+
+ void testRouteStanza_FullJID() {
+ ServerStanzaRouter testling;
+ MockServerSession session1(JID("foo@bar.com/Bla"), 0);
+ testling.addClientSession(&session1);
+ MockServerSession session2(JID("foo@bar.com/Baz"), 0);
+ testling.addClientSession(&session2);
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz"));
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
+ }
+
+ void testRouteStanza_FullJIDWithNegativePriority() {
+ ServerStanzaRouter testling;
+ MockServerSession session1(JID("foo@bar.com/Bla"), -1);
+ testling.addClientSession(&session1);
+ MockServerSession session2(JID("foo@bar.com/Baz"), 0);
+ testling.addClientSession(&session2);
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com/Bla"));
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session1.sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session2.sentStanzas.size()));
+ }
+
+ void testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession() {
+ ServerStanzaRouter testling;
+ MockServerSession session(JID("foo@bar.com/Bla"), 0);
+ testling.addClientSession(&session);
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz"));
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session.sentStanzas.size()));
+ }
+
+ void testRouteStanza_BareJIDWithoutMatchingSession() {
+ ServerStanzaRouter testling;
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
+
+ CPPUNIT_ASSERT(!result);
+ }
+
+ void testRouteStanza_BareJIDWithMultipleSessions() {
+ ServerStanzaRouter testling;
+ MockServerSession session1(JID("foo@bar.com/Bla"), 1);
+ testling.addClientSession(&session1);
+ MockServerSession session2(JID("foo@bar.com/Baz"), 8);
+ testling.addClientSession(&session2);
+ MockServerSession session3(JID("foo@bar.com/Bar"), 5);
+ testling.addClientSession(&session3);
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session3.sentStanzas.size()));
+ }
+
+ void testRouteStanza_BareJIDWithOnlyNegativePriorities() {
+ ServerStanzaRouter testling;
+ MockServerSession session(JID("foo@bar.com/Bla"), -1);
+ testling.addClientSession(&session);
+
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
+
+ CPPUNIT_ASSERT(!result);
+ }
+
+ void testRouteStanza_BareJIDWithChangingPresence() {
+ ServerStanzaRouter testling;
+ MockServerSession session1(JID("foo@bar.com/Baz"), 8);
+ testling.addClientSession(&session1);
+ MockServerSession session2(JID("foo@bar.com/Bar"), 5);
+ testling.addClientSession(&session2);
+
+ session1.priority = 3;
+ session2.priority = 4;
+ bool result = testling.routeStanza(createMessageTo("foo@bar.com"));
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(session1.sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(session2.sentStanzas.size()));
+ }
+
+ private:
+ boost::shared_ptr<Message> createMessageTo(const std::string& recipient) {
+ boost::shared_ptr<Message> message(new Message());
+ message->setTo(JID(recipient));
+ return message;
+ }
+
+ class MockServerSession : public ServerSession {
+ public:
+ MockServerSession(const JID& jid, int priority) : jid(jid), priority(priority) {}
+
+ virtual const JID& getJID() const { return jid; }
+ virtual int getPriority() const { return priority; }
+
+ virtual void sendStanza(boost::shared_ptr<Stanza> stanza) {
+ sentStanzas.push_back(stanza);
+ }
+
+ JID jid;
+ int priority;
+ std::vector< boost::shared_ptr<Stanza> > sentStanzas;
+ };
};
CPPUNIT_TEST_SUITE_REGISTRATION(ServerStanzaRouterTest);
diff --git a/Limber/Server/UserRegistry.h b/Limber/Server/UserRegistry.h
index 812b218..98b3e99 100644
--- a/Limber/Server/UserRegistry.h
+++ b/Limber/Server/UserRegistry.h
@@ -11,12 +11,12 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class JID;
+ class JID;
- class UserRegistry {
- public:
- virtual ~UserRegistry();
+ class UserRegistry {
+ public:
+ virtual ~UserRegistry();
- virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const = 0;
- };
+ virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const = 0;
+ };
}
diff --git a/Limber/main.cpp b/Limber/main.cpp
index e4bac77..52f9347 100644
--- a/Limber/main.cpp
+++ b/Limber/main.cpp
@@ -31,76 +31,76 @@
using namespace Swift;
class Server {
- public:
- Server(UserRegistry* userRegistry, EventLoop* eventLoop) : userRegistry_(userRegistry) {
- serverFromClientConnectionServer_ = BoostConnectionServer::create(5222, boostIOServiceThread_.getIOService(), eventLoop);
- serverFromClientConnectionServer_->onNewConnection.connect(boost::bind(&Server::handleNewConnection, this, _1));
- serverFromClientConnectionServer_->start();
- }
+ public:
+ Server(UserRegistry* userRegistry, EventLoop* eventLoop) : userRegistry_(userRegistry) {
+ serverFromClientConnectionServer_ = BoostConnectionServer::create(5222, boostIOServiceThread_.getIOService(), eventLoop);
+ serverFromClientConnectionServer_->onNewConnection.connect(boost::bind(&Server::handleNewConnection, this, _1));
+ serverFromClientConnectionServer_->start();
+ }
- private:
- void handleNewConnection(boost::shared_ptr<Connection> c) {
- boost::shared_ptr<ServerFromClientSession> session(new ServerFromClientSession(idGenerator_.generateID(), c, &payloadParserFactories_, &payloadSerializers_, &xmlParserFactory, userRegistry_));
- serverFromClientSessions_.push_back(session);
- session->onElementReceived.connect(boost::bind(&Server::handleElementReceived, this, _1, session));
- session->onSessionFinished.connect(boost::bind(&Server::handleSessionFinished, this, session));
- session->startSession();
- }
+ private:
+ void handleNewConnection(boost::shared_ptr<Connection> c) {
+ boost::shared_ptr<ServerFromClientSession> session(new ServerFromClientSession(idGenerator_.generateID(), c, &payloadParserFactories_, &payloadSerializers_, &xmlParserFactory, userRegistry_));
+ serverFromClientSessions_.push_back(session);
+ session->onElementReceived.connect(boost::bind(&Server::handleElementReceived, this, _1, session));
+ session->onSessionFinished.connect(boost::bind(&Server::handleSessionFinished, this, session));
+ session->startSession();
+ }
- void handleSessionFinished(boost::shared_ptr<ServerFromClientSession> session) {
- serverFromClientSessions_.erase(std::remove(serverFromClientSessions_.begin(), serverFromClientSessions_.end(), session), serverFromClientSessions_.end());
- }
+ void handleSessionFinished(boost::shared_ptr<ServerFromClientSession> session) {
+ serverFromClientSessions_.erase(std::remove(serverFromClientSessions_.begin(), serverFromClientSessions_.end(), session), serverFromClientSessions_.end());
+ }
- void handleElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<ServerFromClientSession> session) {
- boost::shared_ptr<Stanza> stanza(boost::dynamic_pointer_cast<Stanza>(element));
- if (!stanza) {
- return;
- }
- stanza->setFrom(session->getRemoteJID());
- if (!stanza->getTo().isValid()) {
- stanza->setTo(JID(session->getLocalJID()));
- }
- if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) {
- if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza)) {
- if (iq->getPayload<RosterPayload>()) {
- session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::make_shared<RosterPayload>()));
- }
- if (iq->getPayload<VCard>()) {
- if (iq->getType() == IQ::Get) {
- boost::shared_ptr<VCard> vcard(new VCard());
- vcard->setNickname(iq->getFrom().getNode());
- session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vcard));
- }
- else {
- session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
- }
- }
- else {
- session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
- }
- }
- }
- }
+ void handleElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<ServerFromClientSession> session) {
+ boost::shared_ptr<Stanza> stanza(boost::dynamic_pointer_cast<Stanza>(element));
+ if (!stanza) {
+ return;
+ }
+ stanza->setFrom(session->getRemoteJID());
+ if (!stanza->getTo().isValid()) {
+ stanza->setTo(JID(session->getLocalJID()));
+ }
+ if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) {
+ if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza)) {
+ if (iq->getPayload<RosterPayload>()) {
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::make_shared<RosterPayload>()));
+ }
+ if (iq->getPayload<VCard>()) {
+ if (iq->getType() == IQ::Get) {
+ boost::shared_ptr<VCard> vcard(new VCard());
+ vcard->setNickname(iq->getFrom().getNode());
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vcard));
+ }
+ else {
+ session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
+ }
+ }
+ else {
+ session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
+ }
+ }
+ }
+ }
- private:
- IDGenerator idGenerator_;
- PlatformXMLParserFactory xmlParserFactory;
- UserRegistry* userRegistry_;
- BoostIOServiceThread boostIOServiceThread_;
- boost::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer_;
- std::vector< boost::shared_ptr<ServerFromClientSession> > serverFromClientSessions_;
- FullPayloadParserFactoryCollection payloadParserFactories_;
- FullPayloadSerializerCollection payloadSerializers_;
+ private:
+ IDGenerator idGenerator_;
+ PlatformXMLParserFactory xmlParserFactory;
+ UserRegistry* userRegistry_;
+ BoostIOServiceThread boostIOServiceThread_;
+ boost::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer_;
+ std::vector< boost::shared_ptr<ServerFromClientSession> > serverFromClientSessions_;
+ FullPayloadParserFactoryCollection payloadParserFactories_;
+ FullPayloadSerializerCollection payloadSerializers_;
};
int main() {
- SimpleEventLoop eventLoop;
- SimpleUserRegistry userRegistry;
- userRegistry.addUser(JID("remko@localhost"), "remko");
- userRegistry.addUser(JID("kevin@localhost"), "kevin");
- userRegistry.addUser(JID("remko@limber.swift.im"), "remko");
- userRegistry.addUser(JID("kevin@limber.swift.im"), "kevin");
- Server server(&userRegistry, &eventLoop);
- eventLoop.run();
- return 0;
+ SimpleEventLoop eventLoop;
+ SimpleUserRegistry userRegistry;
+ userRegistry.addUser(JID("remko@localhost"), "remko");
+ userRegistry.addUser(JID("kevin@localhost"), "kevin");
+ userRegistry.addUser(JID("remko@limber.swift.im"), "remko");
+ userRegistry.addUser(JID("kevin@limber.swift.im"), "kevin");
+ Server server(&userRegistry, &eventLoop);
+ eventLoop.run();
+ return 0;
}
diff --git a/QA/Checker/IO.cpp b/QA/Checker/IO.cpp
index ad9f877..d8fcc96 100644
--- a/QA/Checker/IO.cpp
+++ b/QA/Checker/IO.cpp
@@ -10,56 +10,56 @@
#include <iostream>
std::ostream& operator<<(std::ostream& os, const Swift::ByteArray& s) {
- std::ios::fmtflags oldFlags = os.flags();
- os << std::hex;
- for (Swift::ByteArray::const_iterator i = s.begin(); i != s.end(); ++i) {
- if (*i >= 32 && *i < 127) {
- os << *i;
- }
- else {
- os << "\\x" << static_cast<unsigned int>(static_cast<unsigned char>(*i));
- }
- }
- os << std::endl;
- os.flags(oldFlags);
- return os;
+ std::ios::fmtflags oldFlags = os.flags();
+ os << std::hex;
+ for (Swift::ByteArray::const_iterator i = s.begin(); i != s.end(); ++i) {
+ if (*i >= 32 && *i < 127) {
+ os << *i;
+ }
+ else {
+ os << "\\x" << static_cast<unsigned int>(static_cast<unsigned char>(*i));
+ }
+ }
+ os << std::endl;
+ os.flags(oldFlags);
+ return os;
}
std::ostream& operator<<(std::ostream& os, const Swift::SafeByteArray& s) {
- std::ios::fmtflags oldFlags = os.flags();
- os << std::hex;
- for (Swift::SafeByteArray::const_iterator i = s.begin(); i != s.end(); ++i) {
- if (*i >= 32 && *i < 127) {
- os << *i;
- }
- else {
- os << "\\x" << static_cast<unsigned int>(static_cast<unsigned char>(*i));
- }
- }
- os << std::endl;
- os.flags(oldFlags);
- return os;
+ std::ios::fmtflags oldFlags = os.flags();
+ os << std::hex;
+ for (Swift::SafeByteArray::const_iterator i = s.begin(); i != s.end(); ++i) {
+ if (*i >= 32 && *i < 127) {
+ os << *i;
+ }
+ else {
+ os << "\\x" << static_cast<unsigned int>(static_cast<unsigned char>(*i));
+ }
+ }
+ os << std::endl;
+ os.flags(oldFlags);
+ return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<int>& s) {
- for (std::vector<int>::const_iterator i = s.begin(); i != s.end(); ++i) {
- os << *i << " ";
- }
- os << std::endl;
- return os;
+ for (std::vector<int>::const_iterator i = s.begin(); i != s.end(); ++i) {
+ os << *i << " ";
+ }
+ os << std::endl;
+ return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<size_t>& s) {
- for (std::vector<size_t>::const_iterator i = s.begin(); i != s.end(); ++i) {
- os << *i << " ";
- }
- os << std::endl;
- return os;
+ for (std::vector<size_t>::const_iterator i = s.begin(); i != s.end(); ++i) {
+ os << *i << " ";
+ }
+ os << std::endl;
+ return os;
}
bool operator==(const Swift::ByteArray& a, const Swift::ByteArray& b) {
- if (a.size() != b.size()) {
- return false;
- }
- return std::equal(a.begin(), a.end(), b.begin());
+ if (a.size() != b.size()) {
+ return false;
+ }
+ return std::equal(a.begin(), a.end(), b.begin());
}
diff --git a/QA/Checker/checker.cpp b/QA/Checker/checker.cpp
index 9cae75a..f1186cc 100644
--- a/QA/Checker/checker.cpp
+++ b/QA/Checker/checker.cpp
@@ -17,71 +17,71 @@
#include <Swiften/Base/Log.h>
int main(int argc, char* argv[]) {
- bool verbose = false;
- bool outputXML = false;
+ bool verbose = false;
+ bool outputXML = false;
- Swift::Log::setLogLevel(Swift::Log::error);
+ Swift::Log::setLogLevel(Swift::Log::error);
- // Parse parameters
- std::vector<std::string> testsToRun;
- for (int i = 1; i < argc; ++i) {
- std::string param(argv[i]);
- if (param == "--verbose") {
- verbose = true;
- }
- else if (param == "--xml") {
- outputXML = true;
- }
- else if (param == "--debug") {
- Swift::Log::setLogLevel(Swift::Log::debug);
- }
- else {
- testsToRun.push_back(param);
- }
- }
- if (testsToRun.empty()) {
- testsToRun.push_back("");
- }
+ // Parse parameters
+ std::vector<std::string> testsToRun;
+ for (int i = 1; i < argc; ++i) {
+ std::string param(argv[i]);
+ if (param == "--verbose") {
+ verbose = true;
+ }
+ else if (param == "--xml") {
+ outputXML = true;
+ }
+ else if (param == "--debug") {
+ Swift::Log::setLogLevel(Swift::Log::debug);
+ }
+ else {
+ testsToRun.push_back(param);
+ }
+ }
+ if (testsToRun.empty()) {
+ testsToRun.push_back("");
+ }
- // Set up the listeners
- CppUnit::TestResult controller;
+ // Set up the listeners
+ CppUnit::TestResult controller;
- CppUnit::TestResultCollector result;
- controller.addListener(&result);
+ CppUnit::TestResultCollector result;
+ controller.addListener(&result);
- CppUnit::TextTestProgressListener progressListener;
- CppUnit::BriefTestProgressListener verboseListener;
- if (!outputXML) {
- if (verbose) {
- controller.addListener(&verboseListener);
- }
- else {
- controller.addListener(&progressListener);
- }
- }
+ CppUnit::TextTestProgressListener progressListener;
+ CppUnit::BriefTestProgressListener verboseListener;
+ if (!outputXML) {
+ if (verbose) {
+ controller.addListener(&verboseListener);
+ }
+ else {
+ controller.addListener(&progressListener);
+ }
+ }
- // Run the tests
- CppUnit::TestRunner runner;
- runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
- for (std::vector<std::string>::const_iterator i = testsToRun.begin(); i != testsToRun.end(); ++i) {
- try {
- runner.run(controller, *i);
- }
- catch (const std::exception& e) {
- std::cerr << "Error: " << e.what() << std::endl;
- return -1;
- }
- }
+ // Run the tests
+ CppUnit::TestRunner runner;
+ runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
+ for (std::vector<std::string>::const_iterator i = testsToRun.begin(); i != testsToRun.end(); ++i) {
+ try {
+ runner.run(controller, *i);
+ }
+ catch (const std::exception& e) {
+ std::cerr << "Error: " << e.what() << std::endl;
+ return -1;
+ }
+ }
- // Output the results
- if (outputXML) {
- CppUnit::XmlOutputter outputter(&result, std::cout);
- outputter.write();
- }
- else {
- CppUnit::TextOutputter outputter(&result, std::cerr);
- outputter.write();
- }
+ // Output the results
+ if (outputXML) {
+ CppUnit::XmlOutputter outputter(&result, std::cout);
+ outputter.write();
+ }
+ else {
+ CppUnit::TextOutputter outputter(&result, std::cerr);
+ outputter.write();
+ }
- return result.wasSuccessful() ? 0 : 1;
+ return result.wasSuccessful() ? 0 : 1;
}
diff --git a/QA/UnitTest/template/FooTest.cpp b/QA/UnitTest/template/FooTest.cpp
index 854c24a..adddb5b 100644
--- a/QA/UnitTest/template/FooTest.cpp
+++ b/QA/UnitTest/template/FooTest.cpp
@@ -10,19 +10,19 @@
using namespace Swift;
class FooTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FooTest);
- CPPUNIT_TEST(testBar);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(FooTest);
+ CPPUNIT_TEST(testBar);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- }
+ public:
+ void setUp() {
+ }
- void tearDown() {
- }
+ void tearDown() {
+ }
- void testBar() {
- }
+ void testBar() {
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(FooTest);
diff --git a/Slimber/CLI/DummyMenulet.h b/Slimber/CLI/DummyMenulet.h
index 22d4b36..4b37df6 100644
--- a/Slimber/CLI/DummyMenulet.h
+++ b/Slimber/CLI/DummyMenulet.h
@@ -9,28 +9,28 @@
#include <Slimber/Menulet.h>
class DummyMenulet : public Menulet {
- public:
- DummyMenulet() {
- }
+ public:
+ DummyMenulet() {
+ }
- void clear() {
- }
+ void clear() {
+ }
- void addItem(const std::string&, const std::string&) {
- }
+ void addItem(const std::string&, const std::string&) {
+ }
- void addAboutItem() {
- }
+ void addAboutItem() {
+ }
- void addRestartItem() {
- }
+ void addRestartItem() {
+ }
- void addExitItem() {
- }
+ void addExitItem() {
+ }
- void addSeparator() {
- }
+ void addSeparator() {
+ }
- void setIcon(const std::string&) {
- }
+ void setIcon(const std::string&) {
+ }
};
diff --git a/Slimber/CLI/main.cpp b/Slimber/CLI/main.cpp
index 9084a60..26f88d0 100644
--- a/Slimber/CLI/main.cpp
+++ b/Slimber/CLI/main.cpp
@@ -12,11 +12,11 @@
using namespace Swift;
int main() {
- SimpleEventLoop eventLoop;
-
- DummyMenulet menulet;
- MainController controller(&menulet, &eventLoop);
+ SimpleEventLoop eventLoop;
- eventLoop.run();
- return 0;
+ DummyMenulet menulet;
+ MainController controller(&menulet, &eventLoop);
+
+ eventLoop.run();
+ return 0;
}
diff --git a/Slimber/Cocoa/CocoaController.mm b/Slimber/Cocoa/CocoaController.mm
index 1d2ef5c..7d17948 100644
--- a/Slimber/Cocoa/CocoaController.mm
+++ b/Slimber/Cocoa/CocoaController.mm
@@ -11,19 +11,19 @@
#include <Slimber/MainController.h>
@implementation CocoaController {
- CocoaMenulet* menulet;
- MainController* main;
+ CocoaMenulet* menulet;
+ MainController* main;
}
- (void) dealloc {
- delete main;
- delete menulet;
- [super dealloc];
+ delete main;
+ delete menulet;
+ [super dealloc];
}
- (void) awakeFromNib {
- menulet = new CocoaMenulet();
- main = new MainController(menulet, eventLoop);
+ menulet = new CocoaMenulet();
+ main = new MainController(menulet, eventLoop);
}
@end
diff --git a/Slimber/Cocoa/CocoaMenulet.h b/Slimber/Cocoa/CocoaMenulet.h
index c31f15c..0dc06f5 100644
--- a/Slimber/Cocoa/CocoaMenulet.h
+++ b/Slimber/Cocoa/CocoaMenulet.h
@@ -13,21 +13,21 @@
#include <SwifTools/Cocoa/CocoaAction.h>
class CocoaMenulet : public Menulet {
- public:
- CocoaMenulet();
- virtual ~CocoaMenulet();
-
- private:
- virtual void clear();
- virtual void addItem(const std::string& name, const std::string& icon);
- virtual void addSeparator();
- void setIcon(const std::string& icon);
- virtual void addAboutItem();
- virtual void addRestartItem();
- virtual void addExitItem();
-
- private:
- NSStatusItem* statusItem;
- NSMenu* menu;
- CocoaAction* restartAction;
+ public:
+ CocoaMenulet();
+ virtual ~CocoaMenulet();
+
+ private:
+ virtual void clear();
+ virtual void addItem(const std::string& name, const std::string& icon);
+ virtual void addSeparator();
+ void setIcon(const std::string& icon);
+ virtual void addAboutItem();
+ virtual void addRestartItem();
+ virtual void addExitItem();
+
+ private:
+ NSStatusItem* statusItem;
+ NSMenu* menu;
+ CocoaAction* restartAction;
};
diff --git a/Slimber/Cocoa/CocoaMenulet.mm b/Slimber/Cocoa/CocoaMenulet.mm
index f62da80..98042d7 100644
--- a/Slimber/Cocoa/CocoaMenulet.mm
+++ b/Slimber/Cocoa/CocoaMenulet.mm
@@ -11,72 +11,72 @@
#include <SwifTools/Cocoa/CocoaUtil.h>
CocoaMenulet::CocoaMenulet() {
- restartAction = [[CocoaAction alloc] initWithFunction:
- new boost::function<void()>(boost::ref(onRestartClicked))];
- menu = [[NSMenu alloc] init];
+ restartAction = [[CocoaAction alloc] initWithFunction:
+ new boost::function<void()>(boost::ref(onRestartClicked))];
+ menu = [[NSMenu alloc] init];
- statusItem = [[[NSStatusBar systemStatusBar]
- statusItemWithLength: NSVariableStatusItemLength] retain];
- [statusItem setHighlightMode: YES];
- [statusItem setEnabled: YES];
- [statusItem setToolTip: @"Slimber"];
- [statusItem setMenu: menu];
+ statusItem = [[[NSStatusBar systemStatusBar]
+ statusItemWithLength: NSVariableStatusItemLength] retain];
+ [statusItem setHighlightMode: YES];
+ [statusItem setEnabled: YES];
+ [statusItem setToolTip: @"Slimber"];
+ [statusItem setMenu: menu];
}
CocoaMenulet::~CocoaMenulet() {
- [statusItem release];
- [menu release];
- [restartAction release];
+ [statusItem release];
+ [menu release];
+ [restartAction release];
}
void CocoaMenulet::setIcon(const std::string& icon) {
- NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"];
- NSImage* image = [[NSImage alloc] initWithContentsOfFile: path];
- [statusItem setImage: image];
- [image release];
+ NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"];
+ NSImage* image = [[NSImage alloc] initWithContentsOfFile: path];
+ [statusItem setImage: image];
+ [image release];
}
void CocoaMenulet::clear() {
- while ([menu numberOfItems] > 0) {
- [menu removeItemAtIndex: 0];
- }
+ while ([menu numberOfItems] > 0) {
+ [menu removeItemAtIndex: 0];
+ }
}
void CocoaMenulet::addItem(const std::string& name, const std::string& icon) {
- NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: std2NSString(name)
- action: NULL keyEquivalent: @""];
- if (!icon.empty()) {
- NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"];
- NSImage* image = [[NSImage alloc] initWithContentsOfFile: path];
- [item setImage: image];
- [image release];
- }
- [menu addItem: item];
- [item release];
+ NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: std2NSString(name)
+ action: NULL keyEquivalent: @""];
+ if (!icon.empty()) {
+ NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"];
+ NSImage* image = [[NSImage alloc] initWithContentsOfFile: path];
+ [item setImage: image];
+ [image release];
+ }
+ [menu addItem: item];
+ [item release];
}
void CocoaMenulet::addAboutItem() {
- NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"About Slimber" action: @selector(orderFrontStandardAboutPanel:) keyEquivalent: @""];
- [item setTarget: [NSApplication sharedApplication]];
- [menu addItem: item];
- [item release];
+ NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"About Slimber" action: @selector(orderFrontStandardAboutPanel:) keyEquivalent: @""];
+ [item setTarget: [NSApplication sharedApplication]];
+ [menu addItem: item];
+ [item release];
}
void CocoaMenulet::addRestartItem() {
- NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:
- @"Restart" action: @selector(doAction:) keyEquivalent: @""];
- [item setTarget: restartAction];
- [menu addItem: item];
- [item release];
+ NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:
+ @"Restart" action: @selector(doAction:) keyEquivalent: @""];
+ [item setTarget: restartAction];
+ [menu addItem: item];
+ [item release];
}
void CocoaMenulet::addExitItem() {
- NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"Exit" action: @selector(terminate:) keyEquivalent: @""];
- [item setTarget: [NSApplication sharedApplication]];
- [menu addItem: item];
- [item release];
+ NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"Exit" action: @selector(terminate:) keyEquivalent: @""];
+ [item setTarget: [NSApplication sharedApplication]];
+ [menu addItem: item];
+ [item release];
}
void CocoaMenulet::addSeparator() {
- [menu addItem: [NSMenuItem separatorItem]];
+ [menu addItem: [NSMenuItem separatorItem]];
}
diff --git a/Slimber/Cocoa/main.mm b/Slimber/Cocoa/main.mm
index 41678f1..c5495af 100644
--- a/Slimber/Cocoa/main.mm
+++ b/Slimber/Cocoa/main.mm
@@ -13,8 +13,8 @@
Swift::CocoaEventLoop* eventLoop;
int main(int argc, char *argv[]) {
- eventLoop = new Swift::CocoaEventLoop();
- int result = NSApplicationMain(argc, const_cast<const char **>(argv));
- delete eventLoop;
- return result;
+ eventLoop = new Swift::CocoaEventLoop();
+ int result = NSApplicationMain(argc, const_cast<const char **>(argv));
+ delete eventLoop;
+ return result;
}
diff --git a/Slimber/FileVCardCollection.cpp b/Slimber/FileVCardCollection.cpp
index 33e20c9..af8d57d 100644
--- a/Slimber/FileVCardCollection.cpp
+++ b/Slimber/FileVCardCollection.cpp
@@ -21,24 +21,24 @@ FileVCardCollection::FileVCardCollection(boost::filesystem::path dir) : vcardsPa
}
boost::shared_ptr<VCard> FileVCardCollection::getOwnVCard() const {
- if (boost::filesystem::exists(vcardsPath / std::string("vcard.xml"))) {
- ByteArray data;
- readByteArrayFromFile(data, boost::filesystem::path(vcardsPath / std::string("vcard.xml")).string());
-
- VCardParser parser;
- PayloadParserTester tester(&parser);
- tester.parse(byteArrayToString(data));
- return boost::dynamic_pointer_cast<VCard>(parser.getPayload());
- }
- else {
- return boost::make_shared<VCard>();
- }
+ if (boost::filesystem::exists(vcardsPath / std::string("vcard.xml"))) {
+ ByteArray data;
+ readByteArrayFromFile(data, boost::filesystem::path(vcardsPath / std::string("vcard.xml")).string());
+
+ VCardParser parser;
+ PayloadParserTester tester(&parser);
+ tester.parse(byteArrayToString(data));
+ return boost::dynamic_pointer_cast<VCard>(parser.getPayload());
+ }
+ else {
+ return boost::make_shared<VCard>();
+ }
}
void FileVCardCollection::setOwnVCard(boost::shared_ptr<VCard> v) {
- boost::filesystem::ofstream file(vcardsPath / std::string("vcard.xml"));
- file << VCardSerializer().serializePayload(v);
- file.close();
+ boost::filesystem::ofstream file(vcardsPath / std::string("vcard.xml"));
+ file << VCardSerializer().serializePayload(v);
+ file.close();
}
}
diff --git a/Slimber/FileVCardCollection.h b/Slimber/FileVCardCollection.h
index 40f3e53..c05c4f4 100644
--- a/Slimber/FileVCardCollection.h
+++ b/Slimber/FileVCardCollection.h
@@ -12,14 +12,14 @@
#include <Slimber/VCardCollection.h>
namespace Swift {
- class FileVCardCollection : public VCardCollection {
- public:
- FileVCardCollection(boost::filesystem::path dir);
+ class FileVCardCollection : public VCardCollection {
+ public:
+ FileVCardCollection(boost::filesystem::path dir);
- boost::shared_ptr<VCard> getOwnVCard() const;
- void setOwnVCard(boost::shared_ptr<VCard> vcard);
+ boost::shared_ptr<VCard> getOwnVCard() const;
+ void setOwnVCard(boost::shared_ptr<VCard> vcard);
- private:
- boost::filesystem::path vcardsPath;
- };
+ private:
+ boost::filesystem::path vcardsPath;
+ };
}
diff --git a/Slimber/LinkLocalPresenceManager.cpp b/Slimber/LinkLocalPresenceManager.cpp
index 786f3a8..200e98f 100644
--- a/Slimber/LinkLocalPresenceManager.cpp
+++ b/Slimber/LinkLocalPresenceManager.cpp
@@ -16,54 +16,54 @@
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));
+ 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()) {
- if (service.getJID() == j) {
- return service;
- }
- }
- return boost::optional<LinkLocalService>();
+ foreach(const LinkLocalService& service, browser->getServices()) {
+ if (service.getJID() == j) {
+ return service;
+ }
+ }
+ return boost::optional<LinkLocalService>();
}
void LinkLocalPresenceManager::handleServiceAdded(const LinkLocalService& service) {
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->addItem(getRosterItem(service));
- onRosterChanged(roster);
- onPresenceChanged(getPresence(service));
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(getRosterItem(service));
+ onRosterChanged(roster);
+ onPresenceChanged(getPresence(service));
}
void LinkLocalPresenceManager::handleServiceChanged(const LinkLocalService& service) {
- onPresenceChanged(getPresence(service));
+ onPresenceChanged(getPresence(service));
}
void LinkLocalPresenceManager::handleServiceRemoved(const LinkLocalService& service) {
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->addItem(RosterItemPayload(service.getJID(), "", RosterItemPayload::Remove));
- onRosterChanged(roster);
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(RosterItemPayload(service.getJID(), "", RosterItemPayload::Remove));
+ onRosterChanged(roster);
}
boost::shared_ptr<RosterPayload> LinkLocalPresenceManager::getRoster() const {
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- foreach(const LinkLocalService& service, browser->getServices()) {
- roster->addItem(getRosterItem(service));
- }
- return roster;
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ foreach(const LinkLocalService& service, browser->getServices()) {
+ roster->addItem(getRosterItem(service));
+ }
+ return roster;
}
std::vector<boost::shared_ptr<Presence> > LinkLocalPresenceManager::getAllPresence() const {
- std::vector<boost::shared_ptr<Presence> > result;
- foreach(const LinkLocalService& service, browser->getServices()) {
- result.push_back(getPresence(service));
- }
- return result;
+ std::vector<boost::shared_ptr<Presence> > result;
+ foreach(const LinkLocalService& service, browser->getServices()) {
+ result.push_back(getPresence(service));
+ }
+ return result;
}
RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService& service) const {
@@ -71,39 +71,39 @@ RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService
}
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 "";
+ 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 "";
}
boost::shared_ptr<Presence> LinkLocalPresenceManager::getPresence(const LinkLocalService& service) const {
- boost::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;
- case LinkLocalServiceInfo::DND:
- presence->setShow(StatusShow::DND);
- break;
- }
- presence->setStatus(service.getInfo().getMessage());
- return presence;
+ boost::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;
+ case LinkLocalServiceInfo::DND:
+ presence->setShow(StatusShow::DND);
+ break;
+ }
+ presence->setStatus(service.getInfo().getMessage());
+ return presence;
}
}
diff --git a/Slimber/LinkLocalPresenceManager.h b/Slimber/LinkLocalPresenceManager.h
index 1f27e50..83df624 100644
--- a/Slimber/LinkLocalPresenceManager.h
+++ b/Slimber/LinkLocalPresenceManager.h
@@ -15,33 +15,33 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class LinkLocalService;
- class LinkLocalServiceBrowser;
- class RosterPayload;
- class Presence;
+ class LinkLocalService;
+ class LinkLocalServiceBrowser;
+ class RosterPayload;
+ class Presence;
- class LinkLocalPresenceManager : public boost::bsignals::trackable {
- public:
- LinkLocalPresenceManager(LinkLocalServiceBrowser*);
+ class LinkLocalPresenceManager : public boost::bsignals::trackable {
+ public:
+ LinkLocalPresenceManager(LinkLocalServiceBrowser*);
- boost::shared_ptr<RosterPayload> getRoster() const;
- std::vector<boost::shared_ptr<Presence> > getAllPresence() const;
+ boost::shared_ptr<RosterPayload> getRoster() const;
+ std::vector<boost::shared_ptr<Presence> > getAllPresence() const;
- boost::optional<LinkLocalService> getServiceForJID(const JID&) const;
+ boost::optional<LinkLocalService> getServiceForJID(const JID&) const;
- boost::signal<void (boost::shared_ptr<RosterPayload>)> onRosterChanged;
- boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChanged;
+ boost::signal<void (boost::shared_ptr<RosterPayload>)> onRosterChanged;
+ boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChanged;
- private:
- void handleServiceAdded(const LinkLocalService&);
- void handleServiceChanged(const LinkLocalService&);
- void handleServiceRemoved(const LinkLocalService&);
+ private:
+ void handleServiceAdded(const LinkLocalService&);
+ void handleServiceChanged(const LinkLocalService&);
+ void handleServiceRemoved(const LinkLocalService&);
- RosterItemPayload getRosterItem(const LinkLocalService& service) const;
- std::string getRosterName(const LinkLocalService& service) const;
- boost::shared_ptr<Presence> getPresence(const LinkLocalService& service) const;
+ RosterItemPayload getRosterItem(const LinkLocalService& service) const;
+ std::string getRosterName(const LinkLocalService& service) const;
+ boost::shared_ptr<Presence> getPresence(const LinkLocalService& service) const;
- private:
- LinkLocalServiceBrowser* browser;
- };
+ private:
+ LinkLocalServiceBrowser* browser;
+ };
}
diff --git a/Slimber/MainController.cpp b/Slimber/MainController.cpp
index 85c8f4b..90a1b94 100644
--- a/Slimber/MainController.cpp
+++ b/Slimber/MainController.cpp
@@ -26,105 +26,105 @@
using namespace Swift;
MainController::MainController(Menulet* menulet, EventLoop* eventLoop) {
- dnsSDQuerier = PlatformDNSSDQuerierFactory(eventLoop).createQuerier();
- assert(dnsSDQuerier);
+ 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));
+ 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());
+ vCardCollection = new FileVCardCollection(
+ PlatformApplicationPathProvider("Slimber").getDataDir());
- server = new Server(5222, 5562, linkLocalServiceBrowser, vCardCollection, eventLoop);
- server->onStopped.connect(
- boost::bind(&MainController::handleServerStopped, this, _1));
- server->onSelfConnected.connect(
- boost::bind(&MainController::handleSelfConnected, this, _1));
+ server = new Server(5222, 5562, linkLocalServiceBrowser, vCardCollection, eventLoop);
+ server->onStopped.connect(
+ boost::bind(&MainController::handleServerStopped, this, _1));
+ server->onSelfConnected.connect(
+ boost::bind(&MainController::handleSelfConnected, this, _1));
- menuletController = new MenuletController(menulet);
- menuletController->onRestartRequested.connect(boost::bind(
- &MainController::handleRestartRequested, this));
+ menuletController = new MenuletController(menulet);
+ menuletController->onRestartRequested.connect(boost::bind(
+ &MainController::handleRestartRequested, this));
- start();
+ start();
}
MainController::~MainController() {
- delete server;
- delete menuletController;
- delete vCardCollection;
- linkLocalServiceBrowser->stop();
- delete linkLocalServiceBrowser;
- dnsSDQuerier->stop();
+ delete server;
+ delete menuletController;
+ delete vCardCollection;
+ linkLocalServiceBrowser->stop();
+ delete linkLocalServiceBrowser;
+ dnsSDQuerier->stop();
}
void MainController::start() {
- dnsSDQuerier->start();
- linkLocalServiceBrowser->start();
+ dnsSDQuerier->start();
+ linkLocalServiceBrowser->start();
- handleSelfConnected(false);
- handleServicesChanged();
+ handleSelfConnected(false);
+ handleServicesChanged();
- server->start();
+ server->start();
}
void MainController::stop() {
- server->stop();
- linkLocalServiceBrowser->stop();
- dnsSDQuerier->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);
- }
+ 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()) {
- std::string description = service.getDescription();
- if (description != service.getName()) {
- description += " (" + service.getName() + ")";
- }
- names.push_back(description);
- }
- menuletController->setUserNames(names);
+ std::vector<std::string> names;
+ foreach(const LinkLocalService& 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);
- }
+ 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);
+ }
}
void MainController::handleRestartRequested() {
- stop();
- start();
+ stop();
+ start();
}
diff --git a/Slimber/MainController.h b/Slimber/MainController.h
index 5f28c31..8f4e981 100644
--- a/Slimber/MainController.h
+++ b/Slimber/MainController.h
@@ -12,34 +12,34 @@
#include <Slimber/ServerError.h>
namespace Swift {
- class DNSSDQuerier;
- class LinkLocalServiceBrowser;
- class VCardCollection;
- class Server;
- class EventLoop;
+ class DNSSDQuerier;
+ class LinkLocalServiceBrowser;
+ class VCardCollection;
+ class Server;
+ class EventLoop;
}
class MenuletController;
class Menulet;
class MainController {
- public:
- MainController(Menulet* menulet, Swift::EventLoop* eventLoop);
- virtual ~MainController();
-
- private:
- void handleSelfConnected(bool b);
- void handleServicesChanged();
- void handleServerStopped(boost::optional<Swift::ServerError> error);
- void handleRestartRequested();
-
- void start();
- void stop();
-
- private:
- boost::shared_ptr<Swift::DNSSDQuerier> dnsSDQuerier;
- Swift::LinkLocalServiceBrowser* linkLocalServiceBrowser;
- Swift::VCardCollection* vCardCollection;
- Swift::Server* server;
- MenuletController* menuletController;
+ public:
+ MainController(Menulet* menulet, Swift::EventLoop* eventLoop);
+ virtual ~MainController();
+
+ private:
+ void handleSelfConnected(bool b);
+ void handleServicesChanged();
+ void handleServerStopped(boost::optional<Swift::ServerError> error);
+ void handleRestartRequested();
+
+ void start();
+ void stop();
+
+ private:
+ boost::shared_ptr<Swift::DNSSDQuerier> dnsSDQuerier;
+ Swift::LinkLocalServiceBrowser* linkLocalServiceBrowser;
+ Swift::VCardCollection* vCardCollection;
+ Swift::Server* server;
+ MenuletController* menuletController;
};
diff --git a/Slimber/Menulet.h b/Slimber/Menulet.h
index cd4b4d9..4f2e33f 100644
--- a/Slimber/Menulet.h
+++ b/Slimber/Menulet.h
@@ -11,16 +11,16 @@
#include <Swiften/Base/boost_bsignals.h>
class Menulet {
- public:
- virtual ~Menulet();
+ public:
+ virtual ~Menulet();
- virtual void clear() = 0;
- virtual void addItem(const std::string& name, const std::string& icon = std::string()) = 0;
- virtual void addAboutItem() = 0;
- virtual void addRestartItem() = 0;
- virtual void addExitItem() = 0;
- virtual void addSeparator() = 0;
- virtual void setIcon(const std::string&) = 0;
+ virtual void clear() = 0;
+ virtual void addItem(const std::string& name, const std::string& icon = std::string()) = 0;
+ virtual void addAboutItem() = 0;
+ virtual void addRestartItem() = 0;
+ virtual void addExitItem() = 0;
+ virtual void addSeparator() = 0;
+ virtual void setIcon(const std::string&) = 0;
- boost::signal<void ()> onRestartClicked;
+ boost::signal<void ()> onRestartClicked;
};
diff --git a/Slimber/MenuletController.cpp b/Slimber/MenuletController.cpp
index c09d35f..5868128 100644
--- a/Slimber/MenuletController.cpp
+++ b/Slimber/MenuletController.cpp
@@ -13,44 +13,44 @@
#include <Slimber/Menulet.h>
-MenuletController::MenuletController(Menulet* menulet) :
- menulet(menulet), xmppStatus(Offline) {
- menulet->onRestartClicked.connect(boost::ref(onRestartRequested));
- update();
+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();
+ xmppStatus = status;
+ xmppStatusMessage = message;
+ update();
}
void MenuletController::setUserNames(const std::vector<std::string>& users) {
- linkLocalUsers = users;
- update();
+ 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) {
- menulet->addItem(std::string(" ") + user);
- }
- }
- menulet->addSeparator();
- menulet->addItem(xmppStatusMessage, (xmppStatus == Online ? "Online" : "Offline"));
- menulet->addSeparator();
- menulet->addAboutItem();
- menulet->addSeparator();
- menulet->addRestartItem();
- menulet->addExitItem();
+ 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) {
+ 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/MenuletController.h b/Slimber/MenuletController.h
index 46dc41f..210eac2 100644
--- a/Slimber/MenuletController.h
+++ b/Slimber/MenuletController.h
@@ -14,26 +14,26 @@
class Menulet;
class MenuletController {
- public:
- enum Status {
- Online,
- Offline
- };
-
- MenuletController(Menulet*);
- virtual ~MenuletController();
-
- void setXMPPStatus(const std::string& message, Status status);
- void setUserNames(const std::vector<std::string>&);
-
- boost::signal<void ()> onRestartRequested;
-
- private:
- void update();
-
- private:
- Menulet* menulet;
- Status xmppStatus;
- std::string xmppStatusMessage;
- std::vector<std::string> linkLocalUsers;
+ public:
+ enum Status {
+ Online,
+ Offline
+ };
+
+ MenuletController(Menulet*);
+ virtual ~MenuletController();
+
+ void setXMPPStatus(const std::string& message, Status status);
+ void setUserNames(const std::vector<std::string>&);
+
+ boost::signal<void ()> onRestartRequested;
+
+ private:
+ void update();
+
+ private:
+ Menulet* menulet;
+ Status xmppStatus;
+ std::string xmppStatusMessage;
+ std::vector<std::string> linkLocalUsers;
};
diff --git a/Slimber/Qt/QtAboutDialog.cpp b/Slimber/Qt/QtAboutDialog.cpp
index 7fcd2ca..301661e 100644
--- a/Slimber/Qt/QtAboutDialog.cpp
+++ b/Slimber/Qt/QtAboutDialog.cpp
@@ -12,26 +12,26 @@
#include <QVBoxLayout>
QtAboutDialog::QtAboutDialog() {
- setAttribute(Qt::WA_DeleteOnClose);
- setWindowTitle("About Slimber");
-
- QVBoxLayout* layout = new QVBoxLayout(this);
-
- QLabel* iconLabel = new QLabel(this);
- iconLabel->setPixmap(QPixmap(":/icons/Icon-128.png"));
- iconLabel->setAlignment(Qt::AlignHCenter);
- layout->addWidget(iconLabel);
-
- QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
- layout->addWidget(appNameLabel);
-
- QLabel* versionLabel = new QLabel(QString("<center><font size='-1'>Version ") + QCoreApplication::applicationVersion() + "</font></center>", this);
- layout->addWidget(versionLabel);
- QString buildString = QString("<center><font size='-1'>Built with: Qt version ") + QT_VERSION_STR;
- buildString += QString("<br/>Running with Qt version ") + qVersion();
- buildString += "</font></center>";
- QLabel* buildLabel = new QLabel(buildString, this);
- layout->addWidget(buildLabel);
-
- setFixedSize(minimumSizeHint());
+ setAttribute(Qt::WA_DeleteOnClose);
+ setWindowTitle("About Slimber");
+
+ QVBoxLayout* layout = new QVBoxLayout(this);
+
+ QLabel* iconLabel = new QLabel(this);
+ iconLabel->setPixmap(QPixmap(":/icons/Icon-128.png"));
+ iconLabel->setAlignment(Qt::AlignHCenter);
+ layout->addWidget(iconLabel);
+
+ QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
+ layout->addWidget(appNameLabel);
+
+ QLabel* versionLabel = new QLabel(QString("<center><font size='-1'>Version ") + QCoreApplication::applicationVersion() + "</font></center>", this);
+ layout->addWidget(versionLabel);
+ QString buildString = QString("<center><font size='-1'>Built with: Qt version ") + QT_VERSION_STR;
+ buildString += QString("<br/>Running with Qt version ") + qVersion();
+ buildString += "</font></center>";
+ QLabel* buildLabel = new QLabel(buildString, this);
+ layout->addWidget(buildLabel);
+
+ setFixedSize(minimumSizeHint());
}
diff --git a/Slimber/Qt/QtAboutDialog.h b/Slimber/Qt/QtAboutDialog.h
index d19d209..1f14ebe 100644
--- a/Slimber/Qt/QtAboutDialog.h
+++ b/Slimber/Qt/QtAboutDialog.h
@@ -9,6 +9,6 @@
#include <QDialog>
class QtAboutDialog : public QDialog {
- public:
- QtAboutDialog();
+ public:
+ QtAboutDialog();
};
diff --git a/Slimber/Qt/QtMenulet.h b/Slimber/Qt/QtMenulet.h
index 1aed329..fa17d21 100644
--- a/Slimber/Qt/QtMenulet.h
+++ b/Slimber/Qt/QtMenulet.h
@@ -18,65 +18,65 @@
#include <Slimber/Qt/QtAboutDialog.h>
class QtMenulet : public QObject, public Menulet {
- Q_OBJECT
- public:
- QtMenulet() {
- trayIcon.setIcon(QPixmap(":/icons/UsersOffline.png"));
- trayIcon.setContextMenu(&menu);
- trayIcon.show();
- }
+ Q_OBJECT
+ public:
+ QtMenulet() {
+ trayIcon.setIcon(QPixmap(":/icons/UsersOffline.png"));
+ trayIcon.setContextMenu(&menu);
+ trayIcon.show();
+ }
- void clear() {
- menu.clear();
- }
+ void clear() {
+ menu.clear();
+ }
- void addItem(const std::string& name, const std::string& icon) {
- menu.addAction(getIcon(icon), QString::fromUtf8(name.c_str()));
- }
+ void addItem(const std::string& name, const std::string& icon) {
+ menu.addAction(getIcon(icon), QString::fromUtf8(name.c_str()));
+ }
- void addAboutItem() {
- menu.addAction("About", this, SLOT(showAboutDialog()));
- }
+ void addAboutItem() {
+ menu.addAction("About", this, SLOT(showAboutDialog()));
+ }
- void addRestartItem() {
- menu.addAction("Restart", this, SLOT(restart()));
- }
+ void addRestartItem() {
+ menu.addAction("Restart", this, SLOT(restart()));
+ }
- void addExitItem() {
- menu.addAction("Exit", qApp, SLOT(quit()));
- }
+ void addExitItem() {
+ menu.addAction("Exit", qApp, SLOT(quit()));
+ }
- void addSeparator() {
- menu.addSeparator();
- }
+ void addSeparator() {
+ menu.addSeparator();
+ }
- void setIcon(const std::string& icon) {
- trayIcon.setIcon(getIcon(icon));
- }
+ void setIcon(const std::string& icon) {
+ trayIcon.setIcon(getIcon(icon));
+ }
- private:
- QPixmap getIcon(const std::string& name) {
- return QPixmap(":/icons/" + QString::fromUtf8(name.c_str()) + ".png");
- }
+ private:
+ QPixmap getIcon(const std::string& name) {
+ return QPixmap(":/icons/" + QString::fromUtf8(name.c_str()) + ".png");
+ }
- private slots:
- void showAboutDialog() {
- if (aboutDialog) {
- aboutDialog->raise();
- aboutDialog->activateWindow();
- }
- else {
- aboutDialog = new QtAboutDialog();
- aboutDialog->show();
- }
- }
+ private slots:
+ void showAboutDialog() {
+ if (aboutDialog) {
+ aboutDialog->raise();
+ aboutDialog->activateWindow();
+ }
+ else {
+ aboutDialog = new QtAboutDialog();
+ aboutDialog->show();
+ }
+ }
- void restart() {
- onRestartClicked();
- }
+ void restart() {
+ onRestartClicked();
+ }
- private:
- QMenu menu;
- QSystemTrayIcon trayIcon;
- QPointer<QtAboutDialog> aboutDialog;
+ private:
+ QMenu menu;
+ QSystemTrayIcon trayIcon;
+ QPointer<QtAboutDialog> aboutDialog;
};
diff --git a/Slimber/Qt/main.cpp b/Slimber/Qt/main.cpp
index 69a8b6e..8fbfbb6 100644
--- a/Slimber/Qt/main.cpp
+++ b/Slimber/Qt/main.cpp
@@ -16,21 +16,21 @@
#include <Slimber/Qt/QtMenulet.h>
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- Swift::QtEventLoop eventLoop;
+ QApplication app(argc, argv);
+ Swift::QtEventLoop eventLoop;
- QCoreApplication::setApplicationName("Slimber");
- QCoreApplication::setApplicationVersion(QString(buildVersion));
+ QCoreApplication::setApplicationName("Slimber");
+ QCoreApplication::setApplicationVersion(QString(buildVersion));
- if (!QSystemTrayIcon::isSystemTrayAvailable()) {
+ if (!QSystemTrayIcon::isSystemTrayAvailable()) {
QMessageBox::critical(0, QObject::tr("Systray"), QObject::tr("No system tray"));
- return 1;
- }
+ return 1;
+ }
- app.setQuitOnLastWindowClosed(false);
+ app.setQuitOnLastWindowClosed(false);
- QtMenulet menulet;
- MainController controller(&menulet, &eventLoop);
+ QtMenulet menulet;
+ MainController controller(&menulet, &eventLoop);
- return app.exec();
+ return app.exec();
}
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp
index 79dc22d..c69c75d 100644
--- a/Slimber/Server.cpp
+++ b/Slimber/Server.cpp
@@ -39,401 +39,401 @@
namespace Swift {
Server::Server(
- int clientConnectionPort,
- int linkLocalConnectionPort,
- LinkLocalServiceBrowser* linkLocalServiceBrowser,
- VCardCollection* vCardCollection,
- EventLoop* eventLoop) :
- linkLocalServiceRegistered(false),
- rosterRequested(false),
- clientConnectionPort(clientConnectionPort),
- linkLocalConnectionPort(linkLocalConnectionPort),
- linkLocalServiceBrowser(linkLocalServiceBrowser),
- vCardCollection(vCardCollection),
- eventLoop(eventLoop),
- presenceManager(NULL),
- stopping(false) {
- linkLocalServiceBrowser->onServiceRegistered.connect(
- boost::bind(&Server::handleServiceRegistered, this, _1));
+ int clientConnectionPort,
+ int linkLocalConnectionPort,
+ LinkLocalServiceBrowser* linkLocalServiceBrowser,
+ VCardCollection* vCardCollection,
+ EventLoop* eventLoop) :
+ linkLocalServiceRegistered(false),
+ rosterRequested(false),
+ clientConnectionPort(clientConnectionPort),
+ linkLocalConnectionPort(linkLocalConnectionPort),
+ linkLocalServiceBrowser(linkLocalServiceBrowser),
+ vCardCollection(vCardCollection),
+ eventLoop(eventLoop),
+ presenceManager(NULL),
+ stopping(false) {
+ linkLocalServiceBrowser->onServiceRegistered.connect(
+ boost::bind(&Server::handleServiceRegistered, this, _1));
}
Server::~Server() {
- stop();
+ stop();
}
void Server::start() {
- assert(!serverFromClientConnectionServer);
- serverFromClientConnectionServer = BoostConnectionServer::create(
- clientConnectionPort, boostIOServiceThread.getIOService(), eventLoop);
- serverFromClientConnectionServerSignalConnections.push_back(
- serverFromClientConnectionServer->onNewConnection.connect(
- boost::bind(&Server::handleNewClientConnection, this, _1)));
- serverFromClientConnectionServerSignalConnections.push_back(
- serverFromClientConnectionServer->onStopped.connect(
- boost::bind(&Server::handleClientConnectionServerStopped, this, _1)));
-
- assert(!serverFromNetworkConnectionServer);
- serverFromNetworkConnectionServer = BoostConnectionServer::create(
- linkLocalConnectionPort, boostIOServiceThread.getIOService(), eventLoop);
- serverFromNetworkConnectionServerSignalConnections.push_back(
- serverFromNetworkConnectionServer->onNewConnection.connect(
- boost::bind(&Server::handleNewLinkLocalConnection, this, _1)));
- serverFromNetworkConnectionServerSignalConnections.push_back(
- serverFromNetworkConnectionServer->onStopped.connect(
- boost::bind(&Server::handleLinkLocalConnectionServerStopped, this, _1)));
-
- 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();
+ assert(!serverFromClientConnectionServer);
+ serverFromClientConnectionServer = BoostConnectionServer::create(
+ clientConnectionPort, boostIOServiceThread.getIOService(), eventLoop);
+ serverFromClientConnectionServerSignalConnections.push_back(
+ serverFromClientConnectionServer->onNewConnection.connect(
+ boost::bind(&Server::handleNewClientConnection, this, _1)));
+ serverFromClientConnectionServerSignalConnections.push_back(
+ serverFromClientConnectionServer->onStopped.connect(
+ boost::bind(&Server::handleClientConnectionServerStopped, this, _1)));
+
+ assert(!serverFromNetworkConnectionServer);
+ serverFromNetworkConnectionServer = BoostConnectionServer::create(
+ linkLocalConnectionPort, boostIOServiceThread.getIOService(), eventLoop);
+ serverFromNetworkConnectionServerSignalConnections.push_back(
+ serverFromNetworkConnectionServer->onNewConnection.connect(
+ boost::bind(&Server::handleNewLinkLocalConnection, this, _1)));
+ serverFromNetworkConnectionServerSignalConnections.push_back(
+ serverFromNetworkConnectionServer->onStopped.connect(
+ boost::bind(&Server::handleLinkLocalConnectionServerStopped, this, _1)));
+
+ 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>());
+ stop(boost::optional<ServerError>());
}
void Server::stop(boost::optional<ServerError> e) {
- if (stopping) {
- return;
- }
-
- stopping = true;
-
- delete presenceManager;
- presenceManager = NULL;
-
- if (serverFromClientSession) {
- serverFromClientSession->finishSession();
- }
- serverFromClientSession.reset();
- foreach(boost::shared_ptr<Session> session, linkLocalSessions) {
- session->finishSession();
- }
- linkLocalSessions.clear();
- foreach(boost::shared_ptr<LinkLocalConnector> connector, connectors) {
- connector->cancel();
- }
- connectors.clear();
- tracers.clear();
-
- if (serverFromNetworkConnectionServer) {
- serverFromNetworkConnectionServer->stop();
- foreach(boost::bsignals::connection& connection, serverFromNetworkConnectionServerSignalConnections) {
- connection.disconnect();
- }
- serverFromNetworkConnectionServerSignalConnections.clear();
- serverFromNetworkConnectionServer.reset();
- }
- if (serverFromClientConnectionServer) {
- serverFromClientConnectionServer->stop();
- foreach(boost::bsignals::connection& connection, serverFromClientConnectionServerSignalConnections) {
- connection.disconnect();
- }
- serverFromClientConnectionServerSignalConnections.clear();
- serverFromClientConnectionServer.reset();
- }
-
- stopping = false;
- onStopped(e);
+ if (stopping) {
+ return;
+ }
+
+ stopping = true;
+
+ delete presenceManager;
+ presenceManager = NULL;
+
+ if (serverFromClientSession) {
+ serverFromClientSession->finishSession();
+ }
+ serverFromClientSession.reset();
+ foreach(boost::shared_ptr<Session> session, linkLocalSessions) {
+ session->finishSession();
+ }
+ linkLocalSessions.clear();
+ foreach(boost::shared_ptr<LinkLocalConnector> connector, connectors) {
+ connector->cancel();
+ }
+ connectors.clear();
+ tracers.clear();
+
+ if (serverFromNetworkConnectionServer) {
+ serverFromNetworkConnectionServer->stop();
+ foreach(boost::bsignals::connection& connection, serverFromNetworkConnectionServerSignalConnections) {
+ connection.disconnect();
+ }
+ serverFromNetworkConnectionServerSignalConnections.clear();
+ serverFromNetworkConnectionServer.reset();
+ }
+ if (serverFromClientConnectionServer) {
+ serverFromClientConnectionServer->stop();
+ foreach(boost::bsignals::connection& connection, serverFromClientConnectionServerSignalConnections) {
+ connection.disconnect();
+ }
+ serverFromClientConnectionServerSignalConnections.clear();
+ serverFromClientConnectionServer.reset();
+ }
+
+ stopping = false;
+ onStopped(e);
}
void Server::handleNewClientConnection(boost::shared_ptr<Connection> connection) {
- if (serverFromClientSession) {
- connection->disconnect();
- }
- serverFromClientSession = boost::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(boost::shared_ptr<SessionTracer>(
- // new SessionTracer(serverFromClientSession)));
- serverFromClientSession->startSession();
+ if (serverFromClientSession) {
+ connection->disconnect();
+ }
+ serverFromClientSession = boost::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(boost::shared_ptr<SessionTracer>(
+ // new SessionTracer(serverFromClientSession)));
+ serverFromClientSession->startSession();
}
void Server::handleSessionStarted() {
- onSelfConnected(true);
+ onSelfConnected(true);
}
void Server::handleSessionFinished(boost::shared_ptr<ServerFromClientSession>) {
- serverFromClientSession.reset();
- unregisterService();
- selfJID = JID();
- rosterRequested = false;
- onSelfConnected(false);
- lastPresence.reset();
+ serverFromClientSession.reset();
+ unregisterService();
+ selfJID = JID();
+ rosterRequested = false;
+ onSelfConnected(false);
+ lastPresence.reset();
}
void Server::unregisterService() {
- if (linkLocalServiceRegistered) {
- linkLocalServiceRegistered = false;
- linkLocalServiceBrowser->unregisterService();
- }
+ if (linkLocalServiceRegistered) {
+ linkLocalServiceRegistered = false;
+ linkLocalServiceBrowser->unregisterService();
+ }
}
void Server::handleElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<ServerFromClientSession> session) {
- boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
- if (!stanza) {
- return;
- }
-
- stanza->setFrom(session->getRemoteJID());
- if (!stanza->getTo().isValid()) {
- stanza->setTo(session->getLocalJID());
- }
-
- if (boost::shared_ptr<Presence> presence = boost::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 (boost::shared_ptr<IQ> iq = boost::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 boost::shared_ptr<Presence> presence, presenceManager->getAllPresence()) {
- session->sendElement(presence);
- }
- }
- else {
- session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
- }
- }
- if (boost::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();
- boost::shared_ptr<Session> outgoingSession =
- getLinkLocalSessionForJID(toJID);
- if (outgoingSession) {
- outgoingSession->sendElement(stanza);
- }
- else {
- boost::optional<LinkLocalService> service =
- presenceManager->getServiceForJID(toJID);
- if (service) {
- boost::shared_ptr<LinkLocalConnector> connector =
- getLinkLocalConnectorForJID(toJID);
- if (!connector) {
- connector = boost::shared_ptr<LinkLocalConnector>(
- new LinkLocalConnector(
- *service,
- linkLocalServiceBrowser->getQuerier(),
- BoostConnection::create(boostIOServiceThread.getIOService(), eventLoop)));
- connector->onConnectFinished.connect(
- boost::bind(&Server::handleConnectFinished, this, connector, _1));
- connectors.push_back(connector);
- connector->connect();
- }
- connector->queueElement(element);
- }
- else {
- session->sendElement(IQ::createError(
- stanza->getFrom(), stanza->getID(),
- ErrorPayload::RecipientUnavailable, ErrorPayload::Wait));
- }
- }
- }
+ boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
+ if (!stanza) {
+ return;
+ }
+
+ stanza->setFrom(session->getRemoteJID());
+ if (!stanza->getTo().isValid()) {
+ stanza->setTo(session->getLocalJID());
+ }
+
+ if (boost::shared_ptr<Presence> presence = boost::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 (boost::shared_ptr<IQ> iq = boost::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 boost::shared_ptr<Presence> presence, presenceManager->getAllPresence()) {
+ session->sendElement(presence);
+ }
+ }
+ else {
+ session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
+ }
+ }
+ if (boost::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();
+ boost::shared_ptr<Session> outgoingSession =
+ getLinkLocalSessionForJID(toJID);
+ if (outgoingSession) {
+ outgoingSession->sendElement(stanza);
+ }
+ else {
+ boost::optional<LinkLocalService> service =
+ presenceManager->getServiceForJID(toJID);
+ if (service) {
+ boost::shared_ptr<LinkLocalConnector> connector =
+ getLinkLocalConnectorForJID(toJID);
+ if (!connector) {
+ connector = boost::shared_ptr<LinkLocalConnector>(
+ new LinkLocalConnector(
+ *service,
+ linkLocalServiceBrowser->getQuerier(),
+ BoostConnection::create(boostIOServiceThread.getIOService(), eventLoop)));
+ connector->onConnectFinished.connect(
+ boost::bind(&Server::handleConnectFinished, this, connector, _1));
+ connectors.push_back(connector);
+ connector->connect();
+ }
+ connector->queueElement(element);
+ }
+ else {
+ session->sendElement(IQ::createError(
+ stanza->getFrom(), stanza->getID(),
+ ErrorPayload::RecipientUnavailable, ErrorPayload::Wait));
+ }
+ }
+ }
}
void Server::handleNewLinkLocalConnection(boost::shared_ptr<Connection> connection) {
- boost::shared_ptr<IncomingLinkLocalSession> session(
- new IncomingLinkLocalSession(
- selfJID, connection,
- &payloadParserFactories, &payloadSerializers, &xmlParserFactory));
- registerLinkLocalSession(session);
+ boost::shared_ptr<IncomingLinkLocalSession> session(
+ new IncomingLinkLocalSession(
+ selfJID, connection,
+ &payloadParserFactories, &payloadSerializers, &xmlParserFactory));
+ registerLinkLocalSession(session);
}
void Server::handleLinkLocalSessionFinished(boost::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());
+ //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(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<Session> session) {
- if (boost::shared_ptr<Stanza> stanza = boost::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);
- }
+ if (boost::shared_ptr<Stanza> stanza = boost::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(boost::shared_ptr<LinkLocalConnector> connector, bool error) {
- if (error) {
- std::cerr << "Error connecting" << std::endl;
- // TODO: Send back queued stanzas
- }
- else {
- boost::shared_ptr<OutgoingLinkLocalSession> outgoingSession(
- new OutgoingLinkLocalSession(
- selfJID, connector->getService().getJID(), connector->getConnection(),
- &payloadParserFactories, &payloadSerializers, &xmlParserFactory));
- foreach(const boost::shared_ptr<ToplevelElement> element, connector->getQueuedElements()) {
- outgoingSession->queueElement(element);
- }
- registerLinkLocalSession(outgoingSession);
- }
- connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end());
+ if (error) {
+ std::cerr << "Error connecting" << std::endl;
+ // TODO: Send back queued stanzas
+ }
+ else {
+ boost::shared_ptr<OutgoingLinkLocalSession> outgoingSession(
+ new OutgoingLinkLocalSession(
+ selfJID, connector->getService().getJID(), connector->getConnection(),
+ &payloadParserFactories, &payloadSerializers, &xmlParserFactory));
+ foreach(const boost::shared_ptr<ToplevelElement> element, connector->getQueuedElements()) {
+ outgoingSession->queueElement(element);
+ }
+ registerLinkLocalSession(outgoingSession);
+ }
+ connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end());
}
void Server::registerLinkLocalSession(boost::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(boost::make_shared<SessionTracer>(session));
- session->startSession();
+ 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(boost::make_shared<SessionTracer>(session));
+ session->startSession();
}
boost::shared_ptr<Session> Server::getLinkLocalSessionForJID(const JID& jid) {
- foreach(const boost::shared_ptr<Session> session, linkLocalSessions) {
- if (session->getRemoteJID() == jid) {
- return session;
- }
- }
- return boost::shared_ptr<Session>();
+ foreach(const boost::shared_ptr<Session> session, linkLocalSessions) {
+ if (session->getRemoteJID() == jid) {
+ return session;
+ }
+ }
+ return boost::shared_ptr<Session>();
}
boost::shared_ptr<LinkLocalConnector> Server::getLinkLocalConnectorForJID(const JID& jid) {
- foreach(const boost::shared_ptr<LinkLocalConnector> connector, connectors) {
- if (connector->getService().getJID() == jid) {
- return connector;
- }
- }
- return boost::shared_ptr<LinkLocalConnector>();
+ foreach(const boost::shared_ptr<LinkLocalConnector> connector, connectors) {
+ if (connector->getService().getJID() == jid) {
+ return connector;
+ }
+ }
+ return boost::shared_ptr<LinkLocalConnector>();
}
void Server::handleServiceRegistered(const DNSSDServiceID& service) {
- selfJID = JID(service.getName());
+ selfJID = JID(service.getName());
}
void Server::handleRosterChanged(boost::shared_ptr<RosterPayload> roster) {
- if (rosterRequested) {
- assert(serverFromClientSession);
- boost::shared_ptr<IQ> iq = IQ::createRequest(
- IQ::Set, serverFromClientSession->getRemoteJID(),
- idGenerator.generateID(), roster);
- iq->setFrom(serverFromClientSession->getRemoteJID().toBare());
- serverFromClientSession->sendElement(iq);
- }
+ if (rosterRequested) {
+ assert(serverFromClientSession);
+ boost::shared_ptr<IQ> iq = IQ::createRequest(
+ IQ::Set, serverFromClientSession->getRemoteJID(),
+ idGenerator.generateID(), roster);
+ iq->setFrom(serverFromClientSession->getRemoteJID().toBare());
+ serverFromClientSession->sendElement(iq);
+ }
}
void Server::handlePresenceChanged(boost::shared_ptr<Presence> presence) {
- if (rosterRequested) {
- serverFromClientSession->sendElement(presence);
- }
+ if (rosterRequested) {
+ serverFromClientSession->sendElement(presence);
+ }
}
void Server::handleClientConnectionServerStopped(boost::optional<BoostConnectionServer::Error> e) {
- if (e) {
- if (*e == BoostConnectionServer::Conflict) {
- stop(ServerError(ServerError::C2SPortConflict));
- }
- else {
- stop(ServerError(ServerError::C2SError));
- }
- }
- else {
- stop();
- }
+ if (e) {
+ if (*e == BoostConnectionServer::Conflict) {
+ stop(ServerError(ServerError::C2SPortConflict));
+ }
+ else {
+ stop(ServerError(ServerError::C2SError));
+ }
+ }
+ else {
+ stop();
+ }
}
void Server::handleLinkLocalConnectionServerStopped(boost::optional<BoostConnectionServer::Error> e) {
- if (e) {
- if (*e == BoostConnectionServer::Conflict) {
- stop(ServerError(ServerError::LinkLocalPortConflict));
- }
- else {
- stop(ServerError(ServerError::LinkLocalError));
- }
- }
- else {
- stop();
- }
+ if (e) {
+ if (*e == BoostConnectionServer::Conflict) {
+ stop(ServerError(ServerError::LinkLocalPortConflict));
+ }
+ else {
+ stop(ServerError(ServerError::LinkLocalError));
+ }
+ }
+ else {
+ stop();
+ }
}
LinkLocalServiceInfo Server::getLinkLocalServiceInfo(boost::shared_ptr<Presence> presence) {
- LinkLocalServiceInfo info;
- boost::shared_ptr<VCard> vcard = vCardCollection->getOwnVCard();
- if (!vcard->getFamilyName().empty() || !vcard->getGivenName().empty()) {
- info.setFirstName(vcard->getGivenName());
- info.setLastName(vcard->getFamilyName());
- }
- else if (!vcard->getFullName().empty()) {
- std::pair<std::string,std::string> p = String::getSplittedAtFirst(vcard->getFullName(), ' ');
- info.setFirstName(p.first);
- info.setLastName(p.second);
- }
- if (!vcard->getNickname().empty()) {
- info.setNick(vcard->getNickname());
- }
- if (!vcard->getPreferredEMailAddress().address.empty()) {
- info.setEMail(vcard->getPreferredEMailAddress().address);
- }
- info.setMessage(presence->getStatus());
- switch (presence->getShow()) {
- case StatusShow::Online:
- case StatusShow::None:
- case StatusShow::FFC:
- info.setStatus(LinkLocalServiceInfo::Available);
- break;
- case StatusShow::Away:
- case StatusShow::XA:
- info.setStatus(LinkLocalServiceInfo::Away);
- break;
- case StatusShow::DND:
- info.setStatus(LinkLocalServiceInfo::DND);
- break;
- }
- info.setPort(linkLocalConnectionPort);
- return info;
+ LinkLocalServiceInfo info;
+ boost::shared_ptr<VCard> vcard = vCardCollection->getOwnVCard();
+ if (!vcard->getFamilyName().empty() || !vcard->getGivenName().empty()) {
+ info.setFirstName(vcard->getGivenName());
+ info.setLastName(vcard->getFamilyName());
+ }
+ else if (!vcard->getFullName().empty()) {
+ std::pair<std::string,std::string> p = String::getSplittedAtFirst(vcard->getFullName(), ' ');
+ info.setFirstName(p.first);
+ info.setLastName(p.second);
+ }
+ if (!vcard->getNickname().empty()) {
+ info.setNick(vcard->getNickname());
+ }
+ if (!vcard->getPreferredEMailAddress().address.empty()) {
+ info.setEMail(vcard->getPreferredEMailAddress().address);
+ }
+ info.setMessage(presence->getStatus());
+ switch (presence->getShow()) {
+ case StatusShow::Online:
+ case StatusShow::None:
+ case StatusShow::FFC:
+ info.setStatus(LinkLocalServiceInfo::Available);
+ break;
+ case StatusShow::Away:
+ case StatusShow::XA:
+ info.setStatus(LinkLocalServiceInfo::Away);
+ break;
+ case StatusShow::DND:
+ info.setStatus(LinkLocalServiceInfo::DND);
+ break;
+ }
+ info.setPort(linkLocalConnectionPort);
+ return info;
}
}
diff --git a/Slimber/Server.h b/Slimber/Server.h
index a87381c..7037cdb 100644
--- a/Slimber/Server.h
+++ b/Slimber/Server.h
@@ -26,101 +26,101 @@
#include <Slimber/ServerError.h>
namespace Swift {
- class DNSSDServiceID;
-
- class VCardCollection;
- class LinkLocalConnector;
- class LinkLocalServiceBrowser;
- class LinkLocalPresenceManager;
- class BoostConnectionServer;
- class SessionTracer;
- class RosterPayload;
- class Presence;
- class EventLoop;
-
- class Server {
- public:
- Server(
- int clientConnectionPort,
- int linkLocalConnectionPort,
- LinkLocalServiceBrowser* browser,
- VCardCollection* vCardCollection,
- EventLoop* eventLoop);
- ~Server();
-
- void start();
- void stop();
-
- int getLinkLocalPort() const {
- return linkLocalConnectionPort;
- }
-
- int getClientToServerPort() const {
- return clientConnectionPort;
- }
-
- boost::signal<void (bool)> onSelfConnected;
- boost::signal<void (boost::optional<ServerError>)> onStopped;
-
- private:
- void stop(boost::optional<ServerError>);
-
- void handleNewClientConnection(boost::shared_ptr<Connection> c);
- void handleSessionStarted();
- void handleSessionFinished(boost::shared_ptr<ServerFromClientSession>);
- void handleElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<ServerFromClientSession> session);
- void handleRosterChanged(boost::shared_ptr<RosterPayload> roster);
- void handlePresenceChanged(boost::shared_ptr<Presence> presence);
- void handleServiceRegistered(const DNSSDServiceID& service);
- void handleNewLinkLocalConnection(boost::shared_ptr<Connection> connection);
- void handleLinkLocalSessionFinished(boost::shared_ptr<Session> session);
- void handleLinkLocalElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<Session> session);
- void handleConnectFinished(boost::shared_ptr<LinkLocalConnector> connector, bool error);
- void handleClientConnectionServerStopped(
- boost::optional<BoostConnectionServer::Error>);
- void handleLinkLocalConnectionServerStopped(
- boost::optional<BoostConnectionServer::Error>);
- boost::shared_ptr<Session> getLinkLocalSessionForJID(const JID& jid);
- boost::shared_ptr<LinkLocalConnector> getLinkLocalConnectorForJID(const JID& jid);
- void registerLinkLocalSession(boost::shared_ptr<Session> session);
- void unregisterService();
- LinkLocalServiceInfo getLinkLocalServiceInfo(boost::shared_ptr<Presence> presence);
-
- private:
- class DummyUserRegistry : public UserRegistry {
- public:
- DummyUserRegistry() {}
-
- virtual bool isValidUserPassword(const JID&, const SafeByteArray&) const {
- return true;
- }
- };
-
- private:
- IDGenerator idGenerator;
- FullPayloadParserFactoryCollection payloadParserFactories;
- FullPayloadSerializerCollection payloadSerializers;
- BoostIOServiceThread boostIOServiceThread;
- DummyUserRegistry userRegistry;
- PlatformXMLParserFactory xmlParserFactory;
- bool linkLocalServiceRegistered;
- bool rosterRequested;
- int clientConnectionPort;
- int linkLocalConnectionPort;
- LinkLocalServiceBrowser* linkLocalServiceBrowser;
- VCardCollection* vCardCollection;
- EventLoop* eventLoop;
- LinkLocalPresenceManager* presenceManager;
- bool stopping;
- boost::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer;
- std::vector<boost::bsignals::connection> serverFromClientConnectionServerSignalConnections;
- boost::shared_ptr<ServerFromClientSession> serverFromClientSession;
- boost::shared_ptr<Presence> lastPresence;
- JID selfJID;
- boost::shared_ptr<BoostConnectionServer> serverFromNetworkConnectionServer;
- std::vector<boost::bsignals::connection> serverFromNetworkConnectionServerSignalConnections;
- std::vector< boost::shared_ptr<Session> > linkLocalSessions;
- std::vector< boost::shared_ptr<LinkLocalConnector> > connectors;
- std::vector< boost::shared_ptr<SessionTracer> > tracers;
- };
+ class DNSSDServiceID;
+
+ class VCardCollection;
+ class LinkLocalConnector;
+ class LinkLocalServiceBrowser;
+ class LinkLocalPresenceManager;
+ class BoostConnectionServer;
+ class SessionTracer;
+ class RosterPayload;
+ class Presence;
+ class EventLoop;
+
+ class Server {
+ public:
+ Server(
+ int clientConnectionPort,
+ int linkLocalConnectionPort,
+ LinkLocalServiceBrowser* browser,
+ VCardCollection* vCardCollection,
+ EventLoop* eventLoop);
+ ~Server();
+
+ void start();
+ void stop();
+
+ int getLinkLocalPort() const {
+ return linkLocalConnectionPort;
+ }
+
+ int getClientToServerPort() const {
+ return clientConnectionPort;
+ }
+
+ boost::signal<void (bool)> onSelfConnected;
+ boost::signal<void (boost::optional<ServerError>)> onStopped;
+
+ private:
+ void stop(boost::optional<ServerError>);
+
+ void handleNewClientConnection(boost::shared_ptr<Connection> c);
+ void handleSessionStarted();
+ void handleSessionFinished(boost::shared_ptr<ServerFromClientSession>);
+ void handleElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<ServerFromClientSession> session);
+ void handleRosterChanged(boost::shared_ptr<RosterPayload> roster);
+ void handlePresenceChanged(boost::shared_ptr<Presence> presence);
+ void handleServiceRegistered(const DNSSDServiceID& service);
+ void handleNewLinkLocalConnection(boost::shared_ptr<Connection> connection);
+ void handleLinkLocalSessionFinished(boost::shared_ptr<Session> session);
+ void handleLinkLocalElementReceived(boost::shared_ptr<ToplevelElement> element, boost::shared_ptr<Session> session);
+ void handleConnectFinished(boost::shared_ptr<LinkLocalConnector> connector, bool error);
+ void handleClientConnectionServerStopped(
+ boost::optional<BoostConnectionServer::Error>);
+ void handleLinkLocalConnectionServerStopped(
+ boost::optional<BoostConnectionServer::Error>);
+ boost::shared_ptr<Session> getLinkLocalSessionForJID(const JID& jid);
+ boost::shared_ptr<LinkLocalConnector> getLinkLocalConnectorForJID(const JID& jid);
+ void registerLinkLocalSession(boost::shared_ptr<Session> session);
+ void unregisterService();
+ LinkLocalServiceInfo getLinkLocalServiceInfo(boost::shared_ptr<Presence> presence);
+
+ private:
+ class DummyUserRegistry : public UserRegistry {
+ public:
+ DummyUserRegistry() {}
+
+ virtual bool isValidUserPassword(const JID&, const SafeByteArray&) const {
+ return true;
+ }
+ };
+
+ private:
+ IDGenerator idGenerator;
+ FullPayloadParserFactoryCollection payloadParserFactories;
+ FullPayloadSerializerCollection payloadSerializers;
+ BoostIOServiceThread boostIOServiceThread;
+ DummyUserRegistry userRegistry;
+ PlatformXMLParserFactory xmlParserFactory;
+ bool linkLocalServiceRegistered;
+ bool rosterRequested;
+ int clientConnectionPort;
+ int linkLocalConnectionPort;
+ LinkLocalServiceBrowser* linkLocalServiceBrowser;
+ VCardCollection* vCardCollection;
+ EventLoop* eventLoop;
+ LinkLocalPresenceManager* presenceManager;
+ bool stopping;
+ boost::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer;
+ std::vector<boost::bsignals::connection> serverFromClientConnectionServerSignalConnections;
+ boost::shared_ptr<ServerFromClientSession> serverFromClientSession;
+ boost::shared_ptr<Presence> lastPresence;
+ JID selfJID;
+ boost::shared_ptr<BoostConnectionServer> serverFromNetworkConnectionServer;
+ std::vector<boost::bsignals::connection> serverFromNetworkConnectionServerSignalConnections;
+ std::vector< boost::shared_ptr<Session> > linkLocalSessions;
+ std::vector< boost::shared_ptr<LinkLocalConnector> > connectors;
+ std::vector< boost::shared_ptr<SessionTracer> > tracers;
+ };
}
diff --git a/Slimber/ServerError.h b/Slimber/ServerError.h
index b8cb0a5..93b6a3f 100644
--- a/Slimber/ServerError.h
+++ b/Slimber/ServerError.h
@@ -9,29 +9,29 @@
#include <string>
namespace Swift {
- class ServerError {
- public:
- enum Type {
- C2SPortConflict,
- C2SError,
- LinkLocalPortConflict,
- LinkLocalError
- };
+ class ServerError {
+ public:
+ enum Type {
+ C2SPortConflict,
+ C2SError,
+ LinkLocalPortConflict,
+ LinkLocalError
+ };
- ServerError(Type type, const std::string& message = std::string()) :
- type(type), message(message) {
- }
+ ServerError(Type type, const std::string& message = std::string()) :
+ type(type), message(message) {
+ }
- Type getType() const {
- return type;
- }
+ Type getType() const {
+ return type;
+ }
- const std::string& getMessage() const {
- return message;
- }
+ const std::string& getMessage() const {
+ return message;
+ }
- private:
- Type type;
- std::string message;
- };
+ private:
+ Type type;
+ std::string message;
+ };
}
diff --git a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
index 2681c1a..45bc2aa 100644
--- a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
+++ b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
@@ -26,239 +26,239 @@
using namespace Swift;
class LinkLocalPresenceManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkLocalPresenceManagerTest);
- CPPUNIT_TEST(testConstructor);
- CPPUNIT_TEST(testServiceAdded);
- CPPUNIT_TEST(testServiceRemoved);
- CPPUNIT_TEST(testServiceChanged);
- CPPUNIT_TEST(testGetRoster);
- CPPUNIT_TEST(testGetAllPresence);
- CPPUNIT_TEST(testGetRoster_InfoWithNick);
- CPPUNIT_TEST(testGetRoster_InfoWithFirstName);
- CPPUNIT_TEST(testGetRoster_InfoWithLastName);
- CPPUNIT_TEST(testGetRoster_InfoWithFirstAndLastName);
- CPPUNIT_TEST(testGetRoster_NoInfo);
- CPPUNIT_TEST(testGetServiceForJID);
- CPPUNIT_TEST(testGetServiceForJID_NoMatch);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop = new DummyEventLoop();
- querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
- browser = new LinkLocalServiceBrowser(querier);
- browser->start();
- }
-
- void tearDown() {
- browser->stop();
- delete browser;
- delete eventLoop;
- }
-
- void testConstructor() {
- addService("alice@wonderland");
- addService("rabbit@teaparty");
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getRoster()->getItems().size()));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getAllPresence().size()));
- }
-
- void testServiceAdded() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "Alice");
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges[0]->getItems().size()));
- boost::optional<RosterItemPayload> item = rosterChanges[0]->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(presenceChanges.size()));
- CPPUNIT_ASSERT(StatusShow::Online == presenceChanges[0]->getShow());
- CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[0]->getFrom());
- }
-
- void testServiceRemoved() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
- removeService("alice@wonderland");
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rosterChanges.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges[1]->getItems().size()));
- boost::optional<RosterItemPayload> item = rosterChanges[1]->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Remove, item->getSubscription());
- }
-
- void testServiceChanged() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
- updateServicePresence("alice@wonderland", LinkLocalServiceInfo::Away, "I'm Away");
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges.size()));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(presenceChanges.size()));
- CPPUNIT_ASSERT(StatusShow::Away == presenceChanges[1]->getShow());
- CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[1]->getFrom());
- CPPUNIT_ASSERT_EQUAL(std::string("I'm Away"), presenceChanges[1]->getStatus());
- }
-
- void testGetAllPresence() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
- addService("rabbit@teaparty");
- updateServicePresence("rabbit@teaparty", LinkLocalServiceInfo::Away, "Partying");
-
- std::vector<boost::shared_ptr<Presence> > presences = testling->getAllPresence();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(presences.size()));
- // The order doesn't matter
- CPPUNIT_ASSERT(JID("rabbit@teaparty") == presences[0]->getFrom());
- CPPUNIT_ASSERT(StatusShow::Away == presences[0]->getShow());
- CPPUNIT_ASSERT(JID("alice@wonderland") == presences[1]->getFrom());
- CPPUNIT_ASSERT(StatusShow::Online == presences[1]->getShow());
- }
-
- void testGetRoster() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "Alice");
- addService("rabbit@teaparty", "Rabbit");
-
- boost::shared_ptr<RosterPayload> roster = testling->getRoster();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(roster->getItems().size()));
- boost::optional<RosterItemPayload> item;
- item = roster->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
- item = roster->getItem(JID("rabbit@teaparty"));
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), item->getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
- }
-
- void testGetRoster_InfoWithNick() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "Alice", "Alice In", "Wonderland");
-
- boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
- }
-
- void testGetRoster_InfoWithFirstName() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "", "Alice In", "");
-
- boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), item->getName());
- }
-
- void testGetRoster_InfoWithLastName() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "", "", "Wonderland");
-
- boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), item->getName());
- }
-
- void testGetRoster_InfoWithFirstAndLastName() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland", "", "Alice In", "Wonderland");
-
- boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), item->getName());
- }
-
- void testGetRoster_NoInfo() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
-
- boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
- CPPUNIT_ASSERT_EQUAL(std::string(""), item->getName());
- }
-
- void testGetServiceForJID() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
- addService("rabbit@teaparty");
- addService("queen@garden");
-
- boost::optional<LinkLocalService> service = testling->getServiceForJID(JID("rabbit@teaparty"));
- CPPUNIT_ASSERT(service);
- CPPUNIT_ASSERT_EQUAL(std::string("rabbit@teaparty"), service->getID().getName());
- }
-
- void testGetServiceForJID_NoMatch() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
-
- addService("alice@wonderland");
- addService("queen@garden");
-
- CPPUNIT_ASSERT(!testling->getServiceForJID(JID("rabbit@teaparty")));
- }
-
- private:
- boost::shared_ptr<LinkLocalPresenceManager> createTestling() {
- boost::shared_ptr<LinkLocalPresenceManager> testling(
- new LinkLocalPresenceManager(browser));
- testling->onRosterChanged.connect(boost::bind(
- &LinkLocalPresenceManagerTest::handleRosterChanged, this, _1));
- testling->onPresenceChanged.connect(boost::bind(
- &LinkLocalPresenceManagerTest::handlePresenceChanged, this, _1));
- return testling;
- }
-
- void addService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) {
- DNSSDServiceID service(name, "local.");
- LinkLocalServiceInfo info;
- info.setFirstName(firstName);
- info.setLastName(lastName);
- info.setNick(nickName);
- querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord()));
- querier->addService(service);
- eventLoop->processEvents();
- }
-
- void removeService(const std::string& name) {
- DNSSDServiceID service(name, "local.");
- querier->removeService(DNSSDServiceID(name, "local."));
- eventLoop->processEvents();
- }
-
- void updateServicePresence(const std::string& name, LinkLocalServiceInfo::Status status, const std::string& message) {
- DNSSDServiceID service(name, "local.");
- LinkLocalServiceInfo info;
- info.setStatus(status);
- info.setMessage(message);
- querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord()));
- eventLoop->processEvents();
- }
-
- void handleRosterChanged(boost::shared_ptr<RosterPayload> payload) {
- rosterChanges.push_back(payload);
- }
-
- void handlePresenceChanged(boost::shared_ptr<Presence> presence) {
- presenceChanges.push_back(presence);
- }
-
- private:
- DummyEventLoop* eventLoop;
- boost::shared_ptr<FakeDNSSDQuerier> querier;
- LinkLocalServiceBrowser* browser;
- std::vector< boost::shared_ptr<RosterPayload> > rosterChanges;
- std::vector< boost::shared_ptr<Presence> > presenceChanges;
+ CPPUNIT_TEST_SUITE(LinkLocalPresenceManagerTest);
+ CPPUNIT_TEST(testConstructor);
+ CPPUNIT_TEST(testServiceAdded);
+ CPPUNIT_TEST(testServiceRemoved);
+ CPPUNIT_TEST(testServiceChanged);
+ CPPUNIT_TEST(testGetRoster);
+ CPPUNIT_TEST(testGetAllPresence);
+ CPPUNIT_TEST(testGetRoster_InfoWithNick);
+ CPPUNIT_TEST(testGetRoster_InfoWithFirstName);
+ CPPUNIT_TEST(testGetRoster_InfoWithLastName);
+ CPPUNIT_TEST(testGetRoster_InfoWithFirstAndLastName);
+ CPPUNIT_TEST(testGetRoster_NoInfo);
+ CPPUNIT_TEST(testGetServiceForJID);
+ CPPUNIT_TEST(testGetServiceForJID_NoMatch);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
+ browser = new LinkLocalServiceBrowser(querier);
+ browser->start();
+ }
+
+ void tearDown() {
+ browser->stop();
+ delete browser;
+ delete eventLoop;
+ }
+
+ void testConstructor() {
+ addService("alice@wonderland");
+ addService("rabbit@teaparty");
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getRoster()->getItems().size()));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getAllPresence().size()));
+ }
+
+ void testServiceAdded() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "Alice");
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges[0]->getItems().size()));
+ boost::optional<RosterItemPayload> item = rosterChanges[0]->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(presenceChanges.size()));
+ CPPUNIT_ASSERT(StatusShow::Online == presenceChanges[0]->getShow());
+ CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[0]->getFrom());
+ }
+
+ void testServiceRemoved() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ removeService("alice@wonderland");
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rosterChanges.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges[1]->getItems().size()));
+ boost::optional<RosterItemPayload> item = rosterChanges[1]->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Remove, item->getSubscription());
+ }
+
+ void testServiceChanged() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ updateServicePresence("alice@wonderland", LinkLocalServiceInfo::Away, "I'm Away");
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges.size()));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(presenceChanges.size()));
+ CPPUNIT_ASSERT(StatusShow::Away == presenceChanges[1]->getShow());
+ CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[1]->getFrom());
+ CPPUNIT_ASSERT_EQUAL(std::string("I'm Away"), presenceChanges[1]->getStatus());
+ }
+
+ void testGetAllPresence() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ addService("rabbit@teaparty");
+ updateServicePresence("rabbit@teaparty", LinkLocalServiceInfo::Away, "Partying");
+
+ std::vector<boost::shared_ptr<Presence> > presences = testling->getAllPresence();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(presences.size()));
+ // The order doesn't matter
+ CPPUNIT_ASSERT(JID("rabbit@teaparty") == presences[0]->getFrom());
+ CPPUNIT_ASSERT(StatusShow::Away == presences[0]->getShow());
+ CPPUNIT_ASSERT(JID("alice@wonderland") == presences[1]->getFrom());
+ CPPUNIT_ASSERT(StatusShow::Online == presences[1]->getShow());
+ }
+
+ void testGetRoster() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "Alice");
+ addService("rabbit@teaparty", "Rabbit");
+
+ boost::shared_ptr<RosterPayload> roster = testling->getRoster();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(roster->getItems().size()));
+ boost::optional<RosterItemPayload> item;
+ item = roster->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
+ item = roster->getItem(JID("rabbit@teaparty"));
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), item->getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
+ }
+
+ void testGetRoster_InfoWithNick() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "Alice", "Alice In", "Wonderland");
+
+ boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
+ }
+
+ void testGetRoster_InfoWithFirstName() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "", "Alice In", "");
+
+ boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), item->getName());
+ }
+
+ void testGetRoster_InfoWithLastName() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "", "", "Wonderland");
+
+ boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), item->getName());
+ }
+
+ void testGetRoster_InfoWithFirstAndLastName() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "", "Alice In", "Wonderland");
+
+ boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), item->getName());
+ }
+
+ void testGetRoster_NoInfo() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+
+ boost::optional<RosterItemPayload> item = testling->getRoster()->getItem(JID("alice@wonderland"));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), item->getName());
+ }
+
+ void testGetServiceForJID() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ addService("rabbit@teaparty");
+ addService("queen@garden");
+
+ boost::optional<LinkLocalService> service = testling->getServiceForJID(JID("rabbit@teaparty"));
+ CPPUNIT_ASSERT(service);
+ CPPUNIT_ASSERT_EQUAL(std::string("rabbit@teaparty"), service->getID().getName());
+ }
+
+ void testGetServiceForJID_NoMatch() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ addService("queen@garden");
+
+ CPPUNIT_ASSERT(!testling->getServiceForJID(JID("rabbit@teaparty")));
+ }
+
+ private:
+ boost::shared_ptr<LinkLocalPresenceManager> createTestling() {
+ boost::shared_ptr<LinkLocalPresenceManager> testling(
+ new LinkLocalPresenceManager(browser));
+ testling->onRosterChanged.connect(boost::bind(
+ &LinkLocalPresenceManagerTest::handleRosterChanged, this, _1));
+ testling->onPresenceChanged.connect(boost::bind(
+ &LinkLocalPresenceManagerTest::handlePresenceChanged, this, _1));
+ return testling;
+ }
+
+ void addService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) {
+ DNSSDServiceID service(name, "local.");
+ LinkLocalServiceInfo info;
+ info.setFirstName(firstName);
+ info.setLastName(lastName);
+ info.setNick(nickName);
+ querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord()));
+ querier->addService(service);
+ eventLoop->processEvents();
+ }
+
+ void removeService(const std::string& name) {
+ DNSSDServiceID service(name, "local.");
+ querier->removeService(DNSSDServiceID(name, "local."));
+ eventLoop->processEvents();
+ }
+
+ void updateServicePresence(const std::string& name, LinkLocalServiceInfo::Status status, const std::string& message) {
+ DNSSDServiceID service(name, "local.");
+ LinkLocalServiceInfo info;
+ info.setStatus(status);
+ info.setMessage(message);
+ querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord()));
+ eventLoop->processEvents();
+ }
+
+ void handleRosterChanged(boost::shared_ptr<RosterPayload> payload) {
+ rosterChanges.push_back(payload);
+ }
+
+ void handlePresenceChanged(boost::shared_ptr<Presence> presence) {
+ presenceChanges.push_back(presence);
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ boost::shared_ptr<FakeDNSSDQuerier> querier;
+ LinkLocalServiceBrowser* browser;
+ std::vector< boost::shared_ptr<RosterPayload> > rosterChanges;
+ std::vector< boost::shared_ptr<Presence> > presenceChanges;
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalPresenceManagerTest);
diff --git a/Slimber/UnitTest/MenuletControllerTest.cpp b/Slimber/UnitTest/MenuletControllerTest.cpp
index c379b8b..e3b46ab 100644
--- a/Slimber/UnitTest/MenuletControllerTest.cpp
+++ b/Slimber/UnitTest/MenuletControllerTest.cpp
@@ -11,145 +11,145 @@
#include <Slimber/MenuletController.h>
class MenuletControllerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MenuletControllerTest);
- CPPUNIT_TEST(testConstructor);
- CPPUNIT_TEST(testUpdate);
- CPPUNIT_TEST(testSetXMPPStatus_Online);
- CPPUNIT_TEST(testSetXMPPStatus_Offline);
- CPPUNIT_TEST(testSetUserNames);
- CPPUNIT_TEST(testSetUserNames_NoUsers);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- menulet = new FakeMenulet();
- }
-
- void tearDown() {
- delete menulet;
- }
-
- void testConstructor() {
- MenuletController testling(menulet);
-
- CPPUNIT_ASSERT_EQUAL(8, static_cast<int>(menulet->items.size()));
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("[Offline] "), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]);
- }
-
- void testUpdate() {
- MenuletController testling(menulet);
-
- testling.setXMPPStatus("You are connected", MenuletController::Online);
-
- CPPUNIT_ASSERT_EQUAL(8, static_cast<int>(menulet->items.size()));
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]);
- }
-
- void testSetXMPPStatus_Online() {
- MenuletController testling(menulet);
-
- testling.setXMPPStatus("You are connected", MenuletController::Online);
-
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]);
- }
-
-
- void testSetXMPPStatus_Offline() {
- MenuletController testling(menulet);
-
- testling.setXMPPStatus("You are not connected", MenuletController::Offline);
-
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("[Offline] You are not connected"), menulet->items[i++]);
- }
-
- void testSetUserNames() {
- MenuletController testling(menulet);
-
- std::vector<std::string> users;
- users.push_back("Alice In Wonderland");
- users.push_back("The Mad Hatter");
- testling.setUserNames(users);
-
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("Online users:"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string(" Alice In Wonderland"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string(" The Mad Hatter"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- }
-
- void testSetUserNames_NoUsers() {
- MenuletController testling(menulet);
-
- std::vector<std::string> users;
- testling.setUserNames(users);
-
- size_t i = 0;
- CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
- }
-
- private:
- struct FakeMenulet : public Menulet {
- virtual void clear() {
- items.clear();
- }
-
- virtual void addItem(const std::string& name, const std::string& icon = std::string()) {
- std::string result;
- if (!icon.empty()) {
- result += "[" + icon + "] ";
- }
- result += name;
- items.push_back(result);
- }
-
- virtual void addAboutItem() {
- items.push_back("*About*");
- }
-
- virtual void addRestartItem() {
- items.push_back("*Restart*");
- }
-
- virtual void addExitItem() {
- items.push_back("*Exit*");
- }
-
- virtual void addSeparator() {
- items.push_back("-");
- }
-
- virtual void setIcon(const std::string& i) {
- icon = i;
- }
-
- std::vector<std::string> items;
- std::string icon;
- };
-
- FakeMenulet* menulet;
+ CPPUNIT_TEST_SUITE(MenuletControllerTest);
+ CPPUNIT_TEST(testConstructor);
+ CPPUNIT_TEST(testUpdate);
+ CPPUNIT_TEST(testSetXMPPStatus_Online);
+ CPPUNIT_TEST(testSetXMPPStatus_Offline);
+ CPPUNIT_TEST(testSetUserNames);
+ CPPUNIT_TEST(testSetUserNames_NoUsers);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ menulet = new FakeMenulet();
+ }
+
+ void tearDown() {
+ delete menulet;
+ }
+
+ void testConstructor() {
+ MenuletController testling(menulet);
+
+ CPPUNIT_ASSERT_EQUAL(8, static_cast<int>(menulet->items.size()));
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("[Offline] "), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]);
+ }
+
+ void testUpdate() {
+ MenuletController testling(menulet);
+
+ testling.setXMPPStatus("You are connected", MenuletController::Online);
+
+ CPPUNIT_ASSERT_EQUAL(8, static_cast<int>(menulet->items.size()));
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]);
+ }
+
+ void testSetXMPPStatus_Online() {
+ MenuletController testling(menulet);
+
+ testling.setXMPPStatus("You are connected", MenuletController::Online);
+
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]);
+ }
+
+
+ void testSetXMPPStatus_Offline() {
+ MenuletController testling(menulet);
+
+ testling.setXMPPStatus("You are not connected", MenuletController::Offline);
+
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("[Offline] You are not connected"), menulet->items[i++]);
+ }
+
+ void testSetUserNames() {
+ MenuletController testling(menulet);
+
+ std::vector<std::string> users;
+ users.push_back("Alice In Wonderland");
+ users.push_back("The Mad Hatter");
+ testling.setUserNames(users);
+
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("Online users:"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string(" Alice In Wonderland"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string(" The Mad Hatter"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ }
+
+ void testSetUserNames_NoUsers() {
+ MenuletController testling(menulet);
+
+ std::vector<std::string> users;
+ testling.setUserNames(users);
+
+ size_t i = 0;
+ CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]);
+ }
+
+ private:
+ struct FakeMenulet : public Menulet {
+ virtual void clear() {
+ items.clear();
+ }
+
+ virtual void addItem(const std::string& name, const std::string& icon = std::string()) {
+ std::string result;
+ if (!icon.empty()) {
+ result += "[" + icon + "] ";
+ }
+ result += name;
+ items.push_back(result);
+ }
+
+ virtual void addAboutItem() {
+ items.push_back("*About*");
+ }
+
+ virtual void addRestartItem() {
+ items.push_back("*Restart*");
+ }
+
+ virtual void addExitItem() {
+ items.push_back("*Exit*");
+ }
+
+ virtual void addSeparator() {
+ items.push_back("-");
+ }
+
+ virtual void setIcon(const std::string& i) {
+ icon = i;
+ }
+
+ std::vector<std::string> items;
+ std::string icon;
+ };
+
+ FakeMenulet* menulet;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MenuletControllerTest);
diff --git a/Slimber/VCardCollection.h b/Slimber/VCardCollection.h
index 0e7d27f..3295039 100644
--- a/Slimber/VCardCollection.h
+++ b/Slimber/VCardCollection.h
@@ -11,11 +11,11 @@
#include <Swiften/Elements/VCard.h>
namespace Swift {
- class VCardCollection {
- public:
- virtual ~VCardCollection();
+ class VCardCollection {
+ public:
+ virtual ~VCardCollection();
- virtual boost::shared_ptr<VCard> getOwnVCard() const = 0;
- virtual void setOwnVCard(boost::shared_ptr<VCard> vcard) = 0;
- };
+ virtual boost::shared_ptr<VCard> getOwnVCard() const = 0;
+ virtual void setOwnVCard(boost::shared_ptr<VCard> vcard) = 0;
+ };
}
diff --git a/Sluift/Completer.h b/Sluift/Completer.h
index 1e9defb..564c647 100644
--- a/Sluift/Completer.h
+++ b/Sluift/Completer.h
@@ -10,10 +10,10 @@
#include <vector>
namespace Swift {
- class Completer {
- public:
- virtual ~Completer();
+ class Completer {
+ public:
+ virtual ~Completer();
- virtual std::vector<std::string> getCompletions(const std::string& buffer, int start, int end) = 0;
- };
+ virtual std::vector<std::string> getCompletions(const std::string& buffer, int start, int end) = 0;
+ };
}
diff --git a/Sluift/Console.cpp b/Sluift/Console.cpp
index 623a38f..ef0b1a4 100644
--- a/Sluift/Console.cpp
+++ b/Sluift/Console.cpp
@@ -28,256 +28,256 @@ using namespace Swift;
* Adds the backtrace to the error message.
*/
static int traceback(lua_State* L) {
- if (!lua_isstring(L, 1)) {
- return 1;
- }
- lua_getglobal(L, "debug");
- if (!lua_istable(L, -1)) {
- lua_pop(L, 1);
- return 1;
- }
- lua_getfield(L, -1, "traceback");
- if (!lua_isfunction(L, -1)) {
- lua_pop(L, 2);
- return 1;
- }
- lua_pushvalue(L, 1);
- lua_pushinteger(L, 2);
- lua_call(L, 2, 1);
- return 1;
+ if (!lua_isstring(L, 1)) {
+ return 1;
+ }
+ lua_getglobal(L, "debug");
+ if (!lua_istable(L, -1)) {
+ lua_pop(L, 1);
+ return 1;
+ }
+ lua_getfield(L, -1, "traceback");
+ if (!lua_isfunction(L, -1)) {
+ lua_pop(L, 2);
+ return 1;
+ }
+ lua_pushvalue(L, 1);
+ lua_pushinteger(L, 2);
+ lua_call(L, 2, 1);
+ return 1;
}
Console::Console(lua_State* L, Terminal* terminal) : L(L), terminal(terminal), previousNumberOfReturnArguments(0) {
- terminal->setCompleter(this);
+ terminal->setCompleter(this);
}
Console::~Console() {
}
void Console::run() {
- while (true) {
- lua_settop(L, 0);
- try {
- if (!readCommand()) {
- return;
- }
- int result = call(L, 0, true);
- if (result != 0) {
- throw std::runtime_error(getErrorMessage());
- }
-
- // Clear the previous results
- for (int i = 0; i < previousNumberOfReturnArguments; ++i) {
- lua_pushnil(L);
- lua_setglobal(L, ("_" + boost::lexical_cast<std::string>(i+1)).c_str());
- }
-
- // Store the results
- for (int i = 0; i < lua_gettop(L); ++i) {
- lua_pushvalue(L, i+1);
- lua_setglobal(L, ("_" + boost::lexical_cast<std::string>(i+1)).c_str());
- }
- previousNumberOfReturnArguments = lua_gettop(L);
-
- // Print results
- if (lua_gettop(L) > 0) {
- lua_getglobal(L, "print");
- lua_insert(L, 1);
- if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) {
- throw std::runtime_error("Error calling 'print': " + getErrorMessage());
- }
- }
- }
- catch (const std::exception& e) {
- terminal->printError(e.what());
- }
- }
+ while (true) {
+ lua_settop(L, 0);
+ try {
+ if (!readCommand()) {
+ return;
+ }
+ int result = call(L, 0, true);
+ if (result != 0) {
+ throw std::runtime_error(getErrorMessage());
+ }
+
+ // Clear the previous results
+ for (int i = 0; i < previousNumberOfReturnArguments; ++i) {
+ lua_pushnil(L);
+ lua_setglobal(L, ("_" + boost::lexical_cast<std::string>(i+1)).c_str());
+ }
+
+ // Store the results
+ for (int i = 0; i < lua_gettop(L); ++i) {
+ lua_pushvalue(L, i+1);
+ lua_setglobal(L, ("_" + boost::lexical_cast<std::string>(i+1)).c_str());
+ }
+ previousNumberOfReturnArguments = lua_gettop(L);
+
+ // Print results
+ if (lua_gettop(L) > 0) {
+ lua_getglobal(L, "print");
+ lua_insert(L, 1);
+ if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) {
+ throw std::runtime_error("Error calling 'print': " + getErrorMessage());
+ }
+ }
+ }
+ catch (const std::exception& e) {
+ terminal->printError(e.what());
+ }
+ }
}
int Console::tryLoadCommand(const std::string& originalCommand) {
- std::string command = originalCommand;
+ std::string command = originalCommand;
- // Replace '=' by 'return' (for compatibility with Lua console)
- if (boost::algorithm::starts_with(command, "=")) {
- command = "return " + command.substr(1);
- }
+ // Replace '=' by 'return' (for compatibility with Lua console)
+ if (boost::algorithm::starts_with(command, "=")) {
+ command = "return " + command.substr(1);
+ }
- std::string commandAsExpression = "return " + command;
+ std::string commandAsExpression = "return " + command;
- // Try to load the command as an expression
- if (luaL_loadbuffer(L, commandAsExpression.c_str(), commandAsExpression.size(), "=stdin") == 0) {
- return 0;
- }
- lua_pop(L, 1);
+ // Try to load the command as an expression
+ if (luaL_loadbuffer(L, commandAsExpression.c_str(), commandAsExpression.size(), "=stdin") == 0) {
+ return 0;
+ }
+ lua_pop(L, 1);
- // Try to load the command as a regular command
- return luaL_loadbuffer(L, command.c_str(), command.size(), "=stdin");
+ // Try to load the command as a regular command
+ return luaL_loadbuffer(L, command.c_str(), command.size(), "=stdin");
}
bool Console::readCommand() {
- boost::optional<std::string> line = terminal->readLine(getPrompt(true));
- if (!line) {
- return false;
- }
- std::string command = *line;
- while (true) {
- int result = tryLoadCommand(command);
-
- // Check if we need to read more
- if (result == LUA_ERRSYNTAX) {
- std::string errorMessage(lua_tostring(L, -1));
- if (boost::algorithm::ends_with(errorMessage, "'<eof>'")) {
- lua_pop(L, 1);
-
- // Read another line
- boost::optional<std::string> line = terminal->readLine(getPrompt(false));
- if (!line) {
- return false;
- }
- command = command + "\n" + *line;
- continue;
- }
- }
- if (!command.empty()) {
- terminal->addToHistory(command);
- }
- if (result != 0) {
- throw std::runtime_error(getErrorMessage());
- }
- return true;
- }
+ boost::optional<std::string> line = terminal->readLine(getPrompt(true));
+ if (!line) {
+ return false;
+ }
+ std::string command = *line;
+ while (true) {
+ int result = tryLoadCommand(command);
+
+ // Check if we need to read more
+ if (result == LUA_ERRSYNTAX) {
+ std::string errorMessage(lua_tostring(L, -1));
+ if (boost::algorithm::ends_with(errorMessage, "'<eof>'")) {
+ lua_pop(L, 1);
+
+ // Read another line
+ boost::optional<std::string> line = terminal->readLine(getPrompt(false));
+ if (!line) {
+ return false;
+ }
+ command = command + "\n" + *line;
+ continue;
+ }
+ }
+ if (!command.empty()) {
+ terminal->addToHistory(command);
+ }
+ if (result != 0) {
+ throw std::runtime_error(getErrorMessage());
+ }
+ return true;
+ }
}
std::string Console::getErrorMessage() const {
- if (lua_isnil(L, -1)) {
- return "<null error>";
- }
- const char* errorMessage = lua_tostring(L, -1);
- return errorMessage ? errorMessage : "<error is not a string>";
+ if (lua_isnil(L, -1)) {
+ return "<null error>";
+ }
+ const char* errorMessage = lua_tostring(L, -1);
+ return errorMessage ? errorMessage : "<error is not a string>";
}
int Console::call(lua_State* L, int numberOfArguments, bool keepResult) {
- // Put traceback function on stack below call
- int tracebackIndex = lua_gettop(L) - numberOfArguments;
- lua_pushcfunction(L, traceback);
- lua_insert(L, tracebackIndex);
+ // Put traceback function on stack below call
+ int tracebackIndex = lua_gettop(L) - numberOfArguments;
+ lua_pushcfunction(L, traceback);
+ lua_insert(L, tracebackIndex);
- int result = lua_pcall(L, numberOfArguments, keepResult ? LUA_MULTRET : 0, tracebackIndex);
+ int result = lua_pcall(L, numberOfArguments, keepResult ? LUA_MULTRET : 0, tracebackIndex);
- // Remove traceback
- lua_remove(L, tracebackIndex);
+ // Remove traceback
+ lua_remove(L, tracebackIndex);
- return result;
+ return result;
}
std::string Console::getPrompt(bool firstLine) const {
- lua_getglobal(L,firstLine ? "_PROMPT" : "_PROMPT2");
- const char* rawPrompt = lua_tostring(L, -1);
- std::string prompt;
- if (rawPrompt) {
- prompt = std::string(rawPrompt);
- }
- else {
- prompt = firstLine ? "> " : ">> ";
- }
- lua_pop(L, 1);
- return prompt;
+ lua_getglobal(L,firstLine ? "_PROMPT" : "_PROMPT2");
+ const char* rawPrompt = lua_tostring(L, -1);
+ std::string prompt;
+ if (rawPrompt) {
+ prompt = std::string(rawPrompt);
+ }
+ else {
+ prompt = firstLine ? "> " : ">> ";
+ }
+ lua_pop(L, 1);
+ return prompt;
}
static void addMatchingTableKeys(lua_State* L, const std::string& match, std::vector<std::string>& result) {
- for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
- const char* rawKey = lua_tostring(L, -2);
- if (rawKey) {
- std::string key(rawKey);
- if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) {
- result.push_back(key);
- }
- }
- }
+ for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
+ const char* rawKey = lua_tostring(L, -2);
+ if (rawKey) {
+ std::string key(rawKey);
+ if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) {
+ result.push_back(key);
+ }
+ }
+ }
}
static void addMatchingTableValues(lua_State* L, const std::string& match, std::vector<std::string>& result) {
- for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
- const char* rawValue = lua_tostring(L, -1);
- if (rawValue) {
- std::string key(rawValue);
- if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) {
- result.push_back(key);
- }
- }
- }
+ for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
+ const char* rawValue = lua_tostring(L, -1);
+ if (rawValue) {
+ std::string key(rawValue);
+ if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) {
+ result.push_back(key);
+ }
+ }
+ }
}
std::vector<std::string> Console::getCompletions(const std::string& input, int start, int end) {
- std::string prefix = input.substr(boost::numeric_cast<size_t>(start), boost::numeric_cast<size_t>(end - start));
-
- std::vector<std::string> tokens;
- if (end) {
- tokens = Lua::tokenize(input.substr(0, boost::numeric_cast<size_t>(end)));
- }
-
- // Don't autocomplete strings
- if (!tokens.empty() && ((*tokens.rbegin())[0] == '\'' || (*tokens.rbegin())[0] == '"')) {
- return std::vector<std::string>();
- }
-
- std::vector<std::string> context;
- for (std::vector<std::string>::reverse_iterator i = tokens.rbegin(); i != tokens.rend(); ++i) {
- if (std::isalpha((*i)[0]) || (*i)[0] == '_') {
- if (i != tokens.rbegin()) {
- context.push_back(*i);
- }
- }
- else if (*i != "." && *i != ":") {
- break;
- }
- }
-
- // Drill into context
- int top = lua_gettop(L);
- lua_pushglobaltable(L);
- for (std::vector<std::string>::reverse_iterator i = context.rbegin(); i != context.rend(); ++i) {
- if (lua_istable(L, -1) || lua_isuserdata(L, -1)) {
- lua_getfield(L, -1, i->c_str());
- if (!lua_isnil(L, 1)) {
- continue;
- }
- }
- lua_settop(L, top);
- return std::vector<std::string>();
- }
-
- // Collect all keys from the table
- std::vector<std::string> result;
- if (lua_istable(L, -1)) {
- addMatchingTableKeys(L, prefix, result);
- }
-
- // Collect all keys from the metatable
- if (lua_getmetatable(L, -1)) {
- lua_getfield(L, -1, "__index");
- if (lua_istable(L, -1)) {
- addMatchingTableKeys(L, prefix, result);
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "_completions");
- if (lua_isfunction(L, -1)) {
- lua_pushvalue(L, -3);
- if (lua_pcall(L, 1, 1, 0) != 0) {
- throw std::runtime_error("Error calling '_completions': " + getErrorMessage());
- }
- }
- if (lua_istable(L, -1)) {
- addMatchingTableValues(L, prefix, result);
- }
- lua_pop(L, 2);
- }
-
- lua_settop(L, top);
-
- return result;
+ std::string prefix = input.substr(boost::numeric_cast<size_t>(start), boost::numeric_cast<size_t>(end - start));
+
+ std::vector<std::string> tokens;
+ if (end) {
+ tokens = Lua::tokenize(input.substr(0, boost::numeric_cast<size_t>(end)));
+ }
+
+ // Don't autocomplete strings
+ if (!tokens.empty() && ((*tokens.rbegin())[0] == '\'' || (*tokens.rbegin())[0] == '"')) {
+ return std::vector<std::string>();
+ }
+
+ std::vector<std::string> context;
+ for (std::vector<std::string>::reverse_iterator i = tokens.rbegin(); i != tokens.rend(); ++i) {
+ if (std::isalpha((*i)[0]) || (*i)[0] == '_') {
+ if (i != tokens.rbegin()) {
+ context.push_back(*i);
+ }
+ }
+ else if (*i != "." && *i != ":") {
+ break;
+ }
+ }
+
+ // Drill into context
+ int top = lua_gettop(L);
+ lua_pushglobaltable(L);
+ for (std::vector<std::string>::reverse_iterator i = context.rbegin(); i != context.rend(); ++i) {
+ if (lua_istable(L, -1) || lua_isuserdata(L, -1)) {
+ lua_getfield(L, -1, i->c_str());
+ if (!lua_isnil(L, 1)) {
+ continue;
+ }
+ }
+ lua_settop(L, top);
+ return std::vector<std::string>();
+ }
+
+ // Collect all keys from the table
+ std::vector<std::string> result;
+ if (lua_istable(L, -1)) {
+ addMatchingTableKeys(L, prefix, result);
+ }
+
+ // Collect all keys from the metatable
+ if (lua_getmetatable(L, -1)) {
+ lua_getfield(L, -1, "__index");
+ if (lua_istable(L, -1)) {
+ addMatchingTableKeys(L, prefix, result);
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "_completions");
+ if (lua_isfunction(L, -1)) {
+ lua_pushvalue(L, -3);
+ if (lua_pcall(L, 1, 1, 0) != 0) {
+ throw std::runtime_error("Error calling '_completions': " + getErrorMessage());
+ }
+ }
+ if (lua_istable(L, -1)) {
+ addMatchingTableValues(L, prefix, result);
+ }
+ lua_pop(L, 2);
+ }
+
+ lua_settop(L, top);
+
+ return result;
}
diff --git a/Sluift/Console.h b/Sluift/Console.h
index 4f444fe..d1687bf 100644
--- a/Sluift/Console.h
+++ b/Sluift/Console.h
@@ -17,28 +17,28 @@
struct lua_State;
namespace Swift {
- class Terminal;
+ class Terminal;
- class Console : public Completer {
- public:
- Console(lua_State* L, Terminal* terminal);
- virtual ~Console();
+ class Console : public Completer {
+ public:
+ Console(lua_State* L, Terminal* terminal);
+ virtual ~Console();
- void run();
+ void run();
- static int call(lua_State* L, int numberOfArguments, bool keepResult);
+ static int call(lua_State* L, int numberOfArguments, bool keepResult);
- private:
- std::string getPrompt(bool firstLine) const;
- std::string getErrorMessage() const;
- bool readCommand();
- int tryLoadCommand(const std::string& command);
+ private:
+ std::string getPrompt(bool firstLine) const;
+ std::string getErrorMessage() const;
+ bool readCommand();
+ int tryLoadCommand(const std::string& command);
- virtual std::vector<std::string> getCompletions(const std::string&, int start, int end) SWIFTEN_OVERRIDE;
+ virtual std::vector<std::string> getCompletions(const std::string&, int start, int end) SWIFTEN_OVERRIDE;
- private:
- lua_State* L;
- Terminal* terminal;
- int previousNumberOfReturnArguments;
- };
+ private:
+ lua_State* L;
+ Terminal* terminal;
+ int previousNumberOfReturnArguments;
+ };
}
diff --git a/Sluift/EditlineTerminal.cpp b/Sluift/EditlineTerminal.cpp
index 4d48bd7..fc62142 100644
--- a/Sluift/EditlineTerminal.cpp
+++ b/Sluift/EditlineTerminal.cpp
@@ -27,55 +27,55 @@ static EditlineTerminal* globalInstance = NULL;
static int completionStart = -1;
static int completionEnd = -1;
-#if defined(SWIFTEN_PLATFORM_WINDOWS)
+#if defined(SWIFTEN_PLATFORM_WINDOWS)
static char* getEmptyCompletions(const char*, int) {
#else
static int getEmptyCompletions(const char*, int) {
#endif
- return 0;
+ return 0;
}
static char* getCompletions(const char*, int state) {
- rl_completion_append_character = 0;
+ rl_completion_append_character = 0;
#if RL_READLINE_VERSION >= 0x0600
- rl_completion_suppress_append = 1;
+ rl_completion_suppress_append = 1;
#endif
- static std::vector<std::string> completions;
- if (state == 0) {
- assert(globalInstance);
- completions.clear();
- if (globalInstance->getCompleter()) {
- completions = globalInstance->getCompleter()->getCompletions(rl_line_buffer, completionStart, completionEnd);
- }
- }
- if (boost::numeric_cast<size_t>(state) >= completions.size()) {
- return 0;
- }
- return strdup(completions[boost::numeric_cast<size_t>(state)].c_str());
+ static std::vector<std::string> completions;
+ if (state == 0) {
+ assert(globalInstance);
+ completions.clear();
+ if (globalInstance->getCompleter()) {
+ completions = globalInstance->getCompleter()->getCompletions(rl_line_buffer, completionStart, completionEnd);
+ }
+ }
+ if (boost::numeric_cast<size_t>(state) >= completions.size()) {
+ return 0;
+ }
+ return strdup(completions[boost::numeric_cast<size_t>(state)].c_str());
}
static char** getAttemptedCompletions(const char* text, int start, int end) {
- completionStart = start;
- completionEnd = end;
- return rl_completion_matches(text, getCompletions);
+ completionStart = start;
+ completionEnd = end;
+ return rl_completion_matches(text, getCompletions);
}
EditlineTerminal& EditlineTerminal::getInstance() {
- static EditlineTerminal instance;
- globalInstance = &instance;
- return instance;
+ static EditlineTerminal instance;
+ globalInstance = &instance;
+ return instance;
}
EditlineTerminal::EditlineTerminal() {
- rl_attempted_completion_function = getAttemptedCompletions;
- rl_completion_entry_function = getEmptyCompletions; // Fallback. Do nothing.
+ rl_attempted_completion_function = getAttemptedCompletions;
+ rl_completion_entry_function = getEmptyCompletions; // Fallback. Do nothing.
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- // rl_basic_word_break is a cons char[] in MinGWEditLine.
- // This one seems to work, although it doesn't on OS X for some reason.
- rl_completer_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}");
+ // rl_basic_word_break is a cons char[] in MinGWEditLine.
+ // This one seems to work, although it doesn't on OS X for some reason.
+ rl_completer_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}");
#else
- rl_basic_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}");
+ rl_basic_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}");
#endif
}
@@ -83,19 +83,19 @@ EditlineTerminal::~EditlineTerminal() {
}
void EditlineTerminal::printError(const std::string& message) {
- std::cout << message << std::endl;
+ std::cout << message << std::endl;
}
boost::optional<std::string> EditlineTerminal::readLine(const std::string& prompt) {
- const char* line = readline(prompt.c_str());
- return line ? std::string(line) : boost::optional<std::string>();
+ const char* line = readline(prompt.c_str());
+ return line ? std::string(line) : boost::optional<std::string>();
}
void EditlineTerminal::addToHistory(const std::string& line) {
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- // MinGWEditLine copies the string, so this is safe
- add_history(const_cast<char*>(line.c_str()));
+ // MinGWEditLine copies the string, so this is safe
+ add_history(const_cast<char*>(line.c_str()));
#else
- add_history(line.c_str());
+ add_history(line.c_str());
#endif
}
diff --git a/Sluift/EditlineTerminal.h b/Sluift/EditlineTerminal.h
index 3919c46..ec4cf63 100644
--- a/Sluift/EditlineTerminal.h
+++ b/Sluift/EditlineTerminal.h
@@ -11,16 +11,16 @@
#include <Sluift/Terminal.h>
namespace Swift {
- class EditlineTerminal : public Terminal {
- public:
- static EditlineTerminal& getInstance();
+ class EditlineTerminal : public Terminal {
+ public:
+ static EditlineTerminal& getInstance();
- private:
- EditlineTerminal();
- virtual ~EditlineTerminal();
+ private:
+ EditlineTerminal();
+ virtual ~EditlineTerminal();
- virtual boost::optional<std::string> readLine(const std::string& prompt) SWIFTEN_OVERRIDE;
- virtual void printError(const std::string& message) SWIFTEN_OVERRIDE;
- virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE;
- };
+ virtual boost::optional<std::string> readLine(const std::string& prompt) SWIFTEN_OVERRIDE;
+ virtual void printError(const std::string& message) SWIFTEN_OVERRIDE;
+ virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/BodyConvertor.cpp b/Sluift/ElementConvertors/BodyConvertor.cpp
index 8c1a6cd..4593f01 100644
--- a/Sluift/ElementConvertors/BodyConvertor.cpp
+++ b/Sluift/ElementConvertors/BodyConvertor.cpp
@@ -21,17 +21,17 @@ BodyConvertor::~BodyConvertor() {
}
boost::shared_ptr<Body> BodyConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Body> result = boost::make_shared<Body>();
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "text")) {
- result->setText(*value);
- }
- return result;
+ boost::shared_ptr<Body> result = boost::make_shared<Body>();
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "text")) {
+ result->setText(*value);
+ }
+ return result;
}
void BodyConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Body> payload) {
- lua_createtable(L, 0, 0);
- if (!payload->getText().empty()) {
- lua_pushstring(L, payload->getText().c_str());
- lua_setfield(L, -2, "text");
- }
+ lua_createtable(L, 0, 0);
+ if (!payload->getText().empty()) {
+ lua_pushstring(L, payload->getText().c_str());
+ lua_setfield(L, -2, "text");
+ }
}
diff --git a/Sluift/ElementConvertors/BodyConvertor.h b/Sluift/ElementConvertors/BodyConvertor.h
index 6b7b3c7..75d23e7 100644
--- a/Sluift/ElementConvertors/BodyConvertor.h
+++ b/Sluift/ElementConvertors/BodyConvertor.h
@@ -12,14 +12,14 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class BodyConvertor : public GenericLuaElementConvertor<Body> {
- public:
- BodyConvertor();
- virtual ~BodyConvertor();
+ class BodyConvertor : public GenericLuaElementConvertor<Body> {
+ public:
+ BodyConvertor();
+ virtual ~BodyConvertor();
- virtual boost::shared_ptr<Body> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Body>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Body> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Body>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/CommandConvertor.cpp b/Sluift/ElementConvertors/CommandConvertor.cpp
index d3a8739..272e5d1 100644
--- a/Sluift/ElementConvertors/CommandConvertor.cpp
+++ b/Sluift/ElementConvertors/CommandConvertor.cpp
@@ -20,179 +20,179 @@
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;
+ 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 "";
+ 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"),
- convertors(convertors) {
+CommandConvertor::CommandConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<Command>("command"),
+ convertors(convertors) {
}
CommandConvertor::~CommandConvertor() {
}
boost::shared_ptr<Command> CommandConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Command> result = boost::make_shared<Command>();
-
- lua_getfield(L, -1, "node");
- if (!lua_isnil(L, -1)) {
- result->setNode(std::string(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "session_id");
- if (!lua_isnil(L, -1)) {
- result->setSessionID(std::string(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "status");
- if (!lua_isnil(L, -1)) {
- std::string statusText = Lua::checkString(L, -1);
- Command::Status status = Command::NoStatus;
- if (statusText == "executing") { status = Command::Executing; }
- else if (statusText == "completed") { status = Command::Completed; }
- else if (statusText == "canceled") { status = Command::Canceled; }
- result->setStatus(status);
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "action");
- if (!lua_isnil(L, -1)) {
- result->setAction(convertActionFromString(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "execute_action");
- if (!lua_isnil(L, -1)) {
- result->setExecuteAction(convertActionFromString(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "available_actions");
- if (!lua_isnil(L, -1)) {
- Lua::checkType(L, -1, LUA_TTABLE);
- lua_pushnil(L);
- for (lua_pushnil(L); lua_next(L, -2) != 0; ) {
- result->addAvailableAction(convertActionFromString(Lua::checkString(L, -1)));
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "notes");
- if (!lua_isnil(L, -1)) {
- Lua::checkType(L, -1, LUA_TTABLE);
- lua_pushnil(L);
- for (lua_pushnil(L); lua_next(L, -2) != 0; ) {
- Lua::checkType(L, -1, LUA_TTABLE);
- std::string note;
- lua_getfield(L, -1, "note");
- if (!lua_isnil(L, -1)) {
- note = Lua::checkString(L, -1);
- }
- lua_pop(L, 1);
-
- Command::Note::Type noteType = Command::Note::Info;
- lua_getfield(L, -1, "type");
- if (!lua_isnil(L, -1)) {
- std::string type = Lua::checkString(L, -1);
- if (type == "info") { noteType = Command::Note::Info; }
- else if (type == "warn") { noteType = Command::Note::Warn; }
- else if (type == "error") { noteType = Command::Note::Error; }
- }
- lua_pop(L, 1);
-
- result->addNote(Command::Note(note, noteType));
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "form");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> form = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setForm(form);
- }
- }
- lua_pop(L, 1);
-
- return result;
+ boost::shared_ptr<Command> result = boost::make_shared<Command>();
+
+ lua_getfield(L, -1, "node");
+ if (!lua_isnil(L, -1)) {
+ result->setNode(std::string(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "session_id");
+ if (!lua_isnil(L, -1)) {
+ result->setSessionID(std::string(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "status");
+ if (!lua_isnil(L, -1)) {
+ std::string statusText = Lua::checkString(L, -1);
+ Command::Status status = Command::NoStatus;
+ if (statusText == "executing") { status = Command::Executing; }
+ else if (statusText == "completed") { status = Command::Completed; }
+ else if (statusText == "canceled") { status = Command::Canceled; }
+ result->setStatus(status);
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "action");
+ if (!lua_isnil(L, -1)) {
+ result->setAction(convertActionFromString(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "execute_action");
+ if (!lua_isnil(L, -1)) {
+ result->setExecuteAction(convertActionFromString(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "available_actions");
+ if (!lua_isnil(L, -1)) {
+ Lua::checkType(L, -1, LUA_TTABLE);
+ lua_pushnil(L);
+ for (lua_pushnil(L); lua_next(L, -2) != 0; ) {
+ result->addAvailableAction(convertActionFromString(Lua::checkString(L, -1)));
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "notes");
+ if (!lua_isnil(L, -1)) {
+ Lua::checkType(L, -1, LUA_TTABLE);
+ lua_pushnil(L);
+ for (lua_pushnil(L); lua_next(L, -2) != 0; ) {
+ Lua::checkType(L, -1, LUA_TTABLE);
+ std::string note;
+ lua_getfield(L, -1, "note");
+ if (!lua_isnil(L, -1)) {
+ note = Lua::checkString(L, -1);
+ }
+ lua_pop(L, 1);
+
+ Command::Note::Type noteType = Command::Note::Info;
+ lua_getfield(L, -1, "type");
+ if (!lua_isnil(L, -1)) {
+ std::string type = Lua::checkString(L, -1);
+ if (type == "info") { noteType = Command::Note::Info; }
+ else if (type == "warn") { noteType = Command::Note::Warn; }
+ else if (type == "error") { noteType = Command::Note::Error; }
+ }
+ lua_pop(L, 1);
+
+ result->addNote(Command::Note(note, noteType));
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "form");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> form = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setForm(form);
+ }
+ }
+ lua_pop(L, 1);
+
+ return result;
}
void CommandConvertor::doConvertToLua(lua_State* L, boost::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()) {
- 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()) {
- 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");
- }
+ 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()) {
+ 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()) {
+ 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/CommandConvertor.h b/Sluift/ElementConvertors/CommandConvertor.h
index e129fd9..97b3f2f 100644
--- a/Sluift/ElementConvertors/CommandConvertor.h
+++ b/Sluift/ElementConvertors/CommandConvertor.h
@@ -12,17 +12,17 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class CommandConvertor : public GenericLuaElementConvertor<Command> {
- public:
- CommandConvertor(LuaElementConvertors* convertors);
- virtual ~CommandConvertor();
+ class CommandConvertor : public GenericLuaElementConvertor<Command> {
+ public:
+ CommandConvertor(LuaElementConvertors* convertors);
+ virtual ~CommandConvertor();
- virtual boost::shared_ptr<Command> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Command>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Command> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Command>) SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/DOMElementConvertor.cpp b/Sluift/ElementConvertors/DOMElementConvertor.cpp
index 347bbfd..85b505d 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DOMElementConvertor.cpp
@@ -30,133 +30,133 @@
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()) {
- 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++;
- }
-
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE {
- lua_checkstack(L, 2);
- lua_pushnumber(L, currentIndex);
- lua_pushstring(L, data.c_str());
- lua_settable(L, -3);
- currentIndex++;
- }
-
- private:
- lua_State* L;
- std::vector<int> indexStack;
- int currentIndex;
- };
-
- std::string serializeElement(lua_State* L) {
- std::string tag;
- lua_getfield(L, -1, "tag");
- if (lua_isstring(L, -1)) {
- tag = lua_tostring(L, -1);
- }
- lua_pop(L, 1);
-
- std::string ns;
- lua_getfield(L, -1, "ns");
- if (lua_isstring(L, -1)) {
- ns = lua_tostring(L, -1);
- }
- lua_pop(L, 1);
-
- XMLElement element(tag, ns);
-
- lua_getfield(L, -1, "attributes");
- if (lua_istable(L, -1)) {
- int index = Lua::absoluteOffset(L, -1);
- for (lua_pushnil(L); lua_next(L, index) != 0; ) {
- if (lua_istable(L, -1)) {
- std::string attributeName;
- lua_getfield(L, -1, "name");
- if (lua_isstring(L, -1)) {
- attributeName = lua_tostring(L, -1);
- }
- lua_pop(L, 1);
-
- std::string attributeValue;
- lua_getfield(L, -1, "value");
- if (lua_isstring(L, -1)) {
- attributeValue = lua_tostring(L, -1);
- }
- lua_pop(L, 1);
-
- if (!attributeName.empty()) {
- element.setAttribute(attributeName, attributeValue);
- }
- }
- lua_pop(L, 1); // value
- }
- }
- lua_pop(L, 1); // children
-
- lua_getfield(L, -1, "children");
- if (lua_istable(L, -1)) {
- int index = Lua::absoluteOffset(L, -1);
- for (lua_pushnil(L); lua_next(L, index) != 0; ) {
- if (lua_isstring(L, -1)) {
- element.addNode(boost::make_shared<XMLTextNode>(lua_tostring(L, -1)));
- }
- else if (lua_istable(L, -1)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializeElement(L)));
- }
- lua_pop(L, 1); // value
- }
- }
- lua_pop(L, 1); // children
-
- return element.serialize();
- }
+ 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()) {
+ 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++;
+ }
+
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE {
+ lua_checkstack(L, 2);
+ lua_pushnumber(L, currentIndex);
+ lua_pushstring(L, data.c_str());
+ lua_settable(L, -3);
+ currentIndex++;
+ }
+
+ private:
+ lua_State* L;
+ std::vector<int> indexStack;
+ int currentIndex;
+ };
+
+ std::string serializeElement(lua_State* L) {
+ std::string tag;
+ lua_getfield(L, -1, "tag");
+ if (lua_isstring(L, -1)) {
+ tag = lua_tostring(L, -1);
+ }
+ lua_pop(L, 1);
+
+ std::string ns;
+ lua_getfield(L, -1, "ns");
+ if (lua_isstring(L, -1)) {
+ ns = lua_tostring(L, -1);
+ }
+ lua_pop(L, 1);
+
+ XMLElement element(tag, ns);
+
+ lua_getfield(L, -1, "attributes");
+ if (lua_istable(L, -1)) {
+ int index = Lua::absoluteOffset(L, -1);
+ for (lua_pushnil(L); lua_next(L, index) != 0; ) {
+ if (lua_istable(L, -1)) {
+ std::string attributeName;
+ lua_getfield(L, -1, "name");
+ if (lua_isstring(L, -1)) {
+ attributeName = lua_tostring(L, -1);
+ }
+ lua_pop(L, 1);
+
+ std::string attributeValue;
+ lua_getfield(L, -1, "value");
+ if (lua_isstring(L, -1)) {
+ attributeValue = lua_tostring(L, -1);
+ }
+ lua_pop(L, 1);
+
+ if (!attributeName.empty()) {
+ element.setAttribute(attributeName, attributeValue);
+ }
+ }
+ lua_pop(L, 1); // value
+ }
+ }
+ lua_pop(L, 1); // children
+
+ lua_getfield(L, -1, "children");
+ if (lua_istable(L, -1)) {
+ int index = Lua::absoluteOffset(L, -1);
+ for (lua_pushnil(L); lua_next(L, index) != 0; ) {
+ if (lua_isstring(L, -1)) {
+ element.addNode(boost::make_shared<XMLTextNode>(lua_tostring(L, -1)));
+ }
+ else if (lua_istable(L, -1)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(serializeElement(L)));
+ }
+ lua_pop(L, 1); // value
+ }
+ }
+ lua_pop(L, 1); // children
+
+ return element.serialize();
+ }
}
DOMElementConvertor::DOMElementConvertor() {
@@ -166,39 +166,39 @@ DOMElementConvertor::~DOMElementConvertor() {
}
boost::shared_ptr<Element> DOMElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) {
- if (!lua_istable(L, index) || type != "dom") {
- return boost::shared_ptr<Payload>();
- }
- return boost::make_shared<RawXMLPayload>(serializeElement(L).c_str());
+ if (!lua_istable(L, index) || type != "dom") {
+ return boost::shared_ptr<Payload>();
+ }
+ return boost::make_shared<RawXMLPayload>(serializeElement(L).c_str());
}
boost::optional<std::string> DOMElementConvertor::convertToLua(
- lua_State* L, boost::shared_ptr<Element> element) {
- // Serialize payload to XML
- boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
- if (!payload) {
- return boost::optional<std::string>();
- }
-
- PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
- assert(serializer);
- std::string serializedPayload = serializer->serialize(payload);
-
- lua_newtable(L);
-
- // Parse the payload again
- ParserClient parserClient(L);
- boost::shared_ptr<XMLParser> parser(parsers.createXMLParser(&parserClient));
- bool result = parser->parse(serializedPayload);
- assert(result);
-
- // There can only be one element, so stripping the list
- lua_pushnil(L);
- lua_next(L, -2);
- Lua::registerTableToString(L, -1);
-
- lua_replace(L, -3);
- lua_settop(L, -2);
-
- return std::string("dom");
+ lua_State* L, boost::shared_ptr<Element> element) {
+ // Serialize payload to XML
+ boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
+ if (!payload) {
+ return boost::optional<std::string>();
+ }
+
+ PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
+ assert(serializer);
+ std::string serializedPayload = serializer->serialize(payload);
+
+ lua_newtable(L);
+
+ // Parse the payload again
+ ParserClient parserClient(L);
+ boost::shared_ptr<XMLParser> parser(parsers.createXMLParser(&parserClient));
+ bool result = parser->parse(serializedPayload);
+ assert(result);
+
+ // There can only be one element, so stripping the list
+ lua_pushnil(L);
+ lua_next(L, -2);
+ Lua::registerTableToString(L, -1);
+
+ lua_replace(L, -3);
+ lua_settop(L, -2);
+
+ return std::string("dom");
}
diff --git a/Sluift/ElementConvertors/DOMElementConvertor.h b/Sluift/ElementConvertors/DOMElementConvertor.h
index 550bc3b..0d20251 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.h
+++ b/Sluift/ElementConvertors/DOMElementConvertor.h
@@ -13,16 +13,16 @@
#include <Sluift/LuaElementConvertor.h>
namespace Swift {
- class DOMElementConvertor : public LuaElementConvertor {
- public:
- DOMElementConvertor();
- virtual ~DOMElementConvertor();
+ class DOMElementConvertor : public LuaElementConvertor {
+ public:
+ DOMElementConvertor();
+ virtual ~DOMElementConvertor();
- virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
- virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
- private:
- PlatformXMLParserFactory parsers;
- FullPayloadSerializerCollection serializers;
- };
+ private:
+ PlatformXMLParserFactory parsers;
+ FullPayloadSerializerCollection serializers;
+ };
}
diff --git a/Sluift/ElementConvertors/DefaultElementConvertor.cpp b/Sluift/ElementConvertors/DefaultElementConvertor.cpp
index a1e27fa..8353207 100644
--- a/Sluift/ElementConvertors/DefaultElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DefaultElementConvertor.cpp
@@ -19,12 +19,12 @@ DefaultElementConvertor::~DefaultElementConvertor() {
}
boost::shared_ptr<Element> DefaultElementConvertor::convertFromLua(lua_State*, int, const std::string& type) {
- std::cerr << "Warning: Unable to convert type '" << type << "'" << std::endl;
- return boost::shared_ptr<Element>();
+ std::cerr << "Warning: Unable to convert type '" << type << "'" << std::endl;
+ return boost::shared_ptr<Element>();
}
boost::optional<std::string> DefaultElementConvertor::convertToLua(lua_State*, boost::shared_ptr<Element>) {
- // Should have been handled by the raw XML convertor
- assert(false);
- return NO_RESULT;
+ // Should have been handled by the raw XML convertor
+ assert(false);
+ return NO_RESULT;
}
diff --git a/Sluift/ElementConvertors/DefaultElementConvertor.h b/Sluift/ElementConvertors/DefaultElementConvertor.h
index e08bb98..8f57e4f 100644
--- a/Sluift/ElementConvertors/DefaultElementConvertor.h
+++ b/Sluift/ElementConvertors/DefaultElementConvertor.h
@@ -11,12 +11,12 @@
#include <Sluift/LuaElementConvertor.h>
namespace Swift {
- class DefaultElementConvertor : public LuaElementConvertor {
- public:
- DefaultElementConvertor();
- virtual ~DefaultElementConvertor();
+ class DefaultElementConvertor : public LuaElementConvertor {
+ public:
+ DefaultElementConvertor();
+ virtual ~DefaultElementConvertor();
- virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
- virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/DelayConvertor.cpp b/Sluift/ElementConvertors/DelayConvertor.cpp
index a2ea132..b59744b 100644
--- a/Sluift/ElementConvertors/DelayConvertor.cpp
+++ b/Sluift/ElementConvertors/DelayConvertor.cpp
@@ -24,27 +24,27 @@ DelayConvertor::~DelayConvertor() {
}
boost::shared_ptr<Delay> DelayConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Delay> result = boost::make_shared<Delay>();
- lua_getfield(L, -1, "stamp");
- if (lua_isstring(L, -1)) {
- result->setStamp(stringToDateTime(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "from");
- if (lua_isstring(L, -1)) {
- result->setFrom(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<Delay> result = boost::make_shared<Delay>();
+ lua_getfield(L, -1, "stamp");
+ if (lua_isstring(L, -1)) {
+ result->setStamp(stringToDateTime(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "from");
+ if (lua_isstring(L, -1)) {
+ result->setFrom(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ return result;
}
void DelayConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Delay> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getFrom()) {
- lua_pushstring(L, (*payload->getFrom()).toString().c_str());
- lua_setfield(L, -2, "from");
- }
- lua_pushstring(L, dateTimeToString(payload->getStamp()).c_str());
- lua_setfield(L, -2, "stamp");
+ lua_createtable(L, 0, 0);
+ if (payload->getFrom()) {
+ lua_pushstring(L, (*payload->getFrom()).toString().c_str());
+ lua_setfield(L, -2, "from");
+ }
+ lua_pushstring(L, dateTimeToString(payload->getStamp()).c_str());
+ lua_setfield(L, -2, "stamp");
}
diff --git a/Sluift/ElementConvertors/DelayConvertor.h b/Sluift/ElementConvertors/DelayConvertor.h
index fed032f..064406c 100644
--- a/Sluift/ElementConvertors/DelayConvertor.h
+++ b/Sluift/ElementConvertors/DelayConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class DelayConvertor : public GenericLuaElementConvertor<Delay> {
- public:
- DelayConvertor();
- virtual ~DelayConvertor();
+ class DelayConvertor : public GenericLuaElementConvertor<Delay> {
+ public:
+ DelayConvertor();
+ virtual ~DelayConvertor();
- virtual boost::shared_ptr<Delay> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Delay>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Delay> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Delay>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
index 4ebd6a3..fc48e6c 100644
--- a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
+++ b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
@@ -22,97 +22,97 @@ DiscoInfoConvertor::~DiscoInfoConvertor() {
}
boost::shared_ptr<DiscoInfo> DiscoInfoConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<DiscoInfo> result = boost::make_shared<DiscoInfo>();
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "node")) {
- result->setNode(*value);
- }
-
- lua_getfield(L, -1, "identities");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- result->addIdentity(DiscoInfo::Identity(
- Lua::getStringField(L, -1, "name").get_value_or(""),
- Lua::getStringField(L, -1, "category").get_value_or("client"),
- Lua::getStringField(L, -1, "type").get_value_or("pc"),
- Lua::getStringField(L, -1, "language").get_value_or("")));
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "features");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addFeature(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
-
- // TODO: Extension
-
- return result;
+ boost::shared_ptr<DiscoInfo> result = boost::make_shared<DiscoInfo>();
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "node")) {
+ result->setNode(*value);
+ }
+
+ lua_getfield(L, -1, "identities");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ result->addIdentity(DiscoInfo::Identity(
+ Lua::getStringField(L, -1, "name").get_value_or(""),
+ Lua::getStringField(L, -1, "category").get_value_or("client"),
+ Lua::getStringField(L, -1, "type").get_value_or("pc"),
+ Lua::getStringField(L, -1, "language").get_value_or("")));
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "features");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addFeature(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+
+ // TODO: Extension
+
+ return result;
}
void DiscoInfoConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<DiscoInfo> payload) {
- lua_newtable(L);
- if (!payload->getNode().empty()) {
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- }
-
- const std::vector<DiscoInfo::Identity>& identities = payload->getIdentities();
- if (!identities.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(identities.size()), 0);
- for (size_t i = 0; i < identities.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!identities[i].getName().empty()) {
- lua_pushstring(L, identities[i].getName().c_str());
- lua_setfield(L, -2, "name");
- }
- if (!identities[i].getCategory().empty()) {
- lua_pushstring(L, identities[i].getCategory().c_str());
- lua_setfield(L, -2, "category");
- }
- if (!identities[i].getType().empty()) {
- lua_pushstring(L, identities[i].getType().c_str());
- lua_setfield(L, -2, "type");
- }
- if (!identities[i].getLanguage().empty()) {
- lua_pushstring(L, identities[i].getLanguage().c_str());
- lua_setfield(L, -2, "language");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "identities");
- }
-
- const std::vector<std::string>& features = payload->getFeatures();
- if (!features.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(features.size()), 0);
- for (size_t i = 0; i < features.size(); ++i) {
- lua_pushstring(L, features[i].c_str());
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "features");
- }
-
- // TODO: Extension
+ lua_newtable(L);
+ if (!payload->getNode().empty()) {
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ }
+
+ const std::vector<DiscoInfo::Identity>& identities = payload->getIdentities();
+ if (!identities.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(identities.size()), 0);
+ for (size_t i = 0; i < identities.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!identities[i].getName().empty()) {
+ lua_pushstring(L, identities[i].getName().c_str());
+ lua_setfield(L, -2, "name");
+ }
+ if (!identities[i].getCategory().empty()) {
+ lua_pushstring(L, identities[i].getCategory().c_str());
+ lua_setfield(L, -2, "category");
+ }
+ if (!identities[i].getType().empty()) {
+ lua_pushstring(L, identities[i].getType().c_str());
+ lua_setfield(L, -2, "type");
+ }
+ if (!identities[i].getLanguage().empty()) {
+ lua_pushstring(L, identities[i].getLanguage().c_str());
+ lua_setfield(L, -2, "language");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "identities");
+ }
+
+ const std::vector<std::string>& features = payload->getFeatures();
+ if (!features.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(features.size()), 0);
+ for (size_t i = 0; i < features.size(); ++i) {
+ lua_pushstring(L, features[i].c_str());
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "features");
+ }
+
+ // TODO: Extension
}
boost::optional<LuaElementConvertor::Documentation> DiscoInfoConvertor::getDocumentation() const {
- return Documentation(
- "DiscoInfo",
- "Represents `disco#info` service discovery data.\n\n"
- "This table has the following structure:\n\n"
- "- `node`: string\n"
- "- `identities`: array(table)\n"
- " - `name`: string\n"
- " - `category`: string\n"
- " - `type`: string\n"
- " - `language`: string\n"
- "- `features`: array(string)\n"
- );
+ return Documentation(
+ "DiscoInfo",
+ "Represents `disco#info` service discovery data.\n\n"
+ "This table has the following structure:\n\n"
+ "- `node`: string\n"
+ "- `identities`: array(table)\n"
+ " - `name`: string\n"
+ " - `category`: string\n"
+ " - `type`: string\n"
+ " - `language`: string\n"
+ "- `features`: array(string)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/DiscoInfoConvertor.h b/Sluift/ElementConvertors/DiscoInfoConvertor.h
index 4f397b0..9e8d36d 100644
--- a/Sluift/ElementConvertors/DiscoInfoConvertor.h
+++ b/Sluift/ElementConvertors/DiscoInfoConvertor.h
@@ -12,13 +12,13 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class DiscoInfoConvertor : public GenericLuaElementConvertor<DiscoInfo> {
- public:
- DiscoInfoConvertor();
- virtual ~DiscoInfoConvertor();
+ class DiscoInfoConvertor : public GenericLuaElementConvertor<DiscoInfo> {
+ public:
+ DiscoInfoConvertor();
+ virtual ~DiscoInfoConvertor();
- virtual boost::shared_ptr<DiscoInfo> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<DiscoInfo>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<DiscoInfo> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<DiscoInfo>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/DiscoItemsConvertor.cpp b/Sluift/ElementConvertors/DiscoItemsConvertor.cpp
index a01fa7e..32cbb6e 100644
--- a/Sluift/ElementConvertors/DiscoItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/DiscoItemsConvertor.cpp
@@ -22,49 +22,49 @@ DiscoItemsConvertor::~DiscoItemsConvertor() {
}
boost::shared_ptr<DiscoItems> DiscoItemsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<DiscoItems> result = boost::make_shared<DiscoItems>();
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "node")) {
- result->setNode(*value);
- }
- lua_getfield(L, -1, "items");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- result->addItem(DiscoItems::Item(
- Lua::getStringField(L, -1, "name").get_value_or(""),
- JID(Lua::getStringField(L, -1, "jid").get_value_or("")),
- Lua::getStringField(L, -1, "node").get_value_or("")));
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<DiscoItems> result = boost::make_shared<DiscoItems>();
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "node")) {
+ result->setNode(*value);
+ }
+ lua_getfield(L, -1, "items");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ result->addItem(DiscoItems::Item(
+ Lua::getStringField(L, -1, "name").get_value_or(""),
+ JID(Lua::getStringField(L, -1, "jid").get_value_or("")),
+ Lua::getStringField(L, -1, "node").get_value_or("")));
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void DiscoItemsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<DiscoItems> payload) {
- lua_newtable(L);
- if (!payload->getNode().empty()) {
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- }
- const std::vector<DiscoItems::Item>& items = payload->getItems();
- if (!items.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(items.size()), 0);
- for (size_t i = 0; i < items.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!items[i].getName().empty()) {
- lua_pushstring(L, items[i].getName().c_str());
- lua_setfield(L, -2, "name");
- }
- if (!items[i].getNode().empty()) {
- lua_pushstring(L, items[i].getNode().c_str());
- lua_setfield(L, -2, "node");
- }
- if (items[i].getJID().isValid()) {
- lua_pushstring(L, items[i].getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "items");
- }
+ lua_newtable(L);
+ if (!payload->getNode().empty()) {
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ }
+ const std::vector<DiscoItems::Item>& items = payload->getItems();
+ if (!items.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(items.size()), 0);
+ for (size_t i = 0; i < items.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!items[i].getName().empty()) {
+ lua_pushstring(L, items[i].getName().c_str());
+ lua_setfield(L, -2, "name");
+ }
+ if (!items[i].getNode().empty()) {
+ lua_pushstring(L, items[i].getNode().c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (items[i].getJID().isValid()) {
+ lua_pushstring(L, items[i].getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "items");
+ }
}
diff --git a/Sluift/ElementConvertors/DiscoItemsConvertor.h b/Sluift/ElementConvertors/DiscoItemsConvertor.h
index a1261a4..aa1f1e5 100644
--- a/Sluift/ElementConvertors/DiscoItemsConvertor.h
+++ b/Sluift/ElementConvertors/DiscoItemsConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class DiscoItemsConvertor : public GenericLuaElementConvertor<DiscoItems> {
- public:
- DiscoItemsConvertor();
- virtual ~DiscoItemsConvertor();
+ class DiscoItemsConvertor : public GenericLuaElementConvertor<DiscoItems> {
+ public:
+ DiscoItemsConvertor();
+ virtual ~DiscoItemsConvertor();
- virtual boost::shared_ptr<DiscoItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<DiscoItems>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<DiscoItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<DiscoItems>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/ElementConvertors.ipp b/Sluift/ElementConvertors/ElementConvertors.ipp
index 57e24a4..64e7540 100644
--- a/Sluift/ElementConvertors/ElementConvertors.ipp
+++ b/Sluift/ElementConvertors/ElementConvertors.ipp
@@ -45,43 +45,43 @@
#include <Sluift/ElementConvertors/UserTuneConvertor.h>
void LuaElementConvertors::registerConvertors() {
- convertors.push_back(boost::make_shared<PubSubRetractConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubAffiliationsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubPublishConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubItemsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerRedirectConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventRedirectConvertor>());
- convertors.push_back(boost::make_shared<UserTuneConvertor>());
- convertors.push_back(boost::make_shared<PubSubConfigureConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventDisassociateConvertor>());
- convertors.push_back(boost::make_shared<PubSubOwnerAffiliationsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerConfigureConvertor>(this));
- convertors.push_back(boost::make_shared<UserLocationConvertor>());
- convertors.push_back(boost::make_shared<PubSubSubscribeOptionsConvertor>());
- convertors.push_back(boost::make_shared<PubSubOwnerSubscriptionsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubDefaultConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventCollectionConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventSubscriptionConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventRetractConvertor>());
- convertors.push_back(boost::make_shared<PubSubItemConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubUnsubscribeConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventDeleteConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubCreateConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerPurgeConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventItemsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOptionsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventItemConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerSubscriptionConvertor>());
- convertors.push_back(boost::make_shared<IsodeIQDelegationConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerAffiliationConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventPurgeConvertor>());
- convertors.push_back(boost::make_shared<PubSubAffiliationConvertor>());
- convertors.push_back(boost::make_shared<PubSubSubscribeConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerDeleteConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerDefaultConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubSubscriptionsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventAssociateConvertor>());
- convertors.push_back(boost::make_shared<PubSubSubscriptionConvertor>(this));
- convertors.push_back(boost::make_shared<SecurityLabelConvertor>());
- convertors.push_back(boost::make_shared<PubSubEventConfigurationConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubRetractConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubAffiliationsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubPublishConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubItemsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerRedirectConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventRedirectConvertor>());
+ convertors.push_back(boost::make_shared<UserTuneConvertor>());
+ convertors.push_back(boost::make_shared<PubSubConfigureConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubEventDisassociateConvertor>());
+ convertors.push_back(boost::make_shared<PubSubOwnerAffiliationsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerConfigureConvertor>(this));
+ convertors.push_back(boost::make_shared<UserLocationConvertor>());
+ convertors.push_back(boost::make_shared<PubSubSubscribeOptionsConvertor>());
+ convertors.push_back(boost::make_shared<PubSubOwnerSubscriptionsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubDefaultConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventCollectionConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubEventSubscriptionConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventRetractConvertor>());
+ convertors.push_back(boost::make_shared<PubSubItemConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubUnsubscribeConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventDeleteConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubCreateConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerPurgeConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventItemsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOptionsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubEventItemConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerSubscriptionConvertor>());
+ convertors.push_back(boost::make_shared<IsodeIQDelegationConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerAffiliationConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventPurgeConvertor>());
+ convertors.push_back(boost::make_shared<PubSubAffiliationConvertor>());
+ convertors.push_back(boost::make_shared<PubSubSubscribeConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerDeleteConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubOwnerDefaultConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubSubscriptionsConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubEventAssociateConvertor>());
+ convertors.push_back(boost::make_shared<PubSubSubscriptionConvertor>(this));
+ convertors.push_back(boost::make_shared<SecurityLabelConvertor>());
+ convertors.push_back(boost::make_shared<PubSubEventConfigurationConvertor>(this));
}
diff --git a/Sluift/ElementConvertors/FormConvertor.cpp b/Sluift/ElementConvertors/FormConvertor.cpp
index d1617b6..5b6f664 100644
--- a/Sluift/ElementConvertors/FormConvertor.cpp
+++ b/Sluift/ElementConvertors/FormConvertor.cpp
@@ -22,326 +22,326 @@
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");
- if (lua_equal(L, -1, 2)) {
- lua_pushvalue(L, 3);
- lua_setfield(L, -3, "value");
- foundField = true;
- lua_pop(L, 3);
- break;
- }
- lua_pop(L, 2);
- }
- }
- lua_pop(L, 1);
-
- if (!foundField) {
- lua_pushvalue(L, 2);
- lua_pushvalue(L, 3);
- lua_rawset(L, 1);
- }
- return 0;
- }
-
- Lua::Table convertFieldToLua(boost::shared_ptr<FormField> field) {
- Lua::Table luaField = boost::assign::map_list_of("name", Lua::valueRef(field->getName()));
- std::string type;
- switch (field->getType()) {
- case FormField::UnknownType: type = ""; break;
- case FormField::BooleanType: type = "boolean"; break;
- case FormField::FixedType: type = "fixed"; break;
- case FormField::HiddenType: type = "hidden"; break;
- case FormField::ListSingleType: type = "list-single"; break;
- 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()) {
- 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< boost::shared_ptr<FormField> >& fieldList) {
- Lua::Array fields;
- foreach(boost::shared_ptr<FormField> field, fieldList) {
- fields.push_back(convertFieldToLua(field));
- }
- return fields;
- }
-
-
- boost::shared_ptr<FormField> convertFieldFromLua(lua_State* L) {
- boost::shared_ptr<FormField> result = boost::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") {
- fieldType = FormField::TextSingleType;
- }
- if (*type == "jid-single") {
- fieldType = FormField::JIDSingleType;
- }
- if (*type == "jid-multi") {
- fieldType = FormField::JIDMultiType;
- }
- if (*type == "list-multi") {
- fieldType = FormField::ListMultiType;
- }
- }
- result->setType(fieldType);
- if (boost::optional<std::string> name = Lua::getStringField(L, -1, "name")) {
- result->setName(*name);
- }
- if (boost::optional<std::string> description = Lua::getStringField(L, -1, "description")) {
- result->setDescription(*description);
- }
- if (boost::optional<std::string> label = Lua::getStringField(L, -1, "label")) {
- result->setLabel(*label);
- }
- if (boost::optional<bool> required = Lua::getBooleanField(L, -1, "required")) {
- result->setRequired(*required);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "value")) {
- result->addValue(*value);
- }
- else if (boost::optional<bool> value = Lua::getBooleanField(L, -1, "value")) {
- result->setBoolValue(*value);
- }
- else {
- lua_getfield(L, -1, "value");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addValue(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- }
- lua_getfield(L, -1, "options");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_istable(L, -1)) {
- FormField::Option option("", "");
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "value")) {
- option.value = *value;
- }
- if (boost::optional<std::string> label = Lua::getStringField(L, -1, "label")) {
- option.label = *label;
- }
- result->addOption(option);
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- return result;
- }
-
- std::vector< boost::shared_ptr<FormField> > convertFieldListFromLua(lua_State* L) {
- std::vector< boost::shared_ptr<FormField> > result;
- for (lua_pushnil(L); lua_next(L, -2);) {
- result.push_back(convertFieldFromLua(L));
- lua_pop(L, 1);
- }
- return result;
- }
-
- boost::shared_ptr<Form> convertFormFromLua(lua_State* L) {
- boost::shared_ptr<Form> result = boost::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 (boost::shared_ptr<FormField> formField, convertFieldListFromLua(L)) {
- result->addField(formField);
- }
- }
- lua_pop(L, 1);
-
- lua_getfield(L, -1, "reported_fields");
- if (lua_istable(L, -1)) {
- foreach (boost::shared_ptr<FormField> 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, boost::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());
- }
- if (!payload->getFields().empty()) {
- 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()) {
- 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) {
- boost::shared_ptr<Form> form = convertFormFromLua(L);
-
- // Remove all redundant elements
- form->setInstructions("");
- form->setTitle("");
- form->clearItems();
- form->clearReportedFields();
- std::vector< boost::shared_ptr<FormField> > fields(form->getFields());
- form->clearFields();
- foreach (boost::shared_ptr<FormField> 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;
- }
+ 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");
+ if (lua_equal(L, -1, 2)) {
+ lua_pushvalue(L, 3);
+ lua_setfield(L, -3, "value");
+ foundField = true;
+ lua_pop(L, 3);
+ break;
+ }
+ lua_pop(L, 2);
+ }
+ }
+ lua_pop(L, 1);
+
+ if (!foundField) {
+ lua_pushvalue(L, 2);
+ lua_pushvalue(L, 3);
+ lua_rawset(L, 1);
+ }
+ return 0;
+ }
+
+ Lua::Table convertFieldToLua(boost::shared_ptr<FormField> field) {
+ Lua::Table luaField = boost::assign::map_list_of("name", Lua::valueRef(field->getName()));
+ std::string type;
+ switch (field->getType()) {
+ case FormField::UnknownType: type = ""; break;
+ case FormField::BooleanType: type = "boolean"; break;
+ case FormField::FixedType: type = "fixed"; break;
+ case FormField::HiddenType: type = "hidden"; break;
+ case FormField::ListSingleType: type = "list-single"; break;
+ 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()) {
+ 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< boost::shared_ptr<FormField> >& fieldList) {
+ Lua::Array fields;
+ foreach(boost::shared_ptr<FormField> field, fieldList) {
+ fields.push_back(convertFieldToLua(field));
+ }
+ return fields;
+ }
+
+
+ boost::shared_ptr<FormField> convertFieldFromLua(lua_State* L) {
+ boost::shared_ptr<FormField> result = boost::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") {
+ fieldType = FormField::TextSingleType;
+ }
+ if (*type == "jid-single") {
+ fieldType = FormField::JIDSingleType;
+ }
+ if (*type == "jid-multi") {
+ fieldType = FormField::JIDMultiType;
+ }
+ if (*type == "list-multi") {
+ fieldType = FormField::ListMultiType;
+ }
+ }
+ result->setType(fieldType);
+ if (boost::optional<std::string> name = Lua::getStringField(L, -1, "name")) {
+ result->setName(*name);
+ }
+ if (boost::optional<std::string> description = Lua::getStringField(L, -1, "description")) {
+ result->setDescription(*description);
+ }
+ if (boost::optional<std::string> label = Lua::getStringField(L, -1, "label")) {
+ result->setLabel(*label);
+ }
+ if (boost::optional<bool> required = Lua::getBooleanField(L, -1, "required")) {
+ result->setRequired(*required);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "value")) {
+ result->addValue(*value);
+ }
+ else if (boost::optional<bool> value = Lua::getBooleanField(L, -1, "value")) {
+ result->setBoolValue(*value);
+ }
+ else {
+ lua_getfield(L, -1, "value");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addValue(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ }
+ lua_getfield(L, -1, "options");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_istable(L, -1)) {
+ FormField::Option option("", "");
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "value")) {
+ option.value = *value;
+ }
+ if (boost::optional<std::string> label = Lua::getStringField(L, -1, "label")) {
+ option.label = *label;
+ }
+ result->addOption(option);
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
+ }
+
+ std::vector< boost::shared_ptr<FormField> > convertFieldListFromLua(lua_State* L) {
+ std::vector< boost::shared_ptr<FormField> > result;
+ for (lua_pushnil(L); lua_next(L, -2);) {
+ result.push_back(convertFieldFromLua(L));
+ lua_pop(L, 1);
+ }
+ return result;
+ }
+
+ boost::shared_ptr<Form> convertFormFromLua(lua_State* L) {
+ boost::shared_ptr<Form> result = boost::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 (boost::shared_ptr<FormField> formField, convertFieldListFromLua(L)) {
+ result->addField(formField);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "reported_fields");
+ if (lua_istable(L, -1)) {
+ foreach (boost::shared_ptr<FormField> 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, boost::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());
+ }
+ if (!payload->getFields().empty()) {
+ 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()) {
+ 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) {
+ boost::shared_ptr<Form> form = convertFormFromLua(L);
+
+ // Remove all redundant elements
+ form->setInstructions("");
+ form->setTitle("");
+ form->clearItems();
+ form->clearReportedFields();
+ std::vector< boost::shared_ptr<FormField> > fields(form->getFields());
+ form->clearFields();
+ foreach (boost::shared_ptr<FormField> 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") {
@@ -351,13 +351,13 @@ FormConvertor::~FormConvertor() {
}
boost::shared_ptr<Form> FormConvertor::doConvertFromLua(lua_State* L) {
- return convertFormFromLua(L);
+ return convertFormFromLua(L);
}
void FormConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Form> payload) {
- convertFormToLua(L, payload);
+ convertFormToLua(L, payload);
- lua_pushstring(L, "create_submission");
- lua_pushcfunction(L, createSubmission);
- lua_rawset(L, -3);
+ lua_pushstring(L, "create_submission");
+ lua_pushcfunction(L, createSubmission);
+ lua_rawset(L, -3);
}
diff --git a/Sluift/ElementConvertors/FormConvertor.h b/Sluift/ElementConvertors/FormConvertor.h
index af9020d..05ca57f 100644
--- a/Sluift/ElementConvertors/FormConvertor.h
+++ b/Sluift/ElementConvertors/FormConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class FormConvertor : public GenericLuaElementConvertor<Form> {
- public:
- FormConvertor();
- virtual ~FormConvertor();
+ class FormConvertor : public GenericLuaElementConvertor<Form> {
+ public:
+ FormConvertor();
+ virtual ~FormConvertor();
- virtual boost::shared_ptr<Form> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Form>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Form> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Form>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/ForwardedConvertor.cpp b/Sluift/ElementConvertors/ForwardedConvertor.cpp
index a1f53a3..82539bb 100644
--- a/Sluift/ElementConvertors/ForwardedConvertor.cpp
+++ b/Sluift/ElementConvertors/ForwardedConvertor.cpp
@@ -21,54 +21,54 @@
using namespace Swift;
-ForwardedConvertor::ForwardedConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<Forwarded>("forwarded"),
- convertors(convertors) {
+ForwardedConvertor::ForwardedConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<Forwarded>("forwarded"),
+ convertors(convertors) {
}
ForwardedConvertor::~ForwardedConvertor() {
}
boost::shared_ptr<Forwarded> ForwardedConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Forwarded> result = boost::make_shared<Forwarded>();
- lua_getfield(L, -1, "delay");
- if (!lua_isnil(L, -1)) {
- boost::shared_ptr<Delay> delay = boost::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)) {
- boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(convertors->convertFromLua(L, -1));
- if (!!stanza) {
- result->setStanza(stanza);
- }
- lua_pop(L, 1);
- return result;
- }
- return result;
+ boost::shared_ptr<Forwarded> result = boost::make_shared<Forwarded>();
+ lua_getfield(L, -1, "delay");
+ if (!lua_isnil(L, -1)) {
+ boost::shared_ptr<Delay> delay = boost::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)) {
+ boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(convertors->convertFromLua(L, -1));
+ if (!!stanza) {
+ result->setStanza(stanza);
+ }
+ lua_pop(L, 1);
+ return result;
+ }
+ return result;
}
void ForwardedConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Forwarded> payload) {
- lua_createtable(L, 0, 0);
- if (convertors->convertToLuaUntyped(L, payload->getDelay()) > 0) {
- lua_setfield(L, -2, "delay");
- }
- boost::shared_ptr<Stanza> stanza = payload->getStanza();
- if (!!stanza) {
- if (convertors->convertToLua(L, stanza) > 0) {
- lua_setfield(L, -2, "stanza");
- }
- }
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getDelay()) > 0) {
+ lua_setfield(L, -2, "delay");
+ }
+ boost::shared_ptr<Stanza> stanza = payload->getStanza();
+ if (!!stanza) {
+ if (convertors->convertToLua(L, stanza) > 0) {
+ lua_setfield(L, -2, "stanza");
+ }
+ }
}
boost::optional<LuaElementConvertor::Documentation> ForwardedConvertor::getDocumentation() const {
- return Documentation(
- "Forwarded",
- "This table has the following fields:\n\n"
- "- `delay`: @{Delay} (Optional)\n"
- "- `stanza`: @{Stanza} (Optional)\n"
- );
+ return Documentation(
+ "Forwarded",
+ "This table has the following fields:\n\n"
+ "- `delay`: @{Delay} (Optional)\n"
+ "- `stanza`: @{Stanza} (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/ForwardedConvertor.h b/Sluift/ElementConvertors/ForwardedConvertor.h
index 6c4848a..ee022fa 100644
--- a/Sluift/ElementConvertors/ForwardedConvertor.h
+++ b/Sluift/ElementConvertors/ForwardedConvertor.h
@@ -12,20 +12,20 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class ForwardedConvertor : public GenericLuaElementConvertor<Forwarded> {
- public:
- ForwardedConvertor(LuaElementConvertors* convertors);
- virtual ~ForwardedConvertor();
+ class ForwardedConvertor : public GenericLuaElementConvertor<Forwarded> {
+ public:
+ ForwardedConvertor(LuaElementConvertors* convertors);
+ virtual ~ForwardedConvertor();
- virtual boost::shared_ptr<Forwarded> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Forwarded>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Forwarded> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Forwarded>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/IQConvertor.cpp b/Sluift/ElementConvertors/IQConvertor.cpp
index 019ec57..7e2cb7e 100644
--- a/Sluift/ElementConvertors/IQConvertor.cpp
+++ b/Sluift/ElementConvertors/IQConvertor.cpp
@@ -14,62 +14,62 @@
using namespace Swift;
-IQConvertor::IQConvertor(LuaElementConvertors* convertors) :
- StanzaConvertor<IQ>("iq"),
- convertors(convertors) {
+IQConvertor::IQConvertor(LuaElementConvertors* convertors) :
+ StanzaConvertor<IQ>("iq"),
+ convertors(convertors) {
}
IQConvertor::~IQConvertor() {
}
boost::shared_ptr<IQ> IQConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<IQ> result = getStanza(L, convertors);
- lua_getfield(L, -1, "type");
- if (lua_isstring(L, -1)) {
- result->setType(IQConvertor::convertIQTypeFromString(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<IQ> result = getStanza(L, convertors);
+ lua_getfield(L, -1, "type");
+ if (lua_isstring(L, -1)) {
+ result->setType(IQConvertor::convertIQTypeFromString(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void IQConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<IQ> stanza) {
- pushStanza(L, stanza, convertors);
- const std::string type = IQConvertor::convertIQTypeToString(stanza->getType());
- lua_pushstring(L, type.c_str());
- lua_setfield(L, -2, "type");
+ pushStanza(L, stanza, convertors);
+ const std::string type = IQConvertor::convertIQTypeToString(stanza->getType());
+ lua_pushstring(L, type.c_str());
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> IQConvertor::getDocumentation() const {
- return Documentation(
- "IQ",
- "This table has the following fields:\n\n"
- "- `type`: string\n"
- "- `id`: string\n"
- "- `from`: string\n"
- "- `to`: string\n"
- "- `payloads`: array<@{Payload}>\n"
- );
+ return Documentation(
+ "IQ",
+ "This table has the following fields:\n\n"
+ "- `type`: string\n"
+ "- `id`: string\n"
+ "- `from`: string\n"
+ "- `to`: string\n"
+ "- `payloads`: array<@{Payload}>\n"
+ );
}
std::string IQConvertor::convertIQTypeToString(IQ::Type type) {
- switch (type) {
- case IQ::Get: return "get";
- case IQ::Set: return "set";
- case IQ::Result: return "result";
- case IQ::Error: return "error";
- }
- assert(false);
- return "";
+ switch (type) {
+ case IQ::Get: return "get";
+ case IQ::Set: return "set";
+ case IQ::Result: return "result";
+ case IQ::Error: return "error";
+ }
+ assert(false);
+ return "";
}
IQ::Type IQConvertor::convertIQTypeFromString(const std::string& type) {
- if (type == "get") {
- return IQ::Get;
- }
- else if (type == "set") {
- return IQ::Set;
- }
- else {
- throw Lua::Exception("Illegal query type: '" + type + "'");
- }
+ if (type == "get") {
+ return IQ::Get;
+ }
+ else if (type == "set") {
+ return IQ::Set;
+ }
+ else {
+ throw Lua::Exception("Illegal query type: '" + type + "'");
+ }
}
diff --git a/Sluift/ElementConvertors/IQConvertor.h b/Sluift/ElementConvertors/IQConvertor.h
index 68bda38..49896e7 100644
--- a/Sluift/ElementConvertors/IQConvertor.h
+++ b/Sluift/ElementConvertors/IQConvertor.h
@@ -12,23 +12,23 @@
#include <Sluift/ElementConvertors/StanzaConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class IQConvertor : public StanzaConvertor<IQ> {
- public:
- IQConvertor(LuaElementConvertors* convertors);
- virtual ~IQConvertor();
+ class IQConvertor : public StanzaConvertor<IQ> {
+ public:
+ IQConvertor(LuaElementConvertors* convertors);
+ virtual ~IQConvertor();
- virtual boost::shared_ptr<IQ> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<IQ>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<IQ> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<IQ>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- static std::string convertIQTypeToString(IQ::Type type);
- static IQ::Type convertIQTypeFromString(const std::string& type);
+ static std::string convertIQTypeToString(IQ::Type type);
+ static IQ::Type convertIQTypeFromString(const std::string& type);
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp
index bb1de94..e256dc7 100644
--- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp
+++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp
@@ -14,37 +14,37 @@
using namespace Swift;
-IsodeIQDelegationConvertor::IsodeIQDelegationConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<IsodeIQDelegation>("isode_iq_delegation"),
- convertors(convertors) {
+IsodeIQDelegationConvertor::IsodeIQDelegationConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<IsodeIQDelegation>("isode_iq_delegation"),
+ convertors(convertors) {
}
IsodeIQDelegationConvertor::~IsodeIQDelegationConvertor() {
}
boost::shared_ptr<IsodeIQDelegation> IsodeIQDelegationConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<IsodeIQDelegation> result = boost::make_shared<IsodeIQDelegation>();
- lua_getfield(L, -1, "forward");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Forwarded> payload = boost::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "forwarded"))) {
- result->setForward(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<IsodeIQDelegation> result = boost::make_shared<IsodeIQDelegation>();
+ lua_getfield(L, -1, "forward");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Forwarded> payload = boost::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "forwarded"))) {
+ result->setForward(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void IsodeIQDelegationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<IsodeIQDelegation> payload) {
- lua_createtable(L, 0, 0);
- if (convertors->convertToLuaUntyped(L, payload->getForward()) > 0) {
- lua_setfield(L, -2, "forward");
- }
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getForward()) > 0) {
+ lua_setfield(L, -2, "forward");
+ }
}
boost::optional<LuaElementConvertor::Documentation> IsodeIQDelegationConvertor::getDocumentation() const {
- return Documentation(
- "IsodeIQDelegation",
- "This table has the following fields:\n\n"
- "- `forward`: @{Forwarded}\n"
- );
+ return Documentation(
+ "IsodeIQDelegation",
+ "This table has the following fields:\n\n"
+ "- `forward`: @{Forwarded}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h
index bcbeb40..9fa005b 100644
--- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h
+++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class IsodeIQDelegationConvertor : public GenericLuaElementConvertor<IsodeIQDelegation> {
- public:
- IsodeIQDelegationConvertor(LuaElementConvertors* convertors);
- virtual ~IsodeIQDelegationConvertor();
+ class IsodeIQDelegationConvertor : public GenericLuaElementConvertor<IsodeIQDelegation> {
+ public:
+ IsodeIQDelegationConvertor(LuaElementConvertors* convertors);
+ virtual ~IsodeIQDelegationConvertor();
- virtual boost::shared_ptr<IsodeIQDelegation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<IsodeIQDelegation>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<IsodeIQDelegation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<IsodeIQDelegation>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/MAMFinConvertor.cpp b/Sluift/ElementConvertors/MAMFinConvertor.cpp
index 977dbc9..1bb6c05 100644
--- a/Sluift/ElementConvertors/MAMFinConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMFinConvertor.cpp
@@ -17,64 +17,64 @@
using namespace Swift;
-MAMFinConvertor::MAMFinConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<MAMFin>("mam_fin"),
- convertors(convertors) {
+MAMFinConvertor::MAMFinConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<MAMFin>("mam_fin"),
+ convertors(convertors) {
}
MAMFinConvertor::~MAMFinConvertor() {
}
boost::shared_ptr<MAMFin> MAMFinConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<MAMFin> result = boost::make_shared<MAMFin>();
- lua_getfield(L, -1, "query_id");
- if (lua_isstring(L, -1)) {
- result->setQueryID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "complete");
- if (lua_isboolean(L, -1)) {
- result->setComplete(lua_toboolean(L, -1) != 0);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "stable");
- if (!lua_isnil(L, -1)) {
- result->setStable(lua_toboolean(L, -1) != 0);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "result_set");
- if (!lua_isnil(L, -1)) {
- boost::shared_ptr<ResultSet> resultSet = boost::dynamic_pointer_cast<ResultSet>(convertors->convertFromLuaUntyped(L, -1, "result_set"));
- if (!!resultSet) {
- result->setResultSet(resultSet);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<MAMFin> result = boost::make_shared<MAMFin>();
+ lua_getfield(L, -1, "query_id");
+ if (lua_isstring(L, -1)) {
+ result->setQueryID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "complete");
+ if (lua_isboolean(L, -1)) {
+ result->setComplete(lua_toboolean(L, -1) != 0);
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "stable");
+ if (!lua_isnil(L, -1)) {
+ result->setStable(lua_toboolean(L, -1) != 0);
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "result_set");
+ if (!lua_isnil(L, -1)) {
+ boost::shared_ptr<ResultSet> resultSet = boost::dynamic_pointer_cast<ResultSet>(convertors->convertFromLuaUntyped(L, -1, "result_set"));
+ if (!!resultSet) {
+ result->setResultSet(resultSet);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void MAMFinConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<MAMFin> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getQueryID()) {
- lua_pushstring(L, (*payload->getQueryID()).c_str());
- lua_setfield(L, -2, "query_id");
- }
- lua_pushboolean(L, payload->isComplete());
- lua_setfield(L, -2, "complete");
- lua_pushboolean(L, payload->isStable());
- lua_setfield(L, -2, "stable");
- if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) {
- lua_setfield(L, -2, "result_set");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getQueryID()) {
+ lua_pushstring(L, (*payload->getQueryID()).c_str());
+ lua_setfield(L, -2, "query_id");
+ }
+ lua_pushboolean(L, payload->isComplete());
+ lua_setfield(L, -2, "complete");
+ lua_pushboolean(L, payload->isStable());
+ lua_setfield(L, -2, "stable");
+ if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) {
+ lua_setfield(L, -2, "result_set");
+ }
}
boost::optional<LuaElementConvertor::Documentation> MAMFinConvertor::getDocumentation() const {
- return Documentation(
- "MAMFin",
- "This table has the following fields:\n\n"
- "- `query_id`: string (Optional)\n"
- "- `complete`: boolean (Optional)\n"
- "- `stable`: boolean (Optional)\n"
- "- `result_set`: @{ResultSet} (Optional)\n"
- );
+ return Documentation(
+ "MAMFin",
+ "This table has the following fields:\n\n"
+ "- `query_id`: string (Optional)\n"
+ "- `complete`: boolean (Optional)\n"
+ "- `stable`: boolean (Optional)\n"
+ "- `result_set`: @{ResultSet} (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/MAMFinConvertor.h b/Sluift/ElementConvertors/MAMFinConvertor.h
index 1727403..9345aeb 100644
--- a/Sluift/ElementConvertors/MAMFinConvertor.h
+++ b/Sluift/ElementConvertors/MAMFinConvertor.h
@@ -12,19 +12,19 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class MAMFinConvertor : public GenericLuaElementConvertor<MAMFin> {
- public:
- MAMFinConvertor(LuaElementConvertors* convertors);
- virtual ~MAMFinConvertor();
+ class MAMFinConvertor : public GenericLuaElementConvertor<MAMFin> {
+ public:
+ MAMFinConvertor(LuaElementConvertors* convertors);
+ virtual ~MAMFinConvertor();
- virtual boost::shared_ptr<MAMFin> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMFin>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<MAMFin> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMFin>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/MAMQueryConvertor.cpp b/Sluift/ElementConvertors/MAMQueryConvertor.cpp
index 89a8876..a52abd9 100644
--- a/Sluift/ElementConvertors/MAMQueryConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMQueryConvertor.cpp
@@ -18,70 +18,70 @@
using namespace Swift;
-MAMQueryConvertor::MAMQueryConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<MAMQuery>("mam"),
- convertors(convertors) {
+MAMQueryConvertor::MAMQueryConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<MAMQuery>("mam"),
+ convertors(convertors) {
}
MAMQueryConvertor::~MAMQueryConvertor() {
}
boost::shared_ptr<MAMQuery> MAMQueryConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<MAMQuery> result = boost::make_shared<MAMQuery>();
- lua_getfield(L, -1, "query_id");
- if (lua_isstring(L, -1)) {
- result->setQueryID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- 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, "form");
- if (!lua_isnil(L, -1)) {
- boost::shared_ptr<Form> form = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"));
- if (!!form) {
- result->setForm(form);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "result_set");
- if (!lua_isnil(L, -1)) {
- boost::shared_ptr<ResultSet> resultSet = boost::dynamic_pointer_cast<ResultSet>(convertors->convertFromLuaUntyped(L, -1, "result_set"));
- if (!!resultSet) {
- result->setResultSet(resultSet);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<MAMQuery> result = boost::make_shared<MAMQuery>();
+ lua_getfield(L, -1, "query_id");
+ if (lua_isstring(L, -1)) {
+ result->setQueryID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ 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, "form");
+ if (!lua_isnil(L, -1)) {
+ boost::shared_ptr<Form> form = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"));
+ if (!!form) {
+ result->setForm(form);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "result_set");
+ if (!lua_isnil(L, -1)) {
+ boost::shared_ptr<ResultSet> resultSet = boost::dynamic_pointer_cast<ResultSet>(convertors->convertFromLuaUntyped(L, -1, "result_set"));
+ if (!!resultSet) {
+ result->setResultSet(resultSet);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void MAMQueryConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<MAMQuery> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getQueryID()) {
- lua_pushstring(L, (*payload->getQueryID()).c_str());
- lua_setfield(L, -2, "query_id");
- }
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- if (convertors->convertToLuaUntyped(L, payload->getForm()) > 0) {
- lua_setfield(L, -2, "form");
- }
- if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) {
- lua_setfield(L, -2, "result_set");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getQueryID()) {
+ lua_pushstring(L, (*payload->getQueryID()).c_str());
+ lua_setfield(L, -2, "query_id");
+ }
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (convertors->convertToLuaUntyped(L, payload->getForm()) > 0) {
+ lua_setfield(L, -2, "form");
+ }
+ if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) {
+ lua_setfield(L, -2, "result_set");
+ }
}
boost::optional<LuaElementConvertor::Documentation> MAMQueryConvertor::getDocumentation() const {
- return Documentation(
- "MAMQuery",
- "This table has the following fields:\n\n"
- "- `query_id`: string (Optional)\n"
- "- `node`: string (Optional)\n"
- "- `form`: string @{Form} (Optional)\n"
- "- `result_set`: @{ResultSet} (Optional)\n"
- );
+ return Documentation(
+ "MAMQuery",
+ "This table has the following fields:\n\n"
+ "- `query_id`: string (Optional)\n"
+ "- `node`: string (Optional)\n"
+ "- `form`: string @{Form} (Optional)\n"
+ "- `result_set`: @{ResultSet} (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/MAMQueryConvertor.h b/Sluift/ElementConvertors/MAMQueryConvertor.h
index e839a24..54a99e0 100644
--- a/Sluift/ElementConvertors/MAMQueryConvertor.h
+++ b/Sluift/ElementConvertors/MAMQueryConvertor.h
@@ -12,19 +12,19 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class MAMQueryConvertor : public GenericLuaElementConvertor<MAMQuery> {
- public:
- MAMQueryConvertor(LuaElementConvertors* convertors);
- virtual ~MAMQueryConvertor();
+ class MAMQueryConvertor : public GenericLuaElementConvertor<MAMQuery> {
+ public:
+ MAMQueryConvertor(LuaElementConvertors* convertors);
+ virtual ~MAMQueryConvertor();
- virtual boost::shared_ptr<MAMQuery> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMQuery>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<MAMQuery> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMQuery>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/MAMResultConvertor.cpp b/Sluift/ElementConvertors/MAMResultConvertor.cpp
index 02c5976..2260eb1 100644
--- a/Sluift/ElementConvertors/MAMResultConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMResultConvertor.cpp
@@ -17,56 +17,56 @@
using namespace Swift;
-MAMResultConvertor::MAMResultConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<MAMResult>("mam_result"),
- convertors(convertors) {
+MAMResultConvertor::MAMResultConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<MAMResult>("mam_result"),
+ convertors(convertors) {
}
MAMResultConvertor::~MAMResultConvertor() {
}
boost::shared_ptr<MAMResult> MAMResultConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<MAMResult> result = boost::make_shared<MAMResult>();
- lua_getfield(L, -1, "payload");
- if (!lua_isnil(L, -1)) {
- boost::shared_ptr<Forwarded> payload = boost::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "payload"));
- if (!!payload) {
- result->setPayload(payload);
- }
- }
- 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);
- lua_getfield(L, -1, "query_id");
- if (lua_isstring(L, -1)) {
- result->setQueryID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<MAMResult> result = boost::make_shared<MAMResult>();
+ lua_getfield(L, -1, "payload");
+ if (!lua_isnil(L, -1)) {
+ boost::shared_ptr<Forwarded> payload = boost::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "payload"));
+ if (!!payload) {
+ result->setPayload(payload);
+ }
+ }
+ 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);
+ lua_getfield(L, -1, "query_id");
+ if (lua_isstring(L, -1)) {
+ result->setQueryID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void MAMResultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<MAMResult> payload) {
- lua_createtable(L, 0, 0);
- if (convertors->convertToLuaUntyped(L, payload->getPayload()) > 0) {
- lua_setfield(L, -2, "payload");
- }
- lua_pushstring(L, payload->getID().c_str());
- lua_setfield(L, -2, "id");
- if (payload->getQueryID()) {
- lua_pushstring(L, (*payload->getQueryID()).c_str());
- lua_setfield(L, -2, "query_id");
- }
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getPayload()) > 0) {
+ lua_setfield(L, -2, "payload");
+ }
+ lua_pushstring(L, payload->getID().c_str());
+ lua_setfield(L, -2, "id");
+ if (payload->getQueryID()) {
+ lua_pushstring(L, (*payload->getQueryID()).c_str());
+ lua_setfield(L, -2, "query_id");
+ }
}
boost::optional<LuaElementConvertor::Documentation> MAMResultConvertor::getDocumentation() const {
- return Documentation(
- "MAMResult",
- "This table has the following fields:\n\n"
- "- `payload`: @{Forwarded}\n"
- "- `id`: string\n"
- "- `query_id`: string (Optional)\n"
- );
+ return Documentation(
+ "MAMResult",
+ "This table has the following fields:\n\n"
+ "- `payload`: @{Forwarded}\n"
+ "- `id`: string\n"
+ "- `query_id`: string (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/MAMResultConvertor.h b/Sluift/ElementConvertors/MAMResultConvertor.h
index 49b14e2..c1ddf31 100644
--- a/Sluift/ElementConvertors/MAMResultConvertor.h
+++ b/Sluift/ElementConvertors/MAMResultConvertor.h
@@ -12,19 +12,19 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class MAMResultConvertor : public GenericLuaElementConvertor<MAMResult> {
- public:
- MAMResultConvertor(LuaElementConvertors* convertors);
- virtual ~MAMResultConvertor();
+ class MAMResultConvertor : public GenericLuaElementConvertor<MAMResult> {
+ public:
+ MAMResultConvertor(LuaElementConvertors* convertors);
+ virtual ~MAMResultConvertor();
- virtual boost::shared_ptr<MAMResult> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMResult>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<MAMResult> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<MAMResult>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/MessageConvertor.cpp b/Sluift/ElementConvertors/MessageConvertor.cpp
index 52b3b90..c9285ef 100644
--- a/Sluift/ElementConvertors/MessageConvertor.cpp
+++ b/Sluift/ElementConvertors/MessageConvertor.cpp
@@ -14,72 +14,72 @@
using namespace Swift;
-MessageConvertor::MessageConvertor(LuaElementConvertors* convertors) :
- StanzaConvertor<Message>("message"),
- convertors(convertors) {
+MessageConvertor::MessageConvertor(LuaElementConvertors* convertors) :
+ StanzaConvertor<Message>("message"),
+ convertors(convertors) {
}
MessageConvertor::~MessageConvertor() {
}
boost::shared_ptr<Message> MessageConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Message> result = getStanza(L, convertors);
- lua_getfield(L, -1, "type");
- if (lua_isstring(L, -1)) {
- result->setType(convertMessageTypeFromString(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<Message> result = getStanza(L, convertors);
+ lua_getfield(L, -1, "type");
+ if (lua_isstring(L, -1)) {
+ result->setType(convertMessageTypeFromString(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void MessageConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Message> stanza) {
- pushStanza(L, stanza, convertors);
- const std::string type = convertMessageTypeToString(stanza->getType());
- lua_pushstring(L, type.c_str());
- lua_setfield(L, -2, "type");
+ pushStanza(L, stanza, convertors);
+ const std::string type = convertMessageTypeToString(stanza->getType());
+ lua_pushstring(L, type.c_str());
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> MessageConvertor::getDocumentation() const {
- return Documentation(
- "Message",
- "This table has the following fields:\n\n"
- "- `type`: string\n"
- "- `id`: string\n"
- "- `from`: string\n"
- "- `to`: string\n"
- "- `payloads`: array<@{Payload}>\n"
- );
+ return Documentation(
+ "Message",
+ "This table has the following fields:\n\n"
+ "- `type`: string\n"
+ "- `id`: string\n"
+ "- `from`: string\n"
+ "- `to`: string\n"
+ "- `payloads`: array<@{Payload}>\n"
+ );
}
std::string MessageConvertor::convertMessageTypeToString(Message::Type type) {
- switch (type) {
- case Message::Normal: return "normal";
- case Message::Chat: return "chat";
- case Message::Error: return "error";
- case Message::Groupchat: return "groupchat";
- case Message::Headline: return "headline";
- }
- assert(false);
- return "";
+ switch (type) {
+ case Message::Normal: return "normal";
+ case Message::Chat: return "chat";
+ case Message::Error: return "error";
+ case Message::Groupchat: return "groupchat";
+ case Message::Headline: return "headline";
+ }
+ assert(false);
+ return "";
}
Message::Type MessageConvertor::convertMessageTypeFromString(const std::string& type) {
- if (type == "normal") {
- return Message::Normal;
- }
- else if (type == "chat") {
- return Message::Chat;
- }
- else if (type == "error") {
- return Message::Error;
- }
- else if (type == "groupchat") {
- return Message::Groupchat;
- }
- else if (type == "headline") {
- return Message::Headline;
- }
- else {
- throw Lua::Exception("Illegal message type: '" + type + "'");
- }
+ if (type == "normal") {
+ return Message::Normal;
+ }
+ else if (type == "chat") {
+ return Message::Chat;
+ }
+ else if (type == "error") {
+ return Message::Error;
+ }
+ else if (type == "groupchat") {
+ return Message::Groupchat;
+ }
+ else if (type == "headline") {
+ return Message::Headline;
+ }
+ else {
+ throw Lua::Exception("Illegal message type: '" + type + "'");
+ }
}
diff --git a/Sluift/ElementConvertors/MessageConvertor.h b/Sluift/ElementConvertors/MessageConvertor.h
index 92efea3..e05e00e 100644
--- a/Sluift/ElementConvertors/MessageConvertor.h
+++ b/Sluift/ElementConvertors/MessageConvertor.h
@@ -12,23 +12,23 @@
#include <Sluift/ElementConvertors/StanzaConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class MessageConvertor : public StanzaConvertor<Message> {
- public:
- MessageConvertor(LuaElementConvertors* convertors);
- virtual ~MessageConvertor();
+ class MessageConvertor : public StanzaConvertor<Message> {
+ public:
+ MessageConvertor(LuaElementConvertors* convertors);
+ virtual ~MessageConvertor();
- virtual boost::shared_ptr<Message> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Message>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Message> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Message>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- static std::string convertMessageTypeToString(Message::Type type);
- static Message::Type convertMessageTypeFromString(const std::string& type);
+ static std::string convertMessageTypeToString(Message::Type type);
+ static Message::Type convertMessageTypeFromString(const std::string& type);
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PresenceConvertor.cpp b/Sluift/ElementConvertors/PresenceConvertor.cpp
index edf3941..1b423cc 100644
--- a/Sluift/ElementConvertors/PresenceConvertor.cpp
+++ b/Sluift/ElementConvertors/PresenceConvertor.cpp
@@ -14,84 +14,84 @@
using namespace Swift;
-PresenceConvertor::PresenceConvertor(LuaElementConvertors* convertors) :
- StanzaConvertor<Presence>("presence"),
- convertors(convertors) {
+PresenceConvertor::PresenceConvertor(LuaElementConvertors* convertors) :
+ StanzaConvertor<Presence>("presence"),
+ convertors(convertors) {
}
PresenceConvertor::~PresenceConvertor() {
}
boost::shared_ptr<Presence> PresenceConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Presence> result = getStanza(L, convertors);
- lua_getfield(L, -1, "type");
- if (lua_isstring(L, -1)) {
- result->setType(convertPresenceTypeFromString(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<Presence> result = getStanza(L, convertors);
+ lua_getfield(L, -1, "type");
+ if (lua_isstring(L, -1)) {
+ result->setType(convertPresenceTypeFromString(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PresenceConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Presence> stanza) {
- pushStanza(L, stanza, convertors);
- const std::string type = convertPresenceTypeToString(stanza->getType());
- lua_pushstring(L, type.c_str());
- lua_setfield(L, -2, "type");
+ pushStanza(L, stanza, convertors);
+ const std::string type = convertPresenceTypeToString(stanza->getType());
+ lua_pushstring(L, type.c_str());
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> PresenceConvertor::getDocumentation() const {
- return Documentation(
- "Presence",
- "This table has the following fields:\n\n"
- "- `type`: string\n"
- "- `id`: string\n"
- "- `from`: string\n"
- "- `to`: string\n"
- "- `payloads`: array<@{Payload}>\n"
- );
+ return Documentation(
+ "Presence",
+ "This table has the following fields:\n\n"
+ "- `type`: string\n"
+ "- `id`: string\n"
+ "- `from`: string\n"
+ "- `to`: string\n"
+ "- `payloads`: array<@{Payload}>\n"
+ );
}
std::string PresenceConvertor::convertPresenceTypeToString(Presence::Type type) {
- switch (type) {
- case Presence::Available: return "available";
- case Presence::Error: return "error";
- case Presence::Probe: return "probe";
- case Presence::Subscribe: return "subscribe";
- case Presence::Subscribed: return "subscribed";
- case Presence::Unavailable: return "unavailable";
- case Presence::Unsubscribe: return "unsubscribe";
- case Presence::Unsubscribed: return "unsubscribed";
- }
- assert(false);
- return "";
+ switch (type) {
+ case Presence::Available: return "available";
+ case Presence::Error: return "error";
+ case Presence::Probe: return "probe";
+ case Presence::Subscribe: return "subscribe";
+ case Presence::Subscribed: return "subscribed";
+ case Presence::Unavailable: return "unavailable";
+ case Presence::Unsubscribe: return "unsubscribe";
+ case Presence::Unsubscribed: return "unsubscribed";
+ }
+ assert(false);
+ return "";
}
Presence::Type PresenceConvertor::convertPresenceTypeFromString(const std::string& type) {
- if (type == "available") {
- return Presence::Available;
- }
- else if (type == "error") {
- return Presence::Error;
- }
- else if (type == "probe") {
- return Presence::Probe;
- }
- else if (type == "subscribe") {
- return Presence::Subscribe;
- }
- else if (type == "subscribed") {
- return Presence::Subscribed;
- }
- else if (type == "unavailable") {
- return Presence::Unavailable;
- }
- else if (type == "unsubscribe") {
- return Presence::Unsubscribe;
- }
- else if (type == "unsubscribed") {
- return Presence::Unsubscribed;
- }
- else {
- throw Lua::Exception("Illegal presence type: '" + type + "'");
- }
+ if (type == "available") {
+ return Presence::Available;
+ }
+ else if (type == "error") {
+ return Presence::Error;
+ }
+ else if (type == "probe") {
+ return Presence::Probe;
+ }
+ else if (type == "subscribe") {
+ return Presence::Subscribe;
+ }
+ else if (type == "subscribed") {
+ return Presence::Subscribed;
+ }
+ else if (type == "unavailable") {
+ return Presence::Unavailable;
+ }
+ else if (type == "unsubscribe") {
+ return Presence::Unsubscribe;
+ }
+ else if (type == "unsubscribed") {
+ return Presence::Unsubscribed;
+ }
+ else {
+ throw Lua::Exception("Illegal presence type: '" + type + "'");
+ }
}
diff --git a/Sluift/ElementConvertors/PresenceConvertor.h b/Sluift/ElementConvertors/PresenceConvertor.h
index c919f3a..ae2e78a 100644
--- a/Sluift/ElementConvertors/PresenceConvertor.h
+++ b/Sluift/ElementConvertors/PresenceConvertor.h
@@ -12,23 +12,23 @@
#include <Sluift/ElementConvertors/StanzaConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PresenceConvertor : public StanzaConvertor<Presence> {
- public:
- PresenceConvertor(LuaElementConvertors* convertors);
- virtual ~PresenceConvertor();
+ class PresenceConvertor : public StanzaConvertor<Presence> {
+ public:
+ PresenceConvertor(LuaElementConvertors* convertors);
+ virtual ~PresenceConvertor();
- virtual boost::shared_ptr<Presence> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Presence>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Presence> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Presence>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- static std::string convertPresenceTypeToString(Presence::Type type);
- static Presence::Type convertPresenceTypeFromString(const std::string& type);
+ static std::string convertPresenceTypeToString(Presence::Type type);
+ static Presence::Type convertPresenceTypeFromString(const std::string& type);
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp b/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp
index 717d01c..84d8f55 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp
@@ -13,76 +13,76 @@
using namespace Swift;
PubSubAffiliationConvertor::PubSubAffiliationConvertor() :
- GenericLuaElementConvertor<PubSubAffiliation>("pubsub_affiliation") {
+ GenericLuaElementConvertor<PubSubAffiliation>("pubsub_affiliation") {
}
PubSubAffiliationConvertor::~PubSubAffiliationConvertor() {
}
boost::shared_ptr<PubSubAffiliation> PubSubAffiliationConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubAffiliation> result = boost::make_shared<PubSubAffiliation>();
- 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, "type");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setType(PubSubAffiliation::None);
- }
- if (std::string(lua_tostring(L, -1)) == "member") {
- result->setType(PubSubAffiliation::Member);
- }
- if (std::string(lua_tostring(L, -1)) == "outcast") {
- result->setType(PubSubAffiliation::Outcast);
- }
- if (std::string(lua_tostring(L, -1)) == "owner") {
- result->setType(PubSubAffiliation::Owner);
- }
- if (std::string(lua_tostring(L, -1)) == "publisher") {
- result->setType(PubSubAffiliation::Publisher);
- }
- if (std::string(lua_tostring(L, -1)) == "publish_only") {
- result->setType(PubSubAffiliation::PublishOnly);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubAffiliation> result = boost::make_shared<PubSubAffiliation>();
+ 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, "type");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setType(PubSubAffiliation::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "member") {
+ result->setType(PubSubAffiliation::Member);
+ }
+ if (std::string(lua_tostring(L, -1)) == "outcast") {
+ result->setType(PubSubAffiliation::Outcast);
+ }
+ if (std::string(lua_tostring(L, -1)) == "owner") {
+ result->setType(PubSubAffiliation::Owner);
+ }
+ if (std::string(lua_tostring(L, -1)) == "publisher") {
+ result->setType(PubSubAffiliation::Publisher);
+ }
+ if (std::string(lua_tostring(L, -1)) == "publish_only") {
+ result->setType(PubSubAffiliation::PublishOnly);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubAffiliationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubAffiliation> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- switch (payload->getType()) {
- case PubSubAffiliation::None:
- lua_pushstring(L, "none");
- break;
- case PubSubAffiliation::Member:
- lua_pushstring(L, "member");
- break;
- case PubSubAffiliation::Outcast:
- lua_pushstring(L, "outcast");
- break;
- case PubSubAffiliation::Owner:
- lua_pushstring(L, "owner");
- break;
- case PubSubAffiliation::Publisher:
- lua_pushstring(L, "publisher");
- break;
- case PubSubAffiliation::PublishOnly:
- lua_pushstring(L, "publish_only");
- break;
- }
- lua_setfield(L, -2, "type");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ switch (payload->getType()) {
+ case PubSubAffiliation::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubAffiliation::Member:
+ lua_pushstring(L, "member");
+ break;
+ case PubSubAffiliation::Outcast:
+ lua_pushstring(L, "outcast");
+ break;
+ case PubSubAffiliation::Owner:
+ lua_pushstring(L, "owner");
+ break;
+ case PubSubAffiliation::Publisher:
+ lua_pushstring(L, "publisher");
+ break;
+ case PubSubAffiliation::PublishOnly:
+ lua_pushstring(L, "publish_only");
+ break;
+ }
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> PubSubAffiliationConvertor::getDocumentation() const {
- return Documentation(
- "PubSubAffiliation",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n"
- );
+ return Documentation(
+ "PubSubAffiliation",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubAffiliationConvertor.h b/Sluift/ElementConvertors/PubSubAffiliationConvertor.h
index 7faf9e5..e91342c 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubAffiliationConvertor : public GenericLuaElementConvertor<PubSubAffiliation> {
- public:
- PubSubAffiliationConvertor();
- virtual ~PubSubAffiliationConvertor();
+ class PubSubAffiliationConvertor : public GenericLuaElementConvertor<PubSubAffiliation> {
+ public:
+ PubSubAffiliationConvertor();
+ virtual ~PubSubAffiliationConvertor();
- virtual boost::shared_ptr<PubSubAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubAffiliation>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubAffiliation>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
index e0d003c..f5eab7a 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
@@ -17,63 +17,63 @@
using namespace Swift;
-PubSubAffiliationsConvertor::PubSubAffiliationsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubAffiliations>("pubsub_affiliations"),
- convertors(convertors) {
+PubSubAffiliationsConvertor::PubSubAffiliationsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubAffiliations>("pubsub_affiliations"),
+ convertors(convertors) {
}
PubSubAffiliationsConvertor::~PubSubAffiliationsConvertor() {
}
boost::shared_ptr<PubSubAffiliations> PubSubAffiliationsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubAffiliations> result = boost::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< boost::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 (boost::shared_ptr<PubSubAffiliation> payload = boost::dynamic_pointer_cast<PubSubAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubAffiliations> result = boost::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< boost::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 (boost::shared_ptr<PubSubAffiliation> payload = boost::dynamic_pointer_cast<PubSubAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setAffiliations(items);
- }
- return result;
+ result->setAffiliations(items);
+ }
+ return result;
}
void PubSubAffiliationsConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubAffiliation> item, payload->getAffiliations()) {
- if (convertors->convertToLuaUntyped(L, item) > 0) {
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- ++i;
- }
- }
- }
- }
+ 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(boost::shared_ptr<PubSubAffiliation> 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"
- );
+ return Documentation(
+ "PubSubAffiliations",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `affiliations`: array<@{PubSubAffiliation}>\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h
index b98ff4c..965fb2a 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubAffiliationsConvertor : public GenericLuaElementConvertor<PubSubAffiliations> {
- public:
- PubSubAffiliationsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubAffiliationsConvertor();
+ class PubSubAffiliationsConvertor : public GenericLuaElementConvertor<PubSubAffiliations> {
+ public:
+ PubSubAffiliationsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubAffiliationsConvertor();
- virtual boost::shared_ptr<PubSubAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubAffiliations>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubAffiliations>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp b/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp
index 9153d9e..13ffb7b 100644
--- a/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp
@@ -14,37 +14,37 @@
using namespace Swift;
-PubSubConfigureConvertor::PubSubConfigureConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubConfigure>("pubsub_configure"),
- convertors(convertors) {
+PubSubConfigureConvertor::PubSubConfigureConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubConfigure>("pubsub_configure"),
+ convertors(convertors) {
}
PubSubConfigureConvertor::~PubSubConfigureConvertor() {
}
boost::shared_ptr<PubSubConfigure> PubSubConfigureConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubConfigure> result = boost::make_shared<PubSubConfigure>();
- lua_getfield(L, -1, "data");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setData(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubConfigure> result = boost::make_shared<PubSubConfigure>();
+ lua_getfield(L, -1, "data");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setData(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubConfigureConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubConfigure> payload) {
- lua_createtable(L, 0, 0);
- if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
- lua_setfield(L, -2, "data");
- }
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
+ lua_setfield(L, -2, "data");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubConfigureConvertor::getDocumentation() const {
- return Documentation(
- "PubSubConfigure",
- "This table has the following fields:\n\n"
- "- `data`: @{Form}\n"
- );
+ return Documentation(
+ "PubSubConfigure",
+ "This table has the following fields:\n\n"
+ "- `data`: @{Form}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubConfigureConvertor.h b/Sluift/ElementConvertors/PubSubConfigureConvertor.h
index 27aa906..865d30a 100644
--- a/Sluift/ElementConvertors/PubSubConfigureConvertor.h
+++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubConfigureConvertor : public GenericLuaElementConvertor<PubSubConfigure> {
- public:
- PubSubConfigureConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubConfigureConvertor();
+ class PubSubConfigureConvertor : public GenericLuaElementConvertor<PubSubConfigure> {
+ public:
+ PubSubConfigureConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubConfigureConvertor();
- virtual boost::shared_ptr<PubSubConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubConfigure>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubConfigure>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubCreateConvertor.cpp b/Sluift/ElementConvertors/PubSubCreateConvertor.cpp
index af5056f..8a4086b 100644
--- a/Sluift/ElementConvertors/PubSubCreateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubCreateConvertor.cpp
@@ -14,45 +14,45 @@
using namespace Swift;
-PubSubCreateConvertor::PubSubCreateConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubCreate>("pubsub_create"),
- convertors(convertors) {
+PubSubCreateConvertor::PubSubCreateConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubCreate>("pubsub_create"),
+ convertors(convertors) {
}
PubSubCreateConvertor::~PubSubCreateConvertor() {
}
boost::shared_ptr<PubSubCreate> PubSubCreateConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubCreate> result = boost::make_shared<PubSubCreate>();
- 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, "configure");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubConfigure> payload = boost::dynamic_pointer_cast<PubSubConfigure>(convertors->convertFromLuaUntyped(L, -1, "pubsub_configure"))) {
- result->setConfigure(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubCreate> result = boost::make_shared<PubSubCreate>();
+ 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, "configure");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubConfigure> payload = boost::dynamic_pointer_cast<PubSubConfigure>(convertors->convertFromLuaUntyped(L, -1, "pubsub_configure"))) {
+ result->setConfigure(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubCreateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubCreate> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- if (convertors->convertToLuaUntyped(L, payload->getConfigure()) > 0) {
- lua_setfield(L, -2, "configure");
- }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (convertors->convertToLuaUntyped(L, payload->getConfigure()) > 0) {
+ lua_setfield(L, -2, "configure");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubCreateConvertor::getDocumentation() const {
- return Documentation(
- "PubSubCreate",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `configure`: @{PubSubConfigure}\n"
- );
+ return Documentation(
+ "PubSubCreate",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `configure`: @{PubSubConfigure}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubCreateConvertor.h b/Sluift/ElementConvertors/PubSubCreateConvertor.h
index bcf06af..189da27 100644
--- a/Sluift/ElementConvertors/PubSubCreateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubCreateConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubCreateConvertor : public GenericLuaElementConvertor<PubSubCreate> {
- public:
- PubSubCreateConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubCreateConvertor();
+ class PubSubCreateConvertor : public GenericLuaElementConvertor<PubSubCreate> {
+ public:
+ PubSubCreateConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubCreateConvertor();
- virtual boost::shared_ptr<PubSubCreate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubCreate>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubCreate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubCreate>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp b/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp
index 43dcbe4..5f8fe24 100644
--- a/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp
@@ -13,60 +13,60 @@
using namespace Swift;
PubSubDefaultConvertor::PubSubDefaultConvertor() :
- GenericLuaElementConvertor<PubSubDefault>("pubsub_default") {
+ GenericLuaElementConvertor<PubSubDefault>("pubsub_default") {
}
PubSubDefaultConvertor::~PubSubDefaultConvertor() {
}
boost::shared_ptr<PubSubDefault> PubSubDefaultConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubDefault> result = boost::make_shared<PubSubDefault>();
- 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, "type");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setType(PubSubDefault::None);
- }
- if (std::string(lua_tostring(L, -1)) == "collection") {
- result->setType(PubSubDefault::Collection);
- }
- if (std::string(lua_tostring(L, -1)) == "leaf") {
- result->setType(PubSubDefault::Leaf);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubDefault> result = boost::make_shared<PubSubDefault>();
+ 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, "type");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setType(PubSubDefault::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "collection") {
+ result->setType(PubSubDefault::Collection);
+ }
+ if (std::string(lua_tostring(L, -1)) == "leaf") {
+ result->setType(PubSubDefault::Leaf);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubDefaultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubDefault> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- switch (payload->getType()) {
- case PubSubDefault::None:
- lua_pushstring(L, "none");
- break;
- case PubSubDefault::Collection:
- lua_pushstring(L, "collection");
- break;
- case PubSubDefault::Leaf:
- lua_pushstring(L, "leaf");
- break;
- }
- lua_setfield(L, -2, "type");
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ switch (payload->getType()) {
+ case PubSubDefault::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubDefault::Collection:
+ lua_pushstring(L, "collection");
+ break;
+ case PubSubDefault::Leaf:
+ lua_pushstring(L, "leaf");
+ break;
+ }
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> PubSubDefaultConvertor::getDocumentation() const {
- return Documentation(
- "PubSubDefault",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `type`: `\"none\"`, `\"collection\"`, or `\"leaf\"`\n"
- );
+ return Documentation(
+ "PubSubDefault",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `type`: `\"none\"`, `\"collection\"`, or `\"leaf\"`\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubDefaultConvertor.h b/Sluift/ElementConvertors/PubSubDefaultConvertor.h
index 2eeeaa1..968e03e 100644
--- a/Sluift/ElementConvertors/PubSubDefaultConvertor.h
+++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubDefaultConvertor : public GenericLuaElementConvertor<PubSubDefault> {
- public:
- PubSubDefaultConvertor();
- virtual ~PubSubDefaultConvertor();
+ class PubSubDefaultConvertor : public GenericLuaElementConvertor<PubSubDefault> {
+ public:
+ PubSubDefaultConvertor();
+ virtual ~PubSubDefaultConvertor();
- virtual boost::shared_ptr<PubSubDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubDefault>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubDefault>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp
index fdfec29..bc43b93 100644
--- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubEventAssociateConvertor::PubSubEventAssociateConvertor() :
- GenericLuaElementConvertor<PubSubEventAssociate>("pubsub_event_associate") {
+ GenericLuaElementConvertor<PubSubEventAssociate>("pubsub_event_associate") {
}
PubSubEventAssociateConvertor::~PubSubEventAssociateConvertor() {
}
boost::shared_ptr<PubSubEventAssociate> PubSubEventAssociateConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventAssociate> result = boost::make_shared<PubSubEventAssociate>();
- lua_getfield(L, -1, "node");
- if (lua_isstring(L, -1)) {
- result->setNode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventAssociate> result = boost::make_shared<PubSubEventAssociate>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventAssociateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventAssociate> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventAssociateConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventAssociate",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- );
+ return Documentation(
+ "PubSubEventAssociate",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h
index 116947d..2ba3b40 100644
--- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventAssociateConvertor : public GenericLuaElementConvertor<PubSubEventAssociate> {
- public:
- PubSubEventAssociateConvertor();
- virtual ~PubSubEventAssociateConvertor();
+ class PubSubEventAssociateConvertor : public GenericLuaElementConvertor<PubSubEventAssociate> {
+ public:
+ PubSubEventAssociateConvertor();
+ virtual ~PubSubEventAssociateConvertor();
- virtual boost::shared_ptr<PubSubEventAssociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventAssociate>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventAssociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventAssociate>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp
index 35eeda4..88c7419 100644
--- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp
@@ -14,58 +14,58 @@
using namespace Swift;
-PubSubEventCollectionConvertor::PubSubEventCollectionConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventCollection>("pubsub_event_collection"),
- convertors(convertors) {
+PubSubEventCollectionConvertor::PubSubEventCollectionConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEventCollection>("pubsub_event_collection"),
+ convertors(convertors) {
}
PubSubEventCollectionConvertor::~PubSubEventCollectionConvertor() {
}
boost::shared_ptr<PubSubEventCollection> PubSubEventCollectionConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventCollection> result = boost::make_shared<PubSubEventCollection>();
- 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, "disassociate");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubEventDisassociate> payload = boost::dynamic_pointer_cast<PubSubEventDisassociate>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_disassociate"))) {
- result->setDisassociate(payload);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "associate");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubEventAssociate> payload = boost::dynamic_pointer_cast<PubSubEventAssociate>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_associate"))) {
- result->setAssociate(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventCollection> result = boost::make_shared<PubSubEventCollection>();
+ 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, "disassociate");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubEventDisassociate> payload = boost::dynamic_pointer_cast<PubSubEventDisassociate>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_disassociate"))) {
+ result->setDisassociate(payload);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "associate");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubEventAssociate> payload = boost::dynamic_pointer_cast<PubSubEventAssociate>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_associate"))) {
+ result->setAssociate(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventCollectionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventCollection> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- if (convertors->convertToLuaUntyped(L, payload->getDisassociate()) > 0) {
- lua_setfield(L, -2, "disassociate");
- }
- if (convertors->convertToLuaUntyped(L, payload->getAssociate()) > 0) {
- lua_setfield(L, -2, "associate");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (convertors->convertToLuaUntyped(L, payload->getDisassociate()) > 0) {
+ lua_setfield(L, -2, "disassociate");
+ }
+ if (convertors->convertToLuaUntyped(L, payload->getAssociate()) > 0) {
+ lua_setfield(L, -2, "associate");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventCollectionConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventCollection",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `disassociate`: @{PubSubEventDisassociate}\n"
- "- `associate`: @{PubSubEventAssociate}\n"
- );
+ return Documentation(
+ "PubSubEventCollection",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `disassociate`: @{PubSubEventDisassociate}\n"
+ "- `associate`: @{PubSubEventAssociate}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h
index 38ffd64..7c11178 100644
--- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventCollectionConvertor : public GenericLuaElementConvertor<PubSubEventCollection> {
- public:
- PubSubEventCollectionConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventCollectionConvertor();
+ class PubSubEventCollectionConvertor : public GenericLuaElementConvertor<PubSubEventCollection> {
+ public:
+ PubSubEventCollectionConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventCollectionConvertor();
- virtual boost::shared_ptr<PubSubEventCollection> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventCollection>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEventCollection> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventCollection>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp
index 72c15ae..2c149fa 100644
--- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp
@@ -14,45 +14,45 @@
using namespace Swift;
-PubSubEventConfigurationConvertor::PubSubEventConfigurationConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventConfiguration>("pubsub_event_configuration"),
- convertors(convertors) {
+PubSubEventConfigurationConvertor::PubSubEventConfigurationConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEventConfiguration>("pubsub_event_configuration"),
+ convertors(convertors) {
}
PubSubEventConfigurationConvertor::~PubSubEventConfigurationConvertor() {
}
boost::shared_ptr<PubSubEventConfiguration> PubSubEventConfigurationConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventConfiguration> result = boost::make_shared<PubSubEventConfiguration>();
- 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, "data");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setData(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventConfiguration> result = boost::make_shared<PubSubEventConfiguration>();
+ 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, "data");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setData(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventConfigurationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventConfiguration> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
- lua_setfield(L, -2, "data");
- }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
+ lua_setfield(L, -2, "data");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventConfigurationConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventConfiguration",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `data`: @{Form}\n"
- );
+ return Documentation(
+ "PubSubEventConfiguration",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `data`: @{Form}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h
index 7e8ea02..e8a17e7 100644
--- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventConfigurationConvertor : public GenericLuaElementConvertor<PubSubEventConfiguration> {
- public:
- PubSubEventConfigurationConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventConfigurationConvertor();
+ class PubSubEventConfigurationConvertor : public GenericLuaElementConvertor<PubSubEventConfiguration> {
+ public:
+ PubSubEventConfigurationConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventConfigurationConvertor();
- virtual boost::shared_ptr<PubSubEventConfiguration> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventConfiguration>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEventConfiguration> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventConfiguration>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventConvertor.cpp b/Sluift/ElementConvertors/PubSubEventConvertor.cpp
index fa64e7f..2330bcc 100644
--- a/Sluift/ElementConvertors/PubSubEventConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventConvertor.cpp
@@ -14,22 +14,22 @@
using namespace Swift;
-PubSubEventConvertor::PubSubEventConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEvent>("pubsub_event"),
- convertors(convertors) {
+PubSubEventConvertor::PubSubEventConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEvent>("pubsub_event"),
+ convertors(convertors) {
}
PubSubEventConvertor::~PubSubEventConvertor() {
}
boost::shared_ptr<PubSubEvent> PubSubEventConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEvent> result = boost::make_shared<PubSubEvent>();
- if (boost::shared_ptr<PubSubEventPayload> payload = boost::dynamic_pointer_cast<PubSubEventPayload>(convertors->convertFromLua(L, -1))) {
- result->setPayload(payload);
- }
- return result;
+ boost::shared_ptr<PubSubEvent> result = boost::make_shared<PubSubEvent>();
+ if (boost::shared_ptr<PubSubEventPayload> payload = boost::dynamic_pointer_cast<PubSubEventPayload>(convertors->convertFromLua(L, -1))) {
+ result->setPayload(payload);
+ }
+ return result;
}
void PubSubEventConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEvent> event) {
- convertors->convertToLua(L, event->getPayload());
+ convertors->convertToLua(L, event->getPayload());
}
diff --git a/Sluift/ElementConvertors/PubSubEventConvertor.h b/Sluift/ElementConvertors/PubSubEventConvertor.h
index ab19c8f..2797b88 100644
--- a/Sluift/ElementConvertors/PubSubEventConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventConvertor.h
@@ -12,17 +12,17 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventConvertor : public GenericLuaElementConvertor<PubSubEvent> {
- public:
- PubSubEventConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventConvertor();
+ class PubSubEventConvertor : public GenericLuaElementConvertor<PubSubEvent> {
+ public:
+ PubSubEventConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventConvertor();
- virtual boost::shared_ptr<PubSubEvent> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEvent>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEvent> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEvent>) SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
index d44d1a6..aa77319 100644
--- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
@@ -14,45 +14,45 @@
using namespace Swift;
-PubSubEventDeleteConvertor::PubSubEventDeleteConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventDelete>("pubsub_event_delete"),
- convertors(convertors) {
+PubSubEventDeleteConvertor::PubSubEventDeleteConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEventDelete>("pubsub_event_delete"),
+ convertors(convertors) {
}
PubSubEventDeleteConvertor::~PubSubEventDeleteConvertor() {
}
boost::shared_ptr<PubSubEventDelete> PubSubEventDeleteConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventDelete> result = boost::make_shared<PubSubEventDelete>();
- 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, "redirects");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubEventRedirect> payload = boost::dynamic_pointer_cast<PubSubEventRedirect>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_redirect"))) {
- result->setRedirects(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventDelete> result = boost::make_shared<PubSubEventDelete>();
+ 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, "redirects");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubEventRedirect> payload = boost::dynamic_pointer_cast<PubSubEventRedirect>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_redirect"))) {
+ result->setRedirects(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventDeleteConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventDelete> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- if (convertors->convertToLuaUntyped(L, payload->getRedirects()) > 0) {
- lua_setfield(L, -2, "redirects");
- }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (convertors->convertToLuaUntyped(L, payload->getRedirects()) > 0) {
+ lua_setfield(L, -2, "redirects");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventDeleteConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventDelete",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `redirects`: @{PubSubEventRedirect}\n"
- );
+ return Documentation(
+ "PubSubEventDelete",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `redirects`: @{PubSubEventRedirect}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h
index c8ff8cd..b53c3d7 100644
--- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventDeleteConvertor : public GenericLuaElementConvertor<PubSubEventDelete> {
- public:
- PubSubEventDeleteConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventDeleteConvertor();
+ class PubSubEventDeleteConvertor : public GenericLuaElementConvertor<PubSubEventDelete> {
+ public:
+ PubSubEventDeleteConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventDeleteConvertor();
- virtual boost::shared_ptr<PubSubEventDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventDelete>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEventDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventDelete>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp
index 4811cc2..1d417ac 100644
--- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubEventDisassociateConvertor::PubSubEventDisassociateConvertor() :
- GenericLuaElementConvertor<PubSubEventDisassociate>("pubsub_event_disassociate") {
+ GenericLuaElementConvertor<PubSubEventDisassociate>("pubsub_event_disassociate") {
}
PubSubEventDisassociateConvertor::~PubSubEventDisassociateConvertor() {
}
boost::shared_ptr<PubSubEventDisassociate> PubSubEventDisassociateConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventDisassociate> result = boost::make_shared<PubSubEventDisassociate>();
- lua_getfield(L, -1, "node");
- if (lua_isstring(L, -1)) {
- result->setNode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventDisassociate> result = boost::make_shared<PubSubEventDisassociate>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventDisassociateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventDisassociate> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventDisassociateConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventDisassociate",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- );
+ return Documentation(
+ "PubSubEventDisassociate",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h
index 69f2d11..9a34ac3 100644
--- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor<PubSubEventDisassociate> {
- public:
- PubSubEventDisassociateConvertor();
- virtual ~PubSubEventDisassociateConvertor();
+ class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor<PubSubEventDisassociate> {
+ public:
+ PubSubEventDisassociateConvertor();
+ virtual ~PubSubEventDisassociateConvertor();
- virtual boost::shared_ptr<PubSubEventDisassociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventDisassociate>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventDisassociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventDisassociate>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
index 7e6131a..c8373f5 100644
--- a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
@@ -17,87 +17,87 @@
using namespace Swift;
-PubSubEventItemConvertor::PubSubEventItemConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventItem>("pubsub_event_item"),
- convertors(convertors) {
+PubSubEventItemConvertor::PubSubEventItemConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEventItem>("pubsub_event_item"),
+ convertors(convertors) {
}
PubSubEventItemConvertor::~PubSubEventItemConvertor() {
}
boost::shared_ptr<PubSubEventItem> PubSubEventItemConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventItem> result = boost::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< boost::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 (boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubEventItem> result = boost::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< boost::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 (boost::shared_ptr<Payload> payload = boost::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;
+ 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, boost::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(boost::shared_ptr<Payload> 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");
- }
+ 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(boost::shared_ptr<Payload> 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"
- );
+ 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/PubSubEventItemConvertor.h b/Sluift/ElementConvertors/PubSubEventItemConvertor.h
index 7dfeef6..1f67b9f 100644
--- a/Sluift/ElementConvertors/PubSubEventItemConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventItemConvertor : public GenericLuaElementConvertor<PubSubEventItem> {
- public:
- PubSubEventItemConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventItemConvertor();
+ class PubSubEventItemConvertor : public GenericLuaElementConvertor<PubSubEventItem> {
+ public:
+ PubSubEventItemConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventItemConvertor();
- virtual boost::shared_ptr<PubSubEventItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventItem>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEventItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventItem>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
index 66400e9..0c2035f 100644
--- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
@@ -17,96 +17,96 @@
using namespace Swift;
-PubSubEventItemsConvertor::PubSubEventItemsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventItems>("pubsub_event_items"),
- convertors(convertors) {
+PubSubEventItemsConvertor::PubSubEventItemsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubEventItems>("pubsub_event_items"),
+ convertors(convertors) {
}
PubSubEventItemsConvertor::~PubSubEventItemsConvertor() {
}
boost::shared_ptr<PubSubEventItems> PubSubEventItemsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventItems> result = boost::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< boost::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 (boost::shared_ptr<PubSubEventItem> payload = boost::dynamic_pointer_cast<PubSubEventItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubEventItems> result = boost::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< boost::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 (boost::shared_ptr<PubSubEventItem> payload = boost::dynamic_pointer_cast<PubSubEventItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setItems(items);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "retracts");
- if (lua_type(L, -1) == LUA_TTABLE) {
- std::vector< boost::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 (boost::shared_ptr<PubSubEventRetract> payload = boost::dynamic_pointer_cast<PubSubEventRetract>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_retract"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ result->setItems(items);
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "retracts");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< boost::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 (boost::shared_ptr<PubSubEventRetract> payload = boost::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;
+ result->setRetracts(items);
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventItemsConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubEventItem> 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(boost::shared_ptr<PubSubEventRetract> 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");
- }
+ 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(boost::shared_ptr<PubSubEventItem> 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(boost::shared_ptr<PubSubEventRetract> 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"
- );
+ 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/PubSubEventItemsConvertor.h b/Sluift/ElementConvertors/PubSubEventItemsConvertor.h
index 347200e..b644e7a 100644
--- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventItemsConvertor : public GenericLuaElementConvertor<PubSubEventItems> {
- public:
- PubSubEventItemsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventItemsConvertor();
+ class PubSubEventItemsConvertor : public GenericLuaElementConvertor<PubSubEventItems> {
+ public:
+ PubSubEventItemsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubEventItemsConvertor();
- virtual boost::shared_ptr<PubSubEventItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventItems>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubEventItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventItems>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp
index bd036c1..3b67704 100644
--- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubEventPurgeConvertor::PubSubEventPurgeConvertor() :
- GenericLuaElementConvertor<PubSubEventPurge>("pubsub_event_purge") {
+ GenericLuaElementConvertor<PubSubEventPurge>("pubsub_event_purge") {
}
PubSubEventPurgeConvertor::~PubSubEventPurgeConvertor() {
}
boost::shared_ptr<PubSubEventPurge> PubSubEventPurgeConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventPurge> result = boost::make_shared<PubSubEventPurge>();
- lua_getfield(L, -1, "node");
- if (lua_isstring(L, -1)) {
- result->setNode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventPurge> result = boost::make_shared<PubSubEventPurge>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventPurgeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventPurge> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventPurgeConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventPurge",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- );
+ return Documentation(
+ "PubSubEventPurge",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h
index 88af6f4..b149426 100644
--- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventPurgeConvertor : public GenericLuaElementConvertor<PubSubEventPurge> {
- public:
- PubSubEventPurgeConvertor();
- virtual ~PubSubEventPurgeConvertor();
+ class PubSubEventPurgeConvertor : public GenericLuaElementConvertor<PubSubEventPurge> {
+ public:
+ PubSubEventPurgeConvertor();
+ virtual ~PubSubEventPurgeConvertor();
- virtual boost::shared_ptr<PubSubEventPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventPurge>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventPurge>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp
index 81584e3..ac40d31 100644
--- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubEventRedirectConvertor::PubSubEventRedirectConvertor() :
- GenericLuaElementConvertor<PubSubEventRedirect>("pubsub_event_redirect") {
+ GenericLuaElementConvertor<PubSubEventRedirect>("pubsub_event_redirect") {
}
PubSubEventRedirectConvertor::~PubSubEventRedirectConvertor() {
}
boost::shared_ptr<PubSubEventRedirect> PubSubEventRedirectConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventRedirect> result = boost::make_shared<PubSubEventRedirect>();
- lua_getfield(L, -1, "uri");
- if (lua_isstring(L, -1)) {
- result->setURI(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventRedirect> result = boost::make_shared<PubSubEventRedirect>();
+ lua_getfield(L, -1, "uri");
+ if (lua_isstring(L, -1)) {
+ result->setURI(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventRedirectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventRedirect> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getURI().c_str());
- lua_setfield(L, -2, "uri");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getURI().c_str());
+ lua_setfield(L, -2, "uri");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventRedirectConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventRedirect",
- "This table has the following fields:\n\n"
- "- `uri`: string\n"
- );
+ return Documentation(
+ "PubSubEventRedirect",
+ "This table has the following fields:\n\n"
+ "- `uri`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h
index d5724ae..bdf7951 100644
--- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventRedirectConvertor : public GenericLuaElementConvertor<PubSubEventRedirect> {
- public:
- PubSubEventRedirectConvertor();
- virtual ~PubSubEventRedirectConvertor();
+ class PubSubEventRedirectConvertor : public GenericLuaElementConvertor<PubSubEventRedirect> {
+ public:
+ PubSubEventRedirectConvertor();
+ virtual ~PubSubEventRedirectConvertor();
- virtual boost::shared_ptr<PubSubEventRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventRedirect>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventRedirect>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp b/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp
index f851306..15eec91 100644
--- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubEventRetractConvertor::PubSubEventRetractConvertor() :
- GenericLuaElementConvertor<PubSubEventRetract>("pubsub_event_retract") {
+ GenericLuaElementConvertor<PubSubEventRetract>("pubsub_event_retract") {
}
PubSubEventRetractConvertor::~PubSubEventRetractConvertor() {
}
boost::shared_ptr<PubSubEventRetract> PubSubEventRetractConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventRetract> result = boost::make_shared<PubSubEventRetract>();
- lua_getfield(L, -1, "id");
- if (lua_isstring(L, -1)) {
- result->setID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventRetract> result = boost::make_shared<PubSubEventRetract>();
+ 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 PubSubEventRetractConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventRetract> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getID().c_str());
- lua_setfield(L, -2, "id");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getID().c_str());
+ lua_setfield(L, -2, "id");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventRetractConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventRetract",
- "This table has the following fields:\n\n"
- "- `id`: string\n"
- );
+ return Documentation(
+ "PubSubEventRetract",
+ "This table has the following fields:\n\n"
+ "- `id`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventRetractConvertor.h b/Sluift/ElementConvertors/PubSubEventRetractConvertor.h
index 72ca0a3..38208b0 100644
--- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventRetractConvertor : public GenericLuaElementConvertor<PubSubEventRetract> {
- public:
- PubSubEventRetractConvertor();
- virtual ~PubSubEventRetractConvertor();
+ class PubSubEventRetractConvertor : public GenericLuaElementConvertor<PubSubEventRetract> {
+ public:
+ PubSubEventRetractConvertor();
+ virtual ~PubSubEventRetractConvertor();
- virtual boost::shared_ptr<PubSubEventRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventRetract>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventRetract>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp
index d83f6be..57be1c4 100644
--- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp
@@ -15,90 +15,90 @@
using namespace Swift;
PubSubEventSubscriptionConvertor::PubSubEventSubscriptionConvertor() :
- GenericLuaElementConvertor<PubSubEventSubscription>("pubsub_event_subscription") {
+ GenericLuaElementConvertor<PubSubEventSubscription>("pubsub_event_subscription") {
}
PubSubEventSubscriptionConvertor::~PubSubEventSubscriptionConvertor() {
}
boost::shared_ptr<PubSubEventSubscription> PubSubEventSubscriptionConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubEventSubscription> result = boost::make_shared<PubSubEventSubscription>();
- 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, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "subscription");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setSubscription(PubSubEventSubscription::None);
- }
- if (std::string(lua_tostring(L, -1)) == "pending") {
- result->setSubscription(PubSubEventSubscription::Pending);
- }
- if (std::string(lua_tostring(L, -1)) == "subscribed") {
- result->setSubscription(PubSubEventSubscription::Subscribed);
- }
- if (std::string(lua_tostring(L, -1)) == "unconfigured") {
- result->setSubscription(PubSubEventSubscription::Unconfigured);
- }
- }
- 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);
- lua_getfield(L, -1, "expiry");
- if (lua_isstring(L, -1)) {
- result->setExpiry(stringToDateTime(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubEventSubscription> result = boost::make_shared<PubSubEventSubscription>();
+ 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, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "subscription");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setSubscription(PubSubEventSubscription::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "pending") {
+ result->setSubscription(PubSubEventSubscription::Pending);
+ }
+ if (std::string(lua_tostring(L, -1)) == "subscribed") {
+ result->setSubscription(PubSubEventSubscription::Subscribed);
+ }
+ if (std::string(lua_tostring(L, -1)) == "unconfigured") {
+ result->setSubscription(PubSubEventSubscription::Unconfigured);
+ }
+ }
+ 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);
+ lua_getfield(L, -1, "expiry");
+ if (lua_isstring(L, -1)) {
+ result->setExpiry(stringToDateTime(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubEventSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubEventSubscription> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- switch (payload->getSubscription()) {
- case PubSubEventSubscription::None:
- lua_pushstring(L, "none");
- break;
- case PubSubEventSubscription::Pending:
- lua_pushstring(L, "pending");
- break;
- case PubSubEventSubscription::Subscribed:
- lua_pushstring(L, "subscribed");
- break;
- case PubSubEventSubscription::Unconfigured:
- lua_pushstring(L, "unconfigured");
- break;
- }
- lua_setfield(L, -2, "subscription");
- if (payload->getSubscriptionID()) {
- lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
- lua_setfield(L, -2, "subscription_id");
- }
- lua_pushstring(L, dateTimeToString(payload->getExpiry()).c_str());
- lua_setfield(L, -2, "expiry");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ switch (payload->getSubscription()) {
+ case PubSubEventSubscription::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubEventSubscription::Pending:
+ lua_pushstring(L, "pending");
+ break;
+ case PubSubEventSubscription::Subscribed:
+ lua_pushstring(L, "subscribed");
+ break;
+ case PubSubEventSubscription::Unconfigured:
+ lua_pushstring(L, "unconfigured");
+ break;
+ }
+ lua_setfield(L, -2, "subscription");
+ if (payload->getSubscriptionID()) {
+ lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
+ lua_setfield(L, -2, "subscription_id");
+ }
+ lua_pushstring(L, dateTimeToString(payload->getExpiry()).c_str());
+ lua_setfield(L, -2, "expiry");
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventSubscriptionConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventSubscription",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `jid`: jid (string)\n"
- "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
- "- `subscription_id`: string (Optional)\n"
- "- `expiry`: datetime (string)\n"
- );
+ return Documentation(
+ "PubSubEventSubscription",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `jid`: jid (string)\n"
+ "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
+ "- `subscription_id`: string (Optional)\n"
+ "- `expiry`: datetime (string)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h
index 837a03b..8ee9da5 100644
--- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor<PubSubEventSubscription> {
- public:
- PubSubEventSubscriptionConvertor();
- virtual ~PubSubEventSubscriptionConvertor();
+ class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor<PubSubEventSubscription> {
+ public:
+ PubSubEventSubscriptionConvertor();
+ virtual ~PubSubEventSubscriptionConvertor();
- virtual boost::shared_ptr<PubSubEventSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventSubscription>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubEventSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubEventSubscription>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubItemConvertor.cpp b/Sluift/ElementConvertors/PubSubItemConvertor.cpp
index 60f7946..b88f989 100644
--- a/Sluift/ElementConvertors/PubSubItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemConvertor.cpp
@@ -17,65 +17,65 @@
using namespace Swift;
-PubSubItemConvertor::PubSubItemConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubItem>("pubsub_item"),
- convertors(convertors) {
+PubSubItemConvertor::PubSubItemConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubItem>("pubsub_item"),
+ convertors(convertors) {
}
PubSubItemConvertor::~PubSubItemConvertor() {
}
boost::shared_ptr<PubSubItem> PubSubItemConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubItem> result = boost::make_shared<PubSubItem>();
- lua_getfield(L, -1, "data");
- if (lua_type(L, -1) == LUA_TTABLE) {
- std::vector< boost::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 (boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubItem> result = boost::make_shared<PubSubItem>();
+ lua_getfield(L, -1, "data");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< boost::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 (boost::shared_ptr<Payload> payload = boost::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;
+ 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, boost::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(boost::shared_ptr<Payload> 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");
+ lua_createtable(L, 0, 0);
+ if (!payload->getData().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getData().size()), 0);
+ {
+ int i = 0;
+ foreach(boost::shared_ptr<Payload> 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"
- );
+ return Documentation(
+ "PubSubItem",
+ "This table has the following fields:\n\n"
+ "- `data`: array<element (table)>\n"
+ "- `id`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubItemConvertor.h b/Sluift/ElementConvertors/PubSubItemConvertor.h
index 7f4adbf..1bc2467 100644
--- a/Sluift/ElementConvertors/PubSubItemConvertor.h
+++ b/Sluift/ElementConvertors/PubSubItemConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubItemConvertor : public GenericLuaElementConvertor<PubSubItem> {
- public:
- PubSubItemConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubItemConvertor();
+ class PubSubItemConvertor : public GenericLuaElementConvertor<PubSubItem> {
+ public:
+ PubSubItemConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubItemConvertor();
- virtual boost::shared_ptr<PubSubItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubItem>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubItem>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
index 9b99c86..571bc46 100644
--- a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
@@ -17,81 +17,81 @@
using namespace Swift;
-PubSubItemsConvertor::PubSubItemsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubItems>("pubsub_items"),
- convertors(convertors) {
+PubSubItemsConvertor::PubSubItemsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubItems>("pubsub_items"),
+ convertors(convertors) {
}
PubSubItemsConvertor::~PubSubItemsConvertor() {
}
boost::shared_ptr<PubSubItems> PubSubItemsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubItems> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubItems> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::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;
+ 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, boost::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(boost::shared_ptr<PubSubItem> 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");
- }
+ 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(boost::shared_ptr<PubSubItem> 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"
- );
+ 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/PubSubItemsConvertor.h b/Sluift/ElementConvertors/PubSubItemsConvertor.h
index 04943ac..e40d545 100644
--- a/Sluift/ElementConvertors/PubSubItemsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubItemsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubItemsConvertor : public GenericLuaElementConvertor<PubSubItems> {
- public:
- PubSubItemsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubItemsConvertor();
+ class PubSubItemsConvertor : public GenericLuaElementConvertor<PubSubItems> {
+ public:
+ PubSubItemsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubItemsConvertor();
- virtual boost::shared_ptr<PubSubItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubItems>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubItems>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp
index 2beaee9..52976ea 100644
--- a/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp
@@ -14,63 +14,63 @@
using namespace Swift;
-PubSubOptionsConvertor::PubSubOptionsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOptions>("pubsub_options"),
- convertors(convertors) {
+PubSubOptionsConvertor::PubSubOptionsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOptions>("pubsub_options"),
+ convertors(convertors) {
}
PubSubOptionsConvertor::~PubSubOptionsConvertor() {
}
boost::shared_ptr<PubSubOptions> PubSubOptionsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOptions> result = boost::make_shared<PubSubOptions>();
- 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, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "data");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setData(payload);
- }
- }
- 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;
+ boost::shared_ptr<PubSubOptions> result = boost::make_shared<PubSubOptions>();
+ 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, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "data");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setData(payload);
+ }
+ }
+ 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 PubSubOptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOptions> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
- lua_setfield(L, -2, "data");
- }
- if (payload->getSubscriptionID()) {
- lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
- lua_setfield(L, -2, "subscription_id");
- }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
+ lua_setfield(L, -2, "data");
+ }
+ if (payload->getSubscriptionID()) {
+ lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
+ lua_setfield(L, -2, "subscription_id");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOptionsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOptions",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `jid`: jid (string)\n"
- "- `data`: @{Form}\n"
- "- `subscription_id`: string (Optional)\n"
- );
+ return Documentation(
+ "PubSubOptions",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `jid`: jid (string)\n"
+ "- `data`: @{Form}\n"
+ "- `subscription_id`: string (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOptionsConvertor.h b/Sluift/ElementConvertors/PubSubOptionsConvertor.h
index a0ec68e..88fafd3 100644
--- a/Sluift/ElementConvertors/PubSubOptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOptionsConvertor : public GenericLuaElementConvertor<PubSubOptions> {
- public:
- PubSubOptionsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOptionsConvertor();
+ class PubSubOptionsConvertor : public GenericLuaElementConvertor<PubSubOptions> {
+ public:
+ PubSubOptionsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOptionsConvertor();
- virtual boost::shared_ptr<PubSubOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOptions>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOptions>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp
index 7e1ec9a..da835af 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp
@@ -13,76 +13,76 @@
using namespace Swift;
PubSubOwnerAffiliationConvertor::PubSubOwnerAffiliationConvertor() :
- GenericLuaElementConvertor<PubSubOwnerAffiliation>("pubsub_owner_affiliation") {
+ GenericLuaElementConvertor<PubSubOwnerAffiliation>("pubsub_owner_affiliation") {
}
PubSubOwnerAffiliationConvertor::~PubSubOwnerAffiliationConvertor() {
}
boost::shared_ptr<PubSubOwnerAffiliation> PubSubOwnerAffiliationConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerAffiliation> result = boost::make_shared<PubSubOwnerAffiliation>();
- lua_getfield(L, -1, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "type");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setType(PubSubOwnerAffiliation::None);
- }
- if (std::string(lua_tostring(L, -1)) == "member") {
- result->setType(PubSubOwnerAffiliation::Member);
- }
- if (std::string(lua_tostring(L, -1)) == "outcast") {
- result->setType(PubSubOwnerAffiliation::Outcast);
- }
- if (std::string(lua_tostring(L, -1)) == "owner") {
- result->setType(PubSubOwnerAffiliation::Owner);
- }
- if (std::string(lua_tostring(L, -1)) == "publisher") {
- result->setType(PubSubOwnerAffiliation::Publisher);
- }
- if (std::string(lua_tostring(L, -1)) == "publish_only") {
- result->setType(PubSubOwnerAffiliation::PublishOnly);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerAffiliation> result = boost::make_shared<PubSubOwnerAffiliation>();
+ lua_getfield(L, -1, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "type");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setType(PubSubOwnerAffiliation::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "member") {
+ result->setType(PubSubOwnerAffiliation::Member);
+ }
+ if (std::string(lua_tostring(L, -1)) == "outcast") {
+ result->setType(PubSubOwnerAffiliation::Outcast);
+ }
+ if (std::string(lua_tostring(L, -1)) == "owner") {
+ result->setType(PubSubOwnerAffiliation::Owner);
+ }
+ if (std::string(lua_tostring(L, -1)) == "publisher") {
+ result->setType(PubSubOwnerAffiliation::Publisher);
+ }
+ if (std::string(lua_tostring(L, -1)) == "publish_only") {
+ result->setType(PubSubOwnerAffiliation::PublishOnly);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerAffiliationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerAffiliation> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- switch (payload->getType()) {
- case PubSubOwnerAffiliation::None:
- lua_pushstring(L, "none");
- break;
- case PubSubOwnerAffiliation::Member:
- lua_pushstring(L, "member");
- break;
- case PubSubOwnerAffiliation::Outcast:
- lua_pushstring(L, "outcast");
- break;
- case PubSubOwnerAffiliation::Owner:
- lua_pushstring(L, "owner");
- break;
- case PubSubOwnerAffiliation::Publisher:
- lua_pushstring(L, "publisher");
- break;
- case PubSubOwnerAffiliation::PublishOnly:
- lua_pushstring(L, "publish_only");
- break;
- }
- lua_setfield(L, -2, "type");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ switch (payload->getType()) {
+ case PubSubOwnerAffiliation::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubOwnerAffiliation::Member:
+ lua_pushstring(L, "member");
+ break;
+ case PubSubOwnerAffiliation::Outcast:
+ lua_pushstring(L, "outcast");
+ break;
+ case PubSubOwnerAffiliation::Owner:
+ lua_pushstring(L, "owner");
+ break;
+ case PubSubOwnerAffiliation::Publisher:
+ lua_pushstring(L, "publisher");
+ break;
+ case PubSubOwnerAffiliation::PublishOnly:
+ lua_pushstring(L, "publish_only");
+ break;
+ }
+ lua_setfield(L, -2, "type");
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerAffiliationConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerAffiliation",
- "This table has the following fields:\n\n"
- "- `jid`: jid (string)\n"
- "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n"
- );
+ return Documentation(
+ "PubSubOwnerAffiliation",
+ "This table has the following fields:\n\n"
+ "- `jid`: jid (string)\n"
+ "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h
index 6876882..965e708 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliation> {
- public:
- PubSubOwnerAffiliationConvertor();
- virtual ~PubSubOwnerAffiliationConvertor();
+ class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliation> {
+ public:
+ PubSubOwnerAffiliationConvertor();
+ virtual ~PubSubOwnerAffiliationConvertor();
- virtual boost::shared_ptr<PubSubOwnerAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerAffiliation>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubOwnerAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerAffiliation>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
index 4827914..01a4503 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
@@ -17,61 +17,61 @@
using namespace Swift;
-PubSubOwnerAffiliationsConvertor::PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerAffiliations>("pubsub_owner_affiliations"),
- convertors(convertors) {
+PubSubOwnerAffiliationsConvertor::PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOwnerAffiliations>("pubsub_owner_affiliations"),
+ convertors(convertors) {
}
PubSubOwnerAffiliationsConvertor::~PubSubOwnerAffiliationsConvertor() {
}
boost::shared_ptr<PubSubOwnerAffiliations> PubSubOwnerAffiliationsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerAffiliations> result = boost::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< boost::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 (boost::shared_ptr<PubSubOwnerAffiliation> payload = boost::dynamic_pointer_cast<PubSubOwnerAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubOwnerAffiliations> result = boost::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< boost::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 (boost::shared_ptr<PubSubOwnerAffiliation> payload = boost::dynamic_pointer_cast<PubSubOwnerAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setAffiliations(items);
- }
- return result;
+ result->setAffiliations(items);
+ }
+ return result;
}
void PubSubOwnerAffiliationsConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubOwnerAffiliation> item, payload->getAffiliations()) {
- if (convertors->convertToLuaUntyped(L, item) > 0) {
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- ++i;
- }
- }
- }
- }
+ 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(boost::shared_ptr<PubSubOwnerAffiliation> 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"
- );
+ return Documentation(
+ "PubSubOwnerAffiliations",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `affiliations`: array<@{PubSubOwnerAffiliation}>\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h
index f64426a..3644cd8 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerAffiliationsConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliations> {
- public:
- PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerAffiliationsConvertor();
+ class PubSubOwnerAffiliationsConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliations> {
+ public:
+ PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOwnerAffiliationsConvertor();
- virtual boost::shared_ptr<PubSubOwnerAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerAffiliations>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOwnerAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerAffiliations>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp
index 2620649..0d0d49a 100644
--- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp
@@ -14,47 +14,47 @@
using namespace Swift;
-PubSubOwnerConfigureConvertor::PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerConfigure>("pubsub_owner_configure"),
- convertors(convertors) {
+PubSubOwnerConfigureConvertor::PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOwnerConfigure>("pubsub_owner_configure"),
+ convertors(convertors) {
}
PubSubOwnerConfigureConvertor::~PubSubOwnerConfigureConvertor() {
}
boost::shared_ptr<PubSubOwnerConfigure> PubSubOwnerConfigureConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerConfigure> result = boost::make_shared<PubSubOwnerConfigure>();
- 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, "data");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setData(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerConfigure> result = boost::make_shared<PubSubOwnerConfigure>();
+ 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, "data");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setData(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerConfigureConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerConfigure> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
- lua_setfield(L, -2, "data");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
+ lua_setfield(L, -2, "data");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerConfigureConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerConfigure",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `data`: @{Form}\n"
- );
+ return Documentation(
+ "PubSubOwnerConfigure",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `data`: @{Form}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h
index 7555922..d2fb229 100644
--- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerConfigureConvertor : public GenericLuaElementConvertor<PubSubOwnerConfigure> {
- public:
- PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerConfigureConvertor();
+ class PubSubOwnerConfigureConvertor : public GenericLuaElementConvertor<PubSubOwnerConfigure> {
+ public:
+ PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOwnerConfigureConvertor();
- virtual boost::shared_ptr<PubSubOwnerConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerConfigure>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOwnerConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerConfigure>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp
index e493601..9147900 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp
@@ -14,37 +14,37 @@
using namespace Swift;
-PubSubOwnerDefaultConvertor::PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerDefault>("pubsub_owner_default"),
- convertors(convertors) {
+PubSubOwnerDefaultConvertor::PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOwnerDefault>("pubsub_owner_default"),
+ convertors(convertors) {
}
PubSubOwnerDefaultConvertor::~PubSubOwnerDefaultConvertor() {
}
boost::shared_ptr<PubSubOwnerDefault> PubSubOwnerDefaultConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerDefault> result = boost::make_shared<PubSubOwnerDefault>();
- lua_getfield(L, -1, "data");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
- result->setData(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerDefault> result = boost::make_shared<PubSubOwnerDefault>();
+ lua_getfield(L, -1, "data");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<Form> payload = boost::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setData(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerDefaultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerDefault> payload) {
- lua_createtable(L, 0, 0);
- if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
- lua_setfield(L, -2, "data");
- }
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) {
+ lua_setfield(L, -2, "data");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerDefaultConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerDefault",
- "This table has the following fields:\n\n"
- "- `data`: @{Form}\n"
- );
+ return Documentation(
+ "PubSubOwnerDefault",
+ "This table has the following fields:\n\n"
+ "- `data`: @{Form}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h
index d51223a..274cb12 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerDefaultConvertor : public GenericLuaElementConvertor<PubSubOwnerDefault> {
- public:
- PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerDefaultConvertor();
+ class PubSubOwnerDefaultConvertor : public GenericLuaElementConvertor<PubSubOwnerDefault> {
+ public:
+ PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOwnerDefaultConvertor();
- virtual boost::shared_ptr<PubSubOwnerDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerDefault>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOwnerDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerDefault>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp
index 2c818f1..63579b6 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp
@@ -14,45 +14,45 @@
using namespace Swift;
-PubSubOwnerDeleteConvertor::PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerDelete>("pubsub_owner_delete"),
- convertors(convertors) {
+PubSubOwnerDeleteConvertor::PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOwnerDelete>("pubsub_owner_delete"),
+ convertors(convertors) {
}
PubSubOwnerDeleteConvertor::~PubSubOwnerDeleteConvertor() {
}
boost::shared_ptr<PubSubOwnerDelete> PubSubOwnerDeleteConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerDelete> result = boost::make_shared<PubSubOwnerDelete>();
- 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, "redirect");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubOwnerRedirect> payload = boost::dynamic_pointer_cast<PubSubOwnerRedirect>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_redirect"))) {
- result->setRedirect(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerDelete> result = boost::make_shared<PubSubOwnerDelete>();
+ 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, "redirect");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubOwnerRedirect> payload = boost::dynamic_pointer_cast<PubSubOwnerRedirect>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_redirect"))) {
+ result->setRedirect(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerDeleteConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerDelete> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
- if (convertors->convertToLuaUntyped(L, payload->getRedirect()) > 0) {
- lua_setfield(L, -2, "redirect");
- }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (convertors->convertToLuaUntyped(L, payload->getRedirect()) > 0) {
+ lua_setfield(L, -2, "redirect");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerDeleteConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerDelete",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `redirect`: @{PubSubOwnerRedirect}\n"
- );
+ return Documentation(
+ "PubSubOwnerDelete",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `redirect`: @{PubSubOwnerRedirect}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h
index 4673b92..548fb79 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerDeleteConvertor : public GenericLuaElementConvertor<PubSubOwnerDelete> {
- public:
- PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerDeleteConvertor();
+ class PubSubOwnerDeleteConvertor : public GenericLuaElementConvertor<PubSubOwnerDelete> {
+ public:
+ PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOwnerDeleteConvertor();
- virtual boost::shared_ptr<PubSubOwnerDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerDelete>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOwnerDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerDelete>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp
index cf56f6b..f7d5c50 100644
--- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubOwnerPurgeConvertor::PubSubOwnerPurgeConvertor() :
- GenericLuaElementConvertor<PubSubOwnerPurge>("pubsub_owner_purge") {
+ GenericLuaElementConvertor<PubSubOwnerPurge>("pubsub_owner_purge") {
}
PubSubOwnerPurgeConvertor::~PubSubOwnerPurgeConvertor() {
}
boost::shared_ptr<PubSubOwnerPurge> PubSubOwnerPurgeConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerPurge> result = boost::make_shared<PubSubOwnerPurge>();
- lua_getfield(L, -1, "node");
- if (lua_isstring(L, -1)) {
- result->setNode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerPurge> result = boost::make_shared<PubSubOwnerPurge>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerPurgeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerPurge> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getNode().c_str());
- lua_setfield(L, -2, "node");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerPurgeConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerPurge",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- );
+ return Documentation(
+ "PubSubOwnerPurge",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h
index 2ef7bd5..fc627c6 100644
--- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor<PubSubOwnerPurge> {
- public:
- PubSubOwnerPurgeConvertor();
- virtual ~PubSubOwnerPurgeConvertor();
+ class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor<PubSubOwnerPurge> {
+ public:
+ PubSubOwnerPurgeConvertor();
+ virtual ~PubSubOwnerPurgeConvertor();
- virtual boost::shared_ptr<PubSubOwnerPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerPurge>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubOwnerPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerPurge>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp
index a98a213..86c26ac 100644
--- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubOwnerRedirectConvertor::PubSubOwnerRedirectConvertor() :
- GenericLuaElementConvertor<PubSubOwnerRedirect>("pubsub_owner_redirect") {
+ GenericLuaElementConvertor<PubSubOwnerRedirect>("pubsub_owner_redirect") {
}
PubSubOwnerRedirectConvertor::~PubSubOwnerRedirectConvertor() {
}
boost::shared_ptr<PubSubOwnerRedirect> PubSubOwnerRedirectConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerRedirect> result = boost::make_shared<PubSubOwnerRedirect>();
- lua_getfield(L, -1, "uri");
- if (lua_isstring(L, -1)) {
- result->setURI(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerRedirect> result = boost::make_shared<PubSubOwnerRedirect>();
+ lua_getfield(L, -1, "uri");
+ if (lua_isstring(L, -1)) {
+ result->setURI(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerRedirectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerRedirect> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getURI().c_str());
- lua_setfield(L, -2, "uri");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getURI().c_str());
+ lua_setfield(L, -2, "uri");
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerRedirectConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerRedirect",
- "This table has the following fields:\n\n"
- "- `uri`: string\n"
- );
+ return Documentation(
+ "PubSubOwnerRedirect",
+ "This table has the following fields:\n\n"
+ "- `uri`: string\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h
index 8a61ef2..528e9e5 100644
--- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor<PubSubOwnerRedirect> {
- public:
- PubSubOwnerRedirectConvertor();
- virtual ~PubSubOwnerRedirectConvertor();
+ class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor<PubSubOwnerRedirect> {
+ public:
+ PubSubOwnerRedirectConvertor();
+ virtual ~PubSubOwnerRedirectConvertor();
- virtual boost::shared_ptr<PubSubOwnerRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerRedirect>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubOwnerRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerRedirect>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp
index 57d4f3d..2e5aff3 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp
@@ -13,64 +13,64 @@
using namespace Swift;
PubSubOwnerSubscriptionConvertor::PubSubOwnerSubscriptionConvertor() :
- GenericLuaElementConvertor<PubSubOwnerSubscription>("pubsub_owner_subscription") {
+ GenericLuaElementConvertor<PubSubOwnerSubscription>("pubsub_owner_subscription") {
}
PubSubOwnerSubscriptionConvertor::~PubSubOwnerSubscriptionConvertor() {
}
boost::shared_ptr<PubSubOwnerSubscription> PubSubOwnerSubscriptionConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerSubscription> result = boost::make_shared<PubSubOwnerSubscription>();
- lua_getfield(L, -1, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "subscription");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setSubscription(PubSubOwnerSubscription::None);
- }
- if (std::string(lua_tostring(L, -1)) == "pending") {
- result->setSubscription(PubSubOwnerSubscription::Pending);
- }
- if (std::string(lua_tostring(L, -1)) == "subscribed") {
- result->setSubscription(PubSubOwnerSubscription::Subscribed);
- }
- if (std::string(lua_tostring(L, -1)) == "unconfigured") {
- result->setSubscription(PubSubOwnerSubscription::Unconfigured);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubOwnerSubscription> result = boost::make_shared<PubSubOwnerSubscription>();
+ lua_getfield(L, -1, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "subscription");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setSubscription(PubSubOwnerSubscription::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "pending") {
+ result->setSubscription(PubSubOwnerSubscription::Pending);
+ }
+ if (std::string(lua_tostring(L, -1)) == "subscribed") {
+ result->setSubscription(PubSubOwnerSubscription::Subscribed);
+ }
+ if (std::string(lua_tostring(L, -1)) == "unconfigured") {
+ result->setSubscription(PubSubOwnerSubscription::Unconfigured);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubOwnerSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubOwnerSubscription> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- switch (payload->getSubscription()) {
- case PubSubOwnerSubscription::None:
- lua_pushstring(L, "none");
- break;
- case PubSubOwnerSubscription::Pending:
- lua_pushstring(L, "pending");
- break;
- case PubSubOwnerSubscription::Subscribed:
- lua_pushstring(L, "subscribed");
- break;
- case PubSubOwnerSubscription::Unconfigured:
- lua_pushstring(L, "unconfigured");
- break;
- }
- lua_setfield(L, -2, "subscription");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ switch (payload->getSubscription()) {
+ case PubSubOwnerSubscription::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubOwnerSubscription::Pending:
+ lua_pushstring(L, "pending");
+ break;
+ case PubSubOwnerSubscription::Subscribed:
+ lua_pushstring(L, "subscribed");
+ break;
+ case PubSubOwnerSubscription::Unconfigured:
+ lua_pushstring(L, "unconfigured");
+ break;
+ }
+ lua_setfield(L, -2, "subscription");
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerSubscriptionConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerSubscription",
- "This table has the following fields:\n\n"
- "- `jid`: jid (string)\n"
- "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
- );
+ return Documentation(
+ "PubSubOwnerSubscription",
+ "This table has the following fields:\n\n"
+ "- `jid`: jid (string)\n"
+ "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h
index 61c1a5e..0924c35 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscription> {
- public:
- PubSubOwnerSubscriptionConvertor();
- virtual ~PubSubOwnerSubscriptionConvertor();
+ class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscription> {
+ public:
+ PubSubOwnerSubscriptionConvertor();
+ virtual ~PubSubOwnerSubscriptionConvertor();
- virtual boost::shared_ptr<PubSubOwnerSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerSubscription>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubOwnerSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerSubscription>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
index 3298096..b6f49ad 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
@@ -17,61 +17,61 @@
using namespace Swift;
-PubSubOwnerSubscriptionsConvertor::PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerSubscriptions>("pubsub_owner_subscriptions"),
- convertors(convertors) {
+PubSubOwnerSubscriptionsConvertor::PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubOwnerSubscriptions>("pubsub_owner_subscriptions"),
+ convertors(convertors) {
}
PubSubOwnerSubscriptionsConvertor::~PubSubOwnerSubscriptionsConvertor() {
}
boost::shared_ptr<PubSubOwnerSubscriptions> PubSubOwnerSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubOwnerSubscriptions> result = boost::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< boost::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 (boost::shared_ptr<PubSubOwnerSubscription> payload = boost::dynamic_pointer_cast<PubSubOwnerSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubOwnerSubscriptions> result = boost::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< boost::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 (boost::shared_ptr<PubSubOwnerSubscription> payload = boost::dynamic_pointer_cast<PubSubOwnerSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setSubscriptions(items);
- }
- return result;
+ result->setSubscriptions(items);
+ }
+ return result;
}
void PubSubOwnerSubscriptionsConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubOwnerSubscription> item, payload->getSubscriptions()) {
- if (convertors->convertToLuaUntyped(L, item) > 0) {
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- ++i;
- }
- }
- }
- }
+ 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(boost::shared_ptr<PubSubOwnerSubscription> 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"
- );
+ return Documentation(
+ "PubSubOwnerSubscriptions",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `subscriptions`: array<@{PubSubOwnerSubscription}>\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h
index b1793e3..1511d20 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubOwnerSubscriptionsConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscriptions> {
- public:
- PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerSubscriptionsConvertor();
+ class PubSubOwnerSubscriptionsConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscriptions> {
+ public:
+ PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubOwnerSubscriptionsConvertor();
- virtual boost::shared_ptr<PubSubOwnerSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerSubscriptions>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubOwnerSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubOwnerSubscriptions>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
index 89a7d8d..68045fb 100644
--- a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
@@ -17,65 +17,65 @@
using namespace Swift;
-PubSubPublishConvertor::PubSubPublishConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubPublish>("pubsub_publish"),
- convertors(convertors) {
+PubSubPublishConvertor::PubSubPublishConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubPublish>("pubsub_publish"),
+ convertors(convertors) {
}
PubSubPublishConvertor::~PubSubPublishConvertor() {
}
boost::shared_ptr<PubSubPublish> PubSubPublishConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubPublish> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubPublish> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::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;
+ result->setItems(items);
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubPublishConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubItem> 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");
- }
+ 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(boost::shared_ptr<PubSubItem> 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"
- );
+ return Documentation(
+ "PubSubPublish",
+ "This table has the following fields:\n\n"
+ "- `node`: string\n"
+ "- `items`: array<@{PubSubItem}>\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubPublishConvertor.h b/Sluift/ElementConvertors/PubSubPublishConvertor.h
index d886368..1372c55 100644
--- a/Sluift/ElementConvertors/PubSubPublishConvertor.h
+++ b/Sluift/ElementConvertors/PubSubPublishConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubPublishConvertor : public GenericLuaElementConvertor<PubSubPublish> {
- public:
- PubSubPublishConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubPublishConvertor();
+ class PubSubPublishConvertor : public GenericLuaElementConvertor<PubSubPublish> {
+ public:
+ PubSubPublishConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubPublishConvertor();
- virtual boost::shared_ptr<PubSubPublish> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubPublish>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubPublish> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubPublish>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
index f6d186e..bc0e3d0 100644
--- a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
@@ -17,73 +17,73 @@
using namespace Swift;
-PubSubRetractConvertor::PubSubRetractConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubRetract>("pubsub_retract"),
- convertors(convertors) {
+PubSubRetractConvertor::PubSubRetractConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubRetract>("pubsub_retract"),
+ convertors(convertors) {
}
PubSubRetractConvertor::~PubSubRetractConvertor() {
}
boost::shared_ptr<PubSubRetract> PubSubRetractConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubRetract> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubRetract> result = boost::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< boost::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 (boost::shared_ptr<PubSubItem> payload = boost::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;
+ 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, boost::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(boost::shared_ptr<PubSubItem> 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");
- }
- lua_pushboolean(L, payload->isNotify());
- lua_setfield(L, -2, "notify");
+ 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(boost::shared_ptr<PubSubItem> 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");
+ }
+ lua_pushboolean(L, payload->isNotify());
+ 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"
- );
+ 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/PubSubRetractConvertor.h b/Sluift/ElementConvertors/PubSubRetractConvertor.h
index 6b27ac7..c1f8bd6 100644
--- a/Sluift/ElementConvertors/PubSubRetractConvertor.h
+++ b/Sluift/ElementConvertors/PubSubRetractConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubRetractConvertor : public GenericLuaElementConvertor<PubSubRetract> {
- public:
- PubSubRetractConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubRetractConvertor();
+ class PubSubRetractConvertor : public GenericLuaElementConvertor<PubSubRetract> {
+ public:
+ PubSubRetractConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubRetractConvertor();
- virtual boost::shared_ptr<PubSubRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubRetract>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubRetract>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp
index 436b660..bb3dcb4 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp
@@ -14,55 +14,55 @@
using namespace Swift;
-PubSubSubscribeConvertor::PubSubSubscribeConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubSubscribe>("pubsub_subscribe"),
- convertors(convertors) {
+PubSubSubscribeConvertor::PubSubSubscribeConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubSubscribe>("pubsub_subscribe"),
+ convertors(convertors) {
}
PubSubSubscribeConvertor::~PubSubSubscribeConvertor() {
}
boost::shared_ptr<PubSubSubscribe> PubSubSubscribeConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubSubscribe> result = boost::make_shared<PubSubSubscribe>();
- 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, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "options");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubOptions> payload = boost::dynamic_pointer_cast<PubSubOptions>(convertors->convertFromLuaUntyped(L, -1, "pubsub_options"))) {
- result->setOptions(payload);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubSubscribe> result = boost::make_shared<PubSubSubscribe>();
+ 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, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "options");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubOptions> payload = boost::dynamic_pointer_cast<PubSubOptions>(convertors->convertFromLuaUntyped(L, -1, "pubsub_options"))) {
+ result->setOptions(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubSubscribeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubSubscribe> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) {
- lua_setfield(L, -2, "options");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) {
+ lua_setfield(L, -2, "options");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubSubscribeConvertor::getDocumentation() const {
- return Documentation(
- "PubSubSubscribe",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `jid`: jid (string)\n"
- "- `options`: @{PubSubOptions}\n"
- );
+ return Documentation(
+ "PubSubSubscribe",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `jid`: jid (string)\n"
+ "- `options`: @{PubSubOptions}\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubSubscribeConvertor.h b/Sluift/ElementConvertors/PubSubSubscribeConvertor.h
index a7eac09..592b5aa 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubSubscribeConvertor : public GenericLuaElementConvertor<PubSubSubscribe> {
- public:
- PubSubSubscribeConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubSubscribeConvertor();
+ class PubSubSubscribeConvertor : public GenericLuaElementConvertor<PubSubSubscribe> {
+ public:
+ PubSubSubscribeConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubSubscribeConvertor();
- virtual boost::shared_ptr<PubSubSubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscribe>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubSubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscribe>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp
index 3640084..70c5b4f 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp
@@ -13,32 +13,32 @@
using namespace Swift;
PubSubSubscribeOptionsConvertor::PubSubSubscribeOptionsConvertor() :
- GenericLuaElementConvertor<PubSubSubscribeOptions>("pubsub_subscribe_options") {
+ GenericLuaElementConvertor<PubSubSubscribeOptions>("pubsub_subscribe_options") {
}
PubSubSubscribeOptionsConvertor::~PubSubSubscribeOptionsConvertor() {
}
boost::shared_ptr<PubSubSubscribeOptions> PubSubSubscribeOptionsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubSubscribeOptions> result = boost::make_shared<PubSubSubscribeOptions>();
- lua_getfield(L, -1, "required");
- if (lua_isboolean(L, -1)) {
- result->setRequired(lua_toboolean(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubSubscribeOptions> result = boost::make_shared<PubSubSubscribeOptions>();
+ lua_getfield(L, -1, "required");
+ if (lua_isboolean(L, -1)) {
+ result->setRequired(lua_toboolean(L, -1));
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubSubscribeOptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubSubscribeOptions> payload) {
- lua_createtable(L, 0, 0);
- lua_pushboolean(L, payload->isRequired());
- lua_setfield(L, -2, "required");
+ lua_createtable(L, 0, 0);
+ lua_pushboolean(L, payload->isRequired());
+ lua_setfield(L, -2, "required");
}
boost::optional<LuaElementConvertor::Documentation> PubSubSubscribeOptionsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubSubscribeOptions",
- "This table has the following fields:\n\n"
- "- `required`: boolean\n"
- );
+ return Documentation(
+ "PubSubSubscribeOptions",
+ "This table has the following fields:\n\n"
+ "- `required`: boolean\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h
index 1135300..3214dcf 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor<PubSubSubscribeOptions> {
- public:
- PubSubSubscribeOptionsConvertor();
- virtual ~PubSubSubscribeOptionsConvertor();
+ class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor<PubSubSubscribeOptions> {
+ public:
+ PubSubSubscribeOptionsConvertor();
+ virtual ~PubSubSubscribeOptionsConvertor();
- virtual boost::shared_ptr<PubSubSubscribeOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscribeOptions>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubSubscribeOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscribeOptions>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp
index 21a7fc8..79c188c 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp
@@ -14,97 +14,97 @@
using namespace Swift;
-PubSubSubscriptionConvertor::PubSubSubscriptionConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubSubscription>("pubsub_subscription"),
- convertors(convertors) {
+PubSubSubscriptionConvertor::PubSubSubscriptionConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubSubscription>("pubsub_subscription"),
+ convertors(convertors) {
}
PubSubSubscriptionConvertor::~PubSubSubscriptionConvertor() {
}
boost::shared_ptr<PubSubSubscription> PubSubSubscriptionConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubSubscription> result = boost::make_shared<PubSubSubscription>();
- 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, "subscription_id");
- if (lua_isstring(L, -1)) {
- result->setSubscriptionID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "options");
- if (!lua_isnil(L, -1)) {
- if (boost::shared_ptr<PubSubSubscribeOptions> payload = boost::dynamic_pointer_cast<PubSubSubscribeOptions>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscribe_options"))) {
- result->setOptions(payload);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "subscription");
- if (lua_isstring(L, -1)) {
- if (std::string(lua_tostring(L, -1)) == "none") {
- result->setSubscription(PubSubSubscription::None);
- }
- if (std::string(lua_tostring(L, -1)) == "pending") {
- result->setSubscription(PubSubSubscription::Pending);
- }
- if (std::string(lua_tostring(L, -1)) == "subscribed") {
- result->setSubscription(PubSubSubscription::Subscribed);
- }
- if (std::string(lua_tostring(L, -1)) == "unconfigured") {
- result->setSubscription(PubSubSubscription::Unconfigured);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<PubSubSubscription> result = boost::make_shared<PubSubSubscription>();
+ 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, "subscription_id");
+ if (lua_isstring(L, -1)) {
+ result->setSubscriptionID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "options");
+ if (!lua_isnil(L, -1)) {
+ if (boost::shared_ptr<PubSubSubscribeOptions> payload = boost::dynamic_pointer_cast<PubSubSubscribeOptions>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscribe_options"))) {
+ result->setOptions(payload);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "subscription");
+ if (lua_isstring(L, -1)) {
+ if (std::string(lua_tostring(L, -1)) == "none") {
+ result->setSubscription(PubSubSubscription::None);
+ }
+ if (std::string(lua_tostring(L, -1)) == "pending") {
+ result->setSubscription(PubSubSubscription::Pending);
+ }
+ if (std::string(lua_tostring(L, -1)) == "subscribed") {
+ result->setSubscription(PubSubSubscription::Subscribed);
+ }
+ if (std::string(lua_tostring(L, -1)) == "unconfigured") {
+ result->setSubscription(PubSubSubscription::Unconfigured);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void PubSubSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubSubscription> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- if (payload->getSubscriptionID()) {
- lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
- lua_setfield(L, -2, "subscription_id");
- }
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) {
- lua_setfield(L, -2, "options");
- }
- switch (payload->getSubscription()) {
- case PubSubSubscription::None:
- lua_pushstring(L, "none");
- break;
- case PubSubSubscription::Pending:
- lua_pushstring(L, "pending");
- break;
- case PubSubSubscription::Subscribed:
- lua_pushstring(L, "subscribed");
- break;
- case PubSubSubscription::Unconfigured:
- lua_pushstring(L, "unconfigured");
- break;
- }
- lua_setfield(L, -2, "subscription");
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (payload->getSubscriptionID()) {
+ lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
+ lua_setfield(L, -2, "subscription_id");
+ }
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) {
+ lua_setfield(L, -2, "options");
+ }
+ switch (payload->getSubscription()) {
+ case PubSubSubscription::None:
+ lua_pushstring(L, "none");
+ break;
+ case PubSubSubscription::Pending:
+ lua_pushstring(L, "pending");
+ break;
+ case PubSubSubscription::Subscribed:
+ lua_pushstring(L, "subscribed");
+ break;
+ case PubSubSubscription::Unconfigured:
+ lua_pushstring(L, "unconfigured");
+ break;
+ }
+ lua_setfield(L, -2, "subscription");
}
boost::optional<LuaElementConvertor::Documentation> PubSubSubscriptionConvertor::getDocumentation() const {
- return Documentation(
- "PubSubSubscription",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `subscription_id`: string (Optional)\n"
- "- `jid`: jid (string)\n"
- "- `options`: @{PubSubSubscribeOptions}\n"
- "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
- );
+ return Documentation(
+ "PubSubSubscription",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `subscription_id`: string (Optional)\n"
+ "- `jid`: jid (string)\n"
+ "- `options`: @{PubSubSubscribeOptions}\n"
+ "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h
index 7c1b213..84aa275 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubSubscriptionConvertor : public GenericLuaElementConvertor<PubSubSubscription> {
- public:
- PubSubSubscriptionConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubSubscriptionConvertor();
+ class PubSubSubscriptionConvertor : public GenericLuaElementConvertor<PubSubSubscription> {
+ public:
+ PubSubSubscriptionConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubSubscriptionConvertor();
- virtual boost::shared_ptr<PubSubSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscription>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscription>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
index cdaf5c7..a81817e 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
@@ -17,63 +17,63 @@
using namespace Swift;
-PubSubSubscriptionsConvertor::PubSubSubscriptionsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubSubscriptions>("pubsub_subscriptions"),
- convertors(convertors) {
+PubSubSubscriptionsConvertor::PubSubSubscriptionsConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<PubSubSubscriptions>("pubsub_subscriptions"),
+ convertors(convertors) {
}
PubSubSubscriptionsConvertor::~PubSubSubscriptionsConvertor() {
}
boost::shared_ptr<PubSubSubscriptions> PubSubSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubSubscriptions> result = boost::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< boost::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 (boost::shared_ptr<PubSubSubscription> payload = boost::dynamic_pointer_cast<PubSubSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) {
- items.push_back(payload);
- }
- }
- lua_pop(L, 1);
- }
+ boost::shared_ptr<PubSubSubscriptions> result = boost::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< boost::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 (boost::shared_ptr<PubSubSubscription> payload = boost::dynamic_pointer_cast<PubSubSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setSubscriptions(items);
- }
- return result;
+ result->setSubscriptions(items);
+ }
+ return result;
}
void PubSubSubscriptionsConvertor::doConvertToLua(lua_State* L, boost::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(boost::shared_ptr<PubSubSubscription> item, payload->getSubscriptions()) {
- if (convertors->convertToLuaUntyped(L, item) > 0) {
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- ++i;
- }
- }
- }
- }
+ 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(boost::shared_ptr<PubSubSubscription> 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"
- );
+ return Documentation(
+ "PubSubSubscriptions",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `subscriptions`: array<@{PubSubSubscription}>\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h
index de5e9f4..82fa1f7 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h
@@ -12,18 +12,18 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubSubscriptionsConvertor : public GenericLuaElementConvertor<PubSubSubscriptions> {
- public:
- PubSubSubscriptionsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubSubscriptionsConvertor();
+ class PubSubSubscriptionsConvertor : public GenericLuaElementConvertor<PubSubSubscriptions> {
+ public:
+ PubSubSubscriptionsConvertor(LuaElementConvertors* convertors);
+ virtual ~PubSubSubscriptionsConvertor();
- virtual boost::shared_ptr<PubSubSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscriptions>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<PubSubSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubSubscriptions>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp
index f25e9cf..3e83a97 100644
--- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp
@@ -13,52 +13,52 @@
using namespace Swift;
PubSubUnsubscribeConvertor::PubSubUnsubscribeConvertor() :
- GenericLuaElementConvertor<PubSubUnsubscribe>("pubsub_unsubscribe") {
+ GenericLuaElementConvertor<PubSubUnsubscribe>("pubsub_unsubscribe") {
}
PubSubUnsubscribeConvertor::~PubSubUnsubscribeConvertor() {
}
boost::shared_ptr<PubSubUnsubscribe> PubSubUnsubscribeConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<PubSubUnsubscribe> result = boost::make_shared<PubSubUnsubscribe>();
- 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, "jid");
- if (lua_isstring(L, -1)) {
- result->setJID(JID(std::string(lua_tostring(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;
+ boost::shared_ptr<PubSubUnsubscribe> result = boost::make_shared<PubSubUnsubscribe>();
+ 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, "jid");
+ if (lua_isstring(L, -1)) {
+ result->setJID(JID(std::string(lua_tostring(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 PubSubUnsubscribeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<PubSubUnsubscribe> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getNode()) {
- lua_pushstring(L, (*payload->getNode()).c_str());
- lua_setfield(L, -2, "node");
- }
- lua_pushstring(L, payload->getJID().toString().c_str());
- lua_setfield(L, -2, "jid");
- if (payload->getSubscriptionID()) {
- lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
- lua_setfield(L, -2, "subscription_id");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ lua_pushstring(L, payload->getJID().toString().c_str());
+ lua_setfield(L, -2, "jid");
+ if (payload->getSubscriptionID()) {
+ lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
+ lua_setfield(L, -2, "subscription_id");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubUnsubscribeConvertor::getDocumentation() const {
- return Documentation(
- "PubSubUnsubscribe",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `jid`: jid (string)\n"
- "- `subscription_id`: string (Optional)\n"
- );
+ return Documentation(
+ "PubSubUnsubscribe",
+ "This table has the following fields:\n\n"
+ "- `node`: string (Optional)\n"
+ "- `jid`: jid (string)\n"
+ "- `subscription_id`: string (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h
index 91c856a..c6c3d06 100644
--- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor<PubSubUnsubscribe> {
- public:
- PubSubUnsubscribeConvertor();
- virtual ~PubSubUnsubscribeConvertor();
+ class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor<PubSubUnsubscribe> {
+ public:
+ PubSubUnsubscribeConvertor();
+ virtual ~PubSubUnsubscribeConvertor();
- virtual boost::shared_ptr<PubSubUnsubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubUnsubscribe>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<PubSubUnsubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<PubSubUnsubscribe>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/RawXMLElementConvertor.cpp b/Sluift/ElementConvertors/RawXMLElementConvertor.cpp
index 1b26e74..07ca021 100644
--- a/Sluift/ElementConvertors/RawXMLElementConvertor.cpp
+++ b/Sluift/ElementConvertors/RawXMLElementConvertor.cpp
@@ -26,19 +26,19 @@ RawXMLElementConvertor::~RawXMLElementConvertor() {
}
boost::shared_ptr<Element> RawXMLElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) {
- if (type == "xml") {
- return boost::make_shared<RawXMLPayload>(std::string(Lua::checkString(L, index)));
- }
- return boost::shared_ptr<Payload>();
+ if (type == "xml") {
+ return boost::make_shared<RawXMLPayload>(std::string(Lua::checkString(L, index)));
+ }
+ return boost::shared_ptr<Payload>();
}
boost::optional<std::string> RawXMLElementConvertor::convertToLua(lua_State* L, boost::shared_ptr<Element> element) {
- boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
- if (!payload) {
- return boost::optional<std::string>();
- }
- PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
- assert(serializer);
- lua_pushstring(L, serializer->serialize(payload).c_str());
- return std::string("xml");
+ boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
+ if (!payload) {
+ return boost::optional<std::string>();
+ }
+ PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
+ assert(serializer);
+ lua_pushstring(L, serializer->serialize(payload).c_str());
+ return std::string("xml");
}
diff --git a/Sluift/ElementConvertors/RawXMLElementConvertor.h b/Sluift/ElementConvertors/RawXMLElementConvertor.h
index 0a3b463..22323ec 100644
--- a/Sluift/ElementConvertors/RawXMLElementConvertor.h
+++ b/Sluift/ElementConvertors/RawXMLElementConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/LuaElementConvertor.h>
namespace Swift {
- class RawXMLElementConvertor : public LuaElementConvertor {
- public:
- RawXMLElementConvertor();
- virtual ~RawXMLElementConvertor();
+ class RawXMLElementConvertor : public LuaElementConvertor {
+ public:
+ RawXMLElementConvertor();
+ virtual ~RawXMLElementConvertor();
- virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
- virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) SWIFTEN_OVERRIDE;
- private:
- FullPayloadSerializerCollection serializers;
- };
+ private:
+ FullPayloadSerializerCollection serializers;
+ };
}
diff --git a/Sluift/ElementConvertors/ResultSetConvertor.cpp b/Sluift/ElementConvertors/ResultSetConvertor.cpp
index 166ddd4..aa84aac 100644
--- a/Sluift/ElementConvertors/ResultSetConvertor.cpp
+++ b/Sluift/ElementConvertors/ResultSetConvertor.cpp
@@ -14,102 +14,102 @@
using namespace Swift;
ResultSetConvertor::ResultSetConvertor() :
- GenericLuaElementConvertor<ResultSet>("result_set") {
+ GenericLuaElementConvertor<ResultSet>("result_set") {
}
ResultSetConvertor::~ResultSetConvertor() {
}
boost::shared_ptr<ResultSet> ResultSetConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<ResultSet> result = boost::make_shared<ResultSet>();
- lua_getfield(L, -1, "max_items");
- if (lua_isstring(L, -1)) {
- result->setMaxItems(boost::numeric_cast<int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "count");
- if (lua_isnumber(L, -1)) {
- result->setCount(boost::numeric_cast<int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "index");
- if (lua_isnumber(L, -1)) {
- result->setIndex(boost::numeric_cast<int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "first_id_index");
- if (lua_isstring(L, -1)) {
- result->setFirstIDIndex(boost::numeric_cast<int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "first_id");
- if (lua_isstring(L, -1)) {
- result->setFirstID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "last_id");
- if (lua_isstring(L, -1)) {
- result->setLastID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "after");
- if (lua_isstring(L, -1)) {
- result->setAfter(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "before");
- if (lua_isstring(L, -1)) {
- result->setBefore(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<ResultSet> result = boost::make_shared<ResultSet>();
+ lua_getfield(L, -1, "max_items");
+ if (lua_isstring(L, -1)) {
+ result->setMaxItems(boost::numeric_cast<int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "count");
+ if (lua_isnumber(L, -1)) {
+ result->setCount(boost::numeric_cast<int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "index");
+ if (lua_isnumber(L, -1)) {
+ result->setIndex(boost::numeric_cast<int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "first_id_index");
+ if (lua_isstring(L, -1)) {
+ result->setFirstIDIndex(boost::numeric_cast<int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "first_id");
+ if (lua_isstring(L, -1)) {
+ result->setFirstID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "last_id");
+ if (lua_isstring(L, -1)) {
+ result->setLastID(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "after");
+ if (lua_isstring(L, -1)) {
+ result->setAfter(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "before");
+ if (lua_isstring(L, -1)) {
+ result->setBefore(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void ResultSetConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<ResultSet> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getMaxItems()) {
- lua_pushnumber(L, *payload->getMaxItems());
- lua_setfield(L, -2, "max_items");
- }
- if (payload->getCount()) {
- lua_pushnumber(L, *payload->getCount());
- lua_setfield(L, -2, "count");
- }
- if (payload->getIndex()) {
- lua_pushnumber(L, *payload->getIndex());
- lua_setfield(L, -2, "index");
- }
- if (payload->getFirstIDIndex()) {
- lua_pushnumber(L, *payload->getFirstIDIndex());
- lua_setfield(L, -2, "first_id_index");
- }
- if (payload->getFirstID()) {
- lua_pushstring(L, (*payload->getFirstID()).c_str());
- lua_setfield(L, -2, "first_id");
- }
- if (payload->getLastID()) {
- lua_pushstring(L, (*payload->getLastID()).c_str());
- lua_setfield(L, -2, "last_id");
- }
- if (payload->getAfter()) {
- lua_pushstring(L, (*payload->getAfter()).c_str());
- lua_setfield(L, -2, "after");
- }
- if (payload->getBefore()) {
- lua_pushstring(L, (*payload->getBefore()).c_str());
- lua_setfield(L, -2, "before");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getMaxItems()) {
+ lua_pushnumber(L, *payload->getMaxItems());
+ lua_setfield(L, -2, "max_items");
+ }
+ if (payload->getCount()) {
+ lua_pushnumber(L, *payload->getCount());
+ lua_setfield(L, -2, "count");
+ }
+ if (payload->getIndex()) {
+ lua_pushnumber(L, *payload->getIndex());
+ lua_setfield(L, -2, "index");
+ }
+ if (payload->getFirstIDIndex()) {
+ lua_pushnumber(L, *payload->getFirstIDIndex());
+ lua_setfield(L, -2, "first_id_index");
+ }
+ if (payload->getFirstID()) {
+ lua_pushstring(L, (*payload->getFirstID()).c_str());
+ lua_setfield(L, -2, "first_id");
+ }
+ if (payload->getLastID()) {
+ lua_pushstring(L, (*payload->getLastID()).c_str());
+ lua_setfield(L, -2, "last_id");
+ }
+ if (payload->getAfter()) {
+ lua_pushstring(L, (*payload->getAfter()).c_str());
+ lua_setfield(L, -2, "after");
+ }
+ if (payload->getBefore()) {
+ lua_pushstring(L, (*payload->getBefore()).c_str());
+ lua_setfield(L, -2, "before");
+ }
}
boost::optional<LuaElementConvertor::Documentation> ResultSetConvertor::getDocumentation() const {
- return Documentation(
- "ResultSet",
- "This table has the following fields:\n\n"
- "- `max_items`: number (Optional)\n"
- "- `count`: number (Optional)\n"
- "- `first_id_index`: number (Optional)\n"
- "- `first_id`: string (Optional)\n"
- "- `last_id`: string (Optional)\n"
- "- `after`: string (Optional)\n"
- );
+ return Documentation(
+ "ResultSet",
+ "This table has the following fields:\n\n"
+ "- `max_items`: number (Optional)\n"
+ "- `count`: number (Optional)\n"
+ "- `first_id_index`: number (Optional)\n"
+ "- `first_id`: string (Optional)\n"
+ "- `last_id`: string (Optional)\n"
+ "- `after`: string (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/ResultSetConvertor.h b/Sluift/ElementConvertors/ResultSetConvertor.h
index 46353f2..5df9c3e 100644
--- a/Sluift/ElementConvertors/ResultSetConvertor.h
+++ b/Sluift/ElementConvertors/ResultSetConvertor.h
@@ -12,16 +12,16 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class ResultSetConvertor : public GenericLuaElementConvertor<ResultSet> {
- public:
- ResultSetConvertor();
- virtual ~ResultSetConvertor();
+ class ResultSetConvertor : public GenericLuaElementConvertor<ResultSet> {
+ public:
+ ResultSetConvertor();
+ virtual ~ResultSetConvertor();
- virtual boost::shared_ptr<ResultSet> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<ResultSet>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<ResultSet> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<ResultSet>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
index 011cfda..a5cae40 100644
--- a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
+++ b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
@@ -16,84 +16,84 @@
using namespace Swift;
SecurityLabelConvertor::SecurityLabelConvertor() :
- GenericLuaElementConvertor<SecurityLabel>("security_label") {
+ GenericLuaElementConvertor<SecurityLabel>("security_label") {
}
SecurityLabelConvertor::~SecurityLabelConvertor() {
}
boost::shared_ptr<SecurityLabel> SecurityLabelConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<SecurityLabel> result = boost::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);
- }
+ boost::shared_ptr<SecurityLabel> result = boost::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;
+ 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, boost::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()) {
- 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");
+ 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()) {
+ 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"
- );
+ 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/SecurityLabelConvertor.h b/Sluift/ElementConvertors/SecurityLabelConvertor.h
index 001123d..eff455c 100644
--- a/Sluift/ElementConvertors/SecurityLabelConvertor.h
+++ b/Sluift/ElementConvertors/SecurityLabelConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class SecurityLabelConvertor : public GenericLuaElementConvertor<SecurityLabel> {
- public:
- SecurityLabelConvertor();
- virtual ~SecurityLabelConvertor();
+ class SecurityLabelConvertor : public GenericLuaElementConvertor<SecurityLabel> {
+ public:
+ SecurityLabelConvertor();
+ virtual ~SecurityLabelConvertor();
- virtual boost::shared_ptr<SecurityLabel> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<SecurityLabel>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<SecurityLabel> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<SecurityLabel>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp b/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp
index 9ac1679..4f372c2 100644
--- a/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp
+++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp
@@ -22,31 +22,31 @@ SoftwareVersionConvertor::~SoftwareVersionConvertor() {
}
boost::shared_ptr<SoftwareVersion> SoftwareVersionConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<SoftwareVersion> result = boost::make_shared<SoftwareVersion>();
- lua_getfield(L, -1, "name");
- if (!lua_isnil(L, -1)) {
- result->setName(std::string(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "version");
- if (!lua_isnil(L, -1)) {
- result->setVersion(std::string(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "os");
- if (!lua_isnil(L, -1)) {
- result->setOS(std::string(Lua::checkString(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<SoftwareVersion> result = boost::make_shared<SoftwareVersion>();
+ lua_getfield(L, -1, "name");
+ if (!lua_isnil(L, -1)) {
+ result->setName(std::string(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "version");
+ if (!lua_isnil(L, -1)) {
+ result->setVersion(std::string(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "os");
+ if (!lua_isnil(L, -1)) {
+ result->setOS(std::string(Lua::checkString(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void SoftwareVersionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<SoftwareVersion> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getName().c_str());
- lua_setfield(L, -2, "name");
- lua_pushstring(L, payload->getVersion().c_str());
- lua_setfield(L, -2, "version");
- lua_pushstring(L, payload->getOS().c_str());
- lua_setfield(L, -2, "os");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getName().c_str());
+ lua_setfield(L, -2, "name");
+ lua_pushstring(L, payload->getVersion().c_str());
+ lua_setfield(L, -2, "version");
+ lua_pushstring(L, payload->getOS().c_str());
+ lua_setfield(L, -2, "os");
}
diff --git a/Sluift/ElementConvertors/SoftwareVersionConvertor.h b/Sluift/ElementConvertors/SoftwareVersionConvertor.h
index 77b2ad6..4df23c0 100644
--- a/Sluift/ElementConvertors/SoftwareVersionConvertor.h
+++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class SoftwareVersionConvertor : public GenericLuaElementConvertor<SoftwareVersion> {
- public:
- SoftwareVersionConvertor();
- virtual ~SoftwareVersionConvertor();
+ class SoftwareVersionConvertor : public GenericLuaElementConvertor<SoftwareVersion> {
+ public:
+ SoftwareVersionConvertor();
+ virtual ~SoftwareVersionConvertor();
- virtual boost::shared_ptr<SoftwareVersion> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<SoftwareVersion>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<SoftwareVersion> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<SoftwareVersion>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/StanzaConvertor.h b/Sluift/ElementConvertors/StanzaConvertor.h
index 420232a..309121e 100644
--- a/Sluift/ElementConvertors/StanzaConvertor.h
+++ b/Sluift/ElementConvertors/StanzaConvertor.h
@@ -19,71 +19,71 @@
#include <Sluift/LuaElementConvertors.h>
namespace Swift {
- template <typename T> class StanzaConvertor : public GenericLuaElementConvertor<T> {
- public:
- StanzaConvertor(const std::string& tag)
- : GenericLuaElementConvertor<T>(tag) {
- }
+ template <typename T> class StanzaConvertor : public GenericLuaElementConvertor<T> {
+ public:
+ StanzaConvertor(const std::string& tag)
+ : GenericLuaElementConvertor<T>(tag) {
+ }
- virtual ~StanzaConvertor() {
- }
+ virtual ~StanzaConvertor() {
+ }
- boost::shared_ptr<T> getStanza(lua_State* L, LuaElementConvertors* convertors) {
- boost::shared_ptr<T> result = boost::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));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "to");
- if (lua_isstring(L, -1)) {
- result->setTo(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- 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)) {
- boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1));
- if (!!payload) {
- result->addPayload(payload);
- }
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- return result;
- }
+ boost::shared_ptr<T> getStanza(lua_State* L, LuaElementConvertors* convertors) {
+ boost::shared_ptr<T> result = boost::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));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "to");
+ if (lua_isstring(L, -1)) {
+ result->setTo(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ 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)) {
+ boost::shared_ptr<Payload> payload = boost::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 boost::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 boost::shared_ptr<Payload> &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");
- }
- }
- };
+ void pushStanza(lua_State* L, const boost::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 boost::shared_ptr<Payload> &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/ElementConvertors/StatusConvertor.cpp b/Sluift/ElementConvertors/StatusConvertor.cpp
index 575a4ea..241a2cc 100644
--- a/Sluift/ElementConvertors/StatusConvertor.cpp
+++ b/Sluift/ElementConvertors/StatusConvertor.cpp
@@ -22,17 +22,17 @@ StatusConvertor::~StatusConvertor() {
}
boost::shared_ptr<Status> StatusConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Status> result = boost::make_shared<Status>();
- lua_getfield(L, -1, "text");
- if (lua_isstring(L, -1)) {
- result->setText(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<Status> result = boost::make_shared<Status>();
+ lua_getfield(L, -1, "text");
+ if (lua_isstring(L, -1)) {
+ result->setText(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ return result;
}
void StatusConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Status> payload) {
- lua_createtable(L, 0, 0);
- lua_pushstring(L, payload->getText().c_str());
- lua_setfield(L, -2, "text");
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getText().c_str());
+ lua_setfield(L, -2, "text");
}
diff --git a/Sluift/ElementConvertors/StatusConvertor.h b/Sluift/ElementConvertors/StatusConvertor.h
index 33fe861..739d319 100644
--- a/Sluift/ElementConvertors/StatusConvertor.h
+++ b/Sluift/ElementConvertors/StatusConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class StatusConvertor : public GenericLuaElementConvertor<Status> {
- public:
- StatusConvertor();
- virtual ~StatusConvertor();
+ class StatusConvertor : public GenericLuaElementConvertor<Status> {
+ public:
+ StatusConvertor();
+ virtual ~StatusConvertor();
- virtual boost::shared_ptr<Status> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Status>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Status> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Status>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/StatusShowConvertor.cpp b/Sluift/ElementConvertors/StatusShowConvertor.cpp
index faae289..d1c1e85 100644
--- a/Sluift/ElementConvertors/StatusShowConvertor.cpp
+++ b/Sluift/ElementConvertors/StatusShowConvertor.cpp
@@ -23,54 +23,54 @@ StatusShowConvertor::~StatusShowConvertor() {
}
boost::shared_ptr<StatusShow> StatusShowConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<StatusShow> result = boost::make_shared<StatusShow>();
- lua_getfield(L, -1, "type");
- if (lua_isstring(L, -1)) {
- result->setType(convertStatusShowTypeFromString(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<StatusShow> result = boost::make_shared<StatusShow>();
+ lua_getfield(L, -1, "type");
+ if (lua_isstring(L, -1)) {
+ result->setType(convertStatusShowTypeFromString(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void StatusShowConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<StatusShow> payload) {
- lua_createtable(L, 0, 0);
- const std::string show = convertStatusShowTypeToString(payload->getType());
- if (!show.empty()) {
- lua_pushstring(L, show.c_str());
- lua_setfield(L, -2, "type");
- }
+ lua_createtable(L, 0, 0);
+ const std::string show = convertStatusShowTypeToString(payload->getType());
+ if (!show.empty()) {
+ lua_pushstring(L, show.c_str());
+ lua_setfield(L, -2, "type");
+ }
}
std::string StatusShowConvertor::convertStatusShowTypeToString(const StatusShow::Type &show) {
- switch (show) {
- case StatusShow::Online: return "online";
- case StatusShow::FFC: return "ffc";
- case StatusShow::Away: return "away";
- case StatusShow::XA: return "xa";
- case StatusShow::DND: return "dnd";
- case StatusShow::None: return "";
- }
- assert(false);
- return "";
+ switch (show) {
+ case StatusShow::Online: return "online";
+ case StatusShow::FFC: return "ffc";
+ case StatusShow::Away: return "away";
+ case StatusShow::XA: return "xa";
+ case StatusShow::DND: return "dnd";
+ case StatusShow::None: return "";
+ }
+ assert(false);
+ return "";
}
StatusShow::Type StatusShowConvertor::convertStatusShowTypeFromString(const std::string& show) {
- if (show == "online") {
- return StatusShow::Online;
- }
- else if (show == "ffc") {
- return StatusShow::FFC;
- }
- else if (show == "away") {
- return StatusShow::Away;
- }
- else if (show == "xa") {
- return StatusShow::XA;
- }
- else if (show == "dnd") {
- return StatusShow::DND;
- }
- else {
- throw Lua::Exception("Illegal status show: '" + show + "'");
- }
+ if (show == "online") {
+ return StatusShow::Online;
+ }
+ else if (show == "ffc") {
+ return StatusShow::FFC;
+ }
+ else if (show == "away") {
+ return StatusShow::Away;
+ }
+ else if (show == "xa") {
+ return StatusShow::XA;
+ }
+ else if (show == "dnd") {
+ return StatusShow::DND;
+ }
+ else {
+ throw Lua::Exception("Illegal status show: '" + show + "'");
+ }
}
diff --git a/Sluift/ElementConvertors/StatusShowConvertor.h b/Sluift/ElementConvertors/StatusShowConvertor.h
index d71493d..1eef447 100644
--- a/Sluift/ElementConvertors/StatusShowConvertor.h
+++ b/Sluift/ElementConvertors/StatusShowConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class StatusShowConvertor : public GenericLuaElementConvertor<StatusShow> {
- public:
- StatusShowConvertor();
- virtual ~StatusShowConvertor();
+ class StatusShowConvertor : public GenericLuaElementConvertor<StatusShow> {
+ public:
+ StatusShowConvertor();
+ virtual ~StatusShowConvertor();
- virtual boost::shared_ptr<StatusShow> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<StatusShow>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<StatusShow> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<StatusShow>) SWIFTEN_OVERRIDE;
- static std::string convertStatusShowTypeToString(const StatusShow::Type &show);
- static StatusShow::Type convertStatusShowTypeFromString(const std::string& show);
- };
+ static std::string convertStatusShowTypeToString(const StatusShow::Type &show);
+ static StatusShow::Type convertStatusShowTypeFromString(const std::string& show);
+ };
}
diff --git a/Sluift/ElementConvertors/SubjectConvertor.cpp b/Sluift/ElementConvertors/SubjectConvertor.cpp
index 8f15515..ac40744 100644
--- a/Sluift/ElementConvertors/SubjectConvertor.cpp
+++ b/Sluift/ElementConvertors/SubjectConvertor.cpp
@@ -21,17 +21,17 @@ SubjectConvertor::~SubjectConvertor() {
}
boost::shared_ptr<Subject> SubjectConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<Subject> result = boost::make_shared<Subject>();
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "text")) {
- result->setText(*value);
- }
- return result;
+ boost::shared_ptr<Subject> result = boost::make_shared<Subject>();
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "text")) {
+ result->setText(*value);
+ }
+ return result;
}
void SubjectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Subject> payload) {
- lua_createtable(L, 0, 0);
- if (!payload->getText().empty()) {
- lua_pushstring(L, payload->getText().c_str());
- lua_setfield(L, -2, "text");
- }
+ lua_createtable(L, 0, 0);
+ if (!payload->getText().empty()) {
+ lua_pushstring(L, payload->getText().c_str());
+ lua_setfield(L, -2, "text");
+ }
}
diff --git a/Sluift/ElementConvertors/SubjectConvertor.h b/Sluift/ElementConvertors/SubjectConvertor.h
index 5969293..604ad9c 100644
--- a/Sluift/ElementConvertors/SubjectConvertor.h
+++ b/Sluift/ElementConvertors/SubjectConvertor.h
@@ -12,14 +12,14 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class SubjectConvertor : public GenericLuaElementConvertor<Subject> {
- public:
- SubjectConvertor();
- virtual ~SubjectConvertor();
+ class SubjectConvertor : public GenericLuaElementConvertor<Subject> {
+ public:
+ SubjectConvertor();
+ virtual ~SubjectConvertor();
- virtual boost::shared_ptr<Subject> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<Subject>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<Subject> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<Subject>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/UserLocationConvertor.cpp b/Sluift/ElementConvertors/UserLocationConvertor.cpp
index 67c4ec0..d59382b 100644
--- a/Sluift/ElementConvertors/UserLocationConvertor.cpp
+++ b/Sluift/ElementConvertors/UserLocationConvertor.cpp
@@ -16,244 +16,244 @@
using namespace Swift;
UserLocationConvertor::UserLocationConvertor() :
- GenericLuaElementConvertor<UserLocation>("user_location") {
+ GenericLuaElementConvertor<UserLocation>("user_location") {
}
UserLocationConvertor::~UserLocationConvertor() {
}
boost::shared_ptr<UserLocation> UserLocationConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<UserLocation> result = boost::make_shared<UserLocation>();
- lua_getfield(L, -1, "area");
- if (lua_isstring(L, -1)) {
- result->setArea(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "altitude");
- if (lua_isnumber(L, -1)) {
- result->setAltitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "locality");
- if (lua_isstring(L, -1)) {
- result->setLocality(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "latitude");
- if (lua_isnumber(L, -1)) {
- result->setLatitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "accuracy");
- if (lua_isnumber(L, -1)) {
- result->setAccuracy(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "description");
- if (lua_isstring(L, -1)) {
- result->setDescription(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "country_code");
- if (lua_isstring(L, -1)) {
- result->setCountryCode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "timestamp");
- if (lua_isstring(L, -1)) {
- result->setTimestamp(stringToDateTime(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "floor");
- if (lua_isstring(L, -1)) {
- result->setFloor(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "building");
- if (lua_isstring(L, -1)) {
- result->setBuilding(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "room");
- if (lua_isstring(L, -1)) {
- result->setRoom(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "country");
- if (lua_isstring(L, -1)) {
- result->setCountry(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "region");
- if (lua_isstring(L, -1)) {
- result->setRegion(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "uri");
- if (lua_isstring(L, -1)) {
- result->setURI(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "longitude");
- if (lua_isnumber(L, -1)) {
- result->setLongitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "error");
- if (lua_isnumber(L, -1)) {
- result->setError(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "postal_code");
- if (lua_isstring(L, -1)) {
- result->setPostalCode(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "bearing");
- if (lua_isnumber(L, -1)) {
- result->setBearing(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "text");
- if (lua_isstring(L, -1)) {
- result->setText(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "datum");
- if (lua_isstring(L, -1)) {
- result->setDatum(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "street");
- if (lua_isstring(L, -1)) {
- result->setStreet(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "speed");
- if (lua_isnumber(L, -1)) {
- result->setSpeed(boost::numeric_cast<float>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<UserLocation> result = boost::make_shared<UserLocation>();
+ lua_getfield(L, -1, "area");
+ if (lua_isstring(L, -1)) {
+ result->setArea(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "altitude");
+ if (lua_isnumber(L, -1)) {
+ result->setAltitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "locality");
+ if (lua_isstring(L, -1)) {
+ result->setLocality(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "latitude");
+ if (lua_isnumber(L, -1)) {
+ result->setLatitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "accuracy");
+ if (lua_isnumber(L, -1)) {
+ result->setAccuracy(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "description");
+ if (lua_isstring(L, -1)) {
+ result->setDescription(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "country_code");
+ if (lua_isstring(L, -1)) {
+ result->setCountryCode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "timestamp");
+ if (lua_isstring(L, -1)) {
+ result->setTimestamp(stringToDateTime(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "floor");
+ if (lua_isstring(L, -1)) {
+ result->setFloor(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "building");
+ if (lua_isstring(L, -1)) {
+ result->setBuilding(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "room");
+ if (lua_isstring(L, -1)) {
+ result->setRoom(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "country");
+ if (lua_isstring(L, -1)) {
+ result->setCountry(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "region");
+ if (lua_isstring(L, -1)) {
+ result->setRegion(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "uri");
+ if (lua_isstring(L, -1)) {
+ result->setURI(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "longitude");
+ if (lua_isnumber(L, -1)) {
+ result->setLongitude(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "error");
+ if (lua_isnumber(L, -1)) {
+ result->setError(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "postal_code");
+ if (lua_isstring(L, -1)) {
+ result->setPostalCode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "bearing");
+ if (lua_isnumber(L, -1)) {
+ result->setBearing(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "text");
+ if (lua_isstring(L, -1)) {
+ result->setText(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "datum");
+ if (lua_isstring(L, -1)) {
+ result->setDatum(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "street");
+ if (lua_isstring(L, -1)) {
+ result->setStreet(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "speed");
+ if (lua_isnumber(L, -1)) {
+ result->setSpeed(boost::numeric_cast<float>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void UserLocationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<UserLocation> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getArea()) {
- lua_pushstring(L, (*payload->getArea()).c_str());
- lua_setfield(L, -2, "area");
- }
- if (payload->getAltitude()) {
- lua_pushnumber(L, (*payload->getAltitude()));
- lua_setfield(L, -2, "altitude");
- }
- if (payload->getLocality()) {
- lua_pushstring(L, (*payload->getLocality()).c_str());
- lua_setfield(L, -2, "locality");
- }
- if (payload->getLatitude()) {
- lua_pushnumber(L, (*payload->getLatitude()));
- lua_setfield(L, -2, "latitude");
- }
- if (payload->getAccuracy()) {
- lua_pushnumber(L, (*payload->getAccuracy()));
- lua_setfield(L, -2, "accuracy");
- }
- if (payload->getDescription()) {
- lua_pushstring(L, (*payload->getDescription()).c_str());
- lua_setfield(L, -2, "description");
- }
- if (payload->getCountryCode()) {
- lua_pushstring(L, (*payload->getCountryCode()).c_str());
- lua_setfield(L, -2, "country_code");
- }
- if (payload->getTimestamp()) {
- lua_pushstring(L, dateTimeToString((*payload->getTimestamp())).c_str());
- lua_setfield(L, -2, "timestamp");
- }
- if (payload->getFloor()) {
- lua_pushstring(L, (*payload->getFloor()).c_str());
- lua_setfield(L, -2, "floor");
- }
- if (payload->getBuilding()) {
- lua_pushstring(L, (*payload->getBuilding()).c_str());
- lua_setfield(L, -2, "building");
- }
- if (payload->getRoom()) {
- lua_pushstring(L, (*payload->getRoom()).c_str());
- lua_setfield(L, -2, "room");
- }
- if (payload->getCountry()) {
- lua_pushstring(L, (*payload->getCountry()).c_str());
- lua_setfield(L, -2, "country");
- }
- if (payload->getRegion()) {
- lua_pushstring(L, (*payload->getRegion()).c_str());
- lua_setfield(L, -2, "region");
- }
- if (payload->getURI()) {
- lua_pushstring(L, (*payload->getURI()).c_str());
- lua_setfield(L, -2, "uri");
- }
- if (payload->getLongitude()) {
- lua_pushnumber(L, (*payload->getLongitude()));
- lua_setfield(L, -2, "longitude");
- }
- if (payload->getError()) {
- lua_pushnumber(L, (*payload->getError()));
- lua_setfield(L, -2, "error");
- }
- if (payload->getPostalCode()) {
- lua_pushstring(L, (*payload->getPostalCode()).c_str());
- lua_setfield(L, -2, "postal_code");
- }
- if (payload->getBearing()) {
- lua_pushnumber(L, (*payload->getBearing()));
- lua_setfield(L, -2, "bearing");
- }
- if (payload->getText()) {
- lua_pushstring(L, (*payload->getText()).c_str());
- lua_setfield(L, -2, "text");
- }
- if (payload->getDatum()) {
- lua_pushstring(L, (*payload->getDatum()).c_str());
- lua_setfield(L, -2, "datum");
- }
- if (payload->getStreet()) {
- lua_pushstring(L, (*payload->getStreet()).c_str());
- lua_setfield(L, -2, "street");
- }
- if (payload->getSpeed()) {
- lua_pushnumber(L, (*payload->getSpeed()));
- lua_setfield(L, -2, "speed");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getArea()) {
+ lua_pushstring(L, (*payload->getArea()).c_str());
+ lua_setfield(L, -2, "area");
+ }
+ if (payload->getAltitude()) {
+ lua_pushnumber(L, (*payload->getAltitude()));
+ lua_setfield(L, -2, "altitude");
+ }
+ if (payload->getLocality()) {
+ lua_pushstring(L, (*payload->getLocality()).c_str());
+ lua_setfield(L, -2, "locality");
+ }
+ if (payload->getLatitude()) {
+ lua_pushnumber(L, (*payload->getLatitude()));
+ lua_setfield(L, -2, "latitude");
+ }
+ if (payload->getAccuracy()) {
+ lua_pushnumber(L, (*payload->getAccuracy()));
+ lua_setfield(L, -2, "accuracy");
+ }
+ if (payload->getDescription()) {
+ lua_pushstring(L, (*payload->getDescription()).c_str());
+ lua_setfield(L, -2, "description");
+ }
+ if (payload->getCountryCode()) {
+ lua_pushstring(L, (*payload->getCountryCode()).c_str());
+ lua_setfield(L, -2, "country_code");
+ }
+ if (payload->getTimestamp()) {
+ lua_pushstring(L, dateTimeToString((*payload->getTimestamp())).c_str());
+ lua_setfield(L, -2, "timestamp");
+ }
+ if (payload->getFloor()) {
+ lua_pushstring(L, (*payload->getFloor()).c_str());
+ lua_setfield(L, -2, "floor");
+ }
+ if (payload->getBuilding()) {
+ lua_pushstring(L, (*payload->getBuilding()).c_str());
+ lua_setfield(L, -2, "building");
+ }
+ if (payload->getRoom()) {
+ lua_pushstring(L, (*payload->getRoom()).c_str());
+ lua_setfield(L, -2, "room");
+ }
+ if (payload->getCountry()) {
+ lua_pushstring(L, (*payload->getCountry()).c_str());
+ lua_setfield(L, -2, "country");
+ }
+ if (payload->getRegion()) {
+ lua_pushstring(L, (*payload->getRegion()).c_str());
+ lua_setfield(L, -2, "region");
+ }
+ if (payload->getURI()) {
+ lua_pushstring(L, (*payload->getURI()).c_str());
+ lua_setfield(L, -2, "uri");
+ }
+ if (payload->getLongitude()) {
+ lua_pushnumber(L, (*payload->getLongitude()));
+ lua_setfield(L, -2, "longitude");
+ }
+ if (payload->getError()) {
+ lua_pushnumber(L, (*payload->getError()));
+ lua_setfield(L, -2, "error");
+ }
+ if (payload->getPostalCode()) {
+ lua_pushstring(L, (*payload->getPostalCode()).c_str());
+ lua_setfield(L, -2, "postal_code");
+ }
+ if (payload->getBearing()) {
+ lua_pushnumber(L, (*payload->getBearing()));
+ lua_setfield(L, -2, "bearing");
+ }
+ if (payload->getText()) {
+ lua_pushstring(L, (*payload->getText()).c_str());
+ lua_setfield(L, -2, "text");
+ }
+ if (payload->getDatum()) {
+ lua_pushstring(L, (*payload->getDatum()).c_str());
+ lua_setfield(L, -2, "datum");
+ }
+ if (payload->getStreet()) {
+ lua_pushstring(L, (*payload->getStreet()).c_str());
+ lua_setfield(L, -2, "street");
+ }
+ if (payload->getSpeed()) {
+ lua_pushnumber(L, (*payload->getSpeed()));
+ lua_setfield(L, -2, "speed");
+ }
}
boost::optional<LuaElementConvertor::Documentation> UserLocationConvertor::getDocumentation() const {
- return Documentation(
- "UserLocation",
- "This table has the following fields:\n\n"
- "- `area`: string (Optional)\n"
- "- `altitude`: @{float} (Optional)\n"
- "- `locality`: string (Optional)\n"
- "- `latitude`: @{float} (Optional)\n"
- "- `accuracy`: @{float} (Optional)\n"
- "- `description`: string (Optional)\n"
- "- `country_code`: string (Optional)\n"
- "- `timestamp`: datetime (string) (Optional)\n"
- "- `floor`: string (Optional)\n"
- "- `building`: string (Optional)\n"
- "- `room`: string (Optional)\n"
- "- `country`: string (Optional)\n"
- "- `region`: string (Optional)\n"
- "- `uri`: string (Optional)\n"
- "- `longitude`: @{float} (Optional)\n"
- "- `error`: @{float} (Optional)\n"
- "- `postal_code`: string (Optional)\n"
- "- `bearing`: @{float} (Optional)\n"
- "- `text`: string (Optional)\n"
- "- `datum`: string (Optional)\n"
- "- `street`: string (Optional)\n"
- "- `speed`: @{float} (Optional)\n"
- );
+ return Documentation(
+ "UserLocation",
+ "This table has the following fields:\n\n"
+ "- `area`: string (Optional)\n"
+ "- `altitude`: @{float} (Optional)\n"
+ "- `locality`: string (Optional)\n"
+ "- `latitude`: @{float} (Optional)\n"
+ "- `accuracy`: @{float} (Optional)\n"
+ "- `description`: string (Optional)\n"
+ "- `country_code`: string (Optional)\n"
+ "- `timestamp`: datetime (string) (Optional)\n"
+ "- `floor`: string (Optional)\n"
+ "- `building`: string (Optional)\n"
+ "- `room`: string (Optional)\n"
+ "- `country`: string (Optional)\n"
+ "- `region`: string (Optional)\n"
+ "- `uri`: string (Optional)\n"
+ "- `longitude`: @{float} (Optional)\n"
+ "- `error`: @{float} (Optional)\n"
+ "- `postal_code`: string (Optional)\n"
+ "- `bearing`: @{float} (Optional)\n"
+ "- `text`: string (Optional)\n"
+ "- `datum`: string (Optional)\n"
+ "- `street`: string (Optional)\n"
+ "- `speed`: @{float} (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/UserLocationConvertor.h b/Sluift/ElementConvertors/UserLocationConvertor.h
index 74c0856..d8f7e55 100644
--- a/Sluift/ElementConvertors/UserLocationConvertor.h
+++ b/Sluift/ElementConvertors/UserLocationConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class UserLocationConvertor : public GenericLuaElementConvertor<UserLocation> {
- public:
- UserLocationConvertor();
- virtual ~UserLocationConvertor();
+ class UserLocationConvertor : public GenericLuaElementConvertor<UserLocation> {
+ public:
+ UserLocationConvertor();
+ virtual ~UserLocationConvertor();
- virtual boost::shared_ptr<UserLocation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<UserLocation>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<UserLocation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<UserLocation>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/UserTuneConvertor.cpp b/Sluift/ElementConvertors/UserTuneConvertor.cpp
index d721a34..09bf9bf 100644
--- a/Sluift/ElementConvertors/UserTuneConvertor.cpp
+++ b/Sluift/ElementConvertors/UserTuneConvertor.cpp
@@ -14,94 +14,94 @@
using namespace Swift;
UserTuneConvertor::UserTuneConvertor() :
- GenericLuaElementConvertor<UserTune>("user_tune") {
+ GenericLuaElementConvertor<UserTune>("user_tune") {
}
UserTuneConvertor::~UserTuneConvertor() {
}
boost::shared_ptr<UserTune> UserTuneConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<UserTune> result = boost::make_shared<UserTune>();
- lua_getfield(L, -1, "rating");
- if (lua_isnumber(L, -1)) {
- result->setRating(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "title");
- if (lua_isstring(L, -1)) {
- result->setTitle(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "track");
- if (lua_isstring(L, -1)) {
- result->setTrack(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "artist");
- if (lua_isstring(L, -1)) {
- result->setArtist(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "uri");
- if (lua_isstring(L, -1)) {
- result->setURI(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "source");
- if (lua_isstring(L, -1)) {
- result->setSource(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "length");
- if (lua_isnumber(L, -1)) {
- result->setLength(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<UserTune> result = boost::make_shared<UserTune>();
+ lua_getfield(L, -1, "rating");
+ if (lua_isnumber(L, -1)) {
+ result->setRating(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "title");
+ if (lua_isstring(L, -1)) {
+ result->setTitle(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "track");
+ if (lua_isstring(L, -1)) {
+ result->setTrack(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "artist");
+ if (lua_isstring(L, -1)) {
+ result->setArtist(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "uri");
+ if (lua_isstring(L, -1)) {
+ result->setURI(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "source");
+ if (lua_isstring(L, -1)) {
+ result->setSource(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "length");
+ if (lua_isnumber(L, -1)) {
+ result->setLength(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
+ }
+ lua_pop(L, 1);
+ return result;
}
void UserTuneConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<UserTune> payload) {
- lua_createtable(L, 0, 0);
- if (payload->getRating()) {
- lua_pushnumber(L, (*payload->getRating()));
- lua_setfield(L, -2, "rating");
- }
- if (payload->getTitle()) {
- lua_pushstring(L, (*payload->getTitle()).c_str());
- lua_setfield(L, -2, "title");
- }
- if (payload->getTrack()) {
- lua_pushstring(L, (*payload->getTrack()).c_str());
- lua_setfield(L, -2, "track");
- }
- if (payload->getArtist()) {
- lua_pushstring(L, (*payload->getArtist()).c_str());
- lua_setfield(L, -2, "artist");
- }
- if (payload->getURI()) {
- lua_pushstring(L, (*payload->getURI()).c_str());
- lua_setfield(L, -2, "uri");
- }
- if (payload->getSource()) {
- lua_pushstring(L, (*payload->getSource()).c_str());
- lua_setfield(L, -2, "source");
- }
- if (payload->getLength()) {
- lua_pushnumber(L, (*payload->getLength()));
- lua_setfield(L, -2, "length");
- }
+ lua_createtable(L, 0, 0);
+ if (payload->getRating()) {
+ lua_pushnumber(L, (*payload->getRating()));
+ lua_setfield(L, -2, "rating");
+ }
+ if (payload->getTitle()) {
+ lua_pushstring(L, (*payload->getTitle()).c_str());
+ lua_setfield(L, -2, "title");
+ }
+ if (payload->getTrack()) {
+ lua_pushstring(L, (*payload->getTrack()).c_str());
+ lua_setfield(L, -2, "track");
+ }
+ if (payload->getArtist()) {
+ lua_pushstring(L, (*payload->getArtist()).c_str());
+ lua_setfield(L, -2, "artist");
+ }
+ if (payload->getURI()) {
+ lua_pushstring(L, (*payload->getURI()).c_str());
+ lua_setfield(L, -2, "uri");
+ }
+ if (payload->getSource()) {
+ lua_pushstring(L, (*payload->getSource()).c_str());
+ lua_setfield(L, -2, "source");
+ }
+ if (payload->getLength()) {
+ lua_pushnumber(L, (*payload->getLength()));
+ lua_setfield(L, -2, "length");
+ }
}
boost::optional<LuaElementConvertor::Documentation> UserTuneConvertor::getDocumentation() const {
- return Documentation(
- "UserTune",
- "This table has the following fields:\n\n"
- "- `rating`: number (Optional)\n"
- "- `title`: string (Optional)\n"
- "- `track`: string (Optional)\n"
- "- `artist`: string (Optional)\n"
- "- `uri`: string (Optional)\n"
- "- `source`: string (Optional)\n"
- "- `length`: number (Optional)\n"
- );
+ return Documentation(
+ "UserTune",
+ "This table has the following fields:\n\n"
+ "- `rating`: number (Optional)\n"
+ "- `title`: string (Optional)\n"
+ "- `track`: string (Optional)\n"
+ "- `artist`: string (Optional)\n"
+ "- `uri`: string (Optional)\n"
+ "- `source`: string (Optional)\n"
+ "- `length`: number (Optional)\n"
+ );
}
diff --git a/Sluift/ElementConvertors/UserTuneConvertor.h b/Sluift/ElementConvertors/UserTuneConvertor.h
index 282b9fc..9fb03ed 100644
--- a/Sluift/ElementConvertors/UserTuneConvertor.h
+++ b/Sluift/ElementConvertors/UserTuneConvertor.h
@@ -12,15 +12,15 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class LuaElementConvertors;
+ class LuaElementConvertors;
- class UserTuneConvertor : public GenericLuaElementConvertor<UserTune> {
- public:
- UserTuneConvertor();
- virtual ~UserTuneConvertor();
+ class UserTuneConvertor : public GenericLuaElementConvertor<UserTune> {
+ public:
+ UserTuneConvertor();
+ virtual ~UserTuneConvertor();
- virtual boost::shared_ptr<UserTune> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<UserTune>) SWIFTEN_OVERRIDE;
- virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<UserTune> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<UserTune>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/VCardConvertor.cpp b/Sluift/ElementConvertors/VCardConvertor.cpp
index f704083..108d233 100644
--- a/Sluift/ElementConvertors/VCardConvertor.cpp
+++ b/Sluift/ElementConvertors/VCardConvertor.cpp
@@ -25,608 +25,608 @@ VCardConvertor::~VCardConvertor() {
}
boost::shared_ptr<VCard> VCardConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<VCard> result = boost::make_shared<VCard>();
- lua_getfield(L, -1, "fullname");
- if (lua_isstring(L, -1)) {
- result->setFullName(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "familyname");
- if (lua_isstring(L, -1)) {
- result->setFamilyName(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "givenname");
- if (lua_isstring(L, -1)) {
- result->setGivenName(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "middlename");
- if (lua_isstring(L, -1)) {
- result->setMiddleName(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "prefix");
- if (lua_isstring(L, -1)) {
- result->setPrefix(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "suffix");
- if (lua_isstring(L, -1)) {
- result->setSuffix(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "nick");
- if (lua_isstring(L, -1)) {
- result->setNickname(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "description");
- if (lua_isstring(L, -1)) {
- result->setDescription(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "photo");
- if (lua_isstring(L, -1)) {
- size_t len;
- const char* data = lua_tolstring(L, -1, &len);
- result->setPhoto(createByteArray(data, len));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "phototype");
- if (lua_isstring(L, -1)) {
- result->setPhotoType(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "birthday");
- if (lua_isstring(L, -1)) {
- result->setBirthday(stringToDateTime(std::string(lua_tostring(L, -1))));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "email");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- VCard::EMailAddress emailAddress;
- emailAddress.address = Lua::getStringField(L, -1, "address").get_value_or("");
- if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
- emailAddress.isHome = *home;
- }
- if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
- emailAddress.isWork = *work;
- }
- if (boost::optional<bool> internet = Lua::getBooleanField(L, -1, "internet")) {
- emailAddress.isInternet = *internet;
- }
- if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
- emailAddress.isPreferred = *preferred;
- }
- if (boost::optional<bool> x400 = Lua::getBooleanField(L, -1, "x400")) {
- emailAddress.isX400 = *x400;
- }
- result->addEMailAddress(emailAddress);
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "telephone");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- VCard::Telephone telephone;
- telephone.number = Lua::getStringField(L, -1, "number").get_value_or("");
- if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
- telephone.isHome = *home;
- }
- if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
- telephone.isWork = *work;
- }
- if (boost::optional<bool> voice = Lua::getBooleanField(L, -1, "voice")) {
- telephone.isVoice = *voice;
- }
- if (boost::optional<bool> fax = Lua::getBooleanField(L, -1, "fax")) {
- telephone.isFax = *fax;
- }
- if (boost::optional<bool> pager = Lua::getBooleanField(L, -1, "pager")) {
- telephone.isPager = *pager;
- }
- if (boost::optional<bool> msg = Lua::getBooleanField(L, -1, "msg")) {
- telephone.isMSG = *msg;
- }
- if (boost::optional<bool> cell = Lua::getBooleanField(L, -1, "cell")) {
- telephone.isCell = *cell;
- }
- if (boost::optional<bool> video = Lua::getBooleanField(L, -1, "video")) {
- telephone.isVideo = *video;
- }
- if (boost::optional<bool> bbs = Lua::getBooleanField(L, -1, "bbs")) {
- telephone.isBBS = *bbs;
- }
- if (boost::optional<bool> modem = Lua::getBooleanField(L, -1, "modem")) {
- telephone.isModem = *modem;
- }
- if (boost::optional<bool> isdn = Lua::getBooleanField(L, -1, "isdn")) {
- telephone.isISDN = *isdn;
- }
- if (boost::optional<bool> pcs = Lua::getBooleanField(L, -1, "pcs")) {
- telephone.isPCS = *pcs;
- }
- if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
- telephone.isPreferred = *preferred;
- }
- result->addTelephone(telephone);
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "address");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- VCard::Address address;
- address.poBox = Lua::getStringField(L, -1, "pobox").get_value_or("");
- address.addressExtension = Lua::getStringField(L, -1, "extension").get_value_or("");
- address.street = Lua::getStringField(L, -1, "street").get_value_or("");
- address.locality = Lua::getStringField(L, -1, "locality").get_value_or("");
- address.region = Lua::getStringField(L, -1, "region").get_value_or("");
- address.postalCode = Lua::getStringField(L, -1, "postalcode").get_value_or("");
- address.country = Lua::getStringField(L, -1, "country").get_value_or("");
- if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
- address.isHome = *home;
- }
- if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
- address.isWork = *work;
- }
- if (boost::optional<bool> postal = Lua::getBooleanField(L, -1, "postal")) {
- address.isPostal = *postal;
- }
- if (boost::optional<bool> parcel = Lua::getBooleanField(L, -1, "parcel")) {
- address.isParcel = *parcel;
- }
- if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
- address.isPreferred = *preferred;
- }
- if (boost::optional<bool> domestic = Lua::getBooleanField(L, -1, "domestic")) {
- if (*domestic) {
- address.deliveryType = VCard::DomesticDelivery;
- }
- }
- if (boost::optional<bool> international = Lua::getBooleanField(L, -1, "international")) {
- if (*international) {
- address.deliveryType = VCard::InternationalDelivery;
- }
- }
- result->addAddress(address);
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "addresslabel");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- VCard::AddressLabel addresslabel;
- lua_getfield(L, -1, "lines");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- addresslabel.lines.push_back(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
- addresslabel.isHome = *home;
- }
- if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
- addresslabel.isWork = *work;
- }
- if (boost::optional<bool> postal = Lua::getBooleanField(L, -1, "postal")) {
- addresslabel.isPostal = *postal;
- }
- if (boost::optional<bool> parcel = Lua::getBooleanField(L, -1, "parcel")) {
- addresslabel.isParcel = *parcel;
- }
- if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
- addresslabel.isPreferred = *preferred;
- }
- if (boost::optional<bool> domestic = Lua::getBooleanField(L, -1, "domestic")) {
- if (*domestic) {
- addresslabel.deliveryType = VCard::DomesticDelivery;
- }
- }
- if (boost::optional<bool> international = Lua::getBooleanField(L, -1, "international")) {
- if (*international) {
- addresslabel.deliveryType = VCard::InternationalDelivery;
- }
- }
- result->addAddressLabel(addresslabel);
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "organization");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- VCard::Organization organization;
- organization.name = Lua::getStringField(L, -1, "name").get_value_or("");
- lua_getfield(L, -1, "units");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- organization.units.push_back(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- result->addOrganization(organization);
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "jid");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addJID(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "title");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addTitle(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "role");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addRole(lua_tostring(L, -1));
- }
- lua_pop(L, 1); }
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "url");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); ) {
- if (lua_isstring(L, -1)) {
- result->addURL(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- }
- }
- lua_pop(L, 1);
- return result;
+ boost::shared_ptr<VCard> result = boost::make_shared<VCard>();
+ lua_getfield(L, -1, "fullname");
+ if (lua_isstring(L, -1)) {
+ result->setFullName(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "familyname");
+ if (lua_isstring(L, -1)) {
+ result->setFamilyName(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "givenname");
+ if (lua_isstring(L, -1)) {
+ result->setGivenName(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "middlename");
+ if (lua_isstring(L, -1)) {
+ result->setMiddleName(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "prefix");
+ if (lua_isstring(L, -1)) {
+ result->setPrefix(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "suffix");
+ if (lua_isstring(L, -1)) {
+ result->setSuffix(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "nick");
+ if (lua_isstring(L, -1)) {
+ result->setNickname(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "description");
+ if (lua_isstring(L, -1)) {
+ result->setDescription(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "photo");
+ if (lua_isstring(L, -1)) {
+ size_t len;
+ const char* data = lua_tolstring(L, -1, &len);
+ result->setPhoto(createByteArray(data, len));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "phototype");
+ if (lua_isstring(L, -1)) {
+ result->setPhotoType(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "birthday");
+ if (lua_isstring(L, -1)) {
+ result->setBirthday(stringToDateTime(std::string(lua_tostring(L, -1))));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "email");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ VCard::EMailAddress emailAddress;
+ emailAddress.address = Lua::getStringField(L, -1, "address").get_value_or("");
+ if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
+ emailAddress.isHome = *home;
+ }
+ if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
+ emailAddress.isWork = *work;
+ }
+ if (boost::optional<bool> internet = Lua::getBooleanField(L, -1, "internet")) {
+ emailAddress.isInternet = *internet;
+ }
+ if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
+ emailAddress.isPreferred = *preferred;
+ }
+ if (boost::optional<bool> x400 = Lua::getBooleanField(L, -1, "x400")) {
+ emailAddress.isX400 = *x400;
+ }
+ result->addEMailAddress(emailAddress);
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "telephone");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ VCard::Telephone telephone;
+ telephone.number = Lua::getStringField(L, -1, "number").get_value_or("");
+ if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
+ telephone.isHome = *home;
+ }
+ if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
+ telephone.isWork = *work;
+ }
+ if (boost::optional<bool> voice = Lua::getBooleanField(L, -1, "voice")) {
+ telephone.isVoice = *voice;
+ }
+ if (boost::optional<bool> fax = Lua::getBooleanField(L, -1, "fax")) {
+ telephone.isFax = *fax;
+ }
+ if (boost::optional<bool> pager = Lua::getBooleanField(L, -1, "pager")) {
+ telephone.isPager = *pager;
+ }
+ if (boost::optional<bool> msg = Lua::getBooleanField(L, -1, "msg")) {
+ telephone.isMSG = *msg;
+ }
+ if (boost::optional<bool> cell = Lua::getBooleanField(L, -1, "cell")) {
+ telephone.isCell = *cell;
+ }
+ if (boost::optional<bool> video = Lua::getBooleanField(L, -1, "video")) {
+ telephone.isVideo = *video;
+ }
+ if (boost::optional<bool> bbs = Lua::getBooleanField(L, -1, "bbs")) {
+ telephone.isBBS = *bbs;
+ }
+ if (boost::optional<bool> modem = Lua::getBooleanField(L, -1, "modem")) {
+ telephone.isModem = *modem;
+ }
+ if (boost::optional<bool> isdn = Lua::getBooleanField(L, -1, "isdn")) {
+ telephone.isISDN = *isdn;
+ }
+ if (boost::optional<bool> pcs = Lua::getBooleanField(L, -1, "pcs")) {
+ telephone.isPCS = *pcs;
+ }
+ if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
+ telephone.isPreferred = *preferred;
+ }
+ result->addTelephone(telephone);
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "address");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ VCard::Address address;
+ address.poBox = Lua::getStringField(L, -1, "pobox").get_value_or("");
+ address.addressExtension = Lua::getStringField(L, -1, "extension").get_value_or("");
+ address.street = Lua::getStringField(L, -1, "street").get_value_or("");
+ address.locality = Lua::getStringField(L, -1, "locality").get_value_or("");
+ address.region = Lua::getStringField(L, -1, "region").get_value_or("");
+ address.postalCode = Lua::getStringField(L, -1, "postalcode").get_value_or("");
+ address.country = Lua::getStringField(L, -1, "country").get_value_or("");
+ if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
+ address.isHome = *home;
+ }
+ if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
+ address.isWork = *work;
+ }
+ if (boost::optional<bool> postal = Lua::getBooleanField(L, -1, "postal")) {
+ address.isPostal = *postal;
+ }
+ if (boost::optional<bool> parcel = Lua::getBooleanField(L, -1, "parcel")) {
+ address.isParcel = *parcel;
+ }
+ if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
+ address.isPreferred = *preferred;
+ }
+ if (boost::optional<bool> domestic = Lua::getBooleanField(L, -1, "domestic")) {
+ if (*domestic) {
+ address.deliveryType = VCard::DomesticDelivery;
+ }
+ }
+ if (boost::optional<bool> international = Lua::getBooleanField(L, -1, "international")) {
+ if (*international) {
+ address.deliveryType = VCard::InternationalDelivery;
+ }
+ }
+ result->addAddress(address);
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "addresslabel");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ VCard::AddressLabel addresslabel;
+ lua_getfield(L, -1, "lines");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ addresslabel.lines.push_back(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ if (boost::optional<bool> home = Lua::getBooleanField(L, -1, "home")) {
+ addresslabel.isHome = *home;
+ }
+ if (boost::optional<bool> work = Lua::getBooleanField(L, -1, "work")) {
+ addresslabel.isWork = *work;
+ }
+ if (boost::optional<bool> postal = Lua::getBooleanField(L, -1, "postal")) {
+ addresslabel.isPostal = *postal;
+ }
+ if (boost::optional<bool> parcel = Lua::getBooleanField(L, -1, "parcel")) {
+ addresslabel.isParcel = *parcel;
+ }
+ if (boost::optional<bool> preferred = Lua::getBooleanField(L, -1, "preferred")) {
+ addresslabel.isPreferred = *preferred;
+ }
+ if (boost::optional<bool> domestic = Lua::getBooleanField(L, -1, "domestic")) {
+ if (*domestic) {
+ addresslabel.deliveryType = VCard::DomesticDelivery;
+ }
+ }
+ if (boost::optional<bool> international = Lua::getBooleanField(L, -1, "international")) {
+ if (*international) {
+ addresslabel.deliveryType = VCard::InternationalDelivery;
+ }
+ }
+ result->addAddressLabel(addresslabel);
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "organization");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ VCard::Organization organization;
+ organization.name = Lua::getStringField(L, -1, "name").get_value_or("");
+ lua_getfield(L, -1, "units");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ organization.units.push_back(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ result->addOrganization(organization);
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "jid");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addJID(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "title");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addTitle(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "role");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addRole(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1); }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "url");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); ) {
+ if (lua_isstring(L, -1)) {
+ result->addURL(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
void VCardConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<VCard> payload) {
- lua_newtable(L);
- if (!payload->getFullName().empty()) {
- lua_pushstring(L, payload->getFullName().c_str());
- lua_setfield(L, -2, "fullname");
- }
- if (!payload->getFamilyName().empty()) {
- lua_pushstring(L, payload->getFamilyName().c_str());
- lua_setfield(L, -2, "familyname");
- }
- if (!payload->getGivenName().empty()) {
- lua_pushstring(L, payload->getGivenName().c_str());
- lua_setfield(L, -2, "givenname");
- }
- if (!payload->getMiddleName().empty()) {
- lua_pushstring(L, payload->getMiddleName().c_str());
- lua_setfield(L, -2, "middlename");
- }
- if (!payload->getPrefix().empty()) {
- lua_pushstring(L, payload->getPrefix().c_str());
- lua_setfield(L, -2, "prefix");
- }
- if (!payload->getSuffix().empty()) {
- lua_pushstring(L, payload->getSuffix().c_str());
- lua_setfield(L, -2, "suffix");
- }
- if (!payload->getNickname().empty()) {
- lua_pushstring(L, payload->getNickname().c_str());
- lua_setfield(L, -2, "nick");
- }
- if (!payload->getDescription().empty()) {
- lua_pushstring(L, payload->getDescription().c_str());
- lua_setfield(L, -2, "description");
- }
- if (!payload->getPhoto().empty()) {
- lua_pushlstring(L, reinterpret_cast<const char*>(vecptr(payload->getPhoto())), payload->getPhoto().size());
- lua_setfield(L, -2, "photo");
- }
- if (!payload->getPhotoType().empty()) {
- lua_pushstring(L, payload->getPhotoType().c_str());
- lua_setfield(L, -2, "phototype");
- }
- if (!payload->getBirthday().is_not_a_date_time()) {
- lua_pushstring(L, dateTimeToString(payload->getBirthday()).c_str());
- lua_setfield(L, -2, "birthday");
- }
- const std::vector<VCard::EMailAddress>& emails = payload->getEMailAddresses();
- if (!emails.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(emails.size()), 0);
- for (size_t i = 0; i < emails.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!emails[i].address.empty()) {
- lua_pushstring(L, emails[i].address.c_str());
- lua_setfield(L, -2, "address");
- }
- if (emails[i].isHome) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "home");
- }
- if (emails[i].isWork) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "work");
- }
- if (emails[i].isInternet) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "internet");
- }
- if (emails[i].isPreferred) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "preferred");
- }
- if (emails[i].isX400) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "x400");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "email");
- }
- const std::vector<VCard::Telephone>& telephones = payload->getTelephones();
- if (!telephones.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(telephones.size()), 0);
- for (size_t i = 0; i < telephones.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!telephones[i].number.empty()) {
- lua_pushstring(L, telephones[i].number.c_str());
- lua_setfield(L, -2, "number");
- }
- if (telephones[i].isHome) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "home");
- }
- if (telephones[i].isWork) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "work");
- }
- if (telephones[i].isVoice) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "voice");
- }
- if (telephones[i].isFax) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "fax");
- }
- if (telephones[i].isPager) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "pager");
- }
- if (telephones[i].isMSG) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "msg");
- }
- if (telephones[i].isCell) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "cell");
- }
- if (telephones[i].isVideo) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "video");
- }
- if (telephones[i].isBBS) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "bbs");
- }
- if (telephones[i].isModem) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "modem");
- }
- if (telephones[i].isISDN) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "isdn");
- }
- if (telephones[i].isPCS) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "pcs");
- }
- if (telephones[i].isPreferred) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "preferred");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "telephone");
- }
- const std::vector<VCard::Address>& addresses = payload->getAddresses();
- if (!addresses.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(addresses.size()), 0);
- for (size_t i = 0; i < addresses.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!addresses[i].poBox.empty()) {
- lua_pushstring(L, addresses[i].poBox.c_str());
- lua_setfield(L, -2, "pobox");
- }
- if (!addresses[i].addressExtension.empty()) {
- lua_pushstring(L, addresses[i].addressExtension.c_str());
- lua_setfield(L, -2, "extension");
- }
- if (!addresses[i].street.empty()) {
- lua_pushstring(L, addresses[i].street.c_str());
- lua_setfield(L, -2, "street");
- }
- if (!addresses[i].locality.empty()) {
- lua_pushstring(L, addresses[i].locality.c_str());
- lua_setfield(L, -2, "locality");
- }
- if (!addresses[i].region.empty()) {
- lua_pushstring(L, addresses[i].region.c_str());
- lua_setfield(L, -2, "region");
- }
- if (!addresses[i].postalCode.empty()) {
- lua_pushstring(L, addresses[i].postalCode.c_str());
- lua_setfield(L, -2, "postalcode");
- }
- if (!addresses[i].country.empty()) {
- lua_pushstring(L, addresses[i].country.c_str());
- lua_setfield(L, -2, "country");
- }
- if (addresses[i].isHome) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "home");
- }
- if (addresses[i].isWork) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "work");
- }
- if (addresses[i].isPostal) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "postal");
- }
- if (addresses[i].isParcel) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "parcel");
- }
- if (addresses[i].isPreferred) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "preferred");
- }
- if (addresses[i].deliveryType == VCard::DomesticDelivery) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "domestic");
- }
- if (addresses[i].deliveryType == VCard::InternationalDelivery) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "international");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "address");
- }
- const std::vector<VCard::AddressLabel>& addresslabels = payload->getAddressLabels();
- if (!addresslabels.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(addresslabels.size()), 0);
- for (size_t i = 0; i < addresslabels.size(); ++i) {
- lua_createtable(L, 0, 0);
- const std::vector<std::string>& lines = addresslabels[i].lines;
- if (!lines.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(addresslabels[i].lines.size()), 0);
- for (size_t j = 0; j < lines.size(); ++j) {
- if (!lines[j].empty()) {
- lua_pushstring(L, lines[j].c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(j+1));
- }
- lua_setfield(L, -2, "lines");
- }
- if (addresslabels[i].isHome) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "home");
- }
- if (addresslabels[i].isWork) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "work");
- }
- if (addresslabels[i].isPostal) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "postal");
- }
- if (addresslabels[i].isParcel) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "parcel");
- }
- if (addresslabels[i].isPreferred) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "preferred");
- }
- if (addresslabels[i].deliveryType == VCard::DomesticDelivery) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "domestic");
- }
- if (addresslabels[i].deliveryType == VCard::InternationalDelivery) {
- lua_pushboolean(L, true);
- lua_setfield(L, -2, "international");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "addresslabel");
- }
- const std::vector<VCard::Organization>& organizations = payload->getOrganizations();
- if (!organizations.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(organizations.size()), 0);
- for (size_t i = 0; i < organizations.size(); ++i) {
- lua_createtable(L, 0, 0);
- if (!organizations[i].name.empty()) {
- lua_pushstring(L, organizations[i].name.c_str());
- lua_setfield(L, -2, "name");
- }
- const std::vector<std::string>& units = organizations[i].units;
- if (!units.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(organizations[i].units.size()), 0);
- for (size_t j = 0; j < units.size(); ++j) {
- if (!units[j].empty()) {
- lua_pushstring(L, units[j].c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(j+1));
- }
- lua_setfield(L, -2, "units");
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "organization");
- }
- const std::vector<JID>& jids = payload->getJIDs();
- if (!jids.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(jids.size()), 0);
- for (size_t i = 0; i < jids.size(); ++i) {
- if (!jids[i].toString().empty()) {
- lua_pushstring(L, jids[i].toString().c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "jid");
- }
- const std::vector<std::string>& titles = payload->getTitles();
- if (!titles.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(titles.size()), 0);
- for (size_t i = 0; i < titles.size(); ++i) {
- if (!titles[i].empty()) {
- lua_pushstring(L, titles[i].c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "title");
- }
- const std::vector<std::string>& roles = payload->getRoles();
- if (!roles.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(roles.size()), 0);
- for (size_t i = 0; i < roles.size(); ++i) {
- if (!roles[i].empty()) {
- lua_pushstring(L, roles[i].c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "role");
- }
- const std::vector<std::string>& urls = payload->getURLs();
- if (!urls.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(urls.size()), 0);
- for (size_t i = 0; i < urls.size(); ++i) {
- if (!urls[i].empty()) {
- lua_pushstring(L, urls[i].c_str());
- }
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- lua_setfield(L, -2, "url");
- }
+ lua_newtable(L);
+ if (!payload->getFullName().empty()) {
+ lua_pushstring(L, payload->getFullName().c_str());
+ lua_setfield(L, -2, "fullname");
+ }
+ if (!payload->getFamilyName().empty()) {
+ lua_pushstring(L, payload->getFamilyName().c_str());
+ lua_setfield(L, -2, "familyname");
+ }
+ if (!payload->getGivenName().empty()) {
+ lua_pushstring(L, payload->getGivenName().c_str());
+ lua_setfield(L, -2, "givenname");
+ }
+ if (!payload->getMiddleName().empty()) {
+ lua_pushstring(L, payload->getMiddleName().c_str());
+ lua_setfield(L, -2, "middlename");
+ }
+ if (!payload->getPrefix().empty()) {
+ lua_pushstring(L, payload->getPrefix().c_str());
+ lua_setfield(L, -2, "prefix");
+ }
+ if (!payload->getSuffix().empty()) {
+ lua_pushstring(L, payload->getSuffix().c_str());
+ lua_setfield(L, -2, "suffix");
+ }
+ if (!payload->getNickname().empty()) {
+ lua_pushstring(L, payload->getNickname().c_str());
+ lua_setfield(L, -2, "nick");
+ }
+ if (!payload->getDescription().empty()) {
+ lua_pushstring(L, payload->getDescription().c_str());
+ lua_setfield(L, -2, "description");
+ }
+ if (!payload->getPhoto().empty()) {
+ lua_pushlstring(L, reinterpret_cast<const char*>(vecptr(payload->getPhoto())), payload->getPhoto().size());
+ lua_setfield(L, -2, "photo");
+ }
+ if (!payload->getPhotoType().empty()) {
+ lua_pushstring(L, payload->getPhotoType().c_str());
+ lua_setfield(L, -2, "phototype");
+ }
+ if (!payload->getBirthday().is_not_a_date_time()) {
+ lua_pushstring(L, dateTimeToString(payload->getBirthday()).c_str());
+ lua_setfield(L, -2, "birthday");
+ }
+ const std::vector<VCard::EMailAddress>& emails = payload->getEMailAddresses();
+ if (!emails.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(emails.size()), 0);
+ for (size_t i = 0; i < emails.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!emails[i].address.empty()) {
+ lua_pushstring(L, emails[i].address.c_str());
+ lua_setfield(L, -2, "address");
+ }
+ if (emails[i].isHome) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "home");
+ }
+ if (emails[i].isWork) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "work");
+ }
+ if (emails[i].isInternet) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "internet");
+ }
+ if (emails[i].isPreferred) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "preferred");
+ }
+ if (emails[i].isX400) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "x400");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "email");
+ }
+ const std::vector<VCard::Telephone>& telephones = payload->getTelephones();
+ if (!telephones.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(telephones.size()), 0);
+ for (size_t i = 0; i < telephones.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!telephones[i].number.empty()) {
+ lua_pushstring(L, telephones[i].number.c_str());
+ lua_setfield(L, -2, "number");
+ }
+ if (telephones[i].isHome) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "home");
+ }
+ if (telephones[i].isWork) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "work");
+ }
+ if (telephones[i].isVoice) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "voice");
+ }
+ if (telephones[i].isFax) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "fax");
+ }
+ if (telephones[i].isPager) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "pager");
+ }
+ if (telephones[i].isMSG) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "msg");
+ }
+ if (telephones[i].isCell) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "cell");
+ }
+ if (telephones[i].isVideo) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "video");
+ }
+ if (telephones[i].isBBS) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "bbs");
+ }
+ if (telephones[i].isModem) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "modem");
+ }
+ if (telephones[i].isISDN) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "isdn");
+ }
+ if (telephones[i].isPCS) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "pcs");
+ }
+ if (telephones[i].isPreferred) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "preferred");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "telephone");
+ }
+ const std::vector<VCard::Address>& addresses = payload->getAddresses();
+ if (!addresses.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(addresses.size()), 0);
+ for (size_t i = 0; i < addresses.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!addresses[i].poBox.empty()) {
+ lua_pushstring(L, addresses[i].poBox.c_str());
+ lua_setfield(L, -2, "pobox");
+ }
+ if (!addresses[i].addressExtension.empty()) {
+ lua_pushstring(L, addresses[i].addressExtension.c_str());
+ lua_setfield(L, -2, "extension");
+ }
+ if (!addresses[i].street.empty()) {
+ lua_pushstring(L, addresses[i].street.c_str());
+ lua_setfield(L, -2, "street");
+ }
+ if (!addresses[i].locality.empty()) {
+ lua_pushstring(L, addresses[i].locality.c_str());
+ lua_setfield(L, -2, "locality");
+ }
+ if (!addresses[i].region.empty()) {
+ lua_pushstring(L, addresses[i].region.c_str());
+ lua_setfield(L, -2, "region");
+ }
+ if (!addresses[i].postalCode.empty()) {
+ lua_pushstring(L, addresses[i].postalCode.c_str());
+ lua_setfield(L, -2, "postalcode");
+ }
+ if (!addresses[i].country.empty()) {
+ lua_pushstring(L, addresses[i].country.c_str());
+ lua_setfield(L, -2, "country");
+ }
+ if (addresses[i].isHome) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "home");
+ }
+ if (addresses[i].isWork) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "work");
+ }
+ if (addresses[i].isPostal) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "postal");
+ }
+ if (addresses[i].isParcel) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "parcel");
+ }
+ if (addresses[i].isPreferred) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "preferred");
+ }
+ if (addresses[i].deliveryType == VCard::DomesticDelivery) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "domestic");
+ }
+ if (addresses[i].deliveryType == VCard::InternationalDelivery) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "international");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "address");
+ }
+ const std::vector<VCard::AddressLabel>& addresslabels = payload->getAddressLabels();
+ if (!addresslabels.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(addresslabels.size()), 0);
+ for (size_t i = 0; i < addresslabels.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ const std::vector<std::string>& lines = addresslabels[i].lines;
+ if (!lines.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(addresslabels[i].lines.size()), 0);
+ for (size_t j = 0; j < lines.size(); ++j) {
+ if (!lines[j].empty()) {
+ lua_pushstring(L, lines[j].c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(j+1));
+ }
+ lua_setfield(L, -2, "lines");
+ }
+ if (addresslabels[i].isHome) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "home");
+ }
+ if (addresslabels[i].isWork) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "work");
+ }
+ if (addresslabels[i].isPostal) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "postal");
+ }
+ if (addresslabels[i].isParcel) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "parcel");
+ }
+ if (addresslabels[i].isPreferred) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "preferred");
+ }
+ if (addresslabels[i].deliveryType == VCard::DomesticDelivery) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "domestic");
+ }
+ if (addresslabels[i].deliveryType == VCard::InternationalDelivery) {
+ lua_pushboolean(L, true);
+ lua_setfield(L, -2, "international");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "addresslabel");
+ }
+ const std::vector<VCard::Organization>& organizations = payload->getOrganizations();
+ if (!organizations.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(organizations.size()), 0);
+ for (size_t i = 0; i < organizations.size(); ++i) {
+ lua_createtable(L, 0, 0);
+ if (!organizations[i].name.empty()) {
+ lua_pushstring(L, organizations[i].name.c_str());
+ lua_setfield(L, -2, "name");
+ }
+ const std::vector<std::string>& units = organizations[i].units;
+ if (!units.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(organizations[i].units.size()), 0);
+ for (size_t j = 0; j < units.size(); ++j) {
+ if (!units[j].empty()) {
+ lua_pushstring(L, units[j].c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(j+1));
+ }
+ lua_setfield(L, -2, "units");
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "organization");
+ }
+ const std::vector<JID>& jids = payload->getJIDs();
+ if (!jids.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(jids.size()), 0);
+ for (size_t i = 0; i < jids.size(); ++i) {
+ if (!jids[i].toString().empty()) {
+ lua_pushstring(L, jids[i].toString().c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "jid");
+ }
+ const std::vector<std::string>& titles = payload->getTitles();
+ if (!titles.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(titles.size()), 0);
+ for (size_t i = 0; i < titles.size(); ++i) {
+ if (!titles[i].empty()) {
+ lua_pushstring(L, titles[i].c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "title");
+ }
+ const std::vector<std::string>& roles = payload->getRoles();
+ if (!roles.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(roles.size()), 0);
+ for (size_t i = 0; i < roles.size(); ++i) {
+ if (!roles[i].empty()) {
+ lua_pushstring(L, roles[i].c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "role");
+ }
+ const std::vector<std::string>& urls = payload->getURLs();
+ if (!urls.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(urls.size()), 0);
+ for (size_t i = 0; i < urls.size(); ++i) {
+ if (!urls[i].empty()) {
+ lua_pushstring(L, urls[i].c_str());
+ }
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ lua_setfield(L, -2, "url");
+ }
}
diff --git a/Sluift/ElementConvertors/VCardConvertor.h b/Sluift/ElementConvertors/VCardConvertor.h
index 39e9dda..95da590 100644
--- a/Sluift/ElementConvertors/VCardConvertor.h
+++ b/Sluift/ElementConvertors/VCardConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class VCardConvertor : public GenericLuaElementConvertor<VCard> {
- public:
- VCardConvertor();
- virtual ~VCardConvertor();
+ class VCardConvertor : public GenericLuaElementConvertor<VCard> {
+ public:
+ VCardConvertor();
+ virtual ~VCardConvertor();
- virtual boost::shared_ptr<VCard> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<VCard>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<VCard> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<VCard>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
index b13443d..f3da05a 100644
--- a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
+++ b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
@@ -22,17 +22,17 @@ VCardUpdateConvertor::~VCardUpdateConvertor() {
}
boost::shared_ptr<VCardUpdate> VCardUpdateConvertor::doConvertFromLua(lua_State* L) {
- boost::shared_ptr<VCardUpdate> result = boost::make_shared<VCardUpdate>();
- if (boost::optional<std::string> value = Lua::getStringField(L, -1, "photo_hash")) {
- result->setPhotoHash(*value);
- }
- return result;
+ boost::shared_ptr<VCardUpdate> result = boost::make_shared<VCardUpdate>();
+ if (boost::optional<std::string> value = Lua::getStringField(L, -1, "photo_hash")) {
+ result->setPhotoHash(*value);
+ }
+ return result;
}
void VCardUpdateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<VCardUpdate> payload) {
- lua_newtable(L);
- if (!payload->getPhotoHash().empty()) {
- lua_pushstring(L, payload->getPhotoHash().c_str());
- lua_setfield(L, -2, "photo_hash");
- }
+ lua_newtable(L);
+ if (!payload->getPhotoHash().empty()) {
+ lua_pushstring(L, payload->getPhotoHash().c_str());
+ lua_setfield(L, -2, "photo_hash");
+ }
}
diff --git a/Sluift/ElementConvertors/VCardUpdateConvertor.h b/Sluift/ElementConvertors/VCardUpdateConvertor.h
index 48c1be8..b4a3882 100644
--- a/Sluift/ElementConvertors/VCardUpdateConvertor.h
+++ b/Sluift/ElementConvertors/VCardUpdateConvertor.h
@@ -12,12 +12,12 @@
#include <Sluift/GenericLuaElementConvertor.h>
namespace Swift {
- class VCardUpdateConvertor : public GenericLuaElementConvertor<VCardUpdate> {
- public:
- VCardUpdateConvertor();
- virtual ~VCardUpdateConvertor();
+ class VCardUpdateConvertor : public GenericLuaElementConvertor<VCardUpdate> {
+ public:
+ VCardUpdateConvertor();
+ virtual ~VCardUpdateConvertor();
- virtual boost::shared_ptr<VCardUpdate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<VCardUpdate>) SWIFTEN_OVERRIDE;
- };
+ virtual boost::shared_ptr<VCardUpdate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<VCardUpdate>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/GenericLuaElementConvertor.h b/Sluift/GenericLuaElementConvertor.h
index 8574f14..dd11c2b 100644
--- a/Sluift/GenericLuaElementConvertor.h
+++ b/Sluift/GenericLuaElementConvertor.h
@@ -17,40 +17,40 @@
#include <Sluift/LuaElementConvertor.h>
namespace Swift {
- template<typename T>
- class GenericLuaElementConvertor : public LuaElementConvertor {
- public:
- GenericLuaElementConvertor(const std::string& type) : type(type) {
- }
-
- virtual ~GenericLuaElementConvertor() {}
-
- virtual boost::shared_ptr<Element> convertFromLua(lua_State* L, int index, const std::string& payloadType) SWIFTEN_OVERRIDE {
- if (payloadType == type) {
- Lua::checkType(L, index, LUA_TTABLE);
- lua_pushvalue(L, index);
- boost::shared_ptr<Element> result = doConvertFromLua(L);
- lua_pop(L, 1);
- return result;
- }
- return boost::shared_ptr<Element>();
- }
-
- virtual boost::optional<std::string> convertToLua(
- lua_State* L, boost::shared_ptr<Element> payload) SWIFTEN_OVERRIDE {
- if (boost::shared_ptr<T> actualPayload = boost::dynamic_pointer_cast<T>(payload)) {
- doConvertToLua(L, actualPayload);
- assert(lua_type(L, -1) == LUA_TTABLE);
- return type;
- }
- return NO_RESULT;
- }
-
- protected:
- virtual boost::shared_ptr<T> doConvertFromLua(lua_State*) = 0;
- virtual void doConvertToLua(lua_State*, boost::shared_ptr<T>) = 0;
-
- private:
- std::string type;
- };
+ template<typename T>
+ class GenericLuaElementConvertor : public LuaElementConvertor {
+ public:
+ GenericLuaElementConvertor(const std::string& type) : type(type) {
+ }
+
+ virtual ~GenericLuaElementConvertor() {}
+
+ virtual boost::shared_ptr<Element> convertFromLua(lua_State* L, int index, const std::string& payloadType) SWIFTEN_OVERRIDE {
+ if (payloadType == type) {
+ Lua::checkType(L, index, LUA_TTABLE);
+ lua_pushvalue(L, index);
+ boost::shared_ptr<Element> result = doConvertFromLua(L);
+ lua_pop(L, 1);
+ return result;
+ }
+ return boost::shared_ptr<Element>();
+ }
+
+ virtual boost::optional<std::string> convertToLua(
+ lua_State* L, boost::shared_ptr<Element> payload) SWIFTEN_OVERRIDE {
+ if (boost::shared_ptr<T> actualPayload = boost::dynamic_pointer_cast<T>(payload)) {
+ doConvertToLua(L, actualPayload);
+ assert(lua_type(L, -1) == LUA_TTABLE);
+ return type;
+ }
+ return NO_RESULT;
+ }
+
+ protected:
+ virtual boost::shared_ptr<T> doConvertFromLua(lua_State*) = 0;
+ virtual void doConvertToLua(lua_State*, boost::shared_ptr<T>) = 0;
+
+ private:
+ std::string type;
+ };
}
diff --git a/Sluift/Helpers.cpp b/Sluift/Helpers.cpp
index 12d2f8f..97d14ad 100644
--- a/Sluift/Helpers.cpp
+++ b/Sluift/Helpers.cpp
@@ -12,54 +12,54 @@
using namespace Swift;
std::string Swift::getErrorString(const ClientError& error) {
- std::string reason = "Disconnected: ";
- switch(error.getType()) {
- case ClientError::UnknownError: reason += "Unknown Error"; break;
- case ClientError::ConnectionError: reason += "Error connecting to server"; break;
- case ClientError::ConnectionReadError: reason += "Error while receiving server data"; break;
- case ClientError::ConnectionWriteError: reason += "Error while sending data to the server"; break;
- case ClientError::XMLError: reason += "Error parsing server data"; break;
- case ClientError::AuthenticationFailedError: reason += "Login/password invalid"; break;
- case ClientError::UnexpectedElementError: reason += "Unexpected response"; break;
- case ClientError::DomainNameResolveError: reason += "Unable to find server"; break;
- case ClientError::CompressionFailedError: reason += "Error while compressing stream"; break;
- case ClientError::ServerVerificationFailedError: reason += "Server verification failed"; break;
- case ClientError::NoSupportedAuthMechanismsError: reason += "Authentication mechanisms not supported"; break;
- case ClientError::ResourceBindError: reason += "Error binding resource"; break;
- case ClientError::RevokedError: reason += "Certificate got revoked"; break;
- case ClientError::RevocationCheckFailedError: reason += "Failed to do revokation check"; break;
- case ClientError::SessionStartError: reason += "Error starting session"; break;
- case ClientError::StreamError: reason += "Stream error"; break;
- case ClientError::TLSError: reason += "Encryption error"; break;
- case ClientError::ClientCertificateLoadError: reason += "Error loading certificate (Invalid file or password?)"; break;
- case ClientError::ClientCertificateError: reason += "Certificate not authorized"; break;
- case ClientError::UnknownCertificateError: reason += "Unknown certificate"; break;
- case ClientError::CertificateCardRemoved: reason += "Certificate card removed"; break;
- case ClientError::CertificateExpiredError: reason += "Certificate has expired"; break;
- case ClientError::CertificateNotYetValidError: reason += "Certificate is not yet valid"; break;
- case ClientError::CertificateSelfSignedError: reason += "Certificate is self-signed"; break;
- case ClientError::CertificateRejectedError: reason += "Certificate has been rejected"; break;
- case ClientError::CertificateUntrustedError: reason += "Certificate is not trusted"; break;
- case ClientError::InvalidCertificatePurposeError: reason += "Certificate cannot be used for encrypting your connection"; break;
- case ClientError::CertificatePathLengthExceededError: reason += "Certificate path length constraint exceeded"; break;
- case ClientError::InvalidCertificateSignatureError: reason += "Invalid certificate signature"; break;
- case ClientError::InvalidCAError: reason += "Invalid Certificate Authority"; break;
- case ClientError::InvalidServerIdentityError: reason += "Certificate does not match the host identity"; break;
- }
- return reason;
+ std::string reason = "Disconnected: ";
+ switch(error.getType()) {
+ case ClientError::UnknownError: reason += "Unknown Error"; break;
+ case ClientError::ConnectionError: reason += "Error connecting to server"; break;
+ case ClientError::ConnectionReadError: reason += "Error while receiving server data"; break;
+ case ClientError::ConnectionWriteError: reason += "Error while sending data to the server"; break;
+ case ClientError::XMLError: reason += "Error parsing server data"; break;
+ case ClientError::AuthenticationFailedError: reason += "Login/password invalid"; break;
+ case ClientError::UnexpectedElementError: reason += "Unexpected response"; break;
+ case ClientError::DomainNameResolveError: reason += "Unable to find server"; break;
+ case ClientError::CompressionFailedError: reason += "Error while compressing stream"; break;
+ case ClientError::ServerVerificationFailedError: reason += "Server verification failed"; break;
+ case ClientError::NoSupportedAuthMechanismsError: reason += "Authentication mechanisms not supported"; break;
+ case ClientError::ResourceBindError: reason += "Error binding resource"; break;
+ case ClientError::RevokedError: reason += "Certificate got revoked"; break;
+ case ClientError::RevocationCheckFailedError: reason += "Failed to do revokation check"; break;
+ case ClientError::SessionStartError: reason += "Error starting session"; break;
+ case ClientError::StreamError: reason += "Stream error"; break;
+ case ClientError::TLSError: reason += "Encryption error"; break;
+ case ClientError::ClientCertificateLoadError: reason += "Error loading certificate (Invalid file or password?)"; break;
+ case ClientError::ClientCertificateError: reason += "Certificate not authorized"; break;
+ case ClientError::UnknownCertificateError: reason += "Unknown certificate"; break;
+ case ClientError::CertificateCardRemoved: reason += "Certificate card removed"; break;
+ case ClientError::CertificateExpiredError: reason += "Certificate has expired"; break;
+ case ClientError::CertificateNotYetValidError: reason += "Certificate is not yet valid"; break;
+ case ClientError::CertificateSelfSignedError: reason += "Certificate is self-signed"; break;
+ case ClientError::CertificateRejectedError: reason += "Certificate has been rejected"; break;
+ case ClientError::CertificateUntrustedError: reason += "Certificate is not trusted"; break;
+ case ClientError::InvalidCertificatePurposeError: reason += "Certificate cannot be used for encrypting your connection"; break;
+ case ClientError::CertificatePathLengthExceededError: reason += "Certificate path length constraint exceeded"; break;
+ case ClientError::InvalidCertificateSignatureError: reason += "Invalid certificate signature"; break;
+ case ClientError::InvalidCAError: reason += "Invalid Certificate Authority"; break;
+ case ClientError::InvalidServerIdentityError: reason += "Certificate does not match the host identity"; break;
+ }
+ return reason;
}
std::string Swift::getErrorString(const ComponentError& error) {
- std::string reason = "Disconnected: ";
- switch(error.getType()) {
- case ComponentError::UnknownError: reason += "Unknown Error"; break;
- case ComponentError::ConnectionError: reason += "Error connecting to server"; break;
- case ComponentError::ConnectionReadError: reason += "Error while receiving server data"; break;
- case ComponentError::ConnectionWriteError: reason += "Error while sending data to the server"; break;
- case ComponentError::XMLError: reason += "Error parsing server data"; break;
- case ComponentError::AuthenticationFailedError: reason += "Login/password invalid"; break;
- case ComponentError::UnexpectedElementError: reason += "Unexpected response"; break;
- }
- return reason;
+ std::string reason = "Disconnected: ";
+ switch(error.getType()) {
+ case ComponentError::UnknownError: reason += "Unknown Error"; break;
+ case ComponentError::ConnectionError: reason += "Error connecting to server"; break;
+ case ComponentError::ConnectionReadError: reason += "Error while receiving server data"; break;
+ case ComponentError::ConnectionWriteError: reason += "Error while sending data to the server"; break;
+ case ComponentError::XMLError: reason += "Error parsing server data"; break;
+ case ComponentError::AuthenticationFailedError: reason += "Login/password invalid"; break;
+ case ComponentError::UnexpectedElementError: reason += "Unexpected response"; break;
+ }
+ return reason;
}
diff --git a/Sluift/Helpers.h b/Sluift/Helpers.h
index ebf50f1..6af3906 100644
--- a/Sluift/Helpers.h
+++ b/Sluift/Helpers.h
@@ -12,9 +12,9 @@
#include <Swiften/Base/Override.h>
namespace Swift {
- class ClientError;
- class ComponentError;
+ class ClientError;
+ class ComponentError;
- std::string getErrorString(const ClientError& error);
- std::string getErrorString(const ComponentError& error);
+ std::string getErrorString(const ClientError& error);
+ std::string getErrorString(const ComponentError& error);
}
diff --git a/Sluift/ITunesInterface.h b/Sluift/ITunesInterface.h
index 8862966..075ab35 100644
--- a/Sluift/ITunesInterface.h
+++ b/Sluift/ITunesInterface.h
@@ -12,27 +12,27 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API ITunesInterface {
- public:
- struct Track {
- std::string name;
- std::string artist;
- std::string album;
- long trackNumber;
- double duration;
- long rating;
- };
-
- ITunesInterface();
- virtual ~ITunesInterface();
-
- boost::optional<Track> getCurrentTrack() const;
-
- private:
- bool haveApplication() const;
-
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ class SWIFTEN_API ITunesInterface {
+ public:
+ struct Track {
+ std::string name;
+ std::string artist;
+ std::string album;
+ long trackNumber;
+ double duration;
+ long rating;
+ };
+
+ ITunesInterface();
+ virtual ~ITunesInterface();
+
+ boost::optional<Track> getCurrentTrack() const;
+
+ private:
+ bool haveApplication() const;
+
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Sluift/ITunesInterface.mm b/Sluift/ITunesInterface.mm
index a11be20..a5ada5b 100644
--- a/Sluift/ITunesInterface.mm
+++ b/Sluift/ITunesInterface.mm
@@ -19,10 +19,10 @@
using namespace Swift;
struct ITunesInterface::Private {
- Private() : iTunes(nil) {
- }
+ Private() : iTunes(nil) {
+ }
- iTunesApplication* iTunes;
+ iTunesApplication* iTunes;
};
ITunesInterface::ITunesInterface() : p(boost::make_shared<Private>()) {
@@ -32,27 +32,27 @@ ITunesInterface::~ITunesInterface() {
}
boost::optional<ITunesInterface::Track> ITunesInterface::getCurrentTrack() const {
- if (!haveApplication()) {
- return boost::optional<ITunesInterface::Track>();
- }
- iTunesTrack* currentTrack = p->iTunes.currentTrack;
- if (!currentTrack) {
- return boost::optional<ITunesInterface::Track>();
- }
- ITunesInterface::Track result;
- result.name = ns2StdString(currentTrack.name);
- result.artist = ns2StdString(currentTrack.artist);
- result.album = ns2StdString(currentTrack.album);
- result.trackNumber = currentTrack.trackNumber;
- result.duration = currentTrack.duration;
- result.rating = currentTrack.rating;
- return result;
+ if (!haveApplication()) {
+ return boost::optional<ITunesInterface::Track>();
+ }
+ iTunesTrack* currentTrack = p->iTunes.currentTrack;
+ if (!currentTrack) {
+ return boost::optional<ITunesInterface::Track>();
+ }
+ ITunesInterface::Track result;
+ result.name = ns2StdString(currentTrack.name);
+ result.artist = ns2StdString(currentTrack.artist);
+ result.album = ns2StdString(currentTrack.album);
+ result.trackNumber = currentTrack.trackNumber;
+ result.duration = currentTrack.duration;
+ result.rating = currentTrack.rating;
+ return result;
}
bool ITunesInterface::haveApplication() const {
- if (!p->iTunes) {
- p->iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
- }
- return p->iTunes != nil && [p->iTunes isRunning];
+ if (!p->iTunes) {
+ p->iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
+ }
+ return p->iTunes != nil && [p->iTunes isRunning];
}
diff --git a/Sluift/Lua/Check.cpp b/Sluift/Lua/Check.cpp
index 4eebf4f..74c44be 100644
--- a/Sluift/Lua/Check.cpp
+++ b/Sluift/Lua/Check.cpp
@@ -21,49 +21,49 @@ using namespace Swift;
static std::string getArgTypeError(lua_State* L, int arg, int tag) {
- std::ostringstream s;
- s << "Arg " << arg << ": expected " << lua_typename(L, tag) << ", got " << luaL_typename(L, arg);
- return s.str();
+ std::ostringstream s;
+ s << "Arg " << arg << ": expected " << lua_typename(L, tag) << ", got " << luaL_typename(L, arg);
+ return s.str();
}
void Lua::checkType(lua_State* L, int arg, int type) {
- if (lua_type(L, arg) != type) {
- throw Lua::Exception(getArgTypeError(L, arg, type));
- }
+ if (lua_type(L, arg) != type) {
+ throw Lua::Exception(getArgTypeError(L, arg, type));
+ }
}
int Lua::checkIntNumber(lua_State* L, int arg) {
- if (!lua_isnumber(L, arg)) {
- throw Lua::Exception(getArgTypeError(L, arg, LUA_TNUMBER));
- }
- return boost::numeric_cast<int>(lua_tonumber(L, arg));
+ if (!lua_isnumber(L, arg)) {
+ throw Lua::Exception(getArgTypeError(L, arg, LUA_TNUMBER));
+ }
+ return boost::numeric_cast<int>(lua_tonumber(L, arg));
}
std::string Lua::checkString(lua_State* L, int arg) {
- const char *s = lua_tolstring(L, arg, NULL);
- if (!s) {
- throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING));
- }
- return std::string(s);
+ const char *s = lua_tolstring(L, arg, NULL);
+ if (!s) {
+ throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING));
+ }
+ return std::string(s);
}
ByteArray Lua::checkByteArray(lua_State* L, int arg) {
- size_t len;
- const char *s = lua_tolstring(L, arg, &len);
- if (!s) {
- throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING));
- }
- return createByteArray(s, len);
+ size_t len;
+ const char *s = lua_tolstring(L, arg, &len);
+ if (!s) {
+ throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING));
+ }
+ return createByteArray(s, len);
}
void* Lua::checkUserDataRaw(lua_State* L, int arg) {
- void* userData = lua_touserdata(L, arg);
- if (!userData) {
- throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA));
- }
- if (!lua_getmetatable(L, arg)) {
- throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA));
- }
- lua_pop(L, 1);
- return userData;
+ void* userData = lua_touserdata(L, arg);
+ if (!userData) {
+ throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA));
+ }
+ if (!lua_getmetatable(L, arg)) {
+ throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA));
+ }
+ lua_pop(L, 1);
+ return userData;
}
diff --git a/Sluift/Lua/Check.h b/Sluift/Lua/Check.h
index 4449cd5..61658a6 100644
--- a/Sluift/Lua/Check.h
+++ b/Sluift/Lua/Check.h
@@ -13,17 +13,17 @@
struct lua_State;
namespace Swift {
- namespace Lua {
- void checkType(lua_State* L, int arg, int type);
- int checkIntNumber(lua_State* L, int arg);
- std::string checkString(lua_State* L, int arg);
- ByteArray checkByteArray(lua_State* L, int arg);
+ namespace Lua {
+ void checkType(lua_State* L, int arg, int type);
+ int checkIntNumber(lua_State* L, int arg);
+ std::string checkString(lua_State* L, int arg);
+ ByteArray checkByteArray(lua_State* L, int arg);
- void* checkUserDataRaw(lua_State* L, int arg);
+ void* checkUserDataRaw(lua_State* L, int arg);
- template<typename T>
- T** checkUserData(lua_State* L, int arg) {
- return reinterpret_cast<T**>(checkUserDataRaw(L, arg));
- }
- }
+ template<typename T>
+ T** checkUserData(lua_State* L, int arg) {
+ return reinterpret_cast<T**>(checkUserDataRaw(L, arg));
+ }
+ }
}
diff --git a/Sluift/Lua/Debug.h b/Sluift/Lua/Debug.h
index 32addd6..5f141e1 100644
--- a/Sluift/Lua/Debug.h
+++ b/Sluift/Lua/Debug.h
@@ -11,19 +11,19 @@
#include <lua.hpp>
namespace Swift {
- namespace Lua {
- inline void dumpStack(lua_State *L) {
- for (int i = 1; i <= lua_gettop(L); i++) {
- int type = lua_type(L, i);
- std::cout << i << ": [" << lua_typename(L, type) << "] ";
- switch (type) {
- case LUA_TSTRING: std::cout << lua_tostring(L, i); break;
- case LUA_TNUMBER: std::cout << lua_tonumber(L, i); break;
- case LUA_TBOOLEAN: std::cout << lua_toboolean(L, i); break;
- default: break;
- }
- std::cout << std::endl;
- }
- }
- }
+ namespace Lua {
+ inline void dumpStack(lua_State *L) {
+ for (int i = 1; i <= lua_gettop(L); i++) {
+ int type = lua_type(L, i);
+ std::cout << i << ": [" << lua_typename(L, type) << "] ";
+ switch (type) {
+ case LUA_TSTRING: std::cout << lua_tostring(L, i); break;
+ case LUA_TNUMBER: std::cout << lua_tonumber(L, i); break;
+ case LUA_TBOOLEAN: std::cout << lua_toboolean(L, i); break;
+ default: break;
+ }
+ std::cout << std::endl;
+ }
+ }
+ }
}
diff --git a/Sluift/Lua/Exception.h b/Sluift/Lua/Exception.h
index 0d327e0..a8ecc5f 100644
--- a/Sluift/Lua/Exception.h
+++ b/Sluift/Lua/Exception.h
@@ -11,13 +11,13 @@
#include <Swiften/Base/API.h>
namespace Swift {
- namespace Lua {
- class Exception : public std::runtime_error {
- public:
- Exception(const std::string& what);
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Exception)
- virtual ~Exception() SWIFTEN_NOEXCEPT;
- };
- }
+ namespace Lua {
+ class Exception : public std::runtime_error {
+ public:
+ Exception(const std::string& what);
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Exception)
+ virtual ~Exception() SWIFTEN_NOEXCEPT;
+ };
+ }
}
diff --git a/Sluift/Lua/FunctionRegistration.cpp b/Sluift/Lua/FunctionRegistration.cpp
index 871ed1b..5a6d43e 100644
--- a/Sluift/Lua/FunctionRegistration.cpp
+++ b/Sluift/Lua/FunctionRegistration.cpp
@@ -9,7 +9,7 @@
using namespace Swift::Lua;
FunctionRegistration::FunctionRegistration(const std::string& name, lua_CFunction function, const std::string& type, const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions) {
- FunctionRegistry::getInstance().addFunction(name, function, type, helpDescription, helpParameters, helpOptions);
+ FunctionRegistry::getInstance().addFunction(name, function, type, helpDescription, helpParameters, helpOptions);
}
FunctionRegistration::~FunctionRegistration() {
diff --git a/Sluift/Lua/FunctionRegistration.h b/Sluift/Lua/FunctionRegistration.h
index 3f0afbb..8e1410d 100644
--- a/Sluift/Lua/FunctionRegistration.h
+++ b/Sluift/Lua/FunctionRegistration.h
@@ -16,31 +16,31 @@
#include <Sluift/Lua/FunctionRegistry.h>
namespace Swift {
- namespace Lua {
- class FunctionRegistration {
- public:
- FunctionRegistration(
- const std::string& name, lua_CFunction function, const std::string& type,
- const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions);
- ~FunctionRegistration();
- };
- }
+ namespace Lua {
+ class FunctionRegistration {
+ public:
+ FunctionRegistration(
+ const std::string& name, lua_CFunction function, const std::string& type,
+ const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions);
+ ~FunctionRegistration();
+ };
+ }
}
#define SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS) \
- static int TYPE##_##NAME(lua_State* L); \
- static int TYPE##_##NAME##_wrapper(lua_State* L); \
- static ::Swift::Lua::FunctionRegistration TYPE##_##NAME##_registration( #NAME , TYPE##_##NAME##_wrapper, #TYPE, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS); \
- static int TYPE##_##NAME##_wrapper(lua_State* L) { \
- try { \
- return TYPE ## _ ## NAME (L); \
- } \
- catch (const std::exception& e) { \
- return luaL_error(L, e.what()); \
- } \
- } \
- static int TYPE ## _ ## NAME (lua_State* L)
+ static int TYPE##_##NAME(lua_State* L); \
+ static int TYPE##_##NAME##_wrapper(lua_State* L); \
+ static ::Swift::Lua::FunctionRegistration TYPE##_##NAME##_registration( #NAME , TYPE##_##NAME##_wrapper, #TYPE, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS); \
+ static int TYPE##_##NAME##_wrapper(lua_State* L) { \
+ try { \
+ return TYPE ## _ ## NAME (L); \
+ } \
+ catch (const std::exception& e) { \
+ return luaL_error(L, e.what()); \
+ } \
+ } \
+ static int TYPE ## _ ## NAME (lua_State* L)
#define SLUIFT_LUA_FUNCTION(TYPE, NAME) \
- SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, "", "", "")
+ SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, "", "", "")
diff --git a/Sluift/Lua/FunctionRegistry.cpp b/Sluift/Lua/FunctionRegistry.cpp
index e1fac09..ebbd087 100644
--- a/Sluift/Lua/FunctionRegistry.cpp
+++ b/Sluift/Lua/FunctionRegistry.cpp
@@ -21,39 +21,39 @@ FunctionRegistry::~FunctionRegistry() {
}
FunctionRegistry& FunctionRegistry::getInstance() {
- static FunctionRegistry instance;
- return instance;
+ 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);
+ 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);
+ lua_newtable(L);
+ addFunctionsToTable(L, type);
}
void FunctionRegistry::addFunctionsToTable(lua_State* L, const std::string& type) {
- foreach(const Registration& 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());
- }
- }
+ foreach(const Registration& 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/FunctionRegistry.h b/Sluift/Lua/FunctionRegistry.h
index b6260e0..acab3aa 100644
--- a/Sluift/Lua/FunctionRegistry.h
+++ b/Sluift/Lua/FunctionRegistry.h
@@ -14,36 +14,36 @@
#include <Swiften/Base/Override.h>
namespace Swift {
- namespace Lua {
- class FunctionRegistry {
- public:
- ~FunctionRegistry();
- static FunctionRegistry& getInstance();
-
- void addFunction(const std::string& name, lua_CFunction function, const std::string& type,
- const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions);
-
- void createFunctionTable(lua_State* L, const std::string& type);
-
- /**
- * Adds the functions to the table on the top of the stack.
- */
- void addFunctionsToTable(lua_State* L, const std::string& type);
-
- private:
- FunctionRegistry();
-
-
- private:
- struct Registration {
- std::string name;
- lua_CFunction function;
- std::string type;
- std::string helpDescription;
- std::string helpParameters;
- std::string helpOptions;
- };
- std::vector<Registration> registrations;
- };
- }
+ namespace Lua {
+ class FunctionRegistry {
+ public:
+ ~FunctionRegistry();
+ static FunctionRegistry& getInstance();
+
+ void addFunction(const std::string& name, lua_CFunction function, const std::string& type,
+ const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions);
+
+ void createFunctionTable(lua_State* L, const std::string& type);
+
+ /**
+ * Adds the functions to the table on the top of the stack.
+ */
+ void addFunctionsToTable(lua_State* L, const std::string& type);
+
+ private:
+ FunctionRegistry();
+
+
+ private:
+ struct Registration {
+ std::string name;
+ lua_CFunction function;
+ std::string type;
+ std::string helpDescription;
+ std::string helpParameters;
+ std::string helpOptions;
+ };
+ std::vector<Registration> registrations;
+ };
+ }
}
diff --git a/Sluift/Lua/LuaUtils.cpp b/Sluift/Lua/LuaUtils.cpp
index df1afce..1088624 100644
--- a/Sluift/Lua/LuaUtils.cpp
+++ b/Sluift/Lua/LuaUtils.cpp
@@ -24,178 +24,178 @@ using namespace Swift::Lua;
static const std::string INDENT = " ";
void Swift::Lua::registerTableToString(lua_State* L, int index) {
- index = Lua::absoluteOffset(L, index);
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "register_table_tostring");
- lua_pushvalue(L, index);
- if (lua_pcall(L, 1, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
+ index = Lua::absoluteOffset(L, index);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "register_table_tostring");
+ lua_pushvalue(L, index);
+ if (lua_pcall(L, 1, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
}
void Swift::Lua::registerTableEquals(lua_State* L, int index) {
- index = Lua::absoluteOffset(L, index);
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "register_table_equals");
- lua_pushvalue(L, index);
- if (lua_pcall(L, 1, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
+ index = Lua::absoluteOffset(L, index);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "register_table_equals");
+ lua_pushvalue(L, index);
+ if (lua_pcall(L, 1, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
}
void Swift::Lua::registerGetByTypeIndex(lua_State* L, int index) {
- index = Lua::absoluteOffset(L, index);
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "register_get_by_type_index");
- lua_pushvalue(L, index);
- if (lua_pcall(L, 1, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
+ index = Lua::absoluteOffset(L, index);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "register_get_by_type_index");
+ lua_pushvalue(L, index);
+ if (lua_pcall(L, 1, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
}
boost::optional<std::string> Swift::Lua::getStringField(lua_State* L, int index, const std::string& field) {
- lua_getfield(L, index, field.c_str());
- // Seems to generate warnings with some versions of CLang that i can't turn off.
- // Leaving the more elegant code here, hoping we can re-enable it later (newer boost? c++11?).
- // The same applies to the other get*Field functions.
- //BOOST_SCOPE_EXIT(&L) { lua_pop(L,1); } BOOST_SCOPE_EXIT_END
- //return lua_isstring(L, -1) ? std::string(lua_tostring(L, -1)) : boost::optional<std::string>();
-
- boost::optional<std::string> result;
- if (lua_isstring(L, -1)) {
- result = std::string(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ lua_getfield(L, index, field.c_str());
+ // Seems to generate warnings with some versions of CLang that i can't turn off.
+ // Leaving the more elegant code here, hoping we can re-enable it later (newer boost? c++11?).
+ // The same applies to the other get*Field functions.
+ //BOOST_SCOPE_EXIT(&L) { lua_pop(L,1); } BOOST_SCOPE_EXIT_END
+ //return lua_isstring(L, -1) ? std::string(lua_tostring(L, -1)) : boost::optional<std::string>();
+
+ boost::optional<std::string> result;
+ if (lua_isstring(L, -1)) {
+ result = std::string(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ return result;
}
boost::optional<bool> Swift::Lua::getBooleanField(lua_State* L, int index, const std::string& field) {
- lua_getfield(L, index, field.c_str());
- boost::optional<bool> result;
- if (lua_isboolean(L, -1)) {
- result = lua_toboolean(L, -1);
- }
- lua_pop(L, 1);
- return result;
+ lua_getfield(L, index, field.c_str());
+ boost::optional<bool> result;
+ if (lua_isboolean(L, -1)) {
+ result = lua_toboolean(L, -1);
+ }
+ lua_pop(L, 1);
+ return result;
}
boost::optional<int> Swift::Lua::getIntField(lua_State* L, int index, const std::string& field) {
- lua_getfield(L, index, field.c_str());
- boost::optional<int> result;
- if (lua_isnumber(L, -1)) {
- result = boost::numeric_cast<int>(lua_tonumber(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ lua_getfield(L, index, field.c_str());
+ boost::optional<int> result;
+ if (lua_isnumber(L, -1)) {
+ result = boost::numeric_cast<int>(lua_tonumber(L, -1));
+ }
+ lua_pop(L, 1);
+ return result;
}
void Swift::Lua::registerHelp(lua_State* L, int index, const std::string& description, const std::string& parameters, const std::string& options) {
- index = Lua::absoluteOffset(L, index);
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "register_help");
- lua_pushvalue(L, index);
-
- lua_newtable(L);
- lua_pushstring(L, description.c_str());
- lua_rawseti(L, -2, 1);
-
- if (!parameters.empty()) {
- std::istringstream s(parameters);
- lua_newtable(L);
- int i = 1;
- for (std::string line; std::getline(s, line); ) {
- std::string trimmedLine = boost::trim_copy(line);
- if (trimmedLine.empty()) {
- continue;
- }
- size_t splitIndex = trimmedLine.find_first_of(" \t");
- std::string key;
- std::string value;
- if (splitIndex == std::string::npos) {
- key = trimmedLine;
- }
- else {
- key = trimmedLine.substr(0, splitIndex);
- value = boost::trim_copy(trimmedLine.substr(splitIndex+1));
- }
- lua_createtable(L, 2, 0);
- lua_pushstring(L, key.c_str());
- lua_rawseti(L, -2, 1);
- lua_pushstring(L, value.c_str());
- lua_rawseti(L, -2, 2);
-
- lua_rawseti(L, -2, i++);
- }
- lua_setfield(L, -2, "parameters");
- }
- if (!options.empty()) {
- std::istringstream s(options);
- lua_newtable(L);
- for (std::string line; std::getline(s, line); ) {
- std::string trimmedLine = boost::trim_copy(line);
- if (trimmedLine.empty()) {
- continue;
- }
- size_t splitIndex = trimmedLine.find_first_of(" \t");
- std::string key;
- std::string value;
- if (splitIndex == std::string::npos) {
- key = trimmedLine;
- }
- else {
- key = trimmedLine.substr(0, splitIndex);
- value = boost::trim_copy(trimmedLine.substr(splitIndex+1));
- }
- lua_pushstring(L, value.c_str());
- lua_setfield(L, -2, key.c_str());
- }
- lua_setfield(L, -2, "options");
- }
-
- if (lua_pcall(L, 2, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
+ index = Lua::absoluteOffset(L, index);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "register_help");
+ lua_pushvalue(L, index);
+
+ lua_newtable(L);
+ lua_pushstring(L, description.c_str());
+ lua_rawseti(L, -2, 1);
+
+ if (!parameters.empty()) {
+ std::istringstream s(parameters);
+ lua_newtable(L);
+ int i = 1;
+ for (std::string line; std::getline(s, line); ) {
+ std::string trimmedLine = boost::trim_copy(line);
+ if (trimmedLine.empty()) {
+ continue;
+ }
+ size_t splitIndex = trimmedLine.find_first_of(" \t");
+ std::string key;
+ std::string value;
+ if (splitIndex == std::string::npos) {
+ key = trimmedLine;
+ }
+ else {
+ key = trimmedLine.substr(0, splitIndex);
+ value = boost::trim_copy(trimmedLine.substr(splitIndex+1));
+ }
+ lua_createtable(L, 2, 0);
+ lua_pushstring(L, key.c_str());
+ lua_rawseti(L, -2, 1);
+ lua_pushstring(L, value.c_str());
+ lua_rawseti(L, -2, 2);
+
+ lua_rawseti(L, -2, i++);
+ }
+ lua_setfield(L, -2, "parameters");
+ }
+ if (!options.empty()) {
+ std::istringstream s(options);
+ lua_newtable(L);
+ for (std::string line; std::getline(s, line); ) {
+ std::string trimmedLine = boost::trim_copy(line);
+ if (trimmedLine.empty()) {
+ continue;
+ }
+ size_t splitIndex = trimmedLine.find_first_of(" \t");
+ std::string key;
+ std::string value;
+ if (splitIndex == std::string::npos) {
+ key = trimmedLine;
+ }
+ else {
+ key = trimmedLine.substr(0, splitIndex);
+ value = boost::trim_copy(trimmedLine.substr(splitIndex+1));
+ }
+ lua_pushstring(L, value.c_str());
+ lua_setfield(L, -2, key.c_str());
+ }
+ lua_setfield(L, -2, "options");
+ }
+
+ if (lua_pcall(L, 2, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
}
void Swift::Lua::registerClassHelp(lua_State* L, const std::string& name, const std::string& description) {
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "register_class_help");
- lua_pushstring(L, name.c_str());
-
- lua_newtable(L);
- lua_pushstring(L, description.c_str());
- lua_rawseti(L, -2, 1);
-
- if (lua_pcall(L, 2, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- lua_pop(L, 1);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "register_class_help");
+ lua_pushstring(L, name.c_str());
+
+ lua_newtable(L);
+ lua_pushstring(L, description.c_str());
+ lua_rawseti(L, -2, 1);
+
+ if (lua_pcall(L, 2, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
}
void Swift::Lua::registerExtraHelp(lua_State* L, int index, const std::string& name) {
- index = Lua::absoluteOffset(L, index);
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "extra_help");
- lua_getfield(L, -1, name.c_str());
- if (!lua_isnil(L, -1)) {
- lua_getfield(L, -3, "register_help");
- lua_pushvalue(L, index);
- lua_pushvalue(L, -3);
- if (lua_pcall(L, 2, 0, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- }
- lua_pop(L, 3);
+ index = Lua::absoluteOffset(L, index);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "extra_help");
+ lua_getfield(L, -1, name.c_str());
+ if (!lua_isnil(L, -1)) {
+ lua_getfield(L, -3, "register_help");
+ lua_pushvalue(L, index);
+ lua_pushvalue(L, -3);
+ if (lua_pcall(L, 2, 0, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ }
+ lua_pop(L, 3);
}
void Swift::Lua::pushStringArray(lua_State* L, const std::vector<std::string>& strings) {
- lua_createtable(L, boost::numeric_cast<int>(strings.size()), 0);
- for (size_t i = 0; i < strings.size(); ++i) {
- lua_pushstring(L, strings[i].c_str());
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
+ lua_createtable(L, boost::numeric_cast<int>(strings.size()), 0);
+ for (size_t i = 0; i < strings.size(); ++i) {
+ lua_pushstring(L, strings[i].c_str());
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
}
diff --git a/Sluift/Lua/LuaUtils.h b/Sluift/Lua/LuaUtils.h
index 19b6691..b87eb38 100644
--- a/Sluift/Lua/LuaUtils.h
+++ b/Sluift/Lua/LuaUtils.h
@@ -16,28 +16,28 @@
#endif
namespace Swift {
- namespace Lua {
- /**
- * Can be used as __tostring metamethod on a table.
- */
- int convertTableToString(lua_State* L);
-
- void registerTableToString(lua_State* L, int index);
- void registerTableEquals(lua_State* L, int index);
- void registerGetByTypeIndex(lua_State* L, int index);
- void registerHelp(lua_State* L, int index,
- const std::string& description, const std::string& parameters, const std::string& options);
- void registerClassHelp(lua_State* L, const std::string& name, const std::string& description);
- void registerExtraHelp(lua_State* L, int index, const std::string& name);
-
- inline int absoluteOffset(lua_State* L, int index) {
- return index > 0 ? index : lua_gettop(L) + index + 1;
- }
-
- boost::optional<std::string> getStringField(lua_State* L, int index, const std::string&);
- boost::optional<bool> getBooleanField(lua_State* L, int index, const std::string&);
- boost::optional<int> getIntField(lua_State* L, int index, const std::string&);
-
- void pushStringArray(lua_State* L, const std::vector<std::string>& strings);
- }
+ namespace Lua {
+ /**
+ * Can be used as __tostring metamethod on a table.
+ */
+ int convertTableToString(lua_State* L);
+
+ void registerTableToString(lua_State* L, int index);
+ void registerTableEquals(lua_State* L, int index);
+ void registerGetByTypeIndex(lua_State* L, int index);
+ void registerHelp(lua_State* L, int index,
+ const std::string& description, const std::string& parameters, const std::string& options);
+ void registerClassHelp(lua_State* L, const std::string& name, const std::string& description);
+ void registerExtraHelp(lua_State* L, int index, const std::string& name);
+
+ inline int absoluteOffset(lua_State* L, int index) {
+ return index > 0 ? index : lua_gettop(L) + index + 1;
+ }
+
+ boost::optional<std::string> getStringField(lua_State* L, int index, const std::string&);
+ boost::optional<bool> getBooleanField(lua_State* L, int index, const std::string&);
+ boost::optional<int> getIntField(lua_State* L, int index, const std::string&);
+
+ void pushStringArray(lua_State* L, const std::vector<std::string>& strings);
+ }
}
diff --git a/Sluift/Lua/Value.cpp b/Sluift/Lua/Value.cpp
index b5c459a..dd61d59 100644
--- a/Sluift/Lua/Value.cpp
+++ b/Sluift/Lua/Value.cpp
@@ -10,7 +10,7 @@
#include <boost/variant/apply_visitor.hpp>
extern "C" {
- #include <lualib.h>
+ #include <lualib.h>
}
#include <Swiften/Base/foreach.h>
@@ -19,50 +19,50 @@ 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, boost::shared_ptr<Value> >& table) const {
- lua_createtable(state, 0, boost::numeric_cast<int>(table.size()));
- for(std::map<std::string, boost::shared_ptr<Value> >::const_iterator i = table.begin(); i != table.end(); ++i) {
- boost::apply_visitor(PushVisitor(state), *i->second);
- lua_setfield(state, -2, i->first.c_str());
- }
- }
-
- lua_State* state;
- };
+ 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, boost::shared_ptr<Value> >& table) const {
+ lua_createtable(state, 0, boost::numeric_cast<int>(table.size()));
+ for(std::map<std::string, boost::shared_ptr<Value> >::const_iterator i = table.begin(); i != table.end(); ++i) {
+ 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);
+ boost::apply_visitor(PushVisitor(state), value);
}
}}
diff --git a/Sluift/Lua/Value.h b/Sluift/Lua/Value.h
index 537d764..f525fb8 100644
--- a/Sluift/Lua/Value.h
+++ b/Sluift/Lua/Value.h
@@ -17,45 +17,45 @@
struct lua_State;
namespace Swift {
- namespace Lua {
- struct Nil {};
-
- typedef boost::make_recursive_variant<
- Nil,
- bool,
- int,
- std::string,
- std::vector< boost::recursive_variant_ >,
- std::map<std::string, boost::shared_ptr<boost::recursive_variant_> >
- >::type Value;
-
- typedef std::map<std::string, boost::shared_ptr<Value> > Table;
- typedef std::vector<Value> Array;
-
- inline boost::shared_ptr<Value> nilRef() {
- return boost::make_shared<Value>(Nil());
- }
-
- inline boost::shared_ptr<Value> valueRef(const std::string& value) {
- return boost::make_shared<Value>(value);
- }
-
- inline boost::shared_ptr<Value> intRef(int value) {
- return boost::make_shared<Value>(value);
- }
-
- inline boost::shared_ptr<Value> boolRef(bool value) {
- return boost::make_shared<Value>(value);
- }
-
- inline boost::shared_ptr<Value> valueRef(const Table& table) {
- return boost::make_shared<Value>(table);
- }
-
- inline boost::shared_ptr<Value> valueRef(const Array& array) {
- return boost::make_shared<Value>(array);
- }
-
- void pushValue(lua_State* state, const Value& value);
- }
+ namespace Lua {
+ struct Nil {};
+
+ typedef boost::make_recursive_variant<
+ Nil,
+ bool,
+ int,
+ std::string,
+ std::vector< boost::recursive_variant_ >,
+ std::map<std::string, boost::shared_ptr<boost::recursive_variant_> >
+ >::type Value;
+
+ typedef std::map<std::string, boost::shared_ptr<Value> > Table;
+ typedef std::vector<Value> Array;
+
+ inline boost::shared_ptr<Value> nilRef() {
+ return boost::make_shared<Value>(Nil());
+ }
+
+ inline boost::shared_ptr<Value> valueRef(const std::string& value) {
+ return boost::make_shared<Value>(value);
+ }
+
+ inline boost::shared_ptr<Value> intRef(int value) {
+ return boost::make_shared<Value>(value);
+ }
+
+ inline boost::shared_ptr<Value> boolRef(bool value) {
+ return boost::make_shared<Value>(value);
+ }
+
+ inline boost::shared_ptr<Value> valueRef(const Table& table) {
+ return boost::make_shared<Value>(table);
+ }
+
+ inline boost::shared_ptr<Value> valueRef(const Array& array) {
+ return boost::make_shared<Value>(array);
+ }
+
+ void pushValue(lua_State* state, const Value& value);
+ }
}
diff --git a/Sluift/LuaElementConvertor.h b/Sluift/LuaElementConvertor.h
index 9587628..6c237fd 100644
--- a/Sluift/LuaElementConvertor.h
+++ b/Sluift/LuaElementConvertor.h
@@ -16,26 +16,26 @@
struct lua_State;
namespace Swift {
- class Element;
+ class Element;
- class LuaElementConvertor {
- public:
- static boost::optional<std::string> NO_RESULT;
+ class LuaElementConvertor {
+ public:
+ static boost::optional<std::string> NO_RESULT;
- struct Documentation {
- Documentation(const std::string& className, const std::string& description) :
- className(className), description(description) {}
- std::string className;
- std::string description;
- };
+ struct Documentation {
+ Documentation(const std::string& className, const std::string& description) :
+ className(className), description(description) {}
+ std::string className;
+ std::string description;
+ };
- virtual ~LuaElementConvertor();
+ virtual ~LuaElementConvertor();
- virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) = 0;
- virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) = 0;
+ virtual boost::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) = 0;
+ virtual boost::optional<std::string> convertToLua(lua_State*, boost::shared_ptr<Element>) = 0;
- virtual boost::optional<Documentation> getDocumentation() const {
- return boost::optional<Documentation>();
- }
- };
+ virtual boost::optional<Documentation> getDocumentation() const {
+ return boost::optional<Documentation>();
+ }
+ };
}
diff --git a/Sluift/LuaElementConvertors.cpp b/Sluift/LuaElementConvertors.cpp
index 963a618..67c0545 100644
--- a/Sluift/LuaElementConvertors.cpp
+++ b/Sluift/LuaElementConvertors.cpp
@@ -41,31 +41,31 @@
using namespace Swift;
LuaElementConvertors::LuaElementConvertors() {
- registerConvertors();
- convertors.push_back(boost::make_shared<StatusConvertor>());
- convertors.push_back(boost::make_shared<StatusShowConvertor>());
- convertors.push_back(boost::make_shared<DelayConvertor>());
- convertors.push_back(boost::make_shared<CommandConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventConvertor>(this));
- convertors.push_back(boost::make_shared<BodyConvertor>());
- convertors.push_back(boost::make_shared<SubjectConvertor>());
- convertors.push_back(boost::make_shared<VCardConvertor>());
- convertors.push_back(boost::make_shared<VCardUpdateConvertor>());
- convertors.push_back(boost::make_shared<FormConvertor>());
- convertors.push_back(boost::make_shared<SoftwareVersionConvertor>());
- convertors.push_back(boost::make_shared<DiscoInfoConvertor>());
- convertors.push_back(boost::make_shared<DiscoItemsConvertor>());
- convertors.push_back(boost::make_shared<IQConvertor>(this));
- convertors.push_back(boost::make_shared<PresenceConvertor>(this));
- convertors.push_back(boost::make_shared<MessageConvertor>(this));
- convertors.push_back(boost::make_shared<ResultSetConvertor>());
- convertors.push_back(boost::make_shared<ForwardedConvertor>(this));
- convertors.push_back(boost::make_shared<MAMResultConvertor>(this));
- convertors.push_back(boost::make_shared<MAMQueryConvertor>(this));
- convertors.push_back(boost::make_shared<MAMFinConvertor>(this));
- convertors.push_back(boost::make_shared<DOMElementConvertor>());
- convertors.push_back(boost::make_shared<RawXMLElementConvertor>());
- convertors.push_back(boost::make_shared<DefaultElementConvertor>());
+ registerConvertors();
+ convertors.push_back(boost::make_shared<StatusConvertor>());
+ convertors.push_back(boost::make_shared<StatusShowConvertor>());
+ convertors.push_back(boost::make_shared<DelayConvertor>());
+ convertors.push_back(boost::make_shared<CommandConvertor>(this));
+ convertors.push_back(boost::make_shared<PubSubEventConvertor>(this));
+ convertors.push_back(boost::make_shared<BodyConvertor>());
+ convertors.push_back(boost::make_shared<SubjectConvertor>());
+ convertors.push_back(boost::make_shared<VCardConvertor>());
+ convertors.push_back(boost::make_shared<VCardUpdateConvertor>());
+ convertors.push_back(boost::make_shared<FormConvertor>());
+ convertors.push_back(boost::make_shared<SoftwareVersionConvertor>());
+ convertors.push_back(boost::make_shared<DiscoInfoConvertor>());
+ convertors.push_back(boost::make_shared<DiscoItemsConvertor>());
+ convertors.push_back(boost::make_shared<IQConvertor>(this));
+ convertors.push_back(boost::make_shared<PresenceConvertor>(this));
+ convertors.push_back(boost::make_shared<MessageConvertor>(this));
+ convertors.push_back(boost::make_shared<ResultSetConvertor>());
+ convertors.push_back(boost::make_shared<ForwardedConvertor>(this));
+ convertors.push_back(boost::make_shared<MAMResultConvertor>(this));
+ convertors.push_back(boost::make_shared<MAMQueryConvertor>(this));
+ convertors.push_back(boost::make_shared<MAMFinConvertor>(this));
+ convertors.push_back(boost::make_shared<DOMElementConvertor>());
+ convertors.push_back(boost::make_shared<RawXMLElementConvertor>());
+ convertors.push_back(boost::make_shared<DefaultElementConvertor>());
}
LuaElementConvertors::~LuaElementConvertors() {
@@ -74,64 +74,64 @@ LuaElementConvertors::~LuaElementConvertors() {
#include <Sluift/ElementConvertors/ElementConvertors.ipp>
boost::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");
+ 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");
}
boost::shared_ptr<Element> LuaElementConvertors::convertFromLuaUntyped(lua_State* L, int index, const std::string& type) {
- index = Lua::absoluteOffset(L, index);
- foreach (boost::shared_ptr<LuaElementConvertor> convertor, convertors) {
- if (boost::shared_ptr<Element> result = convertor->convertFromLua(L, index, type)) {
- return result;
- }
- }
- return boost::shared_ptr<Element>();
+ index = Lua::absoluteOffset(L, index);
+ foreach (boost::shared_ptr<LuaElementConvertor> convertor, convertors) {
+ if (boost::shared_ptr<Element> result = convertor->convertFromLua(L, index, type)) {
+ return result;
+ }
+ }
+ return boost::shared_ptr<Element>();
}
int LuaElementConvertors::convertToLua(lua_State* L, boost::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;
+ 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, boost::shared_ptr<Element> payload) {
- if (doConvertToLuaUntyped(L, payload)) {
- return 1;
- }
- return 0;
+ if (doConvertToLuaUntyped(L, payload)) {
+ return 1;
+ }
+ return 0;
}
boost::optional<std::string> LuaElementConvertors::doConvertToLuaUntyped(
- lua_State* L, boost::shared_ptr<Element> payload) {
- if (!payload) {
- return LuaElementConvertor::NO_RESULT;
- }
- foreach (boost::shared_ptr<LuaElementConvertor> convertor, convertors) {
- if (boost::optional<std::string> type = convertor->convertToLua(L, payload)) {
- return *type;
- }
- }
- return LuaElementConvertor::NO_RESULT;
+ lua_State* L, boost::shared_ptr<Element> payload) {
+ if (!payload) {
+ return LuaElementConvertor::NO_RESULT;
+ }
+ foreach (boost::shared_ptr<LuaElementConvertor> convertor, convertors) {
+ if (boost::optional<std::string> type = convertor->convertToLua(L, payload)) {
+ return *type;
+ }
+ }
+ return LuaElementConvertor::NO_RESULT;
}
diff --git a/Sluift/LuaElementConvertors.h b/Sluift/LuaElementConvertors.h
index 1e9dc97..6b3d343 100644
--- a/Sluift/LuaElementConvertors.h
+++ b/Sluift/LuaElementConvertors.h
@@ -16,37 +16,37 @@
struct lua_State;
namespace Swift {
- class LuaElementConvertor;
- class Element;
-
- class LuaElementConvertors {
- public:
- LuaElementConvertors();
- virtual ~LuaElementConvertors();
-
- boost::shared_ptr<Element> convertFromLua(lua_State*, int index);
- int convertToLua(lua_State*, boost::shared_ptr<Element>);
-
- /**
- * Adds a toplevel type+data table with the given type.
- */
- boost::shared_ptr<Element> convertFromLuaUntyped(lua_State*, int index, const std::string& type);
-
- /**
- * Strips the toplevel type+data table, and only return the
- * data.
- */
- int convertToLuaUntyped(lua_State*, boost::shared_ptr<Element>);
-
- const std::vector< boost::shared_ptr<LuaElementConvertor> >& getConvertors() const {
- return convertors;
- }
-
- private:
- boost::optional<std::string> doConvertToLuaUntyped(lua_State*, boost::shared_ptr<Element>);
- void registerConvertors();
-
- private:
- std::vector< boost::shared_ptr<LuaElementConvertor> > convertors;
- };
+ class LuaElementConvertor;
+ class Element;
+
+ class LuaElementConvertors {
+ public:
+ LuaElementConvertors();
+ virtual ~LuaElementConvertors();
+
+ boost::shared_ptr<Element> convertFromLua(lua_State*, int index);
+ int convertToLua(lua_State*, boost::shared_ptr<Element>);
+
+ /**
+ * Adds a toplevel type+data table with the given type.
+ */
+ boost::shared_ptr<Element> convertFromLuaUntyped(lua_State*, int index, const std::string& type);
+
+ /**
+ * Strips the toplevel type+data table, and only return the
+ * data.
+ */
+ int convertToLuaUntyped(lua_State*, boost::shared_ptr<Element>);
+
+ const std::vector< boost::shared_ptr<LuaElementConvertor> >& getConvertors() const {
+ return convertors;
+ }
+
+ private:
+ boost::optional<std::string> doConvertToLuaUntyped(lua_State*, boost::shared_ptr<Element>);
+ void registerConvertors();
+
+ private:
+ std::vector< boost::shared_ptr<LuaElementConvertor> > convertors;
+ };
}
diff --git a/Sluift/Response.cpp b/Sluift/Response.cpp
index ff643f2..97a44d0 100644
--- a/Sluift/Response.cpp
+++ b/Sluift/Response.cpp
@@ -17,65 +17,65 @@ using namespace Swift;
using namespace Swift::Sluift;
static std::string getErrorString(boost::shared_ptr<ErrorPayload> error) {
- // Copied from ChatControllerBase.
- // TODO: Share this code;
- std::string defaultMessage = "Error sending message";
- if (!error->getText().empty()) {
- return error->getText();
- }
- else {
- switch (error->getCondition()) {
- case ErrorPayload::BadRequest: return "Bad request";
- case ErrorPayload::Conflict: return "Conflict";
- case ErrorPayload::FeatureNotImplemented: return "This feature is not implemented";
- case ErrorPayload::Forbidden: return "Forbidden";
- case ErrorPayload::Gone: return "Recipient can no longer be contacted";
- case ErrorPayload::InternalServerError: return "Internal server error";
- case ErrorPayload::ItemNotFound: return "Item not found";
- case ErrorPayload::JIDMalformed: return "JID Malformed";
- case ErrorPayload::NotAcceptable: return "Message was rejected";
- case ErrorPayload::NotAllowed: return "Not allowed";
- case ErrorPayload::NotAuthorized: return "Not authorized";
- case ErrorPayload::PaymentRequired: return "Payment is required";
- case ErrorPayload::RecipientUnavailable: return "Recipient is unavailable";
- case ErrorPayload::Redirect: return "Redirect";
- case ErrorPayload::RegistrationRequired: return "Registration required";
- case ErrorPayload::RemoteServerNotFound: return "Recipient's server not found";
- case ErrorPayload::RemoteServerTimeout: return "Remote server timeout";
- case ErrorPayload::ResourceConstraint: return "The server is low on resources";
- case ErrorPayload::ServiceUnavailable: return "The service is unavailable";
- case ErrorPayload::SubscriptionRequired: return "A subscription is required";
- case ErrorPayload::UndefinedCondition: return "Undefined condition";
- case ErrorPayload::UnexpectedRequest: return "Unexpected request";
- }
- }
- assert(false);
- return defaultMessage;
+ // Copied from ChatControllerBase.
+ // TODO: Share this code;
+ std::string defaultMessage = "Error sending message";
+ if (!error->getText().empty()) {
+ return error->getText();
+ }
+ else {
+ switch (error->getCondition()) {
+ case ErrorPayload::BadRequest: return "Bad request";
+ case ErrorPayload::Conflict: return "Conflict";
+ case ErrorPayload::FeatureNotImplemented: return "This feature is not implemented";
+ case ErrorPayload::Forbidden: return "Forbidden";
+ case ErrorPayload::Gone: return "Recipient can no longer be contacted";
+ case ErrorPayload::InternalServerError: return "Internal server error";
+ case ErrorPayload::ItemNotFound: return "Item not found";
+ case ErrorPayload::JIDMalformed: return "JID Malformed";
+ case ErrorPayload::NotAcceptable: return "Message was rejected";
+ case ErrorPayload::NotAllowed: return "Not allowed";
+ case ErrorPayload::NotAuthorized: return "Not authorized";
+ case ErrorPayload::PaymentRequired: return "Payment is required";
+ case ErrorPayload::RecipientUnavailable: return "Recipient is unavailable";
+ case ErrorPayload::Redirect: return "Redirect";
+ case ErrorPayload::RegistrationRequired: return "Registration required";
+ case ErrorPayload::RemoteServerNotFound: return "Recipient's server not found";
+ case ErrorPayload::RemoteServerTimeout: return "Remote server timeout";
+ case ErrorPayload::ResourceConstraint: return "The server is low on resources";
+ case ErrorPayload::ServiceUnavailable: return "The service is unavailable";
+ case ErrorPayload::SubscriptionRequired: return "A subscription is required";
+ case ErrorPayload::UndefinedCondition: return "Undefined condition";
+ case ErrorPayload::UnexpectedRequest: return "Unexpected request";
+ }
+ }
+ assert(false);
+ return defaultMessage;
}
Response::~Response() {
}
int Response::convertToLuaResult(lua_State* L) {
- if (error) {
- lua_pushnil(L);
- lua_pushstring(L, getErrorString(error).c_str());
- bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, error);
- assert(converted);
- Lua::registerTableToString(L, -1);
- return 3;
- }
- else {
- if (result) {
- bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, result);
- assert(converted);
- Lua::registerTableToString(L, -1);
- }
- else {
- lua_pushboolean(L, 1);
- }
- return 1;
- }
+ if (error) {
+ lua_pushnil(L);
+ lua_pushstring(L, getErrorString(error).c_str());
+ bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, error);
+ assert(converted);
+ Lua::registerTableToString(L, -1);
+ return 3;
+ }
+ else {
+ if (result) {
+ bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, result);
+ assert(converted);
+ Lua::registerTableToString(L, -1);
+ }
+ else {
+ lua_pushboolean(L, 1);
+ }
+ return 1;
+ }
}
diff --git a/Sluift/Response.h b/Sluift/Response.h
index 9830dcc..c0bd28a 100644
--- a/Sluift/Response.h
+++ b/Sluift/Response.h
@@ -13,24 +13,24 @@
struct lua_State;
namespace Swift {
- namespace Sluift {
- struct Response {
- Response(boost::shared_ptr<Payload> result, boost::shared_ptr<ErrorPayload> error) : result(result), error(error) {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Response)
- ~Response();
-
- static Response withResult(boost::shared_ptr<Payload> response) {
- return Response(response, boost::shared_ptr<ErrorPayload>());
- }
-
- static Response withError(boost::shared_ptr<ErrorPayload> error) {
- return Response(boost::shared_ptr<Payload>(), error);
- }
-
- int convertToLuaResult(lua_State* L);
-
- boost::shared_ptr<Payload> result;
- boost::shared_ptr<ErrorPayload> error;
- };
- }
+ namespace Sluift {
+ struct Response {
+ Response(boost::shared_ptr<Payload> result, boost::shared_ptr<ErrorPayload> error) : result(result), error(error) {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Response)
+ ~Response();
+
+ static Response withResult(boost::shared_ptr<Payload> response) {
+ return Response(response, boost::shared_ptr<ErrorPayload>());
+ }
+
+ static Response withError(boost::shared_ptr<ErrorPayload> error) {
+ return Response(boost::shared_ptr<Payload>(), error);
+ }
+
+ int convertToLuaResult(lua_State* L);
+
+ boost::shared_ptr<Payload> result;
+ boost::shared_ptr<ErrorPayload> error;
+ };
+ }
}
diff --git a/Sluift/SluiftClient.cpp b/Sluift/SluiftClient.cpp
index 1de317c..fea3291 100644
--- a/Sluift/SluiftClient.cpp
+++ b/Sluift/SluiftClient.cpp
@@ -23,168 +23,168 @@
using namespace Swift;
SluiftClient::SluiftClient(
- const JID& jid,
- const std::string& password,
- NetworkFactories* networkFactories,
- SimpleEventLoop* eventLoop) :
- networkFactories(networkFactories),
- eventLoop(eventLoop),
- tracer(NULL) {
- client = new Client(jid, password, networkFactories);
- client->setAlwaysTrustCertificates();
- client->onDisconnected.connect(boost::bind(&SluiftClient::handleDisconnected, this, _1));
- client->onMessageReceived.connect(boost::bind(&SluiftClient::handleIncomingMessage, this, _1));
- client->onPresenceReceived.connect(boost::bind(&SluiftClient::handleIncomingPresence, this, _1));
- client->getPubSubManager()->onEvent.connect(boost::bind(&SluiftClient::handleIncomingPubSubEvent, this, _1, _2));
- client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SluiftClient::handleInitialRosterPopulated, this));
+ const JID& jid,
+ const std::string& password,
+ NetworkFactories* networkFactories,
+ SimpleEventLoop* eventLoop) :
+ networkFactories(networkFactories),
+ eventLoop(eventLoop),
+ tracer(NULL) {
+ client = new Client(jid, password, networkFactories);
+ client->setAlwaysTrustCertificates();
+ client->onDisconnected.connect(boost::bind(&SluiftClient::handleDisconnected, this, _1));
+ client->onMessageReceived.connect(boost::bind(&SluiftClient::handleIncomingMessage, this, _1));
+ client->onPresenceReceived.connect(boost::bind(&SluiftClient::handleIncomingPresence, this, _1));
+ client->getPubSubManager()->onEvent.connect(boost::bind(&SluiftClient::handleIncomingPubSubEvent, this, _1, _2));
+ client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SluiftClient::handleInitialRosterPopulated, this));
}
SluiftClient::~SluiftClient() {
- delete tracer;
- delete client;
+ delete tracer;
+ delete client;
}
void SluiftClient::connect() {
- rosterReceived = false;
- disconnectedError = boost::optional<ClientError>();
- client->connect(options);
+ rosterReceived = false;
+ disconnectedError = boost::optional<ClientError>();
+ client->connect(options);
}
void SluiftClient::connect(const std::string& host, int port) {
- rosterReceived = false;
- options.manualHostname = host;
- options.manualPort = port;
- disconnectedError = boost::optional<ClientError>();
- client->connect(options);
+ rosterReceived = false;
+ options.manualHostname = host;
+ options.manualPort = port;
+ disconnectedError = boost::optional<ClientError>();
+ client->connect(options);
}
void SluiftClient::setTraceEnabled(bool b) {
- if (b && !tracer) {
- tracer = new ClientXMLTracer(client, options.boshURL.isEmpty()? false: true);
- }
- else if (!b && tracer) {
- delete tracer;
- tracer = NULL;
- }
+ if (b && !tracer) {
+ tracer = new ClientXMLTracer(client, options.boshURL.isEmpty()? false: true);
+ }
+ else if (!b && tracer) {
+ delete tracer;
+ tracer = NULL;
+ }
}
void SluiftClient::waitConnected(int timeout) {
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- while (!watchdog.getTimedOut() && client->isActive() && !client->isAvailable()) {
- eventLoop->runUntilEvents();
- }
- if (watchdog.getTimedOut()) {
- client->disconnect();
- throw Lua::Exception("Timeout while connecting");
- }
- if (disconnectedError) {
- throw Lua::Exception(getErrorString(*disconnectedError));
- }
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ while (!watchdog.getTimedOut() && client->isActive() && !client->isAvailable()) {
+ eventLoop->runUntilEvents();
+ }
+ if (watchdog.getTimedOut()) {
+ client->disconnect();
+ throw Lua::Exception("Timeout while connecting");
+ }
+ if (disconnectedError) {
+ throw Lua::Exception(getErrorString(*disconnectedError));
+ }
}
bool SluiftClient::isConnected() const {
- return client->isAvailable();
+ return client->isAvailable();
}
void SluiftClient::disconnect() {
- client->disconnect();
- while (client->isActive()) {
- eventLoop->runUntilEvents();
- }
+ client->disconnect();
+ while (client->isActive()) {
+ eventLoop->runUntilEvents();
+ }
}
void SluiftClient::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os) {
- client->setSoftwareVersion(name, version, os);
+ client->setSoftwareVersion(name, version, os);
}
boost::optional<SluiftClient::Event> SluiftClient::getNextEvent(
- int timeout, boost::function<bool (const Event&)> condition) {
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- size_t currentIndex = 0;
- while (true) {
- // Look for pending events in the queue
- while (currentIndex < pendingEvents.size()) {
- Event event = pendingEvents[currentIndex];
- if (!condition || condition(event)) {
- pendingEvents.erase(
- pendingEvents.begin()
- + boost::numeric_cast<int>(currentIndex));
- return event;
- }
- ++currentIndex;
- }
-
- // Wait for new events
- while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && client->isActive()) {
- eventLoop->runUntilEvents();
- }
-
- // Finish if we're disconnected or timed out
- if (watchdog.getTimedOut() || !client->isActive()) {
- return boost::optional<Event>();
- }
- }
+ int timeout, boost::function<bool (const Event&)> condition) {
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ size_t currentIndex = 0;
+ while (true) {
+ // Look for pending events in the queue
+ while (currentIndex < pendingEvents.size()) {
+ Event event = pendingEvents[currentIndex];
+ if (!condition || condition(event)) {
+ pendingEvents.erase(
+ pendingEvents.begin()
+ + boost::numeric_cast<int>(currentIndex));
+ return event;
+ }
+ ++currentIndex;
+ }
+
+ // Wait for new events
+ while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && client->isActive()) {
+ eventLoop->runUntilEvents();
+ }
+
+ // Finish if we're disconnected or timed out
+ if (watchdog.getTimedOut() || !client->isActive()) {
+ return boost::optional<Event>();
+ }
+ }
}
std::vector<XMPPRosterItem> SluiftClient::getRoster(int timeout) {
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- if (!rosterReceived) {
- // If we haven't requested it yet, request it for the first time
- client->requestRoster();
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ if (!rosterReceived) {
+ // If we haven't requested it yet, request it for the first time
+ client->requestRoster();
- // Wait for new events
- while (!watchdog.getTimedOut() && !rosterReceived) {
- eventLoop->runUntilEvents();
- }
+ // Wait for new events
+ while (!watchdog.getTimedOut() && !rosterReceived) {
+ eventLoop->runUntilEvents();
+ }
- // Throw an error if we're timed out
- if (watchdog.getTimedOut()) {
- throw Lua::Exception("Timeout while requesting roster");
- }
- }
- return client->getRoster()->getItems();
+ // Throw an error if we're timed out
+ if (watchdog.getTimedOut()) {
+ throw Lua::Exception("Timeout while requesting roster");
+ }
+ }
+ return client->getRoster()->getItems();
}
void SluiftClient::handleIncomingMessage(boost::shared_ptr<Message> stanza) {
- if (stanza->getPayload<PubSubEvent>()) {
- // Already handled by pubsub manager
- return;
- }
- pendingEvents.push_back(Event(stanza));
+ if (stanza->getPayload<PubSubEvent>()) {
+ // Already handled by pubsub manager
+ return;
+ }
+ pendingEvents.push_back(Event(stanza));
}
void SluiftClient::handleIncomingPresence(boost::shared_ptr<Presence> stanza) {
- pendingEvents.push_back(Event(stanza));
+ pendingEvents.push_back(Event(stanza));
}
void SluiftClient::handleIncomingPubSubEvent(const JID& from, boost::shared_ptr<PubSubEventPayload> event) {
- pendingEvents.push_back(Event(from, event));
+ pendingEvents.push_back(Event(from, event));
}
void SluiftClient::handleInitialRosterPopulated() {
- rosterReceived = true;
+ rosterReceived = true;
}
void SluiftClient::handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error) {
- requestResponse = response;
- requestError = error;
- requestResponseReceived = true;
+ requestResponse = response;
+ requestError = error;
+ requestResponseReceived = true;
}
void SluiftClient::handleDisconnected(const boost::optional<ClientError>& error) {
- disconnectedError = error;
+ disconnectedError = error;
}
Sluift::Response SluiftClient::doSendRequest(boost::shared_ptr<Request> request, int timeout) {
- requestResponse.reset();
- requestError.reset();
- requestResponseReceived = false;
- request->send();
-
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- while (!watchdog.getTimedOut() && !requestResponseReceived) {
- eventLoop->runUntilEvents();
- }
- return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
- boost::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
+ requestResponse.reset();
+ requestError.reset();
+ requestResponseReceived = false;
+ request->send();
+
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ while (!watchdog.getTimedOut() && !requestResponseReceived) {
+ eventLoop->runUntilEvents();
+ }
+ return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
+ boost::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
}
diff --git a/Sluift/SluiftClient.h b/Sluift/SluiftClient.h
index 07073ce..d7c3b32 100644
--- a/Sluift/SluiftClient.h
+++ b/Sluift/SluiftClient.h
@@ -28,106 +28,106 @@
#include <Sluift/Watchdog.h>
namespace Swift {
- struct SluiftGlobals;
- class ClientXMLTracer;
- class Client;
- class Stanza;
- class Payload;
- class ErrorPayload;
- class JID;
-
- class SluiftClient {
- public:
- struct Event {
- enum Type {
- MessageType,
- PresenceType,
- PubSubEventType
- };
-
- Event(boost::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
- Event(boost::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
- Event(const JID& from, boost::shared_ptr<PubSubEventPayload> payload) : type(PubSubEventType), from(from), pubsubEvent(payload) {}
-
- Type type;
-
- // Message & Presence
- boost::shared_ptr<Stanza> stanza;
-
- // PubSubEvent
- JID from;
- boost::shared_ptr<PubSubEventPayload> pubsubEvent;
- };
-
- SluiftClient(
- const JID& jid,
- const std::string& password,
- NetworkFactories* networkFactories,
- SimpleEventLoop* eventLoop);
- ~SluiftClient();
-
- Client* getClient() {
- return client;
- }
-
- ClientOptions& getOptions() {
- return options;
- }
-
- void connect();
- void connect(const std::string& host, int port);
- void waitConnected(int timeout);
- bool isConnected() const;
- void setTraceEnabled(bool b);
-
- template<typename T>
- Sluift::Response sendPubSubRequest(
- IQ::Type type, const JID& jid, boost::shared_ptr<T> payload, int timeout) {
- return sendRequest(client->getPubSubManager()->createRequest(
- type, jid, payload), timeout);
- }
-
- template<typename REQUEST_TYPE>
- Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) {
- boost::signals::scoped_connection c = request->onResponse.connect(
- boost::bind(&SluiftClient::handleRequestResponse, this, _1, _2));
- return doSendRequest(request, timeout);
- }
-
- template<typename REQUEST_TYPE>
- Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) {
- boost::signals::scoped_connection c = request->onResponse.connect(
- boost::bind(&SluiftClient::handleRequestResponse, this, boost::shared_ptr<Payload>(), _1));
- return doSendRequest(request, timeout);
- }
-
- void disconnect();
- void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os);
- boost::optional<SluiftClient::Event> getNextEvent(int timeout,
- boost::function<bool (const Event&)> condition = 0);
- std::vector<XMPPRosterItem> getRoster(int timeout);
-
- private:
- Sluift::Response doSendRequest(boost::shared_ptr<Request> request, int timeout);
-
- void handleIncomingMessage(boost::shared_ptr<Message> stanza);
- void handleIncomingPresence(boost::shared_ptr<Presence> stanza);
- void handleIncomingPubSubEvent(const JID& from, boost::shared_ptr<PubSubEventPayload> event);
- void handleInitialRosterPopulated();
- void handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error);
- void handleDisconnected(const boost::optional<ClientError>& error);
-
- private:
- NetworkFactories* networkFactories;
- SimpleEventLoop* eventLoop;
- Client* client;
- ClientOptions options;
- ClientXMLTracer* tracer;
- bool rosterReceived;
- std::deque<Event> pendingEvents;
- boost::optional<ClientError> disconnectedError;
- bool requestResponseReceived;
- boost::shared_ptr<Payload> requestResponse;
- boost::shared_ptr<ErrorPayload> requestError;
- };
+ struct SluiftGlobals;
+ class ClientXMLTracer;
+ class Client;
+ class Stanza;
+ class Payload;
+ class ErrorPayload;
+ class JID;
+
+ class SluiftClient {
+ public:
+ struct Event {
+ enum Type {
+ MessageType,
+ PresenceType,
+ PubSubEventType
+ };
+
+ Event(boost::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
+ Event(boost::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
+ Event(const JID& from, boost::shared_ptr<PubSubEventPayload> payload) : type(PubSubEventType), from(from), pubsubEvent(payload) {}
+
+ Type type;
+
+ // Message & Presence
+ boost::shared_ptr<Stanza> stanza;
+
+ // PubSubEvent
+ JID from;
+ boost::shared_ptr<PubSubEventPayload> pubsubEvent;
+ };
+
+ SluiftClient(
+ const JID& jid,
+ const std::string& password,
+ NetworkFactories* networkFactories,
+ SimpleEventLoop* eventLoop);
+ ~SluiftClient();
+
+ Client* getClient() {
+ return client;
+ }
+
+ ClientOptions& getOptions() {
+ return options;
+ }
+
+ void connect();
+ void connect(const std::string& host, int port);
+ void waitConnected(int timeout);
+ bool isConnected() const;
+ void setTraceEnabled(bool b);
+
+ template<typename T>
+ Sluift::Response sendPubSubRequest(
+ IQ::Type type, const JID& jid, boost::shared_ptr<T> payload, int timeout) {
+ return sendRequest(client->getPubSubManager()->createRequest(
+ type, jid, payload), timeout);
+ }
+
+ template<typename REQUEST_TYPE>
+ Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) {
+ boost::signals::scoped_connection c = request->onResponse.connect(
+ boost::bind(&SluiftClient::handleRequestResponse, this, _1, _2));
+ return doSendRequest(request, timeout);
+ }
+
+ template<typename REQUEST_TYPE>
+ Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) {
+ boost::signals::scoped_connection c = request->onResponse.connect(
+ boost::bind(&SluiftClient::handleRequestResponse, this, boost::shared_ptr<Payload>(), _1));
+ return doSendRequest(request, timeout);
+ }
+
+ void disconnect();
+ void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os);
+ boost::optional<SluiftClient::Event> getNextEvent(int timeout,
+ boost::function<bool (const Event&)> condition = 0);
+ std::vector<XMPPRosterItem> getRoster(int timeout);
+
+ private:
+ Sluift::Response doSendRequest(boost::shared_ptr<Request> request, int timeout);
+
+ void handleIncomingMessage(boost::shared_ptr<Message> stanza);
+ void handleIncomingPresence(boost::shared_ptr<Presence> stanza);
+ void handleIncomingPubSubEvent(const JID& from, boost::shared_ptr<PubSubEventPayload> event);
+ void handleInitialRosterPopulated();
+ void handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error);
+ void handleDisconnected(const boost::optional<ClientError>& error);
+
+ private:
+ NetworkFactories* networkFactories;
+ SimpleEventLoop* eventLoop;
+ Client* client;
+ ClientOptions options;
+ ClientXMLTracer* tracer;
+ bool rosterReceived;
+ std::deque<Event> pendingEvents;
+ boost::optional<ClientError> disconnectedError;
+ bool requestResponseReceived;
+ boost::shared_ptr<Payload> requestResponse;
+ boost::shared_ptr<ErrorPayload> requestError;
+ };
}
diff --git a/Sluift/SluiftComponent.cpp b/Sluift/SluiftComponent.cpp
index 9d0a92e..c0dcd3c 100644
--- a/Sluift/SluiftComponent.cpp
+++ b/Sluift/SluiftComponent.cpp
@@ -22,125 +22,125 @@
using namespace Swift;
SluiftComponent::SluiftComponent(
- const JID& jid,
- const std::string& password,
- NetworkFactories* networkFactories,
- SimpleEventLoop* eventLoop):
- networkFactories(networkFactories),
- eventLoop(eventLoop),
- tracer(NULL) {
- component = new Component(jid, password, networkFactories);
- component->onError.connect(boost::bind(&SluiftComponent::handleError, this, _1));
- component->onMessageReceived.connect(boost::bind(&SluiftComponent::handleIncomingMessage, this, _1));
- component->onPresenceReceived.connect(boost::bind(&SluiftComponent::handleIncomingPresence, this, _1));
+ const JID& jid,
+ const std::string& password,
+ NetworkFactories* networkFactories,
+ SimpleEventLoop* eventLoop):
+ networkFactories(networkFactories),
+ eventLoop(eventLoop),
+ tracer(NULL) {
+ component = new Component(jid, password, networkFactories);
+ component->onError.connect(boost::bind(&SluiftComponent::handleError, this, _1));
+ component->onMessageReceived.connect(boost::bind(&SluiftComponent::handleIncomingMessage, this, _1));
+ component->onPresenceReceived.connect(boost::bind(&SluiftComponent::handleIncomingPresence, this, _1));
}
SluiftComponent::~SluiftComponent() {
- delete tracer;
- delete component;
+ delete tracer;
+ delete component;
}
void SluiftComponent::connect(const std::string& host, int port) {
- disconnectedError = boost::optional<ComponentError>();
- component->connect(host, port);
+ disconnectedError = boost::optional<ComponentError>();
+ component->connect(host, port);
}
void SluiftComponent::setTraceEnabled(bool b) {
- if (b && !tracer) {
- tracer = new ComponentXMLTracer(component);
- }
- else if (!b && tracer) {
- delete tracer;
- tracer = NULL;
- }
+ if (b && !tracer) {
+ tracer = new ComponentXMLTracer(component);
+ }
+ else if (!b && tracer) {
+ delete tracer;
+ tracer = NULL;
+ }
}
void SluiftComponent::waitConnected(int timeout) {
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- while (!watchdog.getTimedOut() && !disconnectedError && !component->isAvailable()) {
- eventLoop->runUntilEvents();
- }
- if (watchdog.getTimedOut()) {
- component->disconnect();
- throw Lua::Exception("Timeout while connecting");
- }
- if (disconnectedError) {
- throw Lua::Exception(getErrorString(*disconnectedError));
- }
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ while (!watchdog.getTimedOut() && !disconnectedError && !component->isAvailable()) {
+ eventLoop->runUntilEvents();
+ }
+ if (watchdog.getTimedOut()) {
+ component->disconnect();
+ throw Lua::Exception("Timeout while connecting");
+ }
+ if (disconnectedError) {
+ throw Lua::Exception(getErrorString(*disconnectedError));
+ }
}
bool SluiftComponent::isConnected() const {
- return component->isAvailable();
+ return component->isAvailable();
}
void SluiftComponent::disconnect() {
- component->disconnect();
- while (component->isAvailable()) {
- eventLoop->runUntilEvents();
- }
+ component->disconnect();
+ while (component->isAvailable()) {
+ eventLoop->runUntilEvents();
+ }
}
void SluiftComponent::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& /* os */) {
- component->setSoftwareVersion(name, version);
+ component->setSoftwareVersion(name, version);
}
boost::optional<SluiftComponent::Event> SluiftComponent::getNextEvent(
- int timeout, boost::function<bool (const Event&)> condition) {
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- size_t currentIndex = 0;
- while (true) {
- // Look for pending events in the queue
- while (currentIndex < pendingEvents.size()) {
- Event event = pendingEvents[currentIndex];
- if (!condition || condition(event)) {
- pendingEvents.erase(
- pendingEvents.begin()
- + boost::numeric_cast<int>(currentIndex));
- return event;
- }
- ++currentIndex;
- }
-
- // Wait for new events
- while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && component->isAvailable()) {
- eventLoop->runUntilEvents();
- }
-
- // Finish if we're disconnected or timed out
- if (watchdog.getTimedOut() || !component->isAvailable()) {
- return boost::optional<Event>();
- }
- }
+ int timeout, boost::function<bool (const Event&)> condition) {
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ size_t currentIndex = 0;
+ while (true) {
+ // Look for pending events in the queue
+ while (currentIndex < pendingEvents.size()) {
+ Event event = pendingEvents[currentIndex];
+ if (!condition || condition(event)) {
+ pendingEvents.erase(
+ pendingEvents.begin()
+ + boost::numeric_cast<int>(currentIndex));
+ return event;
+ }
+ ++currentIndex;
+ }
+
+ // Wait for new events
+ while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && component->isAvailable()) {
+ eventLoop->runUntilEvents();
+ }
+
+ // Finish if we're disconnected or timed out
+ if (watchdog.getTimedOut() || !component->isAvailable()) {
+ return boost::optional<Event>();
+ }
+ }
}
void SluiftComponent::handleIncomingMessage(boost::shared_ptr<Message> stanza) {
- pendingEvents.push_back(Event(stanza));
+ pendingEvents.push_back(Event(stanza));
}
void SluiftComponent::handleIncomingPresence(boost::shared_ptr<Presence> stanza) {
- pendingEvents.push_back(Event(stanza));
+ pendingEvents.push_back(Event(stanza));
}
void SluiftComponent::handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error) {
- requestResponse = response;
- requestError = error;
- requestResponseReceived = true;
+ requestResponse = response;
+ requestError = error;
+ requestResponseReceived = true;
}
void SluiftComponent::handleError(const boost::optional<ComponentError>& error) {
- disconnectedError = error;
+ disconnectedError = error;
}
Sluift::Response SluiftComponent::doSendRequest(boost::shared_ptr<Request> request, int timeout) {
- requestResponse.reset();
- requestError.reset();
- requestResponseReceived = false;
- request->send();
-
- Watchdog watchdog(timeout, networkFactories->getTimerFactory());
- while (!watchdog.getTimedOut() && !requestResponseReceived) {
- eventLoop->runUntilEvents();
- }
- return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
- boost::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
+ requestResponse.reset();
+ requestError.reset();
+ requestResponseReceived = false;
+ request->send();
+
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ while (!watchdog.getTimedOut() && !requestResponseReceived) {
+ eventLoop->runUntilEvents();
+ }
+ return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
+ boost::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
}
diff --git a/Sluift/SluiftComponent.h b/Sluift/SluiftComponent.h
index 7a8254c..fd1b97a 100644
--- a/Sluift/SluiftComponent.h
+++ b/Sluift/SluiftComponent.h
@@ -27,83 +27,83 @@
#include <Sluift/Watchdog.h>
namespace Swift {
- struct SluiftGlobals;
- class ComponentXMLTracer;
- class Component;
- class Stanza;
- class Payload;
- class ErrorPayload;
- class JID;
-
- class SluiftComponent {
- public:
- struct Event {
- enum Type {
- MessageType,
- PresenceType
- };
-
- Event(boost::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
- Event(boost::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
-
- Type type;
-
- // Message & Presence
- boost::shared_ptr<Stanza> stanza;
- };
-
- SluiftComponent(
- const JID& jid,
- const std::string& password,
- NetworkFactories* networkFactories,
- SimpleEventLoop* eventLoop);
- ~SluiftComponent();
-
- Component* getComponent() {
- return component;
- }
-
- void connect(const std::string& host, int port);
- void waitConnected(int timeout);
- bool isConnected() const;
- void setTraceEnabled(bool b);
-
- template<typename REQUEST_TYPE>
- Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) {
- boost::signals::scoped_connection c = request->onResponse.connect(
- boost::bind(&SluiftComponent::handleRequestResponse, this, _1, _2));
- return doSendRequest(request, timeout);
- }
-
- template<typename REQUEST_TYPE>
- Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) {
- boost::signals::scoped_connection c = request->onResponse.connect(
- boost::bind(&SluiftComponent::handleRequestResponse, this, boost::shared_ptr<Payload>(), _1));
- return doSendRequest(request, timeout);
- }
-
- void disconnect();
- void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os);
- boost::optional<SluiftComponent::Event> getNextEvent(int timeout,
- boost::function<bool (const Event&)> condition = 0);
-
- private:
- Sluift::Response doSendRequest(boost::shared_ptr<Request> request, int timeout);
-
- void handleIncomingMessage(boost::shared_ptr<Message> stanza);
- void handleIncomingPresence(boost::shared_ptr<Presence> stanza);
- void handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error);
- void handleError(const boost::optional<ComponentError>& error);
-
- private:
- NetworkFactories* networkFactories;
- SimpleEventLoop* eventLoop;
- Component* component;
- ComponentXMLTracer* tracer;
- std::deque<Event> pendingEvents;
- boost::optional<ComponentError> disconnectedError;
- bool requestResponseReceived;
- boost::shared_ptr<Payload> requestResponse;
- boost::shared_ptr<ErrorPayload> requestError;
- };
+ struct SluiftGlobals;
+ class ComponentXMLTracer;
+ class Component;
+ class Stanza;
+ class Payload;
+ class ErrorPayload;
+ class JID;
+
+ class SluiftComponent {
+ public:
+ struct Event {
+ enum Type {
+ MessageType,
+ PresenceType
+ };
+
+ Event(boost::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
+ Event(boost::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
+
+ Type type;
+
+ // Message & Presence
+ boost::shared_ptr<Stanza> stanza;
+ };
+
+ SluiftComponent(
+ const JID& jid,
+ const std::string& password,
+ NetworkFactories* networkFactories,
+ SimpleEventLoop* eventLoop);
+ ~SluiftComponent();
+
+ Component* getComponent() {
+ return component;
+ }
+
+ void connect(const std::string& host, int port);
+ void waitConnected(int timeout);
+ bool isConnected() const;
+ void setTraceEnabled(bool b);
+
+ template<typename REQUEST_TYPE>
+ Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) {
+ boost::signals::scoped_connection c = request->onResponse.connect(
+ boost::bind(&SluiftComponent::handleRequestResponse, this, _1, _2));
+ return doSendRequest(request, timeout);
+ }
+
+ template<typename REQUEST_TYPE>
+ Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) {
+ boost::signals::scoped_connection c = request->onResponse.connect(
+ boost::bind(&SluiftComponent::handleRequestResponse, this, boost::shared_ptr<Payload>(), _1));
+ return doSendRequest(request, timeout);
+ }
+
+ void disconnect();
+ void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os);
+ boost::optional<SluiftComponent::Event> getNextEvent(int timeout,
+ boost::function<bool (const Event&)> condition = 0);
+
+ private:
+ Sluift::Response doSendRequest(boost::shared_ptr<Request> request, int timeout);
+
+ void handleIncomingMessage(boost::shared_ptr<Message> stanza);
+ void handleIncomingPresence(boost::shared_ptr<Presence> stanza);
+ void handleRequestResponse(boost::shared_ptr<Payload> response, boost::shared_ptr<ErrorPayload> error);
+ void handleError(const boost::optional<ComponentError>& error);
+
+ private:
+ NetworkFactories* networkFactories;
+ SimpleEventLoop* eventLoop;
+ Component* component;
+ ComponentXMLTracer* tracer;
+ std::deque<Event> pendingEvents;
+ boost::optional<ComponentError> disconnectedError;
+ bool requestResponseReceived;
+ boost::shared_ptr<Payload> requestResponse;
+ boost::shared_ptr<ErrorPayload> requestError;
+ };
}
diff --git a/Sluift/SluiftGlobals.h b/Sluift/SluiftGlobals.h
index a9c5799..14ed6f3 100644
--- a/Sluift/SluiftGlobals.h
+++ b/Sluift/SluiftGlobals.h
@@ -16,22 +16,22 @@
#include <signal.h>
namespace Swift {
- struct SluiftGlobals {
- SluiftGlobals() :
- networkFactories(&eventLoop),
- coreLibIndex(-1),
- moduleLibIndex(-1),
- interruptRequested(0) {}
+ struct SluiftGlobals {
+ SluiftGlobals() :
+ networkFactories(&eventLoop),
+ coreLibIndex(-1),
+ moduleLibIndex(-1),
+ interruptRequested(0) {}
- LuaElementConvertors elementConvertor;
- SimpleEventLoop eventLoop;
- BoostNetworkFactories networkFactories;
- PlatformTLSFactories tlsFactories;
- int coreLibIndex;
- int moduleLibIndex;
- sig_atomic_t interruptRequested;
+ LuaElementConvertors elementConvertor;
+ SimpleEventLoop eventLoop;
+ BoostNetworkFactories networkFactories;
+ PlatformTLSFactories tlsFactories;
+ int coreLibIndex;
+ int moduleLibIndex;
+ sig_atomic_t interruptRequested;
#ifdef HAVE_ITUNES
- ITunesInterface iTunes;
+ ITunesInterface iTunes;
#endif
- };
+ };
}
diff --git a/Sluift/StandardTerminal.cpp b/Sluift/StandardTerminal.cpp
index 8dad2b0..1378346 100644
--- a/Sluift/StandardTerminal.cpp
+++ b/Sluift/StandardTerminal.cpp
@@ -20,19 +20,19 @@ StandardTerminal::~StandardTerminal() {
}
void StandardTerminal::printError(const std::string& message) {
- std::cout << message << std::endl;
+ std::cout << message << std::endl;
}
boost::optional<std::string> StandardTerminal::readLine(const std::string& prompt) {
- std::cout << prompt << std::flush;
- std::string input;
- if (!std::getline(std::cin, input)) {
- if (std::cin.eof()) {
- return boost::optional<std::string>();
- }
- throw std::runtime_error("Input error");
- }
- return input;
+ std::cout << prompt << std::flush;
+ std::string input;
+ if (!std::getline(std::cin, input)) {
+ if (std::cin.eof()) {
+ return boost::optional<std::string>();
+ }
+ throw std::runtime_error("Input error");
+ }
+ return input;
}
void StandardTerminal::addToHistory(const std::string&) {
diff --git a/Sluift/StandardTerminal.h b/Sluift/StandardTerminal.h
index ca71672..2109878 100644
--- a/Sluift/StandardTerminal.h
+++ b/Sluift/StandardTerminal.h
@@ -11,13 +11,13 @@
#include <Sluift/Terminal.h>
namespace Swift {
- class StandardTerminal : public Terminal {
- public:
- StandardTerminal();
- virtual ~StandardTerminal();
+ class StandardTerminal : public Terminal {
+ public:
+ StandardTerminal();
+ virtual ~StandardTerminal();
- virtual boost::optional<std::string> readLine(const std::string& prompt) SWIFTEN_OVERRIDE;
- virtual void printError(const std::string& message) SWIFTEN_OVERRIDE;
- virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE;
- };
+ virtual boost::optional<std::string> readLine(const std::string& prompt) SWIFTEN_OVERRIDE;
+ virtual void printError(const std::string& message) SWIFTEN_OVERRIDE;
+ virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/Terminal.h b/Sluift/Terminal.h
index 72ca3d8..9d44095 100644
--- a/Sluift/Terminal.h
+++ b/Sluift/Terminal.h
@@ -11,26 +11,26 @@
#include <boost/optional/optional_fwd.hpp>
namespace Swift {
- class Completer;
+ class Completer;
- class Terminal {
- public:
- Terminal();
- virtual ~Terminal();
+ class Terminal {
+ public:
+ Terminal();
+ virtual ~Terminal();
- Completer* getCompleter() const {
- return completer;
- }
+ Completer* getCompleter() const {
+ return completer;
+ }
- void setCompleter(Completer* completer) {
- this->completer = completer;
- }
+ void setCompleter(Completer* completer) {
+ this->completer = completer;
+ }
- virtual boost::optional<std::string> readLine(const std::string& prompt) = 0;
- virtual void addToHistory(const std::string& command) = 0;
- virtual void printError(const std::string& message) = 0;
+ virtual boost::optional<std::string> readLine(const std::string& prompt) = 0;
+ virtual void addToHistory(const std::string& command) = 0;
+ virtual void printError(const std::string& message) = 0;
- private:
- Completer* completer;
- };
+ private:
+ Completer* completer;
+ };
}
diff --git a/Sluift/UnitTest/TokenizeTest.cpp b/Sluift/UnitTest/TokenizeTest.cpp
index fb7dbbd..cd617b5 100644
--- a/Sluift/UnitTest/TokenizeTest.cpp
+++ b/Sluift/UnitTest/TokenizeTest.cpp
@@ -12,52 +12,52 @@
using namespace Swift;
class TokenizeTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(TokenizeTest);
- CPPUNIT_TEST(testTokenize);
- CPPUNIT_TEST(testTokenize);
- CPPUNIT_TEST(testTokenize_String);
- CPPUNIT_TEST(testTokenize_IncompleteString);
- CPPUNIT_TEST(testTokenize_Identifier);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(TokenizeTest);
+ CPPUNIT_TEST(testTokenize);
+ CPPUNIT_TEST(testTokenize);
+ CPPUNIT_TEST(testTokenize_String);
+ CPPUNIT_TEST(testTokenize_IncompleteString);
+ CPPUNIT_TEST(testTokenize_Identifier);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testTokenize() {
- std::vector<std::string> tokens = Lua::tokenize("foo.bar + 1.23 - bam");
+ public:
+ void testTokenize() {
+ std::vector<std::string> tokens = Lua::tokenize("foo.bar + 1.23 - bam");
- CPPUNIT_ASSERT_EQUAL(7, static_cast<int>(tokens.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), tokens[2]);
- CPPUNIT_ASSERT_EQUAL(std::string("+"), tokens[3]);
- CPPUNIT_ASSERT_EQUAL(std::string("1.23"), tokens[4]);
- CPPUNIT_ASSERT_EQUAL(std::string("-"), tokens[5]);
- CPPUNIT_ASSERT_EQUAL(std::string("bam"), tokens[6]);
- }
+ CPPUNIT_ASSERT_EQUAL(7, static_cast<int>(tokens.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), tokens[2]);
+ CPPUNIT_ASSERT_EQUAL(std::string("+"), tokens[3]);
+ CPPUNIT_ASSERT_EQUAL(std::string("1.23"), tokens[4]);
+ CPPUNIT_ASSERT_EQUAL(std::string("-"), tokens[5]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bam"), tokens[6]);
+ }
- void testTokenize_String() {
- std::vector<std::string> tokens = Lua::tokenize(" foo .. \"1234\\\"bla blo\"");
+ void testTokenize_String() {
+ std::vector<std::string> tokens = Lua::tokenize(" foo .. \"1234\\\"bla blo\"");
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(tokens.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
- CPPUNIT_ASSERT_EQUAL(std::string(".."), tokens[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("\"1234\\\"bla blo\""), tokens[2]);
- }
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(tokens.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string(".."), tokens[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("\"1234\\\"bla blo\""), tokens[2]);
+ }
- void testTokenize_IncompleteString() {
- std::vector<std::string> tokens = Lua::tokenize("\"1234");
+ void testTokenize_IncompleteString() {
+ std::vector<std::string> tokens = Lua::tokenize("\"1234");
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tokens.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("\"1234"), tokens[0]);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tokens.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("\"1234"), tokens[0]);
+ }
- void testTokenize_Identifier() {
- std::vector<std::string> tokens = Lua::tokenize("foo.bar_baz");
+ void testTokenize_Identifier() {
+ std::vector<std::string> tokens = Lua::tokenize("foo.bar_baz");
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(tokens.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("bar_baz"), tokens[2]);
- }
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(tokens.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar_baz"), tokens[2]);
+ }
};
diff --git a/Sluift/Watchdog.cpp b/Sluift/Watchdog.cpp
index 6494850..a99d63a 100644
--- a/Sluift/Watchdog.cpp
+++ b/Sluift/Watchdog.cpp
@@ -13,38 +13,38 @@ static const int INTERVAL_MS = 500;
using namespace Swift;
-Watchdog::Watchdog(int timeout, TimerFactory* timerFactory) :
- remainingTime(timeout),
- timerFactory(timerFactory),
- timedOut(false) {
- Sluift::globals.interruptRequested = 0;
-
- int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS;
-
- timer = timerFactory->createTimer(nextTimeout);
- timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this));
- remainingTime -= nextTimeout;
- timer->start();
+Watchdog::Watchdog(int timeout, TimerFactory* timerFactory) :
+ remainingTime(timeout),
+ timerFactory(timerFactory),
+ timedOut(false) {
+ Sluift::globals.interruptRequested = 0;
+
+ int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS;
+
+ timer = timerFactory->createTimer(nextTimeout);
+ timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this));
+ remainingTime -= nextTimeout;
+ timer->start();
}
Watchdog::~Watchdog() {
- if (timer) {
- timer->stop();
- }
+ if (timer) {
+ timer->stop();
+ }
}
void Watchdog::handleTimerTick() {
- if (Sluift::globals.interruptRequested || remainingTime == 0) {
- timedOut = true;
- }
- else {
- int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS;
- if (nextTimeout != INTERVAL_MS) {
- timer->onTick.disconnect(boost::bind(&Watchdog::handleTimerTick, this));
- timer = timerFactory->createTimer(nextTimeout);
- timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this));
- }
- remainingTime -= nextTimeout;
- timer->start();
- }
+ if (Sluift::globals.interruptRequested || remainingTime == 0) {
+ timedOut = true;
+ }
+ else {
+ int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS;
+ if (nextTimeout != INTERVAL_MS) {
+ timer->onTick.disconnect(boost::bind(&Watchdog::handleTimerTick, this));
+ timer = timerFactory->createTimer(nextTimeout);
+ timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this));
+ }
+ remainingTime -= nextTimeout;
+ timer->start();
+ }
}
diff --git a/Sluift/Watchdog.h b/Sluift/Watchdog.h
index 8f73128..271c610 100644
--- a/Sluift/Watchdog.h
+++ b/Sluift/Watchdog.h
@@ -11,22 +11,22 @@
#include <Swiften/Network/TimerFactory.h>
namespace Swift {
- class Watchdog {
- public:
- Watchdog(int timeout, TimerFactory* timerFactory);
- ~Watchdog();
+ class Watchdog {
+ public:
+ Watchdog(int timeout, TimerFactory* timerFactory);
+ ~Watchdog();
- bool getTimedOut() const {
- return timedOut;
- }
+ bool getTimedOut() const {
+ return timedOut;
+ }
- private:
- void handleTimerTick();
+ private:
+ void handleTimerTick();
- private:
- Timer::ref timer;
- int remainingTime;
- TimerFactory* timerFactory;
- bool timedOut;
- };
+ private:
+ Timer::ref timer;
+ int remainingTime;
+ TimerFactory* timerFactory;
+ bool timedOut;
+ };
}
diff --git a/Sluift/client.cpp b/Sluift/client.cpp
index 3a8b137..3f7861c 100644
--- a/Sluift/client.cpp
+++ b/Sluift/client.cpp
@@ -49,731 +49,731 @@ using namespace Swift;
namespace lambda = boost::lambda;
static inline SluiftClient* getClient(lua_State* L) {
- return *Lua::checkUserData<SluiftClient>(L, 1);
+ return *Lua::checkUserData<SluiftClient>(L, 1);
}
static inline int getGlobalTimeout(lua_State* L) {
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
- lua_getfield(L, -1, "timeout");
- int result = boost::numeric_cast<int>(lua_tointeger(L, -1));
- lua_pop(L, 2);
- return result;
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
+ lua_getfield(L, -1, "timeout");
+ int result = boost::numeric_cast<int>(lua_tointeger(L, -1));
+ lua_pop(L, 2);
+ return result;
}
static void addPayloadsToTable(lua_State* L, const std::vector<boost::shared_ptr<Payload> >& payloads) {
- if (!payloads.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(payloads.size()), 0);
- for (size_t i = 0; i < payloads.size(); ++i) {
- Sluift::globals.elementConvertor.convertToLua(L, payloads[i]);
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- Lua::registerGetByTypeIndex(L, -1);
- lua_setfield(L, -2, "payloads");
- }
+ if (!payloads.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payloads.size()), 0);
+ for (size_t i = 0; i < payloads.size(); ++i) {
+ Sluift::globals.elementConvertor.convertToLua(L, payloads[i]);
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ Lua::registerGetByTypeIndex(L, -1);
+ lua_setfield(L, -2, "payloads");
+ }
}
static boost::shared_ptr<Payload> getPayload(lua_State* L, int index) {
- if (lua_type(L, index) == LUA_TTABLE) {
- return boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
- }
- else if (lua_type(L, index) == LUA_TSTRING) {
- return boost::make_shared<RawXMLPayload>(Lua::checkString(L, index));
- }
- else {
- return boost::shared_ptr<Payload>();
- }
+ if (lua_type(L, index) == LUA_TTABLE) {
+ return boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
+ }
+ else if (lua_type(L, index) == LUA_TSTRING) {
+ return boost::make_shared<RawXMLPayload>(Lua::checkString(L, index));
+ }
+ else {
+ return boost::shared_ptr<Payload>();
+ }
}
static std::vector< boost::shared_ptr<Payload> > getPayloadsFromTable(lua_State* L, int index) {
- index = Lua::absoluteOffset(L, index);
- std::vector< boost::shared_ptr<Payload> > result;
- lua_getfield(L, index, "payloads");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
- boost::shared_ptr<Payload> payload = getPayload(L, -1);
- if (payload) {
- result.push_back(payload);
- }
- }
- }
- lua_pop(L, 1);
- return result;
+ index = Lua::absoluteOffset(L, index);
+ std::vector< boost::shared_ptr<Payload> > result;
+ lua_getfield(L, index, "payloads");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
+ boost::shared_ptr<Payload> payload = getPayload(L, -1);
+ if (payload) {
+ result.push_back(payload);
+ }
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
SLUIFT_LUA_FUNCTION(Client, async_connect) {
- SluiftClient* client = getClient(L);
-
- std::string host = client->getOptions().manualHostname;
- int port = client->getOptions().manualPort;
- if (lua_istable(L, 2)) {
- if (boost::optional<std::string> hostString = Lua::getStringField(L, 2, "host")) {
- host = *hostString;
- }
- if (boost::optional<int> portInt = Lua::getIntField(L, 2, "port")) {
- port = *portInt;
- }
- }
- client->connect(host, port);
- return 0;
+ SluiftClient* client = getClient(L);
+
+ std::string host = client->getOptions().manualHostname;
+ int port = client->getOptions().manualPort;
+ if (lua_istable(L, 2)) {
+ if (boost::optional<std::string> hostString = Lua::getStringField(L, 2, "host")) {
+ host = *hostString;
+ }
+ if (boost::optional<int> portInt = Lua::getIntField(L, 2, "port")) {
+ port = *portInt;
+ }
+ }
+ client->connect(host, port);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_trace_enabled,
- "Enable/disable tracing of the data sent/received.\n\n.",
- "self\n"
- "enable a boolean specifying whether to enable/disable tracing",
- ""
+ Client, set_trace_enabled,
+ "Enable/disable tracing of the data sent/received.\n\n.",
+ "self\n"
+ "enable a boolean specifying whether to enable/disable tracing",
+ ""
) {
- getClient(L)->setTraceEnabled(lua_toboolean(L, 1));
- return 0;
+ getClient(L)->setTraceEnabled(lua_toboolean(L, 1));
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, wait_connected,
- "Block until the client is connected.\n\nThis is useful after an `async_connect`.",
- "self",
- ""
+ Client, wait_connected,
+ "Block until the client is connected.\n\nThis is useful after an `async_connect`.",
+ "self",
+ ""
) {
- getClient(L)->waitConnected(getGlobalTimeout(L));
- return 0;
+ getClient(L)->waitConnected(getGlobalTimeout(L));
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, is_connected,
- "Checks whether this client is still connected.\n\nReturns a boolean.",
- "self\n",
- ""
+ Client, is_connected,
+ "Checks whether this client is still connected.\n\nReturns a boolean.",
+ "self\n",
+ ""
) {
- lua_pushboolean(L, getClient(L)->isConnected());
- return 1;
+ lua_pushboolean(L, getClient(L)->isConnected());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, disconnect,
- "Disconnect from the server",
- "self\n",
- ""
+ Client, disconnect,
+ "Disconnect from the server",
+ "self\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- getClient(L)->disconnect();
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ getClient(L)->disconnect();
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_version,
+ Client, set_version,
- "Sets the published version of this client.",
+ "Sets the published version of this client.",
- "self",
+ "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"
+ "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 (boost::shared_ptr<SoftwareVersion> version = boost::dynamic_pointer_cast<SoftwareVersion>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) {
- client->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS());
- }
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+ if (boost::shared_ptr<SoftwareVersion> version = boost::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",
- ""
+ 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))) {
- 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", boost::make_shared<Lua::Value>(item.getJID().toString()))
- ("name", boost::make_shared<Lua::Value>(item.getName()))
- ("subscription", boost::make_shared<Lua::Value>(subscription))
- ("groups", boost::make_shared<Lua::Value>(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end())));
- contactsTable[item.getJID().toString()] = boost::make_shared<Lua::Value>(itemTable);
- }
- pushValue(L, contactsTable);
- Lua::registerTableToString(L, -1);
- return 1;
+ Sluift::globals.eventLoop.runOnce();
+
+ SluiftClient* client = getClient(L);
+ Lua::Table contactsTable;
+ foreach(const XMPPRosterItem& 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", boost::make_shared<Lua::Value>(item.getJID().toString()))
+ ("name", boost::make_shared<Lua::Value>(item.getName()))
+ ("subscription", boost::make_shared<Lua::Value>(subscription))
+ ("groups", boost::make_shared<Lua::Value>(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end())));
+ contactsTable[item.getJID().toString()] = boost::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"
- "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n"
- "payloads payloads to add to the message\n"
+ 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"
+ "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n"
+ "payloads payloads to add to the message\n"
) {
- Sluift::globals.eventLoop.runOnce();
- JID to;
- boost::optional<std::string> body;
- boost::optional<std::string> subject;
- std::vector<boost::shared_ptr<Payload> > payloads;
- int index = 2;
- Message::Type type = Message::Chat;
- if (lua_isstring(L, index)) {
- to = std::string(lua_tostring(L, index));
- ++index;
- if (lua_isstring(L, index)) {
- body = lua_tostring(L, index);
- ++index;
- }
- }
- if (lua_istable(L, index)) {
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
- to = *value;
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "body")) {
- body = value;
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
- type = MessageConvertor::convertMessageTypeFromString(*value);
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "subject")) {
- subject = value;
- }
-
- payloads = getPayloadsFromTable(L, index);
- }
-
- if (!to.isValid()) {
- throw Lua::Exception("Missing 'to'");
- }
- if ((!body || body->empty()) && !subject && payloads.empty()) {
- throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'");
- }
- Message::ref message = boost::make_shared<Message>();
- message->setTo(to);
- if (body && !body->empty()) {
- message->setBody(*body);
- }
- if (subject) {
- message->setSubject(*subject);
- }
- message->addPayloads(payloads.begin(), payloads.end());
- message->setType(type);
- getClient(L)->getClient()->sendMessage(message);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ JID to;
+ boost::optional<std::string> body;
+ boost::optional<std::string> subject;
+ std::vector<boost::shared_ptr<Payload> > payloads;
+ int index = 2;
+ Message::Type type = Message::Chat;
+ if (lua_isstring(L, index)) {
+ to = std::string(lua_tostring(L, index));
+ ++index;
+ if (lua_isstring(L, index)) {
+ body = lua_tostring(L, index);
+ ++index;
+ }
+ }
+ if (lua_istable(L, index)) {
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
+ to = *value;
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "body")) {
+ body = value;
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
+ type = MessageConvertor::convertMessageTypeFromString(*value);
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "subject")) {
+ subject = value;
+ }
+
+ payloads = getPayloadsFromTable(L, index);
+ }
+
+ if (!to.isValid()) {
+ throw Lua::Exception("Missing 'to'");
+ }
+ if ((!body || body->empty()) && !subject && payloads.empty()) {
+ throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'");
+ }
+ Message::ref message = boost::make_shared<Message>();
+ message->setTo(to);
+ if (body && !body->empty()) {
+ message->setBody(*body);
+ }
+ if (subject) {
+ message->setSubject(*subject);
+ }
+ message->addPayloads(payloads.begin(), payloads.end());
+ message->setType(type);
+ getClient(L)->getClient()->sendMessage(message);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, send_presence,
- "Send presence.",
-
- "self\n"
- "body the text of the presence. Can alternatively be specified using the `status` option\n",
-
- "to the JID to send the message to\n"
- "status the text of the presence\n"
- "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n"
- "priority the priority of the presence\n"
- "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n"
- "payloads payloads to add to the presence\n"
+ Client, send_presence,
+ "Send presence.",
+
+ "self\n"
+ "body the text of the presence. Can alternatively be specified using the `status` option\n",
+
+ "to the JID to send the message to\n"
+ "status the text of the presence\n"
+ "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n"
+ "priority the priority of the presence\n"
+ "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n"
+ "payloads payloads to add to the presence\n"
) {
- Sluift::globals.eventLoop.runOnce();
- boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
-
- int index = 2;
- if (lua_isstring(L, index)) {
- presence->setStatus(lua_tostring(L, index));
- ++index;
- }
- if (lua_istable(L, index)) {
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
- presence->setTo(*value);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "status")) {
- presence->setStatus(*value);
- }
- if (boost::optional<int> value = Lua::getIntField(L, index, "priority")) {
- presence->setPriority(*value);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
- presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value));
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "show")) {
- presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value));
- }
- std::vector< boost::shared_ptr<Payload> > payloads = getPayloadsFromTable(L, index);
- presence->addPayloads(payloads.begin(), payloads.end());
- }
-
- getClient(L)->getClient()->getPresenceSender()->sendPresence(presence);
- lua_pushvalue(L, 1);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
+
+ int index = 2;
+ if (lua_isstring(L, index)) {
+ presence->setStatus(lua_tostring(L, index));
+ ++index;
+ }
+ if (lua_istable(L, index)) {
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
+ presence->setTo(*value);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "status")) {
+ presence->setStatus(*value);
+ }
+ if (boost::optional<int> value = Lua::getIntField(L, index, "priority")) {
+ presence->setPriority(*value);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
+ presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value));
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "show")) {
+ presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value));
+ }
+ std::vector< boost::shared_ptr<Payload> > payloads = getPayloadsFromTable(L, index);
+ presence->addPayloads(payloads.begin(), payloads.end());
+ }
+
+ getClient(L)->getClient()->getPresenceSender()->sendPresence(presence);
+ lua_pushvalue(L, 1);
+ return 0;
}
static int sendQuery(lua_State* L, IQ::Type type) {
- SluiftClient* client = getClient(L);
+ SluiftClient* client = getClient(L);
- JID to;
- if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
- to = JID(*toString);
- }
+ JID to;
+ if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
+ to = JID(*toString);
+ }
- int timeout = getGlobalTimeout(L);
- if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
- timeout = *timeoutInt;
- }
+ int timeout = getGlobalTimeout(L);
+ if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
+ timeout = *timeoutInt;
+ }
- boost::shared_ptr<Payload> payload;
- lua_getfield(L, 2, "query");
- payload = getPayload(L, -1);
- lua_pop(L, 1);
+ boost::shared_ptr<Payload> payload;
+ lua_getfield(L, 2, "query");
+ payload = getPayload(L, -1);
+ lua_pop(L, 1);
- return client->sendRequest(
- boost::make_shared< GenericRequest<Payload> >(type, to, payload, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L);
+ return client->sendRequest(
+ boost::make_shared< GenericRequest<Payload> >(type, to, payload, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L);
}
#define DISPATCH_PUBSUB_PAYLOAD(payloadType, container, response) \
- else if (boost::shared_ptr<payloadType> p = boost::dynamic_pointer_cast<payloadType>(payload)) { \
- return client->sendPubSubRequest(type, to, p, timeout).convertToLuaResult(L); \
- }
+ else if (boost::shared_ptr<payloadType> p = boost::dynamic_pointer_cast<payloadType>(payload)) { \
+ return client->sendPubSubRequest(type, to, p, timeout).convertToLuaResult(L); \
+ }
SLUIFT_LUA_FUNCTION(Client, query_pubsub) {
- SluiftClient* client = getClient(L);
+ SluiftClient* client = getClient(L);
- JID to;
- if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
- to = JID(*toString);
- }
+ JID to;
+ if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
+ to = JID(*toString);
+ }
- int timeout = getGlobalTimeout(L);
- if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
- timeout = *timeoutInt;
- }
+ int timeout = getGlobalTimeout(L);
+ if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
+ timeout = *timeoutInt;
+ }
- IQ::Type type;
- if (boost::optional<std::string> queryType = Lua::getStringField(L, 2, "type")) {
- type = IQConvertor::convertIQTypeFromString(*queryType);
- }
- else {
- throw Lua::Exception("Missing query type");
- }
+ IQ::Type type;
+ if (boost::optional<std::string> queryType = Lua::getStringField(L, 2, "type")) {
+ type = IQConvertor::convertIQTypeFromString(*queryType);
+ }
+ else {
+ throw Lua::Exception("Missing query type");
+ }
- lua_getfield(L, 2, "query");
- if (!lua_istable(L, -1)) {
- throw Lua::Exception("Missing/incorrect query");
- }
- boost::shared_ptr<Payload> payload = getPayload(L, -1);
+ lua_getfield(L, 2, "query");
+ if (!lua_istable(L, -1)) {
+ throw Lua::Exception("Missing/incorrect query");
+ }
+ boost::shared_ptr<Payload> payload = getPayload(L, -1);
- if (false) { }
- SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(DISPATCH_PUBSUB_PAYLOAD)
- else {
- throw Lua::Exception("Incorrect PubSub payload");
- }
+ if (false) { }
+ SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(DISPATCH_PUBSUB_PAYLOAD)
+ else {
+ throw Lua::Exception("Incorrect PubSub payload");
+ }
}
SLUIFT_LUA_FUNCTION(Client, get) {
- return sendQuery(L, IQ::Get);
+ return sendQuery(L, IQ::Get);
}
SLUIFT_LUA_FUNCTION(Client, set) {
- return sendQuery(L, IQ::Set);
+ return sendQuery(L, IQ::Set);
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, send,
- "Sends a raw string",
+ Client, send,
+ "Sends a raw string",
- "self\n"
- "data the string to send\n",
+ "self\n"
+ "data the string to send\n",
- ""
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
+ Sluift::globals.eventLoop.runOnce();
- getClient(L)->getClient()->sendData(std::string(Lua::checkString(L, 2)));
- lua_pushvalue(L, 1);
- return 0;
+ getClient(L)->getClient()->sendData(std::string(Lua::checkString(L, 2)));
+ lua_pushvalue(L, 1);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_options,
+ Client, set_options,
- "Sets the connection options of this client.",
+ "Sets the connection options of this client.",
- "self",
+ "self",
- "host The host to connect to. When omitted, is determined from resolving the JID domain.\n"
- "port The port to connect to. When omitted, is determined from resolving the JID domain.\n"
- "ack Request acknowledgements\n"
- "compress Use stream compression when available\n"
- "tls Use TLS when available\n"
- "bosh_url Connect using the specified BOSH URL\n"
- "allow_plain_without_tls Allow PLAIN authentication without a TLS encrypted connection\n"
+ "host The host to connect to. When omitted, is determined from resolving the JID domain.\n"
+ "port The port to connect to. When omitted, is determined from resolving the JID domain.\n"
+ "ack Request acknowledgements\n"
+ "compress Use stream compression when available\n"
+ "tls Use TLS when available\n"
+ "bosh_url Connect using the specified BOSH URL\n"
+ "allow_plain_without_tls Allow PLAIN authentication without a TLS encrypted connection\n"
) {
- SluiftClient* client = getClient(L);
- Lua::checkType(L, 2, LUA_TTABLE);
- lua_getfield(L, 2, "host");
- if (!lua_isnil(L, -1)) {
- client->getOptions().manualHostname = lua_tostring(L, -1);
- }
- lua_getfield(L, 2, "port");
- if (!lua_isnil(L, -1)) {
- client->getOptions().manualPort = boost::numeric_cast<int>(lua_tointeger(L, -1));
- }
- lua_getfield(L, 2, "ack");
- if (!lua_isnil(L, -1)) {
- client->getOptions().useAcks = lua_toboolean(L, -1);
- }
- lua_getfield(L, 2, "compress");
- if (!lua_isnil(L, -1)) {
- client->getOptions().useStreamCompression = lua_toboolean(L, -1);
- }
- lua_getfield(L, 2, "tls");
- if (!lua_isnil(L, -1)) {
- bool useTLS = lua_toboolean(L, -1);
- client->getOptions().useTLS = (useTLS ? ClientOptions::UseTLSWhenAvailable : ClientOptions::NeverUseTLS);
- }
- lua_getfield(L, 2, "bosh_url");
- if (!lua_isnil(L, -1)) {
- client->getOptions().boshURL = URL::fromString(lua_tostring(L, -1));
- }
- lua_getfield(L, 2, "allow_plain_without_tls");
- if (!lua_isnil(L, -1)) {
- client->getOptions().allowPLAINWithoutTLS = lua_toboolean(L, -1);
- }
- lua_pushvalue(L, 1);
- return 0;
+ SluiftClient* client = getClient(L);
+ Lua::checkType(L, 2, LUA_TTABLE);
+ lua_getfield(L, 2, "host");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().manualHostname = lua_tostring(L, -1);
+ }
+ lua_getfield(L, 2, "port");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().manualPort = boost::numeric_cast<int>(lua_tointeger(L, -1));
+ }
+ lua_getfield(L, 2, "ack");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().useAcks = lua_toboolean(L, -1);
+ }
+ lua_getfield(L, 2, "compress");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().useStreamCompression = lua_toboolean(L, -1);
+ }
+ lua_getfield(L, 2, "tls");
+ if (!lua_isnil(L, -1)) {
+ bool useTLS = lua_toboolean(L, -1);
+ client->getOptions().useTLS = (useTLS ? ClientOptions::UseTLSWhenAvailable : ClientOptions::NeverUseTLS);
+ }
+ lua_getfield(L, 2, "bosh_url");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().boshURL = URL::fromString(lua_tostring(L, -1));
+ }
+ lua_getfield(L, 2, "allow_plain_without_tls");
+ if (!lua_isnil(L, -1)) {
+ client->getOptions().allowPLAINWithoutTLS = lua_toboolean(L, -1);
+ }
+ lua_pushvalue(L, 1);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, get_options,
- "Returns a table with all the connection options of this client.",
- "self\n",
- ""
+ Client, get_options,
+ "Returns a table with all the connection options of this client.",
+ "self\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
-
- SluiftClient* client = getClient(L);
- Lua::Table optionsTable = boost::assign::map_list_of
- ("host", boost::make_shared<Lua::Value>(client->getOptions().manualHostname))
- ("port", boost::make_shared<Lua::Value>(client->getOptions().manualPort))
- ("ack", boost::make_shared<Lua::Value>(client->getOptions().useAcks))
- ("compress", boost::make_shared<Lua::Value>(client->getOptions().useStreamCompression))
- ("tls", boost::make_shared<Lua::Value>(client->getOptions().useTLS == ClientOptions::NeverUseTLS ? false : true))
- ("bosh_url", boost::make_shared<Lua::Value>(client->getOptions().boshURL.toString()))
- ("allow_plain_without_tls", boost::make_shared<Lua::Value>(client->getOptions().allowPLAINWithoutTLS));
- pushValue(L, optionsTable);
- Lua::registerTableToString(L, -1);
- return 1;
+ Sluift::globals.eventLoop.runOnce();
+
+ SluiftClient* client = getClient(L);
+ Lua::Table optionsTable = boost::assign::map_list_of
+ ("host", boost::make_shared<Lua::Value>(client->getOptions().manualHostname))
+ ("port", boost::make_shared<Lua::Value>(client->getOptions().manualPort))
+ ("ack", boost::make_shared<Lua::Value>(client->getOptions().useAcks))
+ ("compress", boost::make_shared<Lua::Value>(client->getOptions().useStreamCompression))
+ ("tls", boost::make_shared<Lua::Value>(client->getOptions().useTLS == ClientOptions::NeverUseTLS ? false : true))
+ ("bosh_url", boost::make_shared<Lua::Value>(client->getOptions().boshURL.toString()))
+ ("allow_plain_without_tls", boost::make_shared<Lua::Value>(client->getOptions().allowPLAINWithoutTLS));
+ pushValue(L, optionsTable);
+ Lua::registerTableToString(L, -1);
+ return 1;
}
static void pushEvent(lua_State* L, const SluiftClient::Event& event) {
- switch (event.type) {
- case SluiftClient::Event::MessageType: {
- Message::ref message = boost::dynamic_pointer_cast<Message>(event.stanza);
- Lua::Table result = boost::assign::map_list_of
- ("type", boost::make_shared<Lua::Value>(std::string("message")))
- ("from", boost::make_shared<Lua::Value>(message->getFrom().toString()))
- ("body", boost::make_shared<Lua::Value>(message->getBody().get_value_or("")))
- ("message_type", boost::make_shared<Lua::Value>(MessageConvertor::convertMessageTypeToString(message->getType())));
- Lua::pushValue(L, result);
- addPayloadsToTable(L, message->getPayloads());
- Lua::registerTableToString(L, -1);
- break;
- }
- case SluiftClient::Event::PresenceType: {
- Presence::ref presence = boost::dynamic_pointer_cast<Presence>(event.stanza);
- Lua::Table result = boost::assign::map_list_of
- ("type", boost::make_shared<Lua::Value>(std::string("presence")))
- ("from", boost::make_shared<Lua::Value>(presence->getFrom().toString()))
- ("status", boost::make_shared<Lua::Value>(presence->getStatus()))
- ("presence_type", boost::make_shared<Lua::Value>(PresenceConvertor::convertPresenceTypeToString(presence->getType())));
- Lua::pushValue(L, result);
- addPayloadsToTable(L, presence->getPayloads());
- Lua::registerTableToString(L, -1);
- break;
- }
- case SluiftClient::Event::PubSubEventType: {
- Sluift::globals.elementConvertor.convertToLua(L, event.pubsubEvent);
- lua_pushstring(L, "pubsub");
- lua_setfield(L, -2, "type");
- lua_pushstring(L, event.from.toString().c_str());
- lua_setfield(L, -2, "from");
-
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "process_pubsub_event");
- lua_pushvalue(L, -3);
- lua_call(L, 1, 0);
- lua_pop(L, 1);
- }
- }
+ switch (event.type) {
+ case SluiftClient::Event::MessageType: {
+ Message::ref message = boost::dynamic_pointer_cast<Message>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", boost::make_shared<Lua::Value>(std::string("message")))
+ ("from", boost::make_shared<Lua::Value>(message->getFrom().toString()))
+ ("body", boost::make_shared<Lua::Value>(message->getBody().get_value_or("")))
+ ("message_type", boost::make_shared<Lua::Value>(MessageConvertor::convertMessageTypeToString(message->getType())));
+ Lua::pushValue(L, result);
+ addPayloadsToTable(L, message->getPayloads());
+ Lua::registerTableToString(L, -1);
+ break;
+ }
+ case SluiftClient::Event::PresenceType: {
+ Presence::ref presence = boost::dynamic_pointer_cast<Presence>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", boost::make_shared<Lua::Value>(std::string("presence")))
+ ("from", boost::make_shared<Lua::Value>(presence->getFrom().toString()))
+ ("status", boost::make_shared<Lua::Value>(presence->getStatus()))
+ ("presence_type", boost::make_shared<Lua::Value>(PresenceConvertor::convertPresenceTypeToString(presence->getType())));
+ Lua::pushValue(L, result);
+ addPayloadsToTable(L, presence->getPayloads());
+ Lua::registerTableToString(L, -1);
+ break;
+ }
+ case SluiftClient::Event::PubSubEventType: {
+ Sluift::globals.elementConvertor.convertToLua(L, event.pubsubEvent);
+ lua_pushstring(L, "pubsub");
+ lua_setfield(L, -2, "type");
+ lua_pushstring(L, event.from.toString().c_str());
+ lua_setfield(L, -2, "from");
+
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "process_pubsub_event");
+ lua_pushvalue(L, -3);
+ lua_call(L, 1, 0);
+ lua_pop(L, 1);
+ }
+ }
}
struct CallUnaryLuaPredicateOnEvent {
- CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) {
- }
-
- bool operator()(const SluiftClient::Event& event) {
- lua_pushvalue(L, index);
- pushEvent(L, event);
- if (lua_pcall(L, 1, 1, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- bool result = lua_toboolean(L, -1);
- lua_pop(L, 1);
- return result;
- }
-
- lua_State* L;
- int index;
+ CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) {
+ }
+
+ bool operator()(const SluiftClient::Event& event) {
+ lua_pushvalue(L, index);
+ pushEvent(L, event);
+ if (lua_pcall(L, 1, 1, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ bool result = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+ return result;
+ }
+
+ lua_State* L;
+ int index;
};
SLUIFT_LUA_FUNCTION(Client, get_next_event) {
- Sluift::globals.eventLoop.runOnce();
- SluiftClient* client = getClient(L);
-
- int timeout = getGlobalTimeout(L);
- boost::optional<SluiftClient::Event::Type> type;
- int condition = 0;
- if (lua_istable(L, 2)) {
- if (boost::optional<std::string> typeString = Lua::getStringField(L, 2, "type")) {
- if (*typeString == "message") {
- type = SluiftClient::Event::MessageType;
- }
- else if (*typeString == "presence") {
- type = SluiftClient::Event::PresenceType;
- }
- else if (*typeString == "pubsub") {
- type = SluiftClient::Event::PubSubEventType;
- }
- }
- if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
- timeout = *timeoutInt;
- }
- lua_getfield(L, 2, "if");
- if (lua_isfunction(L, -1)) {
- condition = Lua::absoluteOffset(L, -1);
- }
- }
-
- boost::optional<SluiftClient::Event> event;
- if (condition) {
- event = client->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition));
- }
- else if (type) {
- event = client->getNextEvent(
- timeout, lambda::bind(&SluiftClient::Event::type, lambda::_1) == *type);
- }
- else {
- event = client->getNextEvent(timeout);
- }
-
- if (event) {
- pushEvent(L, *event);
- }
- else {
- lua_pushnil(L);
- }
- return 1;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+
+ int timeout = getGlobalTimeout(L);
+ boost::optional<SluiftClient::Event::Type> type;
+ int condition = 0;
+ if (lua_istable(L, 2)) {
+ if (boost::optional<std::string> typeString = Lua::getStringField(L, 2, "type")) {
+ if (*typeString == "message") {
+ type = SluiftClient::Event::MessageType;
+ }
+ else if (*typeString == "presence") {
+ type = SluiftClient::Event::PresenceType;
+ }
+ else if (*typeString == "pubsub") {
+ type = SluiftClient::Event::PubSubEventType;
+ }
+ }
+ if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
+ timeout = *timeoutInt;
+ }
+ lua_getfield(L, 2, "if");
+ if (lua_isfunction(L, -1)) {
+ condition = Lua::absoluteOffset(L, -1);
+ }
+ }
+
+ boost::optional<SluiftClient::Event> event;
+ if (condition) {
+ event = client->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition));
+ }
+ else if (type) {
+ event = client->getNextEvent(
+ timeout, lambda::bind(&SluiftClient::Event::type, lambda::_1) == *type);
+ }
+ else {
+ event = client->getNextEvent(timeout);
+ }
+
+ if (event) {
+ pushEvent(L, *event);
+ }
+ else {
+ lua_pushnil(L);
+ }
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, add_contact,
- "Add a contact to the contact list.",
- "self\n",
- "jid The JID of the contact to add\n"
- "name The name to use in the contact list\n"
- "groups An array of group names to add the contact to\n") {
- Sluift::globals.eventLoop.runOnce();
- SluiftClient* client = getClient(L);
- RosterItemPayload item;
- int timeout = getGlobalTimeout(L);
-
- if (lua_type(L, 2) == LUA_TTABLE) {
- lua_getfield(L, 2, "jid");
- const char* rawJID = lua_tostring(L, -1);
- if (rawJID) {
- item.setJID(std::string(rawJID));
- }
- lua_getfield(L, 2, "name");
- const char* rawName = lua_tostring(L, -1);
- if (rawName) {
- item.setName(rawName);
- }
- lua_getfield(L, 2, "groups");
- if (!lua_isnil(L, -1)) {
- if (lua_type(L, -1) == LUA_TTABLE) {
- for (size_t i = 1; i <= lua_objlen(L, -1); ++i) {
- lua_rawgeti(L, -1, boost::numeric_cast<int>(i));
- const char* rawGroup = lua_tostring(L, -1);
- if (rawGroup) {
- item.addGroup(rawGroup);
- }
- lua_pop(L, 1);
- }
- }
- else {
- throw Lua::Exception("Groups should be a table");
- }
- }
- }
- else {
- item.setJID(Lua::checkString(L, 2));
- }
-
- client->getRoster(timeout);
- if (!client->getClient()->getRoster()->containsJID(item.getJID())) {
- RosterPayload::ref roster = boost::make_shared<RosterPayload>();
- roster->addItem(item);
-
- Sluift::Response response = client->sendVoidRequest(
- SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout);
- if (response.error) {
- return response.convertToLuaResult(L);
- }
- }
- client->getClient()->getSubscriptionManager()->requestSubscription(item.getJID());
- lua_pushboolean(L, true);
- return 1;
+ Client, add_contact,
+ "Add a contact to the contact list.",
+ "self\n",
+ "jid The JID of the contact to add\n"
+ "name The name to use in the contact list\n"
+ "groups An array of group names to add the contact to\n") {
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+ RosterItemPayload item;
+ int timeout = getGlobalTimeout(L);
+
+ if (lua_type(L, 2) == LUA_TTABLE) {
+ lua_getfield(L, 2, "jid");
+ const char* rawJID = lua_tostring(L, -1);
+ if (rawJID) {
+ item.setJID(std::string(rawJID));
+ }
+ lua_getfield(L, 2, "name");
+ const char* rawName = lua_tostring(L, -1);
+ if (rawName) {
+ item.setName(rawName);
+ }
+ lua_getfield(L, 2, "groups");
+ if (!lua_isnil(L, -1)) {
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ for (size_t i = 1; i <= lua_objlen(L, -1); ++i) {
+ lua_rawgeti(L, -1, boost::numeric_cast<int>(i));
+ const char* rawGroup = lua_tostring(L, -1);
+ if (rawGroup) {
+ item.addGroup(rawGroup);
+ }
+ lua_pop(L, 1);
+ }
+ }
+ else {
+ throw Lua::Exception("Groups should be a table");
+ }
+ }
+ }
+ else {
+ item.setJID(Lua::checkString(L, 2));
+ }
+
+ client->getRoster(timeout);
+ if (!client->getClient()->getRoster()->containsJID(item.getJID())) {
+ RosterPayload::ref roster = boost::make_shared<RosterPayload>();
+ roster->addItem(item);
+
+ Sluift::Response response = client->sendVoidRequest(
+ SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout);
+ if (response.error) {
+ return response.convertToLuaResult(L);
+ }
+ }
+ client->getClient()->getSubscriptionManager()->requestSubscription(item.getJID());
+ lua_pushboolean(L, true);
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, remove_contact,
- "Remove a contact from the contact list.",
- "self\n"
- "jid the JID of the contact to remove\n",
- ""
+ Client, remove_contact,
+ "Remove a contact from the contact list.",
+ "self\n"
+ "jid the JID of the contact to remove\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- SluiftClient* client = getClient(L);
- JID jid(Lua::checkString(L, 2));
- int timeout = getGlobalTimeout(L);
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+ JID jid(Lua::checkString(L, 2));
+ int timeout = getGlobalTimeout(L);
- RosterPayload::ref roster = boost::make_shared<RosterPayload>();
- roster->addItem(RosterItemPayload(JID(Lua::checkString(L, 2)), "", RosterItemPayload::Remove));
-
- return client->sendVoidRequest(
- SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L);
+ RosterPayload::ref roster = boost::make_shared<RosterPayload>();
+ roster->addItem(RosterItemPayload(JID(Lua::checkString(L, 2)), "", RosterItemPayload::Remove));
+
+ return client->sendVoidRequest(
+ SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L);
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, confirm_subscription,
- "Confirm subscription of a contact.",
- "self\n"
- "jid the JID of the contact to confirm the subscription of\n",
- ""
+ Client, confirm_subscription,
+ "Confirm subscription of a contact.",
+ "self\n"
+ "jid the JID of the contact to confirm the subscription of\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- SluiftClient* client = getClient(L);
- JID jid(Lua::checkString(L, 2));
- client->getClient()->getSubscriptionManager()->confirmSubscription(jid);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+ JID jid(Lua::checkString(L, 2));
+ client->getClient()->getSubscriptionManager()->confirmSubscription(jid);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, cancel_subscription,
- "Cancel the subscription of a contact.",
- "self\n"
- "jid the JID of the contact to cancel the subscription of\n",
- ""
+ Client, cancel_subscription,
+ "Cancel the subscription of a contact.",
+ "self\n"
+ "jid the JID of the contact to cancel the subscription of\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- SluiftClient* client = getClient(L);
- JID jid(Lua::checkString(L, 2));
- client->getClient()->getSubscriptionManager()->cancelSubscription(jid);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftClient* client = getClient(L);
+ JID jid(Lua::checkString(L, 2));
+ client->getClient()->getSubscriptionManager()->cancelSubscription(jid);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_disco_info,
- "Sets the service discovery information for this client",
- "self\n"
- "disco_info A structured representation of the service discovery information\n",
- ""
+ Client, set_disco_info,
+ "Sets the service discovery information for this client",
+ "self\n"
+ "disco_info A structured representation of the service discovery information\n",
+ ""
) {
- SluiftClient* client = getClient(L);
- if (!lua_istable(L, 2)) {
- throw Lua::Exception("Missing disco info");
- }
- if (boost::shared_ptr<DiscoInfo> discoInfo = boost::dynamic_pointer_cast<DiscoInfo>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "disco_info"))) {
- client->getClient()->getDiscoManager()->setDiscoInfo(*discoInfo);
- }
- else {
- throw Lua::Exception("Illegal disco info");
- }
- return 0;
+ SluiftClient* client = getClient(L);
+ if (!lua_istable(L, 2)) {
+ throw Lua::Exception("Missing disco info");
+ }
+ if (boost::shared_ptr<DiscoInfo> discoInfo = boost::dynamic_pointer_cast<DiscoInfo>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "disco_info"))) {
+ client->getClient()->getDiscoManager()->setDiscoInfo(*discoInfo);
+ }
+ else {
+ throw Lua::Exception("Illegal disco info");
+ }
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_caps_node,
- "Sets the caps node of this client",
- "self\n"
- "node The caps node (e.g. 'http://swift.im/sluift')\n",
- ""
+ Client, set_caps_node,
+ "Sets the caps node of this client",
+ "self\n"
+ "node The caps node (e.g. 'http://swift.im/sluift')\n",
+ ""
) {
- SluiftClient* client = getClient(L);
- std::string node(Lua::checkString(L, 2));
- client->getClient()->getDiscoManager()->setCapsNode(Lua::checkString(L, 2));
- return 0;
+ SluiftClient* client = getClient(L);
+ std::string node(Lua::checkString(L, 2));
+ client->getClient()->getDiscoManager()->setCapsNode(Lua::checkString(L, 2));
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, set_certificate,
- "Sets a client certificate to use for strong authentication with the server.",
- "self\n"
- "file PKCS #12 file\n"
- "pwd passphrase for the certificate private key\n",
- ""
+ Client, set_certificate,
+ "Sets a client certificate to use for strong authentication with the server.",
+ "self\n"
+ "file PKCS #12 file\n"
+ "pwd passphrase for the certificate private key\n",
+ ""
) {
- std::string file;
- std::string pwd;
- int index = 2;
- if (!lua_isnoneornil(L, index)) {
- file = Lua::checkString(L, index);
- ++index;
- if (!lua_isnoneornil(L, index)) {
- pwd = Lua::checkString(L, index);
- ++index;
- }
- }
- if (file.empty()) {
- getClient(L)->getClient()->setCertificate(CertificateWithKey::ref());
- } else {
- getClient(L)->getClient()->setCertificate(boost::make_shared<PKCS12Certificate>(file, createSafeByteArray(pwd)));
- }
- return 0;
+ std::string file;
+ std::string pwd;
+ int index = 2;
+ if (!lua_isnoneornil(L, index)) {
+ file = Lua::checkString(L, index);
+ ++index;
+ if (!lua_isnoneornil(L, index)) {
+ pwd = Lua::checkString(L, index);
+ ++index;
+ }
+ }
+ if (file.empty()) {
+ getClient(L)->getClient()->setCertificate(CertificateWithKey::ref());
+ } else {
+ getClient(L)->getClient()->setCertificate(boost::make_shared<PKCS12Certificate>(file, createSafeByteArray(pwd)));
+ }
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, jid,
- "Returns the JID of this client",
- "self\n",
- ""
+ Client, jid,
+ "Returns the JID of this client",
+ "self\n",
+ ""
) {
- SluiftClient* client = getClient(L);
- lua_pushstring(L, client->getClient()->getJID().toString().c_str());
- return 1;
+ SluiftClient* client = getClient(L);
+ lua_pushstring(L, client->getClient()->getJID().toString().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(Client, __gc) {
- SluiftClient* client = getClient(L);
- delete client;
- return 0;
+ SluiftClient* client = getClient(L);
+ delete client;
+ return 0;
}
diff --git a/Sluift/component.cpp b/Sluift/component.cpp
index af0b66e..f8184c7 100644
--- a/Sluift/component.cpp
+++ b/Sluift/component.cpp
@@ -47,423 +47,423 @@ using namespace Swift;
namespace lambda = boost::lambda;
static inline SluiftComponent* getComponent(lua_State* L) {
- return *Lua::checkUserData<SluiftComponent>(L, 1);
+ return *Lua::checkUserData<SluiftComponent>(L, 1);
}
static inline int getGlobalTimeout(lua_State* L) {
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
- lua_getfield(L, -1, "timeout");
- int result = boost::numeric_cast<int>(lua_tointeger(L, -1));
- lua_pop(L, 2);
- return result;
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
+ lua_getfield(L, -1, "timeout");
+ int result = boost::numeric_cast<int>(lua_tointeger(L, -1));
+ lua_pop(L, 2);
+ return result;
}
static void addPayloadsToTable(lua_State* L, const std::vector<boost::shared_ptr<Payload> >& payloads) {
- if (!payloads.empty()) {
- lua_createtable(L, boost::numeric_cast<int>(payloads.size()), 0);
- for (size_t i = 0; i < payloads.size(); ++i) {
- Sluift::globals.elementConvertor.convertToLua(L, payloads[i]);
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- Lua::registerGetByTypeIndex(L, -1);
- lua_setfield(L, -2, "payloads");
- }
+ if (!payloads.empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payloads.size()), 0);
+ for (size_t i = 0; i < payloads.size(); ++i) {
+ Sluift::globals.elementConvertor.convertToLua(L, payloads[i]);
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ Lua::registerGetByTypeIndex(L, -1);
+ lua_setfield(L, -2, "payloads");
+ }
}
static boost::shared_ptr<Payload> getPayload(lua_State* L, int index) {
- if (lua_type(L, index) == LUA_TTABLE) {
- return boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
- }
- else if (lua_type(L, index) == LUA_TSTRING) {
- return boost::make_shared<RawXMLPayload>(Lua::checkString(L, index));
- }
- else {
- return boost::shared_ptr<Payload>();
- }
+ if (lua_type(L, index) == LUA_TTABLE) {
+ return boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
+ }
+ else if (lua_type(L, index) == LUA_TSTRING) {
+ return boost::make_shared<RawXMLPayload>(Lua::checkString(L, index));
+ }
+ else {
+ return boost::shared_ptr<Payload>();
+ }
}
static std::vector< boost::shared_ptr<Payload> > getPayloadsFromTable(lua_State* L, int index) {
- index = Lua::absoluteOffset(L, index);
- std::vector< boost::shared_ptr<Payload> > result;
- lua_getfield(L, index, "payloads");
- if (lua_istable(L, -1)) {
- for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
- boost::shared_ptr<Payload> payload = getPayload(L, -1);
- if (payload) {
- result.push_back(payload);
- }
- }
- }
- lua_pop(L, 1);
- return result;
+ index = Lua::absoluteOffset(L, index);
+ std::vector< boost::shared_ptr<Payload> > result;
+ lua_getfield(L, index, "payloads");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
+ boost::shared_ptr<Payload> payload = getPayload(L, -1);
+ if (payload) {
+ result.push_back(payload);
+ }
+ }
+ }
+ lua_pop(L, 1);
+ return result;
}
SLUIFT_LUA_FUNCTION(Component, async_connect) {
- SluiftComponent* component = getComponent(L);
-
- std::string host;
- int port = 0;
- if (lua_istable(L, 2)) {
- if (boost::optional<std::string> hostString = Lua::getStringField(L, 2, "host")) {
- host = *hostString;
- }
- if (boost::optional<int> portInt = Lua::getIntField(L, 2, "port")) {
- port = *portInt;
- }
- }
- component->connect(host, port);
- return 0;
+ SluiftComponent* component = getComponent(L);
+
+ std::string host;
+ int port = 0;
+ if (lua_istable(L, 2)) {
+ if (boost::optional<std::string> hostString = Lua::getStringField(L, 2, "host")) {
+ host = *hostString;
+ }
+ if (boost::optional<int> portInt = Lua::getIntField(L, 2, "port")) {
+ port = *portInt;
+ }
+ }
+ component->connect(host, port);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, set_trace_enabled,
- "Enable/disable tracing of the data sent/received.\n\n.",
- "self\n"
- "enable a boolean specifying whether to enable/disable tracing",
- ""
+ Component, set_trace_enabled,
+ "Enable/disable tracing of the data sent/received.\n\n.",
+ "self\n"
+ "enable a boolean specifying whether to enable/disable tracing",
+ ""
) {
- getComponent(L)->setTraceEnabled(lua_toboolean(L, 1));
- return 0;
+ getComponent(L)->setTraceEnabled(lua_toboolean(L, 1));
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, wait_connected,
- "Block until the component is connected.\n\nThis is useful after an `async_connect`.",
- "self",
- ""
+ Component, wait_connected,
+ "Block until the component is connected.\n\nThis is useful after an `async_connect`.",
+ "self",
+ ""
) {
- getComponent(L)->waitConnected(getGlobalTimeout(L));
- return 0;
+ getComponent(L)->waitConnected(getGlobalTimeout(L));
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, is_connected,
- "Checks whether this component is still connected.\n\nReturns a boolean.",
- "self\n",
- ""
+ Component, is_connected,
+ "Checks whether this component is still connected.\n\nReturns a boolean.",
+ "self\n",
+ ""
) {
- lua_pushboolean(L, getComponent(L)->isConnected());
- return 1;
+ lua_pushboolean(L, getComponent(L)->isConnected());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, disconnect,
- "Disconnect from the server",
- "self\n",
- ""
+ Component, disconnect,
+ "Disconnect from the server",
+ "self\n",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- getComponent(L)->disconnect();
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ getComponent(L)->disconnect();
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, set_version,
+ Component, set_version,
- "Sets the published version of this component.",
+ "Sets the published version of this component.",
- "self",
+ "self",
- "name the name of the component software\n"
- "version the version identifier of this component\n"
- "os the OS this component is running on\n"
+ "name the name of the component software\n"
+ "version the version identifier of this component\n"
+ "os the OS this component is running on\n"
) {
- Sluift::globals.eventLoop.runOnce();
- SluiftComponent* component = getComponent(L);
- if (boost::shared_ptr<SoftwareVersion> version = boost::dynamic_pointer_cast<SoftwareVersion>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) {
- component->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS());
- }
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftComponent* component = getComponent(L);
+ if (boost::shared_ptr<SoftwareVersion> version = boost::dynamic_pointer_cast<SoftwareVersion>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) {
+ component->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS());
+ }
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, 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"
- "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n"
- "payloads payloads to add to the message\n"
+ Component, 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"
+ "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n"
+ "payloads payloads to add to the message\n"
) {
- Sluift::globals.eventLoop.runOnce();
- JID to;
- boost::optional<std::string> from;
- boost::optional<std::string> body;
- boost::optional<std::string> subject;
- std::vector<boost::shared_ptr<Payload> > payloads;
- int index = 2;
- Message::Type type = Message::Chat;
- if (lua_isstring(L, index)) {
- to = std::string(lua_tostring(L, index));
- ++index;
- if (lua_isstring(L, index)) {
- body = lua_tostring(L, index);
- ++index;
- }
- }
- if (lua_istable(L, index)) {
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
- to = *value;
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "from")) {
- from = value;
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "body")) {
- body = value;
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
- type = MessageConvertor::convertMessageTypeFromString(*value);
- }
-
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "subject")) {
- subject = value;
- }
-
- payloads = getPayloadsFromTable(L, index);
- }
-
- if (!to.isValid()) {
- throw Lua::Exception("Missing 'to'");
- }
- if ((!body || body->empty()) && !subject && payloads.empty()) {
- throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'");
- }
- Message::ref message = boost::make_shared<Message>();
- message->setTo(to);
- if (from && !from->empty()) {
- message->setFrom(*from);
- }
- if (body && !body->empty()) {
- message->setBody(*body);
- }
- if (subject) {
- message->setSubject(*subject);
- }
- message->addPayloads(payloads.begin(), payloads.end());
- message->setType(type);
- getComponent(L)->getComponent()->sendMessage(message);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ JID to;
+ boost::optional<std::string> from;
+ boost::optional<std::string> body;
+ boost::optional<std::string> subject;
+ std::vector<boost::shared_ptr<Payload> > payloads;
+ int index = 2;
+ Message::Type type = Message::Chat;
+ if (lua_isstring(L, index)) {
+ to = std::string(lua_tostring(L, index));
+ ++index;
+ if (lua_isstring(L, index)) {
+ body = lua_tostring(L, index);
+ ++index;
+ }
+ }
+ if (lua_istable(L, index)) {
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
+ to = *value;
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "from")) {
+ from = value;
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "body")) {
+ body = value;
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
+ type = MessageConvertor::convertMessageTypeFromString(*value);
+ }
+
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "subject")) {
+ subject = value;
+ }
+
+ payloads = getPayloadsFromTable(L, index);
+ }
+
+ if (!to.isValid()) {
+ throw Lua::Exception("Missing 'to'");
+ }
+ if ((!body || body->empty()) && !subject && payloads.empty()) {
+ throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'");
+ }
+ Message::ref message = boost::make_shared<Message>();
+ message->setTo(to);
+ if (from && !from->empty()) {
+ message->setFrom(*from);
+ }
+ if (body && !body->empty()) {
+ message->setBody(*body);
+ }
+ if (subject) {
+ message->setSubject(*subject);
+ }
+ message->addPayloads(payloads.begin(), payloads.end());
+ message->setType(type);
+ getComponent(L)->getComponent()->sendMessage(message);
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, send_presence,
- "Send presence.",
-
- "self\n"
- "body the text of the presence. Can alternatively be specified using the `status` option\n",
-
- "to the JID to send the message to\n"
- "from the JID to send the message from\n"
- "status the text of the presence\n"
- "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n"
- "priority the priority of the presence\n"
- "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n"
- "payloads payloads to add to the presence\n"
+ Component, send_presence,
+ "Send presence.",
+
+ "self\n"
+ "body the text of the presence. Can alternatively be specified using the `status` option\n",
+
+ "to the JID to send the message to\n"
+ "from the JID to send the message from\n"
+ "status the text of the presence\n"
+ "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n"
+ "priority the priority of the presence\n"
+ "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n"
+ "payloads payloads to add to the presence\n"
) {
- Sluift::globals.eventLoop.runOnce();
- boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
-
- int index = 2;
- if (lua_isstring(L, index)) {
- presence->setStatus(lua_tostring(L, index));
- ++index;
- }
- if (lua_istable(L, index)) {
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
- presence->setTo(*value);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "from")) {
- presence->setFrom(*value);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "status")) {
- presence->setStatus(*value);
- }
- if (boost::optional<int> value = Lua::getIntField(L, index, "priority")) {
- presence->setPriority(*value);
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
- presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value));
- }
- if (boost::optional<std::string> value = Lua::getStringField(L, index, "show")) {
- presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value));
- }
- std::vector< boost::shared_ptr<Payload> > payloads = getPayloadsFromTable(L, index);
- presence->addPayloads(payloads.begin(), payloads.end());
- }
-
- getComponent(L)->getComponent()->sendPresence(presence);
- lua_pushvalue(L, 1);
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
+
+ int index = 2;
+ if (lua_isstring(L, index)) {
+ presence->setStatus(lua_tostring(L, index));
+ ++index;
+ }
+ if (lua_istable(L, index)) {
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "to")) {
+ presence->setTo(*value);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "from")) {
+ presence->setFrom(*value);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "status")) {
+ presence->setStatus(*value);
+ }
+ if (boost::optional<int> value = Lua::getIntField(L, index, "priority")) {
+ presence->setPriority(*value);
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "type")) {
+ presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value));
+ }
+ if (boost::optional<std::string> value = Lua::getStringField(L, index, "show")) {
+ presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value));
+ }
+ std::vector< boost::shared_ptr<Payload> > payloads = getPayloadsFromTable(L, index);
+ presence->addPayloads(payloads.begin(), payloads.end());
+ }
+
+ getComponent(L)->getComponent()->sendPresence(presence);
+ lua_pushvalue(L, 1);
+ return 0;
}
static int sendQuery(lua_State* L, IQ::Type type) {
- SluiftComponent* component = getComponent(L);
-
- JID to;
- if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
- to = JID(*toString);
- }
-
- JID from;
- if (boost::optional<std::string> fromString = Lua::getStringField(L, 2, "from")) {
- from = JID(*fromString);
- }
-
- int timeout = getGlobalTimeout(L);
- if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
- timeout = *timeoutInt;
- }
-
- boost::shared_ptr<Payload> payload;
- lua_getfield(L, 2, "query");
- payload = getPayload(L, -1);
- lua_pop(L, 1);
-
- return component->sendRequest(
- boost::make_shared< GenericRequest<Payload> >(type, from, to, payload, component->getComponent()->getIQRouter()), timeout).convertToLuaResult(L);
+ SluiftComponent* component = getComponent(L);
+
+ JID to;
+ if (boost::optional<std::string> toString = Lua::getStringField(L, 2, "to")) {
+ to = JID(*toString);
+ }
+
+ JID from;
+ if (boost::optional<std::string> fromString = Lua::getStringField(L, 2, "from")) {
+ from = JID(*fromString);
+ }
+
+ int timeout = getGlobalTimeout(L);
+ if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
+ timeout = *timeoutInt;
+ }
+
+ boost::shared_ptr<Payload> payload;
+ lua_getfield(L, 2, "query");
+ payload = getPayload(L, -1);
+ lua_pop(L, 1);
+
+ return component->sendRequest(
+ boost::make_shared< GenericRequest<Payload> >(type, from, to, payload, component->getComponent()->getIQRouter()), timeout).convertToLuaResult(L);
}
SLUIFT_LUA_FUNCTION(Component, get) {
- return sendQuery(L, IQ::Get);
+ return sendQuery(L, IQ::Get);
}
SLUIFT_LUA_FUNCTION(Component, set) {
- return sendQuery(L, IQ::Set);
+ return sendQuery(L, IQ::Set);
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, send,
- "Sends a raw string",
+ Component, send,
+ "Sends a raw string",
- "self\n"
- "data the string to send\n",
+ "self\n"
+ "data the string to send\n",
- ""
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
+ Sluift::globals.eventLoop.runOnce();
- getComponent(L)->getComponent()->sendData(std::string(Lua::checkString(L, 2)));
- lua_pushvalue(L, 1);
- return 0;
+ getComponent(L)->getComponent()->sendData(std::string(Lua::checkString(L, 2)));
+ lua_pushvalue(L, 1);
+ return 0;
}
static void pushEvent(lua_State* L, const SluiftComponent::Event& event) {
- switch (event.type) {
- case SluiftComponent::Event::MessageType: {
- Message::ref message = boost::dynamic_pointer_cast<Message>(event.stanza);
- Lua::Table result = boost::assign::map_list_of
- ("type", boost::make_shared<Lua::Value>(std::string("message")))
- ("from", boost::make_shared<Lua::Value>(message->getFrom().toString()))
- ("to", boost::make_shared<Lua::Value>(message->getTo().toString()))
- ("body", boost::make_shared<Lua::Value>(message->getBody().get_value_or("")))
- ("message_type", boost::make_shared<Lua::Value>(MessageConvertor::convertMessageTypeToString(message->getType())));
- Lua::pushValue(L, result);
- addPayloadsToTable(L, message->getPayloads());
- Lua::registerTableToString(L, -1);
- break;
- }
- case SluiftComponent::Event::PresenceType: {
- Presence::ref presence = boost::dynamic_pointer_cast<Presence>(event.stanza);
- Lua::Table result = boost::assign::map_list_of
- ("type", boost::make_shared<Lua::Value>(std::string("presence")))
- ("from", boost::make_shared<Lua::Value>(presence->getFrom().toString()))
- ("to", boost::make_shared<Lua::Value>(presence->getTo().toString()))
- ("status", boost::make_shared<Lua::Value>(presence->getStatus()))
- ("presence_type", boost::make_shared<Lua::Value>(PresenceConvertor::convertPresenceTypeToString(presence->getType())));
- Lua::pushValue(L, result);
- addPayloadsToTable(L, presence->getPayloads());
- Lua::registerTableToString(L, -1);
- break;
- }
- }
+ switch (event.type) {
+ case SluiftComponent::Event::MessageType: {
+ Message::ref message = boost::dynamic_pointer_cast<Message>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", boost::make_shared<Lua::Value>(std::string("message")))
+ ("from", boost::make_shared<Lua::Value>(message->getFrom().toString()))
+ ("to", boost::make_shared<Lua::Value>(message->getTo().toString()))
+ ("body", boost::make_shared<Lua::Value>(message->getBody().get_value_or("")))
+ ("message_type", boost::make_shared<Lua::Value>(MessageConvertor::convertMessageTypeToString(message->getType())));
+ Lua::pushValue(L, result);
+ addPayloadsToTable(L, message->getPayloads());
+ Lua::registerTableToString(L, -1);
+ break;
+ }
+ case SluiftComponent::Event::PresenceType: {
+ Presence::ref presence = boost::dynamic_pointer_cast<Presence>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", boost::make_shared<Lua::Value>(std::string("presence")))
+ ("from", boost::make_shared<Lua::Value>(presence->getFrom().toString()))
+ ("to", boost::make_shared<Lua::Value>(presence->getTo().toString()))
+ ("status", boost::make_shared<Lua::Value>(presence->getStatus()))
+ ("presence_type", boost::make_shared<Lua::Value>(PresenceConvertor::convertPresenceTypeToString(presence->getType())));
+ Lua::pushValue(L, result);
+ addPayloadsToTable(L, presence->getPayloads());
+ Lua::registerTableToString(L, -1);
+ break;
+ }
+ }
}
struct CallUnaryLuaPredicateOnEvent {
- CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) {
- }
-
- bool operator()(const SluiftComponent::Event& event) {
- lua_pushvalue(L, index);
- pushEvent(L, event);
- if (lua_pcall(L, 1, 1, 0) != 0) {
- throw Lua::Exception(lua_tostring(L, -1));
- }
- bool result = lua_toboolean(L, -1);
- lua_pop(L, 1);
- return result;
- }
-
- lua_State* L;
- int index;
+ CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) {
+ }
+
+ bool operator()(const SluiftComponent::Event& event) {
+ lua_pushvalue(L, index);
+ pushEvent(L, event);
+ if (lua_pcall(L, 1, 1, 0) != 0) {
+ throw Lua::Exception(lua_tostring(L, -1));
+ }
+ bool result = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+ return result;
+ }
+
+ lua_State* L;
+ int index;
};
SLUIFT_LUA_FUNCTION(Component, get_next_event) {
- Sluift::globals.eventLoop.runOnce();
- SluiftComponent* component = getComponent(L);
-
- int timeout = getGlobalTimeout(L);
- boost::optional<SluiftComponent::Event::Type> type;
- int condition = 0;
- if (lua_istable(L, 2)) {
- if (boost::optional<std::string> typeString = Lua::getStringField(L, 2, "type")) {
- if (*typeString == "message") {
- type = SluiftComponent::Event::MessageType;
- }
- else if (*typeString == "presence") {
- type = SluiftComponent::Event::PresenceType;
- }
- }
- if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
- timeout = *timeoutInt;
- }
- lua_getfield(L, 2, "if");
- if (lua_isfunction(L, -1)) {
- condition = Lua::absoluteOffset(L, -1);
- }
- }
-
- boost::optional<SluiftComponent::Event> event;
- if (condition) {
- event = component->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition));
- }
- else if (type) {
- event = component->getNextEvent(
- timeout, lambda::bind(&SluiftComponent::Event::type, lambda::_1) == *type);
- }
- else {
- event = component->getNextEvent(timeout);
- }
-
- if (event) {
- pushEvent(L, *event);
- }
- else {
- lua_pushnil(L);
- }
- return 1;
+ Sluift::globals.eventLoop.runOnce();
+ SluiftComponent* component = getComponent(L);
+
+ int timeout = getGlobalTimeout(L);
+ boost::optional<SluiftComponent::Event::Type> type;
+ int condition = 0;
+ if (lua_istable(L, 2)) {
+ if (boost::optional<std::string> typeString = Lua::getStringField(L, 2, "type")) {
+ if (*typeString == "message") {
+ type = SluiftComponent::Event::MessageType;
+ }
+ else if (*typeString == "presence") {
+ type = SluiftComponent::Event::PresenceType;
+ }
+ }
+ if (boost::optional<int> timeoutInt = Lua::getIntField(L, 2, "timeout")) {
+ timeout = *timeoutInt;
+ }
+ lua_getfield(L, 2, "if");
+ if (lua_isfunction(L, -1)) {
+ condition = Lua::absoluteOffset(L, -1);
+ }
+ }
+
+ boost::optional<SluiftComponent::Event> event;
+ if (condition) {
+ event = component->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition));
+ }
+ else if (type) {
+ event = component->getNextEvent(
+ timeout, lambda::bind(&SluiftComponent::Event::type, lambda::_1) == *type);
+ }
+ else {
+ event = component->getNextEvent(timeout);
+ }
+
+ if (event) {
+ pushEvent(L, *event);
+ }
+ else {
+ lua_pushnil(L);
+ }
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Component, jid,
- "Returns the JID of this component",
- "self\n",
- ""
+ Component, jid,
+ "Returns the JID of this component",
+ "self\n",
+ ""
) {
- SluiftComponent* component = getComponent(L);
- lua_pushstring(L, component->getComponent()->getJID().toString().c_str());
- return 1;
+ SluiftComponent* component = getComponent(L);
+ lua_pushstring(L, component->getComponent()->getJID().toString().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(Component, __gc) {
- SluiftComponent* component = getComponent(L);
- delete component;
- return 0;
+ SluiftComponent* component = getComponent(L);
+ delete component;
+ return 0;
}
diff --git a/Sluift/globals.h b/Sluift/globals.h
index e414eb0..f92beeb 100644
--- a/Sluift/globals.h
+++ b/Sluift/globals.h
@@ -9,7 +9,7 @@
#include <Sluift/SluiftGlobals.h>
namespace Swift {
- namespace Sluift {
- extern SluiftGlobals globals;
- }
+ namespace Sluift {
+ extern SluiftGlobals globals;
+ }
}
diff --git a/Sluift/main.cpp b/Sluift/main.cpp
index 425f7fa..6953ca6 100644
--- a/Sluift/main.cpp
+++ b/Sluift/main.cpp
@@ -34,155 +34,155 @@ using namespace Swift;
#endif
static const std::string SLUIFT_WELCOME_STRING(
- "== Sluift XMPP Console (" SLUIFT_VERSION_STRING ")\nPress Ctrl-" EXIT_KEY " to exit. Type help() for help.");
+ "== 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},
- {"sluift", luaopen_sluift},
- {NULL, NULL}
+ {"", 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},
+ {"sluift", luaopen_sluift},
+ {NULL, NULL}
};
static void handleInterruptSignal(int) {
- Sluift::globals.interruptRequested = 1;
+ Sluift::globals.interruptRequested = 1;
}
static void checkResult(lua_State* L, int result) {
- if (result && !lua_isnil(L, -1)) {
- const char* errorMessage = lua_tostring(L, -1);
- throw std::runtime_error(errorMessage ? errorMessage : "Unknown error");
- }
+ if (result && !lua_isnil(L, -1)) {
+ const char* errorMessage = lua_tostring(L, -1);
+ 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++) {
+ 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);
+ 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);
+ lua_pushcfunction(L, lib->func);
+ lua_pushstring(L, lib->name);
+ lua_call(L, 1, 0);
#endif
- }
- lua_gc(L, LUA_GCRESTART, 0);
+ }
+ 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) {
- lua_pushstring(L, scriptArgument.c_str());
- }
- checkResult(L, Console::call(L, boost::numeric_cast<int>(scriptArguments.size()), false));
+ // 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) {
+ 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);
- }
- catch (const boost::program_options::unknown_option& option) {
+ // 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);
+ }
+ catch (const boost::program_options::unknown_option& option) {
#if BOOST_VERSION >= 104200
- std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
+ std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
#else
- std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
+ std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
#endif
- }
- catch (const std::exception& e) {
- std::cout << "Error: " << e.what() << std::endl;
- return -1;
- }
- boost::program_options::notify(arguments);
-
- // Help & version
- 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) {
- lua_getfield(L, -1, globalImport.c_str());
- lua_setglobal(L, globalImport.c_str());
- }
- lua_pop(L, 1);
-
- std::cout << SLUIFT_WELCOME_STRING << std::endl;
+ }
+ catch (const std::exception& e) {
+ std::cout << "Error: " << e.what() << std::endl;
+ return -1;
+ }
+ boost::program_options::notify(arguments);
+
+ // Help & version
+ 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) {
+ 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();
+ EditlineTerminal& terminal = EditlineTerminal::getInstance();
#else
- StandardTerminal terminal;
+ 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;
+ 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 9b82602..aff4533 100644
--- a/Sluift/sluift.cpp
+++ b/Sluift/sluift.cpp
@@ -44,20 +44,20 @@
using namespace Swift;
namespace Swift {
- namespace Sluift {
- SluiftGlobals globals;
- }
+ namespace Sluift {
+ SluiftGlobals globals;
+ }
}
extern "C" const char core_lua[];
extern "C" size_t core_lua_size;
static inline bool getGlobalDebug(lua_State* L) {
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
- lua_getfield(L, -1, "debug");
- int result = lua_toboolean(L, -1);
- lua_pop(L, 2);
- return result;
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex);
+ lua_getfield(L, -1, "debug");
+ int result = lua_toboolean(L, -1);
+ lua_pop(L, 2);
+ return result;
}
@@ -66,157 +66,157 @@ static inline bool getGlobalDebug(lua_State* L) {
******************************************************************************/
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, new_client,
+ Sluift, new_client,
- "Creates a new client.\n\nReturns a @{Client} object.\n",
+ "Creates a new client.\n\nReturns a @{Client} object.\n",
- "jid The JID to connect as\n"
- "passphrase The passphrase to use\n",
+ "jid The JID to connect as\n"
+ "passphrase The passphrase to use\n",
- ""
+ ""
) {
- Lua::checkString(L, 1);
- JID jid(std::string(Lua::checkString(L, 1)));
- std::string password(Lua::checkString(L, 2));
+ Lua::checkString(L, 1);
+ JID jid(std::string(Lua::checkString(L, 1)));
+ std::string password(Lua::checkString(L, 2));
- SluiftClient** client = reinterpret_cast<SluiftClient**>(lua_newuserdata(L, sizeof(SluiftClient*)));
+ SluiftClient** client = reinterpret_cast<SluiftClient**>(lua_newuserdata(L, sizeof(SluiftClient*)));
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "Client");
- lua_setmetatable(L, -3);
- lua_pop(L, 1);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "Client");
+ lua_setmetatable(L, -3);
+ lua_pop(L, 1);
- *client = new SluiftClient(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop);
- (*client)->setTraceEnabled(getGlobalDebug(L));
- return 1;
+ *client = new SluiftClient(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop);
+ (*client)->setTraceEnabled(getGlobalDebug(L));
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, new_component,
+ Sluift, new_component,
- "Creates a new component.\n\nReturns a @{Component} object.\n",
+ "Creates a new component.\n\nReturns a @{Component} object.\n",
- "jid The JID to connect as\n"
- "passphrase The passphrase to use\n",
+ "jid The JID to connect as\n"
+ "passphrase The passphrase to use\n",
- ""
+ ""
) {
- Lua::checkString(L, 1);
- JID jid(std::string(Lua::checkString(L, 1)));
- std::string password(Lua::checkString(L, 2));
+ Lua::checkString(L, 1);
+ JID jid(std::string(Lua::checkString(L, 1)));
+ std::string password(Lua::checkString(L, 2));
- SluiftComponent** component = reinterpret_cast<SluiftComponent**>(lua_newuserdata(L, sizeof(SluiftComponent*)));
+ SluiftComponent** component = reinterpret_cast<SluiftComponent**>(lua_newuserdata(L, sizeof(SluiftComponent*)));
- lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
- lua_getfield(L, -1, "Component");
- lua_setmetatable(L, -3);
- lua_pop(L, 1);
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ lua_getfield(L, -1, "Component");
+ lua_setmetatable(L, -3);
+ lua_pop(L, 1);
- *component = new SluiftComponent(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop);
- (*component)->setTraceEnabled(getGlobalDebug(L));
- return 1;
+ *component = new SluiftComponent(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop);
+ (*component)->setTraceEnabled(getGlobalDebug(L));
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, sha1,
- "Compute the SHA-1 hash of given data",
- "data the data to hash",
- ""
+ Sluift, sha1,
+ "Compute the SHA-1 hash of given data",
+ "data the data to hash",
+ ""
) {
- static boost::shared_ptr<CryptoProvider> crypto(PlatformCryptoProvider::create());
- if (!lua_isstring(L, 1)) {
- throw Lua::Exception("Expected string");
- }
- size_t len;
- const char* data = lua_tolstring(L, 1, &len);
- ByteArray result = crypto->getSHA1Hash(createByteArray(data, len));
- lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
- return 1;
+ static boost::shared_ptr<CryptoProvider> crypto(PlatformCryptoProvider::create());
+ if (!lua_isstring(L, 1)) {
+ throw Lua::Exception("Expected string");
+ }
+ size_t len;
+ const char* data = lua_tolstring(L, 1, &len);
+ ByteArray result = crypto->getSHA1Hash(createByteArray(data, len));
+ lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, sleep,
- "Sleeps for the given time.",
- "milliseconds the amount of milliseconds to sleep",
- ""
+ Sluift, sleep,
+ "Sleeps for the given time.",
+ "milliseconds the amount of milliseconds to sleep",
+ ""
) {
- Sluift::globals.eventLoop.runOnce();
- int timeout = Lua::checkIntNumber(L, 1);
- Watchdog watchdog(timeout, Sluift::globals.networkFactories.getTimerFactory());
- while (!watchdog.getTimedOut()) {
- Swift::sleep(boost::numeric_cast<unsigned int>(std::min(100, timeout)));
- Sluift::globals.eventLoop.runOnce();
- }
- return 0;
+ Sluift::globals.eventLoop.runOnce();
+ int timeout = Lua::checkIntNumber(L, 1);
+ Watchdog watchdog(timeout, Sluift::globals.networkFactories.getTimerFactory());
+ while (!watchdog.getTimedOut()) {
+ Swift::sleep(boost::numeric_cast<unsigned int>(std::min(100, timeout)));
+ Sluift::globals.eventLoop.runOnce();
+ }
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, new_uuid,
- "Generates a new UUID", "", ""
+ Sluift, new_uuid,
+ "Generates a new UUID", "", ""
) {
- lua_pushstring(L, IDGenerator().generateID().c_str());
- return 1;
+ lua_pushstring(L, IDGenerator().generateID().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, from_xml,
- "Convert a raw XML string into a structured representation.",
- "string the string to convert",
- ""
+ Sluift, from_xml,
+ "Convert a raw XML string into a structured representation.",
+ "string the string to convert",
+ ""
) {
- PayloadsParserTester parser;
- if (!parser.parse(Lua::checkString(L, 1))) {
- throw Lua::Exception("Error in XML");
- }
- return Sluift::globals.elementConvertor.convertToLua(L, parser.getPayload());
+ PayloadsParserTester parser;
+ if (!parser.parse(Lua::checkString(L, 1))) {
+ throw Lua::Exception("Error in XML");
+ }
+ return Sluift::globals.elementConvertor.convertToLua(L, parser.getPayload());
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, to_xml,
- "Convert a structured element into XML.",
- "element the element to convert",
- ""
+ Sluift, to_xml,
+ "Convert a structured element into XML.",
+ "element the element to convert",
+ ""
) {
- static FullPayloadSerializerCollection serializers;
- boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, 1));
- if (!payload) {
- throw Lua::Exception("Unrecognized XML");
- }
- PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
- if (!payload) {
- throw Lua::Exception("Unrecognized XML");
- }
- lua_pushstring(L, serializer->serialize(payload).c_str());
- return 1;
+ static FullPayloadSerializerCollection serializers;
+ boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, 1));
+ if (!payload) {
+ throw Lua::Exception("Unrecognized XML");
+ }
+ PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
+ if (!payload) {
+ throw Lua::Exception("Unrecognized XML");
+ }
+ lua_pushstring(L, serializer->serialize(payload).c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, hexify,
- "Convert binary data into hexadecimal format.",
- "data the data to convert",
- ""
+ Sluift, hexify,
+ "Convert binary data into hexadecimal format.",
+ "data the data to convert",
+ ""
) {
- if (!lua_isstring(L, 1)) {
- throw Lua::Exception("Expected string");
- }
- size_t len;
- const char* data = lua_tolstring(L, 1, &len);
- lua_pushstring(L, Hexify::hexify(createByteArray(data, len)).c_str());
- return 1;
+ if (!lua_isstring(L, 1)) {
+ throw Lua::Exception("Expected string");
+ }
+ size_t len;
+ const char* data = lua_tolstring(L, 1, &len);
+ lua_pushstring(L, Hexify::hexify(createByteArray(data, len)).c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Sluift, unhexify,
- "Convert hexadecimal data into binary data.",
- "data the data in hexadecimal format",
- ""
+ Sluift, unhexify,
+ "Convert hexadecimal data into binary data.",
+ "data the data in hexadecimal format",
+ ""
) {
- if (!lua_isstring(L, 1)) {
- throw Lua::Exception("Expected string");
- }
- ByteArray result = Hexify::unhexify(lua_tostring(L, 1));
- lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
- return 1;
+ if (!lua_isstring(L, 1)) {
+ throw Lua::Exception("Expected string");
+ }
+ ByteArray result = Hexify::unhexify(lua_tostring(L, 1));
+ lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
+ return 1;
}
/*******************************************************************************
@@ -224,34 +224,34 @@ SLUIFT_LUA_FUNCTION_WITH_HELP(
******************************************************************************/
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Crypto, new_certificate,
- "Creates a new X.509 certificate from DER data.\n",
+ Crypto, new_certificate,
+ "Creates a new X.509 certificate from DER data.\n",
- "der the DER-encoded certificate data",
+ "der the DER-encoded certificate data",
- "") {
- ByteArray certData(Lua::checkByteArray(L, 1));
- Certificate::ref cert(Sluift::globals.tlsFactories.getCertificateFactory()->createCertificateFromDER(certData));
- lua_createtable(L, 0, 0);
- lua_pushstring(L, cert->getSubjectName().c_str());
- lua_setfield(L, -2, "subject_name");
- lua_pushstring(L, Certificate::getSHA1Fingerprint(cert, Sluift::globals.networkFactories.getCryptoProvider()).c_str());
- lua_setfield(L, -2, "sha1_fingerprint");
+ "") {
+ ByteArray certData(Lua::checkByteArray(L, 1));
+ Certificate::ref cert(Sluift::globals.tlsFactories.getCertificateFactory()->createCertificateFromDER(certData));
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, cert->getSubjectName().c_str());
+ lua_setfield(L, -2, "subject_name");
+ lua_pushstring(L, Certificate::getSHA1Fingerprint(cert, Sluift::globals.networkFactories.getCryptoProvider()).c_str());
+ lua_setfield(L, -2, "sha1_fingerprint");
- Lua::pushStringArray(L, cert->getCommonNames());
- lua_setfield(L, -2, "common_names");
+ Lua::pushStringArray(L, cert->getCommonNames());
+ lua_setfield(L, -2, "common_names");
- Lua::pushStringArray(L, cert->getSRVNames());
- lua_setfield(L, -2, "srv_names");
+ Lua::pushStringArray(L, cert->getSRVNames());
+ lua_setfield(L, -2, "srv_names");
- Lua::pushStringArray(L, cert->getDNSNames());
- lua_setfield(L, -2, "dns_names");
+ Lua::pushStringArray(L, cert->getDNSNames());
+ lua_setfield(L, -2, "dns_names");
- Lua::pushStringArray(L, cert->getXMPPAddresses());
- lua_setfield(L, -2, "xmpp_addresses");
+ Lua::pushStringArray(L, cert->getXMPPAddresses());
+ lua_setfield(L, -2, "xmpp_addresses");
- Lua::registerTableToString(L, -1);
- return 1;
+ Lua::registerTableToString(L, -1);
+ return 1;
}
/*******************************************************************************
@@ -259,30 +259,30 @@ SLUIFT_LUA_FUNCTION_WITH_HELP(
******************************************************************************/
SLUIFT_LUA_FUNCTION(FS, list) {
- boost::filesystem::path dir(std::string(Lua::checkString(L, 1)));
- if (!boost::filesystem::exists(dir) || !boost::filesystem::is_directory(dir)) {
- lua_pushnil(L);
- lua_pushstring(L, "Argument is not an existing directory");
- return 2;
- }
-
- boost::filesystem::directory_iterator i(dir);
- std::vector<boost::filesystem::path> items(
- i, boost::filesystem::directory_iterator());
-
- lua_createtable(L, boost::numeric_cast<int>(items.size()), 0);
- for (size_t i = 0; i < items.size(); ++i) {
- lua_pushstring(L, items[i].string().c_str());
- lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
- }
- Lua::registerTableToString(L, -1);
- return 1;
+ boost::filesystem::path dir(std::string(Lua::checkString(L, 1)));
+ if (!boost::filesystem::exists(dir) || !boost::filesystem::is_directory(dir)) {
+ lua_pushnil(L);
+ lua_pushstring(L, "Argument is not an existing directory");
+ return 2;
+ }
+
+ boost::filesystem::directory_iterator i(dir);
+ std::vector<boost::filesystem::path> items(
+ i, boost::filesystem::directory_iterator());
+
+ lua_createtable(L, boost::numeric_cast<int>(items.size()), 0);
+ for (size_t i = 0; i < items.size(); ++i) {
+ lua_pushstring(L, items[i].string().c_str());
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ }
+ Lua::registerTableToString(L, -1);
+ return 1;
}
SLUIFT_LUA_FUNCTION(FS, is_file) {
- boost::filesystem::path file(std::string(Lua::checkString(L, 1)));
- lua_pushboolean(L, boost::filesystem::is_regular_file(file));
- return 1;
+ boost::filesystem::path file(std::string(Lua::checkString(L, 1)));
+ lua_pushboolean(L, boost::filesystem::is_regular_file(file));
+ return 1;
}
@@ -291,32 +291,32 @@ SLUIFT_LUA_FUNCTION(FS, is_file) {
******************************************************************************/
SLUIFT_LUA_FUNCTION(JID, to_bare) {
- JID jid(std::string(Lua::checkString(L, 1)));
- lua_pushstring(L, jid.toBare().toString().c_str());
- return 1;
+ JID jid(std::string(Lua::checkString(L, 1)));
+ lua_pushstring(L, jid.toBare().toString().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(JID, node) {
- JID jid(std::string(Lua::checkString(L, 1)));
- lua_pushstring(L, jid.getNode().c_str());
- return 1;
+ JID jid(std::string(Lua::checkString(L, 1)));
+ lua_pushstring(L, jid.getNode().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(JID, domain) {
- JID jid(std::string(Lua::checkString(L, 1)));
- lua_pushstring(L, jid.getDomain().c_str());
- return 1;
+ JID jid(std::string(Lua::checkString(L, 1)));
+ lua_pushstring(L, jid.getDomain().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(JID, resource) {
- JID jid(std::string(Lua::checkString(L, 1)));
- lua_pushstring(L, jid.getResource().c_str());
- return 1;
+ JID jid(std::string(Lua::checkString(L, 1)));
+ lua_pushstring(L, jid.getResource().c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(JID, escape_node) {
- lua_pushstring(L, JID::getEscapedNode(Lua::checkString(L, 1)).c_str());
- return 1;
+ lua_pushstring(L, JID::getEscapedNode(Lua::checkString(L, 1)).c_str());
+ return 1;
}
/*******************************************************************************
@@ -324,22 +324,22 @@ SLUIFT_LUA_FUNCTION(JID, escape_node) {
******************************************************************************/
SLUIFT_LUA_FUNCTION(Base64, encode) {
- if (!lua_isstring(L, 1)) {
- throw Lua::Exception("Expected string");
- }
- size_t len;
- const char* data = lua_tolstring(L, 1, &len);
- lua_pushstring(L, Base64::encode(createByteArray(data, len)).c_str());
- return 1;
+ if (!lua_isstring(L, 1)) {
+ throw Lua::Exception("Expected string");
+ }
+ size_t len;
+ const char* data = lua_tolstring(L, 1, &len);
+ lua_pushstring(L, Base64::encode(createByteArray(data, len)).c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(Base64, decode) {
- if (!lua_isstring(L, 1)) {
- throw Lua::Exception("Expected string");
- }
- ByteArray result = Base64::decode(lua_tostring(L, 1));
- lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
- return 1;
+ if (!lua_isstring(L, 1)) {
+ throw Lua::Exception("Expected string");
+ }
+ ByteArray result = Base64::decode(lua_tostring(L, 1));
+ lua_pushlstring(L, reinterpret_cast<char*>(vecptr(result)), result.size());
+ return 1;
}
/*******************************************************************************
@@ -347,43 +347,43 @@ SLUIFT_LUA_FUNCTION(Base64, decode) {
******************************************************************************/
SLUIFT_LUA_FUNCTION(IDN, encode) {
- IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter();
- boost::optional<std::string> encoded = converter->getIDNAEncoded(Lua::checkString(L, 1));
- if (!encoded) {
- lua_pushnil(L);
- lua_pushstring(L, "Error encoding domain name");
- return 2;
- }
- lua_pushstring(L, encoded->c_str());
- return 1;
+ IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter();
+ boost::optional<std::string> encoded = converter->getIDNAEncoded(Lua::checkString(L, 1));
+ if (!encoded) {
+ lua_pushnil(L);
+ lua_pushstring(L, "Error encoding domain name");
+ return 2;
+ }
+ lua_pushstring(L, encoded->c_str());
+ return 1;
}
SLUIFT_LUA_FUNCTION(IDN, stringprep) {
- IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter();
- IDNConverter::StringPrepProfile profile;
- std::string profileString = Lua::checkString(L, 2);
- if (profileString == "nameprep") {
- profile = IDNConverter::NamePrep;
- }
- else if (profileString == "xmpp_nodeprep") {
- profile = IDNConverter::XMPPNodePrep;
- }
- else if (profileString == "xmpp_resourceprep") {
- profile = IDNConverter::XMPPResourcePrep;
- }
- else if (profileString == "saslprep") {
- profile = IDNConverter::SASLPrep;
- }
- else {
- throw Lua::Exception("Invalid profile");
- }
- try {
- lua_pushstring(L, converter->getStringPrepared(Lua::checkString(L, 1), profile).c_str());
- }
- catch (const std::exception&) {
- throw Lua::Exception("Error");
- }
- return 1;
+ IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter();
+ IDNConverter::StringPrepProfile profile;
+ std::string profileString = Lua::checkString(L, 2);
+ if (profileString == "nameprep") {
+ profile = IDNConverter::NamePrep;
+ }
+ else if (profileString == "xmpp_nodeprep") {
+ profile = IDNConverter::XMPPNodePrep;
+ }
+ else if (profileString == "xmpp_resourceprep") {
+ profile = IDNConverter::XMPPResourcePrep;
+ }
+ else if (profileString == "saslprep") {
+ profile = IDNConverter::SASLPrep;
+ }
+ else {
+ throw Lua::Exception("Invalid profile");
+ }
+ try {
+ lua_pushstring(L, converter->getStringPrepared(Lua::checkString(L, 1), profile).c_str());
+ }
+ catch (const std::exception&) {
+ throw Lua::Exception("Error");
+ }
+ return 1;
}
/*******************************************************************************
@@ -392,26 +392,26 @@ SLUIFT_LUA_FUNCTION(IDN, stringprep) {
#ifdef HAVE_ITUNES
SLUIFT_LUA_FUNCTION(iTunes, get_current_track) {
- boost::optional<ITunesInterface::Track> track = Sluift::globals.iTunes.getCurrentTrack();
- if (!track) {
- return 0;
- }
- lua_createtable(L, 0, 0);
- lua_pushstring(L, track->artist.c_str());
- lua_setfield(L, -2, "artist");
- lua_pushstring(L, track->name.c_str());
- lua_setfield(L, -2, "name");
- lua_pushstring(L, track->album.c_str());
- lua_setfield(L, -2, "album");
- lua_pushinteger(L, track->trackNumber);
- lua_setfield(L, -2, "track_number");
- lua_pushnumber(L, track->duration);
- lua_setfield(L, -2, "duration");
- lua_pushinteger(L, track->rating);
- lua_setfield(L, -2, "rating");
- Lua::registerTableToString(L, -1);
- Lua::registerTableEquals(L, -1);
- return 1;
+ boost::optional<ITunesInterface::Track> track = Sluift::globals.iTunes.getCurrentTrack();
+ if (!track) {
+ return 0;
+ }
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, track->artist.c_str());
+ lua_setfield(L, -2, "artist");
+ lua_pushstring(L, track->name.c_str());
+ lua_setfield(L, -2, "name");
+ lua_pushstring(L, track->album.c_str());
+ lua_setfield(L, -2, "album");
+ lua_pushinteger(L, track->trackNumber);
+ lua_setfield(L, -2, "track_number");
+ lua_pushnumber(L, track->duration);
+ lua_setfield(L, -2, "duration");
+ lua_pushinteger(L, track->rating);
+ lua_setfield(L, -2, "rating");
+ Lua::registerTableToString(L, -1);
+ Lua::registerTableEquals(L, -1);
+ return 1;
}
#endif
@@ -422,81 +422,81 @@ SLUIFT_LUA_FUNCTION(iTunes, get_current_track) {
static const luaL_Reg sluift_functions[] = { {NULL, NULL} };
SLUIFT_API int luaopen_sluift(lua_State* L) {
- // Initialize & store the module table
- luaL_register(L, lua_tostring(L, 1), sluift_functions);
- lua_pushinteger(L, -1);
- lua_setfield(L, -2, "timeout");
- lua_pushboolean(L, 0);
- lua_setfield(L, -2, "debug");
-
- lua_pushvalue(L, -1);
- Sluift::globals.moduleLibIndex = luaL_ref(L, LUA_REGISTRYINDEX);
-
- // 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");
+ // Initialize & store the module table
+ luaL_register(L, lua_tostring(L, 1), sluift_functions);
+ lua_pushinteger(L, -1);
+ lua_setfield(L, -2, "timeout");
+ lua_pushboolean(L, 0);
+ lua_setfield(L, -2, "debug");
+
+ lua_pushvalue(L, -1);
+ Sluift::globals.moduleLibIndex = luaL_ref(L, LUA_REGISTRYINDEX);
+
+ // 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");
+ 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) {
- 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) {
- 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) {
- 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 (boost::shared_ptr<LuaElementConvertor> 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;
+ // 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) {
+ 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) {
+ 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) {
+ 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 (boost::shared_ptr<LuaElementConvertor> 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/Sluift/tokenize.cpp b/Sluift/tokenize.cpp
index e0252f7..ff162d6 100644
--- a/Sluift/tokenize.cpp
+++ b/Sluift/tokenize.cpp
@@ -13,75 +13,75 @@
using namespace Swift;
namespace {
- struct LuaTokenizeFunctor {
- void reset() {
- }
+ struct LuaTokenizeFunctor {
+ void reset() {
+ }
- template<typename InputIterator, typename Token>
- bool operator()(InputIterator& next, InputIterator& end, Token& result) {
- while (next != end && std::isspace(*next)) {
- ++next;
- }
- if (next == end) {
- return false;
- }
+ template<typename InputIterator, typename Token>
+ bool operator()(InputIterator& next, InputIterator& end, Token& result) {
+ while (next != end && std::isspace(*next)) {
+ ++next;
+ }
+ if (next == end) {
+ return false;
+ }
- std::vector<char> token;
- char c = *next++;
- token.push_back(c);
+ std::vector<char> token;
+ char c = *next++;
+ token.push_back(c);
- // String literal
- if (c == '\'' || c == '"') {
- char quote = c;
- bool inEscape = false;
- for (; next != end; ++next) {
- c = *next;
- token.push_back(c);
- if (inEscape) {
- inEscape = false;
- }
- else if (c == '\\') {
- inEscape = true;
- }
- else if (c == quote) {
- break;
- }
- }
- if (next != end) {
- ++next;
- }
- }
- // Identifier
- else if (std::isalpha(c) || c == '_') {
- while (next != end && (std::isalpha(*next) || *next == '_' || std::isdigit(*next))) {
- token.push_back(*next);
- ++next;
- }
- }
- // Digit
- else if (std::isdigit(c)) {
- while (next != end && !std::isspace(*next)) {
- token.push_back(*next);
- ++next;
- }
- }
- // Dots
- else if (c == '.') {
- while (next != end && *next == '.') {
- token.push_back(*next);
- ++next;
- }
- }
-
- result = Token(&token[0], token.size());
- return true;
- }
- };
+ // String literal
+ if (c == '\'' || c == '"') {
+ char quote = c;
+ bool inEscape = false;
+ for (; next != end; ++next) {
+ c = *next;
+ token.push_back(c);
+ if (inEscape) {
+ inEscape = false;
+ }
+ else if (c == '\\') {
+ inEscape = true;
+ }
+ else if (c == quote) {
+ break;
+ }
+ }
+ if (next != end) {
+ ++next;
+ }
+ }
+ // Identifier
+ else if (std::isalpha(c) || c == '_') {
+ while (next != end && (std::isalpha(*next) || *next == '_' || std::isdigit(*next))) {
+ token.push_back(*next);
+ ++next;
+ }
+ }
+ // Digit
+ else if (std::isdigit(c)) {
+ while (next != end && !std::isspace(*next)) {
+ token.push_back(*next);
+ ++next;
+ }
+ }
+ // Dots
+ else if (c == '.') {
+ while (next != end && *next == '.') {
+ token.push_back(*next);
+ ++next;
+ }
+ }
+
+ result = Token(&token[0], token.size());
+ return true;
+ }
+ };
}
std::vector<std::string> Lua::tokenize(const std::string& input) {
- boost::tokenizer<LuaTokenizeFunctor> tokenizer(input);
- return std::vector<std::string>(tokenizer.begin(), tokenizer.end());
+ boost::tokenizer<LuaTokenizeFunctor> tokenizer(input);
+ return std::vector<std::string>(tokenizer.begin(), tokenizer.end());
}
diff --git a/Sluift/tokenize.h b/Sluift/tokenize.h
index 842f1d3..33ea435 100644
--- a/Sluift/tokenize.h
+++ b/Sluift/tokenize.h
@@ -10,7 +10,7 @@
#include <vector>
namespace Swift {
- namespace Lua {
- std::vector<std::string> tokenize(const std::string&);
- }
+ namespace Lua {
+ std::vector<std::string> tokenize(const std::string&);
+ }
}
diff --git a/SwifTools/Application/ApplicationPathProvider.cpp b/SwifTools/Application/ApplicationPathProvider.cpp
index ebe9654..3a86f28 100644
--- a/SwifTools/Application/ApplicationPathProvider.cpp
+++ b/SwifTools/Application/ApplicationPathProvider.cpp
@@ -22,29 +22,29 @@ 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) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- return result;
+ boost::filesystem::path result(getHomeDir() / profile);
+ try {
+ boost::filesystem::create_directory(result);
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "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) {
- boost::filesystem::path r(resourcePath / resource);
- if (boost::filesystem::exists(r)) {
- return r;
- }
- }
- return boost::filesystem::path();
+ std::vector<boost::filesystem::path> resourcePaths = getResourceDirs();
+ foreach(const boost::filesystem::path& 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();
+ return Paths::getExecutablePath();
}
}
diff --git a/SwifTools/Application/ApplicationPathProvider.h b/SwifTools/Application/ApplicationPathProvider.h
index aba9687..399ac5d 100644
--- a/SwifTools/Application/ApplicationPathProvider.h
+++ b/SwifTools/Application/ApplicationPathProvider.h
@@ -12,24 +12,24 @@
#include <boost/filesystem.hpp>
namespace Swift {
- class ApplicationPathProvider {
- public:
- ApplicationPathProvider(const std::string& applicationName);
- virtual ~ApplicationPathProvider();
+ class ApplicationPathProvider {
+ public:
+ ApplicationPathProvider(const std::string& applicationName);
+ virtual ~ApplicationPathProvider();
- virtual boost::filesystem::path getHomeDir() const = 0;
- virtual boost::filesystem::path getDataDir() const = 0;
- boost::filesystem::path getExecutableDir() const;
- boost::filesystem::path getProfileDir(const std::string& profile) const;
- boost::filesystem::path getResourcePath(const std::string& resource) const;
+ virtual boost::filesystem::path getHomeDir() const = 0;
+ virtual boost::filesystem::path getDataDir() const = 0;
+ boost::filesystem::path getExecutableDir() const;
+ boost::filesystem::path getProfileDir(const std::string& profile) const;
+ boost::filesystem::path getResourcePath(const std::string& resource) const;
- protected:
- virtual std::vector<boost::filesystem::path> getResourceDirs() const = 0;
- const std::string& getApplicationName() const {
- return applicationName;
- }
+ protected:
+ virtual std::vector<boost::filesystem::path> getResourceDirs() const = 0;
+ const std::string& getApplicationName() const {
+ return applicationName;
+ }
- private:
- std::string applicationName;
- };
+ private:
+ std::string applicationName;
+ };
}
diff --git a/SwifTools/Application/CocoaApplication.h b/SwifTools/Application/CocoaApplication.h
index 2653aca..a3e281c 100644
--- a/SwifTools/Application/CocoaApplication.h
+++ b/SwifTools/Application/CocoaApplication.h
@@ -7,13 +7,13 @@
#pragma once
namespace Swift {
- class CocoaApplication {
- public:
- CocoaApplication();
- ~CocoaApplication();
+ class CocoaApplication {
+ public:
+ CocoaApplication();
+ ~CocoaApplication();
- private:
- class Private;
- Private* d;
- };
+ private:
+ class Private;
+ Private* d;
+ };
}
diff --git a/SwifTools/Application/CocoaApplication.mm b/SwifTools/Application/CocoaApplication.mm
index cbb5f2e..f879014 100644
--- a/SwifTools/Application/CocoaApplication.mm
+++ b/SwifTools/Application/CocoaApplication.mm
@@ -6,19 +6,19 @@
namespace Swift {
class CocoaApplication::Private {
- public:
- NSAutoreleasePool* autoReleasePool_;
+ public:
+ NSAutoreleasePool* autoReleasePool_;
};
CocoaApplication::CocoaApplication() {
- d = new CocoaApplication::Private();
- NSApplicationLoad();
- d->autoReleasePool_ = [[NSAutoreleasePool alloc] init];
+ d = new CocoaApplication::Private();
+ NSApplicationLoad();
+ d->autoReleasePool_ = [[NSAutoreleasePool alloc] init];
}
CocoaApplication::~CocoaApplication() {
- [d->autoReleasePool_ release];
- delete d;
+ [d->autoReleasePool_ release];
+ delete d;
}
}
diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.cpp b/SwifTools/Application/MacOSXApplicationPathProvider.cpp
index 2c35cbe..086bbaa 100644
--- a/SwifTools/Application/MacOSXApplicationPathProvider.cpp
+++ b/SwifTools/Application/MacOSXApplicationPathProvider.cpp
@@ -13,23 +13,23 @@
namespace Swift {
MacOSXApplicationPathProvider::MacOSXApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) {
- resourceDirs.push_back(getExecutableDir() / "../Resources");
- resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
+ resourceDirs.push_back(getExecutableDir() / "../Resources");
+ resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
}
boost::filesystem::path MacOSXApplicationPathProvider::getDataDir() const {
- boost::filesystem::path result(getHomeDir() / "Library/Application Support" / getApplicationName());
- try {
- boost::filesystem::create_directory(result);
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- return result;
+ boost::filesystem::path result(getHomeDir() / "Library/Application Support" / getApplicationName());
+ try {
+ boost::filesystem::create_directory(result);
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
+ return result;
}
boost::filesystem::path MacOSXApplicationPathProvider::getHomeDir() const {
- return boost::filesystem::path(getenv("HOME"));
+ return boost::filesystem::path(getenv("HOME"));
}
}
diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.h b/SwifTools/Application/MacOSXApplicationPathProvider.h
index 93797bc..9d8f619 100644
--- a/SwifTools/Application/MacOSXApplicationPathProvider.h
+++ b/SwifTools/Application/MacOSXApplicationPathProvider.h
@@ -9,18 +9,18 @@
#include <SwifTools/Application/ApplicationPathProvider.h>
namespace Swift {
- class MacOSXApplicationPathProvider : public ApplicationPathProvider {
- public:
- MacOSXApplicationPathProvider(const std::string& name);
+ class MacOSXApplicationPathProvider : public ApplicationPathProvider {
+ public:
+ MacOSXApplicationPathProvider(const std::string& name);
- virtual boost::filesystem::path getHomeDir() const;
- boost::filesystem::path getDataDir() const;
+ virtual boost::filesystem::path getHomeDir() const;
+ boost::filesystem::path getDataDir() const;
- virtual std::vector<boost::filesystem::path> getResourceDirs() const {
- return resourceDirs;
- }
+ virtual std::vector<boost::filesystem::path> getResourceDirs() const {
+ return resourceDirs;
+ }
- private:
- std::vector<boost::filesystem::path> resourceDirs;
- };
+ private:
+ std::vector<boost::filesystem::path> resourceDirs;
+ };
}
diff --git a/SwifTools/Application/PlatformApplicationPathProvider.h b/SwifTools/Application/PlatformApplicationPathProvider.h
index d9400a4..5de91fe 100644
--- a/SwifTools/Application/PlatformApplicationPathProvider.h
+++ b/SwifTools/Application/PlatformApplicationPathProvider.h
@@ -11,16 +11,16 @@
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <SwifTools/Application/MacOSXApplicationPathProvider.h>
namespace Swift {
- typedef MacOSXApplicationPathProvider PlatformApplicationPathProvider;
+ typedef MacOSXApplicationPathProvider PlatformApplicationPathProvider;
}
#elif defined(SWIFTEN_PLATFORM_WIN32)
#include <SwifTools/Application/WindowsApplicationPathProvider.h>
namespace Swift {
- typedef WindowsApplicationPathProvider PlatformApplicationPathProvider;
+ typedef WindowsApplicationPathProvider PlatformApplicationPathProvider;
}
#else
#include <SwifTools/Application/UnixApplicationPathProvider.h>
namespace Swift {
- typedef UnixApplicationPathProvider PlatformApplicationPathProvider;
+ typedef UnixApplicationPathProvider PlatformApplicationPathProvider;
}
#endif
diff --git a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
index df59505..433b379 100644
--- a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
+++ b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
@@ -18,37 +18,37 @@
using namespace Swift;
class ApplicationPathProviderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ApplicationPathProviderTest);
- CPPUNIT_TEST(testGetDataDir);
- CPPUNIT_TEST(testGetExecutableDir);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- testling_ = new PlatformApplicationPathProvider("SwiftTest");
- }
-
- void tearDown() {
- delete testling_;
- }
-
- void testGetDataDir() {
- boost::filesystem::path dir = testling_->getDataDir();
-
- CPPUNIT_ASSERT(boost::filesystem::exists(dir));
- CPPUNIT_ASSERT(boost::filesystem::is_directory(dir));
-
- boost::filesystem::remove(dir);
- }
-
- void testGetExecutableDir() {
- boost::filesystem::path dir = testling_->getExecutableDir();
- CPPUNIT_ASSERT(boost::filesystem::is_directory(dir));
- CPPUNIT_ASSERT(boost::ends_with(pathToString(dir), "UnitTest"));
- }
-
- private:
- ApplicationPathProvider* testling_;
+ CPPUNIT_TEST_SUITE(ApplicationPathProviderTest);
+ CPPUNIT_TEST(testGetDataDir);
+ CPPUNIT_TEST(testGetExecutableDir);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ testling_ = new PlatformApplicationPathProvider("SwiftTest");
+ }
+
+ void tearDown() {
+ delete testling_;
+ }
+
+ void testGetDataDir() {
+ boost::filesystem::path dir = testling_->getDataDir();
+
+ CPPUNIT_ASSERT(boost::filesystem::exists(dir));
+ CPPUNIT_ASSERT(boost::filesystem::is_directory(dir));
+
+ boost::filesystem::remove(dir);
+ }
+
+ void testGetExecutableDir() {
+ boost::filesystem::path dir = testling_->getExecutableDir();
+ CPPUNIT_ASSERT(boost::filesystem::is_directory(dir));
+ CPPUNIT_ASSERT(boost::ends_with(pathToString(dir), "UnitTest"));
+ }
+
+ private:
+ ApplicationPathProvider* testling_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ApplicationPathProviderTest);
diff --git a/SwifTools/Application/UnixApplicationPathProvider.cpp b/SwifTools/Application/UnixApplicationPathProvider.cpp
index 0708bb2..c561d72 100644
--- a/SwifTools/Application/UnixApplicationPathProvider.cpp
+++ b/SwifTools/Application/UnixApplicationPathProvider.cpp
@@ -20,45 +20,45 @@
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) {
- 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()));
+ 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) {
+ 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();
+ 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);
- }
+ 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());
+ 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;
- }
- return dataPath;
+ try {
+ boost::filesystem::create_directories(dataPath);
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
+ return dataPath;
}
}
diff --git a/SwifTools/Application/UnixApplicationPathProvider.h b/SwifTools/Application/UnixApplicationPathProvider.h
index 96f4955..9e27a93 100644
--- a/SwifTools/Application/UnixApplicationPathProvider.h
+++ b/SwifTools/Application/UnixApplicationPathProvider.h
@@ -9,19 +9,19 @@
#include <SwifTools/Application/ApplicationPathProvider.h>
namespace Swift {
- class UnixApplicationPathProvider : public ApplicationPathProvider {
- public:
- UnixApplicationPathProvider(const std::string& name);
+ class UnixApplicationPathProvider : public ApplicationPathProvider {
+ public:
+ UnixApplicationPathProvider(const std::string& name);
- virtual boost::filesystem::path getHomeDir() const;
- boost::filesystem::path getDataDir() const;
+ virtual boost::filesystem::path getHomeDir() const;
+ boost::filesystem::path getDataDir() const;
- virtual std::vector<boost::filesystem::path> getResourceDirs() const {
- return resourceDirs;
- }
+ virtual std::vector<boost::filesystem::path> getResourceDirs() const {
+ return resourceDirs;
+ }
- private:
- std::vector<boost::filesystem::path> resourceDirs;
- };
+ private:
+ std::vector<boost::filesystem::path> resourceDirs;
+ };
}
diff --git a/SwifTools/Application/WindowsApplicationPathProvider.cpp b/SwifTools/Application/WindowsApplicationPathProvider.cpp
index 0b0c9cf..e90214c 100644
--- a/SwifTools/Application/WindowsApplicationPathProvider.cpp
+++ b/SwifTools/Application/WindowsApplicationPathProvider.cpp
@@ -15,24 +15,24 @@
namespace Swift {
WindowsApplicationPathProvider::WindowsApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) {
- resourceDirs.push_back(getExecutableDir());
- resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
+ resourceDirs.push_back(getExecutableDir());
+ resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
}
boost::filesystem::path WindowsApplicationPathProvider::getDataDir() const {
- wchar_t* appDirRaw = _wgetenv(L"APPDATA");
- assert(appDirRaw);
- boost::filesystem::path result(
- boost::filesystem::path(appDirRaw) / getApplicationName());
- boost::filesystem::create_directory(result);
- return result;
+ wchar_t* appDirRaw = _wgetenv(L"APPDATA");
+ assert(appDirRaw);
+ boost::filesystem::path result(
+ boost::filesystem::path(appDirRaw) / getApplicationName());
+ boost::filesystem::create_directory(result);
+ return result;
}
boost::filesystem::path WindowsApplicationPathProvider::getHomeDir() const {
- //FIXME: This should be My Documents
- wchar_t* homeDirRaw = _wgetenv(L"USERPROFILE");
- assert(homeDirRaw);
- return boost::filesystem::path(homeDirRaw);
+ //FIXME: This should be My Documents
+ wchar_t* homeDirRaw = _wgetenv(L"USERPROFILE");
+ assert(homeDirRaw);
+ return boost::filesystem::path(homeDirRaw);
}
diff --git a/SwifTools/Application/WindowsApplicationPathProvider.h b/SwifTools/Application/WindowsApplicationPathProvider.h
index 6d0f5bd..bf8dada 100644
--- a/SwifTools/Application/WindowsApplicationPathProvider.h
+++ b/SwifTools/Application/WindowsApplicationPathProvider.h
@@ -9,18 +9,18 @@
#include <SwifTools/Application/ApplicationPathProvider.h>
namespace Swift {
- class WindowsApplicationPathProvider : public ApplicationPathProvider {
- public:
- WindowsApplicationPathProvider(const std::string& name);
+ class WindowsApplicationPathProvider : public ApplicationPathProvider {
+ public:
+ WindowsApplicationPathProvider(const std::string& name);
- boost::filesystem::path getDataDir() const;
- boost::filesystem::path getHomeDir() const;
+ boost::filesystem::path getDataDir() const;
+ boost::filesystem::path getHomeDir() const;
- virtual std::vector<boost::filesystem::path> getResourceDirs() const {
- return resourceDirs;
- }
+ virtual std::vector<boost::filesystem::path> getResourceDirs() const {
+ return resourceDirs;
+ }
- private:
- std::vector<boost::filesystem::path> resourceDirs;
- };
+ private:
+ std::vector<boost::filesystem::path> resourceDirs;
+ };
}
diff --git a/SwifTools/AutoUpdater/AutoUpdater.h b/SwifTools/AutoUpdater/AutoUpdater.h
index 12abc22..dec85c9 100644
--- a/SwifTools/AutoUpdater/AutoUpdater.h
+++ b/SwifTools/AutoUpdater/AutoUpdater.h
@@ -7,10 +7,10 @@
#pragma once
namespace Swift {
- class AutoUpdater {
- public:
- virtual ~AutoUpdater();
+ class AutoUpdater {
+ public:
+ virtual ~AutoUpdater();
- virtual void checkForUpdates() = 0;
- };
+ virtual void checkForUpdates() = 0;
+ };
}
diff --git a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
index 424c6e0..f693224 100644
--- a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
+++ b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
@@ -16,18 +16,18 @@ namespace Swift {
bool PlatformAutoUpdaterFactory::isSupported() const {
#ifdef HAVE_SPARKLE
- return true;
+ return true;
#else
- return false;
+ return false;
#endif
}
AutoUpdater* PlatformAutoUpdaterFactory::createAutoUpdater(const std::string& appcastURL) {
#ifdef HAVE_SPARKLE
- return new SparkleAutoUpdater(appcastURL);
+ return new SparkleAutoUpdater(appcastURL);
#else
- (void) appcastURL;
- return NULL;
+ (void) appcastURL;
+ return NULL;
#endif
}
diff --git a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h
index 24a2f21..9942d6a 100644
--- a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h
+++ b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h
@@ -7,12 +7,12 @@
#include <string>
namespace Swift {
- class AutoUpdater;
+ class AutoUpdater;
- class PlatformAutoUpdaterFactory {
- public:
- bool isSupported() const;
+ class PlatformAutoUpdaterFactory {
+ public:
+ bool isSupported() const;
- AutoUpdater* createAutoUpdater(const std::string& appcastURL);
- };
+ AutoUpdater* createAutoUpdater(const std::string& appcastURL);
+ };
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.h b/SwifTools/AutoUpdater/SparkleAutoUpdater.h
index 351d075..95ca35e 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdater.h
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.h
@@ -11,15 +11,15 @@
#include <SwifTools/AutoUpdater/AutoUpdater.h>
namespace Swift {
- class SparkleAutoUpdater : public AutoUpdater {
- public:
- SparkleAutoUpdater(const std::string& url);
- ~SparkleAutoUpdater();
+ class SparkleAutoUpdater : public AutoUpdater {
+ public:
+ SparkleAutoUpdater(const std::string& url);
+ ~SparkleAutoUpdater();
- void checkForUpdates();
-
- private:
- class Private;
- Private* d;
- };
+ void checkForUpdates();
+
+ private:
+ class Private;
+ Private* d;
+ };
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
index c35abc8..bcd1388 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
@@ -6,29 +6,29 @@
namespace Swift {
class SparkleAutoUpdater::Private {
- public:
- SUUpdater* updater;
+ public:
+ SUUpdater* updater;
};
SparkleAutoUpdater::SparkleAutoUpdater(const std::string& url) {
- d = new Private;
+ d = new Private;
- d->updater = [SUUpdater sharedUpdater];
- [d->updater retain];
- [d->updater setAutomaticallyChecksForUpdates: true];
+ d->updater = [SUUpdater sharedUpdater];
+ [d->updater retain];
+ [d->updater setAutomaticallyChecksForUpdates: true];
- NSURL* nsurl = [NSURL URLWithString:
- [NSString stringWithUTF8String: url.c_str()]];
- [d->updater setFeedURL: nsurl];
+ NSURL* nsurl = [NSURL URLWithString:
+ [NSString stringWithUTF8String: url.c_str()]];
+ [d->updater setFeedURL: nsurl];
}
SparkleAutoUpdater::~SparkleAutoUpdater() {
- [d->updater release];
- delete d;
+ [d->updater release];
+ delete d;
}
void SparkleAutoUpdater::checkForUpdates() {
- [d->updater checkForUpdatesInBackground];
+ [d->updater checkForUpdatesInBackground];
}
}
diff --git a/SwifTools/Cocoa/CocoaAction.mm b/SwifTools/Cocoa/CocoaAction.mm
index 6daba2e..341da2c 100644
--- a/SwifTools/Cocoa/CocoaAction.mm
+++ b/SwifTools/Cocoa/CocoaAction.mm
@@ -7,24 +7,24 @@
#include <SwifTools/Cocoa/CocoaAction.h>
@implementation CocoaAction {
- boost::function<void ()>* function;
+ boost::function<void ()>* function;
}
- (id) initWithFunction: (boost::function<void()>*) f {
- if ((self = [super init])) {
- function = f;
- }
- return self;
+ if ((self = [super init])) {
+ function = f;
+ }
+ return self;
}
- (void) dealloc {
- delete function;
- [super dealloc];
+ delete function;
+ [super dealloc];
}
- (void) doAction: (id) sender {
- (void) sender;
- (*function)();
+ (void) sender;
+ (*function)();
}
@end
diff --git a/SwifTools/Cocoa/CocoaUtil.h b/SwifTools/Cocoa/CocoaUtil.h
index 83d95b6..8c4dd64 100644
--- a/SwifTools/Cocoa/CocoaUtil.h
+++ b/SwifTools/Cocoa/CocoaUtil.h
@@ -11,37 +11,37 @@ namespace {
inline std::string ns2StdString(NSString* _Nullable nsString);
inline std::string ns2StdString(NSString* _Nullable nsString) {
- std::string stdString;
- if (nsString != nil) {
- stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]);
- }
- return stdString;
+ std::string stdString;
+ if (nsString != nil) {
+ stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]);
+ }
+ return stdString;
}
inline NSString* _Nonnull std2NSString(const std::string& stdString);
inline NSString* _Nonnull std2NSString(const std::string& stdString) {
- NSString* _Nullable nsString = [NSString stringWithUTF8String:stdString.c_str()];
- if (nsString == nil) {
- nsString = @"";
- }
- // At this point nsString is guaranteed to be not null/nil.
- return static_cast<NSString* _Nonnull>(nsString);
+ NSString* _Nullable nsString = [NSString stringWithUTF8String:stdString.c_str()];
+ if (nsString == nil) {
+ nsString = @"";
+ }
+ // At this point nsString is guaranteed to be not null/nil.
+ return static_cast<NSString* _Nonnull>(nsString);
}
}
// Intrusive pointer for NSObjects
-namespace boost {
- inline void intrusive_ptr_add_ref(NSObject* _Nonnull object) {
- [object retain];
- }
-
- inline void intrusive_ptr_release(NSObject* _Nonnull object) {
- [object release];
- }
+namespace boost {
+ inline void intrusive_ptr_add_ref(NSObject* _Nonnull object) {
+ [object retain];
+ }
+
+ inline void intrusive_ptr_release(NSObject* _Nonnull object) {
+ [object release];
+ }
}
-// Including intrusive_ptr after ref/release methods to avoid compilation
+// Including intrusive_ptr after ref/release methods to avoid compilation
// errors with CLang
#include <boost/intrusive_ptr.hpp>
diff --git a/SwifTools/CrashReporter.cpp b/SwifTools/CrashReporter.cpp
index 35db605..b401e76 100644
--- a/SwifTools/CrashReporter.cpp
+++ b/SwifTools/CrashReporter.cpp
@@ -24,46 +24,46 @@
#if defined(SWIFTEN_PLATFORM_WINDOWS)
static bool handleDump(const wchar_t* /* dir */, const wchar_t* /* id*/, void* /* context */, EXCEPTION_POINTERS*, MDRawAssertionInfo*, bool /* succeeded */) {
- return false;
+ return false;
}
#else
static bool handleDump(const char* /* dir */, const char* /* id*/, void* /* context */, bool /* succeeded */) {
- return false;
+ return false;
}
#endif
namespace Swift {
struct CrashReporter::Private {
- boost::shared_ptr<google_breakpad::ExceptionHandler> handler;
+ boost::shared_ptr<google_breakpad::ExceptionHandler> handler;
};
CrashReporter::CrashReporter(const boost::filesystem::path& path) {
- // Create the path that will contain the crash dumps
- if (!boost::filesystem::exists(path)) {
- try {
- boost::filesystem::create_directories(path);
- }
- catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "ERROR: " << e.what() << std::endl;
- }
- }
+ // Create the path that will contain the crash dumps
+ if (!boost::filesystem::exists(path)) {
+ try {
+ boost::filesystem::create_directories(path);
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ SWIFT_LOG(error) << "ERROR: " << e.what() << std::endl;
+ }
+ }
- p = boost::make_shared<Private>();
+ p = boost::make_shared<Private>();
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- // FIXME: Need UTF8 conversion from string to wstring
- std::string pathString = pathToString(path);
- p->handler = boost::shared_ptr<google_breakpad::ExceptionHandler>(
- // Not using make_shared, because 'handleDump' seems to have problems with VC2010
- new google_breakpad::ExceptionHandler(
- std::wstring(pathString.begin(), pathString.end()),
- (google_breakpad::ExceptionHandler::FilterCallback) 0,
- handleDump,
- (void*) 0,
- google_breakpad::ExceptionHandler::HANDLER_ALL));
+ // FIXME: Need UTF8 conversion from string to wstring
+ std::string pathString = pathToString(path);
+ p->handler = boost::shared_ptr<google_breakpad::ExceptionHandler>(
+ // Not using make_shared, because 'handleDump' seems to have problems with VC2010
+ new google_breakpad::ExceptionHandler(
+ std::wstring(pathString.begin(), pathString.end()),
+ (google_breakpad::ExceptionHandler::FilterCallback) 0,
+ handleDump,
+ (void*) 0,
+ google_breakpad::ExceptionHandler::HANDLER_ALL));
// Turning it off for Mac, because it doesn't really help us
//#elif defined(SWIFTEN_PLATFORM_MACOSX)
-// p->handler = boost::make_shared<google_breakpad::ExceptionHandler>(pathToString(path), (google_breakpad::ExceptionHandler::FilterCallback) 0, handleDump, (void*) 0, true, (const char*) 0);
+// p->handler = boost::make_shared<google_breakpad::ExceptionHandler>(pathToString(path), (google_breakpad::ExceptionHandler::FilterCallback) 0, handleDump, (void*) 0, true, (const char*) 0);
#endif
}
@@ -73,7 +73,7 @@ CrashReporter::CrashReporter(const boost::filesystem::path& path) {
// Dummy implementation
namespace Swift {
- CrashReporter::CrashReporter(const boost::filesystem::path&) {}
+ CrashReporter::CrashReporter(const boost::filesystem::path&) {}
}
#endif
diff --git a/SwifTools/CrashReporter.h b/SwifTools/CrashReporter.h
index cce6c43..ee71223 100644
--- a/SwifTools/CrashReporter.h
+++ b/SwifTools/CrashReporter.h
@@ -12,12 +12,12 @@
#include <boost/shared_ptr.hpp>
namespace Swift {
- class CrashReporter {
- public:
- CrashReporter(const boost::filesystem::path& path);
+ class CrashReporter {
+ public:
+ CrashReporter(const boost::filesystem::path& path);
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/SwifTools/Dock/Dock.h b/SwifTools/Dock/Dock.h
index cf7ee5f..6120445 100644
--- a/SwifTools/Dock/Dock.h
+++ b/SwifTools/Dock/Dock.h
@@ -7,12 +7,12 @@
#pragma once
namespace Swift {
-
- class Dock {
- public:
- virtual ~Dock();
- virtual void setNumberOfPendingMessages(int i) = 0;
- };
+ class Dock {
+ public:
+ virtual ~Dock();
+
+ virtual void setNumberOfPendingMessages(int i) = 0;
+ };
}
diff --git a/SwifTools/Dock/MacOSXDock.h b/SwifTools/Dock/MacOSXDock.h
index 60347fb..6b33506 100644
--- a/SwifTools/Dock/MacOSXDock.h
+++ b/SwifTools/Dock/MacOSXDock.h
@@ -9,13 +9,13 @@
#include <SwifTools/Dock/Dock.h>
namespace Swift {
-
- class CocoaApplication;
- class MacOSXDock : public Dock {
- public:
- MacOSXDock(CocoaApplication* application);
+ class CocoaApplication;
- virtual void setNumberOfPendingMessages(int i);
- };
+ class MacOSXDock : public Dock {
+ public:
+ MacOSXDock(CocoaApplication* application);
+
+ virtual void setNumberOfPendingMessages(int i);
+ };
}
diff --git a/SwifTools/Dock/MacOSXDock.mm b/SwifTools/Dock/MacOSXDock.mm
index f231e9a..5c7207c 100644
--- a/SwifTools/Dock/MacOSXDock.mm
+++ b/SwifTools/Dock/MacOSXDock.mm
@@ -19,11 +19,11 @@ MacOSXDock::MacOSXDock(CocoaApplication*) {
}
void MacOSXDock::setNumberOfPendingMessages(int i) {
- std::string label(i > 0 ? boost::lexical_cast<std::string>(i) : "");
- NSString *labelString = [[NSString alloc] initWithUTF8String: label.c_str()];
- [[NSApp dockTile] setBadgeLabel: labelString];
- [labelString release];
- [NSApp requestUserAttention: NSInformationalRequest];
+ std::string label(i > 0 ? boost::lexical_cast<std::string>(i) : "");
+ NSString *labelString = [[NSString alloc] initWithUTF8String: label.c_str()];
+ [[NSApp dockTile] setBadgeLabel: labelString];
+ [labelString release];
+ [NSApp requestUserAttention: NSInformationalRequest];
}
}
diff --git a/SwifTools/Dock/NullDock.h b/SwifTools/Dock/NullDock.h
index e4433f6..9f3c554 100644
--- a/SwifTools/Dock/NullDock.h
+++ b/SwifTools/Dock/NullDock.h
@@ -9,11 +9,11 @@
#include <SwifTools/Dock/Dock.h>
namespace Swift {
- class NullDock : public Dock {
- public:
- NullDock() {}
+ class NullDock : public Dock {
+ public:
+ NullDock() {}
- virtual void setNumberOfPendingMessages(int) {
- }
- };
+ virtual void setNumberOfPendingMessages(int) {
+ }
+ };
}
diff --git a/SwifTools/Dock/WindowsDock.h b/SwifTools/Dock/WindowsDock.h
index 07b0eff..fc10a48 100644
--- a/SwifTools/Dock/WindowsDock.h
+++ b/SwifTools/Dock/WindowsDock.h
@@ -14,30 +14,30 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class WindowsDock : public Dock {
- public:
- WindowsDock(QSystemTrayIcon* tray, Notifier* notifier) : tray(tray), notifier(notifier) {}
-
- virtual void setNumberOfPendingMessages(int i) {
- if (notifier->isAvailable()) {
- return;
- }
-
- if (i > 0) {
- std::string message = boost::lexical_cast<std::string>(i) + " new message";
- if (i > 1) {
- message += "s";
- }
- message += " received.";
- tray->showMessage("New messages", message.c_str(), QSystemTrayIcon::NoIcon);
- }
- else {
- tray->showMessage("", "", QSystemTrayIcon::NoIcon, 0);
- }
- }
-
- private:
- QSystemTrayIcon* tray;
- Notifier* notifier;
- };
+ class WindowsDock : public Dock {
+ public:
+ WindowsDock(QSystemTrayIcon* tray, Notifier* notifier) : tray(tray), notifier(notifier) {}
+
+ virtual void setNumberOfPendingMessages(int i) {
+ if (notifier->isAvailable()) {
+ return;
+ }
+
+ if (i > 0) {
+ std::string message = boost::lexical_cast<std::string>(i) + " new message";
+ if (i > 1) {
+ message += "s";
+ }
+ message += " received.";
+ tray->showMessage("New messages", message.c_str(), QSystemTrayIcon::NoIcon);
+ }
+ else {
+ tray->showMessage("", "", QSystemTrayIcon::NoIcon, 0);
+ }
+ }
+
+ private:
+ QSystemTrayIcon* tray;
+ Notifier* notifier;
+ };
}
diff --git a/SwifTools/HunspellChecker.cpp b/SwifTools/HunspellChecker.cpp
index 2fe7a21..fb1a5d6 100644
--- a/SwifTools/HunspellChecker.cpp
+++ b/SwifTools/HunspellChecker.cpp
@@ -21,44 +21,44 @@
namespace Swift {
HunspellChecker::HunspellChecker(const char* affix_path, const char* dictionary_path) {
- speller_ = new Hunspell(affix_path, dictionary_path);
+ speller_ = new Hunspell(affix_path, dictionary_path);
}
HunspellChecker::~HunspellChecker() {
- delete speller_;
+ delete speller_;
}
bool HunspellChecker::isCorrect(const std::string& word) {
- return speller_->spell(word.c_str());
+ return speller_->spell(word.c_str());
}
void HunspellChecker::getSuggestions(const std::string& word, std::vector<std::string>& list) {
- char **suggestList = NULL;
- int words_returned = 0;
- if (!word.empty()) {
- words_returned = speller_->suggest(&suggestList, word.c_str());
- if (suggestList != NULL) {
- for (int i = 0; i < words_returned; ++i) {
- list.push_back(suggestList[i]);
- free(suggestList[i]);
- }
- free(suggestList);
- }
- }
+ char **suggestList = NULL;
+ int words_returned = 0;
+ if (!word.empty()) {
+ words_returned = speller_->suggest(&suggestList, word.c_str());
+ if (suggestList != NULL) {
+ for (int i = 0; i < words_returned; ++i) {
+ list.push_back(suggestList[i]);
+ free(suggestList[i]);
+ }
+ free(suggestList);
+ }
+ }
}
void HunspellChecker::checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) {
- if (!fragment.empty()) {
- parser_->check(fragment, misspelledPositions);
- for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end();) {
- if (isCorrect(fragment.substr(boost::get<0>(*it), boost::get<1>(*it) - boost::get<0>(*it)))) {
- it = misspelledPositions.erase(it);
- }
- else {
- ++it;
- }
- }
- }
+ if (!fragment.empty()) {
+ parser_->check(fragment, misspelledPositions);
+ for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end();) {
+ if (isCorrect(fragment.substr(boost::get<0>(*it), boost::get<1>(*it) - boost::get<0>(*it)))) {
+ it = misspelledPositions.erase(it);
+ }
+ else {
+ ++it;
+ }
+ }
+ }
}
}
diff --git a/SwifTools/HunspellChecker.h b/SwifTools/HunspellChecker.h
index 689e0e7..076b468 100644
--- a/SwifTools/HunspellChecker.h
+++ b/SwifTools/HunspellChecker.h
@@ -22,14 +22,14 @@
class Hunspell;
namespace Swift {
- class HunspellChecker : public SpellChecker {
- public:
- HunspellChecker(const char* affix_path, const char* dict_path);
- virtual ~HunspellChecker();
- virtual bool isCorrect(const std::string& word);
- virtual void getSuggestions(const std::string& word, std::vector<std::string>& list);
- virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions);
- private:
- Hunspell* speller_;
- };
+ class HunspellChecker : public SpellChecker {
+ public:
+ HunspellChecker(const char* affix_path, const char* dict_path);
+ virtual ~HunspellChecker();
+ virtual bool isCorrect(const std::string& word);
+ virtual void getSuggestions(const std::string& word, std::vector<std::string>& list);
+ virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions);
+ private:
+ Hunspell* speller_;
+ };
}
diff --git a/SwifTools/Idle/ActualIdleDetector.cpp b/SwifTools/Idle/ActualIdleDetector.cpp
index dac4a5e..2a16fca 100644
--- a/SwifTools/Idle/ActualIdleDetector.cpp
+++ b/SwifTools/Idle/ActualIdleDetector.cpp
@@ -16,20 +16,20 @@
namespace Swift {
ActualIdleDetector::ActualIdleDetector(IdleQuerier* querier, TimerFactory* timerFactory, int refreshRateMilliseconds) : querier(querier) {
- timer = timerFactory->createTimer(refreshRateMilliseconds);
- timer->onTick.connect(boost::bind(&ActualIdleDetector::handleTimerTick, this));
- timer->start();
+ timer = timerFactory->createTimer(refreshRateMilliseconds);
+ timer->onTick.connect(boost::bind(&ActualIdleDetector::handleTimerTick, this));
+ timer->start();
}
ActualIdleDetector::~ActualIdleDetector() {
- timer->onTick.disconnect(boost::bind(&ActualIdleDetector::handleTimerTick, this));
- timer->stop();
+ timer->onTick.disconnect(boost::bind(&ActualIdleDetector::handleTimerTick, this));
+ timer->stop();
}
void ActualIdleDetector::handleTimerTick() {
- timer->stop();
- setIdle(querier->getIdleTimeSeconds() >= getIdleTimeSeconds());
- timer->start();
+ timer->stop();
+ setIdle(querier->getIdleTimeSeconds() >= getIdleTimeSeconds());
+ timer->start();
}
}
diff --git a/SwifTools/Idle/ActualIdleDetector.h b/SwifTools/Idle/ActualIdleDetector.h
index 739a005..194606f 100644
--- a/SwifTools/Idle/ActualIdleDetector.h
+++ b/SwifTools/Idle/ActualIdleDetector.h
@@ -11,20 +11,20 @@
#include <SwifTools/Idle/IdleDetector.h>
namespace Swift {
- class IdleQuerier;
- class TimerFactory;
- class Timer;
+ class IdleQuerier;
+ class TimerFactory;
+ class Timer;
- class ActualIdleDetector : public IdleDetector, public boost::bsignals::trackable {
- public:
- ActualIdleDetector(IdleQuerier*, TimerFactory*, int refreshRateMilliseconds);
- ~ActualIdleDetector();
+ class ActualIdleDetector : public IdleDetector, public boost::bsignals::trackable {
+ public:
+ ActualIdleDetector(IdleQuerier*, TimerFactory*, int refreshRateMilliseconds);
+ ~ActualIdleDetector();
- private:
- void handleTimerTick();
+ private:
+ void handleTimerTick();
- private:
- IdleQuerier* querier;
- boost::shared_ptr<Timer> timer;
- };
+ private:
+ IdleQuerier* querier;
+ boost::shared_ptr<Timer> timer;
+ };
}
diff --git a/SwifTools/Idle/DummyIdleQuerier.h b/SwifTools/Idle/DummyIdleQuerier.h
index 068d9ad..d3f5177 100644
--- a/SwifTools/Idle/DummyIdleQuerier.h
+++ b/SwifTools/Idle/DummyIdleQuerier.h
@@ -9,12 +9,12 @@
#include <SwifTools/Idle/IdleQuerier.h>
namespace Swift {
- class DummyIdleQuerier : public IdleQuerier {
- public:
- DummyIdleQuerier() {}
+ class DummyIdleQuerier : public IdleQuerier {
+ public:
+ DummyIdleQuerier() {}
- virtual int getIdleTimeSeconds() {
- return 0;
- }
- };
+ virtual int getIdleTimeSeconds() {
+ return 0;
+ }
+ };
}
diff --git a/SwifTools/Idle/IdleDetector.h b/SwifTools/Idle/IdleDetector.h
index 7819f54..88a1c4c 100644
--- a/SwifTools/Idle/IdleDetector.h
+++ b/SwifTools/Idle/IdleDetector.h
@@ -11,34 +11,34 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class IdleDetector {
- public:
- IdleDetector() : idle(false), idleTimeSeconds(300) {}
- virtual ~IdleDetector();
-
- void setIdleTimeSeconds(int time) {
- idleTimeSeconds = time;
- }
-
- int getIdleTimeSeconds() const {
- return idleTimeSeconds;
- }
-
- virtual bool isIdle() const {
- return idle;
- }
-
- boost::signal<void (bool /* isIdle */)> onIdleChanged;
-
- void setIdle(bool b) {
- if (b != idle) {
- idle = b;
- onIdleChanged(b);
- }
- }
-
- private:
- bool idle;
- int idleTimeSeconds;
- };
+ class IdleDetector {
+ public:
+ IdleDetector() : idle(false), idleTimeSeconds(300) {}
+ virtual ~IdleDetector();
+
+ void setIdleTimeSeconds(int time) {
+ idleTimeSeconds = time;
+ }
+
+ int getIdleTimeSeconds() const {
+ return idleTimeSeconds;
+ }
+
+ virtual bool isIdle() const {
+ return idle;
+ }
+
+ boost::signal<void (bool /* isIdle */)> onIdleChanged;
+
+ void setIdle(bool b) {
+ if (b != idle) {
+ idle = b;
+ onIdleChanged(b);
+ }
+ }
+
+ private:
+ bool idle;
+ int idleTimeSeconds;
+ };
}
diff --git a/SwifTools/Idle/IdleQuerier.h b/SwifTools/Idle/IdleQuerier.h
index ba4879d..e0de8be 100644
--- a/SwifTools/Idle/IdleQuerier.h
+++ b/SwifTools/Idle/IdleQuerier.h
@@ -7,10 +7,10 @@
#pragma once
namespace Swift {
- class IdleQuerier {
- public:
- virtual ~IdleQuerier();
+ class IdleQuerier {
+ public:
+ virtual ~IdleQuerier();
- virtual int getIdleTimeSeconds() = 0;
- };
+ virtual int getIdleTimeSeconds() = 0;
+ };
}
diff --git a/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp b/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp
index 365ed1a..a0b78e6 100644
--- a/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp
+++ b/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp
@@ -14,11 +14,11 @@
using namespace Swift;
int main() {
- PlatformIdleQuerier querier;
- while (true) {
- std::cout << "Idle time: " << querier.getIdleTimeSeconds() << std::endl;
- Swift::sleep(1000);
- }
- assert(false);
- return 0;
+ PlatformIdleQuerier querier;
+ while (true) {
+ std::cout << "Idle time: " << querier.getIdleTimeSeconds() << std::endl;
+ Swift::sleep(1000);
+ }
+ assert(false);
+ return 0;
}
diff --git a/SwifTools/Idle/MacOSXIdleQuerier.cpp b/SwifTools/Idle/MacOSXIdleQuerier.cpp
index f7d4199..6d6780b 100644
--- a/SwifTools/Idle/MacOSXIdleQuerier.cpp
+++ b/SwifTools/Idle/MacOSXIdleQuerier.cpp
@@ -16,20 +16,20 @@
namespace Swift {
MacOSXIdleQuerier::MacOSXIdleQuerier() : ioService(0) {
- mach_port_t masterPort;
- IOMasterPort(MACH_PORT_NULL, &masterPort);
- ioService = IOServiceGetMatchingService(masterPort, IOServiceMatching("IOHIDSystem"));
- assert(ioService);
+ mach_port_t masterPort;
+ IOMasterPort(MACH_PORT_NULL, &masterPort);
+ ioService = IOServiceGetMatchingService(masterPort, IOServiceMatching("IOHIDSystem"));
+ assert(ioService);
}
int MacOSXIdleQuerier::getIdleTimeSeconds() {
- CFTypeRef property = IORegistryEntryCreateCFProperty(ioService, CFSTR("HIDIdleTime"), kCFAllocatorDefault, 0);
- uint64_t idle = 0;
- bool result = CFNumberGetValue((CFNumberRef)property, kCFNumberSInt64Type, &idle);
- assert(result);
- (void) result;
- CFRelease(property);
- return boost::numeric_cast<int>(idle / 1000000000);
+ CFTypeRef property = IORegistryEntryCreateCFProperty(ioService, CFSTR("HIDIdleTime"), kCFAllocatorDefault, 0);
+ uint64_t idle = 0;
+ bool result = CFNumberGetValue((CFNumberRef)property, kCFNumberSInt64Type, &idle);
+ assert(result);
+ (void) result;
+ CFRelease(property);
+ return boost::numeric_cast<int>(idle / 1000000000);
}
}
diff --git a/SwifTools/Idle/MacOSXIdleQuerier.h b/SwifTools/Idle/MacOSXIdleQuerier.h
index 7f70e88..8ff747c 100644
--- a/SwifTools/Idle/MacOSXIdleQuerier.h
+++ b/SwifTools/Idle/MacOSXIdleQuerier.h
@@ -11,13 +11,13 @@
#include <SwifTools/Idle/IdleQuerier.h>
namespace Swift {
- class MacOSXIdleQuerier : public IdleQuerier {
- public:
- MacOSXIdleQuerier();
+ class MacOSXIdleQuerier : public IdleQuerier {
+ public:
+ MacOSXIdleQuerier();
- virtual int getIdleTimeSeconds();
+ virtual int getIdleTimeSeconds();
- private:
- io_service_t ioService;
- };
+ private:
+ io_service_t ioService;
+ };
}
diff --git a/SwifTools/Idle/PlatformIdleQuerier.cpp b/SwifTools/Idle/PlatformIdleQuerier.cpp
index bf8f778..5855749 100644
--- a/SwifTools/Idle/PlatformIdleQuerier.cpp
+++ b/SwifTools/Idle/PlatformIdleQuerier.cpp
@@ -24,21 +24,21 @@ namespace Swift {
PlatformIdleQuerier::PlatformIdleQuerier() : querier(NULL) {
#if defined(SWIFTEN_PLATFORM_MACOSX)
#if defined(HAVE_IOKIT) && !defined(SWIFTEN_PLATFORM_IPHONE)
- querier = new MacOSXIdleQuerier();
+ querier = new MacOSXIdleQuerier();
#else
- querier = new DummyIdleQuerier();
+ querier = new DummyIdleQuerier();
#endif
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- querier = new WindowsIdleQuerier();
+ querier = new WindowsIdleQuerier();
#elif defined(HAVE_XSS)
- querier = new XSSIdleQuerier();
+ querier = new XSSIdleQuerier();
#else
- querier = new DummyIdleQuerier();
+ querier = new DummyIdleQuerier();
#endif
}
PlatformIdleQuerier::~PlatformIdleQuerier() {
- delete querier;
+ delete querier;
}
}
diff --git a/SwifTools/Idle/PlatformIdleQuerier.h b/SwifTools/Idle/PlatformIdleQuerier.h
index 676dad0..1221ada 100644
--- a/SwifTools/Idle/PlatformIdleQuerier.h
+++ b/SwifTools/Idle/PlatformIdleQuerier.h
@@ -9,16 +9,16 @@
#include <SwifTools/Idle/IdleQuerier.h>
namespace Swift {
- class PlatformIdleQuerier : public IdleQuerier {
- public:
- PlatformIdleQuerier();
- ~PlatformIdleQuerier();
+ class PlatformIdleQuerier : public IdleQuerier {
+ public:
+ PlatformIdleQuerier();
+ ~PlatformIdleQuerier();
- virtual int getIdleTimeSeconds() {
- return querier->getIdleTimeSeconds();
- }
+ virtual int getIdleTimeSeconds() {
+ return querier->getIdleTimeSeconds();
+ }
- private:
- IdleQuerier* querier;
- };
+ private:
+ IdleQuerier* querier;
+ };
}
diff --git a/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp b/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp
index c97705e..8af66fc 100644
--- a/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp
+++ b/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp
@@ -19,154 +19,154 @@
using namespace Swift;
class ActualIdleDetectorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ActualIdleDetectorTest);
- CPPUNIT_TEST(testDestructor);
- CPPUNIT_TEST(testHandleTick_Idle);
- CPPUNIT_TEST(testHandleTick_Idle_AlreadyIdle);
- CPPUNIT_TEST(testHandleTick_NotIdle);
- CPPUNIT_TEST(testHandleTick_NotIdle_AlreadyNotIdle);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- querier = new MockIdleQuerier();
- timerFactory = new MockTimerFactory();
- idleEvents.clear();
- }
-
- void tearDown() {
- delete timerFactory;
- delete querier;
- }
-
- void testDestructor() {
- ActualIdleDetector* testling = createDetector();
- testling->setIdleTimeSeconds(15);
- delete testling;
-
- querier->idleTime = 15;
- timerFactory->updateTime(15000);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(idleEvents.size()));
- }
-
- void testHandleTick_Idle() {
- std::auto_ptr<ActualIdleDetector> testling(createDetector());
- testling->setIdleTimeSeconds(15);
- querier->idleTime = 15;
-
- timerFactory->updateTime(15000);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(idleEvents.size()));
- CPPUNIT_ASSERT(idleEvents[0]);
- }
-
- void testHandleTick_Idle_AlreadyIdle() {
- std::auto_ptr<ActualIdleDetector> testling(createDetector());
- testling->setIdleTimeSeconds(15);
- querier->idleTime = 15;
- timerFactory->updateTime(15000);
-
- querier->idleTime = 30;
- timerFactory->updateTime(30000);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(idleEvents.size()));
- CPPUNIT_ASSERT(idleEvents[0]);
- }
-
- void testHandleTick_NotIdle() {
- std::auto_ptr<ActualIdleDetector> testling(createDetector());
- testling->setIdleTimeSeconds(15);
- querier->idleTime = 15;
- timerFactory->updateTime(15000);
-
- querier->idleTime = 5;
- timerFactory->updateTime(30000);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(idleEvents.size()));
- CPPUNIT_ASSERT(idleEvents[0]);
- CPPUNIT_ASSERT(!idleEvents[1]);
- }
-
- void testHandleTick_NotIdle_AlreadyNotIdle() {
- std::auto_ptr<ActualIdleDetector> testling(createDetector());
- testling->setIdleTimeSeconds(15);
- querier->idleTime = 5;
-
- timerFactory->updateTime(15000);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(idleEvents.size()));
- }
-
- private:
- ActualIdleDetector* createDetector() {
- ActualIdleDetector* detector = new ActualIdleDetector(querier, timerFactory, 10);
- detector->onIdleChanged.connect(boost::bind(&ActualIdleDetectorTest::handleIdle, this, _1));
- return detector;
- }
-
- void handleIdle(bool b) {
- idleEvents.push_back(b);
- }
-
- private:
- struct MockIdleQuerier : public IdleQuerier {
- MockIdleQuerier() : idleTime(0) {}
- virtual int getIdleTimeSeconds() { return idleTime; }
- int idleTime;
- };
-
- struct MockTimer : public Timer {
- MockTimer(int interval) : interval(interval), running(false), lastTime(0) {}
-
- virtual void start() {
- running = true;
- }
-
- virtual void stop() {
- running = false;
- }
-
- virtual void updateTime(int currentTime) {
- if (lastTime == currentTime) {
- return;
- }
- if (running) {
- int time = lastTime;
- while (time <= currentTime) {
- onTick();
- time += interval;
- }
- }
- lastTime = currentTime;
- }
-
- int interval;
- bool running;
- int lastTime;
- };
-
- struct MockTimerFactory : public TimerFactory {
- MockTimerFactory() {}
-
- void updateTime(int milliseconds) {
- foreach(boost::shared_ptr<MockTimer> timer, timers) {
- timer->updateTime(milliseconds);
- }
- }
-
- boost::shared_ptr<Timer> createTimer(int milliseconds) {
- boost::shared_ptr<MockTimer> timer(new MockTimer(milliseconds));
- timers.push_back(timer);
- return timer;
- }
-
- std::vector<boost::shared_ptr<MockTimer> > timers;
- };
-
- MockIdleQuerier* querier;
- MockTimerFactory* timerFactory;
- std::vector<bool> idleEvents;
+ CPPUNIT_TEST_SUITE(ActualIdleDetectorTest);
+ CPPUNIT_TEST(testDestructor);
+ CPPUNIT_TEST(testHandleTick_Idle);
+ CPPUNIT_TEST(testHandleTick_Idle_AlreadyIdle);
+ CPPUNIT_TEST(testHandleTick_NotIdle);
+ CPPUNIT_TEST(testHandleTick_NotIdle_AlreadyNotIdle);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ querier = new MockIdleQuerier();
+ timerFactory = new MockTimerFactory();
+ idleEvents.clear();
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete querier;
+ }
+
+ void testDestructor() {
+ ActualIdleDetector* testling = createDetector();
+ testling->setIdleTimeSeconds(15);
+ delete testling;
+
+ querier->idleTime = 15;
+ timerFactory->updateTime(15000);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(idleEvents.size()));
+ }
+
+ void testHandleTick_Idle() {
+ std::auto_ptr<ActualIdleDetector> testling(createDetector());
+ testling->setIdleTimeSeconds(15);
+ querier->idleTime = 15;
+
+ timerFactory->updateTime(15000);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(idleEvents.size()));
+ CPPUNIT_ASSERT(idleEvents[0]);
+ }
+
+ void testHandleTick_Idle_AlreadyIdle() {
+ std::auto_ptr<ActualIdleDetector> testling(createDetector());
+ testling->setIdleTimeSeconds(15);
+ querier->idleTime = 15;
+ timerFactory->updateTime(15000);
+
+ querier->idleTime = 30;
+ timerFactory->updateTime(30000);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(idleEvents.size()));
+ CPPUNIT_ASSERT(idleEvents[0]);
+ }
+
+ void testHandleTick_NotIdle() {
+ std::auto_ptr<ActualIdleDetector> testling(createDetector());
+ testling->setIdleTimeSeconds(15);
+ querier->idleTime = 15;
+ timerFactory->updateTime(15000);
+
+ querier->idleTime = 5;
+ timerFactory->updateTime(30000);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(idleEvents.size()));
+ CPPUNIT_ASSERT(idleEvents[0]);
+ CPPUNIT_ASSERT(!idleEvents[1]);
+ }
+
+ void testHandleTick_NotIdle_AlreadyNotIdle() {
+ std::auto_ptr<ActualIdleDetector> testling(createDetector());
+ testling->setIdleTimeSeconds(15);
+ querier->idleTime = 5;
+
+ timerFactory->updateTime(15000);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(idleEvents.size()));
+ }
+
+ private:
+ ActualIdleDetector* createDetector() {
+ ActualIdleDetector* detector = new ActualIdleDetector(querier, timerFactory, 10);
+ detector->onIdleChanged.connect(boost::bind(&ActualIdleDetectorTest::handleIdle, this, _1));
+ return detector;
+ }
+
+ void handleIdle(bool b) {
+ idleEvents.push_back(b);
+ }
+
+ private:
+ struct MockIdleQuerier : public IdleQuerier {
+ MockIdleQuerier() : idleTime(0) {}
+ virtual int getIdleTimeSeconds() { return idleTime; }
+ int idleTime;
+ };
+
+ struct MockTimer : public Timer {
+ MockTimer(int interval) : interval(interval), running(false), lastTime(0) {}
+
+ virtual void start() {
+ running = true;
+ }
+
+ virtual void stop() {
+ running = false;
+ }
+
+ virtual void updateTime(int currentTime) {
+ if (lastTime == currentTime) {
+ return;
+ }
+ if (running) {
+ int time = lastTime;
+ while (time <= currentTime) {
+ onTick();
+ time += interval;
+ }
+ }
+ lastTime = currentTime;
+ }
+
+ int interval;
+ bool running;
+ int lastTime;
+ };
+
+ struct MockTimerFactory : public TimerFactory {
+ MockTimerFactory() {}
+
+ void updateTime(int milliseconds) {
+ foreach(boost::shared_ptr<MockTimer> timer, timers) {
+ timer->updateTime(milliseconds);
+ }
+ }
+
+ boost::shared_ptr<Timer> createTimer(int milliseconds) {
+ boost::shared_ptr<MockTimer> timer(new MockTimer(milliseconds));
+ timers.push_back(timer);
+ return timer;
+ }
+
+ std::vector<boost::shared_ptr<MockTimer> > timers;
+ };
+
+ MockIdleQuerier* querier;
+ MockTimerFactory* timerFactory;
+ std::vector<bool> idleEvents;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ActualIdleDetectorTest);
diff --git a/SwifTools/Idle/WindowsIdleQuerier.cpp b/SwifTools/Idle/WindowsIdleQuerier.cpp
index ef1738b..f766436 100644
--- a/SwifTools/Idle/WindowsIdleQuerier.cpp
+++ b/SwifTools/Idle/WindowsIdleQuerier.cpp
@@ -14,14 +14,14 @@ WindowsIdleQuerier::WindowsIdleQuerier() {
}
int WindowsIdleQuerier::getIdleTimeSeconds() {
- LASTINPUTINFO info;
- info.cbSize = sizeof(info);
- if (GetLastInputInfo(&info)) {
- return (GetTickCount() - info.dwTime) / 1000;
- }
- else {
- return 0;
- }
+ LASTINPUTINFO info;
+ info.cbSize = sizeof(info);
+ if (GetLastInputInfo(&info)) {
+ return (GetTickCount() - info.dwTime) / 1000;
+ }
+ else {
+ return 0;
+ }
}
}
diff --git a/SwifTools/Idle/WindowsIdleQuerier.h b/SwifTools/Idle/WindowsIdleQuerier.h
index 557ecab..198c6e9 100644
--- a/SwifTools/Idle/WindowsIdleQuerier.h
+++ b/SwifTools/Idle/WindowsIdleQuerier.h
@@ -9,10 +9,10 @@
#include <SwifTools/Idle/IdleQuerier.h>
namespace Swift {
- class WindowsIdleQuerier : public IdleQuerier {
- public:
- WindowsIdleQuerier();
+ class WindowsIdleQuerier : public IdleQuerier {
+ public:
+ WindowsIdleQuerier();
- virtual int getIdleTimeSeconds();
- };
+ virtual int getIdleTimeSeconds();
+ };
}
diff --git a/SwifTools/Idle/XSSIdleQuerier.cpp b/SwifTools/Idle/XSSIdleQuerier.cpp
index 883f76f..03c5330 100644
--- a/SwifTools/Idle/XSSIdleQuerier.cpp
+++ b/SwifTools/Idle/XSSIdleQuerier.cpp
@@ -14,31 +14,31 @@
namespace Swift {
XSSIdleQuerier::XSSIdleQuerier() : display(NULL), info(NULL) {
- display = XOpenDisplay(NULL);
- assert(display);
- rootWindow = DefaultRootWindow(display);
- int event, error;
- available = XScreenSaverQueryExtension(display, &event, &error);
- if (available) {
- info = XScreenSaverAllocInfo();
- }
- else {
- std::cerr << "Warning: XScreenSaver extension not found. Idle time detection will not work." << std::endl;
- }
+ display = XOpenDisplay(NULL);
+ assert(display);
+ rootWindow = DefaultRootWindow(display);
+ int event, error;
+ available = XScreenSaverQueryExtension(display, &event, &error);
+ if (available) {
+ info = XScreenSaverAllocInfo();
+ }
+ else {
+ std::cerr << "Warning: XScreenSaver extension not found. Idle time detection will not work." << std::endl;
+ }
}
XSSIdleQuerier::~XSSIdleQuerier() {
- XFree(info);
+ XFree(info);
}
int XSSIdleQuerier::getIdleTimeSeconds() {
- if (available) {
- XScreenSaverQueryInfo(display, rootWindow, info);
- return info->idle / 1000;
- }
- else {
- return 0;
- }
+ if (available) {
+ XScreenSaverQueryInfo(display, rootWindow, info);
+ return info->idle / 1000;
+ }
+ else {
+ return 0;
+ }
}
}
diff --git a/SwifTools/Idle/XSSIdleQuerier.h b/SwifTools/Idle/XSSIdleQuerier.h
index ae5a502..225f781 100644
--- a/SwifTools/Idle/XSSIdleQuerier.h
+++ b/SwifTools/Idle/XSSIdleQuerier.h
@@ -12,17 +12,17 @@
#include <SwifTools/Idle/IdleQuerier.h>
namespace Swift {
- class XSSIdleQuerier : public IdleQuerier {
- public:
- XSSIdleQuerier();
- ~XSSIdleQuerier();
+ class XSSIdleQuerier : public IdleQuerier {
+ public:
+ XSSIdleQuerier();
+ ~XSSIdleQuerier();
- virtual int getIdleTimeSeconds();
+ virtual int getIdleTimeSeconds();
- private:
- Display* display;
- Window rootWindow;
- bool available;
- XScreenSaverInfo* info;
- };
+ private:
+ Display* display;
+ Window rootWindow;
+ bool available;
+ XScreenSaverInfo* info;
+ };
}
diff --git a/SwifTools/LastLineTracker.cpp b/SwifTools/LastLineTracker.cpp
index 9428ff4..b9f1aa3 100644
--- a/SwifTools/LastLineTracker.cpp
+++ b/SwifTools/LastLineTracker.cpp
@@ -15,22 +15,22 @@
using namespace Swift;
LastLineTracker::LastLineTracker() {
- lastFocus = true;
- shouldMove = false;
+ lastFocus = true;
+ shouldMove = false;
}
void LastLineTracker::setHasFocus(bool focus) {
- if (!focus && lastFocus) {
- shouldMove = true;
- lastFocus = focus;
- return;
- }
- shouldMove = false;
- lastFocus = focus;
+ if (!focus && lastFocus) {
+ shouldMove = true;
+ lastFocus = focus;
+ return;
+ }
+ shouldMove = false;
+ lastFocus = focus;
}
bool LastLineTracker::getShouldMoveLastLine() {
- bool ret = shouldMove;
- shouldMove = false;
- return ret;
+ bool ret = shouldMove;
+ shouldMove = false;
+ return ret;
}
diff --git a/SwifTools/LastLineTracker.h b/SwifTools/LastLineTracker.h
index b7c9a3b..7156ec3 100644
--- a/SwifTools/LastLineTracker.h
+++ b/SwifTools/LastLineTracker.h
@@ -7,13 +7,13 @@
#pragma once
namespace Swift {
- class LastLineTracker {
- public:
- LastLineTracker();
- void setHasFocus(bool focus);
- bool getShouldMoveLastLine();
- private:
- bool lastFocus;
- bool shouldMove;
- };
+ class LastLineTracker {
+ public:
+ LastLineTracker();
+ void setHasFocus(bool focus);
+ bool getShouldMoveLastLine();
+ private:
+ bool lastFocus;
+ bool shouldMove;
+ };
}
diff --git a/SwifTools/Linkify.cpp b/SwifTools/Linkify.cpp
index 324d145..b1557e5 100644
--- a/SwifTools/Linkify.cpp
+++ b/SwifTools/Linkify.cpp
@@ -16,89 +16,89 @@ namespace Swift {
static boost::regex linkifyRegexp("^(https?://|xmpp:).*");
std::string Linkify::linkify(const std::string& input) {
- std::ostringstream result;
- std::vector<char> currentURL;
- bool inURL = false;
- for (size_t i = 0; i < input.size(); ++i) {
- char c = input[i];
- if (inURL) {
- if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) {
- currentURL.push_back(c);
- }
- else {
- std::string url(&currentURL[0], currentURL.size());
- result << "<a href=\"" << url << "\">" << url << "</a>";
- currentURL.clear();
- inURL = false;
- result << c;
- }
- }
- else {
- if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) {
- currentURL.push_back(c);
- inURL = true;
- }
- else {
- result << c;
- }
- }
- }
- if (!currentURL.empty()) {
- std::string url(&currentURL[0], currentURL.size());
- result << "<a href=\"" << url << "\">" << url << "</a>";
- }
- return std::string(result.str());
+ std::ostringstream result;
+ std::vector<char> currentURL;
+ bool inURL = false;
+ for (size_t i = 0; i < input.size(); ++i) {
+ char c = input[i];
+ if (inURL) {
+ if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) {
+ currentURL.push_back(c);
+ }
+ else {
+ std::string url(&currentURL[0], currentURL.size());
+ result << "<a href=\"" << url << "\">" << url << "</a>";
+ currentURL.clear();
+ inURL = false;
+ result << c;
+ }
+ }
+ else {
+ if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) {
+ currentURL.push_back(c);
+ inURL = true;
+ }
+ else {
+ result << c;
+ }
+ }
+ }
+ if (!currentURL.empty()) {
+ std::string url(&currentURL[0], currentURL.size());
+ result << "<a href=\"" << url << "\">" << url << "</a>";
+ }
+ return std::string(result.str());
}
std::pair<std::vector<std::string>, size_t> Linkify::splitLink(const std::string& input) {
- std::vector<std::string> result;
- std::pair<std::vector<std::string>, size_t> pair;
- std::vector<char> currentURL;
- bool inURL = false;
- size_t urlStartsAt = 0;
- for (size_t i = 0; i < input.size(); ++i) {
- char c = input[i];
- if (inURL) {
- if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) {
- // Keep parsing
- }
- else {
- std::string url(input.substr(urlStartsAt, i - urlStartsAt));
- result.push_back(url);
- inURL = false;
- size_t remaining = input.size() - i;
- if (remaining > 0) {
- result.push_back(input.substr(i, remaining));
- }
- pair.first = result;
- pair.second = urlStartsAt == 0 ? 0 : 1;
- return pair;
- }
- }
- else {
- if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) {
- urlStartsAt = i;
- inURL = true;
- if (i > 0) {
- result.push_back(input.substr(0, i));
- }
- }
- else {
- // Just keep swimming
- }
- }
- }
- if (urlStartsAt > 0 || inURL) {
- std::string url(input.substr(urlStartsAt, input.size() - urlStartsAt));
- result.push_back(url);
- pair.first = result;
- pair.second = urlStartsAt == 0 ? 0 : 1;
- }
- else {
- pair.first.push_back(input);
- pair.second = 1;
- }
- return pair;
+ std::vector<std::string> result;
+ std::pair<std::vector<std::string>, size_t> pair;
+ std::vector<char> currentURL;
+ bool inURL = false;
+ size_t urlStartsAt = 0;
+ for (size_t i = 0; i < input.size(); ++i) {
+ char c = input[i];
+ if (inURL) {
+ if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) {
+ // Keep parsing
+ }
+ else {
+ std::string url(input.substr(urlStartsAt, i - urlStartsAt));
+ result.push_back(url);
+ inURL = false;
+ size_t remaining = input.size() - i;
+ if (remaining > 0) {
+ result.push_back(input.substr(i, remaining));
+ }
+ pair.first = result;
+ pair.second = urlStartsAt == 0 ? 0 : 1;
+ return pair;
+ }
+ }
+ else {
+ if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) {
+ urlStartsAt = i;
+ inURL = true;
+ if (i > 0) {
+ result.push_back(input.substr(0, i));
+ }
+ }
+ else {
+ // Just keep swimming
+ }
+ }
+ }
+ if (urlStartsAt > 0 || inURL) {
+ std::string url(input.substr(urlStartsAt, input.size() - urlStartsAt));
+ result.push_back(url);
+ pair.first = result;
+ pair.second = urlStartsAt == 0 ? 0 : 1;
+ }
+ else {
+ pair.first.push_back(input);
+ pair.second = 1;
+ }
+ return pair;
}
}
diff --git a/SwifTools/Linkify.h b/SwifTools/Linkify.h
index 98d55d6..64c92dc 100644
--- a/SwifTools/Linkify.h
+++ b/SwifTools/Linkify.h
@@ -10,18 +10,18 @@
#include <vector>
namespace Swift {
- namespace Linkify {
- std::string linkify(const std::string&);
- /**
- * Parse the string for a URI. The string will be split by the URI, and the segments plus index of the URI returned.
- * If no URI is found the index will be result.size() (i.e. an invalid index)
- *
- * Examples:
- * "not a URI" -> <<"not a URI">, -1>
- * "http://swift.im" -> <<"http://swift.im">, 0
- * " See http://swift.im" -> <<" See ", "http://swift.im">, 1>
- * "Right, http://swift.im it is" -> <<"Right, ", "http://swift.im", " it is">, 1>
- */
- std::pair<std::vector<std::string>, size_t> splitLink(const std::string& text);
- }
+ namespace Linkify {
+ std::string linkify(const std::string&);
+ /**
+ * Parse the string for a URI. The string will be split by the URI, and the segments plus index of the URI returned.
+ * If no URI is found the index will be result.size() (i.e. an invalid index)
+ *
+ * Examples:
+ * "not a URI" -> <<"not a URI">, -1>
+ * "http://swift.im" -> <<"http://swift.im">, 0
+ * " See http://swift.im" -> <<" See ", "http://swift.im">, 1>
+ * "Right, http://swift.im it is" -> <<"Right, ", "http://swift.im", " it is">, 1>
+ */
+ std::pair<std::vector<std::string>, size_t> splitLink(const std::string& text);
+ }
}
diff --git a/SwifTools/MacOSXChecker.h b/SwifTools/MacOSXChecker.h
index 0bc7356..be9a32a 100644
--- a/SwifTools/MacOSXChecker.h
+++ b/SwifTools/MacOSXChecker.h
@@ -19,12 +19,12 @@
#include <SwifTools/SpellChecker.h>
namespace Swift {
- class MacOSXChecker : public SpellChecker {
- public:
- MacOSXChecker();
- virtual ~MacOSXChecker();
- virtual bool isCorrect(const std::string& word);
- virtual void getSuggestions(const std::string& word, std::vector<std::string>& list);
- virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions);
- };
+ class MacOSXChecker : public SpellChecker {
+ public:
+ MacOSXChecker();
+ virtual ~MacOSXChecker();
+ virtual bool isCorrect(const std::string& word);
+ virtual void getSuggestions(const std::string& word, std::vector<std::string>& list);
+ virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions);
+ };
}
diff --git a/SwifTools/MacOSXChecker.mm b/SwifTools/MacOSXChecker.mm
index eefea97..5f4f9c3 100644
--- a/SwifTools/MacOSXChecker.mm
+++ b/SwifTools/MacOSXChecker.mm
@@ -21,43 +21,43 @@
namespace Swift {
MacOSXChecker::MacOSXChecker() {
- NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
- [spellChecker setAutomaticallyIdentifiesLanguages:YES];
+ NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
+ [spellChecker setAutomaticallyIdentifiesLanguages:YES];
}
MacOSXChecker::~MacOSXChecker() {
}
bool MacOSXChecker::isCorrect(const std::string& /*word*/) {
- // No content since it doesn't seem to be used anywhere.
- return false;
+ // No content since it doesn't seem to be used anywhere.
+ return false;
}
void MacOSXChecker::getSuggestions(const std::string& word, std::vector<std::string>& list) {
- NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
- NSString* wordString = [[NSString alloc] initWithUTF8String: word.c_str()];
- NSArray* suggestions = [spellChecker guessesForWordRange:NSMakeRange(0, [wordString length]) inString:wordString language:nil inSpellDocumentWithTag:0];
- for(unsigned int i = 0; i < [suggestions count]; ++i) {
- list.push_back(std::string([[suggestions objectAtIndex:i] UTF8String]));
- }
- [wordString release];
+ NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
+ NSString* wordString = [[NSString alloc] initWithUTF8String: word.c_str()];
+ NSArray* suggestions = [spellChecker guessesForWordRange:NSMakeRange(0, [wordString length]) inString:wordString language:nil inSpellDocumentWithTag:0];
+ for(unsigned int i = 0; i < [suggestions count]; ++i) {
+ list.push_back(std::string([[suggestions objectAtIndex:i] UTF8String]));
+ }
+ [wordString release];
}
void MacOSXChecker::checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) {
- NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
- size_t nextLocation = 0;
- NSRange range;
- NSString *fragmentString = [[NSString alloc] initWithUTF8String: fragment.c_str()];
- do {
- range = [spellChecker checkSpellingOfString:fragmentString startingAt:static_cast<long>(nextLocation)];
- if (range.location != NSNotFound) {
- if (range.location < nextLocation)
- break;
- misspelledPositions.push_back(PositionPair(static_cast<int>(range.location), static_cast<int>(range.location + range.length)));
- nextLocation = range.location + range.length + 1;
- }
- } while (range.location != NSNotFound);
- [fragmentString release];
+ NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker];
+ size_t nextLocation = 0;
+ NSRange range;
+ NSString *fragmentString = [[NSString alloc] initWithUTF8String: fragment.c_str()];
+ do {
+ range = [spellChecker checkSpellingOfString:fragmentString startingAt:static_cast<long>(nextLocation)];
+ if (range.location != NSNotFound) {
+ if (range.location < nextLocation)
+ break;
+ misspelledPositions.push_back(PositionPair(static_cast<int>(range.location), static_cast<int>(range.location + range.length)));
+ nextLocation = range.location + range.length + 1;
+ }
+ } while (range.location != NSNotFound);
+ [fragmentString release];
}
}
diff --git a/SwifTools/Notifier/GNTPNotifier.cpp b/SwifTools/Notifier/GNTPNotifier.cpp
index 01e8726..62203b4 100644
--- a/SwifTools/Notifier/GNTPNotifier.cpp
+++ b/SwifTools/Notifier/GNTPNotifier.cpp
@@ -21,67 +21,67 @@
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) {
- 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";
+ // 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) {
+ 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());
+ 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));
+ 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";
- message << "Notification-Text: " << description << "\r\n";
- message << "Notification-Icon: " << pathToString(picture) << "\r\n";
- message << "\r\n";
- send(message.str());
- }
+ 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";
+ message << "Notification-Text: " << description << "\r\n";
+ message << "Notification-Icon: " << pathToString(picture) << "\r\n";
+ message << "\r\n";
+ send(message.str());
+ }
}
void GNTPNotifier::handleConnectFinished(bool error) {
- if (!initialized) {
- initialized = true;
- registered = !error;
- }
+ if (!initialized) {
+ initialized = true;
+ registered = !error;
+ }
- if (!error) {
- currentConnection->write(currentMessage.c_str());
- }
+ if (!error) {
+ currentConnection->write(currentMessage.c_str());
+ }
}
void GNTPNotifier::handleDataRead(const ByteArray&) {
- currentConnection->onDataRead.disconnect(boost::bind(&GNTPNotifier::handleDataRead, this, _1));
- currentConnection->onConnectFinished.disconnect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1));
- currentConnection.reset();
+ currentConnection->onDataRead.disconnect(boost::bind(&GNTPNotifier::handleDataRead, this, _1));
+ currentConnection->onConnectFinished.disconnect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1));
+ currentConnection.reset();
}
}
diff --git a/SwifTools/Notifier/GNTPNotifier.h b/SwifTools/Notifier/GNTPNotifier.h
index 92ff5a3..44811e7 100644
--- a/SwifTools/Notifier/GNTPNotifier.h
+++ b/SwifTools/Notifier/GNTPNotifier.h
@@ -13,27 +13,27 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class ConnectionFactory;
-
- class GNTPNotifier : public Notifier {
- public:
- GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory);
- ~GNTPNotifier();
-
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
-
- private:
- void handleConnectFinished(bool error);
- void handleDataRead(const ByteArray& data);
- void send(const std::string& message);
-
- private:
- std::string name;
- boost::filesystem::path icon;
- ConnectionFactory* connectionFactory;
- bool initialized;
- bool registered;
- std::string currentMessage;
- Connection::ref currentConnection;
- };
+ class ConnectionFactory;
+
+ class GNTPNotifier : public Notifier {
+ public:
+ GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory);
+ ~GNTPNotifier();
+
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+
+ private:
+ void handleConnectFinished(bool error);
+ void handleDataRead(const ByteArray& data);
+ void send(const std::string& message);
+
+ private:
+ std::string name;
+ boost::filesystem::path icon;
+ ConnectionFactory* connectionFactory;
+ bool initialized;
+ bool registered;
+ std::string currentMessage;
+ Connection::ref currentConnection;
+ };
}
diff --git a/SwifTools/Notifier/GrowlNotifier.h b/SwifTools/Notifier/GrowlNotifier.h
index 9c90471..b4c4eba 100644
--- a/SwifTools/Notifier/GrowlNotifier.h
+++ b/SwifTools/Notifier/GrowlNotifier.h
@@ -11,31 +11,31 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- /**
- * Preconditions for using growlnotifier:
- * - Must be part a bundle.
- * - The Carbon/Cocoa application loop must be running (e.g. through QApplication)
- * such that notifications are coming through.
- */
- class GrowlNotifier : public Notifier {
- public:
- GrowlNotifier(const std::string& name);
- ~GrowlNotifier();
-
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual bool isExternallyConfigured() const;
-
- // Called by the delegate. Don't call.
- void handleNotificationClicked(void* data);
- void handleNotificationTimedOut(void* data);
-
- virtual void purgeCallbacks();
-
- private:
- void clearPendingNotifications();
-
- private:
- class Private;
- boost::shared_ptr<Private> p;
- };
+ /**
+ * Preconditions for using growlnotifier:
+ * - Must be part a bundle.
+ * - The Carbon/Cocoa application loop must be running (e.g. through QApplication)
+ * such that notifications are coming through.
+ */
+ class GrowlNotifier : public Notifier {
+ public:
+ GrowlNotifier(const std::string& name);
+ ~GrowlNotifier();
+
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual bool isExternallyConfigured() const;
+
+ // Called by the delegate. Don't call.
+ void handleNotificationClicked(void* data);
+ void handleNotificationTimedOut(void* data);
+
+ virtual void purgeCallbacks();
+
+ private:
+ void clearPendingNotifications();
+
+ private:
+ class Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/SwifTools/Notifier/GrowlNotifier.mm b/SwifTools/Notifier/GrowlNotifier.mm
index d5bdf6f..e9ffff7 100644
--- a/SwifTools/Notifier/GrowlNotifier.mm
+++ b/SwifTools/Notifier/GrowlNotifier.mm
@@ -17,101 +17,101 @@
#pragma GCC diagnostic ignored "-Wold-style-cast"
namespace {
- struct Context {
- Context(const boost::function<void()>& callback) : callback(new boost::function<void()>(callback)) {}
+ struct Context {
+ Context(const boost::function<void()>& callback) : callback(new boost::function<void()>(callback)) {}
- boost::function<void()>* callback;
- };
+ boost::function<void()>* callback;
+ };
}
namespace Swift {
class GrowlNotifier::Private {
- public:
- std::set<Context*> pendingNotifications;
- boost::intrusive_ptr<GrowlNotifierDelegate> delegate;
+ public:
+ std::set<Context*> pendingNotifications;
+ boost::intrusive_ptr<GrowlNotifierDelegate> delegate;
};
GrowlNotifier::GrowlNotifier(const std::string& name) {
- p = boost::make_shared<Private>();
- p->delegate = boost::intrusive_ptr<GrowlNotifierDelegate>([[GrowlNotifierDelegate alloc] init], false);
- p->delegate.get().notifier = this;
- p->delegate.get().name = std2NSString(name);
-
- NSMutableArray* allNotifications = [[NSMutableArray alloc] init];
- foreach(Type type, getAllTypes()) {
- [allNotifications addObject: std2NSString(typeToString(type))];
- }
-
- NSMutableArray* defaultNotifications = [[NSMutableArray alloc] init];
- foreach(Type type, getDefaultTypes()) {
- [defaultNotifications addObject: std2NSString(typeToString(type))];
- }
-
- p->delegate.get().registrationDictionary = [[[NSDictionary alloc]
- initWithObjects: [NSArray arrayWithObjects: allNotifications, defaultNotifications, nil]
- forKeys: [NSArray arrayWithObjects: GROWL_NOTIFICATIONS_ALL, GROWL_NOTIFICATIONS_DEFAULT, nil]] autorelease];
-
- [allNotifications release];
- [defaultNotifications release];
-
- [GrowlApplicationBridge setGrowlDelegate: p->delegate.get()];
+ p = boost::make_shared<Private>();
+ p->delegate = boost::intrusive_ptr<GrowlNotifierDelegate>([[GrowlNotifierDelegate alloc] init], false);
+ p->delegate.get().notifier = this;
+ p->delegate.get().name = std2NSString(name);
+
+ NSMutableArray* allNotifications = [[NSMutableArray alloc] init];
+ foreach(Type type, getAllTypes()) {
+ [allNotifications addObject: std2NSString(typeToString(type))];
+ }
+
+ NSMutableArray* defaultNotifications = [[NSMutableArray alloc] init];
+ foreach(Type type, getDefaultTypes()) {
+ [defaultNotifications addObject: std2NSString(typeToString(type))];
+ }
+
+ p->delegate.get().registrationDictionary = [[[NSDictionary alloc]
+ initWithObjects: [NSArray arrayWithObjects: allNotifications, defaultNotifications, nil]
+ forKeys: [NSArray arrayWithObjects: GROWL_NOTIFICATIONS_ALL, GROWL_NOTIFICATIONS_DEFAULT, nil]] autorelease];
+
+ [allNotifications release];
+ [defaultNotifications release];
+
+ [GrowlApplicationBridge setGrowlDelegate: p->delegate.get()];
}
GrowlNotifier::~GrowlNotifier() {
- [GrowlApplicationBridge setGrowlDelegate: nil];
- clearPendingNotifications();
+ [GrowlApplicationBridge setGrowlDelegate: nil];
+ clearPendingNotifications();
}
void GrowlNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picturePath, boost::function<void()> callback) {
- ByteArray picture;
- readByteArrayFromFile(picture, picturePath);
-
- Context* context = new Context(callback);
- // Growl sometimes sends timeout notifications twice for the same message. We therefore need
- // to keep track of which ones have already been processed.
- p->pendingNotifications.insert(context);
-
- [GrowlApplicationBridge
- notifyWithTitle: std2NSString(subject)
- description: std2NSString(description)
- notificationName: std2NSString(typeToString(type))
- iconData: [NSData dataWithBytes: vecptr(picture) length: picture.size()]
- priority: 0
- isSticky: NO
- clickContext: [NSData dataWithBytes: &context length: sizeof(context)]];
+ ByteArray picture;
+ readByteArrayFromFile(picture, picturePath);
+
+ Context* context = new Context(callback);
+ // Growl sometimes sends timeout notifications twice for the same message. We therefore need
+ // to keep track of which ones have already been processed.
+ p->pendingNotifications.insert(context);
+
+ [GrowlApplicationBridge
+ notifyWithTitle: std2NSString(subject)
+ description: std2NSString(description)
+ notificationName: std2NSString(typeToString(type))
+ iconData: [NSData dataWithBytes: vecptr(picture) length: picture.size()]
+ priority: 0
+ isSticky: NO
+ clickContext: [NSData dataWithBytes: &context length: sizeof(context)]];
}
void GrowlNotifier::handleNotificationClicked(void* rawData) {
- Context* context = *(Context**) [((NSData*) rawData) bytes];
- if (p->pendingNotifications.erase(context) > 0) {
- if (!context->callback->empty()) {
- (*context->callback)();
- }
- delete context;
- }
+ Context* context = *(Context**) [((NSData*) rawData) bytes];
+ if (p->pendingNotifications.erase(context) > 0) {
+ if (!context->callback->empty()) {
+ (*context->callback)();
+ }
+ delete context;
+ }
}
void GrowlNotifier::handleNotificationTimedOut(void* rawData) {
- Context* context = *(Context**) [((NSData*) rawData) bytes];
- if (p->pendingNotifications.erase(context) > 0) {
- delete context;
- }
+ Context* context = *(Context**) [((NSData*) rawData) bytes];
+ if (p->pendingNotifications.erase(context) > 0) {
+ delete context;
+ }
}
bool GrowlNotifier::isExternallyConfigured() const {
- return ![GrowlApplicationBridge isMistEnabled];
+ return ![GrowlApplicationBridge isMistEnabled];
}
void GrowlNotifier::purgeCallbacks() {
- clearPendingNotifications();
+ clearPendingNotifications();
}
void GrowlNotifier::clearPendingNotifications() {
- foreach (Context* context, p->pendingNotifications) {
- delete context;
- }
- p->pendingNotifications.clear();
+ foreach (Context* context, p->pendingNotifications) {
+ delete context;
+ }
+ p->pendingNotifications.clear();
}
}
diff --git a/SwifTools/Notifier/GrowlNotifierDelegate.h b/SwifTools/Notifier/GrowlNotifierDelegate.h
index 0640ff7..f4ce132 100644
--- a/SwifTools/Notifier/GrowlNotifierDelegate.h
+++ b/SwifTools/Notifier/GrowlNotifierDelegate.h
@@ -7,13 +7,13 @@
#import <Growl/Growl.h>
namespace Swift {
- class GrowlNotifier;
+ class GrowlNotifier;
}
@interface GrowlNotifierDelegate : NSObject<GrowlApplicationBridgeDelegate> {
- Swift::GrowlNotifier* notifier;
- NSString* name;
- NSDictionary* registrationDictionary;
+ Swift::GrowlNotifier* notifier;
+ NSString* name;
+ NSDictionary* registrationDictionary;
}
@property (nonatomic, retain) NSDictionary* registrationDictionary;
diff --git a/SwifTools/Notifier/GrowlNotifierDelegate.mm b/SwifTools/Notifier/GrowlNotifierDelegate.mm
index 1d934ad..77df3ab 100644
--- a/SwifTools/Notifier/GrowlNotifierDelegate.mm
+++ b/SwifTools/Notifier/GrowlNotifierDelegate.mm
@@ -17,19 +17,19 @@
using namespace Swift;
- (NSString *) applicationNameForGrowl {
- return name;
+ return name;
}
- (NSDictionary*) registrationDictionaryForGrowl {
- return registrationDictionary;
+ return registrationDictionary;
}
- (void) growlNotificationWasClicked: (id) clickContext {
- notifier->handleNotificationClicked(clickContext);
+ notifier->handleNotificationClicked(clickContext);
}
- (void) growlNotificationTimedOut: (id) clickContext {
- notifier->handleNotificationTimedOut(clickContext);
+ notifier->handleNotificationTimedOut(clickContext);
}
@end
diff --git a/SwifTools/Notifier/LoggingNotifier.h b/SwifTools/Notifier/LoggingNotifier.h
index d50cb2d..e12500b 100644
--- a/SwifTools/Notifier/LoggingNotifier.h
+++ b/SwifTools/Notifier/LoggingNotifier.h
@@ -11,23 +11,23 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class LoggingNotifier : public Notifier {
- public:
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
- notifications.push_back(Notification(type, subject, description, picture, callback));
- }
+ class LoggingNotifier : public Notifier {
+ public:
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
+ notifications.push_back(Notification(type, subject, description, picture, callback));
+ }
- struct Notification {
- Notification(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) : type(type), subject(subject), description(description), picture(picture), callback(callback) {}
- Type type;
- std::string subject;
- std::string description;
- boost::filesystem::path picture;
- boost::function<void()> callback;
- };
+ struct Notification {
+ Notification(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) : type(type), subject(subject), description(description), picture(picture), callback(callback) {}
+ Type type;
+ std::string subject;
+ std::string description;
+ boost::filesystem::path picture;
+ boost::function<void()> callback;
+ };
- virtual void purgeCallbacks() {}
+ virtual void purgeCallbacks() {}
- std::vector<Notification> notifications;
- };
+ std::vector<Notification> notifications;
+ };
}
diff --git a/SwifTools/Notifier/NotificationCenterNotifier.h b/SwifTools/Notifier/NotificationCenterNotifier.h
index 0d43c5b..75b4df7 100644
--- a/SwifTools/Notifier/NotificationCenterNotifier.h
+++ b/SwifTools/Notifier/NotificationCenterNotifier.h
@@ -18,21 +18,21 @@ namespace Swift {
*/
class NotificationCenterNotifier : public Notifier {
public:
- NotificationCenterNotifier();
- virtual ~NotificationCenterNotifier();
+ NotificationCenterNotifier();
+ virtual ~NotificationCenterNotifier();
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void ()> callback);
- virtual void purgeCallbacks();
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void ()> callback);
+ virtual void purgeCallbacks();
- /**
- * @brief The handleUserNotificationActivated is called by the delegate, when a user activates/clicks on a notification.
- * @param identifier The std::string UUID identifiying the notification.
- */
- void handleUserNotificationActivated(const std::string& identifier);
+ /**
+ * @brief The handleUserNotificationActivated is called by the delegate, when a user activates/clicks on a notification.
+ * @param identifier The std::string UUID identifiying the notification.
+ */
+ void handleUserNotificationActivated(const std::string& identifier);
private:
- class Private;
- boost::shared_ptr<Private> p;
+ class Private;
+ boost::shared_ptr<Private> p;
};
}
diff --git a/SwifTools/Notifier/NotificationCenterNotifier.mm b/SwifTools/Notifier/NotificationCenterNotifier.mm
index 01e6368..57b9a4b 100644
--- a/SwifTools/Notifier/NotificationCenterNotifier.mm
+++ b/SwifTools/Notifier/NotificationCenterNotifier.mm
@@ -19,78 +19,78 @@
#include <SwifTools/Cocoa/CocoaUtil.h>
namespace {
- struct Context {
- Context(const boost::function<void()>& callback) : callback(new boost::function<void()>(callback)) {
- }
+ struct Context {
+ Context(const boost::function<void()>& callback) : callback(new boost::function<void()>(callback)) {
+ }
- ~Context() {
- delete callback;
- }
+ ~Context() {
+ delete callback;
+ }
- boost::function<void()>* callback;
- };
+ boost::function<void()>* callback;
+ };
}
namespace Swift {
class NotificationCenterNotifier::Private {
- public:
- std::map<std::string, boost::shared_ptr<Context> > callbacksForNotifications;
- boost::intrusive_ptr<NotificationCenterNotifierDelegate> delegate;
+ public:
+ std::map<std::string, boost::shared_ptr<Context> > callbacksForNotifications;
+ boost::intrusive_ptr<NotificationCenterNotifierDelegate> delegate;
};
NotificationCenterNotifier::NotificationCenterNotifier() {
- p = boost::make_shared<Private>();
- p->delegate = boost::intrusive_ptr<NotificationCenterNotifierDelegate>([[NotificationCenterNotifierDelegate alloc] init], false);
- [p->delegate.get() setNotifier: this];
+ p = boost::make_shared<Private>();
+ p->delegate = boost::intrusive_ptr<NotificationCenterNotifierDelegate>([[NotificationCenterNotifierDelegate alloc] init], false);
+ [p->delegate.get() setNotifier: this];
- [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: p->delegate.get()];
+ [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: p->delegate.get()];
}
NotificationCenterNotifier::~NotificationCenterNotifier() {
- [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: nil];
- p->callbacksForNotifications.clear();
+ [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: nil];
+ p->callbacksForNotifications.clear();
}
void NotificationCenterNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void ()> callback) {
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
- return;
- }
- NSImage* image = [[NSImage alloc] initWithContentsOfFile: std2NSString(picture.string())];
- NSUserNotification* notification = [[NSUserNotification alloc] init];
- [notification setTitle:std2NSString(typeToString(type))];
- [notification setSubtitle:std2NSString(subject)];
- [notification setInformativeText:std2NSString(description)];
- [notification setContentImage: image];
- [image release];
-
- // The OS X Notification Center API does not allow to attach custom data, like a pointer to a callback function,
- // to the NSUserNotification object. Therefore we maintain a mapping from a NSUserNotification instance's identification
- // to their respective callbacks.
- [notification setIdentifier:[[NSUUID UUID] UUIDString]];
-
- /// \todo Currently the elements are only removed on application exit. Ideally the notifications not required anymore
- /// are removed from the map; e.g. when visiting a chat view, all notifications from that view can be removed from
- /// the map and the NSUserNotificationCenter.
- p->callbacksForNotifications[ns2StdString(notification.identifier)] = boost::make_shared<Context>(callback);
- [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
- [notification release];
+ std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
+ if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
+ return;
+ }
+ NSImage* image = [[NSImage alloc] initWithContentsOfFile: std2NSString(picture.string())];
+ NSUserNotification* notification = [[NSUserNotification alloc] init];
+ [notification setTitle:std2NSString(typeToString(type))];
+ [notification setSubtitle:std2NSString(subject)];
+ [notification setInformativeText:std2NSString(description)];
+ [notification setContentImage: image];
+ [image release];
+
+ // The OS X Notification Center API does not allow to attach custom data, like a pointer to a callback function,
+ // to the NSUserNotification object. Therefore we maintain a mapping from a NSUserNotification instance's identification
+ // to their respective callbacks.
+ [notification setIdentifier:[[NSUUID UUID] UUIDString]];
+
+ /// \todo Currently the elements are only removed on application exit. Ideally the notifications not required anymore
+ /// are removed from the map; e.g. when visiting a chat view, all notifications from that view can be removed from
+ /// the map and the NSUserNotificationCenter.
+ p->callbacksForNotifications[ns2StdString(notification.identifier)] = boost::make_shared<Context>(callback);
+ [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
+ [notification release];
}
void NotificationCenterNotifier::purgeCallbacks() {
- p->callbacksForNotifications.clear();
+ p->callbacksForNotifications.clear();
}
void NotificationCenterNotifier::handleUserNotificationActivated(const std::string& identifier) {
- if (p->callbacksForNotifications.find(identifier) != p->callbacksForNotifications.end()) {
- if (!(*p->callbacksForNotifications[identifier]->callback).empty()) {
- (*p->callbacksForNotifications[identifier]->callback)();
- }
- }
- else {
- SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance." << std::endl;
- }
+ if (p->callbacksForNotifications.find(identifier) != p->callbacksForNotifications.end()) {
+ if (!(*p->callbacksForNotifications[identifier]->callback).empty()) {
+ (*p->callbacksForNotifications[identifier]->callback)();
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance." << std::endl;
+ }
}
}
diff --git a/SwifTools/Notifier/NotificationCenterNotifierDelegate.h b/SwifTools/Notifier/NotificationCenterNotifierDelegate.h
index ea8fae0..f09c09f 100644
--- a/SwifTools/Notifier/NotificationCenterNotifierDelegate.h
+++ b/SwifTools/Notifier/NotificationCenterNotifierDelegate.h
@@ -9,7 +9,7 @@
#import <Cocoa/Cocoa.h>
namespace Swift {
- class NotificationCenterNotifier;
+ class NotificationCenterNotifier;
}
@interface NotificationCenterNotifierDelegate : NSObject<NSUserNotificationCenterDelegate> {
diff --git a/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm b/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm
index 2b1c2a4..84ec943 100644
--- a/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm
+++ b/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm
@@ -18,9 +18,9 @@ using namespace Swift;
@synthesize notifier;
- (void)userNotificationCenter:(NSUserNotificationCenter *) center didActivateNotification:(NSUserNotification *)notification {
- (void)center;
- std::string identifier = ns2StdString(notification.identifier);
- notifier->handleUserNotificationActivated(identifier);
+ (void)center;
+ std::string identifier = ns2StdString(notification.identifier);
+ notifier->handleUserNotificationActivated(identifier);
}
@end
diff --git a/SwifTools/Notifier/Notifier.cpp b/SwifTools/Notifier/Notifier.cpp
index b8fd1a0..314d39c 100644
--- a/SwifTools/Notifier/Notifier.cpp
+++ b/SwifTools/Notifier/Notifier.cpp
@@ -15,32 +15,32 @@ Notifier::~Notifier() {
}
std::string Notifier::typeToString(Type type) {
- switch (type) {
- case ContactAvailable: return "Contact Becomes Available";
- case ContactUnavailable: return "Contact Becomes Unavailable";
- case ContactStatusChange: return "Contact Changes Status";
- case IncomingMessage: return "Incoming Message";
- case SystemMessage: return "System Message";
- }
- assert(false);
- return "";
+ switch (type) {
+ case ContactAvailable: return "Contact Becomes Available";
+ case ContactUnavailable: return "Contact Becomes Unavailable";
+ case ContactStatusChange: return "Contact Changes Status";
+ case IncomingMessage: return "Incoming Message";
+ case SystemMessage: return "System Message";
+ }
+ assert(false);
+ return "";
}
std::vector<Notifier::Type> Notifier::getAllTypes() {
- std::vector<Type> result;
- result.push_back(ContactAvailable);
- result.push_back(ContactUnavailable);
- result.push_back(ContactStatusChange);
- result.push_back(IncomingMessage);
- result.push_back(SystemMessage);
- return result;
+ std::vector<Type> result;
+ result.push_back(ContactAvailable);
+ result.push_back(ContactUnavailable);
+ result.push_back(ContactStatusChange);
+ result.push_back(IncomingMessage);
+ result.push_back(SystemMessage);
+ return result;
}
std::vector<Notifier::Type> Notifier::getDefaultTypes() {
- std::vector<Type> result;
- result.push_back(IncomingMessage);
- result.push_back(SystemMessage);
- return result;
+ std::vector<Type> result;
+ result.push_back(IncomingMessage);
+ result.push_back(SystemMessage);
+ return result;
}
}
diff --git a/SwifTools/Notifier/Notifier.h b/SwifTools/Notifier/Notifier.h
index b099701..afd596b 100644
--- a/SwifTools/Notifier/Notifier.h
+++ b/SwifTools/Notifier/Notifier.h
@@ -13,39 +13,39 @@
#include <boost/function.hpp>
namespace Swift {
- class Notifier {
- public:
- virtual ~Notifier();
-
- enum Type { ContactAvailable, ContactUnavailable, ContactStatusChange, IncomingMessage, SystemMessage };
-
- /**
- * Picture is a PNG image.
- */
- virtual void showMessage(
- Type type,
- const std::string& subject,
- const std::string& description,
- const boost::filesystem::path& picture,
- boost::function<void()> callback) = 0;
-
- virtual bool isAvailable() const {
- return true;
- }
-
- virtual bool isExternallyConfigured() const {
- return false;
- }
-
- /** Remove any pending callbacks. */
- virtual void purgeCallbacks() = 0;
-
- protected:
- std::string typeToString(Type type);
- static std::vector<Type> getAllTypes();
- static std::vector<Type> getDefaultTypes();
-
- static const int DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
- static const int DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS;
- };
+ class Notifier {
+ public:
+ virtual ~Notifier();
+
+ enum Type { ContactAvailable, ContactUnavailable, ContactStatusChange, IncomingMessage, SystemMessage };
+
+ /**
+ * Picture is a PNG image.
+ */
+ virtual void showMessage(
+ Type type,
+ const std::string& subject,
+ const std::string& description,
+ const boost::filesystem::path& picture,
+ boost::function<void()> callback) = 0;
+
+ virtual bool isAvailable() const {
+ return true;
+ }
+
+ virtual bool isExternallyConfigured() const {
+ return false;
+ }
+
+ /** Remove any pending callbacks. */
+ virtual void purgeCallbacks() = 0;
+
+ protected:
+ std::string typeToString(Type type);
+ static std::vector<Type> getAllTypes();
+ static std::vector<Type> getDefaultTypes();
+
+ static const int DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+ static const int DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS;
+ };
}
diff --git a/SwifTools/Notifier/NullNotifier.h b/SwifTools/Notifier/NullNotifier.h
index 1f6d7d9..8945a53 100644
--- a/SwifTools/Notifier/NullNotifier.h
+++ b/SwifTools/Notifier/NullNotifier.h
@@ -9,11 +9,11 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class NullNotifier : public Notifier {
- public:
- virtual void showMessage(Type, const std::string&, const std::string&, const boost::filesystem::path&, boost::function<void()>) {
- }
- virtual void purgeCallbacks() {
- }
- };
+ class NullNotifier : public Notifier {
+ public:
+ virtual void showMessage(Type, const std::string&, const std::string&, const boost::filesystem::path&, boost::function<void()>) {
+ }
+ virtual void purgeCallbacks() {
+ }
+ };
}
diff --git a/SwifTools/Notifier/SnarlNotifier.cpp b/SwifTools/Notifier/SnarlNotifier.cpp
index b4e5ef3..e3977a7 100644
--- a/SwifTools/Notifier/SnarlNotifier.cpp
+++ b/SwifTools/Notifier/SnarlNotifier.cpp
@@ -18,56 +18,56 @@
namespace Swift {
SnarlNotifier::SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon) : window(window), available(false) {
- window->onMessageReceived.connect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1));
- available = snarl.RegisterApp(name.c_str(), name.c_str(), icon.string().c_str(), window->getID(), SWIFT_SNARLNOTIFIER_MESSAGE_ID);
- foreach(Notifier::Type type, getAllTypes()) {
- snarl.AddClass(typeToString(type).c_str(), typeToString(type).c_str());
- }
+ window->onMessageReceived.connect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1));
+ available = snarl.RegisterApp(name.c_str(), name.c_str(), icon.string().c_str(), window->getID(), SWIFT_SNARLNOTIFIER_MESSAGE_ID);
+ foreach(Notifier::Type type, getAllTypes()) {
+ snarl.AddClass(typeToString(type).c_str(), typeToString(type).c_str());
+ }
}
SnarlNotifier::~SnarlNotifier() {
- snarl.UnregisterApp();
- window->onMessageReceived.disconnect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1));
- if (!notifications.empty()) {
- std::cerr << "Warning: " << notifications.size() << " Snarl notifications pending" << std::endl;
- }
+ snarl.UnregisterApp();
+ window->onMessageReceived.disconnect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1));
+ if (!notifications.empty()) {
+ std::cerr << "Warning: " << notifications.size() << " Snarl notifications pending" << std::endl;
+ }
}
bool SnarlNotifier::isAvailable() const {
- return available;
+ return available;
}
void SnarlNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
- int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
- int notificationID = snarl.EZNotify(
- typeToString(type).c_str(),
- subject.c_str(),
- description.c_str(),
- timeout,
- picture.string().c_str());
- if (notificationID > 0) {
- notifications.insert(std::make_pair(notificationID, callback));
- }
+ int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+ int notificationID = snarl.EZNotify(
+ typeToString(type).c_str(),
+ subject.c_str(),
+ description.c_str(),
+ timeout,
+ picture.string().c_str());
+ if (notificationID > 0) {
+ notifications.insert(std::make_pair(notificationID, callback));
+ }
}
void SnarlNotifier::handleMessageReceived(MSG* message) {
- if (message->message == SWIFT_SNARLNOTIFIER_MESSAGE_ID) {
- int action = message->wParam;
- if (action == Snarl::V41::SnarlEnums::NotificationTimedOut || action == Snarl::V41::SnarlEnums::NotificationAck || action == Snarl::V41::SnarlEnums::NotificationClosed) {
- int notificationID = message->lParam;
- NotificationsMap::iterator i = notifications.find(notificationID);
- if (i != notifications.end()) {
- if (action == Snarl::V41::SnarlEnums::NotificationAck && !i->second.empty()) {
- i->second();
- }
- notifications.erase(i);
- }
- else {
- std::cerr << "Warning: Orphaned Snarl notification received";
- }
- }
- }
+ if (message->message == SWIFT_SNARLNOTIFIER_MESSAGE_ID) {
+ int action = message->wParam;
+ if (action == Snarl::V41::SnarlEnums::NotificationTimedOut || action == Snarl::V41::SnarlEnums::NotificationAck || action == Snarl::V41::SnarlEnums::NotificationClosed) {
+ int notificationID = message->lParam;
+ NotificationsMap::iterator i = notifications.find(notificationID);
+ if (i != notifications.end()) {
+ if (action == Snarl::V41::SnarlEnums::NotificationAck && !i->second.empty()) {
+ i->second();
+ }
+ notifications.erase(i);
+ }
+ else {
+ std::cerr << "Warning: Orphaned Snarl notification received";
+ }
+ }
+ }
}
}
diff --git a/SwifTools/Notifier/SnarlNotifier.h b/SwifTools/Notifier/SnarlNotifier.h
index b8b9a48..5006185 100644
--- a/SwifTools/Notifier/SnarlNotifier.h
+++ b/SwifTools/Notifier/SnarlNotifier.h
@@ -13,28 +13,28 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class Win32NotifierWindow;
-
- class SnarlNotifier : public Notifier {
- public:
- SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon);
- ~SnarlNotifier();
-
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual bool isAvailable() const;
-
- virtual void purgeCallbacks() {
- notifications.clear();
- }
-
- private:
- void handleMessageReceived(MSG* message);
-
- private:
- Snarl::V41::SnarlInterface snarl;
- Win32NotifierWindow* window;
- bool available;
- typedef std::map<int, boost::function<void()> > NotificationsMap;
- NotificationsMap notifications;
- };
+ class Win32NotifierWindow;
+
+ class SnarlNotifier : public Notifier {
+ public:
+ SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon);
+ ~SnarlNotifier();
+
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual bool isAvailable() const;
+
+ virtual void purgeCallbacks() {
+ notifications.clear();
+ }
+
+ private:
+ void handleMessageReceived(MSG* message);
+
+ private:
+ Snarl::V41::SnarlInterface snarl;
+ Win32NotifierWindow* window;
+ bool available;
+ typedef std::map<int, boost::function<void()> > NotificationsMap;
+ NotificationsMap notifications;
+ };
}
diff --git a/SwifTools/Notifier/TogglableNotifier.h b/SwifTools/Notifier/TogglableNotifier.h
index 5580322..c537a6f 100644
--- a/SwifTools/Notifier/TogglableNotifier.h
+++ b/SwifTools/Notifier/TogglableNotifier.h
@@ -9,54 +9,54 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class TogglableNotifier : public Notifier {
- public:
- TogglableNotifier(Notifier* notifier) : notifier(notifier), persistentEnabled(true), temporarilyDisabled(false) {
- }
-
- /**
- * Set a long-term (usually user-set) enabled.
- * This may be temporarily overriden by the application, e.g. if the
- * user is marked DND.
- */
- void setPersistentEnabled(bool b) {
- persistentEnabled = b;
- }
-
- /**
- * Set a temporary override to stop notifications without changing the
- * long-term state. e.g. if the user goes DND, but the persistent
- * enabled shouldn't be lost when they become available again.
- */
- void setTemporarilyDisabled(bool b) {
- temporarilyDisabled = b;
- }
-
- /**
- * Get the result of applying the temporary override to the persistent
- * enabledness.
- */
- bool getCurrentlyEnabled() const {
- return persistentEnabled && !temporarilyDisabled;
- }
-
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
- if (getCurrentlyEnabled() || notifier->isExternallyConfigured()) {
- notifier->showMessage(type, subject, description, picture, callback);
- }
- }
-
- virtual bool isExternallyConfigured() const {
- return notifier->isExternallyConfigured();
- }
-
- virtual void purgeCallbacks() {
- notifier->purgeCallbacks();
- }
-
- private:
- Notifier* notifier;
- bool persistentEnabled;
- bool temporarilyDisabled;
- };
+ class TogglableNotifier : public Notifier {
+ public:
+ TogglableNotifier(Notifier* notifier) : notifier(notifier), persistentEnabled(true), temporarilyDisabled(false) {
+ }
+
+ /**
+ * Set a long-term (usually user-set) enabled.
+ * This may be temporarily overriden by the application, e.g. if the
+ * user is marked DND.
+ */
+ void setPersistentEnabled(bool b) {
+ persistentEnabled = b;
+ }
+
+ /**
+ * Set a temporary override to stop notifications without changing the
+ * long-term state. e.g. if the user goes DND, but the persistent
+ * enabled shouldn't be lost when they become available again.
+ */
+ void setTemporarilyDisabled(bool b) {
+ temporarilyDisabled = b;
+ }
+
+ /**
+ * Get the result of applying the temporary override to the persistent
+ * enabledness.
+ */
+ bool getCurrentlyEnabled() const {
+ return persistentEnabled && !temporarilyDisabled;
+ }
+
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
+ if (getCurrentlyEnabled() || notifier->isExternallyConfigured()) {
+ notifier->showMessage(type, subject, description, picture, callback);
+ }
+ }
+
+ virtual bool isExternallyConfigured() const {
+ return notifier->isExternallyConfigured();
+ }
+
+ virtual void purgeCallbacks() {
+ notifier->purgeCallbacks();
+ }
+
+ private:
+ Notifier* notifier;
+ bool persistentEnabled;
+ bool temporarilyDisabled;
+ };
}
diff --git a/SwifTools/Notifier/Win32NotifierWindow.h b/SwifTools/Notifier/Win32NotifierWindow.h
index 8e67146..3f03825 100644
--- a/SwifTools/Notifier/Win32NotifierWindow.h
+++ b/SwifTools/Notifier/Win32NotifierWindow.h
@@ -11,12 +11,12 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class Win32NotifierWindow {
- public:
- virtual ~Win32NotifierWindow() {}
+ class Win32NotifierWindow {
+ public:
+ virtual ~Win32NotifierWindow() {}
- virtual HWND getID() const = 0;
+ virtual HWND getID() const = 0;
- boost::signal<void (MSG*)> onMessageReceived;
- };
+ boost::signal<void (MSG*)> onMessageReceived;
+ };
}
diff --git a/SwifTools/SpellChecker.h b/SwifTools/SpellChecker.h
index e161d20..415d3f6 100644
--- a/SwifTools/SpellChecker.h
+++ b/SwifTools/SpellChecker.h
@@ -20,18 +20,18 @@
#include <SwifTools/SpellParser.h>
namespace Swift {
- class SpellChecker {
- public:
- SpellChecker() {
- parser_ = new SpellParser();
- }
- virtual ~SpellChecker() {
- delete parser_;
- }
- virtual bool isCorrect(const std::string& word) = 0;
- virtual void getSuggestions(const std::string& word, std::vector<std::string>& list) = 0;
- virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) = 0;
- protected:
- SpellParser *parser_;
- };
+ class SpellChecker {
+ public:
+ SpellChecker() {
+ parser_ = new SpellParser();
+ }
+ virtual ~SpellChecker() {
+ delete parser_;
+ }
+ virtual bool isCorrect(const std::string& word) = 0;
+ virtual void getSuggestions(const std::string& word, std::vector<std::string>& list) = 0;
+ virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) = 0;
+ protected:
+ SpellParser *parser_;
+ };
}
diff --git a/SwifTools/SpellCheckerFactory.cpp b/SwifTools/SpellCheckerFactory.cpp
index 428e1a5..e53447e 100644
--- a/SwifTools/SpellCheckerFactory.cpp
+++ b/SwifTools/SpellCheckerFactory.cpp
@@ -24,17 +24,17 @@ SpellCheckerFactory::SpellCheckerFactory() {
#ifdef HAVE_HUNSPELL
SpellChecker* SpellCheckerFactory::createSpellChecker(const std::string& dictFile) {
- std::string affixFile(dictFile);
- boost::replace_all(affixFile, ".dic", ".aff");
- if ((boost::filesystem::exists(dictFile)) && (boost::filesystem::exists(affixFile))) {
- return new HunspellChecker(affixFile.c_str(), dictFile.c_str());
- }
- // If dictionaries don't exist disable the checker
- return NULL;
+ std::string affixFile(dictFile);
+ boost::replace_all(affixFile, ".dic", ".aff");
+ if ((boost::filesystem::exists(dictFile)) && (boost::filesystem::exists(affixFile))) {
+ return new HunspellChecker(affixFile.c_str(), dictFile.c_str());
+ }
+ // If dictionaries don't exist disable the checker
+ return NULL;
}
#elif defined(SWIFTEN_PLATFORM_MACOSX)
SpellChecker* SpellCheckerFactory::createSpellChecker(const std::string& /*dictFile*/) {
- return new MacOSXChecker();
+ return new MacOSXChecker();
}
#endif
diff --git a/SwifTools/SpellCheckerFactory.h b/SwifTools/SpellCheckerFactory.h
index 91118f9..a0de98c 100644
--- a/SwifTools/SpellCheckerFactory.h
+++ b/SwifTools/SpellCheckerFactory.h
@@ -15,10 +15,10 @@
#endif
namespace Swift {
- class SpellChecker;
- class SpellCheckerFactory {
- public:
- SpellCheckerFactory();
- SpellChecker* createSpellChecker(const std::string& dictFile);
- };
+ class SpellChecker;
+ class SpellCheckerFactory {
+ public:
+ SpellCheckerFactory();
+ SpellChecker* createSpellChecker(const std::string& dictFile);
+ };
}
diff --git a/SwifTools/SpellParser.cpp b/SwifTools/SpellParser.cpp
index e60486f..5bafa6e 100644
--- a/SwifTools/SpellParser.cpp
+++ b/SwifTools/SpellParser.cpp
@@ -26,51 +26,51 @@ namespace Swift {
template <typename Lexer>
struct word_count_tokens : lex::lexer<Lexer>
{
- word_count_tokens()
- {
- // define tokens (regular expresions) to match strings
- // order is important
- this->self.add
- ("w{3}.[^ ]+", ID_WWW)
- ("http:\\/\\/[^ ]+", ID_HTTP)
- ("\\w{1,}['?|\\-?]?\\w{1,}", ID_WORD)
- (".", ID_CHAR);
- }
+ word_count_tokens()
+ {
+ // define tokens (regular expresions) to match strings
+ // order is important
+ this->self.add
+ ("w{3}.[^ ]+", ID_WWW)
+ ("http:\\/\\/[^ ]+", ID_HTTP)
+ ("\\w{1,}['?|\\-?]?\\w{1,}", ID_WORD)
+ (".", ID_CHAR);
+ }
};
struct counter
{
- typedef bool result_type;
- // the function operator gets called for each of the matched tokens
- template <typename Token>
- bool operator()(Token const& t, PositionPairList& wordPositions, std::size_t& position) const
- {
- switch (t.id()) {
- case ID_WWW:
- position += boost::numeric_cast<size_t>(t.value().size());
- break;
- case ID_HTTP:
- position += boost::numeric_cast<size_t>(t.value().size());
- break;
- case ID_WORD: // matched a word
- wordPositions.push_back(boost::tuples::make_tuple(position, position + boost::numeric_cast<size_t>(t.value().size())));
- position += boost::numeric_cast<size_t>(t.value().size());
- break;
- case ID_CHAR: // match a simple char
- ++position;
- break;
- }
- return true; // always continue to tokenize
- }
+ typedef bool result_type;
+ // the function operator gets called for each of the matched tokens
+ template <typename Token>
+ bool operator()(Token const& t, PositionPairList& wordPositions, std::size_t& position) const
+ {
+ switch (t.id()) {
+ case ID_WWW:
+ position += boost::numeric_cast<size_t>(t.value().size());
+ break;
+ case ID_HTTP:
+ position += boost::numeric_cast<size_t>(t.value().size());
+ break;
+ case ID_WORD: // matched a word
+ wordPositions.push_back(boost::tuples::make_tuple(position, position + boost::numeric_cast<size_t>(t.value().size())));
+ position += boost::numeric_cast<size_t>(t.value().size());
+ break;
+ case ID_CHAR: // match a simple char
+ ++position;
+ break;
+ }
+ return true; // always continue to tokenize
+ }
};
void SpellParser::check(const std::string& fragment, PositionPairList& wordPositions) {
- std::size_t position = 0;
- // create the token definition instance needed to invoke the lexical analyzer
- word_count_tokens<lex::lexertl::lexer<> > word_count_functor;
- char const* first = fragment.c_str();
- char const* last = &first[fragment.size()];
- lex::tokenize(first, last, word_count_functor, boost::bind(counter(), _1, boost::ref(wordPositions), boost::ref(position)));
+ std::size_t position = 0;
+ // create the token definition instance needed to invoke the lexical analyzer
+ word_count_tokens<lex::lexertl::lexer<> > word_count_functor;
+ char const* first = fragment.c_str();
+ char const* last = &first[fragment.size()];
+ lex::tokenize(first, last, word_count_functor, boost::bind(counter(), _1, boost::ref(wordPositions), boost::ref(position)));
}
}
diff --git a/SwifTools/SpellParser.h b/SwifTools/SpellParser.h
index b37cb48..5b057c9 100644
--- a/SwifTools/SpellParser.h
+++ b/SwifTools/SpellParser.h
@@ -18,19 +18,19 @@
#include <boost/tuple/tuple.hpp>
namespace Swift {
- enum token_ids
- {
- ID_WWW = 1,
- ID_HTTP = 2,
- ID_WORD = 3,
- ID_CHAR = 4
- };
+ enum token_ids
+ {
+ ID_WWW = 1,
+ ID_HTTP = 2,
+ ID_WORD = 3,
+ ID_CHAR = 4
+ };
- typedef boost::tuple<int, int> PositionPair;
- typedef std::vector<PositionPair > PositionPairList;
+ typedef boost::tuple<int, int> PositionPair;
+ typedef std::vector<PositionPair > PositionPairList;
- class SpellParser{
- public:
- void check(const std::string& fragment, PositionPairList& wordPositions);
- };
+ class SpellParser{
+ public:
+ void check(const std::string& fragment, PositionPairList& wordPositions);
+ };
}
diff --git a/SwifTools/TabComplete.cpp b/SwifTools/TabComplete.cpp
index 4796f1b..f158ffa 100644
--- a/SwifTools/TabComplete.cpp
+++ b/SwifTools/TabComplete.cpp
@@ -15,42 +15,42 @@
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);
- }
+ 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());
+ 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_) {
- 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_;
+ 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_) {
+ 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/SwifTools/TabComplete.h b/SwifTools/TabComplete.h
index a1bdc40..ac1e07e 100644
--- a/SwifTools/TabComplete.h
+++ b/SwifTools/TabComplete.h
@@ -10,15 +10,15 @@
#include <vector>
namespace Swift {
- class TabComplete {
- public:
- void addWord(const std::string& word);
- void removeWord(const std::string& word);
- std::string completeWord(const std::string& word);
- private:
- std::vector<std::string> words_;
- std::string lastCompletion_;
- std::string lastShort_;
- std::vector<std::string> lastCompletionCandidates_;
- };
+ class TabComplete {
+ public:
+ void addWord(const std::string& word);
+ void removeWord(const std::string& word);
+ std::string completeWord(const std::string& word);
+ private:
+ std::vector<std::string> words_;
+ std::string lastCompletion_;
+ std::string lastShort_;
+ std::vector<std::string> lastCompletionCandidates_;
+ };
}
diff --git a/SwifTools/URIHandler/MacOSXURIHandler.h b/SwifTools/URIHandler/MacOSXURIHandler.h
index 274f76d..afa4c6c 100644
--- a/SwifTools/URIHandler/MacOSXURIHandler.h
+++ b/SwifTools/URIHandler/MacOSXURIHandler.h
@@ -9,16 +9,16 @@
#include <SwifTools/URIHandler/URIHandler.h>
namespace Swift {
- class MacOSXURIHandler : public URIHandler {
- public:
- MacOSXURIHandler();
- virtual ~MacOSXURIHandler();
+ class MacOSXURIHandler : public URIHandler {
+ public:
+ MacOSXURIHandler();
+ virtual ~MacOSXURIHandler();
- virtual void start();
- virtual void stop();
+ virtual void start();
+ virtual void stop();
- private:
- class Private;
- Private* p;
- };
+ private:
+ class Private;
+ Private* p;
+ };
}
diff --git a/SwifTools/URIHandler/MacOSXURIHandler.mm b/SwifTools/URIHandler/MacOSXURIHandler.mm
index 482be8f..6285e12 100644
--- a/SwifTools/URIHandler/MacOSXURIHandler.mm
+++ b/SwifTools/URIHandler/MacOSXURIHandler.mm
@@ -21,47 +21,47 @@ using namespace Swift;
@end
@implementation MacOSXURIEventHandler
- {
- URIHandler* handler;
- }
-
- - (id) initWithHandler: (URIHandler*) h {
- if ((self = [super init])) {
- handler = h;
- }
- return self;
- }
-
- - (void) getUrl: (NSAppleEventDescriptor*) event withReplyEvent: (NSAppleEventDescriptor*) replyEvent {
- (void) replyEvent;
- NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
- handler->onURI(std::string([url UTF8String]));
- }
+ {
+ URIHandler* handler;
+ }
+
+ - (id) initWithHandler: (URIHandler*) h {
+ if ((self = [super init])) {
+ handler = h;
+ }
+ return self;
+ }
+
+ - (void) getUrl: (NSAppleEventDescriptor*) event withReplyEvent: (NSAppleEventDescriptor*) replyEvent {
+ (void) replyEvent;
+ NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
+ handler->onURI(std::string([url UTF8String]));
+ }
@end
class MacOSXURIHandler::Private {
- public:
- MacOSXURIEventHandler* eventHandler;
+ public:
+ MacOSXURIEventHandler* eventHandler;
};
MacOSXURIHandler::MacOSXURIHandler() {
- p = new Private();
- p->eventHandler = [[MacOSXURIEventHandler alloc] initWithHandler: this];
+ p = new Private();
+ p->eventHandler = [[MacOSXURIEventHandler alloc] initWithHandler: this];
}
MacOSXURIHandler::~MacOSXURIHandler() {
- [p->eventHandler release];
- delete p;
+ [p->eventHandler release];
+ delete p;
}
void MacOSXURIHandler::start() {
- [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->eventHandler andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
+ [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->eventHandler andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
- // Register ourselves as default URI handler
- //NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier];
- //LSSetDefaultHandlerForURLScheme((CFStringRef)@"xmpp", (CFStringRef)bundleID);
+ // Register ourselves as default URI handler
+ //NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier];
+ //LSSetDefaultHandlerForURLScheme((CFStringRef)@"xmpp", (CFStringRef)bundleID);
}
void MacOSXURIHandler::stop() {
- [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
+ [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
}
diff --git a/SwifTools/URIHandler/NullURIHandler.h b/SwifTools/URIHandler/NullURIHandler.h
index 646fab7..99c01e8 100644
--- a/SwifTools/URIHandler/NullURIHandler.h
+++ b/SwifTools/URIHandler/NullURIHandler.h
@@ -9,12 +9,12 @@
#include <SwifTools/URIHandler/URIHandler.h>
namespace Swift {
- class NullURIHandler : public URIHandler {
- public:
- virtual void start() {
- }
+ class NullURIHandler : public URIHandler {
+ public:
+ virtual void start() {
+ }
- virtual void stop() {
- }
- };
+ virtual void stop() {
+ }
+ };
}
diff --git a/SwifTools/URIHandler/URIHandler.h b/SwifTools/URIHandler/URIHandler.h
index 84bb368..0f85e64 100644
--- a/SwifTools/URIHandler/URIHandler.h
+++ b/SwifTools/URIHandler/URIHandler.h
@@ -11,11 +11,11 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class URIHandler {
- public:
- URIHandler();
- virtual ~URIHandler();
+ class URIHandler {
+ public:
+ URIHandler();
+ virtual ~URIHandler();
- boost::signal<void (const std::string&)> onURI;
- };
+ boost::signal<void (const std::string&)> onURI;
+ };
}
diff --git a/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp b/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp
index 0cafefb..aa0570c 100644
--- a/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp
+++ b/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp
@@ -12,180 +12,180 @@
using namespace Swift;
class XMPPURITest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPURITest);
- CPPUNIT_TEST(testFromString_Authority);
- CPPUNIT_TEST(testFromString_AuthorityWithPath);
- CPPUNIT_TEST(testFromString_AuthorityWithFragment);
- CPPUNIT_TEST(testFromString_AuthorityWithPathAndFragment);
- CPPUNIT_TEST(testFromString_AuthorityWithIntlChars);
- CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParameters);
- CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParameters);
- CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParametersWithFragment);
- CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParametersWithFragment);
- CPPUNIT_TEST(testFromString_Path);
- CPPUNIT_TEST(testFromString_PathWithFragment);
- CPPUNIT_TEST(testFromString_PathWithIntlChars);
- CPPUNIT_TEST(testFromString_PathWithInvalidEscapedChar);
- CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar);
- CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar2);
- CPPUNIT_TEST(testFromString_PathWithQueryWithoutParameters);
- CPPUNIT_TEST(testFromString_PathWithQueryWithParameters);
- CPPUNIT_TEST(testFromString_PathWithQueryWithoutParametersWithFragment);
- CPPUNIT_TEST(testFromString_PathWithQueryWithParametersWithFragment);
- CPPUNIT_TEST(testFromString_NoPrefix);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testFromString_Authority() {
- XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com");
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
- }
-
- void testFromString_AuthorityWithPath() {
- XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com");
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
- }
-
- void testFromString_AuthorityWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com#myfragment");
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
-
- void testFromString_AuthorityWithPathAndFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com#myfragment");
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
-
- void testFromString_AuthorityWithIntlChars() {
- XMPPURI testling = XMPPURI::fromString("xmpp://nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com");
-
- CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getAuthority());
- }
-
- void testFromString_AuthorityWithQueryWithoutParameters() {
- XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message");
-
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- }
-
- void testFromString_AuthorityWithQueryWithParameters() {
- XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message");
-
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
- CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
- }
-
- void testFromString_AuthorityWithQueryWithoutParametersWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message#myfragment");
-
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
-
- void testFromString_AuthorityWithQueryWithParametersWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment");
-
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
- CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
-
- void testFromString_Path() {
- XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com");
-
- CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
- }
-
- void testFromString_PathWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com#myfragment");
-
- CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
-
- void testFromString_PathWithIntlChars() {
- XMPPURI testling = XMPPURI::fromString("xmpp:nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com");
+ CPPUNIT_TEST_SUITE(XMPPURITest);
+ CPPUNIT_TEST(testFromString_Authority);
+ CPPUNIT_TEST(testFromString_AuthorityWithPath);
+ CPPUNIT_TEST(testFromString_AuthorityWithFragment);
+ CPPUNIT_TEST(testFromString_AuthorityWithPathAndFragment);
+ CPPUNIT_TEST(testFromString_AuthorityWithIntlChars);
+ CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParameters);
+ CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParameters);
+ CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParametersWithFragment);
+ CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParametersWithFragment);
+ CPPUNIT_TEST(testFromString_Path);
+ CPPUNIT_TEST(testFromString_PathWithFragment);
+ CPPUNIT_TEST(testFromString_PathWithIntlChars);
+ CPPUNIT_TEST(testFromString_PathWithInvalidEscapedChar);
+ CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar);
+ CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar2);
+ CPPUNIT_TEST(testFromString_PathWithQueryWithoutParameters);
+ CPPUNIT_TEST(testFromString_PathWithQueryWithParameters);
+ CPPUNIT_TEST(testFromString_PathWithQueryWithoutParametersWithFragment);
+ CPPUNIT_TEST(testFromString_PathWithQueryWithParametersWithFragment);
+ CPPUNIT_TEST(testFromString_NoPrefix);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testFromString_Authority() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com");
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
+ }
+
+ void testFromString_AuthorityWithPath() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com");
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
+ }
+
+ void testFromString_AuthorityWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com#myfragment");
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
+
+ void testFromString_AuthorityWithPathAndFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com#myfragment");
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
+
+ void testFromString_AuthorityWithIntlChars() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com");
+
+ CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getAuthority());
+ }
+
+ void testFromString_AuthorityWithQueryWithoutParameters() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message");
+
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ }
+
+ void testFromString_AuthorityWithQueryWithParameters() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message");
+
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
+ }
+
+ void testFromString_AuthorityWithQueryWithoutParametersWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message#myfragment");
+
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
+
+ void testFromString_AuthorityWithQueryWithParametersWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment");
+
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
+
+ void testFromString_Path() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com");
+
+ CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
+ }
+
+ void testFromString_PathWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com#myfragment");
+
+ CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
+
+ void testFromString_PathWithIntlChars() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com");
- CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getPath());
- }
+ CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getPath());
+ }
- void testFromString_PathWithInvalidEscapedChar() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test%%@example.com");
+ void testFromString_PathWithInvalidEscapedChar() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test%%@example.com");
- CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
- }
+ CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
+ }
- void testFromString_PathWithIncompleteEscapedChar() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%");
+ void testFromString_PathWithIncompleteEscapedChar() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%");
- CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
- }
+ CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
+ }
- void testFromString_PathWithIncompleteEscapedChar2() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%1");
+ void testFromString_PathWithIncompleteEscapedChar2() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%1");
- CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
- }
+ CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath());
+ }
- void testFromString_PathWithQueryWithoutParameters() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message");
+ void testFromString_PathWithQueryWithoutParameters() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message");
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- }
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ }
- void testFromString_PathWithQueryWithParameters() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message");
+ void testFromString_PathWithQueryWithParameters() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message");
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
- CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
- }
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
+ }
- void testFromString_PathWithQueryWithoutParametersWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message#myfragment");
+ void testFromString_PathWithQueryWithoutParametersWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message#myfragment");
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
- void testFromString_PathWithQueryWithParametersWithFragment() {
- XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment");
+ void testFromString_PathWithQueryWithParametersWithFragment() {
+ XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment");
- CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
- CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
- CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
- CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
- CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
- }
+ CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath());
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType());
+ CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body"));
+ CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment());
+ }
- void testFromString_NoPrefix() {
- XMPPURI testling = XMPPURI::fromString("baz@example.com");
+ void testFromString_NoPrefix() {
+ XMPPURI testling = XMPPURI::fromString("baz@example.com");
- CPPUNIT_ASSERT(testling.isNull());
- }
+ CPPUNIT_ASSERT(testling.isNull());
+ }
- private:
- std::string get(const std::map<std::string, std::string>& m, const std::string& k) {
- std::map<std::string, std::string>::const_iterator i = m.find(k);
- return i == m.end() ? "" : i->second;
- }
+ private:
+ std::string get(const std::map<std::string, std::string>& m, const std::string& k) {
+ std::map<std::string, std::string>::const_iterator i = m.find(k);
+ return i == m.end() ? "" : i->second;
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPURITest);
diff --git a/SwifTools/URIHandler/XMPPURI.cpp b/SwifTools/URIHandler/XMPPURI.cpp
index 38fc72d..8b8b81c 100644
--- a/SwifTools/URIHandler/XMPPURI.cpp
+++ b/SwifTools/URIHandler/XMPPURI.cpp
@@ -26,77 +26,77 @@ XMPPURI::XMPPURI() {
}
XMPPURI XMPPURI::fromString(const std::string& s) {
- XMPPURI result;
- if (boost::starts_with(s, "xmpp:")) {
- std::string uri = s.substr(5, s.npos);
- bool parsePath = true;
- bool parseQuery = true;
- bool parseFragment = true;
+ XMPPURI result;
+ if (boost::starts_with(s, "xmpp:")) {
+ std::string uri = s.substr(5, s.npos);
+ bool parsePath = true;
+ bool parseQuery = true;
+ bool parseFragment = true;
- // Parse authority
- if (boost::starts_with(uri, "//")) {
- size_t i = uri.find_first_of("/#?", 2);
- result.setAuthority(JID(URL::unescape(uri.substr(2, i - 2))));
- if (i == uri.npos) {
- uri = "";
- parsePath = parseQuery = parseFragment = false;
- }
- else {
- if (uri[i] == '?') {
- parsePath = false;
- }
- else if (uri[i] == '#') {
- parseQuery = parsePath = false;
- }
- uri = uri.substr(i + 1, uri.npos);
- }
- }
+ // Parse authority
+ if (boost::starts_with(uri, "//")) {
+ size_t i = uri.find_first_of("/#?", 2);
+ result.setAuthority(JID(URL::unescape(uri.substr(2, i - 2))));
+ if (i == uri.npos) {
+ uri = "";
+ parsePath = parseQuery = parseFragment = false;
+ }
+ else {
+ if (uri[i] == '?') {
+ parsePath = false;
+ }
+ else if (uri[i] == '#') {
+ parseQuery = parsePath = false;
+ }
+ uri = uri.substr(i + 1, uri.npos);
+ }
+ }
- // Parse path
- if (parsePath) {
- size_t i = uri.find_first_of("#?");
- result.setPath(JID(URL::unescape(uri.substr(0, i))));
- if (i == uri.npos) {
- uri = "";
- parseQuery = parseFragment = false;
- }
- else {
- if (uri[i] == '#') {
- parseQuery = false;
- }
- uri = uri.substr(i + 1, uri.npos);
- }
- }
+ // Parse path
+ if (parsePath) {
+ size_t i = uri.find_first_of("#?");
+ result.setPath(JID(URL::unescape(uri.substr(0, i))));
+ if (i == uri.npos) {
+ uri = "";
+ parseQuery = parseFragment = false;
+ }
+ else {
+ if (uri[i] == '#') {
+ parseQuery = false;
+ }
+ uri = uri.substr(i + 1, uri.npos);
+ }
+ }
- // Parse query
- if (parseQuery) {
- size_t end = uri.find_first_of("#");
- std::string query = uri.substr(0, end);
- bool haveType = false;
- typedef boost::split_iterator<std::string::iterator> split_iterator;
- for (split_iterator it = boost::make_split_iterator(query, boost::first_finder(";")); it != split_iterator(); ++it) {
- if (haveType) {
- std::vector<std::string> keyValue;
- boost::split(keyValue, *it, boost::is_any_of("="));
- if (keyValue.size() == 1) {
- result.addQueryParameter(URL::unescape(keyValue[0]), "");
- }
- else if (keyValue.size() >= 2) {
- result.addQueryParameter(URL::unescape(keyValue[0]), URL::unescape(keyValue[1]));
- }
- }
- else {
- result.setQueryType(URL::unescape(boost::copy_range<std::string>(*it)));
- haveType = true;
- }
- }
- uri = (end == uri.npos ? "" : uri.substr(end + 1, uri.npos));
- }
+ // Parse query
+ if (parseQuery) {
+ size_t end = uri.find_first_of("#");
+ std::string query = uri.substr(0, end);
+ bool haveType = false;
+ typedef boost::split_iterator<std::string::iterator> split_iterator;
+ for (split_iterator it = boost::make_split_iterator(query, boost::first_finder(";")); it != split_iterator(); ++it) {
+ if (haveType) {
+ std::vector<std::string> keyValue;
+ boost::split(keyValue, *it, boost::is_any_of("="));
+ if (keyValue.size() == 1) {
+ result.addQueryParameter(URL::unescape(keyValue[0]), "");
+ }
+ else if (keyValue.size() >= 2) {
+ result.addQueryParameter(URL::unescape(keyValue[0]), URL::unescape(keyValue[1]));
+ }
+ }
+ else {
+ result.setQueryType(URL::unescape(boost::copy_range<std::string>(*it)));
+ haveType = true;
+ }
+ }
+ uri = (end == uri.npos ? "" : uri.substr(end + 1, uri.npos));
+ }
- // Parse fragment
- if (parseFragment) {
- result.setFragment(URL::unescape(uri));
- }
- }
- return result;
+ // Parse fragment
+ if (parseFragment) {
+ result.setFragment(URL::unescape(uri));
+ }
+ }
+ return result;
}
diff --git a/SwifTools/URIHandler/XMPPURI.h b/SwifTools/URIHandler/XMPPURI.h
index 275f99a..a8c9f95 100644
--- a/SwifTools/URIHandler/XMPPURI.h
+++ b/SwifTools/URIHandler/XMPPURI.h
@@ -12,62 +12,62 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- // TODO: Implement using Base/URI
- class XMPPURI {
- public:
- XMPPURI();
-
- const JID& getAuthority() const {
- return authority;
- }
-
- void setAuthority(const JID& j) {
- authority = j;
- }
-
- const JID& getPath() const {
- return path;
- }
-
- void setPath(const JID& j) {
- path = j;
- }
-
- const std::string& getQueryType() const {
- return queryType;
- }
-
- void setQueryType(const std::string& q) {
- queryType = q;
- }
-
- const std::map<std::string, std::string>& getQueryParameters() const {
- return queryParameters;
- }
-
- void addQueryParameter(const std::string& key, const std::string& path) {
- queryParameters[key] = path;
- }
-
- const std::string& getFragment() const {
- return fragment;
- }
-
- void setFragment(const std::string& f) {
- fragment = f;
- }
-
- bool isNull() const {
- return !authority.isValid() && !path.isValid();
- }
-
- static XMPPURI fromString(const std::string&);
-
- private:
- JID authority;
- JID path;
- std::string fragment;
- std::string queryType;
- std::map<std::string, std::string> queryParameters;
- };
+ // TODO: Implement using Base/URI
+ class XMPPURI {
+ public:
+ XMPPURI();
+
+ const JID& getAuthority() const {
+ return authority;
+ }
+
+ void setAuthority(const JID& j) {
+ authority = j;
+ }
+
+ const JID& getPath() const {
+ return path;
+ }
+
+ void setPath(const JID& j) {
+ path = j;
+ }
+
+ const std::string& getQueryType() const {
+ return queryType;
+ }
+
+ void setQueryType(const std::string& q) {
+ queryType = q;
+ }
+
+ const std::map<std::string, std::string>& getQueryParameters() const {
+ return queryParameters;
+ }
+
+ void addQueryParameter(const std::string& key, const std::string& path) {
+ queryParameters[key] = path;
+ }
+
+ const std::string& getFragment() const {
+ return fragment;
+ }
+
+ void setFragment(const std::string& f) {
+ fragment = f;
+ }
+
+ bool isNull() const {
+ return !authority.isValid() && !path.isValid();
+ }
+
+ static XMPPURI fromString(const std::string&);
+
+ private:
+ JID authority;
+ JID path;
+ std::string fragment;
+ std::string queryType;
+ std::map<std::string, std::string> queryParameters;
+ };
}
diff --git a/SwifTools/UnitTest/LastLineTrackerTest.cpp b/SwifTools/UnitTest/LastLineTrackerTest.cpp
index 97790e5..0fc77b6 100644
--- a/SwifTools/UnitTest/LastLineTrackerTest.cpp
+++ b/SwifTools/UnitTest/LastLineTrackerTest.cpp
@@ -12,53 +12,53 @@
using namespace Swift;
class LastLineTrackerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LastLineTrackerTest);
- CPPUNIT_TEST(testFocusNormal);
- CPPUNIT_TEST(testFocusOut);
- CPPUNIT_TEST(testFocusOtherTab);
- CPPUNIT_TEST(testRepeatedFocusOut);
- CPPUNIT_TEST(testRepeatedFocusIn);
- CPPUNIT_TEST_SUITE_END();
- public:
- LastLineTrackerTest () {
- }
- void testFocusNormal() {
- LastLineTracker testling;
- testling.setHasFocus(true);
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- }
- void testFocusOut() {
- LastLineTracker testling;
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- }
- void testFocusOtherTab() {
- LastLineTracker testling;
- testling.setHasFocus(true);
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- }
+ CPPUNIT_TEST_SUITE(LastLineTrackerTest);
+ CPPUNIT_TEST(testFocusNormal);
+ CPPUNIT_TEST(testFocusOut);
+ CPPUNIT_TEST(testFocusOtherTab);
+ CPPUNIT_TEST(testRepeatedFocusOut);
+ CPPUNIT_TEST(testRepeatedFocusIn);
+ CPPUNIT_TEST_SUITE_END();
+ public:
+ LastLineTrackerTest () {
+ }
+ void testFocusNormal() {
+ LastLineTracker testling;
+ testling.setHasFocus(true);
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ }
+ void testFocusOut() {
+ LastLineTracker testling;
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ }
+ void testFocusOtherTab() {
+ LastLineTracker testling;
+ testling.setHasFocus(true);
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ }
- void testRepeatedFocusOut() {
- LastLineTracker testling;
- testling.setHasFocus(true);
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
- }
- void testRepeatedFocusIn() {
- LastLineTracker testling;
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
- testling.setHasFocus(true);
- testling.setHasFocus(false);
- CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
- }
+ void testRepeatedFocusOut() {
+ LastLineTracker testling;
+ testling.setHasFocus(true);
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine());
+ }
+ void testRepeatedFocusIn() {
+ LastLineTracker testling;
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
+ testling.setHasFocus(true);
+ testling.setHasFocus(false);
+ CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(LastLineTrackerTest);
diff --git a/SwifTools/UnitTest/LinkifyTest.cpp b/SwifTools/UnitTest/LinkifyTest.cpp
index 663581d..69a0e23 100644
--- a/SwifTools/UnitTest/LinkifyTest.cpp
+++ b/SwifTools/UnitTest/LinkifyTest.cpp
@@ -12,230 +12,230 @@
using namespace Swift;
class LinkifyTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkifyTest);
- CPPUNIT_TEST(testLinkify_URLWithResource);
- CPPUNIT_TEST(testLinkify_HTTPSURLWithResource);
- CPPUNIT_TEST(testLinkify_URLWithEmptyResource);
- CPPUNIT_TEST(testLinkify_BareURL);
- CPPUNIT_TEST(testLinkify_URLSurroundedByWhitespace);
- CPPUNIT_TEST(testLinkify_MultipleURLs);
- CPPUNIT_TEST(testLinkify_CamelCase);
- CPPUNIT_TEST(testLinkify_HierarchicalResource);
- CPPUNIT_TEST(testLinkify_Anchor);
- CPPUNIT_TEST(testLinkify_Plus);
- CPPUNIT_TEST(testLinkify_Tilde);
- CPPUNIT_TEST(testLinkify_Equal);
- CPPUNIT_TEST(testLinkify_Authentication);
- CPPUNIT_TEST(testLinkify_At);
- CPPUNIT_TEST(testLinkify_Amps);
- CPPUNIT_TEST(testLinkify_UnicodeCharacter);
- CPPUNIT_TEST(testLinkify_NewLine);
- CPPUNIT_TEST(testLinkify_Tab);
- CPPUNIT_TEST(testLinkify_Action);
-
- CPPUNIT_TEST(testLinkify_SplitNone);
- CPPUNIT_TEST(testLinkify_SplitAll);
- CPPUNIT_TEST(testLinkify_SplitFirst);
- CPPUNIT_TEST(testLinkify_SplitSecond);
- CPPUNIT_TEST(testLinkify_SplitMiddle);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testLinkify_URLWithResource() {
- std::string result = Linkify::linkify("http://swift.im/blog");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im/blog\">http://swift.im/blog</a>"),
- result);
- }
-
- void testLinkify_HTTPSURLWithResource() {
- std::string result = Linkify::linkify("https://swift.im/blog");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"https://swift.im/blog\">https://swift.im/blog</a>"),
- result);
- }
-
- void testLinkify_URLWithEmptyResource() {
- std::string result = Linkify::linkify("http://swift.im/");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im/\">http://swift.im/</a>"),
- result);
- }
-
-
- void testLinkify_BareURL() {
- std::string result = Linkify::linkify("http://swift.im");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im\">http://swift.im</a>"),
- result);
- }
-
- void testLinkify_URLSurroundedByWhitespace() {
- std::string result = Linkify::linkify("Foo http://swift.im/blog Bar");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("Foo <a href=\"http://swift.im/blog\">http://swift.im/blog</a> Bar"),
- result);
- }
-
- void testLinkify_MultipleURLs() {
- std::string result = Linkify::linkify("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("Foo <a href=\"http://swift.im/blog\">http://swift.im/blog</a> Bar <a href=\"http://el-tramo.be/about\">http://el-tramo.be/about</a> Baz"),
- result);
- }
-
- void testLinkify_CamelCase() {
- std::string result = Linkify::linkify("http://fOo.cOm/bAz");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://fOo.cOm/bAz\">http://fOo.cOm/bAz</a>"),
- result);
- }
-
- void testLinkify_HierarchicalResource() {
- std::string result = Linkify::linkify("http://foo.com/bar/baz/");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://foo.com/bar/baz/\">http://foo.com/bar/baz/</a>"),
- result);
- }
-
- void testLinkify_Anchor() {
- std::string result = Linkify::linkify("http://foo.com/bar#baz");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://foo.com/bar#baz\">http://foo.com/bar#baz</a>"),
- result);
- }
-
- void testLinkify_Plus() {
- std::string result = Linkify::linkify("http://foo.com/bar+baz");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://foo.com/bar+baz\">http://foo.com/bar+baz</a>"),
- result);
- }
-
- void testLinkify_Tilde() {
- std::string result = Linkify::linkify("http://foo.com/~kev/");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://foo.com/~kev/\">http://foo.com/~kev/</a>"),
- result);
- }
-
- void testLinkify_Equal() {
- std::string result = Linkify::linkify("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0\">http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0</a>"),
- result);
- }
-
- void testLinkify_Authentication() {
- std::string result = Linkify::linkify("http://bob:bla@swift.im/foo/bar");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://bob:bla@swift.im/foo/bar\">http://bob:bla@swift.im/foo/bar</a>"),
- result);
- }
-
- void testLinkify_At() {
- std::string result = Linkify::linkify("http://swift.im/foo@bar");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im/foo@bar\">http://swift.im/foo@bar</a>"),
- result);
- }
-
- void testLinkify_Amps() {
- std::string result = Linkify::linkify("http://swift.im/foo&bar&baz");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im/foo&bar&baz\">http://swift.im/foo&bar&baz</a>"),
- result);
- }
-
- void testLinkify_UnicodeCharacter() {
- std::string result = Linkify::linkify("http://\xe2\x98\x83.net");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://\xe2\x98\x83.net\">http://\xe2\x98\x83.net</a>"),
- result);
- }
-
- void testLinkify_NewLine() {
- std::string result = Linkify::linkify("http://swift.im\nfoo");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im\">http://swift.im</a>\nfoo"),
- result);
- }
-
- void testLinkify_Tab() {
- std::string result = Linkify::linkify("http://swift.im\tfoo");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("<a href=\"http://swift.im\">http://swift.im</a>\tfoo"),
- result);
- }
-
- void testLinkify_Action() {
- std::string result = Linkify::linkify("*http://swift.im*");
-
- CPPUNIT_ASSERT_EQUAL(
- std::string("*<a href=\"http://swift.im\">http://swift.im</a>*"),
- result);
- }
-
- void checkResult(const std::string& testling, size_t expectedIndex, std::string expectedSplit[]) {
- std::pair<std::vector<std::string>, size_t> result = Linkify::splitLink(testling);
- CPPUNIT_ASSERT_EQUAL(expectedIndex, result.second);
- for (size_t i = 0; i < result.first.size(); i++) {
- CPPUNIT_ASSERT_EQUAL(expectedSplit[i], result.first[i]);
- }
- }
-
- void testLinkify_SplitNone() {
- std::string testling = "http this ain't";
- size_t expectedIndex = 1;
- std::string expectedSplit[] = {"http this ain't"};
- checkResult(testling, expectedIndex, expectedSplit);
- }
-
- void testLinkify_SplitAll() {
- std::string testling = "http://swift.im";
- size_t expectedIndex = 0;
- std::string expectedSplit[] = {"http://swift.im"};
- checkResult(testling, expectedIndex, expectedSplit);
- }
-
- void testLinkify_SplitFirst() {
- std::string testling = "http://swift.im is a link";
- size_t expectedIndex = 0;
- std::string expectedSplit[] = {"http://swift.im", " is a link"};
- checkResult(testling, expectedIndex, expectedSplit);
- }
-
- void testLinkify_SplitSecond() {
- std::string testling = "this is a link: http://swift.im";
- size_t expectedIndex = 1;
- std::string expectedSplit[] = {"this is a link: ", "http://swift.im"};
- checkResult(testling, expectedIndex, expectedSplit);
- }
-
- void testLinkify_SplitMiddle() {
- std::string testling = "Shove a link like http://swift.im in the middle";
- size_t expectedIndex = 1;
- std::string expectedSplit[] = {"Shove a link like ","http://swift.im", " in the middle"};
- checkResult(testling, expectedIndex, expectedSplit);
- }
+ CPPUNIT_TEST_SUITE(LinkifyTest);
+ CPPUNIT_TEST(testLinkify_URLWithResource);
+ CPPUNIT_TEST(testLinkify_HTTPSURLWithResource);
+ CPPUNIT_TEST(testLinkify_URLWithEmptyResource);
+ CPPUNIT_TEST(testLinkify_BareURL);
+ CPPUNIT_TEST(testLinkify_URLSurroundedByWhitespace);
+ CPPUNIT_TEST(testLinkify_MultipleURLs);
+ CPPUNIT_TEST(testLinkify_CamelCase);
+ CPPUNIT_TEST(testLinkify_HierarchicalResource);
+ CPPUNIT_TEST(testLinkify_Anchor);
+ CPPUNIT_TEST(testLinkify_Plus);
+ CPPUNIT_TEST(testLinkify_Tilde);
+ CPPUNIT_TEST(testLinkify_Equal);
+ CPPUNIT_TEST(testLinkify_Authentication);
+ CPPUNIT_TEST(testLinkify_At);
+ CPPUNIT_TEST(testLinkify_Amps);
+ CPPUNIT_TEST(testLinkify_UnicodeCharacter);
+ CPPUNIT_TEST(testLinkify_NewLine);
+ CPPUNIT_TEST(testLinkify_Tab);
+ CPPUNIT_TEST(testLinkify_Action);
+
+ CPPUNIT_TEST(testLinkify_SplitNone);
+ CPPUNIT_TEST(testLinkify_SplitAll);
+ CPPUNIT_TEST(testLinkify_SplitFirst);
+ CPPUNIT_TEST(testLinkify_SplitSecond);
+ CPPUNIT_TEST(testLinkify_SplitMiddle);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testLinkify_URLWithResource() {
+ std::string result = Linkify::linkify("http://swift.im/blog");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im/blog\">http://swift.im/blog</a>"),
+ result);
+ }
+
+ void testLinkify_HTTPSURLWithResource() {
+ std::string result = Linkify::linkify("https://swift.im/blog");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"https://swift.im/blog\">https://swift.im/blog</a>"),
+ result);
+ }
+
+ void testLinkify_URLWithEmptyResource() {
+ std::string result = Linkify::linkify("http://swift.im/");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im/\">http://swift.im/</a>"),
+ result);
+ }
+
+
+ void testLinkify_BareURL() {
+ std::string result = Linkify::linkify("http://swift.im");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im\">http://swift.im</a>"),
+ result);
+ }
+
+ void testLinkify_URLSurroundedByWhitespace() {
+ std::string result = Linkify::linkify("Foo http://swift.im/blog Bar");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("Foo <a href=\"http://swift.im/blog\">http://swift.im/blog</a> Bar"),
+ result);
+ }
+
+ void testLinkify_MultipleURLs() {
+ std::string result = Linkify::linkify("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("Foo <a href=\"http://swift.im/blog\">http://swift.im/blog</a> Bar <a href=\"http://el-tramo.be/about\">http://el-tramo.be/about</a> Baz"),
+ result);
+ }
+
+ void testLinkify_CamelCase() {
+ std::string result = Linkify::linkify("http://fOo.cOm/bAz");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://fOo.cOm/bAz\">http://fOo.cOm/bAz</a>"),
+ result);
+ }
+
+ void testLinkify_HierarchicalResource() {
+ std::string result = Linkify::linkify("http://foo.com/bar/baz/");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://foo.com/bar/baz/\">http://foo.com/bar/baz/</a>"),
+ result);
+ }
+
+ void testLinkify_Anchor() {
+ std::string result = Linkify::linkify("http://foo.com/bar#baz");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://foo.com/bar#baz\">http://foo.com/bar#baz</a>"),
+ result);
+ }
+
+ void testLinkify_Plus() {
+ std::string result = Linkify::linkify("http://foo.com/bar+baz");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://foo.com/bar+baz\">http://foo.com/bar+baz</a>"),
+ result);
+ }
+
+ void testLinkify_Tilde() {
+ std::string result = Linkify::linkify("http://foo.com/~kev/");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://foo.com/~kev/\">http://foo.com/~kev/</a>"),
+ result);
+ }
+
+ void testLinkify_Equal() {
+ std::string result = Linkify::linkify("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0\">http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0</a>"),
+ result);
+ }
+
+ void testLinkify_Authentication() {
+ std::string result = Linkify::linkify("http://bob:bla@swift.im/foo/bar");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://bob:bla@swift.im/foo/bar\">http://bob:bla@swift.im/foo/bar</a>"),
+ result);
+ }
+
+ void testLinkify_At() {
+ std::string result = Linkify::linkify("http://swift.im/foo@bar");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im/foo@bar\">http://swift.im/foo@bar</a>"),
+ result);
+ }
+
+ void testLinkify_Amps() {
+ std::string result = Linkify::linkify("http://swift.im/foo&bar&baz");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im/foo&bar&baz\">http://swift.im/foo&bar&baz</a>"),
+ result);
+ }
+
+ void testLinkify_UnicodeCharacter() {
+ std::string result = Linkify::linkify("http://\xe2\x98\x83.net");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://\xe2\x98\x83.net\">http://\xe2\x98\x83.net</a>"),
+ result);
+ }
+
+ void testLinkify_NewLine() {
+ std::string result = Linkify::linkify("http://swift.im\nfoo");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im\">http://swift.im</a>\nfoo"),
+ result);
+ }
+
+ void testLinkify_Tab() {
+ std::string result = Linkify::linkify("http://swift.im\tfoo");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("<a href=\"http://swift.im\">http://swift.im</a>\tfoo"),
+ result);
+ }
+
+ void testLinkify_Action() {
+ std::string result = Linkify::linkify("*http://swift.im*");
+
+ CPPUNIT_ASSERT_EQUAL(
+ std::string("*<a href=\"http://swift.im\">http://swift.im</a>*"),
+ result);
+ }
+
+ void checkResult(const std::string& testling, size_t expectedIndex, std::string expectedSplit[]) {
+ std::pair<std::vector<std::string>, size_t> result = Linkify::splitLink(testling);
+ CPPUNIT_ASSERT_EQUAL(expectedIndex, result.second);
+ for (size_t i = 0; i < result.first.size(); i++) {
+ CPPUNIT_ASSERT_EQUAL(expectedSplit[i], result.first[i]);
+ }
+ }
+
+ void testLinkify_SplitNone() {
+ std::string testling = "http this ain't";
+ size_t expectedIndex = 1;
+ std::string expectedSplit[] = {"http this ain't"};
+ checkResult(testling, expectedIndex, expectedSplit);
+ }
+
+ void testLinkify_SplitAll() {
+ std::string testling = "http://swift.im";
+ size_t expectedIndex = 0;
+ std::string expectedSplit[] = {"http://swift.im"};
+ checkResult(testling, expectedIndex, expectedSplit);
+ }
+
+ void testLinkify_SplitFirst() {
+ std::string testling = "http://swift.im is a link";
+ size_t expectedIndex = 0;
+ std::string expectedSplit[] = {"http://swift.im", " is a link"};
+ checkResult(testling, expectedIndex, expectedSplit);
+ }
+
+ void testLinkify_SplitSecond() {
+ std::string testling = "this is a link: http://swift.im";
+ size_t expectedIndex = 1;
+ std::string expectedSplit[] = {"this is a link: ", "http://swift.im"};
+ checkResult(testling, expectedIndex, expectedSplit);
+ }
+
+ void testLinkify_SplitMiddle() {
+ std::string testling = "Shove a link like http://swift.im in the middle";
+ size_t expectedIndex = 1;
+ std::string expectedSplit[] = {"Shove a link like ","http://swift.im", " in the middle"};
+ checkResult(testling, expectedIndex, expectedSplit);
+ }
};
diff --git a/SwifTools/UnitTest/SpellParserTest.cpp b/SwifTools/UnitTest/SpellParserTest.cpp
index 3747eb1..da233e5 100644
--- a/SwifTools/UnitTest/SpellParserTest.cpp
+++ b/SwifTools/UnitTest/SpellParserTest.cpp
@@ -20,38 +20,38 @@
using namespace Swift;
class SpellParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SpellParserTest);
- CPPUNIT_TEST(testSimpleCheckFragment);
- CPPUNIT_TEST(testWWWCheckFragment);
- CPPUNIT_TEST_SUITE_END();
- public:
- SpellParserTest() {
- parser_ = new SpellParser();
- };
- void tearDown() {
- position_.clear();
- }
- void testSimpleCheckFragment() {
- parser_->check("fragment test", position_);
- int size = position_.size();
- CPPUNIT_ASSERT_EQUAL(2, size);
- CPPUNIT_ASSERT_EQUAL(0, boost::get<0>(position_.front()));
- CPPUNIT_ASSERT_EQUAL(8, boost::get<1>(position_.front()));
- CPPUNIT_ASSERT_EQUAL(9, boost::get<0>(position_.back()));
- CPPUNIT_ASSERT_EQUAL(13, boost::get<1>(position_.back()));
- }
- void testWWWCheckFragment() {
- parser_->check("www.link.com fragment test", position_);
- int size = position_.size();
- CPPUNIT_ASSERT_EQUAL(2, size);
- CPPUNIT_ASSERT_EQUAL(13, boost::get<0>(position_.front()));
- CPPUNIT_ASSERT_EQUAL(21, boost::get<1>(position_.front()));
- CPPUNIT_ASSERT_EQUAL(22, boost::get<0>(position_.back()));
- CPPUNIT_ASSERT_EQUAL(26, boost::get<1>(position_.back()));
- }
- private:
- SpellParser *parser_;
- PositionPairList position_;
+ CPPUNIT_TEST_SUITE(SpellParserTest);
+ CPPUNIT_TEST(testSimpleCheckFragment);
+ CPPUNIT_TEST(testWWWCheckFragment);
+ CPPUNIT_TEST_SUITE_END();
+ public:
+ SpellParserTest() {
+ parser_ = new SpellParser();
+ };
+ void tearDown() {
+ position_.clear();
+ }
+ void testSimpleCheckFragment() {
+ parser_->check("fragment test", position_);
+ int size = position_.size();
+ CPPUNIT_ASSERT_EQUAL(2, size);
+ CPPUNIT_ASSERT_EQUAL(0, boost::get<0>(position_.front()));
+ CPPUNIT_ASSERT_EQUAL(8, boost::get<1>(position_.front()));
+ CPPUNIT_ASSERT_EQUAL(9, boost::get<0>(position_.back()));
+ CPPUNIT_ASSERT_EQUAL(13, boost::get<1>(position_.back()));
+ }
+ void testWWWCheckFragment() {
+ parser_->check("www.link.com fragment test", position_);
+ int size = position_.size();
+ CPPUNIT_ASSERT_EQUAL(2, size);
+ CPPUNIT_ASSERT_EQUAL(13, boost::get<0>(position_.front()));
+ CPPUNIT_ASSERT_EQUAL(21, boost::get<1>(position_.front()));
+ CPPUNIT_ASSERT_EQUAL(22, boost::get<0>(position_.back()));
+ CPPUNIT_ASSERT_EQUAL(26, boost::get<1>(position_.back()));
+ }
+ private:
+ SpellParser *parser_;
+ PositionPairList position_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SpellParserTest);
diff --git a/SwifTools/UnitTest/TabCompleteTest.cpp b/SwifTools/UnitTest/TabCompleteTest.cpp
index 2642410..56c91a8 100644
--- a/SwifTools/UnitTest/TabCompleteTest.cpp
+++ b/SwifTools/UnitTest/TabCompleteTest.cpp
@@ -12,254 +12,254 @@
using namespace Swift;
class TabCompleteTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(TabCompleteTest);
- CPPUNIT_TEST(testEmpty);
- CPPUNIT_TEST(testNoMatch);
- CPPUNIT_TEST(testOneMatch);
- CPPUNIT_TEST(testTwoMatch);
- CPPUNIT_TEST(testChangeMatch);
- CPPUNIT_TEST(testRemoveDuringComplete);
- CPPUNIT_TEST(testAddDuringComplete);
- CPPUNIT_TEST(testSwiftRoomSample);
- CPPUNIT_TEST_SUITE_END();
-
+ CPPUNIT_TEST_SUITE(TabCompleteTest);
+ CPPUNIT_TEST(testEmpty);
+ CPPUNIT_TEST(testNoMatch);
+ CPPUNIT_TEST(testOneMatch);
+ CPPUNIT_TEST(testTwoMatch);
+ CPPUNIT_TEST(testChangeMatch);
+ CPPUNIT_TEST(testRemoveDuringComplete);
+ CPPUNIT_TEST(testAddDuringComplete);
+ CPPUNIT_TEST(testSwiftRoomSample);
+ CPPUNIT_TEST_SUITE_END();
+
public:
- TabCompleteTest() {}
-
- void setUp() {
- completer_ = TabComplete();
- }
-
- void testEmpty() {
- std::string blah("Blah");
- CPPUNIT_ASSERT_EQUAL(
- blah,
- completer_.completeWord(blah));
- CPPUNIT_ASSERT_EQUAL(
- blah,
- completer_.completeWord(blah));
- }
-
- void testNoMatch() {
- completer_.addWord("Bleh");
- std::string blah("Blah");
- CPPUNIT_ASSERT_EQUAL(
- blah,
- completer_.completeWord(blah));
- CPPUNIT_ASSERT_EQUAL(
- blah,
- completer_.completeWord(blah));
- }
-
- void testOneMatch() {
- std::string short1("Bl");
- std::string long1("Blehling");
- completer_.addWord(long1);
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(short1));
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(long1));
- }
-
- void testTwoMatch() {
- std::string short1("Hur");
- std::string long1("Hurgle");
- std::string long2("Hurdler");
- completer_.addWord(long1);
- completer_.addWord("Blah");
- completer_.addWord(long2);
- completer_.addWord("Bleh");
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(short1));
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(long2));
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(long1));
- }
-
- void testChangeMatch() {
- std::string short1("Hur");
- std::string short2("Rub");
- std::string long1("Hurgle");
- std::string long2("Rubbish");
- completer_.addWord(long2);
- completer_.addWord("Blah");
- completer_.addWord(long1);
- completer_.addWord("Bleh");
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(short1));
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(short2));
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(long2));
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(short1));
- }
-
- void testRemoveDuringComplete() {
- std::string short1("Kev");
- std::string long1("Kevin");
- std::string long2("Kevlar");
- completer_.addWord(long1);
- completer_.addWord("Blah");
- completer_.addWord(long2);
- completer_.addWord("Bleh");
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(short1));
- completer_.removeWord(long2);
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(long2));
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(long1));
- }
-
- void testAddDuringComplete() {
- std::string short1("Rem");
- std::string long1("Remko");
- std::string long2("Remove");
- std::string long3("Remedial");
- completer_.addWord(long1);
- completer_.addWord("Blah");
- completer_.addWord(long2);
- completer_.addWord("Bleh");
- CPPUNIT_ASSERT_EQUAL(
- long2,
- completer_.completeWord(short1));
- completer_.addWord(long3);
- CPPUNIT_ASSERT_EQUAL(
- long1,
- completer_.completeWord(long2));
- CPPUNIT_ASSERT_EQUAL(
- long3,
- completer_.completeWord(long1));
- }
-
- void testSwiftRoomSample() {
- std::string t("t");
- std::string Anpan("Anpan");
- std::string cdubouloz("cdubouloz");
- std::string Tobias("Tobias");
- std::string Zash("Zash");
- std::string lastsky("lastsky");
- std::string Steve("Steve Kille");
- std::string Flo("Flo");
- std::string Test("Test");
- std::string test("test");
- completer_.addWord(Anpan);
- completer_.addWord(cdubouloz);
- completer_.addWord(Tobias);
- completer_.addWord(lastsky);
- completer_.addWord(Steve);
- completer_.addWord(Flo);
- completer_.addWord(Zash);
-
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Tobias));
-
- completer_.addWord(Test);
-
- CPPUNIT_ASSERT_EQUAL(
- Test,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Test));
- CPPUNIT_ASSERT_EQUAL(
- Test,
- completer_.completeWord(Tobias));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Test));
-
- completer_.addWord(Zash);
- completer_.addWord(Zash);
- completer_.addWord(Zash);
- completer_.addWord(Zash);
-
- completer_.removeWord(Test);
-
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Tobias));
-
- completer_.addWord(test);
-
- completer_.addWord(Zash);
- completer_.addWord(Zash);
- completer_.addWord(Zash);
- completer_.addWord(Zash);
-
-
- CPPUNIT_ASSERT_EQUAL(
- test,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(test));
- CPPUNIT_ASSERT_EQUAL(
- test,
- completer_.completeWord(Tobias));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(test));
-
- completer_.removeWord(test);
-
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Tobias));
-
- completer_.removeWord(Tobias);
- CPPUNIT_ASSERT_EQUAL(
- t,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- t,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- t,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- t,
- completer_.completeWord(t));
-
- completer_.addWord(Tobias);
-
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(t));
- CPPUNIT_ASSERT_EQUAL(
- Tobias,
- completer_.completeWord(Tobias));
-
- }
+ TabCompleteTest() {}
+
+ void setUp() {
+ completer_ = TabComplete();
+ }
+
+ void testEmpty() {
+ std::string blah("Blah");
+ CPPUNIT_ASSERT_EQUAL(
+ blah,
+ completer_.completeWord(blah));
+ CPPUNIT_ASSERT_EQUAL(
+ blah,
+ completer_.completeWord(blah));
+ }
+
+ void testNoMatch() {
+ completer_.addWord("Bleh");
+ std::string blah("Blah");
+ CPPUNIT_ASSERT_EQUAL(
+ blah,
+ completer_.completeWord(blah));
+ CPPUNIT_ASSERT_EQUAL(
+ blah,
+ completer_.completeWord(blah));
+ }
+
+ void testOneMatch() {
+ std::string short1("Bl");
+ std::string long1("Blehling");
+ completer_.addWord(long1);
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(short1));
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(long1));
+ }
+
+ void testTwoMatch() {
+ std::string short1("Hur");
+ std::string long1("Hurgle");
+ std::string long2("Hurdler");
+ completer_.addWord(long1);
+ completer_.addWord("Blah");
+ completer_.addWord(long2);
+ completer_.addWord("Bleh");
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(short1));
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(long2));
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(long1));
+ }
+
+ void testChangeMatch() {
+ std::string short1("Hur");
+ std::string short2("Rub");
+ std::string long1("Hurgle");
+ std::string long2("Rubbish");
+ completer_.addWord(long2);
+ completer_.addWord("Blah");
+ completer_.addWord(long1);
+ completer_.addWord("Bleh");
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(short1));
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(short2));
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(long2));
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(short1));
+ }
+
+ void testRemoveDuringComplete() {
+ std::string short1("Kev");
+ std::string long1("Kevin");
+ std::string long2("Kevlar");
+ completer_.addWord(long1);
+ completer_.addWord("Blah");
+ completer_.addWord(long2);
+ completer_.addWord("Bleh");
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(short1));
+ completer_.removeWord(long2);
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(long2));
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(long1));
+ }
+
+ void testAddDuringComplete() {
+ std::string short1("Rem");
+ std::string long1("Remko");
+ std::string long2("Remove");
+ std::string long3("Remedial");
+ completer_.addWord(long1);
+ completer_.addWord("Blah");
+ completer_.addWord(long2);
+ completer_.addWord("Bleh");
+ CPPUNIT_ASSERT_EQUAL(
+ long2,
+ completer_.completeWord(short1));
+ completer_.addWord(long3);
+ CPPUNIT_ASSERT_EQUAL(
+ long1,
+ completer_.completeWord(long2));
+ CPPUNIT_ASSERT_EQUAL(
+ long3,
+ completer_.completeWord(long1));
+ }
+
+ void testSwiftRoomSample() {
+ std::string t("t");
+ std::string Anpan("Anpan");
+ std::string cdubouloz("cdubouloz");
+ std::string Tobias("Tobias");
+ std::string Zash("Zash");
+ std::string lastsky("lastsky");
+ std::string Steve("Steve Kille");
+ std::string Flo("Flo");
+ std::string Test("Test");
+ std::string test("test");
+ completer_.addWord(Anpan);
+ completer_.addWord(cdubouloz);
+ completer_.addWord(Tobias);
+ completer_.addWord(lastsky);
+ completer_.addWord(Steve);
+ completer_.addWord(Flo);
+ completer_.addWord(Zash);
+
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Tobias));
+
+ completer_.addWord(Test);
+
+ CPPUNIT_ASSERT_EQUAL(
+ Test,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Test));
+ CPPUNIT_ASSERT_EQUAL(
+ Test,
+ completer_.completeWord(Tobias));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Test));
+
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+
+ completer_.removeWord(Test);
+
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Tobias));
+
+ completer_.addWord(test);
+
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+ completer_.addWord(Zash);
+
+
+ CPPUNIT_ASSERT_EQUAL(
+ test,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(test));
+ CPPUNIT_ASSERT_EQUAL(
+ test,
+ completer_.completeWord(Tobias));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(test));
+
+ completer_.removeWord(test);
+
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Tobias));
+
+ completer_.removeWord(Tobias);
+ CPPUNIT_ASSERT_EQUAL(
+ t,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ t,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ t,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ t,
+ completer_.completeWord(t));
+
+ completer_.addWord(Tobias);
+
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(t));
+ CPPUNIT_ASSERT_EQUAL(
+ Tobias,
+ completer_.completeWord(Tobias));
+
+ }
private:
- TabComplete completer_;
+ TabComplete completer_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(TabCompleteTest);
diff --git a/Swift/Controllers/AdHocController.cpp b/Swift/Controllers/AdHocController.cpp
index 38b0fc5..4b93f2b 100644
--- a/Swift/Controllers/AdHocController.cpp
+++ b/Swift/Controllers/AdHocController.cpp
@@ -13,21 +13,21 @@
namespace Swift {
AdHocController::AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr<OutgoingAdHocCommandSession> command) {
- window_ = factory->createAdHocCommandWindow(command);
- window_->onClosing.connect(boost::bind(&AdHocController::handleWindowClosed, this));
+ window_ = factory->createAdHocCommandWindow(command);
+ window_->onClosing.connect(boost::bind(&AdHocController::handleWindowClosed, this));
}
AdHocController::~AdHocController() {
- window_->onClosing.disconnect(boost::bind(&AdHocController::handleWindowClosed, this));
- delete window_;
+ window_->onClosing.disconnect(boost::bind(&AdHocController::handleWindowClosed, this));
+ delete window_;
}
void AdHocController::setOnline(bool online) {
- window_->setOnline(online);
+ window_->setOnline(online);
}
void AdHocController::handleWindowClosed() {
- onDeleting();
+ onDeleting();
}
}
diff --git a/Swift/Controllers/AdHocController.h b/Swift/Controllers/AdHocController.h
index e2b93df..4694991 100644
--- a/Swift/Controllers/AdHocController.h
+++ b/Swift/Controllers/AdHocController.h
@@ -17,13 +17,13 @@ class AdHocCommandWindow;
class AdHocController {
public:
- AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr<OutgoingAdHocCommandSession> command);
- ~AdHocController();
- boost::signal<void ()> onDeleting;
- void setOnline(bool online);
+ AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr<OutgoingAdHocCommandSession> command);
+ ~AdHocController();
+ boost::signal<void ()> onDeleting;
+ void setOnline(bool online);
private:
- void handleWindowClosed();
- AdHocCommandWindow* window_;
+ void handleWindowClosed();
+ AdHocCommandWindow* window_;
};
}
diff --git a/Swift/Controllers/AdHocManager.cpp b/Swift/Controllers/AdHocManager.cpp
index 4733b57..1dcefbd 100644
--- a/Swift/Controllers/AdHocManager.cpp
+++ b/Swift/Controllers/AdHocManager.cpp
@@ -23,73 +23,73 @@
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;
+ iqRouter_ = iqRouter;
+ uiEventStream_ = uiEventStream;
+ mainWindow_ = mainWindow;
+ factory_ = factory;
- uiEventStream_->onUIEvent.connect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
+ uiEventStream_->onUIEvent.connect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
}
AdHocManager::~AdHocManager() {
- uiEventStream_->onUIEvent.disconnect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
- for (size_t i = 0; i < controllers_.size(); ++i) {
- controllers_[i]->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controllers_[i]));
- }
+ uiEventStream_->onUIEvent.disconnect(boost::bind(&AdHocManager::handleUIEvent, this, _1));
+ for (size_t i = 0; i < controllers_.size(); ++i) {
+ controllers_[i]->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controllers_[i]));
+ }
}
void AdHocManager::removeController(boost::shared_ptr<AdHocController> controller) {
- controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
- controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller));
+ controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
+ controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller));
}
void AdHocManager::setServerDiscoInfo(boost::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>());
- }
+ 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 (boost::shared_ptr<AdHocController> controller, controllers_) {
- controller->setOnline(online);
- }
+ foreach (boost::shared_ptr<AdHocController> controller, controllers_) {
+ controller->setOnline(online);
+ }
}
void AdHocManager::handleServerDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error) {
- std::vector<DiscoItems::Item> commands;
- if (!error) {
- foreach (DiscoItems::Item item, items->getItems()) {
- if (item.getNode() != "http://isode.com/xmpp/commands#test") {
- commands.push_back(item);
- }
- }
- }
- mainWindow_->setAvailableAdHocCommands(commands);
+ std::vector<DiscoItems::Item> commands;
+ if (!error) {
+ foreach (DiscoItems::Item item, items->getItems()) {
+ if (item.getNode() != "http://isode.com/xmpp/commands#test") {
+ commands.push_back(item);
+ }
+ }
+ }
+ mainWindow_->setAvailableAdHocCommands(commands);
}
void AdHocManager::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- boost::shared_ptr<RequestAdHocUIEvent> adHocEvent = boost::dynamic_pointer_cast<RequestAdHocUIEvent>(event);
- if (adHocEvent) {
- boost::shared_ptr<OutgoingAdHocCommandSession> command = boost::make_shared<OutgoingAdHocCommandSession>(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_);
- boost::shared_ptr<AdHocController> controller = boost::make_shared<AdHocController>(factory_, command);
- controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
- controllers_.push_back(controller);
- }
- boost::shared_ptr<RequestAdHocWithJIDUIEvent> adHocJIDEvent = boost::dynamic_pointer_cast<RequestAdHocWithJIDUIEvent>(event);
- if (!!adHocJIDEvent) {
- boost::shared_ptr<OutgoingAdHocCommandSession> command = boost::make_shared<OutgoingAdHocCommandSession>(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_);
- boost::shared_ptr<AdHocController> controller = boost::make_shared<AdHocController>(factory_, command);
- controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
- controllers_.push_back(controller);
- }
+ boost::shared_ptr<RequestAdHocUIEvent> adHocEvent = boost::dynamic_pointer_cast<RequestAdHocUIEvent>(event);
+ if (adHocEvent) {
+ boost::shared_ptr<OutgoingAdHocCommandSession> command = boost::make_shared<OutgoingAdHocCommandSession>(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_);
+ boost::shared_ptr<AdHocController> controller = boost::make_shared<AdHocController>(factory_, command);
+ controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
+ controllers_.push_back(controller);
+ }
+ boost::shared_ptr<RequestAdHocWithJIDUIEvent> adHocJIDEvent = boost::dynamic_pointer_cast<RequestAdHocWithJIDUIEvent>(event);
+ if (!!adHocJIDEvent) {
+ boost::shared_ptr<OutgoingAdHocCommandSession> command = boost::make_shared<OutgoingAdHocCommandSession>(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_);
+ boost::shared_ptr<AdHocController> controller = boost::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 00289b0..73c057c 100644
--- a/Swift/Controllers/AdHocManager.h
+++ b/Swift/Controllers/AdHocManager.h
@@ -23,22 +23,22 @@ class UIEventStream;
class AdHocCommandWindowFactory;
class AdHocManager {
public:
- AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow);
- ~AdHocManager();
- void removeController(boost::shared_ptr<AdHocController> contoller);
- void setServerDiscoInfo(boost::shared_ptr<DiscoInfo> info);
- void setOnline(bool online);
+ AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow);
+ ~AdHocManager();
+ void removeController(boost::shared_ptr<AdHocController> contoller);
+ void setServerDiscoInfo(boost::shared_ptr<DiscoInfo> info);
+ void setOnline(bool online);
private:
- void handleServerDiscoItemsResponse(boost::shared_ptr<DiscoItems>, ErrorPayload::ref error);
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- boost::signal<void (const AdHocController&)> onControllerComplete;
- JID jid_;
- IQRouter* iqRouter_;
- UIEventStream* uiEventStream_;
- MainWindow* mainWindow_;
- AdHocCommandWindowFactory* factory_;
- GetDiscoItemsRequest::ref discoItemsRequest_;
- std::vector<boost::shared_ptr<AdHocController> > controllers_;
+ void handleServerDiscoItemsResponse(boost::shared_ptr<DiscoItems>, ErrorPayload::ref error);
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ boost::signal<void (const AdHocController&)> onControllerComplete;
+ JID jid_;
+ IQRouter* iqRouter_;
+ UIEventStream* uiEventStream_;
+ MainWindow* mainWindow_;
+ AdHocCommandWindowFactory* factory_;
+ GetDiscoItemsRequest::ref discoItemsRequest_;
+ std::vector<boost::shared_ptr<AdHocController> > controllers_;
};
}
diff --git a/Swift/Controllers/BlockListController.cpp b/Swift/Controllers/BlockListController.cpp
index 2c8d401..6fbf6b3 100644
--- a/Swift/Controllers/BlockListController.cpp
+++ b/Swift/Controllers/BlockListController.cpp
@@ -28,159 +28,159 @@
namespace Swift {
BlockListController::BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController) : blockListManager_(blockListManager), blockListEditorWidgetFactory_(blockListEditorWidgetFactory), blockListEditorWidget_(0), 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));
+ 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));
+ 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) {
- if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) {
- jidsToUnblock.push_back(jid);
- }
- }
-
- foreach (const JID& jid, newBlockList) {
- if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
- jidsToBlock.push_back(jid);
- }
- }
+ foreach (const JID& jid, blockListBeforeEdit) {
+ if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) {
+ jidsToUnblock.push_back(jid);
+ }
+ }
+
+ foreach (const JID& jid, newBlockList) {
+ if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
+ jidsToBlock.push_back(jid);
+ }
+ }
}
void BlockListController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent) {
- // handle UI dialog
- boost::shared_ptr<RequestBlockListDialogUIEvent> requestDialogEvent = boost::dynamic_pointer_cast<RequestBlockListDialogUIEvent>(rawEvent);
- if (requestDialogEvent != NULL) {
- if (blockListEditorWidget_ == NULL) {
- 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
- boost::shared_ptr<RequestChangeBlockStateUIEvent> changeStateEvent = boost::dynamic_pointer_cast<RequestChangeBlockStateUIEvent>(rawEvent);
- if (changeStateEvent != NULL) {
- 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());
- unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, std::vector<JID>(1, changeStateEvent->getContact()), false));
- unblockRequest->send();
- }
- return;
- }
+ // handle UI dialog
+ boost::shared_ptr<RequestBlockListDialogUIEvent> requestDialogEvent = boost::dynamic_pointer_cast<RequestBlockListDialogUIEvent>(rawEvent);
+ if (requestDialogEvent != NULL) {
+ if (blockListEditorWidget_ == NULL) {
+ 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
+ boost::shared_ptr<RequestChangeBlockStateUIEvent> changeStateEvent = boost::dynamic_pointer_cast<RequestChangeBlockStateUIEvent>(rawEvent);
+ if (changeStateEvent != NULL) {
+ 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());
+ unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, std::vector<JID>(1, changeStateEvent->getContact()), false));
+ unblockRequest->send();
+ }
+ return;
+ }
}
void BlockListController::handleBlockResponse(GenericRequest<BlockPayload>::ref request, boost::shared_ptr<BlockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor) {
- if (error) {
- std::string errorMessage;
- // FIXME: Handle reporting of list of JIDs in a translatable way.
- errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to block %1%.")) % jids.at(0).toString());
- if (!error->getText().empty()) {
- errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText());
- }
- if (blockListEditorWidget_ && originEditor) {
- blockListEditorWidget_->setError(errorMessage);
- blockListEditorWidget_->setBusy(false);
- }
- else {
- eventController_->handleIncomingEvent(boost::make_shared<ErrorEvent>(request->getReceiver(), errorMessage));
- }
- }
- if (originEditor) {
- remainingRequests_--;
- if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) {
- blockListEditorWidget_->setBusy(false);
- blockListEditorWidget_->hide();
- }
- }
+ if (error) {
+ std::string errorMessage;
+ // FIXME: Handle reporting of list of JIDs in a translatable way.
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to block %1%.")) % jids.at(0).toString());
+ if (!error->getText().empty()) {
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText());
+ }
+ if (blockListEditorWidget_ && originEditor) {
+ blockListEditorWidget_->setError(errorMessage);
+ blockListEditorWidget_->setBusy(false);
+ }
+ else {
+ eventController_->handleIncomingEvent(boost::make_shared<ErrorEvent>(request->getReceiver(), errorMessage));
+ }
+ }
+ if (originEditor) {
+ remainingRequests_--;
+ if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) {
+ blockListEditorWidget_->setBusy(false);
+ blockListEditorWidget_->hide();
+ }
+ }
}
void BlockListController::handleUnblockResponse(GenericRequest<UnblockPayload>::ref request, boost::shared_ptr<UnblockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor) {
- if (error) {
- std::string errorMessage;
- // FIXME: Handle reporting of list of JIDs in a translatable way.
- errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to unblock %1%.")) % jids.at(0).toString());
- if (!error->getText().empty()) {
- errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText());
- }
- if (blockListEditorWidget_ && originEditor) {
- blockListEditorWidget_->setError(errorMessage);
- blockListEditorWidget_->setBusy(false);
- }
- else {
- eventController_->handleIncomingEvent(boost::make_shared<ErrorEvent>(request->getReceiver(), errorMessage));
- }
- }
- if (originEditor) {
- remainingRequests_--;
- if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) {
- blockListEditorWidget_->setBusy(false);
- blockListEditorWidget_->hide();
- }
- }
+ if (error) {
+ std::string errorMessage;
+ // FIXME: Handle reporting of list of JIDs in a translatable way.
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to unblock %1%.")) % jids.at(0).toString());
+ if (!error->getText().empty()) {
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText());
+ }
+ if (blockListEditorWidget_ && originEditor) {
+ blockListEditorWidget_->setError(errorMessage);
+ blockListEditorWidget_->setBusy(false);
+ }
+ else {
+ eventController_->handleIncomingEvent(boost::make_shared<ErrorEvent>(request->getReceiver(), errorMessage));
+ }
+ }
+ if (originEditor) {
+ remainingRequests_--;
+ if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) {
+ blockListEditorWidget_->setBusy(false);
+ blockListEditorWidget_->hide();
+ }
+ }
}
void BlockListController::handleSetNewBlockList(const std::vector<JID> &newBlockList) {
- std::vector<JID> jidsToBlock;
- std::vector<JID> jidsToUnblock;
-
- blockListDifferences(newBlockList, jidsToUnblock, jidsToBlock);
-
- 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();
- }
+ std::vector<JID> jidsToBlock;
+ std::vector<JID> jidsToUnblock;
+
+ blockListDifferences(newBlockList, jidsToUnblock, jidsToBlock);
+
+ 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;
+ if (blockListEditorWidget_) {
+ std::vector<JID> jidsToBlock;
+ std::vector<JID> jidsToUnblock;
- blockListDifferences(blockListEditorWidget_->getCurrentBlockList(), jidsToUnblock, jidsToBlock);
- blockListBeforeEdit = blockListManager_->getBlockList()->getItems();
+ blockListDifferences(blockListEditorWidget_->getCurrentBlockList(), jidsToUnblock, jidsToBlock);
+ blockListBeforeEdit = blockListManager_->getBlockList()->getItems();
- foreach (const JID& jid, jidsToBlock) {
- if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
- blockListBeforeEdit.push_back(jid);
- }
- }
+ foreach (const JID& jid, jidsToBlock) {
+ if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) {
+ blockListBeforeEdit.push_back(jid);
+ }
+ }
- foreach (const JID& jid, jidsToUnblock) {
- blockListBeforeEdit.erase(std::remove(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid), blockListBeforeEdit.end());
- }
+ foreach (const JID& jid, jidsToUnblock) {
+ blockListBeforeEdit.erase(std::remove(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid), blockListBeforeEdit.end());
+ }
- blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit);
- }
+ blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit);
+ }
}
}
diff --git a/Swift/Controllers/BlockListController.h b/Swift/Controllers/BlockListController.h
index c911344..f9ee5a6 100644
--- a/Swift/Controllers/BlockListController.h
+++ b/Swift/Controllers/BlockListController.h
@@ -28,29 +28,29 @@ class EventController;
class BlockListController {
public:
- BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController);
- ~BlockListController();
+ BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController);
+ ~BlockListController();
private:
- void blockListDifferences(const std::vector<JID> &newBlockList, std::vector<JID>& jidsToUnblock, std::vector<JID>& jidsToBlock) const;
+ void blockListDifferences(const std::vector<JID> &newBlockList, std::vector<JID>& jidsToUnblock, std::vector<JID>& jidsToBlock) const;
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleBlockResponse(GenericRequest<BlockPayload>::ref, boost::shared_ptr<BlockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor);
- void handleUnblockResponse(GenericRequest<UnblockPayload>::ref, boost::shared_ptr<UnblockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor);
+ void handleBlockResponse(GenericRequest<BlockPayload>::ref, boost::shared_ptr<BlockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor);
+ void handleUnblockResponse(GenericRequest<UnblockPayload>::ref, boost::shared_ptr<UnblockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor);
- void handleSetNewBlockList(const std::vector<JID>& newBlockList);
+ void handleSetNewBlockList(const std::vector<JID>& newBlockList);
- void handleBlockListChanged();
+ void handleBlockListChanged();
private:
- ClientBlockListManager* blockListManager_;
- BlockListEditorWidgetFactory* blockListEditorWidgetFactory_;
- BlockListEditorWidget* blockListEditorWidget_;
- EventController* eventController_;
- std::vector<JID> blockListBeforeEdit;
- int remainingRequests_;
- UIEventStream* uiEventStream_;
+ ClientBlockListManager* blockListManager_;
+ BlockListEditorWidgetFactory* blockListEditorWidgetFactory_;
+ BlockListEditorWidget* blockListEditorWidget_;
+ EventController* eventController_;
+ std::vector<JID> blockListBeforeEdit;
+ int remainingRequests_;
+ UIEventStream* uiEventStream_;
};
}
diff --git a/Swift/Controllers/CertificateMemoryStorageFactory.h b/Swift/Controllers/CertificateMemoryStorageFactory.h
index de9f3fe..080b157 100644
--- a/Swift/Controllers/CertificateMemoryStorageFactory.h
+++ b/Swift/Controllers/CertificateMemoryStorageFactory.h
@@ -10,19 +10,19 @@
#include <Swift/Controllers/Storages/CertificateStorageFactory.h>
namespace Swift {
- class CertificateFactory;
+ class CertificateFactory;
- class CertificateMemoryStorageFactory : public CertificateStorageFactory {
- public:
- CertificateMemoryStorageFactory() {
- }
+ class CertificateMemoryStorageFactory : public CertificateStorageFactory {
+ public:
+ CertificateMemoryStorageFactory() {
+ }
- virtual CertificateStorage* createCertificateStorage(const JID&) const {
- return new CertificateMemoryStorage();
- }
+ virtual CertificateStorage* createCertificateStorage(const JID&) const {
+ return new CertificateMemoryStorage();
+ }
- private:
- boost::filesystem::path basePath;
- CertificateFactory* certificateFactory;
- };
+ private:
+ boost::filesystem::path basePath;
+ CertificateFactory* certificateFactory;
+ };
}
diff --git a/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h b/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h
index 8ea6dff..646612b 100644
--- a/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h
+++ b/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h
@@ -19,36 +19,36 @@
#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
- class AutoAcceptMUCInviteDecider {
- public:
- AutoAcceptMUCInviteDecider(const JID& domain, XMPPRoster* roster, SettingsProvider* settings) : domain_(domain), roster_(roster), settings_(settings) {
- }
-
- bool isAutoAcceptedInvite(const JID& from, MUCInvitationPayload::ref invite) {
- if (!invite->getIsImpromptu()) {
- return false; /* always ask the user for normal MUC invites */
- }
-
- if (invite->getIsContinuation()) {
- return true;
- }
-
- std::string auto_accept_mode = settings_->getSetting(SettingConstants::INVITE_AUTO_ACCEPT_MODE);
- if (auto_accept_mode == "no") {
- return false;
- } else if (auto_accept_mode == "presence") {
- return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both;
- } else if (auto_accept_mode == "domain") {
- return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both || from.getDomain() == domain_;
- } else {
- assert(false);
- return false;
- }
- }
-
- private:
- JID domain_;
- XMPPRoster* roster_;
- SettingsProvider* settings_;
- };
+ class AutoAcceptMUCInviteDecider {
+ public:
+ AutoAcceptMUCInviteDecider(const JID& domain, XMPPRoster* roster, SettingsProvider* settings) : domain_(domain), roster_(roster), settings_(settings) {
+ }
+
+ bool isAutoAcceptedInvite(const JID& from, MUCInvitationPayload::ref invite) {
+ if (!invite->getIsImpromptu()) {
+ return false; /* always ask the user for normal MUC invites */
+ }
+
+ if (invite->getIsContinuation()) {
+ return true;
+ }
+
+ std::string auto_accept_mode = settings_->getSetting(SettingConstants::INVITE_AUTO_ACCEPT_MODE);
+ if (auto_accept_mode == "no") {
+ return false;
+ } else if (auto_accept_mode == "presence") {
+ return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both;
+ } else if (auto_accept_mode == "domain") {
+ return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both || from.getDomain() == domain_;
+ } else {
+ assert(false);
+ return false;
+ }
+ }
+
+ private:
+ JID domain_;
+ XMPPRoster* roster_;
+ SettingsProvider* settings_;
+ };
}
diff --git a/Swift/Controllers/Chat/ChatController.cpp b/Swift/Controllers/Chat/ChatController.cpp
index 7f62c36..5302492 100644
--- a/Swift/Controllers/Chat/ChatController.cpp
+++ b/Swift/Controllers/Chat/ChatController.cpp
@@ -45,489 +45,489 @@
#include <Swift/Controllers/XMPPEvents/EventController.h>
namespace Swift {
-
+
/**
* The controller does not gain ownership of the stanzaChannel, nor the factory.
*/
ChatController::ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider)
- : ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, contact, presenceOracle, avatarManager, useDelayForLatency, eventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), eventStream_(eventStream), userWantsReceipts_(userWantsReceipts), settings_(settings), clientBlockListManager_(clientBlockListManager) {
- isInMUC_ = isInMUC;
- lastWasPresence_ = false;
- chatStateNotifier_ = new ChatStateNotifier(stanzaChannel, contact, entityCapsProvider);
- chatStateTracker_ = new ChatStateTracker();
- nickResolver_ = nickResolver;
- presenceOracle_->onPresenceChange.connect(boost::bind(&ChatController::handlePresenceChange, this, _1));
- chatStateTracker_->onChatStateChange.connect(boost::bind(&ChatWindow::setContactChatState, chatWindow_, _1));
- stanzaChannel_->onStanzaAcked.connect(boost::bind(&ChatController::handleStanzaAcked, this, _1));
- nickResolver_->onNickChanged.connect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2));
- std::string nick = nickResolver_->jidToNick(toJID_);
- chatWindow_->setName(nick);
- std::string startMessage;
- Presence::ref theirPresence;
- if (isInMUC) {
- startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% in chatroom %2%")) % nick % contact.toBare().toString());
- theirPresence = presenceOracle->getLastPresence(contact);
- } else {
- startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% - %2%")) % nick % contact.toBare().toString());
- theirPresence = contact.isBare() ? presenceOracle->getAccountPresence(contact) : presenceOracle->getLastPresence(contact);
- }
- Idle::ref idle;
- if (theirPresence && (idle = theirPresence->getPayload<Idle>())) {
- startMessage += str(format(QT_TRANSLATE_NOOP("", ", who has been idle since %1%")) % dateTimeToLocalString(idle->getSince()));
- }
- startMessage += ": " + statusShowTypeToFriendlyName(theirPresence ? theirPresence->getShow() : StatusShow::None);
- if (theirPresence && !theirPresence->getStatus().empty()) {
- startMessage += " (" + theirPresence->getStatus() + ")";
- }
- lastShownStatus_ = theirPresence ? theirPresence->getShow() : StatusShow::None;
- chatStateNotifier_->setContactIsOnline(theirPresence && theirPresence->getType() == Presence::Available);
- startMessage += ".";
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(startMessage), ChatWindow::DefaultDirection);
- chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
- chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
- chatWindow_->onFileTransferStart.connect(boost::bind(&ChatController::handleFileTransferStart, this, _1, _2));
- chatWindow_->onFileTransferAccept.connect(boost::bind(&ChatController::handleFileTransferAccept, this, _1, _2));
- chatWindow_->onFileTransferCancel.connect(boost::bind(&ChatController::handleFileTransferCancel, this, _1));
- chatWindow_->onSendFileRequest.connect(boost::bind(&ChatController::handleSendFileRequest, this, _1));
- chatWindow_->onWhiteboardSessionAccept.connect(boost::bind(&ChatController::handleWhiteboardSessionAccept, this));
- chatWindow_->onWhiteboardSessionCancel.connect(boost::bind(&ChatController::handleWhiteboardSessionCancel, this));
- chatWindow_->onWhiteboardWindowShow.connect(boost::bind(&ChatController::handleWhiteboardWindowShow, this));
- chatWindow_->onBlockUserRequest.connect(boost::bind(&ChatController::handleBlockUserRequest, this));
- chatWindow_->onUnblockUserRequest.connect(boost::bind(&ChatController::handleUnblockUserRequest, this));
- chatWindow_->onInviteToChat.connect(boost::bind(&ChatController::handleInviteToChat, this, _1));
- chatWindow_->onClosed.connect(boost::bind(&ChatController::handleWindowClosed, this));
- ChatController::handleBareJIDCapsChanged(toJID_);
-
- settings_->onSettingChanged.connect(boost::bind(&ChatController::handleSettingChanged, this, _1));
- eventStream_->onUIEvent.connect(boost::bind(&ChatController::handleUIEvent, this, _1));
+ : ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, contact, presenceOracle, avatarManager, useDelayForLatency, eventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), eventStream_(eventStream), userWantsReceipts_(userWantsReceipts), settings_(settings), clientBlockListManager_(clientBlockListManager) {
+ isInMUC_ = isInMUC;
+ lastWasPresence_ = false;
+ chatStateNotifier_ = new ChatStateNotifier(stanzaChannel, contact, entityCapsProvider);
+ chatStateTracker_ = new ChatStateTracker();
+ nickResolver_ = nickResolver;
+ presenceOracle_->onPresenceChange.connect(boost::bind(&ChatController::handlePresenceChange, this, _1));
+ chatStateTracker_->onChatStateChange.connect(boost::bind(&ChatWindow::setContactChatState, chatWindow_, _1));
+ stanzaChannel_->onStanzaAcked.connect(boost::bind(&ChatController::handleStanzaAcked, this, _1));
+ nickResolver_->onNickChanged.connect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2));
+ std::string nick = nickResolver_->jidToNick(toJID_);
+ chatWindow_->setName(nick);
+ std::string startMessage;
+ Presence::ref theirPresence;
+ if (isInMUC) {
+ startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% in chatroom %2%")) % nick % contact.toBare().toString());
+ theirPresence = presenceOracle->getLastPresence(contact);
+ } else {
+ startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% - %2%")) % nick % contact.toBare().toString());
+ theirPresence = contact.isBare() ? presenceOracle->getAccountPresence(contact) : presenceOracle->getLastPresence(contact);
+ }
+ Idle::ref idle;
+ if (theirPresence && (idle = theirPresence->getPayload<Idle>())) {
+ startMessage += str(format(QT_TRANSLATE_NOOP("", ", who has been idle since %1%")) % dateTimeToLocalString(idle->getSince()));
+ }
+ startMessage += ": " + statusShowTypeToFriendlyName(theirPresence ? theirPresence->getShow() : StatusShow::None);
+ if (theirPresence && !theirPresence->getStatus().empty()) {
+ startMessage += " (" + theirPresence->getStatus() + ")";
+ }
+ lastShownStatus_ = theirPresence ? theirPresence->getShow() : StatusShow::None;
+ chatStateNotifier_->setContactIsOnline(theirPresence && theirPresence->getType() == Presence::Available);
+ startMessage += ".";
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(startMessage), ChatWindow::DefaultDirection);
+ chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
+ chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
+ chatWindow_->onFileTransferStart.connect(boost::bind(&ChatController::handleFileTransferStart, this, _1, _2));
+ chatWindow_->onFileTransferAccept.connect(boost::bind(&ChatController::handleFileTransferAccept, this, _1, _2));
+ chatWindow_->onFileTransferCancel.connect(boost::bind(&ChatController::handleFileTransferCancel, this, _1));
+ chatWindow_->onSendFileRequest.connect(boost::bind(&ChatController::handleSendFileRequest, this, _1));
+ chatWindow_->onWhiteboardSessionAccept.connect(boost::bind(&ChatController::handleWhiteboardSessionAccept, this));
+ chatWindow_->onWhiteboardSessionCancel.connect(boost::bind(&ChatController::handleWhiteboardSessionCancel, this));
+ chatWindow_->onWhiteboardWindowShow.connect(boost::bind(&ChatController::handleWhiteboardWindowShow, this));
+ chatWindow_->onBlockUserRequest.connect(boost::bind(&ChatController::handleBlockUserRequest, this));
+ chatWindow_->onUnblockUserRequest.connect(boost::bind(&ChatController::handleUnblockUserRequest, this));
+ chatWindow_->onInviteToChat.connect(boost::bind(&ChatController::handleInviteToChat, this, _1));
+ chatWindow_->onClosed.connect(boost::bind(&ChatController::handleWindowClosed, this));
+ ChatController::handleBareJIDCapsChanged(toJID_);
+
+ settings_->onSettingChanged.connect(boost::bind(&ChatController::handleSettingChanged, this, _1));
+ eventStream_->onUIEvent.connect(boost::bind(&ChatController::handleUIEvent, this, _1));
}
void ChatController::handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/) {
- if (jid.toBare() == toJID_.toBare()) {
- chatWindow_->setName(nickResolver_->jidToNick(toJID_));
- }
+ if (jid.toBare() == toJID_.toBare()) {
+ chatWindow_->setName(nickResolver_->jidToNick(toJID_));
+ }
}
ChatController::~ChatController() {
- eventStream_->onUIEvent.disconnect(boost::bind(&ChatController::handleUIEvent, this, _1));
- settings_->onSettingChanged.disconnect(boost::bind(&ChatController::handleSettingChanged, this, _1));
- nickResolver_->onNickChanged.disconnect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2));
- delete chatStateNotifier_;
- delete chatStateTracker_;
+ eventStream_->onUIEvent.disconnect(boost::bind(&ChatController::handleUIEvent, this, _1));
+ settings_->onSettingChanged.disconnect(boost::bind(&ChatController::handleSettingChanged, this, _1));
+ nickResolver_->onNickChanged.disconnect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2));
+ delete chatStateNotifier_;
+ delete chatStateTracker_;
}
JID ChatController::getBaseJID() {
- return isInMUC_ ? toJID_ : ChatControllerBase::getBaseJID();
+ return isInMUC_ ? toJID_ : ChatControllerBase::getBaseJID();
}
void ChatController::cancelReplaces() {
- lastWasPresence_ = false;
+ lastWasPresence_ = false;
}
void ChatController::handleBareJIDCapsChanged(const JID& /*jid*/) {
- FeatureOracle featureOracle(entityCapsProvider_, presenceOracle_);
+ FeatureOracle featureOracle(entityCapsProvider_, presenceOracle_);
- chatWindow_->setCorrectionEnabled(featureOracle.isMessageCorrectionSupported(toJID_));
- chatWindow_->setFileTransferEnabled(isInMUC_ ? No : featureOracle.isFileTransferSupported(toJID_));
- contactSupportsReceipts_ = featureOracle.isMessageReceiptsSupported(toJID_);
+ chatWindow_->setCorrectionEnabled(featureOracle.isMessageCorrectionSupported(toJID_));
+ chatWindow_->setFileTransferEnabled(isInMUC_ ? No : featureOracle.isFileTransferSupported(toJID_));
+ contactSupportsReceipts_ = featureOracle.isMessageReceiptsSupported(toJID_);
- checkForDisplayingDisplayReceiptsAlert();
+ checkForDisplayingDisplayReceiptsAlert();
}
void ChatController::setToJID(const JID& jid) {
- chatStateNotifier_->setContact(jid);
- ChatControllerBase::setToJID(jid);
- Presence::ref presence;
- if (isInMUC_) {
- presence = presenceOracle_->getLastPresence(jid);
- } else {
- presence = jid.isBare() ? presenceOracle_->getAccountPresence(jid.toBare()) : presenceOracle_->getLastPresence(jid);
- }
- chatStateNotifier_->setContactIsOnline(presence && presence->getType() == Presence::Available);
- handleBareJIDCapsChanged(toJID_);
+ chatStateNotifier_->setContact(jid);
+ ChatControllerBase::setToJID(jid);
+ Presence::ref presence;
+ if (isInMUC_) {
+ presence = presenceOracle_->getLastPresence(jid);
+ } else {
+ presence = jid.isBare() ? presenceOracle_->getAccountPresence(jid.toBare()) : presenceOracle_->getLastPresence(jid);
+ }
+ chatStateNotifier_->setContactIsOnline(presence && presence->getType() == Presence::Available);
+ handleBareJIDCapsChanged(toJID_);
}
void ChatController::setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) {
- ChatControllerBase::setAvailableServerFeatures(info);
- if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ ChatControllerBase::setAvailableServerFeatures(info);
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
- blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
- blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
- blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+ blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+ blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+ blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
- handleBlockingStateChanged();
- }
+ handleBlockingStateChanged();
+ }
}
bool ChatController::isIncomingMessageFromMe(boost::shared_ptr<Message>) {
- return false;
+ return false;
}
void ChatController::preHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent) {
- if (messageEvent->isReadable()) {
- chatWindow_->flash();
- lastWasPresence_ = false;
- }
- boost::shared_ptr<Message> message = messageEvent->getStanza();
- JID from = message->getFrom();
- if (!from.equals(toJID_, JID::WithResource)) {
- if (toJID_.equals(from, JID::WithoutResource) && toJID_.isBare()){
- // Bind controller to a full JID if message contains body text or is a typing chat state.
- ChatState::ref chatState = message->getPayload<ChatState>();
- if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) {
- setToJID(from);
- }
- }
- }
- chatStateTracker_->handleMessageReceived(message);
- chatStateNotifier_->receivedMessageFromContact(!!message->getPayload<ChatState>());
-
- // handle XEP-0184 Message Receipts
- // incomming receipts
- if (boost::shared_ptr<DeliveryReceipt> receipt = message->getPayload<DeliveryReceipt>()) {
- SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID() << std::endl;
- if (requestedReceipts_.find(receipt->getReceivedID()) != requestedReceipts_.end()) {
- chatWindow_->setMessageReceiptState(requestedReceipts_[receipt->getReceivedID()], ChatWindow::ReceiptReceived);
- requestedReceipts_.erase(receipt->getReceivedID());
- }
- // incomming errors in response to send out receipts
- } else if (message->getPayload<DeliveryReceiptRequest>() && (message->getType() == Message::Error)) {
- if (requestedReceipts_.find(message->getID()) != requestedReceipts_.end()) {
- chatWindow_->setMessageReceiptState(requestedReceipts_[message->getID()], ChatWindow::ReceiptFailed);
- requestedReceipts_.erase(message->getID());
- }
- // incoming receipt requests
- } else if (message->getPayload<DeliveryReceiptRequest>()) {
- if (receivingPresenceFromUs_) {
- boost::shared_ptr<Message> receiptMessage = boost::make_shared<Message>();
- receiptMessage->setTo(toJID_);
- receiptMessage->addPayload(boost::make_shared<DeliveryReceipt>(message->getID()));
- stanzaChannel_->sendMessage(receiptMessage);
- }
- }
+ if (messageEvent->isReadable()) {
+ chatWindow_->flash();
+ lastWasPresence_ = false;
+ }
+ boost::shared_ptr<Message> message = messageEvent->getStanza();
+ JID from = message->getFrom();
+ if (!from.equals(toJID_, JID::WithResource)) {
+ if (toJID_.equals(from, JID::WithoutResource) && toJID_.isBare()){
+ // Bind controller to a full JID if message contains body text or is a typing chat state.
+ ChatState::ref chatState = message->getPayload<ChatState>();
+ if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) {
+ setToJID(from);
+ }
+ }
+ }
+ chatStateTracker_->handleMessageReceived(message);
+ chatStateNotifier_->receivedMessageFromContact(!!message->getPayload<ChatState>());
+
+ // handle XEP-0184 Message Receipts
+ // incomming receipts
+ if (boost::shared_ptr<DeliveryReceipt> receipt = message->getPayload<DeliveryReceipt>()) {
+ SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID() << std::endl;
+ if (requestedReceipts_.find(receipt->getReceivedID()) != requestedReceipts_.end()) {
+ chatWindow_->setMessageReceiptState(requestedReceipts_[receipt->getReceivedID()], ChatWindow::ReceiptReceived);
+ requestedReceipts_.erase(receipt->getReceivedID());
+ }
+ // incomming errors in response to send out receipts
+ } else if (message->getPayload<DeliveryReceiptRequest>() && (message->getType() == Message::Error)) {
+ if (requestedReceipts_.find(message->getID()) != requestedReceipts_.end()) {
+ chatWindow_->setMessageReceiptState(requestedReceipts_[message->getID()], ChatWindow::ReceiptFailed);
+ requestedReceipts_.erase(message->getID());
+ }
+ // incoming receipt requests
+ } else if (message->getPayload<DeliveryReceiptRequest>()) {
+ if (receivingPresenceFromUs_) {
+ boost::shared_ptr<Message> receiptMessage = boost::make_shared<Message>();
+ receiptMessage->setTo(toJID_);
+ receiptMessage->addPayload(boost::make_shared<DeliveryReceipt>(message->getID()));
+ stanzaChannel_->sendMessage(receiptMessage);
+ }
+ }
}
void ChatController::postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) {
- eventController_->handleIncomingEvent(messageEvent);
- if (!messageEvent->getConcluded()) {
- handleHighlightActions(chatMessage);
- }
+ eventController_->handleIncomingEvent(messageEvent);
+ if (!messageEvent->getConcluded()) {
+ handleHighlightActions(chatMessage);
+ }
}
void ChatController::preSendMessageRequest(boost::shared_ptr<Message> message) {
- chatStateNotifier_->addChatStateRequest(message);
- if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) {
- message->addPayload(boost::make_shared<DeliveryReceiptRequest>());
- }
+ chatStateNotifier_->addChatStateRequest(message);
+ if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) {
+ message->addPayload(boost::make_shared<DeliveryReceiptRequest>());
+ }
}
void ChatController::setContactIsReceivingPresence(bool isReceivingPresence) {
- receivingPresenceFromUs_ = isReceivingPresence;
+ receivingPresenceFromUs_ = isReceivingPresence;
}
void ChatController::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
- userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
- checkForDisplayingDisplayReceiptsAlert();
- }
+ if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
+ userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
+ checkForDisplayingDisplayReceiptsAlert();
+ }
}
void ChatController::checkForDisplayingDisplayReceiptsAlert() {
- boost::optional<ChatWindow::AlertID> newDeliverReceiptAlert;
- if (userWantsReceipts_ && (contactSupportsReceipts_ == No)) {
- newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat doesn't support delivery receipts."));
- } else if (userWantsReceipts_ && (contactSupportsReceipts_ == Maybe)) {
- newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat may not support delivery receipts. You might not receive delivery receipts for the messages you send."));
- } else {
- if (deliveryReceiptAlert_) {
- chatWindow_->removeAlert(*deliveryReceiptAlert_);
- deliveryReceiptAlert_.reset();
- }
- }
- if (newDeliverReceiptAlert) {
- if (deliveryReceiptAlert_) {
- chatWindow_->removeAlert(*deliveryReceiptAlert_);
- }
- deliveryReceiptAlert_ = newDeliverReceiptAlert;
- }
+ boost::optional<ChatWindow::AlertID> newDeliverReceiptAlert;
+ if (userWantsReceipts_ && (contactSupportsReceipts_ == No)) {
+ newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat doesn't support delivery receipts."));
+ } else if (userWantsReceipts_ && (contactSupportsReceipts_ == Maybe)) {
+ newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat may not support delivery receipts. You might not receive delivery receipts for the messages you send."));
+ } else {
+ if (deliveryReceiptAlert_) {
+ chatWindow_->removeAlert(*deliveryReceiptAlert_);
+ deliveryReceiptAlert_.reset();
+ }
+ }
+ if (newDeliverReceiptAlert) {
+ if (deliveryReceiptAlert_) {
+ chatWindow_->removeAlert(*deliveryReceiptAlert_);
+ }
+ deliveryReceiptAlert_ = newDeliverReceiptAlert;
+ }
}
void ChatController::handleBlockingStateChanged() {
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
- if (blockList->getState() == BlockList::Available) {
- if (isInMUC_ ? blockList->isBlocked(toJID_) : blockList->isBlocked(toJID_.toBare())) {
- if (!blockedContactAlert_) {
- blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've currently blocked this contact. To continue your conversation you have to unblock the contact first."));
- }
- chatWindow_->setBlockingState(ChatWindow::IsBlocked);
-
- // disconnect typing events to prevent chat state notifciations to blocked contacts
- chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
- chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
- } else {
- if (blockedContactAlert_) {
- chatWindow_->removeAlert(*blockedContactAlert_);
- blockedContactAlert_.reset();
- }
- chatWindow_->setBlockingState(ChatWindow::IsUnblocked);
-
- chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
- chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
- }
- }
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ if (blockList->getState() == BlockList::Available) {
+ if (isInMUC_ ? blockList->isBlocked(toJID_) : blockList->isBlocked(toJID_.toBare())) {
+ if (!blockedContactAlert_) {
+ blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've currently blocked this contact. To continue your conversation you have to unblock the contact first."));
+ }
+ chatWindow_->setBlockingState(ChatWindow::IsBlocked);
+
+ // disconnect typing events to prevent chat state notifciations to blocked contacts
+ chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
+ chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
+ } else {
+ if (blockedContactAlert_) {
+ chatWindow_->removeAlert(*blockedContactAlert_);
+ blockedContactAlert_.reset();
+ }
+ chatWindow_->setBlockingState(ChatWindow::IsUnblocked);
+
+ chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
+ chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
+ }
+ }
}
void ChatController::handleBlockUserRequest() {
- if (isInMUC_) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, toJID_));
- } else {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, toJID_.toBare()));
- }
+ if (isInMUC_) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, toJID_));
+ } else {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, toJID_.toBare()));
+ }
}
void ChatController::handleUnblockUserRequest() {
- if (isInMUC_) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, toJID_));
- } else {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, toJID_.toBare()));
- }
+ if (isInMUC_) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, toJID_));
+ } else {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, toJID_.toBare()));
+ }
}
void ChatController::handleInviteToChat(const std::vector<JID>& droppedJIDs) {
- boost::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(toJID_.toBare(), droppedJIDs, RequestInviteToMUCUIEvent::Impromptu));
- eventStream_->send(event);
+ boost::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(toJID_.toBare(), droppedJIDs, RequestInviteToMUCUIEvent::Impromptu));
+ eventStream_->send(event);
}
void ChatController::handleWindowClosed() {
- onWindowClosed();
+ onWindowClosed();
}
void ChatController::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- boost::shared_ptr<InviteToMUCUIEvent> inviteEvent = boost::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
- if (inviteEvent && inviteEvent->getRoom() == toJID_.toBare()) {
- onConvertToMUC(detachChatWindow(), inviteEvent->getInvites(), inviteEvent->getReason());
- }
+ boost::shared_ptr<InviteToMUCUIEvent> inviteEvent = boost::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
+ if (inviteEvent && inviteEvent->getRoom() == toJID_.toBare()) {
+ onConvertToMUC(detachChatWindow(), inviteEvent->getInvites(), inviteEvent->getReason());
+ }
}
void ChatController::postSendMessage(const std::string& body, boost::shared_ptr<Stanza> sentStanza) {
- boost::shared_ptr<Replace> replace = sentStanza->getPayload<Replace>();
- if (replace) {
- eraseIf(unackedStanzas_, PairSecondEquals<boost::shared_ptr<Stanza>, std::string>(myLastMessageUIID_));
- replaceMessage(chatMessageParser_->parseMessageBody(body, "", true), myLastMessageUIID_, boost::posix_time::microsec_clock::universal_time());
- } else {
- myLastMessageUIID_ = addMessage(chatMessageParser_->parseMessageBody(body, "", true), QT_TRANSLATE_NOOP("", "me"), true, labelsEnabled_ ? chatWindow_->getSelectedSecurityLabel().getLabel() : boost::shared_ptr<SecurityLabel>(), avatarManager_->getAvatarPath(selfJID_), boost::posix_time::microsec_clock::universal_time());
- }
+ boost::shared_ptr<Replace> replace = sentStanza->getPayload<Replace>();
+ if (replace) {
+ eraseIf(unackedStanzas_, PairSecondEquals<boost::shared_ptr<Stanza>, std::string>(myLastMessageUIID_));
+ replaceMessage(chatMessageParser_->parseMessageBody(body, "", true), myLastMessageUIID_, boost::posix_time::microsec_clock::universal_time());
+ } else {
+ myLastMessageUIID_ = addMessage(chatMessageParser_->parseMessageBody(body, "", true), QT_TRANSLATE_NOOP("", "me"), true, labelsEnabled_ ? chatWindow_->getSelectedSecurityLabel().getLabel() : boost::shared_ptr<SecurityLabel>(), avatarManager_->getAvatarPath(selfJID_), boost::posix_time::microsec_clock::universal_time());
+ }
- if (stanzaChannel_->getStreamManagementEnabled() && !myLastMessageUIID_.empty() ) {
- chatWindow_->setAckState(myLastMessageUIID_, ChatWindow::Pending);
- unackedStanzas_[sentStanza] = myLastMessageUIID_;
- }
+ if (stanzaChannel_->getStreamManagementEnabled() && !myLastMessageUIID_.empty() ) {
+ chatWindow_->setAckState(myLastMessageUIID_, ChatWindow::Pending);
+ unackedStanzas_[sentStanza] = myLastMessageUIID_;
+ }
- if (sentStanza->getPayload<DeliveryReceiptRequest>()) {
- requestedReceipts_[sentStanza->getID()] = myLastMessageUIID_;
- chatWindow_->setMessageReceiptState(myLastMessageUIID_, ChatWindow::ReceiptRequested);
- }
+ if (sentStanza->getPayload<DeliveryReceiptRequest>()) {
+ requestedReceipts_[sentStanza->getID()] = myLastMessageUIID_;
+ chatWindow_->setMessageReceiptState(myLastMessageUIID_, ChatWindow::ReceiptRequested);
+ }
- lastWasPresence_ = false;
- chatStateNotifier_->userSentMessage();
+ lastWasPresence_ = false;
+ chatStateNotifier_->userSentMessage();
}
void ChatController::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
- std::map<boost::shared_ptr<Stanza>, std::string>::iterator unackedStanza = unackedStanzas_.find(stanza);
- if (unackedStanza != unackedStanzas_.end()) {
- chatWindow_->setAckState(unackedStanza->second, ChatWindow::Received);
- unackedStanzas_.erase(unackedStanza);
- }
+ std::map<boost::shared_ptr<Stanza>, std::string>::iterator unackedStanza = unackedStanzas_.find(stanza);
+ if (unackedStanza != unackedStanzas_.end()) {
+ chatWindow_->setAckState(unackedStanza->second, ChatWindow::Received);
+ unackedStanzas_.erase(unackedStanza);
+ }
}
void ChatController::setOnline(bool online) {
- if (!online) {
- std::map<boost::shared_ptr<Stanza>, std::string>::iterator it = unackedStanzas_.begin();
- for ( ; it != unackedStanzas_.end(); ++it) {
- chatWindow_->setAckState(it->second, ChatWindow::Failed);
- }
- unackedStanzas_.clear();
+ if (!online) {
+ std::map<boost::shared_ptr<Stanza>, std::string>::iterator it = unackedStanzas_.begin();
+ for ( ; it != unackedStanzas_.end(); ++it) {
+ chatWindow_->setAckState(it->second, ChatWindow::Failed);
+ }
+ unackedStanzas_.clear();
- Presence::ref fakeOffline(new Presence());
- fakeOffline->setFrom(toJID_);
- fakeOffline->setType(Presence::Unavailable);
- chatStateTracker_->handlePresenceChange(fakeOffline);
- }
- ChatControllerBase::setOnline(online);
+ Presence::ref fakeOffline(new Presence());
+ fakeOffline->setFrom(toJID_);
+ fakeOffline->setType(Presence::Unavailable);
+ chatStateTracker_->handlePresenceChange(fakeOffline);
+ }
+ ChatControllerBase::setOnline(online);
}
void ChatController::handleNewFileTransferController(FileTransferController* ftc) {
- std::string nick = senderDisplayNameFromMessage(ftc->getOtherParty());
- std::string ftID = ftc->setChatWindow(chatWindow_, nick);
- ftControllers[ftID] = ftc;
- lastWasPresence_ = false;
+ std::string nick = senderDisplayNameFromMessage(ftc->getOtherParty());
+ std::string ftID = ftc->setChatWindow(chatWindow_, nick);
+ ftControllers[ftID] = ftc;
+ lastWasPresence_ = false;
}
void ChatController::handleWhiteboardSessionRequest(bool senderIsSelf) {
- lastWbID_ = chatWindow_->addWhiteboardRequest(senderIsSelf);
+ lastWbID_ = chatWindow_->addWhiteboardRequest(senderIsSelf);
}
void ChatController::handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state) {
- chatWindow_->setWhiteboardSessionStatus(lastWbID_, state);
+ chatWindow_->setWhiteboardSessionStatus(lastWbID_, state);
}
void ChatController::handleFileTransferCancel(std::string id) {
- SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")" << std::endl;
- if (ftControllers.find(id) != ftControllers.end()) {
- ftControllers[id]->cancel();
- } else {
- std::cerr << "unknown file transfer UI id" << std::endl;
- }
+ SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")" << std::endl;
+ if (ftControllers.find(id) != ftControllers.end()) {
+ ftControllers[id]->cancel();
+ } else {
+ std::cerr << "unknown file transfer UI id" << std::endl;
+ }
}
void ChatController::handleFileTransferStart(std::string id, std::string description) {
- SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")" << std::endl;
- if (ftControllers.find(id) != ftControllers.end()) {
- ftControllers[id]->start(description);
- } else {
- std::cerr << "unknown file transfer UI id" << std::endl;
- }
+ SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")" << std::endl;
+ if (ftControllers.find(id) != ftControllers.end()) {
+ ftControllers[id]->start(description);
+ } else {
+ std::cerr << "unknown file transfer UI id" << std::endl;
+ }
}
void ChatController::handleFileTransferAccept(std::string id, std::string filename) {
- SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")" << std::endl;
- if (ftControllers.find(id) != ftControllers.end()) {
- ftControllers[id]->accept(filename);
- } else {
- std::cerr << "unknown file transfer UI id" << std::endl;
- }
+ SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")" << std::endl;
+ if (ftControllers.find(id) != ftControllers.end()) {
+ ftControllers[id]->accept(filename);
+ } else {
+ std::cerr << "unknown file transfer UI id" << std::endl;
+ }
}
void ChatController::handleSendFileRequest(std::string filename) {
- SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")" << std::endl;
- eventStream_->send(boost::make_shared<SendFileUIEvent>(getToJID(), filename));
+ SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")" << std::endl;
+ eventStream_->send(boost::make_shared<SendFileUIEvent>(getToJID(), filename));
}
void ChatController::handleWhiteboardSessionAccept() {
- eventStream_->send(boost::make_shared<AcceptWhiteboardSessionUIEvent>(toJID_));
+ eventStream_->send(boost::make_shared<AcceptWhiteboardSessionUIEvent>(toJID_));
}
void ChatController::handleWhiteboardSessionCancel() {
- eventStream_->send(boost::make_shared<CancelWhiteboardSessionUIEvent>(toJID_));
+ eventStream_->send(boost::make_shared<CancelWhiteboardSessionUIEvent>(toJID_));
}
void ChatController::handleWhiteboardWindowShow() {
- eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(toJID_));
+ eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(toJID_));
}
std::string ChatController::senderHighlightNameFromMessage(const JID& from) {
- if (isInMUC_) {
- return nickResolver_->jidToNick(from);
- }
- else {
- return from.toBare().toString();
- }
+ if (isInMUC_) {
+ return nickResolver_->jidToNick(from);
+ }
+ else {
+ return from.toBare().toString();
+ }
}
std::string ChatController::senderDisplayNameFromMessage(const JID& from) {
- return nickResolver_->jidToNick(from);
+ return nickResolver_->jidToNick(from);
}
std::string ChatController::getStatusChangeString(boost::shared_ptr<Presence> presence) {
- std::string nick = senderDisplayNameFromMessage(presence->getFrom());
- std::string response;
- if (!presence || presence->getType() == Presence::Unavailable || presence->getType() == Presence::Error) {
- response = QT_TRANSLATE_NOOP("", "%1% has gone offline");
- } else if (presence->getType() == Presence::Available) {
- StatusShow::Type show = presence->getShow();
- if (show == StatusShow::Online || show == StatusShow::FFC) {
- response = QT_TRANSLATE_NOOP("", "%1% has become available");
- } else if (show == StatusShow::Away || show == StatusShow::XA) {
- response = QT_TRANSLATE_NOOP("", "%1% has gone away");
- } else if (show == StatusShow::DND) {
- response = QT_TRANSLATE_NOOP("", "%1% is now busy");
- }
- }
- Idle::ref idle;
- if ((idle = presence->getPayload<Idle>())) {
- response += str(format(QT_TRANSLATE_NOOP("", " and has been idle since %1%")) % dateTimeToLocalString(idle->getSince()));
- }
-
- if (!response.empty()) {
- response = str(format(response) % nick);
- }
-
- if (!presence->getStatus().empty()) {
- response += " (" + presence->getStatus() + ")";
- }
- return response + ".";
+ std::string nick = senderDisplayNameFromMessage(presence->getFrom());
+ std::string response;
+ if (!presence || presence->getType() == Presence::Unavailable || presence->getType() == Presence::Error) {
+ response = QT_TRANSLATE_NOOP("", "%1% has gone offline");
+ } else if (presence->getType() == Presence::Available) {
+ StatusShow::Type show = presence->getShow();
+ if (show == StatusShow::Online || show == StatusShow::FFC) {
+ response = QT_TRANSLATE_NOOP("", "%1% has become available");
+ } else if (show == StatusShow::Away || show == StatusShow::XA) {
+ response = QT_TRANSLATE_NOOP("", "%1% has gone away");
+ } else if (show == StatusShow::DND) {
+ response = QT_TRANSLATE_NOOP("", "%1% is now busy");
+ }
+ }
+ Idle::ref idle;
+ if ((idle = presence->getPayload<Idle>())) {
+ response += str(format(QT_TRANSLATE_NOOP("", " and has been idle since %1%")) % dateTimeToLocalString(idle->getSince()));
+ }
+
+ if (!response.empty()) {
+ response = str(format(response) % nick);
+ }
+
+ if (!presence->getStatus().empty()) {
+ response += " (" + presence->getStatus() + ")";
+ }
+ return response + ".";
}
void ChatController::handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
- bool relevantPresence = false;
-
- if (isInMUC_) {
- // For MUC participants we only have a single presence to choose one and
- // even for multi-session nicknames multiple resources are not distinguishable
- // to other participants.
- if (toJID_.equals(newPresence->getFrom(), JID::WithResource)) {
- relevantPresence = true;
- }
- }
- else {
- // For standard chats we retrieve the account presence from the PresenceOracle,
- // as there can be multiple presences to choose from.
- if (toJID_.equals(newPresence->getFrom(), JID::WithoutResource)) {
- // Presence matches ChatController JID.
- newPresence = presenceOracle_->getAccountPresence(toJID_);
- relevantPresence = true;
- }
- }
-
- if (!relevantPresence) {
- return;
- }
-
- if (!newPresence) {
- newPresence = boost::make_shared<Presence>();
- newPresence->setType(Presence::Unavailable);
- }
- lastShownStatus_ = newPresence->getShow();
-
- chatStateTracker_->handlePresenceChange(newPresence);
- chatStateNotifier_->setContactIsOnline(newPresence->getType() == Presence::Available);
- std::string newStatusChangeString = getStatusChangeString(newPresence);
- if (newStatusChangeString != lastStatusChangeString_) {
- if (lastWasPresence_) {
- chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::UpdateTimestamp);
- } else {
- chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::DefaultDirection);
- }
- lastStatusChangeString_ = newStatusChangeString;
- lastWasPresence_ = true;
- }
+ bool relevantPresence = false;
+
+ if (isInMUC_) {
+ // For MUC participants we only have a single presence to choose one and
+ // even for multi-session nicknames multiple resources are not distinguishable
+ // to other participants.
+ if (toJID_.equals(newPresence->getFrom(), JID::WithResource)) {
+ relevantPresence = true;
+ }
+ }
+ else {
+ // For standard chats we retrieve the account presence from the PresenceOracle,
+ // as there can be multiple presences to choose from.
+ if (toJID_.equals(newPresence->getFrom(), JID::WithoutResource)) {
+ // Presence matches ChatController JID.
+ newPresence = presenceOracle_->getAccountPresence(toJID_);
+ relevantPresence = true;
+ }
+ }
+
+ if (!relevantPresence) {
+ return;
+ }
+
+ if (!newPresence) {
+ newPresence = boost::make_shared<Presence>();
+ newPresence->setType(Presence::Unavailable);
+ }
+ lastShownStatus_ = newPresence->getShow();
+
+ chatStateTracker_->handlePresenceChange(newPresence);
+ chatStateNotifier_->setContactIsOnline(newPresence->getType() == Presence::Available);
+ std::string newStatusChangeString = getStatusChangeString(newPresence);
+ if (newStatusChangeString != lastStatusChangeString_) {
+ if (lastWasPresence_) {
+ chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::UpdateTimestamp);
+ } else {
+ chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::DefaultDirection);
+ }
+ lastStatusChangeString_ = newStatusChangeString;
+ lastWasPresence_ = true;
+ }
}
boost::optional<boost::posix_time::ptime> ChatController::getMessageTimestamp(boost::shared_ptr<Message> message) const {
- return message->getTimestamp();
+ return message->getTimestamp();
}
void ChatController::logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool /* isIncoming */) {
- HistoryMessage::Type type;
- if (mucRegistry_->isMUC(fromJID.toBare()) || mucRegistry_->isMUC(toJID.toBare())) {
- type = HistoryMessage::PrivateMessage;
- }
- else {
- type = HistoryMessage::Chat;
- }
+ HistoryMessage::Type type;
+ if (mucRegistry_->isMUC(fromJID.toBare()) || mucRegistry_->isMUC(toJID.toBare())) {
+ type = HistoryMessage::PrivateMessage;
+ }
+ else {
+ type = HistoryMessage::Chat;
+ }
- if (historyController_) {
- historyController_->addMessage(message, fromJID, toJID, type, timeStamp);
- }
+ if (historyController_) {
+ historyController_->addMessage(message, fromJID, toJID, type, timeStamp);
+ }
}
ChatWindow* ChatController::detachChatWindow() {
- chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
- chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
- return ChatControllerBase::detachChatWindow();
+ chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_));
+ chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_));
+ return ChatControllerBase::detachChatWindow();
}
}
diff --git a/Swift/Controllers/Chat/ChatController.h b/Swift/Controllers/Chat/ChatController.h
index 6ec19df..aa2b203 100644
--- a/Swift/Controllers/Chat/ChatController.h
+++ b/Swift/Controllers/Chat/ChatController.h
@@ -16,101 +16,101 @@
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
namespace Swift {
- class AvatarManager;
- class ChatStateNotifier;
- class ChatStateTracker;
- class NickResolver;
- class EntityCapsProvider;
- class FileTransferController;
- class SettingsProvider;
- class HistoryController;
- class HighlightManager;
- class ClientBlockListManager;
- class UIEvent;
-
- class ChatController : public ChatControllerBase {
- public:
- ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider);
- virtual ~ChatController();
- virtual void setToJID(const JID& jid) SWIFTEN_OVERRIDE;
- virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) SWIFTEN_OVERRIDE;
- virtual void setOnline(bool online) SWIFTEN_OVERRIDE;
- virtual void handleNewFileTransferController(FileTransferController* ftc);
- virtual void handleWhiteboardSessionRequest(bool senderIsSelf);
- virtual void handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state);
- virtual void setContactIsReceivingPresence(bool /*isReceivingPresence*/) SWIFTEN_OVERRIDE;
- virtual ChatWindow* detachChatWindow() SWIFTEN_OVERRIDE;
-
- protected:
- virtual void cancelReplaces() SWIFTEN_OVERRIDE;
- virtual JID getBaseJID() SWIFTEN_OVERRIDE;
- virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE;
-
- private:
- void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
- std::string getStatusChangeString(boost::shared_ptr<Presence> presence);
- virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
- virtual void postSendMessage(const std::string &body, boost::shared_ptr<Stanza> sentStanza) SWIFTEN_OVERRIDE;
- virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent) SWIFTEN_OVERRIDE;
- virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE;
- virtual void preSendMessageRequest(boost::shared_ptr<Message>) SWIFTEN_OVERRIDE;
- virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
- virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
- virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message>) const SWIFTEN_OVERRIDE;
- void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
- virtual void dayTicked() SWIFTEN_OVERRIDE { lastWasPresence_ = false; }
- void handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/);
- virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE;
-
- void handleFileTransferCancel(std::string /* id */);
- void handleFileTransferStart(std::string /* id */, std::string /* description */);
- void handleFileTransferAccept(std::string /* id */, std::string /* filename */);
- void handleSendFileRequest(std::string filename);
-
- void handleWhiteboardSessionAccept();
- void handleWhiteboardSessionCancel();
- void handleWhiteboardWindowShow();
-
- void handleSettingChanged(const std::string& settingPath);
- void checkForDisplayingDisplayReceiptsAlert();
-
- void handleBlockingStateChanged();
- void handleBlockUserRequest();
- void handleUnblockUserRequest();
-
- void handleInviteToChat(const std::vector<JID>& droppedJIDs);
-
- void handleWindowClosed();
-
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
-
- private:
- NickResolver* nickResolver_;
- ChatStateNotifier* chatStateNotifier_;
- ChatStateTracker* chatStateTracker_;
- std::string myLastMessageUIID_;
- bool isInMUC_;
- bool lastWasPresence_;
- std::string lastStatusChangeString_;
- std::map<boost::shared_ptr<Stanza>, std::string> unackedStanzas_;
- std::map<std::string, std::string> requestedReceipts_;
- StatusShow::Type lastShownStatus_;
- UIEventStream* eventStream_;
-
- Tristate contactSupportsReceipts_;
- bool receivingPresenceFromUs_;
- bool userWantsReceipts_;
- std::map<std::string, FileTransferController*> ftControllers;
- SettingsProvider* settings_;
- std::string lastWbID_;
-
- ClientBlockListManager* clientBlockListManager_;
- boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
- boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
- boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
-
- boost::optional<ChatWindow::AlertID> deliveryReceiptAlert_;
- boost::optional<ChatWindow::AlertID> blockedContactAlert_;
- };
+ class AvatarManager;
+ class ChatStateNotifier;
+ class ChatStateTracker;
+ class NickResolver;
+ class EntityCapsProvider;
+ class FileTransferController;
+ class SettingsProvider;
+ class HistoryController;
+ class HighlightManager;
+ class ClientBlockListManager;
+ class UIEvent;
+
+ class ChatController : public ChatControllerBase {
+ public:
+ ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider);
+ virtual ~ChatController();
+ virtual void setToJID(const JID& jid) SWIFTEN_OVERRIDE;
+ virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) SWIFTEN_OVERRIDE;
+ virtual void setOnline(bool online) SWIFTEN_OVERRIDE;
+ virtual void handleNewFileTransferController(FileTransferController* ftc);
+ virtual void handleWhiteboardSessionRequest(bool senderIsSelf);
+ virtual void handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state);
+ virtual void setContactIsReceivingPresence(bool /*isReceivingPresence*/) SWIFTEN_OVERRIDE;
+ virtual ChatWindow* detachChatWindow() SWIFTEN_OVERRIDE;
+
+ protected:
+ virtual void cancelReplaces() SWIFTEN_OVERRIDE;
+ virtual JID getBaseJID() SWIFTEN_OVERRIDE;
+ virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE;
+
+ private:
+ void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
+ std::string getStatusChangeString(boost::shared_ptr<Presence> presence);
+ virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
+ virtual void postSendMessage(const std::string &body, boost::shared_ptr<Stanza> sentStanza) SWIFTEN_OVERRIDE;
+ virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent) SWIFTEN_OVERRIDE;
+ virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE;
+ virtual void preSendMessageRequest(boost::shared_ptr<Message>) SWIFTEN_OVERRIDE;
+ virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
+ virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
+ virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message>) const SWIFTEN_OVERRIDE;
+ void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
+ virtual void dayTicked() SWIFTEN_OVERRIDE { lastWasPresence_ = false; }
+ void handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/);
+ virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE;
+
+ void handleFileTransferCancel(std::string /* id */);
+ void handleFileTransferStart(std::string /* id */, std::string /* description */);
+ void handleFileTransferAccept(std::string /* id */, std::string /* filename */);
+ void handleSendFileRequest(std::string filename);
+
+ void handleWhiteboardSessionAccept();
+ void handleWhiteboardSessionCancel();
+ void handleWhiteboardWindowShow();
+
+ void handleSettingChanged(const std::string& settingPath);
+ void checkForDisplayingDisplayReceiptsAlert();
+
+ void handleBlockingStateChanged();
+ void handleBlockUserRequest();
+ void handleUnblockUserRequest();
+
+ void handleInviteToChat(const std::vector<JID>& droppedJIDs);
+
+ void handleWindowClosed();
+
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+
+ private:
+ NickResolver* nickResolver_;
+ ChatStateNotifier* chatStateNotifier_;
+ ChatStateTracker* chatStateTracker_;
+ std::string myLastMessageUIID_;
+ bool isInMUC_;
+ bool lastWasPresence_;
+ std::string lastStatusChangeString_;
+ std::map<boost::shared_ptr<Stanza>, std::string> unackedStanzas_;
+ std::map<std::string, std::string> requestedReceipts_;
+ StatusShow::Type lastShownStatus_;
+ UIEventStream* eventStream_;
+
+ Tristate contactSupportsReceipts_;
+ bool receivingPresenceFromUs_;
+ bool userWantsReceipts_;
+ std::map<std::string, FileTransferController*> ftControllers;
+ SettingsProvider* settings_;
+ std::string lastWbID_;
+
+ ClientBlockListManager* clientBlockListManager_;
+ boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
+
+ boost::optional<ChatWindow::AlertID> deliveryReceiptAlert_;
+ boost::optional<ChatWindow::AlertID> blockedContactAlert_;
+ };
}
diff --git a/Swift/Controllers/Chat/ChatControllerBase.cpp b/Swift/Controllers/Chat/ChatControllerBase.cpp
index c790cce..d478e2a 100644
--- a/Swift/Controllers/Chat/ChatControllerBase.cpp
+++ b/Swift/Controllers/Chat/ChatControllerBase.cpp
@@ -43,378 +43,378 @@
namespace Swift {
ChatControllerBase::ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider) : selfJID_(self), stanzaChannel_(stanzaChannel), iqRouter_(iqRouter), chatWindowFactory_(chatWindowFactory), toJID_(toJID), labelsEnabled_(false), presenceOracle_(presenceOracle), avatarManager_(avatarManager), useDelayForLatency_(useDelayForLatency), eventController_(eventController), timerFactory_(timerFactory), entityCapsProvider_(entityCapsProvider), historyController_(historyController), mucRegistry_(mucRegistry), chatMessageParser_(chatMessageParser), autoAcceptMUCInviteDecider_(autoAcceptMUCInviteDecider), eventStream_(eventStream) {
- chatWindow_ = chatWindowFactory_->createChatWindow(toJID, eventStream);
- chatWindow_->onAllMessagesRead.connect(boost::bind(&ChatControllerBase::handleAllMessagesRead, this));
- chatWindow_->onSendMessageRequest.connect(boost::bind(&ChatControllerBase::handleSendMessageRequest, this, _1, _2));
- chatWindow_->onLogCleared.connect(boost::bind(&ChatControllerBase::handleLogCleared, this));
- entityCapsProvider_->onCapsChanged.connect(boost::bind(&ChatControllerBase::handleCapsChanged, this, _1));
- highlighter_ = highlightManager->createHighlighter();
- ChatControllerBase::setOnline(stanzaChannel->isAvailable() && iqRouter->isAvailable());
- createDayChangeTimer();
+ chatWindow_ = chatWindowFactory_->createChatWindow(toJID, eventStream);
+ chatWindow_->onAllMessagesRead.connect(boost::bind(&ChatControllerBase::handleAllMessagesRead, this));
+ chatWindow_->onSendMessageRequest.connect(boost::bind(&ChatControllerBase::handleSendMessageRequest, this, _1, _2));
+ chatWindow_->onLogCleared.connect(boost::bind(&ChatControllerBase::handleLogCleared, this));
+ entityCapsProvider_->onCapsChanged.connect(boost::bind(&ChatControllerBase::handleCapsChanged, this, _1));
+ highlighter_ = highlightManager->createHighlighter();
+ ChatControllerBase::setOnline(stanzaChannel->isAvailable() && iqRouter->isAvailable());
+ createDayChangeTimer();
}
ChatControllerBase::~ChatControllerBase() {
- if (dateChangeTimer_) {
- dateChangeTimer_->onTick.disconnect(boost::bind(&ChatControllerBase::handleDayChangeTick, this));
- dateChangeTimer_->stop();
- }
+ if (dateChangeTimer_) {
+ dateChangeTimer_->onTick.disconnect(boost::bind(&ChatControllerBase::handleDayChangeTick, this));
+ dateChangeTimer_->stop();
+ }
- delete highlighter_;
- delete chatWindow_;
+ delete highlighter_;
+ delete chatWindow_;
}
void ChatControllerBase::handleLogCleared() {
- cancelReplaces();
+ cancelReplaces();
}
ChatWindow* ChatControllerBase::detachChatWindow() {
- ChatWindow* chatWindow = chatWindow_;
- chatWindow_ = NULL;
- return chatWindow;
+ ChatWindow* chatWindow = chatWindow_;
+ chatWindow_ = NULL;
+ return chatWindow;
}
void ChatControllerBase::handleCapsChanged(const JID& jid) {
- if (jid.compare(toJID_, JID::WithoutResource) == 0) {
- handleBareJIDCapsChanged(jid);
- }
+ if (jid.compare(toJID_, JID::WithoutResource) == 0) {
+ handleBareJIDCapsChanged(jid);
+ }
}
void ChatControllerBase::setCanStartImpromptuChats(bool supportsImpromptu) {
- if (chatWindow_) {
- chatWindow_->setCanInitiateImpromptuChats(supportsImpromptu);
- }
+ if (chatWindow_) {
+ chatWindow_->setCanInitiateImpromptuChats(supportsImpromptu);
+ }
}
void ChatControllerBase::createDayChangeTimer() {
- if (timerFactory_) {
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- boost::posix_time::ptime midnight(now.date() + boost::gregorian::days(1));
- int millisecondsUntilMidnight = boost::numeric_cast<int>((midnight - now).total_milliseconds());
- dateChangeTimer_ = timerFactory_->createTimer(millisecondsUntilMidnight);
- dateChangeTimer_->onTick.connect(boost::bind(&ChatControllerBase::handleDayChangeTick, this));
- dateChangeTimer_->start();
- }
+ if (timerFactory_) {
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ boost::posix_time::ptime midnight(now.date() + boost::gregorian::days(1));
+ int millisecondsUntilMidnight = boost::numeric_cast<int>((midnight - now).total_milliseconds());
+ dateChangeTimer_ = timerFactory_->createTimer(millisecondsUntilMidnight);
+ dateChangeTimer_->onTick.connect(boost::bind(&ChatControllerBase::handleDayChangeTick, this));
+ dateChangeTimer_->start();
+ }
}
void ChatControllerBase::handleDayChangeTick() {
- dateChangeTimer_->stop();
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The day is now %1%")) % std::string(boost::posix_time::to_iso_extended_string(now)).substr(0,10))), ChatWindow::DefaultDirection);
- dayTicked();
- createDayChangeTimer();
+ dateChangeTimer_->stop();
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The day is now %1%")) % std::string(boost::posix_time::to_iso_extended_string(now)).substr(0,10))), ChatWindow::DefaultDirection);
+ dayTicked();
+ createDayChangeTimer();
}
void ChatControllerBase::setEnabled(bool enabled) {
- chatWindow_->setOnline(enabled);
- chatWindow_->setCanInitiateImpromptuChats(false);
+ chatWindow_->setOnline(enabled);
+ chatWindow_->setCanInitiateImpromptuChats(false);
}
void ChatControllerBase::setOnline(bool online) {
- setEnabled(online);
+ setEnabled(online);
}
JID ChatControllerBase::getBaseJID() {
- return JID(toJID_.toBare());
+ return JID(toJID_.toBare());
}
void ChatControllerBase::setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) {
- if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::SecurityLabelsCatalogFeature)) {
- GetSecurityLabelsCatalogRequest::ref request = GetSecurityLabelsCatalogRequest::create(getBaseJID(), iqRouter_);
- request->onResponse.connect(boost::bind(&ChatControllerBase::handleSecurityLabelsCatalogResponse, this, _1, _2));
- request->send();
- } else {
- chatWindow_->setSecurityLabelsEnabled(false);
- labelsEnabled_ = false;
- }
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::SecurityLabelsCatalogFeature)) {
+ GetSecurityLabelsCatalogRequest::ref request = GetSecurityLabelsCatalogRequest::create(getBaseJID(), iqRouter_);
+ request->onResponse.connect(boost::bind(&ChatControllerBase::handleSecurityLabelsCatalogResponse, this, _1, _2));
+ request->send();
+ } else {
+ chatWindow_->setSecurityLabelsEnabled(false);
+ labelsEnabled_ = false;
+ }
}
void ChatControllerBase::handleAllMessagesRead() {
- if (!unreadMessages_.empty()) {
- targetedUnreadMessages_.clear();
- foreach (boost::shared_ptr<StanzaEvent> stanzaEvent, unreadMessages_) {
- stanzaEvent->conclude();
- }
- unreadMessages_.clear();
- chatWindow_->setUnreadMessageCount(0);
- onUnreadCountChanged();
- }
+ if (!unreadMessages_.empty()) {
+ targetedUnreadMessages_.clear();
+ foreach (boost::shared_ptr<StanzaEvent> stanzaEvent, unreadMessages_) {
+ stanzaEvent->conclude();
+ }
+ unreadMessages_.clear();
+ chatWindow_->setUnreadMessageCount(0);
+ onUnreadCountChanged();
+ }
}
int ChatControllerBase::getUnreadCount() {
- return boost::numeric_cast<int>(targetedUnreadMessages_.size());
+ return boost::numeric_cast<int>(targetedUnreadMessages_.size());
}
void ChatControllerBase::handleSendMessageRequest(const std::string &body, bool isCorrectionMessage) {
- if (!stanzaChannel_->isAvailable() || body.empty()) {
- return;
- }
- boost::shared_ptr<Message> message(new Message());
- message->setTo(toJID_);
- message->setType(Swift::Message::Chat);
- message->setBody(body);
- if (labelsEnabled_) {
- if (!isCorrectionMessage) {
- lastLabel_ = chatWindow_->getSelectedSecurityLabel();
- }
- SecurityLabelsCatalog::Item labelItem = lastLabel_;
- if (labelItem.getLabel()) {
- message->addPayload(labelItem.getLabel());
- }
- }
- preSendMessageRequest(message);
-
- boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
- if (useDelayForLatency_) {
- message->addPayload(boost::make_shared<Delay>(now, selfJID_));
- }
- if (isCorrectionMessage) {
- message->addPayload(boost::shared_ptr<Replace> (new Replace(lastSentMessageStanzaID_)));
- }
- message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID());
- stanzaChannel_->sendMessage(message);
- postSendMessage(message->getBody().get(), boost::dynamic_pointer_cast<Stanza>(message));
- onActivity(message->getBody().get());
+ if (!stanzaChannel_->isAvailable() || body.empty()) {
+ return;
+ }
+ boost::shared_ptr<Message> message(new Message());
+ message->setTo(toJID_);
+ message->setType(Swift::Message::Chat);
+ message->setBody(body);
+ if (labelsEnabled_) {
+ if (!isCorrectionMessage) {
+ lastLabel_ = chatWindow_->getSelectedSecurityLabel();
+ }
+ SecurityLabelsCatalog::Item labelItem = lastLabel_;
+ if (labelItem.getLabel()) {
+ message->addPayload(labelItem.getLabel());
+ }
+ }
+ preSendMessageRequest(message);
+
+ boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
+ if (useDelayForLatency_) {
+ message->addPayload(boost::make_shared<Delay>(now, selfJID_));
+ }
+ if (isCorrectionMessage) {
+ message->addPayload(boost::shared_ptr<Replace> (new Replace(lastSentMessageStanzaID_)));
+ }
+ message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID());
+ stanzaChannel_->sendMessage(message);
+ postSendMessage(message->getBody().get(), boost::dynamic_pointer_cast<Stanza>(message));
+ onActivity(message->getBody().get());
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- logMessage(body, selfJID_, toJID_, now, false);
+ logMessage(body, selfJID_, toJID_, now, false);
#endif
}
void ChatControllerBase::handleSecurityLabelsCatalogResponse(boost::shared_ptr<SecurityLabelsCatalog> catalog, ErrorPayload::ref error) {
- if (catalog && !error) {
- if (catalog->getItems().size() == 0) {
- chatWindow_->setSecurityLabelsEnabled(false);
- labelsEnabled_ = false;
- } else {
- labelsEnabled_ = true;
- chatWindow_->setAvailableSecurityLabels(catalog->getItems());
- chatWindow_->setSecurityLabelsEnabled(true);
- }
- } else {
- labelsEnabled_ = false;
- chatWindow_->setSecurityLabelsError();
- }
+ if (catalog && !error) {
+ if (catalog->getItems().size() == 0) {
+ chatWindow_->setSecurityLabelsEnabled(false);
+ labelsEnabled_ = false;
+ } else {
+ labelsEnabled_ = true;
+ chatWindow_->setAvailableSecurityLabels(catalog->getItems());
+ chatWindow_->setSecurityLabelsEnabled(true);
+ }
+ } else {
+ labelsEnabled_ = false;
+ chatWindow_->setSecurityLabelsError();
+ }
}
void ChatControllerBase::showChatWindow() {
- chatWindow_->show();
+ chatWindow_->show();
}
void ChatControllerBase::activateChatWindow() {
- chatWindow_->activate();
+ chatWindow_->activate();
}
bool ChatControllerBase::hasOpenWindow() const {
- return chatWindow_ && chatWindow_->isVisible();
+ return chatWindow_ && chatWindow_->isVisible();
}
ChatWindow::ChatMessage ChatControllerBase::buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction) {
- ChatWindow::ChatMessage chatMessage;
- if (boost::starts_with(message, "/me ")) {
- chatMessage = chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second);
- }
- else {
- chatMessage = chatMessageParser_->parseMessageBody(message, highlighter_->getNick(), senderIsSelf);
- }
- chatMessage.setFullMessageHighlightAction(fullMessageHighlightAction);
- return chatMessage;
+ ChatWindow::ChatMessage chatMessage;
+ if (boost::starts_with(message, "/me ")) {
+ chatMessage = chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second);
+ }
+ else {
+ chatMessage = chatMessageParser_->parseMessageBody(message, highlighter_->getNick(), senderIsSelf);
+ }
+ chatMessage.setFullMessageHighlightAction(fullMessageHighlightAction);
+ return chatMessage;
}
void ChatControllerBase::handleHighlightActions(const ChatWindow::ChatMessage& chatMessage) {
- std::set<std::string> playedSounds;
- if (chatMessage.getFullMessageHighlightAction().playSound()) {
- highlighter_->handleHighlightAction(chatMessage.getFullMessageHighlightAction());
- playedSounds.insert(chatMessage.getFullMessageHighlightAction().getSoundFile());
- }
- foreach(boost::shared_ptr<ChatWindow::ChatMessagePart> part, chatMessage.getParts()) {
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightMessage = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part);
- if (highlightMessage && highlightMessage->action.playSound()) {
- if (playedSounds.find(highlightMessage->action.getSoundFile()) == playedSounds.end()) {
- highlighter_->handleHighlightAction(highlightMessage->action);
- playedSounds.insert(highlightMessage->action.getSoundFile());
- }
- }
- }
+ std::set<std::string> playedSounds;
+ if (chatMessage.getFullMessageHighlightAction().playSound()) {
+ highlighter_->handleHighlightAction(chatMessage.getFullMessageHighlightAction());
+ playedSounds.insert(chatMessage.getFullMessageHighlightAction().getSoundFile());
+ }
+ foreach(boost::shared_ptr<ChatWindow::ChatMessagePart> part, chatMessage.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightMessage = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part);
+ if (highlightMessage && highlightMessage->action.playSound()) {
+ if (playedSounds.find(highlightMessage->action.getSoundFile()) == playedSounds.end()) {
+ highlighter_->handleHighlightAction(highlightMessage->action);
+ playedSounds.insert(highlightMessage->action.getSoundFile());
+ }
+ }
+ }
}
std::string ChatControllerBase::addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, const boost::shared_ptr<SecurityLabel> label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time) {
- if (chatMessage.isMeCommand()) {
- return chatWindow_->addAction(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time);
- }
- else {
- return chatWindow_->addMessage(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time);
- }
+ if (chatMessage.isMeCommand()) {
+ return chatWindow_->addAction(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time);
+ }
+ else {
+ return chatWindow_->addMessage(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time);
+ }
}
void ChatControllerBase::replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time) {
- if (chatMessage.isMeCommand()) {
- chatWindow_->replaceWithAction(chatMessage, id, time);
- }
- else {
- chatWindow_->replaceMessage(chatMessage, id, time);
- }
+ if (chatMessage.isMeCommand()) {
+ chatWindow_->replaceWithAction(chatMessage, id, time);
+ }
+ else {
+ chatWindow_->replaceMessage(chatMessage, id, time);
+ }
}
bool ChatControllerBase::isFromContact(const JID& from) {
- return from.toBare() == toJID_.toBare();
+ return from.toBare() == toJID_.toBare();
}
void ChatControllerBase::handleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent) {
- preHandleIncomingMessage(messageEvent);
- if (messageEvent->isReadable() && !messageEvent->getConcluded()) {
- unreadMessages_.push_back(messageEvent);
- if (messageEvent->targetsMe()) {
- targetedUnreadMessages_.push_back(messageEvent);
- }
- }
-
- boost::shared_ptr<Message> message = messageEvent->getStanza();
- ChatWindow::ChatMessage chatMessage;
- boost::optional<std::string> optionalBody = message->getBody();
- std::string body = optionalBody.get_value_or("");
- if (message->isError()) {
- if (!message->getTo().getResource().empty()) {
- std::string errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't send message: %1%")) % getErrorMessage(message->getPayload<ErrorPayload>()));
- chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
- }
- }
- else if (messageEvent->getStanza()->getPayload<MUCInvitationPayload>()) {
- handleMUCInvitation(messageEvent->getStanza());
- return;
- }
- else if (messageEvent->getStanza()->getPayload<MUCUserPayload>() && messageEvent->getStanza()->getPayload<MUCUserPayload>()->getInvite()) {
- handleMediatedMUCInvitation(messageEvent->getStanza());
- return;
- }
- else {
- if (!messageEvent->isReadable()) {
- return;
- }
- showChatWindow();
- JID from = message->getFrom();
- std::vector<boost::shared_ptr<Delay> > delayPayloads = message->getPayloads<Delay>();
- for (size_t i = 0; useDelayForLatency_ && i < delayPayloads.size(); i++) {
- if (!delayPayloads[i]->getFrom()) {
- continue;
- }
- boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
- std::ostringstream s;
- s << "The following message took " << (now - delayPayloads[i]->getStamp()).total_milliseconds() / 1000.0 << " seconds to be delivered from " << delayPayloads[i]->getFrom()->toString() << ".";
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(std::string(s.str())), ChatWindow::DefaultDirection);
- }
- boost::shared_ptr<SecurityLabel> label = message->getPayload<SecurityLabel>();
-
- // Determine the timestamp
- boost::posix_time::ptime timeStamp = boost::posix_time::microsec_clock::universal_time();
- boost::optional<boost::posix_time::ptime> messageTimeStamp = getMessageTimestamp(message);
- if (messageTimeStamp) {
- timeStamp = *messageTimeStamp;
- }
- onActivity(body);
-
- // Highlight
- HighlightAction fullMessageHighlight;
- if (!isIncomingMessageFromMe(message)) {
- fullMessageHighlight = highlighter_->findFirstFullMessageMatchAction(body, senderHighlightNameFromMessage(from));
- }
-
- boost::shared_ptr<Replace> replace = message->getPayload<Replace>();
- bool senderIsSelf = isIncomingMessageFromMe(message);
- if (replace) {
- // Should check if the user has a previous message
- std::map<JID, std::string>::iterator lastMessage;
- lastMessage = lastMessagesUIID_.find(from);
- if (lastMessage != lastMessagesUIID_.end()) {
- chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight);
- replaceMessage(chatMessage, lastMessagesUIID_[from], timeStamp);
- }
- }
- else {
- chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight);
- addMessageHandleIncomingMessage(from, chatMessage, senderIsSelf, label, timeStamp);
- }
-
- logMessage(body, from, selfJID_, timeStamp, true);
- }
- chatWindow_->show();
- chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
- onUnreadCountChanged();
- postHandleIncomingMessage(messageEvent, chatMessage);
+ preHandleIncomingMessage(messageEvent);
+ if (messageEvent->isReadable() && !messageEvent->getConcluded()) {
+ unreadMessages_.push_back(messageEvent);
+ if (messageEvent->targetsMe()) {
+ targetedUnreadMessages_.push_back(messageEvent);
+ }
+ }
+
+ boost::shared_ptr<Message> message = messageEvent->getStanza();
+ ChatWindow::ChatMessage chatMessage;
+ boost::optional<std::string> optionalBody = message->getBody();
+ std::string body = optionalBody.get_value_or("");
+ if (message->isError()) {
+ if (!message->getTo().getResource().empty()) {
+ std::string errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't send message: %1%")) % getErrorMessage(message->getPayload<ErrorPayload>()));
+ chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
+ }
+ }
+ else if (messageEvent->getStanza()->getPayload<MUCInvitationPayload>()) {
+ handleMUCInvitation(messageEvent->getStanza());
+ return;
+ }
+ else if (messageEvent->getStanza()->getPayload<MUCUserPayload>() && messageEvent->getStanza()->getPayload<MUCUserPayload>()->getInvite()) {
+ handleMediatedMUCInvitation(messageEvent->getStanza());
+ return;
+ }
+ else {
+ if (!messageEvent->isReadable()) {
+ return;
+ }
+ showChatWindow();
+ JID from = message->getFrom();
+ std::vector<boost::shared_ptr<Delay> > delayPayloads = message->getPayloads<Delay>();
+ for (size_t i = 0; useDelayForLatency_ && i < delayPayloads.size(); i++) {
+ if (!delayPayloads[i]->getFrom()) {
+ continue;
+ }
+ boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
+ std::ostringstream s;
+ s << "The following message took " << (now - delayPayloads[i]->getStamp()).total_milliseconds() / 1000.0 << " seconds to be delivered from " << delayPayloads[i]->getFrom()->toString() << ".";
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(std::string(s.str())), ChatWindow::DefaultDirection);
+ }
+ boost::shared_ptr<SecurityLabel> label = message->getPayload<SecurityLabel>();
+
+ // Determine the timestamp
+ boost::posix_time::ptime timeStamp = boost::posix_time::microsec_clock::universal_time();
+ boost::optional<boost::posix_time::ptime> messageTimeStamp = getMessageTimestamp(message);
+ if (messageTimeStamp) {
+ timeStamp = *messageTimeStamp;
+ }
+ onActivity(body);
+
+ // Highlight
+ HighlightAction fullMessageHighlight;
+ if (!isIncomingMessageFromMe(message)) {
+ fullMessageHighlight = highlighter_->findFirstFullMessageMatchAction(body, senderHighlightNameFromMessage(from));
+ }
+
+ boost::shared_ptr<Replace> replace = message->getPayload<Replace>();
+ bool senderIsSelf = isIncomingMessageFromMe(message);
+ if (replace) {
+ // Should check if the user has a previous message
+ std::map<JID, std::string>::iterator lastMessage;
+ lastMessage = lastMessagesUIID_.find(from);
+ if (lastMessage != lastMessagesUIID_.end()) {
+ chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight);
+ replaceMessage(chatMessage, lastMessagesUIID_[from], timeStamp);
+ }
+ }
+ else {
+ chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight);
+ addMessageHandleIncomingMessage(from, chatMessage, senderIsSelf, label, timeStamp);
+ }
+
+ logMessage(body, from, selfJID_, timeStamp, true);
+ }
+ chatWindow_->show();
+ chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
+ onUnreadCountChanged();
+ postHandleIncomingMessage(messageEvent, chatMessage);
}
void ChatControllerBase::addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& timeStamp) {
- lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp);
+ lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp);
}
std::string ChatControllerBase::getErrorMessage(boost::shared_ptr<ErrorPayload> error) {
- std::string defaultMessage = QT_TRANSLATE_NOOP("", "Error sending message");
- if (!error->getText().empty()) {
- return error->getText();
- }
- else {
- switch (error->getCondition()) {
- case ErrorPayload::BadRequest: return QT_TRANSLATE_NOOP("", "Bad request");
- case ErrorPayload::Conflict: return QT_TRANSLATE_NOOP("", "Conflict");
- case ErrorPayload::FeatureNotImplemented: return QT_TRANSLATE_NOOP("", "This feature is not implemented");
- case ErrorPayload::Forbidden: return QT_TRANSLATE_NOOP("", "Forbidden");
- case ErrorPayload::Gone: return QT_TRANSLATE_NOOP("", "Recipient can no longer be contacted");
- case ErrorPayload::InternalServerError: return QT_TRANSLATE_NOOP("", "Internal server error");
- case ErrorPayload::ItemNotFound: return QT_TRANSLATE_NOOP("", "Item not found");
- case ErrorPayload::JIDMalformed: return QT_TRANSLATE_NOOP("", "JID Malformed");
- case ErrorPayload::NotAcceptable: return QT_TRANSLATE_NOOP("", "Message was rejected");
- case ErrorPayload::NotAllowed: return QT_TRANSLATE_NOOP("", "Not allowed");
- case ErrorPayload::NotAuthorized: return QT_TRANSLATE_NOOP("", "Not authorized");
- case ErrorPayload::PaymentRequired: return QT_TRANSLATE_NOOP("", "Payment is required");
- case ErrorPayload::RecipientUnavailable: return QT_TRANSLATE_NOOP("", "Recipient is unavailable");
- case ErrorPayload::Redirect: return QT_TRANSLATE_NOOP("", "Redirect");
- case ErrorPayload::RegistrationRequired: return QT_TRANSLATE_NOOP("", "Registration required");
- case ErrorPayload::RemoteServerNotFound: return QT_TRANSLATE_NOOP("", "Recipient's server not found");
- case ErrorPayload::RemoteServerTimeout: return QT_TRANSLATE_NOOP("", "Remote server timeout");
- case ErrorPayload::ResourceConstraint: return QT_TRANSLATE_NOOP("", "The server is low on resources");
- case ErrorPayload::ServiceUnavailable: return QT_TRANSLATE_NOOP("", "The service is unavailable");
- case ErrorPayload::SubscriptionRequired: return QT_TRANSLATE_NOOP("", "A subscription is required");
- case ErrorPayload::UndefinedCondition: return QT_TRANSLATE_NOOP("", "Undefined condition");
- case ErrorPayload::UnexpectedRequest: return QT_TRANSLATE_NOOP("", "Unexpected request");
- }
- }
- assert(false);
- return defaultMessage;
+ std::string defaultMessage = QT_TRANSLATE_NOOP("", "Error sending message");
+ if (!error->getText().empty()) {
+ return error->getText();
+ }
+ else {
+ switch (error->getCondition()) {
+ case ErrorPayload::BadRequest: return QT_TRANSLATE_NOOP("", "Bad request");
+ case ErrorPayload::Conflict: return QT_TRANSLATE_NOOP("", "Conflict");
+ case ErrorPayload::FeatureNotImplemented: return QT_TRANSLATE_NOOP("", "This feature is not implemented");
+ case ErrorPayload::Forbidden: return QT_TRANSLATE_NOOP("", "Forbidden");
+ case ErrorPayload::Gone: return QT_TRANSLATE_NOOP("", "Recipient can no longer be contacted");
+ case ErrorPayload::InternalServerError: return QT_TRANSLATE_NOOP("", "Internal server error");
+ case ErrorPayload::ItemNotFound: return QT_TRANSLATE_NOOP("", "Item not found");
+ case ErrorPayload::JIDMalformed: return QT_TRANSLATE_NOOP("", "JID Malformed");
+ case ErrorPayload::NotAcceptable: return QT_TRANSLATE_NOOP("", "Message was rejected");
+ case ErrorPayload::NotAllowed: return QT_TRANSLATE_NOOP("", "Not allowed");
+ case ErrorPayload::NotAuthorized: return QT_TRANSLATE_NOOP("", "Not authorized");
+ case ErrorPayload::PaymentRequired: return QT_TRANSLATE_NOOP("", "Payment is required");
+ case ErrorPayload::RecipientUnavailable: return QT_TRANSLATE_NOOP("", "Recipient is unavailable");
+ case ErrorPayload::Redirect: return QT_TRANSLATE_NOOP("", "Redirect");
+ case ErrorPayload::RegistrationRequired: return QT_TRANSLATE_NOOP("", "Registration required");
+ case ErrorPayload::RemoteServerNotFound: return QT_TRANSLATE_NOOP("", "Recipient's server not found");
+ case ErrorPayload::RemoteServerTimeout: return QT_TRANSLATE_NOOP("", "Remote server timeout");
+ case ErrorPayload::ResourceConstraint: return QT_TRANSLATE_NOOP("", "The server is low on resources");
+ case ErrorPayload::ServiceUnavailable: return QT_TRANSLATE_NOOP("", "The service is unavailable");
+ case ErrorPayload::SubscriptionRequired: return QT_TRANSLATE_NOOP("", "A subscription is required");
+ case ErrorPayload::UndefinedCondition: return QT_TRANSLATE_NOOP("", "Undefined condition");
+ case ErrorPayload::UnexpectedRequest: return QT_TRANSLATE_NOOP("", "Unexpected request");
+ }
+ }
+ assert(false);
+ return defaultMessage;
}
void ChatControllerBase::handleGeneralMUCInvitation(MUCInviteEvent::ref event) {
- unreadMessages_.push_back(event);
- chatWindow_->show();
- chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
- onUnreadCountChanged();
- chatWindow_->addMUCInvitation(senderDisplayNameFromMessage(event->getInviter()), event->getRoomJID(), event->getReason(), event->getPassword(), event->getDirect(), event->getImpromptu());
- eventController_->handleIncomingEvent(event);
+ unreadMessages_.push_back(event);
+ chatWindow_->show();
+ chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
+ onUnreadCountChanged();
+ chatWindow_->addMUCInvitation(senderDisplayNameFromMessage(event->getInviter()), event->getRoomJID(), event->getReason(), event->getPassword(), event->getDirect(), event->getImpromptu());
+ eventController_->handleIncomingEvent(event);
}
void ChatControllerBase::handleMUCInvitation(Message::ref message) {
- MUCInvitationPayload::ref invite = message->getPayload<MUCInvitationPayload>();
-
- if (autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) {
- eventStream_->send(boost::make_shared<JoinMUCUIEvent>(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true));
- } else {
- MUCInviteEvent::ref inviteEvent = boost::make_shared<MUCInviteEvent>(toJID_, invite->getJID(), invite->getReason(), invite->getPassword(), true, invite->getIsImpromptu());
- handleGeneralMUCInvitation(inviteEvent);
- }
+ MUCInvitationPayload::ref invite = message->getPayload<MUCInvitationPayload>();
+
+ if (autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) {
+ eventStream_->send(boost::make_shared<JoinMUCUIEvent>(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true));
+ } else {
+ MUCInviteEvent::ref inviteEvent = boost::make_shared<MUCInviteEvent>(toJID_, invite->getJID(), invite->getReason(), invite->getPassword(), true, invite->getIsImpromptu());
+ handleGeneralMUCInvitation(inviteEvent);
+ }
}
void ChatControllerBase::handleMediatedMUCInvitation(Message::ref message) {
- MUCUserPayload::Invite invite = *message->getPayload<MUCUserPayload>()->getInvite();
- JID from = message->getFrom();
- std::string reason;
- if (!invite.reason.empty()) {
- reason = invite.reason;
- }
- std::string password;
- if (message->getPayload<MUCUserPayload>()->getPassword()) {
- password = *message->getPayload<MUCUserPayload>()->getPassword();
- }
-
- MUCInviteEvent::ref inviteEvent = boost::make_shared<MUCInviteEvent>(invite.from, from, reason, password, false, false);
- handleGeneralMUCInvitation(inviteEvent);
+ MUCUserPayload::Invite invite = *message->getPayload<MUCUserPayload>()->getInvite();
+ JID from = message->getFrom();
+ std::string reason;
+ if (!invite.reason.empty()) {
+ reason = invite.reason;
+ }
+ std::string password;
+ if (message->getPayload<MUCUserPayload>()->getPassword()) {
+ password = *message->getPayload<MUCUserPayload>()->getPassword();
+ }
+
+ MUCInviteEvent::ref inviteEvent = boost::make_shared<MUCInviteEvent>(invite.from, from, reason, password, false, false);
+ handleGeneralMUCInvitation(inviteEvent);
}
}
diff --git a/Swift/Controllers/Chat/ChatControllerBase.h b/Swift/Controllers/Chat/ChatControllerBase.h
index 98f0ab0..bd8ba0f 100644
--- a/Swift/Controllers/Chat/ChatControllerBase.h
+++ b/Swift/Controllers/Chat/ChatControllerBase.h
@@ -35,107 +35,107 @@
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
namespace Swift {
- class IQRouter;
- class StanzaChannel;
- class ChatWindowFactory;
- class AvatarManager;
- class UIEventStream;
- class EventController;
- class EntityCapsProvider;
- class HighlightManager;
- class Highlighter;
- class ChatMessageParser;
- class AutoAcceptMUCInviteDecider;
+ class IQRouter;
+ class StanzaChannel;
+ class ChatWindowFactory;
+ class AvatarManager;
+ class UIEventStream;
+ class EventController;
+ class EntityCapsProvider;
+ class HighlightManager;
+ class Highlighter;
+ class ChatMessageParser;
+ class AutoAcceptMUCInviteDecider;
- class ChatControllerBase : public boost::bsignals::trackable {
- public:
- virtual ~ChatControllerBase();
- void showChatWindow();
- void activateChatWindow();
- bool hasOpenWindow() const;
- virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info);
- void handleIncomingMessage(boost::shared_ptr<MessageEvent> message);
- std::string addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time);
- void replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time);
- virtual void setOnline(bool online);
- void setEnabled(bool enabled);
- virtual void setToJID(const JID& jid) {toJID_ = jid;}
- /** Used for determining when something is recent.*/
- boost::signal<void (const std::string& /*activity*/)> onActivity;
- boost::signal<void ()> onUnreadCountChanged;
- boost::signal<void ()> onWindowClosed;
- int getUnreadCount();
- const JID& getToJID() {return toJID_;}
- void handleCapsChanged(const JID& jid);
- void setCanStartImpromptuChats(bool supportsImpromptu);
- virtual ChatWindow* detachChatWindow();
- boost::signal<void(ChatWindow* /*window to reuse*/, const std::vector<JID>& /*invite people*/, const std::string& /*reason*/)> onConvertToMUC;
+ class ChatControllerBase : public boost::bsignals::trackable {
+ public:
+ virtual ~ChatControllerBase();
+ void showChatWindow();
+ void activateChatWindow();
+ bool hasOpenWindow() const;
+ virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info);
+ void handleIncomingMessage(boost::shared_ptr<MessageEvent> message);
+ std::string addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time);
+ void replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time);
+ virtual void setOnline(bool online);
+ void setEnabled(bool enabled);
+ virtual void setToJID(const JID& jid) {toJID_ = jid;}
+ /** Used for determining when something is recent.*/
+ boost::signal<void (const std::string& /*activity*/)> onActivity;
+ boost::signal<void ()> onUnreadCountChanged;
+ boost::signal<void ()> onWindowClosed;
+ int getUnreadCount();
+ const JID& getToJID() {return toJID_;}
+ void handleCapsChanged(const JID& jid);
+ void setCanStartImpromptuChats(bool supportsImpromptu);
+ virtual ChatWindow* detachChatWindow();
+ boost::signal<void(ChatWindow* /*window to reuse*/, const std::vector<JID>& /*invite people*/, const std::string& /*reason*/)> onConvertToMUC;
- protected:
- ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider);
+ protected:
+ ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider);
- /**
- * Pass the Message appended, and the stanza used to send it.
- */
- virtual void postSendMessage(const std::string&, boost::shared_ptr<Stanza>) {}
- virtual std::string senderDisplayNameFromMessage(const JID& from) = 0;
- virtual std::string senderHighlightNameFromMessage(const JID& from) = 0;
- virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message>) = 0;
- virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent>) {}
- virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time);
- virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const ChatWindow::ChatMessage&) {}
- virtual void preSendMessageRequest(boost::shared_ptr<Message>) {}
- virtual bool isFromContact(const JID& from);
- virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message>) const = 0;
- virtual void dayTicked() {}
- virtual void handleBareJIDCapsChanged(const JID& jid) = 0;
- std::string getErrorMessage(boost::shared_ptr<ErrorPayload>);
- virtual void setContactIsReceivingPresence(bool /* isReceivingPresence */) {}
- virtual void cancelReplaces() = 0;
- /** JID any iq for account should go to - bare except for PMs */
- virtual JID getBaseJID();
- virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) = 0;
- ChatWindow::ChatMessage buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction);
- void handleHighlightActions(const ChatWindow::ChatMessage& chatMessage);
+ /**
+ * Pass the Message appended, and the stanza used to send it.
+ */
+ virtual void postSendMessage(const std::string&, boost::shared_ptr<Stanza>) {}
+ virtual std::string senderDisplayNameFromMessage(const JID& from) = 0;
+ virtual std::string senderHighlightNameFromMessage(const JID& from) = 0;
+ virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message>) = 0;
+ virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent>) {}
+ virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time);
+ virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const ChatWindow::ChatMessage&) {}
+ virtual void preSendMessageRequest(boost::shared_ptr<Message>) {}
+ virtual bool isFromContact(const JID& from);
+ virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message>) const = 0;
+ virtual void dayTicked() {}
+ virtual void handleBareJIDCapsChanged(const JID& jid) = 0;
+ std::string getErrorMessage(boost::shared_ptr<ErrorPayload>);
+ virtual void setContactIsReceivingPresence(bool /* isReceivingPresence */) {}
+ virtual void cancelReplaces() = 0;
+ /** JID any iq for account should go to - bare except for PMs */
+ virtual JID getBaseJID();
+ virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) = 0;
+ ChatWindow::ChatMessage buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction);
+ void handleHighlightActions(const ChatWindow::ChatMessage& chatMessage);
- private:
- IDGenerator idGenerator_;
- std::string lastSentMessageStanzaID_;
- void createDayChangeTimer();
+ private:
+ IDGenerator idGenerator_;
+ std::string lastSentMessageStanzaID_;
+ void createDayChangeTimer();
- void handleSendMessageRequest(const std::string &body, bool isCorrectionMessage);
- void handleAllMessagesRead();
- void handleSecurityLabelsCatalogResponse(boost::shared_ptr<SecurityLabelsCatalog>, ErrorPayload::ref error);
- void handleDayChangeTick();
- void handleMUCInvitation(Message::ref message);
- void handleMediatedMUCInvitation(Message::ref message);
- void handleGeneralMUCInvitation(MUCInviteEvent::ref event);
- void handleLogCleared();
+ void handleSendMessageRequest(const std::string &body, bool isCorrectionMessage);
+ void handleAllMessagesRead();
+ void handleSecurityLabelsCatalogResponse(boost::shared_ptr<SecurityLabelsCatalog>, ErrorPayload::ref error);
+ void handleDayChangeTick();
+ void handleMUCInvitation(Message::ref message);
+ void handleMediatedMUCInvitation(Message::ref message);
+ void handleGeneralMUCInvitation(MUCInviteEvent::ref event);
+ void handleLogCleared();
- protected:
- JID selfJID_;
- std::vector<boost::shared_ptr<StanzaEvent> > unreadMessages_;
- std::vector<boost::shared_ptr<StanzaEvent> > targetedUnreadMessages_;
- StanzaChannel* stanzaChannel_;
- IQRouter* iqRouter_;
- ChatWindowFactory* chatWindowFactory_;
- ChatWindow* chatWindow_;
- JID toJID_;
- bool labelsEnabled_;
- std::map<JID, std::string> lastMessagesUIID_;
- PresenceOracle* presenceOracle_;
- AvatarManager* avatarManager_;
- bool useDelayForLatency_;
- EventController* eventController_;
- boost::shared_ptr<Timer> dateChangeTimer_;
- TimerFactory* timerFactory_;
- EntityCapsProvider* entityCapsProvider_;
- SecurityLabelsCatalog::Item lastLabel_;
- HistoryController* historyController_;
- MUCRegistry* mucRegistry_;
- Highlighter* highlighter_;
- boost::shared_ptr<ChatMessageParser> chatMessageParser_;
- AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_;
- UIEventStream* eventStream_;
- };
+ protected:
+ JID selfJID_;
+ std::vector<boost::shared_ptr<StanzaEvent> > unreadMessages_;
+ std::vector<boost::shared_ptr<StanzaEvent> > targetedUnreadMessages_;
+ StanzaChannel* stanzaChannel_;
+ IQRouter* iqRouter_;
+ ChatWindowFactory* chatWindowFactory_;
+ ChatWindow* chatWindow_;
+ JID toJID_;
+ bool labelsEnabled_;
+ std::map<JID, std::string> lastMessagesUIID_;
+ PresenceOracle* presenceOracle_;
+ AvatarManager* avatarManager_;
+ bool useDelayForLatency_;
+ EventController* eventController_;
+ boost::shared_ptr<Timer> dateChangeTimer_;
+ TimerFactory* timerFactory_;
+ EntityCapsProvider* entityCapsProvider_;
+ SecurityLabelsCatalog::Item lastLabel_;
+ HistoryController* historyController_;
+ MUCRegistry* mucRegistry_;
+ Highlighter* highlighter_;
+ boost::shared_ptr<ChatMessageParser> chatMessageParser_;
+ AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_;
+ UIEventStream* eventStream_;
+ };
}
diff --git a/Swift/Controllers/Chat/ChatMessageParser.cpp b/Swift/Controllers/Chat/ChatMessageParser.cpp
index 53c7588..08e4fcd 100644
--- a/Swift/Controllers/Chat/ChatMessageParser.cpp
+++ b/Swift/Controllers/Chat/ChatMessageParser.cpp
@@ -19,177 +19,177 @@
namespace Swift {
- ChatMessageParser::ChatMessageParser(const std::map<std::string, std::string>& emoticons, HighlightRulesListPtr highlightRules, bool mucMode)
- : emoticons_(emoticons), highlightRules_(highlightRules), mucMode_(mucMode) {
- }
-
- typedef std::pair<std::string, std::string> StringPair;
-
- ChatWindow::ChatMessage ChatMessageParser::parseMessageBody(const std::string& body, const std::string& nick, bool senderIsSelf) {
- ChatWindow::ChatMessage parsedMessage;
- std::string remaining = body;
- /* Parse one, URLs */
- while (!remaining.empty()) {
- bool found = false;
- std::pair<std::vector<std::string>, size_t> links = Linkify::splitLink(remaining);
- remaining = "";
- for (size_t i = 0; i < links.first.size(); i++) {
- const std::string& part = links.first[i];
- if (found) {
- // Must be on the last part, then
- remaining = part;
- }
- else {
- if (i == links.second) {
- found = true;
- parsedMessage.append(boost::make_shared<ChatWindow::ChatURIMessagePart>(part));
- }
- else {
- parsedMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(part));
- }
- }
- }
- }
-
- /* do emoticon substitution */
- parsedMessage = emoticonHighlight(parsedMessage);
-
- if (!senderIsSelf) { /* do not highlight our own messsages */
- /* do word-based color highlighting */
- parsedMessage = splitHighlight(parsedMessage, nick);
- }
-
- return parsedMessage;
- }
-
- ChatWindow::ChatMessage ChatMessageParser::emoticonHighlight(const ChatWindow::ChatMessage& message)
- {
- ChatWindow::ChatMessage parsedMessage = message;
-
- std::string regexString;
- /* Parse two, emoticons */
- foreach (StringPair emoticon, emoticons_) {
- /* Construct a regexp that finds an instance of any of the emoticons inside a group
- * at the start or end of the line, or beside whitespace.
- */
- regexString += regexString.empty() ? "" : "|";
- std::string escaped = "(" + Regex::escape(emoticon.first) + ")";
- regexString += "^" + escaped + "|";
- regexString += escaped + "$|";
- regexString += "\\s" + escaped + "|";
- regexString += escaped + "\\s";
-
- }
- if (!regexString.empty()) {
- regexString += "";
- boost::regex emoticonRegex(regexString);
-
- ChatWindow::ChatMessage newMessage;
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, parsedMessage.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- try {
- boost::match_results<std::string::const_iterator> match;
- const std::string& text = textPart->text;
- std::string::const_iterator start = text.begin();
- while (regex_search(start, text.end(), match, emoticonRegex)) {
- int matchIndex = 0;
- for (matchIndex = 1; matchIndex < static_cast<int>(match.size()); matchIndex++) {
- if (match[matchIndex].length() > 0) {
- //This is the matching subgroup
- break;
- }
- }
- std::string::const_iterator matchStart = match[matchIndex].first;
- std::string::const_iterator matchEnd = match[matchIndex].second;
- if (start != matchStart) {
- /* If we're skipping over plain text since the previous emoticon, record it as plain text */
- newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
- }
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart = boost::make_shared<ChatWindow::ChatEmoticonMessagePart>();
- std::string matchString = match[matchIndex].str();
- std::map<std::string, std::string>::const_iterator emoticonIterator = emoticons_.find(matchString);
- assert (emoticonIterator != emoticons_.end());
- const StringPair& emoticon = *emoticonIterator;
- emoticonPart->imagePath = emoticon.second;
- emoticonPart->alternativeText = emoticon.first;
- newMessage.append(emoticonPart);
- start = matchEnd;
- }
- if (start != text.end()) {
- /* If there's plain text after the last emoticon, record it */
- newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, text.end())));
- }
-
- }
- catch (std::runtime_error) {
- /* Basically too expensive to compute the regex results and it gave up, so pass through as text */
- newMessage.append(part);
- }
- }
- else {
- newMessage.append(part);
- }
- }
- parsedMessage = newMessage;
-
- }
- return parsedMessage;
- }
-
- ChatWindow::ChatMessage ChatMessageParser::splitHighlight(const ChatWindow::ChatMessage& message, const std::string& nick)
- {
- ChatWindow::ChatMessage parsedMessage = message;
-
- for (size_t i = 0; i < highlightRules_->getSize(); ++i) {
- const HighlightRule& rule = highlightRules_->getRule(i);
- if (rule.getMatchMUC() && !mucMode_) {
- continue; /* this rule only applies to MUC's, and this is a CHAT */
- } else if (rule.getMatchChat() && mucMode_) {
- continue; /* this rule only applies to CHAT's, and this is a MUC */
- } else if (rule.getAction().getTextBackground().empty() && rule.getAction().getTextColor().empty()) {
- continue; /* do not try to highlight text, if no highlight color is specified */
- }
- const std::vector<boost::regex> keywordRegex = rule.getKeywordRegex(nick);
- foreach(const boost::regex& regex, keywordRegex) {
- ChatWindow::ChatMessage newMessage;
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, parsedMessage.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- try {
- boost::match_results<std::string::const_iterator> match;
- const std::string& text = textPart->text;
- std::string::const_iterator start = text.begin();
- while (regex_search(start, text.end(), match, regex)) {
- std::string::const_iterator matchStart = match[0].first;
- std::string::const_iterator matchEnd = match[0].second;
- if (start != matchStart) {
- /* If we're skipping over plain text since the previous emoticon, record it as plain text */
- newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
- }
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart = boost::make_shared<ChatWindow::ChatHighlightingMessagePart>();
- highlightPart->text = match.str();
- highlightPart->action = rule.getAction();
- newMessage.append(highlightPart);
- start = matchEnd;
- }
- if (start != text.end()) {
- /* If there's plain text after the last emoticon, record it */
- newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, text.end())));
- }
- }
- catch (std::runtime_error) {
- /* Basically too expensive to compute the regex results and it gave up, so pass through as text */
- newMessage.append(part);
- }
- } else {
- newMessage.append(part);
- }
- }
- parsedMessage = newMessage;
- }
- }
-
- return parsedMessage;
- }
+ ChatMessageParser::ChatMessageParser(const std::map<std::string, std::string>& emoticons, HighlightRulesListPtr highlightRules, bool mucMode)
+ : emoticons_(emoticons), highlightRules_(highlightRules), mucMode_(mucMode) {
+ }
+
+ typedef std::pair<std::string, std::string> StringPair;
+
+ ChatWindow::ChatMessage ChatMessageParser::parseMessageBody(const std::string& body, const std::string& nick, bool senderIsSelf) {
+ ChatWindow::ChatMessage parsedMessage;
+ std::string remaining = body;
+ /* Parse one, URLs */
+ while (!remaining.empty()) {
+ bool found = false;
+ std::pair<std::vector<std::string>, size_t> links = Linkify::splitLink(remaining);
+ remaining = "";
+ for (size_t i = 0; i < links.first.size(); i++) {
+ const std::string& part = links.first[i];
+ if (found) {
+ // Must be on the last part, then
+ remaining = part;
+ }
+ else {
+ if (i == links.second) {
+ found = true;
+ parsedMessage.append(boost::make_shared<ChatWindow::ChatURIMessagePart>(part));
+ }
+ else {
+ parsedMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(part));
+ }
+ }
+ }
+ }
+
+ /* do emoticon substitution */
+ parsedMessage = emoticonHighlight(parsedMessage);
+
+ if (!senderIsSelf) { /* do not highlight our own messsages */
+ /* do word-based color highlighting */
+ parsedMessage = splitHighlight(parsedMessage, nick);
+ }
+
+ return parsedMessage;
+ }
+
+ ChatWindow::ChatMessage ChatMessageParser::emoticonHighlight(const ChatWindow::ChatMessage& message)
+ {
+ ChatWindow::ChatMessage parsedMessage = message;
+
+ std::string regexString;
+ /* Parse two, emoticons */
+ foreach (StringPair emoticon, emoticons_) {
+ /* Construct a regexp that finds an instance of any of the emoticons inside a group
+ * at the start or end of the line, or beside whitespace.
+ */
+ regexString += regexString.empty() ? "" : "|";
+ std::string escaped = "(" + Regex::escape(emoticon.first) + ")";
+ regexString += "^" + escaped + "|";
+ regexString += escaped + "$|";
+ regexString += "\\s" + escaped + "|";
+ regexString += escaped + "\\s";
+
+ }
+ if (!regexString.empty()) {
+ regexString += "";
+ boost::regex emoticonRegex(regexString);
+
+ ChatWindow::ChatMessage newMessage;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, parsedMessage.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ try {
+ boost::match_results<std::string::const_iterator> match;
+ const std::string& text = textPart->text;
+ std::string::const_iterator start = text.begin();
+ while (regex_search(start, text.end(), match, emoticonRegex)) {
+ int matchIndex = 0;
+ for (matchIndex = 1; matchIndex < static_cast<int>(match.size()); matchIndex++) {
+ if (match[matchIndex].length() > 0) {
+ //This is the matching subgroup
+ break;
+ }
+ }
+ std::string::const_iterator matchStart = match[matchIndex].first;
+ std::string::const_iterator matchEnd = match[matchIndex].second;
+ if (start != matchStart) {
+ /* If we're skipping over plain text since the previous emoticon, record it as plain text */
+ newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
+ }
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart = boost::make_shared<ChatWindow::ChatEmoticonMessagePart>();
+ std::string matchString = match[matchIndex].str();
+ std::map<std::string, std::string>::const_iterator emoticonIterator = emoticons_.find(matchString);
+ assert (emoticonIterator != emoticons_.end());
+ const StringPair& emoticon = *emoticonIterator;
+ emoticonPart->imagePath = emoticon.second;
+ emoticonPart->alternativeText = emoticon.first;
+ newMessage.append(emoticonPart);
+ start = matchEnd;
+ }
+ if (start != text.end()) {
+ /* If there's plain text after the last emoticon, record it */
+ newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, text.end())));
+ }
+
+ }
+ catch (std::runtime_error) {
+ /* Basically too expensive to compute the regex results and it gave up, so pass through as text */
+ newMessage.append(part);
+ }
+ }
+ else {
+ newMessage.append(part);
+ }
+ }
+ parsedMessage = newMessage;
+
+ }
+ return parsedMessage;
+ }
+
+ ChatWindow::ChatMessage ChatMessageParser::splitHighlight(const ChatWindow::ChatMessage& message, const std::string& nick)
+ {
+ ChatWindow::ChatMessage parsedMessage = message;
+
+ for (size_t i = 0; i < highlightRules_->getSize(); ++i) {
+ const HighlightRule& rule = highlightRules_->getRule(i);
+ if (rule.getMatchMUC() && !mucMode_) {
+ continue; /* this rule only applies to MUC's, and this is a CHAT */
+ } else if (rule.getMatchChat() && mucMode_) {
+ continue; /* this rule only applies to CHAT's, and this is a MUC */
+ } else if (rule.getAction().getTextBackground().empty() && rule.getAction().getTextColor().empty()) {
+ continue; /* do not try to highlight text, if no highlight color is specified */
+ }
+ const std::vector<boost::regex> keywordRegex = rule.getKeywordRegex(nick);
+ foreach(const boost::regex& regex, keywordRegex) {
+ ChatWindow::ChatMessage newMessage;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, parsedMessage.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ try {
+ boost::match_results<std::string::const_iterator> match;
+ const std::string& text = textPart->text;
+ std::string::const_iterator start = text.begin();
+ while (regex_search(start, text.end(), match, regex)) {
+ std::string::const_iterator matchStart = match[0].first;
+ std::string::const_iterator matchEnd = match[0].second;
+ if (start != matchStart) {
+ /* If we're skipping over plain text since the previous emoticon, record it as plain text */
+ newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
+ }
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart = boost::make_shared<ChatWindow::ChatHighlightingMessagePart>();
+ highlightPart->text = match.str();
+ highlightPart->action = rule.getAction();
+ newMessage.append(highlightPart);
+ start = matchEnd;
+ }
+ if (start != text.end()) {
+ /* If there's plain text after the last emoticon, record it */
+ newMessage.append(boost::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, text.end())));
+ }
+ }
+ catch (std::runtime_error) {
+ /* Basically too expensive to compute the regex results and it gave up, so pass through as text */
+ newMessage.append(part);
+ }
+ } else {
+ newMessage.append(part);
+ }
+ }
+ parsedMessage = newMessage;
+ }
+ }
+
+ return parsedMessage;
+ }
}
diff --git a/Swift/Controllers/Chat/ChatMessageParser.h b/Swift/Controllers/Chat/ChatMessageParser.h
index e56d21b..4bed669 100644
--- a/Swift/Controllers/Chat/ChatMessageParser.h
+++ b/Swift/Controllers/Chat/ChatMessageParser.h
@@ -12,15 +12,15 @@
namespace Swift {
- class ChatMessageParser {
- public:
- ChatMessageParser(const std::map<std::string, std::string>& emoticons, HighlightRulesListPtr highlightRules, bool mucMode = false);
- ChatWindow::ChatMessage parseMessageBody(const std::string& body, const std::string& nick = "", bool senderIsSelf = false);
- private:
- ChatWindow::ChatMessage emoticonHighlight(const ChatWindow::ChatMessage& parsedMessage);
- ChatWindow::ChatMessage splitHighlight(const ChatWindow::ChatMessage& parsedMessage, const std::string& nick);
- std::map<std::string, std::string> emoticons_;
- HighlightRulesListPtr highlightRules_;
- bool mucMode_;
- };
+ class ChatMessageParser {
+ public:
+ ChatMessageParser(const std::map<std::string, std::string>& emoticons, HighlightRulesListPtr highlightRules, bool mucMode = false);
+ ChatWindow::ChatMessage parseMessageBody(const std::string& body, const std::string& nick = "", bool senderIsSelf = false);
+ private:
+ ChatWindow::ChatMessage emoticonHighlight(const ChatWindow::ChatMessage& parsedMessage);
+ ChatWindow::ChatMessage splitHighlight(const ChatWindow::ChatMessage& parsedMessage, const std::string& nick);
+ std::map<std::string, std::string> emoticons_;
+ HighlightRulesListPtr highlightRules_;
+ bool mucMode_;
+ };
}
diff --git a/Swift/Controllers/Chat/ChatsManager.cpp b/Swift/Controllers/Chat/ChatsManager.cpp
index 49caee4..32da58a 100644
--- a/Swift/Controllers/Chat/ChatsManager.cpp
+++ b/Swift/Controllers/Chat/ChatsManager.cpp
@@ -67,32 +67,32 @@ BOOST_CLASS_VERSION(Swift::ChatListWindow::Chat, 1)
namespace boost {
namespace serialization {
- template<class Archive> void save(Archive& ar, const Swift::JID& jid, const unsigned int /*version*/) {
- std::string jidStr = jid.toString();
- ar << jidStr;
- }
-
- template<class Archive> void load(Archive& ar, Swift::JID& jid, const unsigned int /*version*/) {
- std::string stringJID;
- ar >> stringJID;
- jid = Swift::JID(stringJID);
- }
-
- template<class Archive> inline void serialize(Archive& ar, Swift::JID& t, const unsigned int file_version){
- split_free(ar, t, file_version);
- }
-
- template<class Archive> void serialize(Archive& ar, Swift::ChatListWindow::Chat& chat, const unsigned int version) {
- ar & chat.jid;
- ar & chat.chatName;
- ar & chat.activity;
- ar & chat.isMUC;
- ar & chat.nick;
- ar & chat.impromptuJIDs;
- if (version > 0) {
- ar & chat.password;
- }
- }
+ template<class Archive> void save(Archive& ar, const Swift::JID& jid, const unsigned int /*version*/) {
+ std::string jidStr = jid.toString();
+ ar << jidStr;
+ }
+
+ template<class Archive> void load(Archive& ar, Swift::JID& jid, const unsigned int /*version*/) {
+ std::string stringJID;
+ ar >> stringJID;
+ jid = Swift::JID(stringJID);
+ }
+
+ template<class Archive> inline void serialize(Archive& ar, Swift::JID& t, const unsigned int file_version){
+ split_free(ar, t, file_version);
+ }
+
+ template<class Archive> void serialize(Archive& ar, Swift::ChatListWindow::Chat& chat, const unsigned int version) {
+ ar & chat.jid;
+ ar & chat.chatName;
+ ar & chat.activity;
+ ar & chat.isMUC;
+ ar & chat.nick;
+ ar & chat.impromptuJIDs;
+ if (version > 0) {
+ ar & chat.password;
+ }
+ }
}
}
@@ -104,950 +104,950 @@ typedef std::pair<JID, MUCController*> JIDMUCControllerPair;
#define RECENT_CHATS "recent_chats"
ChatsManager::ChatsManager(
- JID jid, StanzaChannel* stanzaChannel,
- IQRouter* iqRouter,
- EventController* eventController,
- ChatWindowFactory* chatWindowFactory,
- JoinMUCWindowFactory* joinMUCWindowFactory,
- NickResolver* nickResolver,
- PresenceOracle* presenceOracle,
- PresenceSender* presenceSender,
- UIEventStream* uiEventStream,
- ChatListWindowFactory* chatListWindowFactory,
- bool useDelayForLatency,
- TimerFactory* timerFactory,
- MUCRegistry* mucRegistry,
- EntityCapsProvider* entityCapsProvider,
- MUCManager* mucManager,
- MUCSearchWindowFactory* mucSearchWindowFactory,
- ProfileSettingsProvider* profileSettings,
- FileTransferOverview* ftOverview,
- XMPPRoster* roster,
- bool eagleMode,
- SettingsProvider* settings,
- HistoryController* historyController,
- WhiteboardManager* whiteboardManager,
- HighlightManager* highlightManager,
- ClientBlockListManager* clientBlockListManager,
- const std::map<std::string, std::string>& emoticons,
- VCardManager* vcardManager) :
- jid_(jid),
- joinMUCWindowFactory_(joinMUCWindowFactory),
- useDelayForLatency_(useDelayForLatency),
- mucRegistry_(mucRegistry),
- entityCapsProvider_(entityCapsProvider),
- mucManager(mucManager),
- ftOverview_(ftOverview),
- roster_(roster),
- eagleMode_(eagleMode),
- settings_(settings),
- historyController_(historyController),
- whiteboardManager_(whiteboardManager),
- highlightManager_(highlightManager),
- emoticons_(emoticons),
- clientBlockListManager_(clientBlockListManager),
- vcardManager_(vcardManager) {
- timerFactory_ = timerFactory;
- eventController_ = eventController;
- stanzaChannel_ = stanzaChannel;
- iqRouter_ = iqRouter;
- chatWindowFactory_ = chatWindowFactory;
- nickResolver_ = nickResolver;
- presenceOracle_ = presenceOracle;
- avatarManager_ = NULL;
- serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
- presenceSender_ = presenceSender;
- uiEventStream_ = uiEventStream;
- mucBookmarkManager_ = NULL;
- profileSettings_ = profileSettings;
- presenceOracle_->onPresenceChange.connect(boost::bind(&ChatsManager::handlePresenceChange, this, _1));
- uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&ChatsManager::handleUIEvent, this, _1));
-
- chatListWindow_ = chatListWindowFactory->createChatListWindow(uiEventStream_);
- chatListWindow_->onMUCBookmarkActivated.connect(boost::bind(&ChatsManager::handleMUCBookmarkActivated, this, _1));
- chatListWindow_->onRecentActivated.connect(boost::bind(&ChatsManager::handleRecentActivated, this, _1));
- chatListWindow_->onClearRecentsRequested.connect(boost::bind(&ChatsManager::handleClearRecentsRequested, this));
-
- joinMUCWindow_ = NULL;
- mucSearchController_ = new MUCSearchController(jid_, mucSearchWindowFactory, iqRouter, profileSettings_);
- mucSearchController_->onMUCSelected.connect(boost::bind(&ChatsManager::handleMUCSelectedAfterSearch, this, _1));
- ftOverview_->onNewFileTransferController.connect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1));
- whiteboardManager_->onSessionRequest.connect(boost::bind(&ChatsManager::handleWhiteboardSessionRequest, this, _1, _2));
- whiteboardManager_->onRequestAccepted.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardAccepted));
- whiteboardManager_->onSessionTerminate.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardTerminated));
- whiteboardManager_->onRequestRejected.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardRejected));
- roster_->onJIDAdded.connect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
- roster_->onJIDRemoved.connect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
- roster_->onJIDUpdated.connect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
- roster_->onRosterCleared.connect(boost::bind(&ChatsManager::handleRosterCleared, this));
-
- settings_->onSettingChanged.connect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
-
- userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
-
- setupBookmarks();
- loadRecents();
-
- autoAcceptMUCInviteDecider_ = new AutoAcceptMUCInviteDecider(jid.getDomain(), roster_, settings_);
+ JID jid, StanzaChannel* stanzaChannel,
+ IQRouter* iqRouter,
+ EventController* eventController,
+ ChatWindowFactory* chatWindowFactory,
+ JoinMUCWindowFactory* joinMUCWindowFactory,
+ NickResolver* nickResolver,
+ PresenceOracle* presenceOracle,
+ PresenceSender* presenceSender,
+ UIEventStream* uiEventStream,
+ ChatListWindowFactory* chatListWindowFactory,
+ bool useDelayForLatency,
+ TimerFactory* timerFactory,
+ MUCRegistry* mucRegistry,
+ EntityCapsProvider* entityCapsProvider,
+ MUCManager* mucManager,
+ MUCSearchWindowFactory* mucSearchWindowFactory,
+ ProfileSettingsProvider* profileSettings,
+ FileTransferOverview* ftOverview,
+ XMPPRoster* roster,
+ bool eagleMode,
+ SettingsProvider* settings,
+ HistoryController* historyController,
+ WhiteboardManager* whiteboardManager,
+ HighlightManager* highlightManager,
+ ClientBlockListManager* clientBlockListManager,
+ const std::map<std::string, std::string>& emoticons,
+ VCardManager* vcardManager) :
+ jid_(jid),
+ joinMUCWindowFactory_(joinMUCWindowFactory),
+ useDelayForLatency_(useDelayForLatency),
+ mucRegistry_(mucRegistry),
+ entityCapsProvider_(entityCapsProvider),
+ mucManager(mucManager),
+ ftOverview_(ftOverview),
+ roster_(roster),
+ eagleMode_(eagleMode),
+ settings_(settings),
+ historyController_(historyController),
+ whiteboardManager_(whiteboardManager),
+ highlightManager_(highlightManager),
+ emoticons_(emoticons),
+ clientBlockListManager_(clientBlockListManager),
+ vcardManager_(vcardManager) {
+ timerFactory_ = timerFactory;
+ eventController_ = eventController;
+ stanzaChannel_ = stanzaChannel;
+ iqRouter_ = iqRouter;
+ chatWindowFactory_ = chatWindowFactory;
+ nickResolver_ = nickResolver;
+ presenceOracle_ = presenceOracle;
+ avatarManager_ = NULL;
+ serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
+ presenceSender_ = presenceSender;
+ uiEventStream_ = uiEventStream;
+ mucBookmarkManager_ = NULL;
+ profileSettings_ = profileSettings;
+ presenceOracle_->onPresenceChange.connect(boost::bind(&ChatsManager::handlePresenceChange, this, _1));
+ uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&ChatsManager::handleUIEvent, this, _1));
+
+ chatListWindow_ = chatListWindowFactory->createChatListWindow(uiEventStream_);
+ chatListWindow_->onMUCBookmarkActivated.connect(boost::bind(&ChatsManager::handleMUCBookmarkActivated, this, _1));
+ chatListWindow_->onRecentActivated.connect(boost::bind(&ChatsManager::handleRecentActivated, this, _1));
+ chatListWindow_->onClearRecentsRequested.connect(boost::bind(&ChatsManager::handleClearRecentsRequested, this));
+
+ joinMUCWindow_ = NULL;
+ mucSearchController_ = new MUCSearchController(jid_, mucSearchWindowFactory, iqRouter, profileSettings_);
+ mucSearchController_->onMUCSelected.connect(boost::bind(&ChatsManager::handleMUCSelectedAfterSearch, this, _1));
+ ftOverview_->onNewFileTransferController.connect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1));
+ whiteboardManager_->onSessionRequest.connect(boost::bind(&ChatsManager::handleWhiteboardSessionRequest, this, _1, _2));
+ whiteboardManager_->onRequestAccepted.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardAccepted));
+ whiteboardManager_->onSessionTerminate.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardTerminated));
+ whiteboardManager_->onRequestRejected.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardRejected));
+ roster_->onJIDAdded.connect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
+ roster_->onJIDRemoved.connect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
+ roster_->onJIDUpdated.connect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
+ roster_->onRosterCleared.connect(boost::bind(&ChatsManager::handleRosterCleared, this));
+
+ settings_->onSettingChanged.connect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
+
+ userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
+
+ setupBookmarks();
+ loadRecents();
+
+ autoAcceptMUCInviteDecider_ = new AutoAcceptMUCInviteDecider(jid.getDomain(), roster_, settings_);
}
ChatsManager::~ChatsManager() {
- settings_->onSettingChanged.disconnect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
- roster_->onJIDAdded.disconnect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
- roster_->onJIDRemoved.disconnect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
- roster_->onJIDUpdated.disconnect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
- roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this));
- delete joinMUCWindow_;
- foreach (JIDChatControllerPair controllerPair, chatControllers_) {
- delete controllerPair.second;
- }
- foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
- delete controllerPair.second;
- }
- delete mucBookmarkManager_;
- delete mucSearchController_;
- delete autoAcceptMUCInviteDecider_;
+ settings_->onSettingChanged.disconnect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
+ roster_->onJIDAdded.disconnect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
+ roster_->onJIDRemoved.disconnect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
+ roster_->onJIDUpdated.disconnect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
+ roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this));
+ delete joinMUCWindow_;
+ foreach (JIDChatControllerPair controllerPair, chatControllers_) {
+ delete controllerPair.second;
+ }
+ foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
+ delete controllerPair.second;
+ }
+ delete mucBookmarkManager_;
+ delete mucSearchController_;
+ delete autoAcceptMUCInviteDecider_;
}
void ChatsManager::saveRecents() {
- std::stringstream serializeStream;
- boost::archive::text_oarchive oa(serializeStream);
- std::vector<ChatListWindow::Chat> recentsLimited = std::vector<ChatListWindow::Chat>(recentChats_.begin(), recentChats_.end());
- if (recentsLimited.size() > 25) {
- recentsLimited.erase(recentsLimited.begin() + 25, recentsLimited.end());
- }
- if (eagleMode_) {
- foreach(ChatListWindow::Chat& chat, recentsLimited) {
- chat.activity = "";
- }
- }
-
- class RemoveRecent {
- public:
- static bool ifPrivateMessage(const ChatListWindow::Chat& chat) {
- return chat.isPrivateMessage;
- }
- };
-
- recentsLimited.erase(std::remove_if(recentsLimited.begin(), recentsLimited.end(), RemoveRecent::ifPrivateMessage), recentsLimited.end());
-
- oa << recentsLimited;
- std::string serializedStr = Base64::encode(createByteArray(serializeStream.str()));
- profileSettings_->storeString(RECENT_CHATS, serializedStr);
+ std::stringstream serializeStream;
+ boost::archive::text_oarchive oa(serializeStream);
+ std::vector<ChatListWindow::Chat> recentsLimited = std::vector<ChatListWindow::Chat>(recentChats_.begin(), recentChats_.end());
+ if (recentsLimited.size() > 25) {
+ recentsLimited.erase(recentsLimited.begin() + 25, recentsLimited.end());
+ }
+ if (eagleMode_) {
+ foreach(ChatListWindow::Chat& chat, recentsLimited) {
+ chat.activity = "";
+ }
+ }
+
+ class RemoveRecent {
+ public:
+ static bool ifPrivateMessage(const ChatListWindow::Chat& chat) {
+ return chat.isPrivateMessage;
+ }
+ };
+
+ recentsLimited.erase(std::remove_if(recentsLimited.begin(), recentsLimited.end(), RemoveRecent::ifPrivateMessage), recentsLimited.end());
+
+ oa << recentsLimited;
+ std::string serializedStr = Base64::encode(createByteArray(serializeStream.str()));
+ profileSettings_->storeString(RECENT_CHATS, serializedStr);
}
void ChatsManager::handleClearRecentsRequested() {
- recentChats_.clear();
- saveRecents();
- handleUnreadCountChanged(NULL);
+ recentChats_.clear();
+ saveRecents();
+ handleUnreadCountChanged(NULL);
}
void ChatsManager::handleJIDAddedToRoster(const JID &jid) {
- updatePresenceReceivingStateOnChatController(jid);
+ updatePresenceReceivingStateOnChatController(jid);
}
void ChatsManager::handleJIDRemovedFromRoster(const JID &jid) {
- updatePresenceReceivingStateOnChatController(jid);
+ updatePresenceReceivingStateOnChatController(jid);
}
void ChatsManager::handleJIDUpdatedInRoster(const JID &jid) {
- updatePresenceReceivingStateOnChatController(jid);
+ updatePresenceReceivingStateOnChatController(jid);
}
void ChatsManager::handleRosterCleared() {
- /* Setting that all chat controllers aren't receiving presence anymore;
- including MUC 1-to-1 chats due to the assumtion that this handler
- is only called on log out. */
- foreach(JIDChatControllerPair pair, chatControllers_) {
- pair.second->setContactIsReceivingPresence(false);
- }
+ /* Setting that all chat controllers aren't receiving presence anymore;
+ including MUC 1-to-1 chats due to the assumtion that this handler
+ is only called on log out. */
+ foreach(JIDChatControllerPair pair, chatControllers_) {
+ pair.second->setContactIsReceivingPresence(false);
+ }
}
void ChatsManager::updatePresenceReceivingStateOnChatController(const JID &jid) {
- ChatController* controller = getChatControllerIfExists(jid);
- if (controller) {
- if (!mucRegistry_->isMUC(jid.toBare())) {
- RosterItemPayload::Subscription subscription = roster_->getSubscriptionStateForJID(jid);
- controller->setContactIsReceivingPresence(subscription == RosterItemPayload::From || subscription == RosterItemPayload::Both);
- } else {
- controller->setContactIsReceivingPresence(true);
- }
- }
+ ChatController* controller = getChatControllerIfExists(jid);
+ if (controller) {
+ if (!mucRegistry_->isMUC(jid.toBare())) {
+ RosterItemPayload::Subscription subscription = roster_->getSubscriptionStateForJID(jid);
+ controller->setContactIsReceivingPresence(subscription == RosterItemPayload::From || subscription == RosterItemPayload::Both);
+ } else {
+ controller->setContactIsReceivingPresence(true);
+ }
+ }
}
ChatListWindow::Chat ChatsManager::updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const {
- ChatListWindow::Chat fixedChat = chat;
- if (fixedChat.isMUC) {
- if (mucControllers_.find(fixedChat.jid.toBare()) != mucControllers_.end()) {
- fixedChat.statusType = StatusShow::Online;
- }
- } else {
- if (avatarManager_) {
- fixedChat.avatarPath = avatarManager_->getAvatarPath(fixedChat.jid);
- }
- Presence::ref presence = presenceOracle_->getAccountPresence(fixedChat.jid.toBare());
- fixedChat.statusType = presence ? presence->getShow() : StatusShow::None;
- }
- return fixedChat;
+ ChatListWindow::Chat fixedChat = chat;
+ if (fixedChat.isMUC) {
+ if (mucControllers_.find(fixedChat.jid.toBare()) != mucControllers_.end()) {
+ fixedChat.statusType = StatusShow::Online;
+ }
+ } else {
+ if (avatarManager_) {
+ fixedChat.avatarPath = avatarManager_->getAvatarPath(fixedChat.jid);
+ }
+ Presence::ref presence = presenceOracle_->getAccountPresence(fixedChat.jid.toBare());
+ fixedChat.statusType = presence ? presence->getShow() : StatusShow::None;
+ }
+ return fixedChat;
}
void ChatsManager::loadRecents() {
- std::string recentsString(profileSettings_->getStringSetting(RECENT_CHATS));
- if (recentsString.find("\t") != std::string::npos) {
- // old format
- std::vector<std::string> recents;
- boost::split(recents, recentsString, boost::is_any_of("\n"));
- int i = 0;
- foreach (std::string recentString, recents) {
- if (i++ > 30) {
- break;
- }
- std::vector<std::string> recent;
- boost::split(recent, recentString, boost::is_any_of("\t"));
- if (recent.size() < 4) {
- continue;
- }
- JID jid(recent[0]);
- if (!jid.isValid()) {
- continue;
- }
- std::string activity(recent[1]);
- bool isMUC = recent[2] == "true";
- std::string nick(recent[3]);
- StatusShow::Type type = StatusShow::None;
- boost::filesystem::path path;
-
- ChatListWindow::Chat chat(jid, nickResolver_->jidToNick(jid), activity, 0, type, path, isMUC, false, nick);
- chat = updateChatStatusAndAvatarHelper(chat);
- prependRecent(chat);
- }
- } else if (!recentsString.empty()){
- // boost searilaize based format
- ByteArray debase64 = Base64::decode(recentsString);
- std::vector<ChatListWindow::Chat> recentChats;
- std::stringstream deserializeStream(std::string(reinterpret_cast<const char*>(vecptr(debase64)), debase64.size()));
- try {
- boost::archive::text_iarchive ia(deserializeStream);
- ia >> recentChats;
- } catch (const boost::archive::archive_exception& e) {
- SWIFT_LOG(debug) << "Failed to load recents: " << e.what() << std::endl;
- return;
- }
-
- foreach(ChatListWindow::Chat chat, recentChats) {
- chat.statusType = StatusShow::None;
- chat = updateChatStatusAndAvatarHelper(chat);
- prependRecent(chat);
- }
- }
- handleUnreadCountChanged(NULL);
+ std::string recentsString(profileSettings_->getStringSetting(RECENT_CHATS));
+ if (recentsString.find("\t") != std::string::npos) {
+ // old format
+ std::vector<std::string> recents;
+ boost::split(recents, recentsString, boost::is_any_of("\n"));
+ int i = 0;
+ foreach (std::string recentString, recents) {
+ if (i++ > 30) {
+ break;
+ }
+ std::vector<std::string> recent;
+ boost::split(recent, recentString, boost::is_any_of("\t"));
+ if (recent.size() < 4) {
+ continue;
+ }
+ JID jid(recent[0]);
+ if (!jid.isValid()) {
+ continue;
+ }
+ std::string activity(recent[1]);
+ bool isMUC = recent[2] == "true";
+ std::string nick(recent[3]);
+ StatusShow::Type type = StatusShow::None;
+ boost::filesystem::path path;
+
+ ChatListWindow::Chat chat(jid, nickResolver_->jidToNick(jid), activity, 0, type, path, isMUC, false, nick);
+ chat = updateChatStatusAndAvatarHelper(chat);
+ prependRecent(chat);
+ }
+ } else if (!recentsString.empty()){
+ // boost searilaize based format
+ ByteArray debase64 = Base64::decode(recentsString);
+ std::vector<ChatListWindow::Chat> recentChats;
+ std::stringstream deserializeStream(std::string(reinterpret_cast<const char*>(vecptr(debase64)), debase64.size()));
+ try {
+ boost::archive::text_iarchive ia(deserializeStream);
+ ia >> recentChats;
+ } catch (const boost::archive::archive_exception& e) {
+ SWIFT_LOG(debug) << "Failed to load recents: " << e.what() << std::endl;
+ return;
+ }
+
+ foreach(ChatListWindow::Chat chat, recentChats) {
+ chat.statusType = StatusShow::None;
+ chat = updateChatStatusAndAvatarHelper(chat);
+ prependRecent(chat);
+ }
+ }
+ handleUnreadCountChanged(NULL);
}
void ChatsManager::setupBookmarks() {
- if (!mucBookmarkManager_) {
- mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_);
- mucBookmarkManager_->onBookmarksReady.connect(boost::bind(&ChatsManager::handleBookmarksReady, this));
- mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&ChatsManager::handleMUCBookmarkAdded, this, _1));
- mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&ChatsManager::handleMUCBookmarkRemoved, this, _1));
-
- if (chatListWindow_) {
- chatListWindow_->setBookmarksEnabled(false);
- chatListWindow_->clearBookmarks();
- }
- }
+ if (!mucBookmarkManager_) {
+ mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_);
+ mucBookmarkManager_->onBookmarksReady.connect(boost::bind(&ChatsManager::handleBookmarksReady, this));
+ mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&ChatsManager::handleMUCBookmarkAdded, this, _1));
+ mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&ChatsManager::handleMUCBookmarkRemoved, this, _1));
+
+ if (chatListWindow_) {
+ chatListWindow_->setBookmarksEnabled(false);
+ chatListWindow_->clearBookmarks();
+ }
+ }
}
void ChatsManager::handleBookmarksReady() {
- if (chatListWindow_) {
- chatListWindow_->setBookmarksEnabled(true);
- }
+ if (chatListWindow_) {
+ chatListWindow_->setBookmarksEnabled(true);
+ }
}
void ChatsManager::handleMUCBookmarkAdded(const MUCBookmark& bookmark) {
- std::map<JID, MUCController*>::iterator it = mucControllers_.find(bookmark.getRoom());
- if (it == mucControllers_.end() && bookmark.getAutojoin()) {
- handleJoinMUCRequest(bookmark.getRoom(), bookmark.getPassword(), bookmark.getNick(), false, false, false );
- }
- chatListWindow_->addMUCBookmark(bookmark);
+ std::map<JID, MUCController*>::iterator it = mucControllers_.find(bookmark.getRoom());
+ if (it == mucControllers_.end() && bookmark.getAutojoin()) {
+ handleJoinMUCRequest(bookmark.getRoom(), bookmark.getPassword(), bookmark.getNick(), false, false, false );
+ }
+ chatListWindow_->addMUCBookmark(bookmark);
}
void ChatsManager::handleMUCBookmarkRemoved(const MUCBookmark& bookmark) {
- chatListWindow_->removeMUCBookmark(bookmark);
+ chatListWindow_->removeMUCBookmark(bookmark);
}
ChatListWindow::Chat ChatsManager::createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage) {
- int unreadCount = 0;
- if (mucRegistry_->isMUC(jid)) {
- MUCController* controller = mucControllers_[jid.toBare()];
- StatusShow::Type type = StatusShow::None;
- std::string nick = "";
- std::string password = "";
- if (controller) {
- unreadCount = controller->getUnreadCount();
- if (controller->isJoined()) {
- type = StatusShow::Online;
- }
- nick = controller->getNick();
-
- if (controller->getPassword()) {
- password = *controller->getPassword();
- }
-
- if (controller->isImpromptu()) {
- ChatListWindow::Chat chat = ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password);
- std::map<std::string, JID> participants = controller->getParticipantJIDs();
- chat.impromptuJIDs = participants;
- return chat;
- }
- }
- return ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password);
- } else {
- ChatController* controller = getChatControllerIfExists(jid, false);
- if (controller) {
- unreadCount = controller->getUnreadCount();
- }
- JID bareishJID = mucRegistry_->isMUC(jid.toBare()) ? jid : jid.toBare();
- Presence::ref presence = presenceOracle_->getAccountPresence(bareishJID);
- StatusShow::Type type = presence ? presence->getShow() : StatusShow::None;
- boost::filesystem::path avatarPath = avatarManager_ ? avatarManager_->getAvatarPath(bareishJID) : boost::filesystem::path();
- return ChatListWindow::Chat(bareishJID, nickResolver_->jidToNick(bareishJID), activity, unreadCount, type, avatarPath, false, privateMessage);
- }
+ int unreadCount = 0;
+ if (mucRegistry_->isMUC(jid)) {
+ MUCController* controller = mucControllers_[jid.toBare()];
+ StatusShow::Type type = StatusShow::None;
+ std::string nick = "";
+ std::string password = "";
+ if (controller) {
+ unreadCount = controller->getUnreadCount();
+ if (controller->isJoined()) {
+ type = StatusShow::Online;
+ }
+ nick = controller->getNick();
+
+ if (controller->getPassword()) {
+ password = *controller->getPassword();
+ }
+
+ if (controller->isImpromptu()) {
+ ChatListWindow::Chat chat = ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password);
+ std::map<std::string, JID> participants = controller->getParticipantJIDs();
+ chat.impromptuJIDs = participants;
+ return chat;
+ }
+ }
+ return ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password);
+ } else {
+ ChatController* controller = getChatControllerIfExists(jid, false);
+ if (controller) {
+ unreadCount = controller->getUnreadCount();
+ }
+ JID bareishJID = mucRegistry_->isMUC(jid.toBare()) ? jid : jid.toBare();
+ Presence::ref presence = presenceOracle_->getAccountPresence(bareishJID);
+ StatusShow::Type type = presence ? presence->getShow() : StatusShow::None;
+ boost::filesystem::path avatarPath = avatarManager_ ? avatarManager_->getAvatarPath(bareishJID) : boost::filesystem::path();
+ return ChatListWindow::Chat(bareishJID, nickResolver_->jidToNick(bareishJID), activity, unreadCount, type, avatarPath, false, privateMessage);
+ }
}
void ChatsManager::handleChatActivity(const JID& jid, const std::string& activity, bool isMUC) {
- const bool privateMessage = mucRegistry_->isMUC(jid.toBare()) && !isMUC;
- ChatListWindow::Chat chat = createChatListChatItem(jid, activity, privateMessage);
- /* FIXME: handle nick changes */
- appendRecent(chat);
- handleUnreadCountChanged(NULL);
- saveRecents();
+ const bool privateMessage = mucRegistry_->isMUC(jid.toBare()) && !isMUC;
+ ChatListWindow::Chat chat = createChatListChatItem(jid, activity, privateMessage);
+ /* FIXME: handle nick changes */
+ appendRecent(chat);
+ handleUnreadCountChanged(NULL);
+ saveRecents();
}
void ChatsManager::handleChatClosed(const JID& /*jid*/) {
- cleanupPrivateMessageRecents();
- chatListWindow_->setRecents(recentChats_);
+ cleanupPrivateMessageRecents();
+ chatListWindow_->setRecents(recentChats_);
}
void ChatsManager::handleUnreadCountChanged(ChatControllerBase* controller) {
- int unreadTotal = 0;
- bool controllerIsMUC = dynamic_cast<MUCController*>(controller);
- bool isPM = controller && !controllerIsMUC && mucRegistry_->isMUC(controller->getToJID().toBare());
- foreach (ChatListWindow::Chat& chatItem, recentChats_) {
- bool match = false;
- if (controller) {
- /* Matching MUC item */
- match |= chatItem.isMUC == controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare();
- /* Matching PM */
- match |= isPM && chatItem.jid == controller->getToJID();
- /* Matching non-PM */
- match |= !isPM && !controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare();
- }
- if (match) {
- chatItem.setUnreadCount(controller->getUnreadCount());
- }
- unreadTotal += chatItem.unreadCount;
- }
- chatListWindow_->setRecents(recentChats_);
- chatListWindow_->setUnreadCount(unreadTotal);
+ int unreadTotal = 0;
+ bool controllerIsMUC = dynamic_cast<MUCController*>(controller);
+ bool isPM = controller && !controllerIsMUC && mucRegistry_->isMUC(controller->getToJID().toBare());
+ foreach (ChatListWindow::Chat& chatItem, recentChats_) {
+ bool match = false;
+ if (controller) {
+ /* Matching MUC item */
+ match |= chatItem.isMUC == controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare();
+ /* Matching PM */
+ match |= isPM && chatItem.jid == controller->getToJID();
+ /* Matching non-PM */
+ match |= !isPM && !controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare();
+ }
+ if (match) {
+ chatItem.setUnreadCount(controller->getUnreadCount());
+ }
+ unreadTotal += chatItem.unreadCount;
+ }
+ chatListWindow_->setRecents(recentChats_);
+ chatListWindow_->setUnreadCount(unreadTotal);
}
boost::optional<ChatListWindow::Chat> ChatsManager::removeExistingChat(const ChatListWindow::Chat& chat) {
- std::list<ChatListWindow::Chat>::iterator result = std::find(recentChats_.begin(), recentChats_.end(), chat);
- if (result != recentChats_.end()) {
- ChatListWindow::Chat existingChat = *result;
- recentChats_.erase(std::remove(recentChats_.begin(), recentChats_.end(), chat), recentChats_.end());
- return boost::optional<ChatListWindow::Chat>(existingChat);
- } else {
- return boost::optional<ChatListWindow::Chat>();
- }
+ std::list<ChatListWindow::Chat>::iterator result = std::find(recentChats_.begin(), recentChats_.end(), chat);
+ if (result != recentChats_.end()) {
+ ChatListWindow::Chat existingChat = *result;
+ recentChats_.erase(std::remove(recentChats_.begin(), recentChats_.end(), chat), recentChats_.end());
+ return boost::optional<ChatListWindow::Chat>(existingChat);
+ } else {
+ return boost::optional<ChatListWindow::Chat>();
+ }
}
void ChatsManager::cleanupPrivateMessageRecents() {
- /* if we leave a MUC and close a PM, remove it's recent chat entry */
- const std::list<ChatListWindow::Chat> chats = recentChats_;
- foreach (const ChatListWindow::Chat& chat, chats) {
- if (chat.isPrivateMessage) {
- typedef std::map<JID, MUCController*> ControllerMap;
- ControllerMap::iterator muc = mucControllers_.find(chat.jid.toBare());
- if (muc == mucControllers_.end() || !muc->second->isJoined()) {
- ChatController* chatController = getChatControllerIfExists(chat.jid);
- if (!chatController || !chatController->hasOpenWindow()) {
- removeExistingChat(chat);
- break;
- }
- }
- }
- }
+ /* if we leave a MUC and close a PM, remove it's recent chat entry */
+ const std::list<ChatListWindow::Chat> chats = recentChats_;
+ foreach (const ChatListWindow::Chat& chat, chats) {
+ if (chat.isPrivateMessage) {
+ typedef std::map<JID, MUCController*> ControllerMap;
+ ControllerMap::iterator muc = mucControllers_.find(chat.jid.toBare());
+ if (muc == mucControllers_.end() || !muc->second->isJoined()) {
+ ChatController* chatController = getChatControllerIfExists(chat.jid);
+ if (!chatController || !chatController->hasOpenWindow()) {
+ removeExistingChat(chat);
+ break;
+ }
+ }
+ }
+ }
}
void ChatsManager::appendRecent(const ChatListWindow::Chat& chat) {
- boost::optional<ChatListWindow::Chat> oldChat = removeExistingChat(chat);
- ChatListWindow::Chat mergedChat = chat;
- if (oldChat && !oldChat->impromptuJIDs.empty()) {
- mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end());
- }
- recentChats_.push_front(mergedChat);
+ boost::optional<ChatListWindow::Chat> oldChat = removeExistingChat(chat);
+ ChatListWindow::Chat mergedChat = chat;
+ if (oldChat && !oldChat->impromptuJIDs.empty()) {
+ mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end());
+ }
+ recentChats_.push_front(mergedChat);
}
void ChatsManager::prependRecent(const ChatListWindow::Chat& chat) {
- boost::optional<ChatListWindow::Chat> oldChat = removeExistingChat(chat);
- ChatListWindow::Chat mergedChat = chat;
- if (oldChat && !oldChat->impromptuJIDs.empty()) {
- mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end());
- }
- recentChats_.push_back(mergedChat);
+ boost::optional<ChatListWindow::Chat> oldChat = removeExistingChat(chat);
+ ChatListWindow::Chat mergedChat = chat;
+ if (oldChat && !oldChat->impromptuJIDs.empty()) {
+ mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end());
+ }
+ recentChats_.push_back(mergedChat);
}
void ChatsManager::handleUserLeftMUC(MUCController* mucController) {
- std::map<JID, MUCController*>::iterator it;
- for (it = mucControllers_.begin(); it != mucControllers_.end(); ++it) {
- if ((*it).second == mucController) {
- foreach (ChatListWindow::Chat& chat, recentChats_) {
- if (chat.isMUC && chat.jid == (*it).first) {
- chat.statusType = StatusShow::None;
- }
- }
- mucControllers_.erase(it);
- delete mucController;
- break;
- }
- }
- cleanupPrivateMessageRecents();
- chatListWindow_->setRecents(recentChats_);
+ std::map<JID, MUCController*>::iterator it;
+ for (it = mucControllers_.begin(); it != mucControllers_.end(); ++it) {
+ if ((*it).second == mucController) {
+ foreach (ChatListWindow::Chat& chat, recentChats_) {
+ if (chat.isMUC && chat.jid == (*it).first) {
+ chat.statusType = StatusShow::None;
+ }
+ }
+ mucControllers_.erase(it);
+ delete mucController;
+ break;
+ }
+ }
+ cleanupPrivateMessageRecents();
+ chatListWindow_->setRecents(recentChats_);
}
void ChatsManager::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
- userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
- return;
- }
+ if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
+ userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
+ return;
+ }
}
void ChatsManager::finalizeImpromptuJoin(MUC::ref muc, const std::vector<JID>& jidsToInvite, const std::string& reason, const boost::optional<JID>& reuseChatJID) {
- // send impromptu invites for the new MUC
- std::vector<JID> missingJIDsToInvite = jidsToInvite;
-
- typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair;
- std::map<std::string, MUCOccupant> occupants = muc->getOccupants();
- foreach(StringMUCOccupantPair occupant, occupants) {
- boost::optional<JID> realJID = occupant.second.getRealJID();
- if (realJID) {
- missingJIDsToInvite.erase(std::remove(missingJIDsToInvite.begin(), missingJIDsToInvite.end(), realJID->toBare()), missingJIDsToInvite.end());
- }
- }
-
- if (reuseChatJID) {
- muc->invitePerson(reuseChatJID.get(), reason, true, true);
- }
- foreach(const JID& jid, missingJIDsToInvite) {
- muc->invitePerson(jid, reason, true);
- }
+ // send impromptu invites for the new MUC
+ std::vector<JID> missingJIDsToInvite = jidsToInvite;
+
+ typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair;
+ std::map<std::string, MUCOccupant> occupants = muc->getOccupants();
+ foreach(StringMUCOccupantPair occupant, occupants) {
+ boost::optional<JID> realJID = occupant.second.getRealJID();
+ if (realJID) {
+ missingJIDsToInvite.erase(std::remove(missingJIDsToInvite.begin(), missingJIDsToInvite.end(), realJID->toBare()), missingJIDsToInvite.end());
+ }
+ }
+
+ if (reuseChatJID) {
+ muc->invitePerson(reuseChatJID.get(), reason, true, true);
+ }
+ foreach(const JID& jid, missingJIDsToInvite) {
+ muc->invitePerson(jid, reason, true);
+ }
}
void ChatsManager::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- boost::shared_ptr<RequestChatUIEvent> chatEvent = boost::dynamic_pointer_cast<RequestChatUIEvent>(event);
- if (chatEvent) {
- handleChatRequest(chatEvent->getContact());
- return;
- }
- boost::shared_ptr<RemoveMUCBookmarkUIEvent> removeMUCBookmarkEvent = boost::dynamic_pointer_cast<RemoveMUCBookmarkUIEvent>(event);
- if (removeMUCBookmarkEvent) {
- mucBookmarkManager_->removeBookmark(removeMUCBookmarkEvent->getBookmark());
- return;
- }
- boost::shared_ptr<AddMUCBookmarkUIEvent> addMUCBookmarkEvent = boost::dynamic_pointer_cast<AddMUCBookmarkUIEvent>(event);
- if (addMUCBookmarkEvent) {
- mucBookmarkManager_->addBookmark(addMUCBookmarkEvent->getBookmark());
- return;
- }
-
- boost::shared_ptr<CreateImpromptuMUCUIEvent> createImpromptuMUCEvent = boost::dynamic_pointer_cast<CreateImpromptuMUCUIEvent>(event);
- if (createImpromptuMUCEvent) {
- assert(!localMUCServiceJID_.toString().empty());
- // create new muc
- JID roomJID = createImpromptuMUCEvent->getRoomJID().toString().empty() ? JID(idGenerator_.generateID(), localMUCServiceJID_) : createImpromptuMUCEvent->getRoomJID();
-
- // join muc
- MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional<std::string>(), nickResolver_->jidToNick(jid_), false, true, true);
- mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, createImpromptuMUCEvent->getJIDs(), createImpromptuMUCEvent->getReason(), boost::optional<JID>()));
- mucControllers_[roomJID]->activateChatWindow();
- }
-
- boost::shared_ptr<EditMUCBookmarkUIEvent> editMUCBookmarkEvent = boost::dynamic_pointer_cast<EditMUCBookmarkUIEvent>(event);
- if (editMUCBookmarkEvent) {
- mucBookmarkManager_->replaceBookmark(editMUCBookmarkEvent->getOldBookmark(), editMUCBookmarkEvent->getNewBookmark());
- }
- else if (JoinMUCUIEvent::ref joinEvent = boost::dynamic_pointer_cast<JoinMUCUIEvent>(event)) {
- handleJoinMUCRequest(joinEvent->getJID(), joinEvent->getPassword(), joinEvent->getNick(), joinEvent->getShouldJoinAutomatically(), joinEvent->getCreateAsReservedRoomIfNew(), joinEvent->isImpromptu());
- mucControllers_[joinEvent->getJID()]->activateChatWindow();
- }
- else if (boost::shared_ptr<RequestJoinMUCUIEvent> joinEvent = boost::dynamic_pointer_cast<RequestJoinMUCUIEvent>(event)) {
- if (!joinMUCWindow_) {
- joinMUCWindow_ = joinMUCWindowFactory_->createJoinMUCWindow(uiEventStream_);
- joinMUCWindow_->onSearchMUC.connect(boost::bind(&ChatsManager::handleSearchMUCRequest, this));
- }
- joinMUCWindow_->setMUC(joinEvent->getRoom());
- joinMUCWindow_->setNick(nickResolver_->jidToNick(jid_));
- joinMUCWindow_->show();
- }
+ boost::shared_ptr<RequestChatUIEvent> chatEvent = boost::dynamic_pointer_cast<RequestChatUIEvent>(event);
+ if (chatEvent) {
+ handleChatRequest(chatEvent->getContact());
+ return;
+ }
+ boost::shared_ptr<RemoveMUCBookmarkUIEvent> removeMUCBookmarkEvent = boost::dynamic_pointer_cast<RemoveMUCBookmarkUIEvent>(event);
+ if (removeMUCBookmarkEvent) {
+ mucBookmarkManager_->removeBookmark(removeMUCBookmarkEvent->getBookmark());
+ return;
+ }
+ boost::shared_ptr<AddMUCBookmarkUIEvent> addMUCBookmarkEvent = boost::dynamic_pointer_cast<AddMUCBookmarkUIEvent>(event);
+ if (addMUCBookmarkEvent) {
+ mucBookmarkManager_->addBookmark(addMUCBookmarkEvent->getBookmark());
+ return;
+ }
+
+ boost::shared_ptr<CreateImpromptuMUCUIEvent> createImpromptuMUCEvent = boost::dynamic_pointer_cast<CreateImpromptuMUCUIEvent>(event);
+ if (createImpromptuMUCEvent) {
+ assert(!localMUCServiceJID_.toString().empty());
+ // create new muc
+ JID roomJID = createImpromptuMUCEvent->getRoomJID().toString().empty() ? JID(idGenerator_.generateID(), localMUCServiceJID_) : createImpromptuMUCEvent->getRoomJID();
+
+ // join muc
+ MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional<std::string>(), nickResolver_->jidToNick(jid_), false, true, true);
+ mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, createImpromptuMUCEvent->getJIDs(), createImpromptuMUCEvent->getReason(), boost::optional<JID>()));
+ mucControllers_[roomJID]->activateChatWindow();
+ }
+
+ boost::shared_ptr<EditMUCBookmarkUIEvent> editMUCBookmarkEvent = boost::dynamic_pointer_cast<EditMUCBookmarkUIEvent>(event);
+ if (editMUCBookmarkEvent) {
+ mucBookmarkManager_->replaceBookmark(editMUCBookmarkEvent->getOldBookmark(), editMUCBookmarkEvent->getNewBookmark());
+ }
+ else if (JoinMUCUIEvent::ref joinEvent = boost::dynamic_pointer_cast<JoinMUCUIEvent>(event)) {
+ handleJoinMUCRequest(joinEvent->getJID(), joinEvent->getPassword(), joinEvent->getNick(), joinEvent->getShouldJoinAutomatically(), joinEvent->getCreateAsReservedRoomIfNew(), joinEvent->isImpromptu());
+ mucControllers_[joinEvent->getJID()]->activateChatWindow();
+ }
+ else if (boost::shared_ptr<RequestJoinMUCUIEvent> joinEvent = boost::dynamic_pointer_cast<RequestJoinMUCUIEvent>(event)) {
+ if (!joinMUCWindow_) {
+ joinMUCWindow_ = joinMUCWindowFactory_->createJoinMUCWindow(uiEventStream_);
+ joinMUCWindow_->onSearchMUC.connect(boost::bind(&ChatsManager::handleSearchMUCRequest, this));
+ }
+ joinMUCWindow_->setMUC(joinEvent->getRoom());
+ joinMUCWindow_->setNick(nickResolver_->jidToNick(jid_));
+ joinMUCWindow_->show();
+ }
}
void ChatsManager::markAllRecentsOffline() {
- foreach (ChatListWindow::Chat& chat, recentChats_) {
- chat.setStatusType(StatusShow::None);
- }
+ foreach (ChatListWindow::Chat& chat, recentChats_) {
+ chat.setStatusType(StatusShow::None);
+ }
- chatListWindow_->setRecents(recentChats_);
+ chatListWindow_->setRecents(recentChats_);
}
void ChatsManager::handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector<JID>& jidsToInvite, const std::string& reason) {
- JID reuseChatInvite = chatController->getToJID();
- chatControllers_.erase(chatController->getToJID());
- delete chatController;
+ JID reuseChatInvite = chatController->getToJID();
+ chatControllers_.erase(chatController->getToJID());
+ delete chatController;
- // join new impromptu muc
- assert(!localMUCServiceJID_.toString().empty());
+ // join new impromptu muc
+ assert(!localMUCServiceJID_.toString().empty());
- // create new muc
- JID roomJID = JID(idGenerator_.generateID(), localMUCServiceJID_);
+ // create new muc
+ JID roomJID = JID(idGenerator_.generateID(), localMUCServiceJID_);
- // join muc
- MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional<std::string>(), nickResolver_->jidToNick(jid_), false, true, true, chatWindow);
- mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, jidsToInvite, reason, boost::optional<JID>(reuseChatInvite)));
+ // join muc
+ MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional<std::string>(), nickResolver_->jidToNick(jid_), false, true, true, chatWindow);
+ mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, jidsToInvite, reason, boost::optional<JID>(reuseChatInvite)));
}
/**
* If a resource goes offline, release bound chatdialog to that resource.
*/
void ChatsManager::handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
- if (mucRegistry_->isMUC(newPresence->getFrom().toBare())) return;
-
- foreach (ChatListWindow::Chat& chat, recentChats_) {
- if (newPresence->getFrom().toBare() == chat.jid.toBare() && !chat.isMUC) {
- Presence::ref presence = presenceOracle_->getHighestPriorityPresence(chat.jid.toBare());
- chat.setStatusType(presence ? presence->getShow() : StatusShow::None);
- chatListWindow_->setRecents(recentChats_);
- break;
- }
- }
-
- //if (newPresence->getType() != Presence::Unavailable) return;
- JID fullJID(newPresence->getFrom());
- std::map<JID, ChatController*>::iterator it = chatControllers_.find(fullJID);
- if (it == chatControllers_.end()) return;
- JID bareJID(fullJID.toBare());
- //It doesn't make sense to have two unbound dialogs.
- if (chatControllers_.find(bareJID) != chatControllers_.end()) return;
- rebindControllerJID(fullJID, bareJID);
+ if (mucRegistry_->isMUC(newPresence->getFrom().toBare())) return;
+
+ foreach (ChatListWindow::Chat& chat, recentChats_) {
+ if (newPresence->getFrom().toBare() == chat.jid.toBare() && !chat.isMUC) {
+ Presence::ref presence = presenceOracle_->getHighestPriorityPresence(chat.jid.toBare());
+ chat.setStatusType(presence ? presence->getShow() : StatusShow::None);
+ chatListWindow_->setRecents(recentChats_);
+ break;
+ }
+ }
+
+ //if (newPresence->getType() != Presence::Unavailable) return;
+ JID fullJID(newPresence->getFrom());
+ std::map<JID, ChatController*>::iterator it = chatControllers_.find(fullJID);
+ if (it == chatControllers_.end()) return;
+ JID bareJID(fullJID.toBare());
+ //It doesn't make sense to have two unbound dialogs.
+ if (chatControllers_.find(bareJID) != chatControllers_.end()) return;
+ rebindControllerJID(fullJID, bareJID);
}
void ChatsManager::setAvatarManager(AvatarManager* avatarManager) {
- if (avatarManager_) {
- avatarManager_->onAvatarChanged.disconnect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1));
- }
- avatarManager_ = avatarManager;
- foreach (ChatListWindow::Chat& chat, recentChats_) {
- if (!chat.isMUC) {
- chat.setAvatarPath(avatarManager_->getAvatarPath(chat.jid));
- }
- }
- avatarManager_->onAvatarChanged.connect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1));
+ if (avatarManager_) {
+ avatarManager_->onAvatarChanged.disconnect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1));
+ }
+ avatarManager_ = avatarManager;
+ foreach (ChatListWindow::Chat& chat, recentChats_) {
+ if (!chat.isMUC) {
+ chat.setAvatarPath(avatarManager_->getAvatarPath(chat.jid));
+ }
+ }
+ avatarManager_->onAvatarChanged.connect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1));
}
void ChatsManager::handleAvatarChanged(const JID& jid) {
- foreach (ChatListWindow::Chat& chat, recentChats_) {
- if (!chat.isMUC && jid.toBare() == chat.jid.toBare()) {
- chat.setAvatarPath(avatarManager_->getAvatarPath(jid));
- break;
- }
- }
+ foreach (ChatListWindow::Chat& chat, recentChats_) {
+ if (!chat.isMUC && jid.toBare() == chat.jid.toBare()) {
+ chat.setAvatarPath(avatarManager_->getAvatarPath(jid));
+ break;
+ }
+ }
}
void ChatsManager::setServerDiscoInfo(boost::shared_ptr<DiscoInfo> info) {
- serverDiscoInfo_ = info;
- foreach (JIDChatControllerPair pair, chatControllers_) {
- pair.second->setAvailableServerFeatures(info);
- }
- foreach (JIDMUCControllerPair pair, mucControllers_) {
- pair.second->setAvailableServerFeatures(info);
- }
+ serverDiscoInfo_ = info;
+ foreach (JIDChatControllerPair pair, chatControllers_) {
+ pair.second->setAvailableServerFeatures(info);
+ }
+ foreach (JIDMUCControllerPair pair, mucControllers_) {
+ pair.second->setAvailableServerFeatures(info);
+ }
}
/**
* This is to be called on connect/disconnect.
- */
+ */
void ChatsManager::setOnline(bool enabled) {
- foreach (JIDChatControllerPair controllerPair, chatControllers_) {
- controllerPair.second->setOnline(enabled);
- }
- foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
- controllerPair.second->setOnline(enabled);
- if (enabled) {
- controllerPair.second->rejoin();
- }
- }
- if (!enabled) {
- markAllRecentsOffline();
- } else {
- setupBookmarks();
- localMUCServiceJID_ = JID();
- localMUCServiceFinderWalker_ = boost::make_shared<DiscoServiceWalker>(jid_.getDomain(), iqRouter_);
- localMUCServiceFinderWalker_->onServiceFound.connect(boost::bind(&ChatsManager::handleLocalServiceFound, this, _1, _2));
- localMUCServiceFinderWalker_->onWalkAborted.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this));
- localMUCServiceFinderWalker_->onWalkComplete.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this));
- localMUCServiceFinderWalker_->beginWalk();
- }
-
- if (chatListWindow_) {
- chatListWindow_->setBookmarksEnabled(enabled);
- }
+ foreach (JIDChatControllerPair controllerPair, chatControllers_) {
+ controllerPair.second->setOnline(enabled);
+ }
+ foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
+ controllerPair.second->setOnline(enabled);
+ if (enabled) {
+ controllerPair.second->rejoin();
+ }
+ }
+ if (!enabled) {
+ markAllRecentsOffline();
+ } else {
+ setupBookmarks();
+ localMUCServiceJID_ = JID();
+ localMUCServiceFinderWalker_ = boost::make_shared<DiscoServiceWalker>(jid_.getDomain(), iqRouter_);
+ localMUCServiceFinderWalker_->onServiceFound.connect(boost::bind(&ChatsManager::handleLocalServiceFound, this, _1, _2));
+ localMUCServiceFinderWalker_->onWalkAborted.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this));
+ localMUCServiceFinderWalker_->onWalkComplete.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this));
+ localMUCServiceFinderWalker_->beginWalk();
+ }
+
+ if (chatListWindow_) {
+ chatListWindow_->setBookmarksEnabled(enabled);
+ }
}
void ChatsManager::handleChatRequest(const std::string &contact) {
- ChatController* controller = getChatControllerOrFindAnother(JID(contact));
- controller->activateChatWindow();
+ ChatController* controller = getChatControllerOrFindAnother(JID(contact));
+ controller->activateChatWindow();
}
ChatController* ChatsManager::getChatControllerOrFindAnother(const JID &contact) {
- ChatController* controller = getChatControllerIfExists(contact);
- if (!controller && !mucRegistry_->isMUC(contact.toBare())) {
- foreach (JIDChatControllerPair pair, chatControllers_) {
- if (pair.first.toBare() == contact.toBare()) {
- controller = pair.second;
- break;
- }
- }
- }
- return controller ? controller : createNewChatController(contact);
+ ChatController* controller = getChatControllerIfExists(contact);
+ if (!controller && !mucRegistry_->isMUC(contact.toBare())) {
+ foreach (JIDChatControllerPair pair, chatControllers_) {
+ if (pair.first.toBare() == contact.toBare()) {
+ controller = pair.second;
+ break;
+ }
+ }
+ }
+ return controller ? controller : createNewChatController(contact);
}
ChatController* ChatsManager::createNewChatController(const JID& contact) {
- assert(chatControllers_.find(contact) == chatControllers_.end());
- boost::shared_ptr<ChatMessageParser> chatMessageParser = boost::make_shared<ChatMessageParser>(emoticons_, highlightManager_->getRules(), false); /* a message parser that knows this is a chat (not a room/MUC) */
- ChatController* controller = new ChatController(jid_, stanzaChannel_, iqRouter_, chatWindowFactory_, contact, nickResolver_, presenceOracle_, avatarManager_, mucRegistry_->isMUC(contact.toBare()), useDelayForLatency_, uiEventStream_, eventController_, timerFactory_, entityCapsProvider_, userWantsReceipts_, settings_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, autoAcceptMUCInviteDecider_);
- chatControllers_[contact] = controller;
- controller->setAvailableServerFeatures(serverDiscoInfo_);
- controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, contact, _1, false));
- controller->onWindowClosed.connect(boost::bind(&ChatsManager::handleChatClosed, this, contact));
- controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller));
- controller->onConvertToMUC.connect(boost::bind(&ChatsManager::handleTransformChatToMUC, this, controller, _1, _2, _3));
- updatePresenceReceivingStateOnChatController(contact);
- controller->setCanStartImpromptuChats(!localMUCServiceJID_.toString().empty());
- return controller;
+ assert(chatControllers_.find(contact) == chatControllers_.end());
+ boost::shared_ptr<ChatMessageParser> chatMessageParser = boost::make_shared<ChatMessageParser>(emoticons_, highlightManager_->getRules(), false); /* a message parser that knows this is a chat (not a room/MUC) */
+ ChatController* controller = new ChatController(jid_, stanzaChannel_, iqRouter_, chatWindowFactory_, contact, nickResolver_, presenceOracle_, avatarManager_, mucRegistry_->isMUC(contact.toBare()), useDelayForLatency_, uiEventStream_, eventController_, timerFactory_, entityCapsProvider_, userWantsReceipts_, settings_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, autoAcceptMUCInviteDecider_);
+ chatControllers_[contact] = controller;
+ controller->setAvailableServerFeatures(serverDiscoInfo_);
+ controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, contact, _1, false));
+ controller->onWindowClosed.connect(boost::bind(&ChatsManager::handleChatClosed, this, contact));
+ controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller));
+ controller->onConvertToMUC.connect(boost::bind(&ChatsManager::handleTransformChatToMUC, this, controller, _1, _2, _3));
+ updatePresenceReceivingStateOnChatController(contact);
+ controller->setCanStartImpromptuChats(!localMUCServiceJID_.toString().empty());
+ return controller;
}
ChatController* ChatsManager::getChatControllerOrCreate(const JID &contact) {
- ChatController* controller = getChatControllerIfExists(contact);
- return controller ? controller : createNewChatController(contact);
+ ChatController* controller = getChatControllerIfExists(contact);
+ return controller ? controller : createNewChatController(contact);
}
ChatController* ChatsManager::getChatControllerIfExists(const JID &contact, bool rebindIfNeeded) {
- if (chatControllers_.find(contact) == chatControllers_.end()) {
- if (mucRegistry_->isMUC(contact.toBare())) {
- return NULL;
- }
- //Need to look for an unbound window to bind first
- JID bare(contact.toBare());
- if (chatControllers_.find(bare) != chatControllers_.end()) {
- if (rebindIfNeeded) {
- rebindControllerJID(bare, contact);
- }
- else {
- return chatControllers_[bare];
- }
- } else {
- foreach (JIDChatControllerPair pair, chatControllers_) {
- if (pair.first.toBare() == contact.toBare()) {
- if (rebindIfNeeded) {
- rebindControllerJID(pair.first, contact);
- return chatControllers_[contact];
- } else {
- return pair.second;
- }
- }
- }
- return NULL;
- }
- }
- return chatControllers_[contact];
+ if (chatControllers_.find(contact) == chatControllers_.end()) {
+ if (mucRegistry_->isMUC(contact.toBare())) {
+ return NULL;
+ }
+ //Need to look for an unbound window to bind first
+ JID bare(contact.toBare());
+ if (chatControllers_.find(bare) != chatControllers_.end()) {
+ if (rebindIfNeeded) {
+ rebindControllerJID(bare, contact);
+ }
+ else {
+ return chatControllers_[bare];
+ }
+ } else {
+ foreach (JIDChatControllerPair pair, chatControllers_) {
+ if (pair.first.toBare() == contact.toBare()) {
+ if (rebindIfNeeded) {
+ rebindControllerJID(pair.first, contact);
+ return chatControllers_[contact];
+ } else {
+ return pair.second;
+ }
+ }
+ }
+ return NULL;
+ }
+ }
+ return chatControllers_[contact];
}
void ChatsManager::rebindControllerJID(const JID& from, const JID& to) {
- chatControllers_[to] = chatControllers_[from];
- chatControllers_.erase(from);
- chatControllers_[to]->setToJID(to);
+ chatControllers_[to] = chatControllers_[from];
+ chatControllers_.erase(from);
+ chatControllers_[to]->setToJID(to);
}
MUC::ref ChatsManager::handleJoinMUCRequest(const JID &mucJID, const boost::optional<std::string>& password, const boost::optional<std::string>& nickMaybe, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow) {
- MUC::ref muc;
- if (addAutoJoin) {
- MUCBookmark bookmark(mucJID, mucJID.getNode());
- bookmark.setAutojoin(true);
- if (nickMaybe) {
- bookmark.setNick(*nickMaybe);
- }
- if (password) {
- bookmark.setPassword(*password);
- }
- mucBookmarkManager_->addBookmark(bookmark);
- }
-
- std::map<JID, MUCController*>::iterator it = mucControllers_.find(mucJID);
- if (it != mucControllers_.end()) {
- if (stanzaChannel_->isAvailable()) {
- it->second->rejoin();
- }
- } else {
- std::string nick = (nickMaybe && !(*nickMaybe).empty()) ? nickMaybe.get() : nickResolver_->jidToNick(jid_);
- muc = mucManager->createMUC(mucJID);
- if (createAsReservedIfNew) {
- muc->setCreateAsReservedIfNew();
- }
- if (isImpromptu) {
- muc->setCreateAsReservedIfNew();
- }
-
- MUCController* controller = NULL;
- SingleChatWindowFactoryAdapter* chatWindowFactoryAdapter = NULL;
- if (reuseChatwindow) {
- chatWindowFactoryAdapter = new SingleChatWindowFactoryAdapter(reuseChatwindow);
- }
- boost::shared_ptr<ChatMessageParser> chatMessageParser = boost::make_shared<ChatMessageParser>(emoticons_, highlightManager_->getRules(), true); /* a message parser that knows this is a room/MUC (not a chat) */
- controller = new MUCController(jid_, muc, password, nick, stanzaChannel_, iqRouter_, reuseChatwindow ? chatWindowFactoryAdapter : chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory_, eventController_, entityCapsProvider_, roster_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, isImpromptu, autoAcceptMUCInviteDecider_, vcardManager_, mucBookmarkManager_);
- if (chatWindowFactoryAdapter) {
- /* The adapters are only passed to chat windows, which are deleted in their
- * controllers' dtor, which are deleted in ChatManager's dtor. The adapters
- * are also deleted there.*/
- chatWindowFactoryAdapters_[controller] = chatWindowFactoryAdapter;
- }
-
- mucControllers_[mucJID] = controller;
- controller->setAvailableServerFeatures(serverDiscoInfo_);
- controller->onUserLeft.connect(boost::bind(&ChatsManager::handleUserLeftMUC, this, controller));
- controller->onUserJoined.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), "", true));
- controller->onUserNicknameChanged.connect(boost::bind(&ChatsManager::handleUserNicknameChanged, this, controller, _1, _2));
- controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), _1, true));
- controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller));
- if (!stanzaChannel_->isAvailable()) {
- /* When online, the MUC is added to the registry in MUCImpl::internalJoin. This method is not
- * called when Swift is offline, so we add it here as only MUCs in the registry are rejoined
- * when going back online.
- */
- mucRegistry_->addMUC(mucJID.toBare());
- }
- handleChatActivity(mucJID.toBare(), "", true);
- }
-
- mucControllers_[mucJID]->showChatWindow();
- return muc;
+ MUC::ref muc;
+ if (addAutoJoin) {
+ MUCBookmark bookmark(mucJID, mucJID.getNode());
+ bookmark.setAutojoin(true);
+ if (nickMaybe) {
+ bookmark.setNick(*nickMaybe);
+ }
+ if (password) {
+ bookmark.setPassword(*password);
+ }
+ mucBookmarkManager_->addBookmark(bookmark);
+ }
+
+ std::map<JID, MUCController*>::iterator it = mucControllers_.find(mucJID);
+ if (it != mucControllers_.end()) {
+ if (stanzaChannel_->isAvailable()) {
+ it->second->rejoin();
+ }
+ } else {
+ std::string nick = (nickMaybe && !(*nickMaybe).empty()) ? nickMaybe.get() : nickResolver_->jidToNick(jid_);
+ muc = mucManager->createMUC(mucJID);
+ if (createAsReservedIfNew) {
+ muc->setCreateAsReservedIfNew();
+ }
+ if (isImpromptu) {
+ muc->setCreateAsReservedIfNew();
+ }
+
+ MUCController* controller = NULL;
+ SingleChatWindowFactoryAdapter* chatWindowFactoryAdapter = NULL;
+ if (reuseChatwindow) {
+ chatWindowFactoryAdapter = new SingleChatWindowFactoryAdapter(reuseChatwindow);
+ }
+ boost::shared_ptr<ChatMessageParser> chatMessageParser = boost::make_shared<ChatMessageParser>(emoticons_, highlightManager_->getRules(), true); /* a message parser that knows this is a room/MUC (not a chat) */
+ controller = new MUCController(jid_, muc, password, nick, stanzaChannel_, iqRouter_, reuseChatwindow ? chatWindowFactoryAdapter : chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory_, eventController_, entityCapsProvider_, roster_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, isImpromptu, autoAcceptMUCInviteDecider_, vcardManager_, mucBookmarkManager_);
+ if (chatWindowFactoryAdapter) {
+ /* The adapters are only passed to chat windows, which are deleted in their
+ * controllers' dtor, which are deleted in ChatManager's dtor. The adapters
+ * are also deleted there.*/
+ chatWindowFactoryAdapters_[controller] = chatWindowFactoryAdapter;
+ }
+
+ mucControllers_[mucJID] = controller;
+ controller->setAvailableServerFeatures(serverDiscoInfo_);
+ controller->onUserLeft.connect(boost::bind(&ChatsManager::handleUserLeftMUC, this, controller));
+ controller->onUserJoined.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), "", true));
+ controller->onUserNicknameChanged.connect(boost::bind(&ChatsManager::handleUserNicknameChanged, this, controller, _1, _2));
+ controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), _1, true));
+ controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller));
+ if (!stanzaChannel_->isAvailable()) {
+ /* When online, the MUC is added to the registry in MUCImpl::internalJoin. This method is not
+ * called when Swift is offline, so we add it here as only MUCs in the registry are rejoined
+ * when going back online.
+ */
+ mucRegistry_->addMUC(mucJID.toBare());
+ }
+ handleChatActivity(mucJID.toBare(), "", true);
+ }
+
+ mucControllers_[mucJID]->showChatWindow();
+ return muc;
}
void ChatsManager::handleSearchMUCRequest() {
- mucSearchController_->openSearchWindow();
+ mucSearchController_->openSearchWindow();
}
void ChatsManager::handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname) {
- JID oldMUCChatJID = mucController->getToJID().withResource(oldNickname);
- JID newMUCChatJID = mucController->getToJID().withResource(newNickname);
-
- SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname << std::endl;
-
- // get current chat controller
- ChatController *chatController = getChatControllerIfExists(oldMUCChatJID);
- if (chatController) {
- // adjust chat controller
- chatController->setToJID(newMUCChatJID);
- nickResolver_->onNickChanged(newMUCChatJID, oldNickname);
- chatControllers_.erase(oldMUCChatJID);
- chatControllers_[newMUCChatJID] = chatController;
-
- chatController->onActivity.disconnect(boost::bind(&ChatsManager::handleChatActivity, this, oldMUCChatJID, _1, false));
- chatController->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, newMUCChatJID, _1, false));
- }
+ JID oldMUCChatJID = mucController->getToJID().withResource(oldNickname);
+ JID newMUCChatJID = mucController->getToJID().withResource(newNickname);
+
+ SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname << std::endl;
+
+ // get current chat controller
+ ChatController *chatController = getChatControllerIfExists(oldMUCChatJID);
+ if (chatController) {
+ // adjust chat controller
+ chatController->setToJID(newMUCChatJID);
+ nickResolver_->onNickChanged(newMUCChatJID, oldNickname);
+ chatControllers_.erase(oldMUCChatJID);
+ chatControllers_[newMUCChatJID] = chatController;
+
+ chatController->onActivity.disconnect(boost::bind(&ChatsManager::handleChatActivity, this, oldMUCChatJID, _1, false));
+ chatController->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, newMUCChatJID, _1, false));
+ }
}
void ChatsManager::handleIncomingMessage(boost::shared_ptr<Message> message) {
- JID jid = message->getFrom();
- boost::shared_ptr<MessageEvent> event(new MessageEvent(message));
- bool isInvite = !!message->getPayload<MUCInvitationPayload>();
- bool isMediatedInvite = (message->getPayload<MUCUserPayload>() && message->getPayload<MUCUserPayload>()->getInvite());
- if (isMediatedInvite) {
- jid = (*message->getPayload<MUCUserPayload>()->getInvite()).from;
- }
- if (!event->isReadable() && !message->getPayload<ChatState>() && !message->getPayload<DeliveryReceipt>() && !message->getPayload<DeliveryReceiptRequest>() && !isInvite && !isMediatedInvite && !message->hasSubject()) {
- return;
- }
-
- // Try to deliver it to a MUC
- if (message->getType() == Message::Groupchat || message->getType() == Message::Error /*|| (isInvite && message->getType() == Message::Normal)*/) {
- std::map<JID, MUCController*>::iterator i = mucControllers_.find(jid.toBare());
- if (i != mucControllers_.end()) {
- i->second->handleIncomingMessage(event);
- return;
- }
- else if (message->getType() == Message::Groupchat) {
- //FIXME: Error handling - groupchat messages from an unknown muc.
- return;
- }
- }
-
- // check for impromptu invite to potentially auto-accept
- MUCInvitationPayload::ref invite = message->getPayload<MUCInvitationPayload>();
- if (invite && autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) {
- if (invite->getIsContinuation()) {
- // check for existing chat controller for the from JID
- ChatController* controller = getChatControllerIfExists(jid);
- if (controller) {
- ChatWindow* window = controller->detachChatWindow();
- chatControllers_.erase(jid);
- delete controller;
- handleJoinMUCRequest(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true, window);
- return;
- }
- } else {
- handleJoinMUCRequest(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true);
- return;
- }
- }
-
- //if not a mucroom
- if (!event->isReadable() && !isInvite && !isMediatedInvite) {
- /* Only route such messages if a window exists, don't open new windows for them.*/
-
- // Do not bind a controller to a full JID, for delivery receipts or chat state notifications.
- bool bindControllerToJID = false;
- ChatState::ref chatState = message->getPayload<ChatState>();
- if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) {
- bindControllerToJID = true;
- }
-
- ChatController* controller = getChatControllerIfExists(jid, bindControllerToJID);
- if (controller) {
- controller->handleIncomingMessage(event);
- }
- } else {
- getChatControllerOrCreate(jid)->handleIncomingMessage(event);
- }
+ JID jid = message->getFrom();
+ boost::shared_ptr<MessageEvent> event(new MessageEvent(message));
+ bool isInvite = !!message->getPayload<MUCInvitationPayload>();
+ bool isMediatedInvite = (message->getPayload<MUCUserPayload>() && message->getPayload<MUCUserPayload>()->getInvite());
+ if (isMediatedInvite) {
+ jid = (*message->getPayload<MUCUserPayload>()->getInvite()).from;
+ }
+ if (!event->isReadable() && !message->getPayload<ChatState>() && !message->getPayload<DeliveryReceipt>() && !message->getPayload<DeliveryReceiptRequest>() && !isInvite && !isMediatedInvite && !message->hasSubject()) {
+ return;
+ }
+
+ // Try to deliver it to a MUC
+ if (message->getType() == Message::Groupchat || message->getType() == Message::Error /*|| (isInvite && message->getType() == Message::Normal)*/) {
+ std::map<JID, MUCController*>::iterator i = mucControllers_.find(jid.toBare());
+ if (i != mucControllers_.end()) {
+ i->second->handleIncomingMessage(event);
+ return;
+ }
+ else if (message->getType() == Message::Groupchat) {
+ //FIXME: Error handling - groupchat messages from an unknown muc.
+ return;
+ }
+ }
+
+ // check for impromptu invite to potentially auto-accept
+ MUCInvitationPayload::ref invite = message->getPayload<MUCInvitationPayload>();
+ if (invite && autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) {
+ if (invite->getIsContinuation()) {
+ // check for existing chat controller for the from JID
+ ChatController* controller = getChatControllerIfExists(jid);
+ if (controller) {
+ ChatWindow* window = controller->detachChatWindow();
+ chatControllers_.erase(jid);
+ delete controller;
+ handleJoinMUCRequest(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true, window);
+ return;
+ }
+ } else {
+ handleJoinMUCRequest(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true);
+ return;
+ }
+ }
+
+ //if not a mucroom
+ if (!event->isReadable() && !isInvite && !isMediatedInvite) {
+ /* Only route such messages if a window exists, don't open new windows for them.*/
+
+ // Do not bind a controller to a full JID, for delivery receipts or chat state notifications.
+ bool bindControllerToJID = false;
+ ChatState::ref chatState = message->getPayload<ChatState>();
+ if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) {
+ bindControllerToJID = true;
+ }
+
+ ChatController* controller = getChatControllerIfExists(jid, bindControllerToJID);
+ if (controller) {
+ controller->handleIncomingMessage(event);
+ }
+ } else {
+ getChatControllerOrCreate(jid)->handleIncomingMessage(event);
+ }
}
void ChatsManager::handleMUCSelectedAfterSearch(const JID& muc) {
- if (joinMUCWindow_) {
- joinMUCWindow_->setMUC(muc.toString());
- }
+ if (joinMUCWindow_) {
+ joinMUCWindow_->setMUC(muc.toString());
+ }
}
void ChatsManager::handleMUCBookmarkActivated(const MUCBookmark& mucBookmark) {
- uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(mucBookmark.getRoom(), mucBookmark.getPassword(), mucBookmark.getNick()));
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(mucBookmark.getRoom(), mucBookmark.getPassword(), mucBookmark.getNick()));
}
void ChatsManager::handleNewFileTransferController(FileTransferController* ftc) {
- ChatController* chatController = getChatControllerOrCreate(ftc->getOtherParty());
- chatController->handleNewFileTransferController(ftc);
- chatController->activateChatWindow();
- if (ftc->isIncoming()) {
- eventController_->handleIncomingEvent(boost::make_shared<IncomingFileTransferEvent>(ftc->getOtherParty()));
- }
+ ChatController* chatController = getChatControllerOrCreate(ftc->getOtherParty());
+ chatController->handleNewFileTransferController(ftc);
+ chatController->activateChatWindow();
+ if (ftc->isIncoming()) {
+ eventController_->handleIncomingEvent(boost::make_shared<IncomingFileTransferEvent>(ftc->getOtherParty()));
+ }
}
void ChatsManager::handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf) {
- ChatController* chatController = getChatControllerOrCreate(contact);
- chatController->handleWhiteboardSessionRequest(senderIsSelf);
- chatController->activateChatWindow();
+ ChatController* chatController = getChatControllerOrCreate(contact);
+ chatController->handleWhiteboardSessionRequest(senderIsSelf);
+ chatController->activateChatWindow();
}
void ChatsManager::handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state) {
- ChatController* chatController = getChatControllerOrCreate(contact);
- chatController->handleWhiteboardStateChange(state);
- chatController->activateChatWindow();
- if (state == ChatWindow::WhiteboardAccepted) {
- boost::filesystem::path path;
- JID bareJID = contact.toBare();
- if (avatarManager_) {
- path = avatarManager_->getAvatarPath(bareJID);
- }
- ChatListWindow::Chat chat(bareJID, nickResolver_->jidToNick(bareJID), "", 0, StatusShow::None, path, false);
- chatListWindow_->addWhiteboardSession(chat);
- } else {
- chatListWindow_->removeWhiteboardSession(contact.toBare());
- }
+ ChatController* chatController = getChatControllerOrCreate(contact);
+ chatController->handleWhiteboardStateChange(state);
+ chatController->activateChatWindow();
+ if (state == ChatWindow::WhiteboardAccepted) {
+ boost::filesystem::path path;
+ JID bareJID = contact.toBare();
+ if (avatarManager_) {
+ path = avatarManager_->getAvatarPath(bareJID);
+ }
+ ChatListWindow::Chat chat(bareJID, nickResolver_->jidToNick(bareJID), "", 0, StatusShow::None, path, false);
+ chatListWindow_->addWhiteboardSession(chat);
+ } else {
+ chatListWindow_->removeWhiteboardSession(contact.toBare());
+ }
}
void ChatsManager::handleRecentActivated(const ChatListWindow::Chat& chat) {
- if (chat.isMUC && !chat.impromptuJIDs.empty()) {
- typedef std::pair<std::string, JID> StringJIDPair;
- std::vector<JID> inviteJIDs;
- foreach(StringJIDPair pair, chat.impromptuJIDs) {
- inviteJIDs.push_back(pair.second);
- }
- uiEventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(inviteJIDs, chat.jid, ""));
- }
- else if (chat.isMUC) {
- /* FIXME: This means that recents requiring passwords will just flat-out not work */
- uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(chat.jid, boost::optional<std::string>(), chat.nick));
- }
- else {
- uiEventStream_->send(boost::make_shared<RequestChatUIEvent>(chat.jid));
- }
+ if (chat.isMUC && !chat.impromptuJIDs.empty()) {
+ typedef std::pair<std::string, JID> StringJIDPair;
+ std::vector<JID> inviteJIDs;
+ foreach(StringJIDPair pair, chat.impromptuJIDs) {
+ inviteJIDs.push_back(pair.second);
+ }
+ uiEventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(inviteJIDs, chat.jid, ""));
+ }
+ else if (chat.isMUC) {
+ /* FIXME: This means that recents requiring passwords will just flat-out not work */
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(chat.jid, boost::optional<std::string>(), chat.nick));
+ }
+ else {
+ uiEventStream_->send(boost::make_shared<RequestChatUIEvent>(chat.jid));
+ }
}
void ChatsManager::handleLocalServiceFound(const JID& service, boost::shared_ptr<DiscoInfo> info) {
- foreach (DiscoInfo::Identity identity, info->getIdentities()) {
- if ((identity.getCategory() == "directory"
- && identity.getType() == "chatroom")
- || (identity.getCategory() == "conference"
- && identity.getType() == "text")) {
- localMUCServiceJID_ = service;
- localMUCServiceFinderWalker_->endWalk();
- SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_ << std::endl;
- break;
- }
- }
+ foreach (DiscoInfo::Identity identity, info->getIdentities()) {
+ if ((identity.getCategory() == "directory"
+ && identity.getType() == "chatroom")
+ || (identity.getCategory() == "conference"
+ && identity.getType() == "text")) {
+ localMUCServiceJID_ = service;
+ localMUCServiceFinderWalker_->endWalk();
+ SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_ << std::endl;
+ break;
+ }
+ }
}
void ChatsManager::handleLocalServiceWalkFinished() {
- bool impromptuMUCSupported = !localMUCServiceJID_.toString().empty();
- foreach (JIDChatControllerPair controllerPair, chatControllers_) {
- controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported);
- }
- foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
- controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported);
- }
- onImpromptuMUCServiceDiscovered(impromptuMUCSupported);
+ bool impromptuMUCSupported = !localMUCServiceJID_.toString().empty();
+ foreach (JIDChatControllerPair controllerPair, chatControllers_) {
+ controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported);
+ }
+ foreach (JIDMUCControllerPair controllerPair, mucControllers_) {
+ controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported);
+ }
+ onImpromptuMUCServiceDiscovered(impromptuMUCSupported);
}
std::vector<ChatListWindow::Chat> ChatsManager::getRecentChats() const {
- return std::vector<ChatListWindow::Chat>(recentChats_.begin(), recentChats_.end());
+ return std::vector<ChatListWindow::Chat>(recentChats_.begin(), recentChats_.end());
}
std::vector<Contact::ref> Swift::ChatsManager::getContacts(bool withMUCNicks) {
- std::vector<Contact::ref> result;
- foreach (ChatListWindow::Chat chat, recentChats_) {
- if (!chat.isMUC) {
- result.push_back(boost::make_shared<Contact>(chat.chatName.empty() ? chat.jid.toString() : chat.chatName, chat.jid, chat.statusType, chat.avatarPath));
- }
- }
- if (withMUCNicks) {
- /* collect MUC nicks */
- typedef std::map<JID, MUCController*>::value_type Item;
- foreach (const Item& item, mucControllers_) {
- JID mucJID = item.second->getToJID();
- std::map<std::string, JID> participants = item.second->getParticipantJIDs();
- typedef std::map<std::string, JID>::value_type ParticipantType;
- foreach (const ParticipantType& participant, participants) {
- const JID nickJID = JID(mucJID.getNode(), mucJID.getDomain(), participant.first);
- Presence::ref presence = presenceOracle_->getLastPresence(nickJID);
- const boost::filesystem::path avatar = avatarManager_->getAvatarPath(nickJID);
- result.push_back(boost::make_shared<Contact>(participant.first, JID(), presence->getShow(), avatar));
- }
- }
- }
- return result;
+ std::vector<Contact::ref> result;
+ foreach (ChatListWindow::Chat chat, recentChats_) {
+ if (!chat.isMUC) {
+ result.push_back(boost::make_shared<Contact>(chat.chatName.empty() ? chat.jid.toString() : chat.chatName, chat.jid, chat.statusType, chat.avatarPath));
+ }
+ }
+ if (withMUCNicks) {
+ /* collect MUC nicks */
+ typedef std::map<JID, MUCController*>::value_type Item;
+ foreach (const Item& item, mucControllers_) {
+ JID mucJID = item.second->getToJID();
+ std::map<std::string, JID> participants = item.second->getParticipantJIDs();
+ typedef std::map<std::string, JID>::value_type ParticipantType;
+ foreach (const ParticipantType& participant, participants) {
+ const JID nickJID = JID(mucJID.getNode(), mucJID.getDomain(), participant.first);
+ Presence::ref presence = presenceOracle_->getLastPresence(nickJID);
+ const boost::filesystem::path avatar = avatarManager_->getAvatarPath(nickJID);
+ result.push_back(boost::make_shared<Contact>(participant.first, JID(), presence->getShow(), avatar));
+ }
+ }
+ }
+ return result;
}
ChatsManager::SingleChatWindowFactoryAdapter::SingleChatWindowFactoryAdapter(ChatWindow* chatWindow) : chatWindow_(chatWindow) {}
ChatsManager::SingleChatWindowFactoryAdapter::~SingleChatWindowFactoryAdapter() {}
ChatWindow* ChatsManager::SingleChatWindowFactoryAdapter::createChatWindow(const JID &, UIEventStream*) {
- return chatWindow_;
+ return chatWindow_;
}
}
diff --git a/Swift/Controllers/Chat/ChatsManager.h b/Swift/Controllers/Chat/ChatsManager.h
index 58a9017..7bba219 100644
--- a/Swift/Controllers/Chat/ChatsManager.h
+++ b/Swift/Controllers/Chat/ChatsManager.h
@@ -27,159 +27,159 @@
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
namespace Swift {
- class EventController;
- class ChatController;
- class ChatControllerBase;
- class MUCController;
- class MUCManager;
- class JoinMUCWindow;
- class JoinMUCWindowFactory;
- class NickResolver;
- class PresenceOracle;
- class AvatarManager;
- class StanzaChannel;
- class IQRouter;
- class PresenceSender;
- class MUCBookmarkManager;
- class ChatListWindowFactory;
- class TimerFactory;
- class EntityCapsProvider;
- class DirectedPresenceSender;
- class MUCSearchWindowFactory;
- class ProfileSettingsProvider;
- class MUCSearchController;
- class FileTransferOverview;
- class FileTransferController;
- class XMPPRoster;
- class SettingsProvider;
- class WhiteboardManager;
- class HistoryController;
- class HighlightManager;
- class ClientBlockListManager;
- class ChatMessageParser;
- class DiscoServiceWalker;
- class AutoAcceptMUCInviteDecider;
- class VCardManager;
-
- class ChatsManager : public ContactProvider {
- public:
- ChatsManager(JID jid, StanzaChannel* stanzaChannel, IQRouter* iqRouter, EventController* eventController, ChatWindowFactory* chatWindowFactory, JoinMUCWindowFactory* joinMUCWindowFactory, NickResolver* nickResolver, PresenceOracle* presenceOracle, PresenceSender* presenceSender, UIEventStream* uiEventStream, ChatListWindowFactory* chatListWindowFactory, bool useDelayForLatency, TimerFactory* timerFactory, MUCRegistry* mucRegistry, EntityCapsProvider* entityCapsProvider, MUCManager* mucManager, MUCSearchWindowFactory* mucSearchWindowFactory, ProfileSettingsProvider* profileSettings, FileTransferOverview* ftOverview, XMPPRoster* roster, bool eagleMode, SettingsProvider* settings, HistoryController* historyController_, WhiteboardManager* whiteboardManager, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, const std::map<std::string, std::string>& emoticons, VCardManager* vcardManager);
- virtual ~ChatsManager();
- void setAvatarManager(AvatarManager* avatarManager);
- void setOnline(bool enabled);
- void setServerDiscoInfo(boost::shared_ptr<DiscoInfo> info);
- void handleIncomingMessage(boost::shared_ptr<Message> message);
- std::vector<ChatListWindow::Chat> getRecentChats() const;
- virtual std::vector<Contact::ref> getContacts(bool withMUCNicks);
-
- boost::signal<void (bool supportsImpromptu)> onImpromptuMUCServiceDiscovered;
-
- private:
- class SingleChatWindowFactoryAdapter : public ChatWindowFactory {
- public:
- SingleChatWindowFactoryAdapter(ChatWindow* chatWindow);
- virtual ~SingleChatWindowFactoryAdapter();
- virtual ChatWindow* createChatWindow(const JID &, UIEventStream*);
-
- private:
- ChatWindow* chatWindow_;
- };
-
- private:
- ChatListWindow::Chat createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage);
- void handleChatRequest(const std::string& contact);
- void finalizeImpromptuJoin(MUC::ref muc, const std::vector<JID>& jidsToInvite, const std::string& reason, const boost::optional<JID>& reuseChatJID = boost::optional<JID>());
- MUC::ref handleJoinMUCRequest(const JID& muc, const boost::optional<std::string>& password, const boost::optional<std::string>& nick, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow = 0);
- void handleSearchMUCRequest();
- void handleMUCSelectedAfterSearch(const JID&);
- void rebindControllerJID(const JID& from, const JID& to);
- void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleMUCBookmarkAdded(const MUCBookmark& bookmark);
- void handleMUCBookmarkRemoved(const MUCBookmark& bookmark);
- void handleUserLeftMUC(MUCController* mucController);
- void handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname);
- void handleBookmarksReady();
- void handleChatActivity(const JID& jid, const std::string& activity, bool isMUC);
- void handleChatClosed(const JID& jid);
- void handleNewFileTransferController(FileTransferController*);
- void handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf);
- void handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state);
- boost::optional<ChatListWindow::Chat> removeExistingChat(const ChatListWindow::Chat& chat);
- void cleanupPrivateMessageRecents();
- void appendRecent(const ChatListWindow::Chat& chat);
- void prependRecent(const ChatListWindow::Chat& chat);
- void setupBookmarks();
- void loadRecents();
- void saveRecents();
- void handleChatMadeRecent();
- void handleMUCBookmarkActivated(const MUCBookmark&);
- void handleRecentActivated(const ChatListWindow::Chat&);
- void handleUnreadCountChanged(ChatControllerBase* controller);
- void handleAvatarChanged(const JID& jid);
- void handleClearRecentsRequested();
- void handleJIDAddedToRoster(const JID&);
- void handleJIDRemovedFromRoster(const JID&);
- void handleJIDUpdatedInRoster(const JID&);
- void handleRosterCleared();
- void handleSettingChanged(const std::string& settingPath);
- void markAllRecentsOffline();
- void handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector<JID>& jidsToInvite, const std::string& reason);
-
- void handleLocalServiceFound(const JID& service, boost::shared_ptr<DiscoInfo> info);
- void handleLocalServiceWalkFinished();
-
- void updatePresenceReceivingStateOnChatController(const JID&);
- ChatListWindow::Chat updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const;
-
-
- ChatController* getChatControllerOrFindAnother(const JID &contact);
- ChatController* createNewChatController(const JID &contact);
- ChatController* getChatControllerOrCreate(const JID &contact);
- ChatController* getChatControllerIfExists(const JID &contact, bool rebindIfNeeded = true);
-
- private:
- std::map<JID, MUCController*> mucControllers_;
- std::map<JID, ChatController*> chatControllers_;
- std::map<ChatControllerBase*, SingleChatWindowFactoryAdapter*> chatWindowFactoryAdapters_;
- EventController* eventController_;
- JID jid_;
- StanzaChannel* stanzaChannel_;
- IQRouter* iqRouter_;
- ChatWindowFactory* chatWindowFactory_;
- JoinMUCWindowFactory* joinMUCWindowFactory_;
- NickResolver* nickResolver_;
- PresenceOracle* presenceOracle_;
- AvatarManager* avatarManager_;
- PresenceSender* presenceSender_;
- UIEventStream* uiEventStream_;
- MUCBookmarkManager* mucBookmarkManager_;
- boost::shared_ptr<DiscoInfo> serverDiscoInfo_;
- ChatListWindow* chatListWindow_;
- JoinMUCWindow* joinMUCWindow_;
- boost::bsignals::scoped_connection uiEventConnection_;
- bool useDelayForLatency_;
- TimerFactory* timerFactory_;
- MUCRegistry* mucRegistry_;
- EntityCapsProvider* entityCapsProvider_;
- MUCManager* mucManager;
- MUCSearchController* mucSearchController_;
- std::list<ChatListWindow::Chat> recentChats_;
- ProfileSettingsProvider* profileSettings_;
- FileTransferOverview* ftOverview_;
- XMPPRoster* roster_;
- bool eagleMode_;
- bool userWantsReceipts_;
- SettingsProvider* settings_;
- HistoryController* historyController_;
- WhiteboardManager* whiteboardManager_;
- HighlightManager* highlightManager_;
- std::map<std::string, std::string> emoticons_;
- ClientBlockListManager* clientBlockListManager_;
- JID localMUCServiceJID_;
- boost::shared_ptr<DiscoServiceWalker> localMUCServiceFinderWalker_;
- AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_;
- IDGenerator idGenerator_;
- VCardManager* vcardManager_;
- };
+ class EventController;
+ class ChatController;
+ class ChatControllerBase;
+ class MUCController;
+ class MUCManager;
+ class JoinMUCWindow;
+ class JoinMUCWindowFactory;
+ class NickResolver;
+ class PresenceOracle;
+ class AvatarManager;
+ class StanzaChannel;
+ class IQRouter;
+ class PresenceSender;
+ class MUCBookmarkManager;
+ class ChatListWindowFactory;
+ class TimerFactory;
+ class EntityCapsProvider;
+ class DirectedPresenceSender;
+ class MUCSearchWindowFactory;
+ class ProfileSettingsProvider;
+ class MUCSearchController;
+ class FileTransferOverview;
+ class FileTransferController;
+ class XMPPRoster;
+ class SettingsProvider;
+ class WhiteboardManager;
+ class HistoryController;
+ class HighlightManager;
+ class ClientBlockListManager;
+ class ChatMessageParser;
+ class DiscoServiceWalker;
+ class AutoAcceptMUCInviteDecider;
+ class VCardManager;
+
+ class ChatsManager : public ContactProvider {
+ public:
+ ChatsManager(JID jid, StanzaChannel* stanzaChannel, IQRouter* iqRouter, EventController* eventController, ChatWindowFactory* chatWindowFactory, JoinMUCWindowFactory* joinMUCWindowFactory, NickResolver* nickResolver, PresenceOracle* presenceOracle, PresenceSender* presenceSender, UIEventStream* uiEventStream, ChatListWindowFactory* chatListWindowFactory, bool useDelayForLatency, TimerFactory* timerFactory, MUCRegistry* mucRegistry, EntityCapsProvider* entityCapsProvider, MUCManager* mucManager, MUCSearchWindowFactory* mucSearchWindowFactory, ProfileSettingsProvider* profileSettings, FileTransferOverview* ftOverview, XMPPRoster* roster, bool eagleMode, SettingsProvider* settings, HistoryController* historyController_, WhiteboardManager* whiteboardManager, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, const std::map<std::string, std::string>& emoticons, VCardManager* vcardManager);
+ virtual ~ChatsManager();
+ void setAvatarManager(AvatarManager* avatarManager);
+ void setOnline(bool enabled);
+ void setServerDiscoInfo(boost::shared_ptr<DiscoInfo> info);
+ void handleIncomingMessage(boost::shared_ptr<Message> message);
+ std::vector<ChatListWindow::Chat> getRecentChats() const;
+ virtual std::vector<Contact::ref> getContacts(bool withMUCNicks);
+
+ boost::signal<void (bool supportsImpromptu)> onImpromptuMUCServiceDiscovered;
+
+ private:
+ class SingleChatWindowFactoryAdapter : public ChatWindowFactory {
+ public:
+ SingleChatWindowFactoryAdapter(ChatWindow* chatWindow);
+ virtual ~SingleChatWindowFactoryAdapter();
+ virtual ChatWindow* createChatWindow(const JID &, UIEventStream*);
+
+ private:
+ ChatWindow* chatWindow_;
+ };
+
+ private:
+ ChatListWindow::Chat createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage);
+ void handleChatRequest(const std::string& contact);
+ void finalizeImpromptuJoin(MUC::ref muc, const std::vector<JID>& jidsToInvite, const std::string& reason, const boost::optional<JID>& reuseChatJID = boost::optional<JID>());
+ MUC::ref handleJoinMUCRequest(const JID& muc, const boost::optional<std::string>& password, const boost::optional<std::string>& nick, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow = 0);
+ void handleSearchMUCRequest();
+ void handleMUCSelectedAfterSearch(const JID&);
+ void rebindControllerJID(const JID& from, const JID& to);
+ void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleMUCBookmarkAdded(const MUCBookmark& bookmark);
+ void handleMUCBookmarkRemoved(const MUCBookmark& bookmark);
+ void handleUserLeftMUC(MUCController* mucController);
+ void handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname);
+ void handleBookmarksReady();
+ void handleChatActivity(const JID& jid, const std::string& activity, bool isMUC);
+ void handleChatClosed(const JID& jid);
+ void handleNewFileTransferController(FileTransferController*);
+ void handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf);
+ void handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state);
+ boost::optional<ChatListWindow::Chat> removeExistingChat(const ChatListWindow::Chat& chat);
+ void cleanupPrivateMessageRecents();
+ void appendRecent(const ChatListWindow::Chat& chat);
+ void prependRecent(const ChatListWindow::Chat& chat);
+ void setupBookmarks();
+ void loadRecents();
+ void saveRecents();
+ void handleChatMadeRecent();
+ void handleMUCBookmarkActivated(const MUCBookmark&);
+ void handleRecentActivated(const ChatListWindow::Chat&);
+ void handleUnreadCountChanged(ChatControllerBase* controller);
+ void handleAvatarChanged(const JID& jid);
+ void handleClearRecentsRequested();
+ void handleJIDAddedToRoster(const JID&);
+ void handleJIDRemovedFromRoster(const JID&);
+ void handleJIDUpdatedInRoster(const JID&);
+ void handleRosterCleared();
+ void handleSettingChanged(const std::string& settingPath);
+ void markAllRecentsOffline();
+ void handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector<JID>& jidsToInvite, const std::string& reason);
+
+ void handleLocalServiceFound(const JID& service, boost::shared_ptr<DiscoInfo> info);
+ void handleLocalServiceWalkFinished();
+
+ void updatePresenceReceivingStateOnChatController(const JID&);
+ ChatListWindow::Chat updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const;
+
+
+ ChatController* getChatControllerOrFindAnother(const JID &contact);
+ ChatController* createNewChatController(const JID &contact);
+ ChatController* getChatControllerOrCreate(const JID &contact);
+ ChatController* getChatControllerIfExists(const JID &contact, bool rebindIfNeeded = true);
+
+ private:
+ std::map<JID, MUCController*> mucControllers_;
+ std::map<JID, ChatController*> chatControllers_;
+ std::map<ChatControllerBase*, SingleChatWindowFactoryAdapter*> chatWindowFactoryAdapters_;
+ EventController* eventController_;
+ JID jid_;
+ StanzaChannel* stanzaChannel_;
+ IQRouter* iqRouter_;
+ ChatWindowFactory* chatWindowFactory_;
+ JoinMUCWindowFactory* joinMUCWindowFactory_;
+ NickResolver* nickResolver_;
+ PresenceOracle* presenceOracle_;
+ AvatarManager* avatarManager_;
+ PresenceSender* presenceSender_;
+ UIEventStream* uiEventStream_;
+ MUCBookmarkManager* mucBookmarkManager_;
+ boost::shared_ptr<DiscoInfo> serverDiscoInfo_;
+ ChatListWindow* chatListWindow_;
+ JoinMUCWindow* joinMUCWindow_;
+ boost::bsignals::scoped_connection uiEventConnection_;
+ bool useDelayForLatency_;
+ TimerFactory* timerFactory_;
+ MUCRegistry* mucRegistry_;
+ EntityCapsProvider* entityCapsProvider_;
+ MUCManager* mucManager;
+ MUCSearchController* mucSearchController_;
+ std::list<ChatListWindow::Chat> recentChats_;
+ ProfileSettingsProvider* profileSettings_;
+ FileTransferOverview* ftOverview_;
+ XMPPRoster* roster_;
+ bool eagleMode_;
+ bool userWantsReceipts_;
+ SettingsProvider* settings_;
+ HistoryController* historyController_;
+ WhiteboardManager* whiteboardManager_;
+ HighlightManager* highlightManager_;
+ std::map<std::string, std::string> emoticons_;
+ ClientBlockListManager* clientBlockListManager_;
+ JID localMUCServiceJID_;
+ boost::shared_ptr<DiscoServiceWalker> localMUCServiceFinderWalker_;
+ AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_;
+ IDGenerator idGenerator_;
+ VCardManager* vcardManager_;
+ };
}
diff --git a/Swift/Controllers/Chat/MUCController.cpp b/Swift/Controllers/Chat/MUCController.cpp
index 0bb670d..1e2b7ad 100644
--- a/Swift/Controllers/Chat/MUCController.cpp
+++ b/Swift/Controllers/Chat/MUCController.cpp
@@ -58,1163 +58,1163 @@
namespace Swift {
class MUCBookmarkPredicate {
- public:
- MUCBookmarkPredicate(const JID& mucJID) : roomJID_(mucJID) { }
- bool operator()(const MUCBookmark& operand) {
- return operand.getRoom() == roomJID_;
- }
-
- private:
- JID roomJID_;
+ public:
+ MUCBookmarkPredicate(const JID& mucJID) : roomJID_(mucJID) { }
+ bool operator()(const MUCBookmark& operand) {
+ return operand.getRoom() == roomJID_;
+ }
+
+ private:
+ JID roomJID_;
};
/**
* The controller does not gain ownership of the stanzaChannel, nor the factory.
*/
MUCController::MUCController (
- const JID& self,
- MUC::ref muc,
- const boost::optional<std::string>& password,
- const std::string &nick,
- StanzaChannel* stanzaChannel,
- IQRouter* iqRouter,
- ChatWindowFactory* chatWindowFactory,
- PresenceOracle* presenceOracle,
- AvatarManager* avatarManager,
- UIEventStream* uiEventStream,
- bool useDelayForLatency,
- TimerFactory* timerFactory,
- EventController* eventController,
- EntityCapsProvider* entityCapsProvider,
- XMPPRoster* roster,
- HistoryController* historyController,
- MUCRegistry* mucRegistry,
- HighlightManager* highlightManager,
- ClientBlockListManager* clientBlockListManager,
- boost::shared_ptr<ChatMessageParser> chatMessageParser,
- bool isImpromptu,
- AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider,
- VCardManager* vcardManager,
- MUCBookmarkManager* mucBookmarkManager) :
- ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, muc->getJID(), presenceOracle, avatarManager, useDelayForLatency, uiEventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), muc_(muc), nick_(nick), desiredNick_(nick), password_(password), renameCounter_(0), isImpromptu_(isImpromptu), isImpromptuAlreadyConfigured_(false), clientBlockListManager_(clientBlockListManager), mucBookmarkManager_(mucBookmarkManager) {
- parting_ = true;
- joined_ = false;
- lastWasPresence_ = false;
- shouldJoinOnReconnect_ = true;
- doneGettingHistory_ = false;
- events_ = uiEventStream;
- xmppRoster_ = roster;
-
- roster_ = new Roster(false, true);
- rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithResource);
- completer_ = new TabComplete();
- chatWindow_->setRosterModel(roster_);
- chatWindow_->setTabComplete(completer_);
- chatWindow_->onClosed.connect(boost::bind(&MUCController::handleWindowClosed, this));
- chatWindow_->onOccupantSelectionChanged.connect(boost::bind(&MUCController::handleWindowOccupantSelectionChanged, this, _1));
- chatWindow_->onOccupantActionSelected.connect(boost::bind(&MUCController::handleActionRequestedOnOccupant, this, _1, _2));
- chatWindow_->onChangeSubjectRequest.connect(boost::bind(&MUCController::handleChangeSubjectRequest, this, _1));
- chatWindow_->onBookmarkRequest.connect(boost::bind(&MUCController::handleBookmarkRequest, this));
- chatWindow_->onConfigureRequest.connect(boost::bind(&MUCController::handleConfigureRequest, this, _1));
- chatWindow_->onConfigurationFormCancelled.connect(boost::bind(&MUCController::handleConfigurationCancelled, this));
- chatWindow_->onDestroyRequest.connect(boost::bind(&MUCController::handleDestroyRoomRequest, this));
- chatWindow_->onInviteToChat.connect(boost::bind(&MUCController::handleInvitePersonToThisMUCRequest, this, _1));
- chatWindow_->onGetAffiliationsRequest.connect(boost::bind(&MUCController::handleGetAffiliationsRequest, this));
- chatWindow_->onChangeAffiliationsRequest.connect(boost::bind(&MUCController::handleChangeAffiliationsRequest, this, _1));
- chatWindow_->onUnblockUserRequest.connect(boost::bind(&MUCController::handleUnblockUserRequest, this));
- muc_->onJoinComplete.connect(boost::bind(&MUCController::handleJoinComplete, this, _1));
- muc_->onJoinFailed.connect(boost::bind(&MUCController::handleJoinFailed, this, _1));
- muc_->onOccupantJoined.connect(boost::bind(&MUCController::handleOccupantJoined, this, _1));
- muc_->onOccupantNicknameChanged.connect(boost::bind(&MUCController::handleOccupantNicknameChanged, this, _1, _2));
- muc_->onOccupantPresenceChange.connect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1));
- muc_->onOccupantLeft.connect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3));
- muc_->onRoleChangeFailed.connect(boost::bind(&MUCController::handleOccupantRoleChangeFailed, this, _1, _2, _3));
- muc_->onAffiliationListReceived.connect(boost::bind(&MUCController::handleAffiliationListReceived, this, _1, _2));
- muc_->onConfigurationFailed.connect(boost::bind(&MUCController::handleConfigurationFailed, this, _1));
- muc_->onConfigurationFormReceived.connect(boost::bind(&MUCController::handleConfigurationFormReceived, this, _1));
- highlighter_->setMode(isImpromptu_ ? Highlighter::ChatMode : Highlighter::MUCMode);
- highlighter_->setNick(nick_);
- if (timerFactory && stanzaChannel_->isAvailable()) {
- loginCheckTimer_ = boost::shared_ptr<Timer>(timerFactory->createTimer(MUC_JOIN_WARNING_TIMEOUT_MILLISECONDS));
- loginCheckTimer_->onTick.connect(boost::bind(&MUCController::handleJoinTimeoutTick, this));
- loginCheckTimer_->start();
- }
- else {
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You are currently offline. You will enter this room when you are connected.")), ChatWindow::DefaultDirection);
- }
- if (isImpromptu) {
- muc_->onUnlocked.connect(boost::bind(&MUCController::handleRoomUnlocked, this));
- chatWindow_->convertToMUC(ChatWindow::ImpromptuMUC);
- } else {
- muc_->onOccupantRoleChanged.connect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3));
- muc_->onOccupantAffiliationChanged.connect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3));
- chatWindow_->convertToMUC(ChatWindow::StandardMUC);
- chatWindow_->setName(muc->getJID().getNode());
- }
- if (stanzaChannel->isAvailable()) {
- MUCController::setOnline(true);
- }
- if (avatarManager_ != NULL) {
- avatarChangedConnection_ = (avatarManager_->onAvatarChanged.connect(boost::bind(&MUCController::handleAvatarChanged, this, _1)));
- }
- MUCController::handleBareJIDCapsChanged(muc->getJID());
- eventStream_->onUIEvent.connect(boost::bind(&MUCController::handleUIEvent, this, _1));
-
-
- // setup handling of MUC bookmark changes
- mucBookmarkManagerBookmarkAddedConnection_ = (mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&MUCController::handleMUCBookmarkAdded, this, _1)));
- mucBookmarkManagerBookmarkRemovedConnection_ = (mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&MUCController::handleMUCBookmarkRemoved, this, _1)));
-
- std::vector<MUCBookmark> mucBookmarks = mucBookmarkManager_->getBookmarks();
- std::vector<MUCBookmark>::iterator bookmarkIterator = std::find_if(mucBookmarks.begin(), mucBookmarks.end(), MUCBookmarkPredicate(muc->getJID()));
- if (bookmarkIterator != mucBookmarks.end()) {
- updateChatWindowBookmarkStatus(*bookmarkIterator);
- }
- else {
- updateChatWindowBookmarkStatus(boost::optional<MUCBookmark>());
- }
+ const JID& self,
+ MUC::ref muc,
+ const boost::optional<std::string>& password,
+ const std::string &nick,
+ StanzaChannel* stanzaChannel,
+ IQRouter* iqRouter,
+ ChatWindowFactory* chatWindowFactory,
+ PresenceOracle* presenceOracle,
+ AvatarManager* avatarManager,
+ UIEventStream* uiEventStream,
+ bool useDelayForLatency,
+ TimerFactory* timerFactory,
+ EventController* eventController,
+ EntityCapsProvider* entityCapsProvider,
+ XMPPRoster* roster,
+ HistoryController* historyController,
+ MUCRegistry* mucRegistry,
+ HighlightManager* highlightManager,
+ ClientBlockListManager* clientBlockListManager,
+ boost::shared_ptr<ChatMessageParser> chatMessageParser,
+ bool isImpromptu,
+ AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider,
+ VCardManager* vcardManager,
+ MUCBookmarkManager* mucBookmarkManager) :
+ ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, muc->getJID(), presenceOracle, avatarManager, useDelayForLatency, uiEventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), muc_(muc), nick_(nick), desiredNick_(nick), password_(password), renameCounter_(0), isImpromptu_(isImpromptu), isImpromptuAlreadyConfigured_(false), clientBlockListManager_(clientBlockListManager), mucBookmarkManager_(mucBookmarkManager) {
+ parting_ = true;
+ joined_ = false;
+ lastWasPresence_ = false;
+ shouldJoinOnReconnect_ = true;
+ doneGettingHistory_ = false;
+ events_ = uiEventStream;
+ xmppRoster_ = roster;
+
+ roster_ = new Roster(false, true);
+ rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithResource);
+ completer_ = new TabComplete();
+ chatWindow_->setRosterModel(roster_);
+ chatWindow_->setTabComplete(completer_);
+ chatWindow_->onClosed.connect(boost::bind(&MUCController::handleWindowClosed, this));
+ chatWindow_->onOccupantSelectionChanged.connect(boost::bind(&MUCController::handleWindowOccupantSelectionChanged, this, _1));
+ chatWindow_->onOccupantActionSelected.connect(boost::bind(&MUCController::handleActionRequestedOnOccupant, this, _1, _2));
+ chatWindow_->onChangeSubjectRequest.connect(boost::bind(&MUCController::handleChangeSubjectRequest, this, _1));
+ chatWindow_->onBookmarkRequest.connect(boost::bind(&MUCController::handleBookmarkRequest, this));
+ chatWindow_->onConfigureRequest.connect(boost::bind(&MUCController::handleConfigureRequest, this, _1));
+ chatWindow_->onConfigurationFormCancelled.connect(boost::bind(&MUCController::handleConfigurationCancelled, this));
+ chatWindow_->onDestroyRequest.connect(boost::bind(&MUCController::handleDestroyRoomRequest, this));
+ chatWindow_->onInviteToChat.connect(boost::bind(&MUCController::handleInvitePersonToThisMUCRequest, this, _1));
+ chatWindow_->onGetAffiliationsRequest.connect(boost::bind(&MUCController::handleGetAffiliationsRequest, this));
+ chatWindow_->onChangeAffiliationsRequest.connect(boost::bind(&MUCController::handleChangeAffiliationsRequest, this, _1));
+ chatWindow_->onUnblockUserRequest.connect(boost::bind(&MUCController::handleUnblockUserRequest, this));
+ muc_->onJoinComplete.connect(boost::bind(&MUCController::handleJoinComplete, this, _1));
+ muc_->onJoinFailed.connect(boost::bind(&MUCController::handleJoinFailed, this, _1));
+ muc_->onOccupantJoined.connect(boost::bind(&MUCController::handleOccupantJoined, this, _1));
+ muc_->onOccupantNicknameChanged.connect(boost::bind(&MUCController::handleOccupantNicknameChanged, this, _1, _2));
+ muc_->onOccupantPresenceChange.connect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1));
+ muc_->onOccupantLeft.connect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3));
+ muc_->onRoleChangeFailed.connect(boost::bind(&MUCController::handleOccupantRoleChangeFailed, this, _1, _2, _3));
+ muc_->onAffiliationListReceived.connect(boost::bind(&MUCController::handleAffiliationListReceived, this, _1, _2));
+ muc_->onConfigurationFailed.connect(boost::bind(&MUCController::handleConfigurationFailed, this, _1));
+ muc_->onConfigurationFormReceived.connect(boost::bind(&MUCController::handleConfigurationFormReceived, this, _1));
+ highlighter_->setMode(isImpromptu_ ? Highlighter::ChatMode : Highlighter::MUCMode);
+ highlighter_->setNick(nick_);
+ if (timerFactory && stanzaChannel_->isAvailable()) {
+ loginCheckTimer_ = boost::shared_ptr<Timer>(timerFactory->createTimer(MUC_JOIN_WARNING_TIMEOUT_MILLISECONDS));
+ loginCheckTimer_->onTick.connect(boost::bind(&MUCController::handleJoinTimeoutTick, this));
+ loginCheckTimer_->start();
+ }
+ else {
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You are currently offline. You will enter this room when you are connected.")), ChatWindow::DefaultDirection);
+ }
+ if (isImpromptu) {
+ muc_->onUnlocked.connect(boost::bind(&MUCController::handleRoomUnlocked, this));
+ chatWindow_->convertToMUC(ChatWindow::ImpromptuMUC);
+ } else {
+ muc_->onOccupantRoleChanged.connect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3));
+ muc_->onOccupantAffiliationChanged.connect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3));
+ chatWindow_->convertToMUC(ChatWindow::StandardMUC);
+ chatWindow_->setName(muc->getJID().getNode());
+ }
+ if (stanzaChannel->isAvailable()) {
+ MUCController::setOnline(true);
+ }
+ if (avatarManager_ != NULL) {
+ avatarChangedConnection_ = (avatarManager_->onAvatarChanged.connect(boost::bind(&MUCController::handleAvatarChanged, this, _1)));
+ }
+ MUCController::handleBareJIDCapsChanged(muc->getJID());
+ eventStream_->onUIEvent.connect(boost::bind(&MUCController::handleUIEvent, this, _1));
+
+
+ // setup handling of MUC bookmark changes
+ mucBookmarkManagerBookmarkAddedConnection_ = (mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&MUCController::handleMUCBookmarkAdded, this, _1)));
+ mucBookmarkManagerBookmarkRemovedConnection_ = (mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&MUCController::handleMUCBookmarkRemoved, this, _1)));
+
+ std::vector<MUCBookmark> mucBookmarks = mucBookmarkManager_->getBookmarks();
+ std::vector<MUCBookmark>::iterator bookmarkIterator = std::find_if(mucBookmarks.begin(), mucBookmarks.end(), MUCBookmarkPredicate(muc->getJID()));
+ if (bookmarkIterator != mucBookmarks.end()) {
+ updateChatWindowBookmarkStatus(*bookmarkIterator);
+ }
+ else {
+ updateChatWindowBookmarkStatus(boost::optional<MUCBookmark>());
+ }
}
MUCController::~MUCController() {
- eventStream_->onUIEvent.disconnect(boost::bind(&MUCController::handleUIEvent, this, _1));
- chatWindow_->setRosterModel(NULL);
- delete rosterVCardProvider_;
- delete roster_;
- if (loginCheckTimer_) {
- loginCheckTimer_->stop();
- }
- chatWindow_->setTabComplete(NULL);
- delete completer_;
+ eventStream_->onUIEvent.disconnect(boost::bind(&MUCController::handleUIEvent, this, _1));
+ chatWindow_->setRosterModel(NULL);
+ delete rosterVCardProvider_;
+ delete roster_;
+ if (loginCheckTimer_) {
+ loginCheckTimer_->stop();
+ }
+ chatWindow_->setTabComplete(NULL);
+ delete completer_;
}
void MUCController::cancelReplaces() {
- lastWasPresence_ = false;
+ lastWasPresence_ = false;
}
void MUCController::handleWindowOccupantSelectionChanged(ContactRosterItem* item) {
- std::vector<ChatWindow::OccupantAction> actions;
-
- if (item) {
- MUCOccupant::Affiliation affiliation = muc_->getOccupant(getNick()).getAffiliation();
- MUCOccupant::Role role = muc_->getOccupant(getNick()).getRole();
- if (role == MUCOccupant::Moderator && !isImpromptu_)
- {
- if (affiliation == MUCOccupant::Admin || affiliation == MUCOccupant::Owner) {
- actions.push_back(ChatWindow::Ban);
- }
-
- actions.push_back(ChatWindow::Kick);
- actions.push_back(ChatWindow::MakeModerator);
- actions.push_back(ChatWindow::MakeParticipant);
- actions.push_back(ChatWindow::MakeVisitor);
- }
- // 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);
+ std::vector<ChatWindow::OccupantAction> actions;
+
+ if (item) {
+ MUCOccupant::Affiliation affiliation = muc_->getOccupant(getNick()).getAffiliation();
+ MUCOccupant::Role role = muc_->getOccupant(getNick()).getRole();
+ if (role == MUCOccupant::Moderator && !isImpromptu_)
+ {
+ if (affiliation == MUCOccupant::Admin || affiliation == MUCOccupant::Owner) {
+ actions.push_back(ChatWindow::Ban);
+ }
+
+ actions.push_back(ChatWindow::Kick);
+ actions.push_back(ChatWindow::MakeModerator);
+ actions.push_back(ChatWindow::MakeParticipant);
+ actions.push_back(ChatWindow::MakeVisitor);
+ }
+ // 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(boost::make_shared<RequestAddUserDialogUIEvent>(realJID, occupant.getNick()));break;
- case ChatWindow::ShowProfile: events_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(mucJID));break;
- }
+ 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(boost::make_shared<RequestAddUserDialogUIEvent>(realJID, occupant.getNick()));break;
+ case ChatWindow::ShowProfile: events_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(mucJID));break;
+ }
}
void MUCController::handleBareJIDCapsChanged(const JID& /*jid*/) {
- Tristate support = Yes;
- bool any = false;
- foreach (const std::string& 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);
+ Tristate support = Yes;
+ bool any = false;
+ foreach (const std::string& 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
+ 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_);
- }
+ 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_);
- }
- }
+ if (lastActivity_ == boost::posix_time::not_a_date_time) {
+ muc_->joinAs(nick_);
+ }
+ else {
+ muc_->joinWithContextSince(nick_, lastActivity_);
+ }
+ }
}
bool MUCController::isJoined() {
- return joined_;
+ return joined_;
}
const std::string& MUCController::getNick() {
- return nick_;
+ return nick_;
}
const boost::optional<std::string> MUCController::getPassword() const {
- return password_;
+ return password_;
}
bool MUCController::isImpromptu() const {
- return isImpromptu_;
+ 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) {
- if (occupant.first != nick_) {
- participants[occupant.first] = occupant.second.getRealJID().is_initialized() ? occupant.second.getRealJID().get().toBare() : JID();
- }
- }
- return participants;
+ 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) {
+ 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) {
- muc_->invitePerson(jid, reason, isImpromptu_);
- }
+ foreach (const JID& 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);
+ 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();
- }
+ if (loginCheckTimer_) {
+ loginCheckTimer_->stop();
+ }
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch-enum"
void MUCController::handleJoinFailed(boost::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 += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "No nickname specified");
- break;
- case ErrorPayload::NotAuthorized:
- errorMessage += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "The correct room password is needed");
- break;
- case ErrorPayload::RegistrationRequired:
- errorMessage += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "Only members may enter");
- break;
- case ErrorPayload::Forbidden:
- errorMessage += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "You are banned from the room");
- break;
- case ErrorPayload::ServiceUnavailable:
- errorMessage += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "The room is full");
- break;
- case ErrorPayload::ItemNotFound:
- errorMessage += ": ";
- errorMessage += QT_TRANSLATE_NOOP("", "The room does not exist");
- break;
-
- default: break;
- }
- }
- errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't enter room: %1%.")) % errorMessage);
- chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
- parting_ = true;
- if (!rejoinNick.empty() && renameCounter_ < 10) {
- renameCounter_++;
- setNick(rejoinNick);
- rejoin();
- }
+ 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 += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "No nickname specified");
+ break;
+ case ErrorPayload::NotAuthorized:
+ errorMessage += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "The correct room password is needed");
+ break;
+ case ErrorPayload::RegistrationRequired:
+ errorMessage += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "Only members may enter");
+ break;
+ case ErrorPayload::Forbidden:
+ errorMessage += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "You are banned from the room");
+ break;
+ case ErrorPayload::ServiceUnavailable:
+ errorMessage += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "The room is full");
+ break;
+ case ErrorPayload::ItemNotFound:
+ errorMessage += ": ";
+ errorMessage += QT_TRANSLATE_NOOP("", "The room does not exist");
+ break;
+
+ default: break;
+ }
+ }
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't enter room: %1%.")) % errorMessage);
+ chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
+ parting_ = true;
+ if (!rejoinNick.empty() && renameCounter_ < 10) {
+ renameCounter_++;
+ setNick(rejoinNick);
+ rejoin();
+ }
}
#pragma clang diagnostic pop
void MUCController::handleJoinComplete(const std::string& nick) {
- receivedActivity();
- renameCounter_ = 0;
- joined_ = true;
- std::string joinMessage;
- if (isImpromptu_) {
- joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have joined the chat as %1%.")) % nick);
- } else {
- joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have entered room %1% as %2%.")) % toJID_.toString() % nick);
- }
- setNick(nick);
- chatWindow_->replaceSystemMessage(chatMessageParser_->parseMessageBody(joinMessage), lastJoinMessageUID_, ChatWindow::UpdateTimestamp);
- lastJoinMessageUID_ = "";
+ receivedActivity();
+ renameCounter_ = 0;
+ joined_ = true;
+ std::string joinMessage;
+ if (isImpromptu_) {
+ joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have joined the chat as %1%.")) % nick);
+ } else {
+ joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have entered room %1% as %2%.")) % toJID_.toString() % nick);
+ }
+ setNick(nick);
+ chatWindow_->replaceSystemMessage(chatMessageParser_->parseMessageBody(joinMessage), lastJoinMessageUID_, ChatWindow::UpdateTimestamp);
+ lastJoinMessageUID_ = "";
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- addRecentLogs();
+ addRecentLogs();
#endif
- clearPresenceQueue();
- shouldJoinOnReconnect_ = true;
- setEnabled(true);
- if (isImpromptu_) {
- setAvailableRoomActions(MUCOccupant::NoAffiliation, MUCOccupant::Participant);
- } else {
- MUCOccupant occupant = muc_->getOccupant(nick);
- setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole());
- }
- onUserJoined();
+ clearPresenceQueue();
+ shouldJoinOnReconnect_ = true;
+ setEnabled(true);
+ if (isImpromptu_) {
+ setAvailableRoomActions(MUCOccupant::NoAffiliation, MUCOccupant::Participant);
+ } else {
+ MUCOccupant occupant = muc_->getOccupant(nick);
+ setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole());
+ }
+ onUserJoined();
- if (isImpromptu_) {
- setImpromptuWindowTitle();
- }
+ if (isImpromptu_) {
+ setImpromptuWindowTitle();
+ }
}
void MUCController::handleAvatarChanged(const JID& jid) {
- if (parting_ || !jid.equals(toJID_, JID::WithoutResource)) {
- return;
- }
- roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid), JID::WithResource));
+ if (parting_ || !jid.equals(toJID_, JID::WithoutResource)) {
+ return;
+ }
+ roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid), JID::WithResource));
}
void MUCController::handleWindowClosed() {
- parting_ = true;
- shouldJoinOnReconnect_ = false;
- muc_->part();
- onUserLeft();
+ parting_ = true;
+ shouldJoinOnReconnect_ = false;
+ muc_->part();
+ onUserLeft();
}
void MUCController::handleOccupantJoined(const MUCOccupant& occupant) {
- if (nick_ != occupant.getNick()) {
- completer_->addWord(occupant.getNick());
- }
- receivedActivity();
- JID jid(nickToJID(occupant.getNick()));
- JID realJID;
- if (occupant.getRealJID()) {
- realJID = occupant.getRealJID().get();
- }
- currentOccupants_.insert(occupant.getNick());
- NickJoinPart event(occupant.getNick(), Join);
- appendToJoinParts(joinParts_, event);
- MUCOccupant::Role role = MUCOccupant::Participant;
- MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation;
- if (!isImpromptu_) {
- role = occupant.getRole();
- affiliation = occupant.getAffiliation();
- }
- std::string groupName(roleToGroupName(role));
- roster_->addContact(jid, realJID, occupant.getNick(), groupName, avatarManager_->getAvatarPath(jid));
- roster_->applyOnItems(SetMUC(jid, role, affiliation));
- roster_->getGroup(groupName)->setManualSort(roleToSortName(role));
- if (joined_) {
- std::string joinString;
- if (role != MUCOccupant::NoRole && role != MUCOccupant::Participant) {
- joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %3% as a %2%.")) % occupant.getNick() % roleToFriendlyName(role) % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room")));
- }
- else {
- joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %2%.")) % occupant.getNick() % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room")));
- }
- if (shouldUpdateJoinParts()) {
- updateJoinParts();
- } else {
- addPresenceMessage(joinString);
- }
-
- if (isImpromptu_) {
- setImpromptuWindowTitle();
- onActivity("");
- }
- }
- if (avatarManager_ != NULL) {
- handleAvatarChanged(jid);
- }
+ if (nick_ != occupant.getNick()) {
+ completer_->addWord(occupant.getNick());
+ }
+ receivedActivity();
+ JID jid(nickToJID(occupant.getNick()));
+ JID realJID;
+ if (occupant.getRealJID()) {
+ realJID = occupant.getRealJID().get();
+ }
+ currentOccupants_.insert(occupant.getNick());
+ NickJoinPart event(occupant.getNick(), Join);
+ appendToJoinParts(joinParts_, event);
+ MUCOccupant::Role role = MUCOccupant::Participant;
+ MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation;
+ if (!isImpromptu_) {
+ role = occupant.getRole();
+ affiliation = occupant.getAffiliation();
+ }
+ std::string groupName(roleToGroupName(role));
+ roster_->addContact(jid, realJID, occupant.getNick(), groupName, avatarManager_->getAvatarPath(jid));
+ roster_->applyOnItems(SetMUC(jid, role, affiliation));
+ roster_->getGroup(groupName)->setManualSort(roleToSortName(role));
+ if (joined_) {
+ std::string joinString;
+ if (role != MUCOccupant::NoRole && role != MUCOccupant::Participant) {
+ joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %3% as a %2%.")) % occupant.getNick() % roleToFriendlyName(role) % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room")));
+ }
+ else {
+ joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %2%.")) % occupant.getNick() % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room")));
+ }
+ if (shouldUpdateJoinParts()) {
+ updateJoinParts();
+ } else {
+ addPresenceMessage(joinString);
+ }
+
+ if (isImpromptu_) {
+ setImpromptuWindowTitle();
+ onActivity("");
+ }
+ }
+ if (avatarManager_ != NULL) {
+ handleAvatarChanged(jid);
+ }
}
void MUCController::addPresenceMessage(const std::string& message) {
- lastWasPresence_ = true;
- chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(message), ChatWindow::DefaultDirection);
+ lastWasPresence_ = true;
+ chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(message), ChatWindow::DefaultDirection);
}
void MUCController::setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role)
{
- std::vector<ChatWindow::RoomAction> actions;
-
- if (role <= MUCOccupant::Participant) {
- actions.push_back(ChatWindow::ChangeSubject);
- }
- if (affiliation == MUCOccupant::Owner) {
- actions.push_back(ChatWindow::Configure);
- }
- if (affiliation <= MUCOccupant::Admin) {
- actions.push_back(ChatWindow::Affiliations);
- }
- if (affiliation == MUCOccupant::Owner) {
- actions.push_back(ChatWindow::Destroy);
- }
- if (role <= MUCOccupant::Visitor) {
- actions.push_back(ChatWindow::Invite);
- }
- chatWindow_->setAvailableRoomActions(actions);
+ std::vector<ChatWindow::RoomAction> actions;
+
+ if (role <= MUCOccupant::Participant) {
+ actions.push_back(ChatWindow::ChangeSubject);
+ }
+ if (affiliation == MUCOccupant::Owner) {
+ actions.push_back(ChatWindow::Configure);
+ }
+ if (affiliation <= MUCOccupant::Admin) {
+ actions.push_back(ChatWindow::Affiliations);
+ }
+ if (affiliation == MUCOccupant::Owner) {
+ actions.push_back(ChatWindow::Destroy);
+ }
+ if (role <= MUCOccupant::Visitor) {
+ actions.push_back(ChatWindow::Invite);
+ }
+ chatWindow_->setAvailableRoomActions(actions);
}
void MUCController::clearPresenceQueue() {
- lastWasPresence_ = false;
- joinParts_.clear();
+ lastWasPresence_ = false;
+ joinParts_.clear();
}
std::string MUCController::roleToFriendlyName(MUCOccupant::Role role) {
- switch (role) {
- case MUCOccupant::Moderator: return QT_TRANSLATE_NOOP("", "moderator");
- case MUCOccupant::Participant: return QT_TRANSLATE_NOOP("", "participant");
- case MUCOccupant::Visitor: return QT_TRANSLATE_NOOP("", "visitor");
- case MUCOccupant::NoRole: return "";
- }
- assert(false);
- return "";
+ switch (role) {
+ case MUCOccupant::Moderator: return QT_TRANSLATE_NOOP("", "moderator");
+ case MUCOccupant::Participant: return QT_TRANSLATE_NOOP("", "participant");
+ case MUCOccupant::Visitor: return QT_TRANSLATE_NOOP("", "visitor");
+ case MUCOccupant::NoRole: return "";
+ }
+ assert(false);
+ return "";
}
std::string MUCController::roleToSortName(MUCOccupant::Role role) {
- switch (role) {
- case MUCOccupant::Moderator: return "1";
- case MUCOccupant::Participant: return "2";
- case MUCOccupant::Visitor: return "3";
- case MUCOccupant::NoRole: return "4";
- }
- assert(false);
- return "5";
+ switch (role) {
+ case MUCOccupant::Moderator: return "1";
+ case MUCOccupant::Participant: return "2";
+ case MUCOccupant::Visitor: return "3";
+ case MUCOccupant::NoRole: return "4";
+ }
+ assert(false);
+ return "5";
}
JID MUCController::nickToJID(const std::string& nick) {
- return muc_->getJID().withResource(nick);
+ return muc_->getJID().withResource(nick);
}
bool MUCController::messageTargetsMe(boost::shared_ptr<Message> message) {
- std::string stringRegexp(".*\\b" + boost::to_lower_copy(nick_) + "\\b.*");
- boost::regex myRegexp(stringRegexp);
- return boost::regex_match(boost::to_lower_copy(message->getBody().get_value_or("")), myRegexp);
+ std::string stringRegexp(".*\\b" + boost::to_lower_copy(nick_) + "\\b.*");
+ boost::regex myRegexp(stringRegexp);
+ return boost::regex_match(boost::to_lower_copy(message->getBody().get_value_or("")), myRegexp);
}
void MUCController::preHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent) {
- if (messageEvent->getStanza()->getType() == Message::Groupchat) {
- lastActivity_ = boost::posix_time::microsec_clock::universal_time();
- }
- clearPresenceQueue();
- boost::shared_ptr<Message> message = messageEvent->getStanza();
- if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && messageTargetsMe(message) && !message->getPayload<Delay>() && messageEvent->isReadable()) {
- chatWindow_->flash();
- }
- else {
- messageEvent->setTargetsMe(false);
- }
- if (messageEvent->isReadable() && isImpromptu_) {
- chatWindow_->flash(); /* behave like a regular char*/
- }
- if (joined_) {
- std::string nick = message->getFrom().getResource();
- if (nick != nick_ && currentOccupants_.find(nick) != currentOccupants_.end()) {
- completer_->addWord(nick);
- }
- }
- /*Buggy implementations never send the status code, so use an incoming message as a hint that joining's done (e.g. the old ejabberd on psi-im.org).*/
- receivedActivity();
- joined_ = true;
-
- if (message->hasSubject() && !message->getPayload<Body>() && !message->getPayload<Thread>()) {
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The room subject is now: %1%")) % message->getSubject())), ChatWindow::DefaultDirection);
- chatWindow_->setSubject(message->getSubject());
- doneGettingHistory_ = true;
- }
-
- if (!doneGettingHistory_ && !message->getPayload<Delay>()) {
- doneGettingHistory_ = true;
- }
-
- if (!doneGettingHistory_) {
- checkDuplicates(message);
- messageEvent->conclude();
- }
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ lastActivity_ = boost::posix_time::microsec_clock::universal_time();
+ }
+ clearPresenceQueue();
+ boost::shared_ptr<Message> message = messageEvent->getStanza();
+ if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && messageTargetsMe(message) && !message->getPayload<Delay>() && messageEvent->isReadable()) {
+ chatWindow_->flash();
+ }
+ else {
+ messageEvent->setTargetsMe(false);
+ }
+ if (messageEvent->isReadable() && isImpromptu_) {
+ chatWindow_->flash(); /* behave like a regular char*/
+ }
+ if (joined_) {
+ std::string nick = message->getFrom().getResource();
+ if (nick != nick_ && currentOccupants_.find(nick) != currentOccupants_.end()) {
+ completer_->addWord(nick);
+ }
+ }
+ /*Buggy implementations never send the status code, so use an incoming message as a hint that joining's done (e.g. the old ejabberd on psi-im.org).*/
+ receivedActivity();
+ joined_ = true;
+
+ if (message->hasSubject() && !message->getPayload<Body>() && !message->getPayload<Thread>()) {
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The room subject is now: %1%")) % message->getSubject())), ChatWindow::DefaultDirection);
+ chatWindow_->setSubject(message->getSubject());
+ doneGettingHistory_ = true;
+ }
+
+ if (!doneGettingHistory_ && !message->getPayload<Delay>()) {
+ doneGettingHistory_ = true;
+ }
+
+ if (!doneGettingHistory_) {
+ checkDuplicates(message);
+ messageEvent->conclude();
+ }
}
void MUCController::addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time) {
- if (from.isBare()) {
- chatWindow_->addSystemMessage(message, ChatWindow::DefaultDirection);
- }
- else {
- ChatControllerBase::addMessageHandleIncomingMessage(from, message, senderIsSelf, label, time);
- }
+ if (from.isBare()) {
+ chatWindow_->addSystemMessage(message, ChatWindow::DefaultDirection);
+ }
+ else {
+ ChatControllerBase::addMessageHandleIncomingMessage(from, message, senderIsSelf, label, time);
+ }
}
void MUCController::postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) {
- boost::shared_ptr<Message> message = messageEvent->getStanza();
- if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && !message->getPayload<Delay>()) {
- if (messageTargetsMe(message) || isImpromptu_) {
- eventController_->handleIncomingEvent(messageEvent);
- }
- if (!messageEvent->getConcluded()) {
- handleHighlightActions(chatMessage);
- }
- }
+ boost::shared_ptr<Message> message = messageEvent->getStanza();
+ if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && !message->getPayload<Delay>()) {
+ if (messageTargetsMe(message) || isImpromptu_) {
+ eventController_->handleIncomingEvent(messageEvent);
+ }
+ if (!messageEvent->getConcluded()) {
+ handleHighlightActions(chatMessage);
+ }
+ }
}
void MUCController::handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant, const MUCOccupant::Role& oldRole) {
- clearPresenceQueue();
- receivedActivity();
- JID jid(nickToJID(nick));
- roster_->removeContactFromGroup(jid, roleToGroupName(oldRole));
- JID realJID;
- if (occupant.getRealJID()) {
- realJID = occupant.getRealJID().get();
- }
- std::string group(roleToGroupName(occupant.getRole()));
- roster_->addContact(jid, realJID, nick, group, avatarManager_->getAvatarPath(jid));
- roster_->getGroup(group)->setManualSort(roleToSortName(occupant.getRole()));
- roster_->applyOnItems(SetMUC(jid, occupant.getRole(), occupant.getAffiliation()));
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "%1% is now a %2%")) % nick % roleToFriendlyName(occupant.getRole()))), ChatWindow::DefaultDirection);
- if (nick == nick_) {
- setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole());
- }
+ clearPresenceQueue();
+ receivedActivity();
+ JID jid(nickToJID(nick));
+ roster_->removeContactFromGroup(jid, roleToGroupName(oldRole));
+ JID realJID;
+ if (occupant.getRealJID()) {
+ realJID = occupant.getRealJID().get();
+ }
+ std::string group(roleToGroupName(occupant.getRole()));
+ roster_->addContact(jid, realJID, nick, group, avatarManager_->getAvatarPath(jid));
+ roster_->getGroup(group)->setManualSort(roleToSortName(occupant.getRole()));
+ roster_->applyOnItems(SetMUC(jid, occupant.getRole(), occupant.getAffiliation()));
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "%1% is now a %2%")) % nick % roleToFriendlyName(occupant.getRole()))), ChatWindow::DefaultDirection);
+ if (nick == nick_) {
+ setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole());
+ }
}
void MUCController::handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Affiliation& /*oldAffiliation*/)
{
- if (nick == nick_) {
- setAvailableRoomActions(affiliation, muc_->getOccupant(nick_).getRole());
- }
- JID jid(nickToJID(nick));
- MUCOccupant occupant = muc_->getOccupant(nick);
- roster_->applyOnItems(SetMUC(jid, occupant.getRole(), affiliation));
+ if (nick == nick_) {
+ setAvailableRoomActions(affiliation, muc_->getOccupant(nick_).getRole());
+ }
+ JID jid(nickToJID(nick));
+ MUCOccupant occupant = muc_->getOccupant(nick);
+ roster_->applyOnItems(SetMUC(jid, occupant.getRole(), affiliation));
}
std::string MUCController::roleToGroupName(MUCOccupant::Role role) {
- std::string result;
- switch (role) {
- case MUCOccupant::Moderator: result = QT_TRANSLATE_NOOP("", "Moderators"); break;
- case MUCOccupant::Participant: result = QT_TRANSLATE_NOOP("", "Participants"); break;
- case MUCOccupant::Visitor: result = QT_TRANSLATE_NOOP("", "Visitors"); break;
- case MUCOccupant::NoRole: result = QT_TRANSLATE_NOOP("", "Occupants"); break;
- }
- return result;
+ std::string result;
+ switch (role) {
+ case MUCOccupant::Moderator: result = QT_TRANSLATE_NOOP("", "Moderators"); break;
+ case MUCOccupant::Participant: result = QT_TRANSLATE_NOOP("", "Participants"); break;
+ case MUCOccupant::Visitor: result = QT_TRANSLATE_NOOP("", "Visitors"); break;
+ case MUCOccupant::NoRole: result = QT_TRANSLATE_NOOP("", "Occupants"); break;
+ }
+ return result;
}
void MUCController::setOnline(bool online) {
- ChatControllerBase::setOnline(online);
- if (!online) {
- muc_->part();
- parting_ = true;
- processUserPart();
- } else {
- if (shouldJoinOnReconnect_) {
- renameCounter_ = 0;
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
- if (blockList && blockList->isBlocked(muc_->getJID())) {
- handleBlockingStateChanged();
- lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")), ChatWindow::DefaultDirection);
- }
- else {
- if (isImpromptu_) {
- lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "Trying to join chat")), ChatWindow::DefaultDirection);
- } else {
- lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Trying to enter room %1%")) % toJID_.toString())), ChatWindow::DefaultDirection);
- }
- if (loginCheckTimer_) {
- loginCheckTimer_->start();
- }
- setNick(desiredNick_);
- rejoin();
- }
- }
- }
+ ChatControllerBase::setOnline(online);
+ if (!online) {
+ muc_->part();
+ parting_ = true;
+ processUserPart();
+ } else {
+ if (shouldJoinOnReconnect_) {
+ renameCounter_ = 0;
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ if (blockList && blockList->isBlocked(muc_->getJID())) {
+ handleBlockingStateChanged();
+ lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")), ChatWindow::DefaultDirection);
+ }
+ else {
+ if (isImpromptu_) {
+ lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "Trying to join chat")), ChatWindow::DefaultDirection);
+ } else {
+ lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Trying to enter room %1%")) % toJID_.toString())), ChatWindow::DefaultDirection);
+ }
+ if (loginCheckTimer_) {
+ loginCheckTimer_->start();
+ }
+ setNick(desiredNick_);
+ rejoin();
+ }
+ }
+ }
}
void MUCController::processUserPart() {
- roster_->removeAll();
- /* handleUserLeft won't throw a part back up unless this is called
- when it doesn't yet know we've left - which only happens on
- disconnect, so call with disconnect here so if the signal does
- bubble back up, it'll be with the right type.*/
- muc_->handleUserLeft(MUC::Disconnect);
- setEnabled(false);
+ roster_->removeAll();
+ /* handleUserLeft won't throw a part back up unless this is called
+ when it doesn't yet know we've left - which only happens on
+ disconnect, so call with disconnect here so if the signal does
+ bubble back up, it'll be with the right type.*/
+ muc_->handleUserLeft(MUC::Disconnect);
+ setEnabled(false);
}
bool MUCController::shouldUpdateJoinParts() {
- return lastWasPresence_;
+ return lastWasPresence_;
}
void MUCController::handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason) {
- NickJoinPart event(occupant.getNick(), Part);
- appendToJoinParts(joinParts_, event);
- currentOccupants_.erase(occupant.getNick());
- completer_->removeWord(occupant.getNick());
- std::string partMessage;
- bool clearAfter = false;
- if (occupant.getNick() != nick_) {
- std::string partType;
- switch (type) {
- case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partType = " (kicked)"; break;
- case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partType = " (banned)"; break;
- case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partType = " (no longer a member)"; break;
- case MUC::LeaveDestroy:
- case MUC::Disconnect:
- case MUC::LeavePart: break;
- }
- if (isImpromptu_) {
- partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the chat%2%")) % occupant.getNick() % partType);
- } else {
- partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the room%2%")) % occupant.getNick() % partType);
- }
- }
- else if (isImpromptu_) {
- switch (type) {
- case MUC::LeaveKick:
- case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break;
- case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break;
- case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "This chat has ended"); break;
- case MUC::Disconnect:
- case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the chat");
- }
- }
- else {
- switch (type) {
- case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been kicked out of the room"); break;
- case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been banned from the room"); break;
- case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You are no longer a member of the room and have been removed"); break;
- case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "The room has been destroyed"); break;
- case MUC::Disconnect:
- case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the room");
- }
- }
- if (!reason.empty()) {
- partMessage += " (" + reason + ")";
- }
- partMessage += ".";
-
- if (occupant.getNick() != nick_) {
- if (shouldUpdateJoinParts()) {
- updateJoinParts();
- } else {
- addPresenceMessage(partMessage);
- }
- roster_->removeContact(JID(toJID_.getNode(), toJID_.getDomain(), occupant.getNick()));
- } else {
- addPresenceMessage(partMessage);
- parting_ = true;
- processUserPart();
- }
- if (clearAfter) {
- clearPresenceQueue();
- }
-
- if (isImpromptu_) {
- setImpromptuWindowTitle();
- }
+ NickJoinPart event(occupant.getNick(), Part);
+ appendToJoinParts(joinParts_, event);
+ currentOccupants_.erase(occupant.getNick());
+ completer_->removeWord(occupant.getNick());
+ std::string partMessage;
+ bool clearAfter = false;
+ if (occupant.getNick() != nick_) {
+ std::string partType;
+ switch (type) {
+ case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partType = " (kicked)"; break;
+ case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partType = " (banned)"; break;
+ case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partType = " (no longer a member)"; break;
+ case MUC::LeaveDestroy:
+ case MUC::Disconnect:
+ case MUC::LeavePart: break;
+ }
+ if (isImpromptu_) {
+ partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the chat%2%")) % occupant.getNick() % partType);
+ } else {
+ partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the room%2%")) % occupant.getNick() % partType);
+ }
+ }
+ else if (isImpromptu_) {
+ switch (type) {
+ case MUC::LeaveKick:
+ case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break;
+ case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break;
+ case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "This chat has ended"); break;
+ case MUC::Disconnect:
+ case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the chat");
+ }
+ }
+ else {
+ switch (type) {
+ case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been kicked out of the room"); break;
+ case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been banned from the room"); break;
+ case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You are no longer a member of the room and have been removed"); break;
+ case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "The room has been destroyed"); break;
+ case MUC::Disconnect:
+ case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the room");
+ }
+ }
+ if (!reason.empty()) {
+ partMessage += " (" + reason + ")";
+ }
+ partMessage += ".";
+
+ if (occupant.getNick() != nick_) {
+ if (shouldUpdateJoinParts()) {
+ updateJoinParts();
+ } else {
+ addPresenceMessage(partMessage);
+ }
+ roster_->removeContact(JID(toJID_.getNode(), toJID_.getDomain(), occupant.getNick()));
+ } else {
+ addPresenceMessage(partMessage);
+ parting_ = true;
+ processUserPart();
+ }
+ if (clearAfter) {
+ clearPresenceQueue();
+ }
+
+ if (isImpromptu_) {
+ setImpromptuWindowTitle();
+ }
}
void MUCController::handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname) {
- addPresenceMessage(generateNicknameChangeString(oldNickname, newNickname));
- JID oldJID = muc_->getJID().withResource(oldNickname);
- JID newJID = muc_->getJID().withResource(newNickname);
-
- // adjust occupants
- currentOccupants_.erase(oldNickname);
- currentOccupants_.insert(newNickname);
-
- // adjust completer
- completer_->removeWord(oldNickname);
- completer_->addWord(newNickname);
-
- // update contact
- roster_->removeContact(oldJID);
- MUCOccupant occupant = muc_->getOccupant(newNickname);
-
- JID realJID;
- if (occupant.getRealJID()) {
- realJID = occupant.getRealJID().get();
- }
- MUCOccupant::Role role = MUCOccupant::Participant;
- MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation;
- if (!isImpromptu_) {
- role = occupant.getRole();
- affiliation = occupant.getAffiliation();
- }
- std::string groupName(roleToGroupName(role));
- roster_->addContact(newJID, realJID, newNickname, groupName, avatarManager_->getAvatarPath(newJID));
- roster_->applyOnItems(SetMUC(newJID, role, affiliation));
- if (avatarManager_ != NULL) {
- handleAvatarChanged(newJID);
- }
-
- clearPresenceQueue();
- onUserNicknameChanged(oldNickname, newNickname);
+ addPresenceMessage(generateNicknameChangeString(oldNickname, newNickname));
+ JID oldJID = muc_->getJID().withResource(oldNickname);
+ JID newJID = muc_->getJID().withResource(newNickname);
+
+ // adjust occupants
+ currentOccupants_.erase(oldNickname);
+ currentOccupants_.insert(newNickname);
+
+ // adjust completer
+ completer_->removeWord(oldNickname);
+ completer_->addWord(newNickname);
+
+ // update contact
+ roster_->removeContact(oldJID);
+ MUCOccupant occupant = muc_->getOccupant(newNickname);
+
+ JID realJID;
+ if (occupant.getRealJID()) {
+ realJID = occupant.getRealJID().get();
+ }
+ MUCOccupant::Role role = MUCOccupant::Participant;
+ MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation;
+ if (!isImpromptu_) {
+ role = occupant.getRole();
+ affiliation = occupant.getAffiliation();
+ }
+ std::string groupName(roleToGroupName(role));
+ roster_->addContact(newJID, realJID, newNickname, groupName, avatarManager_->getAvatarPath(newJID));
+ roster_->applyOnItems(SetMUC(newJID, role, affiliation));
+ if (avatarManager_ != NULL) {
+ handleAvatarChanged(newJID);
+ }
+
+ clearPresenceQueue();
+ onUserNicknameChanged(oldNickname, newNickname);
}
void MUCController::handleOccupantPresenceChange(boost::shared_ptr<Presence> presence) {
- receivedActivity();
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+ receivedActivity();
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
}
bool MUCController::isIncomingMessageFromMe(boost::shared_ptr<Message> message) {
- JID from = message->getFrom();
- return nick_ == from.getResource();
+ JID from = message->getFrom();
+ return nick_ == from.getResource();
}
std::string MUCController::senderHighlightNameFromMessage(const JID& from) {
- return from.getResource();
+ return from.getResource();
}
std::string MUCController::senderDisplayNameFromMessage(const JID& from) {
- return from.getResource();
+ return from.getResource();
}
void MUCController::preSendMessageRequest(boost::shared_ptr<Message> message) {
- message->setType(Swift::Message::Groupchat);
+ message->setType(Swift::Message::Groupchat);
}
boost::optional<boost::posix_time::ptime> MUCController::getMessageTimestamp(boost::shared_ptr<Message> message) const {
- return message->getTimestampFrom(toJID_);
+ return message->getTimestampFrom(toJID_);
}
void MUCController::updateJoinParts() {
- chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(generateJoinPartString(joinParts_, isImpromptu())), ChatWindow::UpdateTimestamp);
+ chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(generateJoinPartString(joinParts_, isImpromptu())), ChatWindow::UpdateTimestamp);
}
void MUCController::appendToJoinParts(std::vector<NickJoinPart>& joinParts, const NickJoinPart& newEvent) {
- std::vector<NickJoinPart>::iterator it = joinParts.begin();
- bool matched = false;
- for (; it != joinParts.end(); ++it) {
- if ((*it).nick == newEvent.nick) {
- matched = true;
- JoinPart type = (*it).type;
- switch (newEvent.type) {
- case Join: type = (type == Part) ? PartThenJoin : Join; break;
- case Part: type = (type == Join) ? JoinThenPart : Part; break;
- case PartThenJoin: break;
- case JoinThenPart: break;
- }
- (*it).type = type;
- break;
- }
- }
- if (!matched) {
- joinParts.push_back(newEvent);
- }
+ std::vector<NickJoinPart>::iterator it = joinParts.begin();
+ bool matched = false;
+ for (; it != joinParts.end(); ++it) {
+ if ((*it).nick == newEvent.nick) {
+ matched = true;
+ JoinPart type = (*it).type;
+ switch (newEvent.type) {
+ case Join: type = (type == Part) ? PartThenJoin : Join; break;
+ case Part: type = (type == Join) ? JoinThenPart : Part; break;
+ case PartThenJoin: break;
+ 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 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) {
- 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 {
- eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% has entered then left the room"));
- }
- break;
- case PartThenJoin:
- if (sorted[i].size() > 1) {
- eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% have left then returned to the room"));
- }
- else {
- eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% has left then returned to the room"));
- }
- break;
- }
- populatedEvents.push_back(static_cast<JoinPart>(i));
- eventStrings[i] = str(boost::format(eventString) % names);
- }
- }
- for (size_t i = 0; i < populatedEvents.size(); i++) {
- if (i > 0) {
- if (i < populatedEvents.size() - 1) {
- result += ", ";
- } else {
- result += QT_TRANSLATE_NOOP("", " and ");
- }
- }
- result += eventStrings[populatedEvents[i]];
- }
- return result;
+ std::vector<NickJoinPart> sorted[4];
+ std::string eventStrings[4];
+ foreach (NickJoinPart 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 {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% has entered then left the room"));
+ }
+ break;
+ case PartThenJoin:
+ if (sorted[i].size() > 1) {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% have left then returned to the room"));
+ }
+ else {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% has left then returned to the room"));
+ }
+ break;
+ }
+ populatedEvents.push_back(static_cast<JoinPart>(i));
+ eventStrings[i] = str(boost::format(eventString) % names);
+ }
+ }
+ for (size_t i = 0; i < populatedEvents.size(); i++) {
+ 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);
+ 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);
+ muc_->changeSubject(subject);
}
void MUCController::handleBookmarkRequest() {
- const JID jid = muc_->getJID();
+ const JID jid = muc_->getJID();
- // Prepare new bookmark for this room.
- MUCBookmark roomBookmark(jid, jid.toBare().toString());
- roomBookmark.setPassword(password_);
- roomBookmark.setNick(nick_);
+ // 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) {
- if (bookmark.getRoom() == jid.toBare()) {
- roomBookmark = bookmark;
- break;
- }
- }
+ // 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) {
+ if (bookmark.getRoom() == jid.toBare()) {
+ roomBookmark = bookmark;
+ break;
+ }
+ }
- chatWindow_->showBookmarkWindow(roomBookmark);
+ chatWindow_->showBookmarkWindow(roomBookmark);
}
void MUCController::handleConfigureRequest(Form::ref form) {
- if (form) {
- muc_->configureRoom(form);
- }
- else {
- muc_->requestConfigurationForm();
- }
+ 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));
+ 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));
+ std::string errorMessage = getErrorMessage(error);
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "Occupant role change failed: %1%.")) % errorMessage);
+ chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage));
}
void MUCController::configureAsImpromptuRoom(Form::ref form) {
- muc_->configureRoom(buildImpromptuRoomConfiguration(form));
- isImpromptuAlreadyConfigured_ = true;
- onImpromptuConfigCompleted();
+ muc_->configureRoom(buildImpromptuRoomConfiguration(form));
+ isImpromptuAlreadyConfigured_ = true;
+ onImpromptuConfigCompleted();
}
void MUCController::handleConfigurationFormReceived(Form::ref form) {
- if (isImpromptu_) {
- if (!isImpromptuAlreadyConfigured_) {
- configureAsImpromptuRoom(form);
- }
- } else {
- chatWindow_->showRoomConfigurationForm(form);
- }
+ if (isImpromptu_) {
+ if (!isImpromptuAlreadyConfigured_) {
+ configureAsImpromptuRoom(form);
+ }
+ } else {
+ chatWindow_->showRoomConfigurationForm(form);
+ }
}
void MUCController::handleConfigurationCancelled() {
- muc_->cancelConfigureRoom();
+ muc_->cancelConfigureRoom();
}
void MUCController::handleDestroyRoomRequest() {
- muc_->destroyRoom();
+ muc_->destroyRoom();
}
void MUCController::handleInvitePersonToThisMUCRequest(const std::vector<JID>& jidsToInvite) {
- RequestInviteToMUCUIEvent::ImpromptuMode mode = isImpromptu_ ? RequestInviteToMUCUIEvent::Impromptu : RequestInviteToMUCUIEvent::NotImpromptu;
- boost::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(muc_->getJID(), jidsToInvite, mode));
- eventStream_->send(event);
+ RequestInviteToMUCUIEvent::ImpromptuMode mode = isImpromptu_ ? RequestInviteToMUCUIEvent::Impromptu : RequestInviteToMUCUIEvent::NotImpromptu;
+ boost::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(muc_->getJID(), jidsToInvite, mode));
+ eventStream_->send(event);
}
void MUCController::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- boost::shared_ptr<InviteToMUCUIEvent> inviteEvent = boost::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
- if (inviteEvent && inviteEvent->getRoom() == muc_->getJID()) {
- foreach (const JID& jid, inviteEvent->getInvites()) {
- muc_->invitePerson(jid, inviteEvent->getReason(), isImpromptu_);
- }
- }
+ boost::shared_ptr<InviteToMUCUIEvent> inviteEvent = boost::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
+ if (inviteEvent && inviteEvent->getRoom() == muc_->getJID()) {
+ foreach (const JID& 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);
+ 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) {
- if (change.first != MUCOccupant::NoAffiliation) {
- addedJIDs.insert(change.second);
- }
- }
- foreach (const AffiliationChangePair& change, changes) {
- if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) {
- muc_->changeAffiliation(change.second, change.first);
- }
- }
+ std::set<JID> addedJIDs;
+ foreach (const AffiliationChangePair& change, changes) {
+ if (change.first != MUCOccupant::NoAffiliation) {
+ addedJIDs.insert(change.second);
+ }
+ }
+ foreach (const AffiliationChangePair& change, changes) {
+ if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) {
+ muc_->changeAffiliation(change.second, change.first);
+ }
+ }
}
void MUCController::handleUnblockUserRequest() {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID()));
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID()));
}
void MUCController::handleBlockingStateChanged() {
- boost::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);
- }
- }
+ boost::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);
+ 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);
- }
+ // log only incoming messages
+ if (isIncoming && historyController_) {
+ historyController_->addMessage(message, fromJID, toJID, HistoryMessage::Groupchat, timeStamp);
+ }
}
void MUCController::addRecentLogs() {
- if (!historyController_) {
- return;
- }
+ if (!historyController_) {
+ return;
+ }
- joinContext_ = historyController_->getMUCContext(selfJID_, toJID_, lastActivity_);
+ joinContext_ = historyController_->getMUCContext(selfJID_, toJID_, lastActivity_);
- foreach (const HistoryMessage& message, joinContext_) {
- bool senderIsSelf = nick_ == message.getFromJID().getResource();
+ foreach (const HistoryMessage& message, joinContext_) {
+ bool senderIsSelf = nick_ == message.getFromJID().getResource();
- // the chatWindow uses utc timestamps
- addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, boost::shared_ptr<SecurityLabel>(new SecurityLabel()), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset()));
- }
+ // the chatWindow uses utc timestamps
+ addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, boost::shared_ptr<SecurityLabel>(new SecurityLabel()), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset()));
+ }
}
void MUCController::checkDuplicates(boost::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_) {
- 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("");
- }
+ 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_) {
+ 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_);
+ nick_ = nick;
+ highlighter_->setNick(nick_);
}
Form::ref MUCController::buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm) {
- Form::ref result = boost::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 (boost::shared_ptr<FormField> field, roomConfigurationForm->getFields()) {
- boost::shared_ptr<FormField> resultField;
- if (field->getName() == "muc#roomconfig_enablelogging") {
- resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
- }
- if (field->getName() == "muc#roomconfig_persistentroom") {
- resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
- }
- if (field->getName() == "muc#roomconfig_publicroom") {
- resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
- }
- if (field->getName() == "muc#roomconfig_whois") {
- resultField = boost::make_shared<FormField>(FormField::ListSingleType, "anyone");
- }
-
- if (field->getName() == "FORM_TYPE") {
- resultField = boost::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) {
- 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;
+ Form::ref result = boost::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 (boost::shared_ptr<FormField> field, roomConfigurationForm->getFields()) {
+ boost::shared_ptr<FormField> resultField;
+ if (field->getName() == "muc#roomconfig_enablelogging") {
+ resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_persistentroom") {
+ resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_publicroom") {
+ resultField = boost::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_whois") {
+ resultField = boost::make_shared<FormField>(FormField::ListSingleType, "anyone");
+ }
+
+ if (field->getName() == "FORM_TYPE") {
+ resultField = boost::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) {
+ 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) {
- if (pair.first != nick_) {
- title += (title.empty() ? "" : ", ") + pair.first;
- }
- }
- }
- chatWindow_->setName(title);
+ 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) {
+ 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();
- }
- }
+ // 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(boost::shared_ptr<DiscoInfo> info) {
- ChatControllerBase::setAvailableServerFeatures(info);
- if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ ChatControllerBase::setAvailableServerFeatures(info);
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
+ boost::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));
+ 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();
- }
+ handleBlockingStateChanged();
+ }
}
void MUCController::handleMUCBookmarkAdded(const MUCBookmark& bookmark) {
- if (bookmark.getRoom() == muc_->getJID()) {
- updateChatWindowBookmarkStatus(bookmark);
- }
+ if (bookmark.getRoom() == muc_->getJID()) {
+ updateChatWindowBookmarkStatus(bookmark);
+ }
}
void MUCController::handleMUCBookmarkRemoved(const MUCBookmark& bookmark) {
- if (bookmark.getRoom() == muc_->getJID()) {
- updateChatWindowBookmarkStatus(boost::optional<MUCBookmark>());
- }
+ if (bookmark.getRoom() == muc_->getJID()) {
+ updateChatWindowBookmarkStatus(boost::optional<MUCBookmark>());
+ }
}
void MUCController::updateChatWindowBookmarkStatus(const boost::optional<MUCBookmark>& bookmark) {
- assert(chatWindow_);
- if (bookmark) {
- if (bookmark->getAutojoin()) {
- chatWindow_->setBookmarkState(ChatWindow::RoomAutoJoined);
- }
- else {
- chatWindow_->setBookmarkState(ChatWindow::RoomBookmarked);
- }
- }
- else {
- chatWindow_->setBookmarkState(ChatWindow::RoomNotBookmarked);
- }
+ assert(chatWindow_);
+ if (bookmark) {
+ if (bookmark->getAutojoin()) {
+ chatWindow_->setBookmarkState(ChatWindow::RoomAutoJoined);
+ }
+ else {
+ chatWindow_->setBookmarkState(ChatWindow::RoomBookmarked);
+ }
+ }
+ else {
+ chatWindow_->setBookmarkState(ChatWindow::RoomNotBookmarked);
+ }
}
}
diff --git a/Swift/Controllers/Chat/MUCController.h b/Swift/Controllers/Chat/MUCController.h
index 0fb739a..3a61952 100644
--- a/Swift/Controllers/Chat/MUCController.h
+++ b/Swift/Controllers/Chat/MUCController.h
@@ -27,159 +27,159 @@
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
namespace Swift {
- class StanzaChannel;
- class IQRouter;
- class ChatWindowFactory;
- class Roster;
- class AvatarManager;
- class UIEventStream;
- class TimerFactory;
- class TabComplete;
- class XMPPRoster;
- class HighlightManager;
- class UIEvent;
- class VCardManager;
- class RosterVCardProvider;
- class ClientBlockListManager;
- class MUCBookmarkManager;
- class MUCBookmark;
-
- enum JoinPart {Join, Part, JoinThenPart, PartThenJoin};
-
- struct NickJoinPart {
- NickJoinPart(const std::string& nick, JoinPart type) : nick(nick), type(type) {}
- std::string nick;
- JoinPart type;
- };
-
- class MUCController : public ChatControllerBase {
- public:
- MUCController(const JID& self, MUC::ref muc, const boost::optional<std::string>& password, const std::string &nick, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, PresenceOracle* presenceOracle, AvatarManager* avatarManager, UIEventStream* events, bool useDelayForLatency, TimerFactory* timerFactory, EventController* eventController, EntityCapsProvider* entityCapsProvider, XMPPRoster* roster, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, bool isImpromptu, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, VCardManager* vcardManager, MUCBookmarkManager* mucBookmarkManager);
- virtual ~MUCController();
- boost::signal<void ()> onUserLeft;
- boost::signal<void ()> onUserJoined;
- boost::signal<void ()> onImpromptuConfigCompleted;
- boost::signal<void (const std::string&, const std::string& )> onUserNicknameChanged;
- virtual void setOnline(bool online) SWIFTEN_OVERRIDE;
- virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) SWIFTEN_OVERRIDE;
- void rejoin();
- static void appendToJoinParts(std::vector<NickJoinPart>& joinParts, const NickJoinPart& newEvent);
- static std::string generateJoinPartString(const std::vector<NickJoinPart>& joinParts, bool isImpromptu);
- static std::string concatenateListOfNames(const std::vector<NickJoinPart>& joinParts);
- static std::string generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname);
- bool isJoined();
- const std::string& getNick();
- const boost::optional<std::string> getPassword() const;
- bool isImpromptu() const;
- std::map<std::string, JID> getParticipantJIDs() const;
- void sendInvites(const std::vector<JID>& jids, const std::string& reason) const;
-
- protected:
- virtual void preSendMessageRequest(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
- virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
- virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
- virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
- virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message> message) const SWIFTEN_OVERRIDE;
- virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent>) SWIFTEN_OVERRIDE;
- virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE;
- virtual void cancelReplaces() SWIFTEN_OVERRIDE;
- virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE;
-
- private:
- void setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role);
- void clearPresenceQueue();
- void addPresenceMessage(const std::string& message);
- void handleWindowOccupantSelectionChanged(ContactRosterItem* item);
- void handleActionRequestedOnOccupant(ChatWindow::OccupantAction, ContactRosterItem* item);
- void handleWindowClosed();
- void handleAvatarChanged(const JID& jid);
- void handleOccupantJoined(const MUCOccupant& occupant);
- void handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname);
- void handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason);
- void handleOccupantPresenceChange(boost::shared_ptr<Presence> presence);
- void handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant,const MUCOccupant::Role& oldRole);
- void handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation,const MUCOccupant::Affiliation& oldAffiliation);
- void handleJoinComplete(const std::string& nick);
- void handleJoinFailed(boost::shared_ptr<ErrorPayload> error);
- void handleJoinTimeoutTick();
- void handleChangeSubjectRequest(const std::string&);
- void handleBookmarkRequest();
- std::string roleToGroupName(MUCOccupant::Role role);
- std::string roleToSortName(MUCOccupant::Role role);
- JID nickToJID(const std::string& nick);
- std::string roleToFriendlyName(MUCOccupant::Role role);
- void receivedActivity();
- bool messageTargetsMe(boost::shared_ptr<Message> message);
- void updateJoinParts();
- bool shouldUpdateJoinParts();
- virtual void dayTicked() SWIFTEN_OVERRIDE { clearPresenceQueue(); }
- void processUserPart();
- virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE;
- void handleConfigureRequest(Form::ref);
- void handleConfigurationFailed(ErrorPayload::ref);
- void handleConfigurationFormReceived(Form::ref);
- void handleDestroyRoomRequest();
- void handleInvitePersonToThisMUCRequest(const std::vector<JID>& jidsToInvite);
- void handleConfigurationCancelled();
- void handleOccupantRoleChangeFailed(ErrorPayload::ref, const JID&, MUCOccupant::Role);
- void handleGetAffiliationsRequest();
- void handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids);
- void handleChangeAffiliationsRequest(const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes);
- void handleInviteToMUCWindowDismissed();
- void handleInviteToMUCWindowCompleted();
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void addRecentLogs();
- void checkDuplicates(boost::shared_ptr<Message> newMessage);
- void setNick(const std::string& nick);
- void setImpromptuWindowTitle();
- void handleRoomUnlocked();
- void configureAsImpromptuRoom(Form::ref form);
- Form::ref buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm);
-
- void handleUnblockUserRequest();
- void handleBlockingStateChanged();
-
- void handleMUCBookmarkAdded(const MUCBookmark& bookmark);
- void handleMUCBookmarkRemoved(const MUCBookmark& bookmark);
- void updateChatWindowBookmarkStatus(const boost::optional<MUCBookmark>& bookmark);
-
- private:
- MUC::ref muc_;
- UIEventStream* events_;
- std::string nick_;
- std::string desiredNick_;
- Roster* roster_;
- TabComplete* completer_;
- bool parting_;
- bool joined_;
- bool lastWasPresence_;
- bool shouldJoinOnReconnect_;
- bool doneGettingHistory_;
- boost::bsignals::scoped_connection avatarChangedConnection_;
- boost::shared_ptr<Timer> loginCheckTimer_;
- std::set<std::string> currentOccupants_;
- std::vector<NickJoinPart> joinParts_;
- boost::posix_time::ptime lastActivity_;
- boost::optional<std::string> password_;
- XMPPRoster* xmppRoster_;
- std::vector<HistoryMessage> joinContext_;
- size_t renameCounter_;
- bool isImpromptu_;
- bool isImpromptuAlreadyConfigured_;
- RosterVCardProvider* rosterVCardProvider_;
- std::string lastJoinMessageUID_;
-
- ClientBlockListManager* clientBlockListManager_;
- boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
- boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
- boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
-
- boost::optional<ChatWindow::AlertID> blockedContactAlert_;
-
- MUCBookmarkManager* mucBookmarkManager_;
- boost::bsignals::scoped_connection mucBookmarkManagerBookmarkAddedConnection_;
- boost::bsignals::scoped_connection mucBookmarkManagerBookmarkRemovedConnection_;
- };
+ class StanzaChannel;
+ class IQRouter;
+ class ChatWindowFactory;
+ class Roster;
+ class AvatarManager;
+ class UIEventStream;
+ class TimerFactory;
+ class TabComplete;
+ class XMPPRoster;
+ class HighlightManager;
+ class UIEvent;
+ class VCardManager;
+ class RosterVCardProvider;
+ class ClientBlockListManager;
+ class MUCBookmarkManager;
+ class MUCBookmark;
+
+ enum JoinPart {Join, Part, JoinThenPart, PartThenJoin};
+
+ struct NickJoinPart {
+ NickJoinPart(const std::string& nick, JoinPart type) : nick(nick), type(type) {}
+ std::string nick;
+ JoinPart type;
+ };
+
+ class MUCController : public ChatControllerBase {
+ public:
+ MUCController(const JID& self, MUC::ref muc, const boost::optional<std::string>& password, const std::string &nick, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, PresenceOracle* presenceOracle, AvatarManager* avatarManager, UIEventStream* events, bool useDelayForLatency, TimerFactory* timerFactory, EventController* eventController, EntityCapsProvider* entityCapsProvider, XMPPRoster* roster, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr<ChatMessageParser> chatMessageParser, bool isImpromptu, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, VCardManager* vcardManager, MUCBookmarkManager* mucBookmarkManager);
+ virtual ~MUCController();
+ boost::signal<void ()> onUserLeft;
+ boost::signal<void ()> onUserJoined;
+ boost::signal<void ()> onImpromptuConfigCompleted;
+ boost::signal<void (const std::string&, const std::string& )> onUserNicknameChanged;
+ virtual void setOnline(bool online) SWIFTEN_OVERRIDE;
+ virtual void setAvailableServerFeatures(boost::shared_ptr<DiscoInfo> info) SWIFTEN_OVERRIDE;
+ void rejoin();
+ static void appendToJoinParts(std::vector<NickJoinPart>& joinParts, const NickJoinPart& newEvent);
+ static std::string generateJoinPartString(const std::vector<NickJoinPart>& joinParts, bool isImpromptu);
+ static std::string concatenateListOfNames(const std::vector<NickJoinPart>& joinParts);
+ static std::string generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname);
+ bool isJoined();
+ const std::string& getNick();
+ const boost::optional<std::string> getPassword() const;
+ bool isImpromptu() const;
+ std::map<std::string, JID> getParticipantJIDs() const;
+ void sendInvites(const std::vector<JID>& jids, const std::string& reason) const;
+
+ protected:
+ virtual void preSendMessageRequest(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
+ virtual bool isIncomingMessageFromMe(boost::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
+ virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
+ virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE;
+ virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(boost::shared_ptr<Message> message) const SWIFTEN_OVERRIDE;
+ virtual void preHandleIncomingMessage(boost::shared_ptr<MessageEvent>) SWIFTEN_OVERRIDE;
+ virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE;
+ virtual void cancelReplaces() SWIFTEN_OVERRIDE;
+ virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE;
+
+ private:
+ void setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role);
+ void clearPresenceQueue();
+ void addPresenceMessage(const std::string& message);
+ void handleWindowOccupantSelectionChanged(ContactRosterItem* item);
+ void handleActionRequestedOnOccupant(ChatWindow::OccupantAction, ContactRosterItem* item);
+ void handleWindowClosed();
+ void handleAvatarChanged(const JID& jid);
+ void handleOccupantJoined(const MUCOccupant& occupant);
+ void handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname);
+ void handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason);
+ void handleOccupantPresenceChange(boost::shared_ptr<Presence> presence);
+ void handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant,const MUCOccupant::Role& oldRole);
+ void handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation,const MUCOccupant::Affiliation& oldAffiliation);
+ void handleJoinComplete(const std::string& nick);
+ void handleJoinFailed(boost::shared_ptr<ErrorPayload> error);
+ void handleJoinTimeoutTick();
+ void handleChangeSubjectRequest(const std::string&);
+ void handleBookmarkRequest();
+ std::string roleToGroupName(MUCOccupant::Role role);
+ std::string roleToSortName(MUCOccupant::Role role);
+ JID nickToJID(const std::string& nick);
+ std::string roleToFriendlyName(MUCOccupant::Role role);
+ void receivedActivity();
+ bool messageTargetsMe(boost::shared_ptr<Message> message);
+ void updateJoinParts();
+ bool shouldUpdateJoinParts();
+ virtual void dayTicked() SWIFTEN_OVERRIDE { clearPresenceQueue(); }
+ void processUserPart();
+ virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE;
+ void handleConfigureRequest(Form::ref);
+ void handleConfigurationFailed(ErrorPayload::ref);
+ void handleConfigurationFormReceived(Form::ref);
+ void handleDestroyRoomRequest();
+ void handleInvitePersonToThisMUCRequest(const std::vector<JID>& jidsToInvite);
+ void handleConfigurationCancelled();
+ void handleOccupantRoleChangeFailed(ErrorPayload::ref, const JID&, MUCOccupant::Role);
+ void handleGetAffiliationsRequest();
+ void handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids);
+ void handleChangeAffiliationsRequest(const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes);
+ void handleInviteToMUCWindowDismissed();
+ void handleInviteToMUCWindowCompleted();
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void addRecentLogs();
+ void checkDuplicates(boost::shared_ptr<Message> newMessage);
+ void setNick(const std::string& nick);
+ void setImpromptuWindowTitle();
+ void handleRoomUnlocked();
+ void configureAsImpromptuRoom(Form::ref form);
+ Form::ref buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm);
+
+ void handleUnblockUserRequest();
+ void handleBlockingStateChanged();
+
+ void handleMUCBookmarkAdded(const MUCBookmark& bookmark);
+ void handleMUCBookmarkRemoved(const MUCBookmark& bookmark);
+ void updateChatWindowBookmarkStatus(const boost::optional<MUCBookmark>& bookmark);
+
+ private:
+ MUC::ref muc_;
+ UIEventStream* events_;
+ std::string nick_;
+ std::string desiredNick_;
+ Roster* roster_;
+ TabComplete* completer_;
+ bool parting_;
+ bool joined_;
+ bool lastWasPresence_;
+ bool shouldJoinOnReconnect_;
+ bool doneGettingHistory_;
+ boost::bsignals::scoped_connection avatarChangedConnection_;
+ boost::shared_ptr<Timer> loginCheckTimer_;
+ std::set<std::string> currentOccupants_;
+ std::vector<NickJoinPart> joinParts_;
+ boost::posix_time::ptime lastActivity_;
+ boost::optional<std::string> password_;
+ XMPPRoster* xmppRoster_;
+ std::vector<HistoryMessage> joinContext_;
+ size_t renameCounter_;
+ bool isImpromptu_;
+ bool isImpromptuAlreadyConfigured_;
+ RosterVCardProvider* rosterVCardProvider_;
+ std::string lastJoinMessageUID_;
+
+ ClientBlockListManager* clientBlockListManager_;
+ boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
+
+ boost::optional<ChatWindow::AlertID> blockedContactAlert_;
+
+ MUCBookmarkManager* mucBookmarkManager_;
+ boost::bsignals::scoped_connection mucBookmarkManagerBookmarkAddedConnection_;
+ boost::bsignals::scoped_connection mucBookmarkManagerBookmarkRemovedConnection_;
+ };
}
diff --git a/Swift/Controllers/Chat/MUCSearchController.cpp b/Swift/Controllers/Chat/MUCSearchController.cpp
index 702a366..884978c 100644
--- a/Swift/Controllers/Chat/MUCSearchController.cpp
+++ b/Swift/Controllers/Chat/MUCSearchController.cpp
@@ -26,159 +26,159 @@ namespace Swift {
static const std::string SEARCHED_SERVICES = "searchedServices";
MUCSearchController::MUCSearchController(const JID& jid, MUCSearchWindowFactory* factory, IQRouter* iqRouter, ProfileSettingsProvider* settings) : jid_(jid), factory_(factory), iqRouter_(iqRouter), settings_(settings), window_(NULL), walker_(NULL) {
- itemsInProgress_ = 0;
- loadSavedServices();
+ itemsInProgress_ = 0;
+ loadSavedServices();
}
MUCSearchController::~MUCSearchController() {
- delete walker_;
- delete window_;
+ delete walker_;
+ delete window_;
}
void MUCSearchController::openSearchWindow() {
- if (!window_) {
- window_ = factory_->createMUCSearchWindow();
- window_->onSearchService.connect(boost::bind(&MUCSearchController::handleSearchService, this, _1));
- window_->onFinished.connect(boost::bind(&MUCSearchController::handleMUCSearchFinished, this, _1));
- window_->addSavedServices(savedServices_);
- }
- handleSearchService(JID(jid_.getDomain()));
- window_->show();
+ if (!window_) {
+ window_ = factory_->createMUCSearchWindow();
+ window_->onSearchService.connect(boost::bind(&MUCSearchController::handleSearchService, this, _1));
+ window_->onFinished.connect(boost::bind(&MUCSearchController::handleMUCSearchFinished, this, _1));
+ window_->addSavedServices(savedServices_);
+ }
+ handleSearchService(JID(jid_.getDomain()));
+ window_->show();
}
void MUCSearchController::loadSavedServices() {
- savedServices_.clear();
- foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_SERVICES), '\n')) {
- savedServices_.push_back(JID(stringItem));
- }
+ savedServices_.clear();
+ foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_SERVICES), '\n')) {
+ savedServices_.push_back(JID(stringItem));
+ }
}
void MUCSearchController::addToSavedServices(const JID& jid) {
- savedServices_.erase(std::remove(savedServices_.begin(), savedServices_.end(), jid), savedServices_.end());
- savedServices_.push_front(jid);
-
- std::string collapsed;
- int i = 0;
- foreach (JID jidItem, savedServices_) {
- if (i >= 15) {
- break;
- }
- if (!collapsed.empty()) {
- collapsed += "\n";
- }
- collapsed += jidItem.toString();
- ++i;
- }
- settings_->storeString(SEARCHED_SERVICES, collapsed);
- window_->addSavedServices(savedServices_);
+ savedServices_.erase(std::remove(savedServices_.begin(), savedServices_.end(), jid), savedServices_.end());
+ savedServices_.push_front(jid);
+
+ std::string collapsed;
+ int i = 0;
+ foreach (JID jidItem, savedServices_) {
+ if (i >= 15) {
+ break;
+ }
+ if (!collapsed.empty()) {
+ collapsed += "\n";
+ }
+ collapsed += jidItem.toString();
+ ++i;
+ }
+ settings_->storeString(SEARCHED_SERVICES, collapsed);
+ window_->addSavedServices(savedServices_);
}
void MUCSearchController::handleSearchService(const JID& jid) {
- if (!jid.isValid()) {
- //Set Window to say error this isn't valid
- return;
- }
- addToSavedServices(jid);
-
- services_.clear();
- serviceDetails_.clear();
-
- window_->setSearchInProgress(true);
- refreshView();
-
- if (walker_) {
- walker_->endWalk();
- walker_->onServiceFound.disconnect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2));
- walker_->onWalkComplete.disconnect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this));
- delete walker_;
- }
-
- SWIFT_LOG(debug) << "Starting walking MUC services" << std::endl;
- itemsInProgress_ = 0;
- walker_ = new DiscoServiceWalker(jid, iqRouter_);
- walker_->onServiceFound.connect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2));
- walker_->onWalkComplete.connect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this));
- walker_->beginWalk();
+ if (!jid.isValid()) {
+ //Set Window to say error this isn't valid
+ return;
+ }
+ addToSavedServices(jid);
+
+ services_.clear();
+ serviceDetails_.clear();
+
+ window_->setSearchInProgress(true);
+ refreshView();
+
+ if (walker_) {
+ walker_->endWalk();
+ walker_->onServiceFound.disconnect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2));
+ walker_->onWalkComplete.disconnect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this));
+ delete walker_;
+ }
+
+ SWIFT_LOG(debug) << "Starting walking MUC services" << std::endl;
+ itemsInProgress_ = 0;
+ walker_ = new DiscoServiceWalker(jid, iqRouter_);
+ walker_->onServiceFound.connect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2));
+ walker_->onWalkComplete.connect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this));
+ walker_->beginWalk();
}
void MUCSearchController::handleDiscoServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> info) {
- bool isMUC = false;
- std::string name;
- foreach (DiscoInfo::Identity identity, info->getIdentities()) {
- if ((identity.getCategory() == "directory"
- && identity.getType() == "chatroom")
- || (identity.getCategory() == "conference"
- && identity.getType() == "text")) {
- isMUC = true;
- name = identity.getName();
- }
- }
- if (isMUC) {
- SWIFT_LOG(debug) << "MUC Service found: " << jid << std::endl;
- services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end());
- services_.push_back(jid);
- serviceDetails_[jid].setName(name);
- serviceDetails_[jid].setJID(jid);
- serviceDetails_[jid].setComplete(false);
- itemsInProgress_++;
- SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
- GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(jid, iqRouter_);
- discoItemsRequest->onResponse.connect(boost::bind(&MUCSearchController::handleRoomsItemsResponse, this, _1, _2, jid));
- discoItemsRequest->send();
- }
- else {
- removeService(jid);
- }
- refreshView();
+ bool isMUC = false;
+ std::string name;
+ foreach (DiscoInfo::Identity identity, info->getIdentities()) {
+ if ((identity.getCategory() == "directory"
+ && identity.getType() == "chatroom")
+ || (identity.getCategory() == "conference"
+ && identity.getType() == "text")) {
+ isMUC = true;
+ name = identity.getName();
+ }
+ }
+ if (isMUC) {
+ SWIFT_LOG(debug) << "MUC Service found: " << jid << std::endl;
+ services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end());
+ services_.push_back(jid);
+ serviceDetails_[jid].setName(name);
+ serviceDetails_[jid].setJID(jid);
+ serviceDetails_[jid].setComplete(false);
+ itemsInProgress_++;
+ SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
+ GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(jid, iqRouter_);
+ discoItemsRequest->onResponse.connect(boost::bind(&MUCSearchController::handleRoomsItemsResponse, this, _1, _2, jid));
+ discoItemsRequest->send();
+ }
+ else {
+ removeService(jid);
+ }
+ refreshView();
}
void MUCSearchController::handleDiscoWalkFinished() {
- SWIFT_LOG(debug) << "MUC Walk finished" << std::endl;
- updateInProgressness();
+ SWIFT_LOG(debug) << "MUC Walk finished" << std::endl;
+ updateInProgressness();
}
void MUCSearchController::removeService(const JID& jid) {
- serviceDetails_.erase(jid);
- services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end());
- refreshView();
+ serviceDetails_.erase(jid);
+ services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end());
+ refreshView();
}
void MUCSearchController::handleRoomsItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, const JID& jid) {
- itemsInProgress_--;
- SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
- updateInProgressness();
- if (error) {
- handleDiscoError(jid, error);
- return;
- }
- serviceDetails_[jid].clearRooms();
- foreach (DiscoItems::Item item, items->getItems()) {
- serviceDetails_[jid].addRoom(MUCService::MUCRoom(item.getJID().getNode(), item.getName(), -1));
- }
- serviceDetails_[jid].setComplete(true);
- refreshView();
+ itemsInProgress_--;
+ SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
+ updateInProgressness();
+ if (error) {
+ handleDiscoError(jid, error);
+ return;
+ }
+ serviceDetails_[jid].clearRooms();
+ foreach (DiscoItems::Item item, items->getItems()) {
+ serviceDetails_[jid].addRoom(MUCService::MUCRoom(item.getJID().getNode(), item.getName(), -1));
+ }
+ serviceDetails_[jid].setComplete(true);
+ refreshView();
}
void MUCSearchController::handleDiscoError(const JID& jid, ErrorPayload::ref error) {
- serviceDetails_[jid].setComplete(true);
- serviceDetails_[jid].setError(error->getText());
+ serviceDetails_[jid].setComplete(true);
+ serviceDetails_[jid].setError(error->getText());
}
void MUCSearchController::refreshView() {
- window_->clearList();
- foreach (JID jid, services_) {
- window_->addService(serviceDetails_[jid]);
- }
+ window_->clearList();
+ foreach (JID jid, services_) {
+ window_->addService(serviceDetails_[jid]);
+ }
}
void MUCSearchController::updateInProgressness() {
- window_->setSearchInProgress((walker_ && walker_->isActive()) || itemsInProgress_ > 0);
+ window_->setSearchInProgress((walker_ && walker_->isActive()) || itemsInProgress_ > 0);
}
void MUCSearchController::handleMUCSearchFinished(const boost::optional<JID>& result) {
- if (result) {
- onMUCSelected(*result);
- }
+ if (result) {
+ onMUCSelected(*result);
+ }
}
}
diff --git a/Swift/Controllers/Chat/MUCSearchController.h b/Swift/Controllers/Chat/MUCSearchController.h
index 01bcf74..3d2a2ca 100644
--- a/Swift/Controllers/Chat/MUCSearchController.h
+++ b/Swift/Controllers/Chat/MUCSearchController.h
@@ -22,103 +22,103 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class UIEventStream;
- class MUCSearchWindow;
- class MUCSearchWindowFactory;
- class IQRouter;
- class DiscoServiceWalker;
- class NickResolver;
-
- class MUCService {
- public:
- class MUCRoom {
- public:
- MUCRoom(const std::string& node, const std::string& name, int occupants) : node_(node), name_(name), occupants_(occupants) {}
- std::string getNode() {return node_;}
- std::string getName() {return name_;}
- int getOccupantCount() {return occupants_;}
- private:
- std::string node_;
- std::string name_;
- int occupants_;
- };
-
- MUCService() {error_ = false; complete_ = false;}
-
- void setComplete(bool complete) {
- complete_ = complete;
- }
-
- void setName(const std::string& name) {
- name_ = name;
- }
-
- void setJID(const JID& jid) {
- jid_ = jid;
- }
-
- bool getComplete() const {
- return complete_;
- }
-
- JID getJID() const {
- return jid_;
- }
-
- std::string getName() const {
- return name_;
- }
-
- void setError(const std::string& errorText) {error_ = true; errorText_ = errorText;}
-
- void clearRooms() {rooms_.clear();}
-
- void addRoom(const MUCRoom& room) {rooms_.push_back(room);}
-
- std::vector<MUCRoom> getRooms() const {return rooms_;}
- private:
- std::string name_;
- JID jid_;
- std::vector<MUCRoom> rooms_;
- bool complete_;
- bool error_;
- std::string errorText_;
- };
-
- class MUCSearchController {
- public:
- MUCSearchController(const JID& jid, MUCSearchWindowFactory* mucSearchWindowFactory, IQRouter* iqRouter, ProfileSettingsProvider* settings);
- ~MUCSearchController();
-
- void openSearchWindow();
-
- public:
- boost::signal<void (const JID&)> onMUCSelected;
-
- private:
- void handleSearchService(const JID& jid);
- void handleRoomsItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, const JID& jid);
- void handleDiscoError(const JID& jid, ErrorPayload::ref error);
- void handleDiscoServiceFound(const JID&, boost::shared_ptr<DiscoInfo>);
- void handleDiscoWalkFinished();
- void handleMUCSearchFinished(const boost::optional<JID>& result);
- void removeService(const JID& jid);
- void refreshView();
- void loadSavedServices();
- void addToSavedServices(const JID& jid);
- void updateInProgressness();
-
- private:
- JID jid_;
- MUCSearchWindowFactory* factory_;
- IQRouter* iqRouter_;
- ProfileSettingsProvider* settings_;
- MUCSearchWindow* window_;
- DiscoServiceWalker* walker_;
- std::list<JID> services_;
- std::list<JID> savedServices_;
- std::map<JID, MUCService> serviceDetails_;
- std::vector<DiscoServiceWalker*> walksInProgress_;
- int itemsInProgress_;
- };
+ class UIEventStream;
+ class MUCSearchWindow;
+ class MUCSearchWindowFactory;
+ class IQRouter;
+ class DiscoServiceWalker;
+ class NickResolver;
+
+ class MUCService {
+ public:
+ class MUCRoom {
+ public:
+ MUCRoom(const std::string& node, const std::string& name, int occupants) : node_(node), name_(name), occupants_(occupants) {}
+ std::string getNode() {return node_;}
+ std::string getName() {return name_;}
+ int getOccupantCount() {return occupants_;}
+ private:
+ std::string node_;
+ std::string name_;
+ int occupants_;
+ };
+
+ MUCService() {error_ = false; complete_ = false;}
+
+ void setComplete(bool complete) {
+ complete_ = complete;
+ }
+
+ void setName(const std::string& name) {
+ name_ = name;
+ }
+
+ void setJID(const JID& jid) {
+ jid_ = jid;
+ }
+
+ bool getComplete() const {
+ return complete_;
+ }
+
+ JID getJID() const {
+ return jid_;
+ }
+
+ std::string getName() const {
+ return name_;
+ }
+
+ void setError(const std::string& errorText) {error_ = true; errorText_ = errorText;}
+
+ void clearRooms() {rooms_.clear();}
+
+ void addRoom(const MUCRoom& room) {rooms_.push_back(room);}
+
+ std::vector<MUCRoom> getRooms() const {return rooms_;}
+ private:
+ std::string name_;
+ JID jid_;
+ std::vector<MUCRoom> rooms_;
+ bool complete_;
+ bool error_;
+ std::string errorText_;
+ };
+
+ class MUCSearchController {
+ public:
+ MUCSearchController(const JID& jid, MUCSearchWindowFactory* mucSearchWindowFactory, IQRouter* iqRouter, ProfileSettingsProvider* settings);
+ ~MUCSearchController();
+
+ void openSearchWindow();
+
+ public:
+ boost::signal<void (const JID&)> onMUCSelected;
+
+ private:
+ void handleSearchService(const JID& jid);
+ void handleRoomsItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, const JID& jid);
+ void handleDiscoError(const JID& jid, ErrorPayload::ref error);
+ void handleDiscoServiceFound(const JID&, boost::shared_ptr<DiscoInfo>);
+ void handleDiscoWalkFinished();
+ void handleMUCSearchFinished(const boost::optional<JID>& result);
+ void removeService(const JID& jid);
+ void refreshView();
+ void loadSavedServices();
+ void addToSavedServices(const JID& jid);
+ void updateInProgressness();
+
+ private:
+ JID jid_;
+ MUCSearchWindowFactory* factory_;
+ IQRouter* iqRouter_;
+ ProfileSettingsProvider* settings_;
+ MUCSearchWindow* window_;
+ DiscoServiceWalker* walker_;
+ std::list<JID> services_;
+ std::list<JID> savedServices_;
+ std::map<JID, MUCService> serviceDetails_;
+ std::vector<DiscoServiceWalker*> walksInProgress_;
+ int itemsInProgress_;
+ };
}
diff --git a/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp
index 6748b9e..9ed8bf4 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp
@@ -13,269 +13,269 @@
using namespace Swift;
class ChatMessageParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ChatMessageParserTest);
- CPPUNIT_TEST(testFullBody);
- CPPUNIT_TEST(testOneEmoticon);
- CPPUNIT_TEST(testBareEmoticon);
- CPPUNIT_TEST(testHiddenEmoticon);
- CPPUNIT_TEST(testEndlineEmoticon);
- CPPUNIT_TEST(testBoundedEmoticons);
- CPPUNIT_TEST(testNoColourNoHighlight);
- CPPUNIT_TEST_SUITE_END();
-
+ CPPUNIT_TEST_SUITE(ChatMessageParserTest);
+ CPPUNIT_TEST(testFullBody);
+ CPPUNIT_TEST(testOneEmoticon);
+ CPPUNIT_TEST(testBareEmoticon);
+ CPPUNIT_TEST(testHiddenEmoticon);
+ CPPUNIT_TEST(testEndlineEmoticon);
+ CPPUNIT_TEST(testBoundedEmoticons);
+ CPPUNIT_TEST(testNoColourNoHighlight);
+ CPPUNIT_TEST_SUITE_END();
+
public:
- void setUp() {
- smile1_ = ":)";
- smile1Path_ = "/blah/smile1.png";
- smile2_ = ":(";
- smile2Path_ = "/blah/smile2.jpg";
- emoticons_[smile1_] = smile1Path_;
- emoticons_[smile2_] = smile2Path_;
- }
-
- void tearDown() {
- emoticons_.clear();
- }
-
- void assertText(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(result.getParts()[index]);
- CPPUNIT_ASSERT_EQUAL(text, part->text);
- }
-
- void assertEmoticon(const ChatWindow::ChatMessage& result, size_t index, const std::string& text, const std::string& path) {
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(result.getParts()[index]);
- CPPUNIT_ASSERT(!!part);
- CPPUNIT_ASSERT_EQUAL(text, part->alternativeText);
- CPPUNIT_ASSERT_EQUAL(path, part->imagePath);
- }
+ void setUp() {
+ smile1_ = ":)";
+ smile1Path_ = "/blah/smile1.png";
+ smile2_ = ":(";
+ smile2Path_ = "/blah/smile2.jpg";
+ emoticons_[smile1_] = smile1Path_;
+ emoticons_[smile2_] = smile2Path_;
+ }
+
+ void tearDown() {
+ emoticons_.clear();
+ }
+
+ void assertText(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(result.getParts()[index]);
+ CPPUNIT_ASSERT_EQUAL(text, part->text);
+ }
+
+ void assertEmoticon(const ChatWindow::ChatMessage& result, size_t index, const std::string& text, const std::string& path) {
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(result.getParts()[index]);
+ CPPUNIT_ASSERT(!!part);
+ CPPUNIT_ASSERT_EQUAL(text, part->alternativeText);
+ CPPUNIT_ASSERT_EQUAL(path, part->imagePath);
+ }
#define assertHighlight(RESULT, INDEX, TEXT, EXPECTED_HIGHLIGHT) \
- { \
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(RESULT.getParts()[INDEX]); \
- CPPUNIT_ASSERT_EQUAL(std::string(TEXT), part->text); \
- CPPUNIT_ASSERT(EXPECTED_HIGHLIGHT == part->action); \
- }
-
- void assertURL(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) {
- boost::shared_ptr<ChatWindow::ChatURIMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(result.getParts()[index]);
- CPPUNIT_ASSERT_EQUAL(text, part->target);
- }
-
- static HighlightRule ruleFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord)
- {
- HighlightRule rule;
- std::vector<std::string> keywords;
- keywords.push_back(keyword);
- rule.setKeywords(keywords);
- rule.setMatchCase(matchCase);
- rule.setMatchWholeWords(matchWholeWord);
- rule.setMatchChat(true);
- rule.getAction().setTextBackground("white");
- return rule;
- }
-
- static const HighlightRulesListPtr ruleListFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord)
- {
- boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
- list->addRule(ruleFromKeyword(keyword, matchCase, matchWholeWord));
- return list;
- }
-
- static const HighlightRulesListPtr ruleListFromKeywords(const HighlightRule &rule1, const HighlightRule &rule2)
- {
- boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
- list->addRule(rule1);
- list->addRule(rule2);
- return list;
- }
-
- static HighlightRulesListPtr ruleListWithNickHighlight(bool withHighlightColour = true)
- {
- HighlightRule rule;
- rule.setMatchChat(true);
- rule.setNickIsKeyword(true);
- rule.setMatchCase(true);
- rule.setMatchWholeWords(true);
- if (withHighlightColour) {
- rule.getAction().setTextBackground("white");
- }
- boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
- list->addRule(rule);
- return list;
- }
-
- void testFullBody() {
- const std::string no_special_message = "a message with no special content";
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody(no_special_message);
- assertText(result, 0, no_special_message);
-
- HighlightRulesListPtr highlightRuleList = ruleListFromKeyword("trigger", false, false);
- testling = ChatMessageParser(emoticons_, highlightRuleList);
- result = testling.parseMessageBody(":) shiny :( trigger :) http://wonderland.lit/blah http://denmark.lit boom boom");
- assertEmoticon(result, 0, smile1_, smile1Path_);
- assertText(result, 1, " shiny ");
- assertEmoticon(result, 2, smile2_, smile2Path_);
- assertText(result, 3, " ");
- assertHighlight(result, 4, "trigger", highlightRuleList->getRule(0).getAction());
- assertText(result, 5, " ");
- assertEmoticon(result, 6, smile1_, smile1Path_);
- assertText(result, 7, " ");
- assertURL(result, 8, "http://wonderland.lit/blah");
- assertText(result, 9, " ");
- assertURL(result, 10, "http://denmark.lit");
- assertText(result, 11, " boom boom");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
- result = testling.parseMessageBody("testtriggermessage");
- assertText(result, 0, "test");
- assertHighlight(result, 1, "trigger", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, "message");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, true));
- result = testling.parseMessageBody("testtriggermessage");
- assertText(result, 0, "testtriggermessage");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", true, false));
- result = testling.parseMessageBody("TrIgGeR");
- assertText(result, 0, "TrIgGeR");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
- result = testling.parseMessageBody("TrIgGeR");
- assertHighlight(result, 0, "TrIgGeR", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
- result = testling.parseMessageBody("partialTrIgGeRmatch");
- assertText(result, 0, "partial");
- assertHighlight(result, 1, "TrIgGeR", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, "match");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zero one two three");
- assertText(result, 0, "zero ");
- assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, " two ");
- assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zero oNe two tHrEe");
- assertText(result, 0, "zero ");
- assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, " two ");
- assertHighlight(result, 3, "tHrEe", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", true, false)));
- result = testling.parseMessageBody("zero oNe two tHrEe");
- assertText(result, 0, "zero ");
- assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, " two tHrEe");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", true, false)));
- result = testling.parseMessageBody("zero oNe two tHrEe");
- assertText(result, 0, "zero oNe two tHrEe");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zeroonetwothree");
- assertText(result, 0, "zero");
- assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, "two");
- assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zeroOnEtwoThReE");
- assertText(result, 0, "zeroOnEtwo");
- assertHighlight(result, 1, "ThReE", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zeroonetwothree");
- assertText(result, 0, "zeroonetwo");
- assertHighlight(result, 1, "three", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, true)));
- result = testling.parseMessageBody("zeroonetwothree");
- assertText(result, 0, "zeroonetwothree");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Alice", "Alice");
- assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction());
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("TextAliceText", "Alice");
- assertText(result, 0, "TextAliceText");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Text Alice Text", "Alice");
- assertText(result, 0, "Text ");
- assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction());
- assertText(result, 2, " Text");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Alice Text", "Alice");
- assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction());
- assertText(result, 1, " Text");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Text Alice", "Alice");
- assertText(result, 0, "Text ");
- assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction());
- }
-
- void testOneEmoticon() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody(" :) ");
- assertText(result, 0, " ");
- assertEmoticon(result, 1, smile1_, smile1Path_);
- assertText(result, 2, " ");
- }
-
-
- void testBareEmoticon() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody(":)");
- assertEmoticon(result, 0, smile1_, smile1Path_);
- }
-
- void testHiddenEmoticon() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody("b:)a");
- assertText(result, 0, "b:)a");
- }
-
- void testEndlineEmoticon() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody("Lazy:)");
- assertText(result, 0, "Lazy");
- assertEmoticon(result, 1, smile1_, smile1Path_);
- }
-
- void testBoundedEmoticons() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody(":)Lazy:(");
- assertEmoticon(result, 0, smile1_, smile1Path_);
- assertText(result, 1, "Lazy");
- assertEmoticon(result, 2, smile2_, smile2Path_);
- }
-
- void testEmoticonParenthesis() {
- ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
- ChatWindow::ChatMessage result = testling.parseMessageBody("(Like this :))");
- assertText(result, 0, "(Like this ");
- assertEmoticon(result, 1, smile1_, smile1Path_);
- assertText(result, 2, ")");
- }
-
- void testNoColourNoHighlight() {
- ChatMessageParser testling(emoticons_, ruleListWithNickHighlight(false));
- ChatWindow::ChatMessage result = testling.parseMessageBody("Alice", "Alice");
- assertText(result, 0, "Alice");
- }
+ { \
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(RESULT.getParts()[INDEX]); \
+ CPPUNIT_ASSERT_EQUAL(std::string(TEXT), part->text); \
+ CPPUNIT_ASSERT(EXPECTED_HIGHLIGHT == part->action); \
+ }
+
+ void assertURL(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) {
+ boost::shared_ptr<ChatWindow::ChatURIMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(result.getParts()[index]);
+ CPPUNIT_ASSERT_EQUAL(text, part->target);
+ }
+
+ static HighlightRule ruleFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord)
+ {
+ HighlightRule rule;
+ std::vector<std::string> keywords;
+ keywords.push_back(keyword);
+ rule.setKeywords(keywords);
+ rule.setMatchCase(matchCase);
+ rule.setMatchWholeWords(matchWholeWord);
+ rule.setMatchChat(true);
+ rule.getAction().setTextBackground("white");
+ return rule;
+ }
+
+ static const HighlightRulesListPtr ruleListFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord)
+ {
+ boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
+ list->addRule(ruleFromKeyword(keyword, matchCase, matchWholeWord));
+ return list;
+ }
+
+ static const HighlightRulesListPtr ruleListFromKeywords(const HighlightRule &rule1, const HighlightRule &rule2)
+ {
+ boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
+ list->addRule(rule1);
+ list->addRule(rule2);
+ return list;
+ }
+
+ static HighlightRulesListPtr ruleListWithNickHighlight(bool withHighlightColour = true)
+ {
+ HighlightRule rule;
+ rule.setMatchChat(true);
+ rule.setNickIsKeyword(true);
+ rule.setMatchCase(true);
+ rule.setMatchWholeWords(true);
+ if (withHighlightColour) {
+ rule.getAction().setTextBackground("white");
+ }
+ boost::shared_ptr<HighlightManager::HighlightRulesList> list = boost::make_shared<HighlightManager::HighlightRulesList>();
+ list->addRule(rule);
+ return list;
+ }
+
+ void testFullBody() {
+ const std::string no_special_message = "a message with no special content";
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody(no_special_message);
+ assertText(result, 0, no_special_message);
+
+ HighlightRulesListPtr highlightRuleList = ruleListFromKeyword("trigger", false, false);
+ testling = ChatMessageParser(emoticons_, highlightRuleList);
+ result = testling.parseMessageBody(":) shiny :( trigger :) http://wonderland.lit/blah http://denmark.lit boom boom");
+ assertEmoticon(result, 0, smile1_, smile1Path_);
+ assertText(result, 1, " shiny ");
+ assertEmoticon(result, 2, smile2_, smile2Path_);
+ assertText(result, 3, " ");
+ assertHighlight(result, 4, "trigger", highlightRuleList->getRule(0).getAction());
+ assertText(result, 5, " ");
+ assertEmoticon(result, 6, smile1_, smile1Path_);
+ assertText(result, 7, " ");
+ assertURL(result, 8, "http://wonderland.lit/blah");
+ assertText(result, 9, " ");
+ assertURL(result, 10, "http://denmark.lit");
+ assertText(result, 11, " boom boom");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
+ result = testling.parseMessageBody("testtriggermessage");
+ assertText(result, 0, "test");
+ assertHighlight(result, 1, "trigger", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, "message");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, true));
+ result = testling.parseMessageBody("testtriggermessage");
+ assertText(result, 0, "testtriggermessage");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", true, false));
+ result = testling.parseMessageBody("TrIgGeR");
+ assertText(result, 0, "TrIgGeR");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
+ result = testling.parseMessageBody("TrIgGeR");
+ assertHighlight(result, 0, "TrIgGeR", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
+ result = testling.parseMessageBody("partialTrIgGeRmatch");
+ assertText(result, 0, "partial");
+ assertHighlight(result, 1, "TrIgGeR", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, "match");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
+ result = testling.parseMessageBody("zero one two three");
+ assertText(result, 0, "zero ");
+ assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, " two ");
+ assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
+ result = testling.parseMessageBody("zero oNe two tHrEe");
+ assertText(result, 0, "zero ");
+ assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, " two ");
+ assertHighlight(result, 3, "tHrEe", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", true, false)));
+ result = testling.parseMessageBody("zero oNe two tHrEe");
+ assertText(result, 0, "zero ");
+ assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, " two tHrEe");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", true, false)));
+ result = testling.parseMessageBody("zero oNe two tHrEe");
+ assertText(result, 0, "zero oNe two tHrEe");
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false)));
+ result = testling.parseMessageBody("zeroonetwothree");
+ assertText(result, 0, "zero");
+ assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, "two");
+ assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", false, false)));
+ result = testling.parseMessageBody("zeroOnEtwoThReE");
+ assertText(result, 0, "zeroOnEtwo");
+ assertHighlight(result, 1, "ThReE", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, false)));
+ result = testling.parseMessageBody("zeroonetwothree");
+ assertText(result, 0, "zeroonetwo");
+ assertHighlight(result, 1, "three", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, true)));
+ result = testling.parseMessageBody("zeroonetwothree");
+ assertText(result, 0, "zeroonetwothree");
+
+ testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
+ result = testling.parseMessageBody("Alice", "Alice");
+ assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction());
+
+ testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
+ result = testling.parseMessageBody("TextAliceText", "Alice");
+ assertText(result, 0, "TextAliceText");
+
+ testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
+ result = testling.parseMessageBody("Text Alice Text", "Alice");
+ assertText(result, 0, "Text ");
+ assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction());
+ assertText(result, 2, " Text");
+
+ testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
+ result = testling.parseMessageBody("Alice Text", "Alice");
+ assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction());
+ assertText(result, 1, " Text");
+
+ testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
+ result = testling.parseMessageBody("Text Alice", "Alice");
+ assertText(result, 0, "Text ");
+ assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction());
+ }
+
+ void testOneEmoticon() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody(" :) ");
+ assertText(result, 0, " ");
+ assertEmoticon(result, 1, smile1_, smile1Path_);
+ assertText(result, 2, " ");
+ }
+
+
+ void testBareEmoticon() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody(":)");
+ assertEmoticon(result, 0, smile1_, smile1Path_);
+ }
+
+ void testHiddenEmoticon() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody("b:)a");
+ assertText(result, 0, "b:)a");
+ }
+
+ void testEndlineEmoticon() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody("Lazy:)");
+ assertText(result, 0, "Lazy");
+ assertEmoticon(result, 1, smile1_, smile1Path_);
+ }
+
+ void testBoundedEmoticons() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody(":)Lazy:(");
+ assertEmoticon(result, 0, smile1_, smile1Path_);
+ assertText(result, 1, "Lazy");
+ assertEmoticon(result, 2, smile2_, smile2Path_);
+ }
+
+ void testEmoticonParenthesis() {
+ ChatMessageParser testling(emoticons_, boost::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody("(Like this :))");
+ assertText(result, 0, "(Like this ");
+ assertEmoticon(result, 1, smile1_, smile1Path_);
+ assertText(result, 2, ")");
+ }
+
+ void testNoColourNoHighlight() {
+ ChatMessageParser testling(emoticons_, ruleListWithNickHighlight(false));
+ ChatWindow::ChatMessage result = testling.parseMessageBody("Alice", "Alice");
+ assertText(result, 0, "Alice");
+ }
private:
- std::map<std::string, std::string> emoticons_;
- std::string smile1_;
- std::string smile1Path_;
- std::string smile2_;
- std::string smile2Path_;
+ std::map<std::string, std::string> emoticons_;
+ std::string smile1_;
+ std::string smile1Path_;
+ std::string smile2_;
+ std::string smile2Path_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChatMessageParserTest);
diff --git a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
index d29337d..7445c4b 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
@@ -61,808 +61,808 @@
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(testChatControllerHighlightingNotificationTesting);
- CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds);
- CPPUNIT_TEST_SUITE_END();
+ 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(testChatControllerHighlightingNotificationTesting);
+ CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds);
+ CPPUNIT_TEST_SUITE_END();
public:
- void setUp() {
- mocks_ = new MockRepository();
- jid_ = JID("test@test.com/resource");
- stanzaChannel_ = new DummyStanzaChannel();
- iqChannel_ = new DummyIQChannel();
- iqRouter_ = new IQRouter(iqChannel_);
-// capsProvider_ = new DummyCapsProvider();
- eventController_ = new EventController();
- chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
- joinMUCWindowFactory_ = mocks_->InterfaceMock<JoinMUCWindowFactory>();
- xmppRoster_ = new XMPPRosterImpl();
- mucRegistry_ = new MUCRegistry();
- nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_);
- presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
- serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
- presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
- directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
- mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_);
- uiEventStream_ = new UIEventStream();
-// entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_);
- entityCapsProvider_ = new DummyEntityCapsProvider();
- chatListWindowFactory_ = mocks_->InterfaceMock<ChatListWindowFactory>();
- mucSearchWindowFactory_ = mocks_->InterfaceMock<MUCSearchWindowFactory>();
- settings_ = new DummySettingsProvider();
- profileSettings_ = new ProfileSettingsProvider("a", settings_);
- chatListWindow_ = new MockChatListWindow();
- ftManager_ = new DummyFileTransferManager();
- ftOverview_ = new FileTransferOverview(ftManager_);
- avatarManager_ = new NullAvatarManager();
- wbSessionManager_ = new WhiteboardSessionManager(iqRouter_, stanzaChannel_, presenceOracle_, entityCapsProvider_);
- wbManager_ = new WhiteboardManager(whiteboardWindowFactory_, uiEventStream_, nickResolver_, wbSessionManager_);
- highlightManager_ = new HighlightManager(settings_);
- handledHighlightActions_ = 0;
- soundsPlayed_.clear();
- highlightManager_->onHighlight.connect(boost::bind(&ChatsManagerTest::handleHighlightAction, this, _1));
-
- crypto_ = PlatformCryptoProvider::create();
- vcardStorage_ = new VCardMemoryStorage(crypto_);
- vcardManager_ = new VCardManager(jid_, iqRouter_, vcardStorage_);
- mocks_->ExpectCall(chatListWindowFactory_, ChatListWindowFactory::createChatListWindow).With(uiEventStream_).Return(chatListWindow_);
- clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
- manager_ = new ChatsManager(jid_, stanzaChannel_, iqRouter_, eventController_, chatWindowFactory_, joinMUCWindowFactory_, nickResolver_, presenceOracle_, directedPresenceSender_, uiEventStream_, chatListWindowFactory_, true, NULL, mucRegistry_, entityCapsProvider_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_, NULL, wbManager_, highlightManager_, clientBlockListManager_, emoticons_, vcardManager_);
-
- manager_->setAvatarManager(avatarManager_);
- }
-
- void tearDown() {
- delete highlightManager_;
- //delete chatListWindowFactory
- delete profileSettings_;
- delete avatarManager_;
- delete manager_;
- delete clientBlockListManager_;
- delete vcardManager_;
- delete vcardStorage_;
- delete crypto_;
- delete ftOverview_;
- delete ftManager_;
- delete wbSessionManager_;
- delete wbManager_;
- delete directedPresenceSender_;
- delete presenceSender_;
- delete presenceOracle_;
- delete nickResolver_;
- delete mucRegistry_;
- delete stanzaChannel_;
- delete eventController_;
- delete iqRouter_;
- delete iqChannel_;
- delete uiEventStream_;
- delete mucManager_;
- delete xmppRoster_;
- delete entityCapsProvider_;
- delete chatListWindow_;
- delete mocks_;
- delete settings_;
- }
-
- void testFirstOpenWindowIncoming() {
- JID messageJID("testling@test.com/resource1");
-
- MockChatWindow* window = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
-
- boost::shared_ptr<Message> message(new Message());
- message->setFrom(messageJID);
- std::string body("This is a legible message. >HEH@)oeueu");
- message->setBody(body);
- manager_->handleIncomingMessage(message);
- CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_);
- }
-
- void testSecondOpenWindowIncoming() {
- JID messageJID1("testling@test.com/resource1");
-
- MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
-
- boost::shared_ptr<Message> message1(new Message());
- message1->setFrom(messageJID1);
- std::string body1("This is a legible message. >HEH@)oeueu");
- message1->setBody(body1);
- manager_->handleIncomingMessage(message1);
- CPPUNIT_ASSERT_EQUAL(body1, window1->lastMessageBody_);
-
- JID messageJID2("testling@test.com/resource2");
-
- //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2);
-
- boost::shared_ptr<Message> message2(new Message());
- message2->setFrom(messageJID2);
- std::string body2("This is a legible message. .cmaulm.chul");
- message2->setBody(body2);
- manager_->handleIncomingMessage(message2);
- CPPUNIT_ASSERT_EQUAL(body2, window1->lastMessageBody_);
- }
-
- void testFirstOpenWindowOutgoing() {
- std::string messageJIDString("testling@test.com");
-
- ChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString), uiEventStream_).Return(window);
-
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString))));
- }
-
-
- void testFirstOpenWindowBareToFull() {
- std::string bareJIDString("testling@test.com");
- std::string fullJIDString("testling@test.com/resource1");
-
- MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(bareJIDString))));
-
- boost::shared_ptr<Message> message(new Message());
- message->setFrom(JID(fullJIDString));
- std::string body("This is a legible message. mjuga3089gm8G(*>M)@*(");
- message->setBody(body);
- manager_->handleIncomingMessage(message);
- CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_);
- }
-
- void testSecondWindow() {
- std::string messageJIDString1("testling1@test.com");
- ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
-
- std::string messageJIDString2("testling2@test.com");
- ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
-
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString2))));
- }
-
- /** Complete cycle.
- Create unbound window.
- Bind it.
- Unbind it.
- Rebind it.
- */
- void testUnbindRebind() {
- std::string bareJIDString("testling@test.com");
- std::string fullJIDString1("testling@test.com/resource1");
- std::string fullJIDString2("testling@test.com/resource2");
-
- MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(bareJIDString))));
-
- boost::shared_ptr<Message> message1(new Message());
- message1->setFrom(JID(fullJIDString1));
- std::string messageBody1("This is a legible message.");
- message1->setBody(messageBody1);
- manager_->handleIncomingMessage(message1);
- CPPUNIT_ASSERT_EQUAL(messageBody1, window->lastMessageBody_);
-
- boost::shared_ptr<Presence> jid1Online(new Presence());
- jid1Online->setFrom(JID(fullJIDString1));
- boost::shared_ptr<Presence> jid1Offline(new Presence());
- jid1Offline->setFrom(JID(fullJIDString1));
- jid1Offline->setType(Presence::Unavailable);
- presenceOracle_->onPresenceChange(jid1Offline);
-
- boost::shared_ptr<Message> message2(new Message());
- message2->setFrom(JID(fullJIDString2));
- std::string messageBody2("This is another legible message.");
- message2->setBody(messageBody2);
- manager_->handleIncomingMessage(message2);
- CPPUNIT_ASSERT_EQUAL(messageBody2, window->lastMessageBody_);
- }
-
- /**
- * Test that MUC PMs get opened in the right windows
- */
- void testThreeMUCWindows() {
- JID muc("testling@test.com");
- ChatWindow* mucWindow = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc, uiEventStream_).Return(mucWindow);
- uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(muc, std::string("nick")));
-
-
- std::string messageJIDString1("testling@test.com/1");
- ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
-
- std::string messageJIDString2("testling@test.com/2");
- ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
-
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString2))));
-
- std::string messageJIDString3("testling@test.com/3");
- ChatWindow* window3 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3);
-
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString3))));
-
- /* Refetch an earlier window */
- /* We do not expect a new window to be created */
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
-
- }
-
- /**
- Test that a second window isn't unbound where there's already an unbound one.
- Bind 1
- Bind 2
- Unbind 1
- Unbind 2 (but it doesn't)
- Sent to bound 2
- Rebind 1
- */
- void testNoDuplicateUnbind() {
- JID messageJID1("testling@test.com/resource1");
-
- MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
-
- boost::shared_ptr<Message> message1(new Message());
- message1->setFrom(messageJID1);
- message1->setBody("This is a legible message1.");
- manager_->handleIncomingMessage(message1);
-
- JID messageJID2("testling@test.com/resource2");
-
- //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2);
-
- boost::shared_ptr<Message> message2(new Message());
- message2->setFrom(messageJID2);
- message2->setBody("This is a legible message2.");
- manager_->handleIncomingMessage(message2);
-
- boost::shared_ptr<Presence> jid1Online(new Presence());
- jid1Online->setFrom(JID(messageJID1));
- boost::shared_ptr<Presence> jid1Offline(new Presence());
- jid1Offline->setFrom(JID(messageJID1));
- jid1Offline->setType(Presence::Unavailable);
- presenceOracle_->onPresenceChange(jid1Offline);
-
- boost::shared_ptr<Presence> jid2Online(new Presence());
- jid2Online->setFrom(JID(messageJID2));
- boost::shared_ptr<Presence> jid2Offline(new Presence());
- jid2Offline->setFrom(JID(messageJID2));
- jid2Offline->setType(Presence::Unavailable);
- presenceOracle_->onPresenceChange(jid2Offline);
-
- JID messageJID3("testling@test.com/resource3");
-
- boost::shared_ptr<Message> message3(new Message());
- message3->setFrom(messageJID3);
- std::string body3("This is a legible message3.");
- message3->setBody(body3);
- manager_->handleIncomingMessage(message3);
- CPPUNIT_ASSERT_EQUAL(body3, window1->lastMessageBody_);
-
- boost::shared_ptr<Message> message2b(new Message());
- message2b->setFrom(messageJID2);
- std::string body2b("This is a legible message2b.");
- message2b->setBody(body2b);
- manager_->handleIncomingMessage(message2b);
- CPPUNIT_ASSERT_EQUAL(body2b, window1->lastMessageBody_);
- }
-
- /**
- * Test that ChatController doesn't send receipts anymore after removal of the contact from the roster.
- */
- void testChatControllerPresenceAccessUpdatedOnRemoveFromRoster() {
- JID messageJID("testling@test.com/resource1");
- xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), RosterItemPayload::Both);
-
- MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
- settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
-
- boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
- manager_->handleIncomingMessage(message);
- Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
- CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
- CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
-
- xmppRoster_->removeContact(messageJID);
-
- message->setID("2");
- manager_->handleIncomingMessage(message);
- CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
- }
-
- /**
- * Test that ChatController sends receipts after the contact has been added to the roster.
- */
- void testChatControllerPresenceAccessUpdatedOnAddToRoster() {
- JID messageJID("testling@test.com/resource1");
-
- MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
- settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
-
- boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size());
-
- xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), RosterItemPayload::Both);
- message->setID("2");
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
- Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
- CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
- }
-
- /**
- * 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(boost::make_shared<RequestChatUIEvent>(sender));
-
- foreach(const JID& senderJID, senderResource) {
- // The sender supports delivery receipts.
- DiscoInfo::ref disco = boost::make_shared<DiscoInfo>();
- disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
- entityCapsProvider_->caps[senderJID] = disco;
-
- // The sender is online.
- Presence::ref senderPresence = boost::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>(0)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(0)->getPayload<DeliveryReceiptRequest>());
-
- // Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
- Message::ref receiptReply = boost::make_shared<Message>();
- receiptReply->setFrom(senderJID);
- receiptReply->setTo(ownJID);
-
- boost::shared_ptr<DeliveryReceipt> receipt = boost::make_shared<DeliveryReceipt>();
- receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(0)->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) {
- Message::ref receiptReply = boost::make_shared<Message>();
- receiptReply->setFrom(senderJID);
- receiptReply->setTo(ownJID);
-
- boost::shared_ptr<DeliveryReceipt> receipt = boost::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 = boost::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>(2)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
-
- // Receive random receipt from second sender resource.
- reply = boost::make_shared<Message>();
- reply->setFrom(senderResource[1]);
- reply->setTo(ownJID);
-
- boost::shared_ptr<DeliveryReceipt> receipt = boost::make_shared<DeliveryReceipt>();
- receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(2)->getID());
- reply->addPayload(receipt);
- manager_->handleIncomingMessage(reply);
-
- // Send forth message.
- window->onSendMessageRequest("what else is new?", 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>(3)->getPayload<DeliveryReceiptRequest>());
-
- // Reply with a message including a body text from second resource.
- reply = boost::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>(4)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(4)->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(boost::make_shared<RequestChatUIEvent>(sender));
-
- foreach(const JID& senderJID, senderResource) {
- // The sender supports delivery receipts.
- DiscoInfo::ref disco = boost::make_shared<DiscoInfo>();
- disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
- entityCapsProvider_->caps[senderJID] = disco;
-
- // The sender is online.
- Presence::ref senderPresence = boost::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>(0)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(0)->getPayload<DeliveryReceiptRequest>());
-
- // Two resources respond with message receipts.
- foreach(const JID& senderJID, senderResource) {
- Message::ref reply = boost::make_shared<Message>();
- reply->setFrom(senderJID);
- reply->setTo(ownJID);
-
- boost::shared_ptr<ChatState> csn = boost::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) {
- Message::ref receiptReply = boost::make_shared<Message>();
- receiptReply->setFrom(senderJID);
- receiptReply->setTo(ownJID);
-
- boost::shared_ptr<DeliveryReceipt> receipt = boost::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 = boost::make_shared<Message>();
- reply->setFrom(senderResource[0]);
- reply->setTo(ownJID);
-
- boost::shared_ptr<ChatState> csn = boost::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>(2)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
-
- // Reply with a message including a CSN from the other resource.
- reply = boost::make_shared<Message>();
- reply->setFrom(senderResource[1]);
- reply->setTo(ownJID);
-
- csn = boost::make_shared<ChatState>();
- csn->setChatState(ChatState::Composing);
- reply->addPayload(csn);
- manager_->handleIncomingMessage(reply);
-
- // Send third message.
- window->onSendMessageRequest("ping.", false);
-
- // The chat session is now bound to the full JID of the second resource due to its recent composing message.
- CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
- CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(3)->getPayload<DeliveryReceiptRequest>());
- }
-
- void testChatControllerPMPresenceHandling() {
- JID participantA = JID("test@rooms.test.com/participantA");
- JID participantB = JID("test@rooms.test.com/participantB");
-
- mucRegistry_->addMUC("test@rooms.test.com");
-
- MockChatWindow* window = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(participantA, uiEventStream_).Return(window);
-
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(participantA))));
-
- Presence::ref presence = Presence::create();
- presence->setFrom(participantA);
- presence->setShow(StatusShow::Online);
- stanzaChannel_->onPresenceReceived(presence);
- CPPUNIT_ASSERT_EQUAL(std::string("participantA has become available."), MockChatWindow::bodyFromMessage(window->lastAddedPresence_));
-
- presence = Presence::create();
- presence->setFrom(participantB);
- presence->setShow(StatusShow::Away);
- stanzaChannel_->onPresenceReceived(presence);
-
- presence = Presence::create();
- presence->setFrom(participantA);
- presence->setShow(StatusShow::None);
- presence->setType(Presence::Unavailable);
- stanzaChannel_->onPresenceReceived(presence);
- CPPUNIT_ASSERT_EQUAL(std::string("participantA has gone offline."), MockChatWindow::bodyFromMessage(window->lastReplacedMessage_));
- }
-
- void testLocalMUCServiceDiscoveryResetOnDisconnect() {
- JID ownJID("test@test.com/resource");
- JID sender("foo@test.com");
-
- manager_->setOnline(true);
-
- // Open chat window to a sender.
- MockChatWindow* window = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
-
- uiEventStream_->send(boost::make_shared<RequestChatUIEvent>(sender));
-
- CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_);
-
- boost::shared_ptr<IQ> infoRequest= iqChannel_->iqs_[1];
- boost::shared_ptr<IQ> infoResponse = IQ::createResult(infoRequest->getFrom(), infoRequest->getTo(), infoRequest->getID());
-
- DiscoInfo info;
- info.addIdentity(DiscoInfo::Identity("Shakespearean Chat Service", "conference", "text"));
- info.addFeature("http://jabber.org/protocol/muc");
- infoResponse->addPayload(boost::make_shared<DiscoInfo>(info));
- iqChannel_->onIQReceived(infoResponse);
-
- CPPUNIT_ASSERT_EQUAL(true, window->impromptuMUCSupported_);
- manager_->setOnline(false);
- CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_);
- }
-
- void testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::Subscription from, RosterItemPayload::Subscription to) {
- JID messageJID("testling@test.com/resource1");
- xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), from);
-
- MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
- settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
-
- boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size());
-
- xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), to);
- message->setID("2");
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
- Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
- CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
- }
-
- void testChatControllerHighlightingNotificationTesting() {
- HighlightRule keywordRuleA;
- keywordRuleA.setMatchChat(true);
- std::vector<std::string> keywordsA;
- keywordsA.push_back("Romeo");
- keywordRuleA.setKeywords(keywordsA);
- keywordRuleA.getAction().setTextColor("yellow");
- keywordRuleA.getAction().setPlaySound(true);
- highlightManager_->insertRule(0, keywordRuleA);
-
- HighlightRule keywordRuleB;
- keywordRuleB.setMatchChat(true);
- std::vector<std::string> keywordsB;
- keywordsB.push_back("Juliet");
- keywordRuleB.setKeywords(keywordsB);
- keywordRuleB.getAction().setTextColor("green");
- keywordRuleB.getAction().setPlaySound(true);
- keywordRuleB.getAction().setSoundFile("/tmp/someotherfile.wav");
- highlightManager_->insertRule(0, keywordRuleB);
-
- JID messageJID = JID("testling@test.com");
-
- MockChatWindow* window = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
-
- boost::shared_ptr<Message> message(new Message());
- message->setFrom(messageJID);
- std::string body("This message should cause two sounds: Juliet and Romeo.");
- message->setBody(body);
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(2, handledHighlightActions_);
- CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end());
- CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end());
- }
-
- void testChatControllerHighlightingNotificationDeduplicateSounds() {
- HighlightRule keywordRuleA;
- keywordRuleA.setMatchChat(true);
- std::vector<std::string> keywordsA;
- keywordsA.push_back("Romeo");
- keywordRuleA.setKeywords(keywordsA);
- keywordRuleA.getAction().setTextColor("yellow");
- keywordRuleA.getAction().setPlaySound(true);
- highlightManager_->insertRule(0, keywordRuleA);
-
- HighlightRule keywordRuleB;
- keywordRuleB.setMatchChat(true);
- std::vector<std::string> keywordsB;
- keywordsB.push_back("Juliet");
- keywordRuleB.setKeywords(keywordsB);
- keywordRuleB.getAction().setTextColor("green");
- keywordRuleB.getAction().setPlaySound(true);
- highlightManager_->insertRule(0, keywordRuleB);
-
- JID messageJID = JID("testling@test.com");
-
- MockChatWindow* window = new MockChatWindow();
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
-
- boost::shared_ptr<Message> message(new Message());
- message->setFrom(messageJID);
- std::string body("This message should cause one sound, because both actions have the same sound: Juliet and Romeo.");
- message->setBody(body);
- manager_->handleIncomingMessage(message);
-
- CPPUNIT_ASSERT_EQUAL(1, handledHighlightActions_);
- CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end());
- CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end());
- }
+ void setUp() {
+ mocks_ = new MockRepository();
+ jid_ = JID("test@test.com/resource");
+ stanzaChannel_ = new DummyStanzaChannel();
+ iqChannel_ = new DummyIQChannel();
+ iqRouter_ = new IQRouter(iqChannel_);
+// capsProvider_ = new DummyCapsProvider();
+ eventController_ = new EventController();
+ chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
+ joinMUCWindowFactory_ = mocks_->InterfaceMock<JoinMUCWindowFactory>();
+ xmppRoster_ = new XMPPRosterImpl();
+ mucRegistry_ = new MUCRegistry();
+ nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_);
+ presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
+ serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
+ presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
+ directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
+ mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_);
+ uiEventStream_ = new UIEventStream();
+// entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_);
+ entityCapsProvider_ = new DummyEntityCapsProvider();
+ chatListWindowFactory_ = mocks_->InterfaceMock<ChatListWindowFactory>();
+ mucSearchWindowFactory_ = mocks_->InterfaceMock<MUCSearchWindowFactory>();
+ settings_ = new DummySettingsProvider();
+ profileSettings_ = new ProfileSettingsProvider("a", settings_);
+ chatListWindow_ = new MockChatListWindow();
+ ftManager_ = new DummyFileTransferManager();
+ ftOverview_ = new FileTransferOverview(ftManager_);
+ avatarManager_ = new NullAvatarManager();
+ wbSessionManager_ = new WhiteboardSessionManager(iqRouter_, stanzaChannel_, presenceOracle_, entityCapsProvider_);
+ wbManager_ = new WhiteboardManager(whiteboardWindowFactory_, uiEventStream_, nickResolver_, wbSessionManager_);
+ highlightManager_ = new HighlightManager(settings_);
+ handledHighlightActions_ = 0;
+ soundsPlayed_.clear();
+ highlightManager_->onHighlight.connect(boost::bind(&ChatsManagerTest::handleHighlightAction, this, _1));
+
+ crypto_ = PlatformCryptoProvider::create();
+ vcardStorage_ = new VCardMemoryStorage(crypto_);
+ vcardManager_ = new VCardManager(jid_, iqRouter_, vcardStorage_);
+ mocks_->ExpectCall(chatListWindowFactory_, ChatListWindowFactory::createChatListWindow).With(uiEventStream_).Return(chatListWindow_);
+ clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
+ manager_ = new ChatsManager(jid_, stanzaChannel_, iqRouter_, eventController_, chatWindowFactory_, joinMUCWindowFactory_, nickResolver_, presenceOracle_, directedPresenceSender_, uiEventStream_, chatListWindowFactory_, true, NULL, mucRegistry_, entityCapsProvider_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_, NULL, wbManager_, highlightManager_, clientBlockListManager_, emoticons_, vcardManager_);
+
+ manager_->setAvatarManager(avatarManager_);
+ }
+
+ void tearDown() {
+ delete highlightManager_;
+ //delete chatListWindowFactory
+ delete profileSettings_;
+ delete avatarManager_;
+ delete manager_;
+ delete clientBlockListManager_;
+ delete vcardManager_;
+ delete vcardStorage_;
+ delete crypto_;
+ delete ftOverview_;
+ delete ftManager_;
+ delete wbSessionManager_;
+ delete wbManager_;
+ delete directedPresenceSender_;
+ delete presenceSender_;
+ delete presenceOracle_;
+ delete nickResolver_;
+ delete mucRegistry_;
+ delete stanzaChannel_;
+ delete eventController_;
+ delete iqRouter_;
+ delete iqChannel_;
+ delete uiEventStream_;
+ delete mucManager_;
+ delete xmppRoster_;
+ delete entityCapsProvider_;
+ delete chatListWindow_;
+ delete mocks_;
+ delete settings_;
+ }
+
+ void testFirstOpenWindowIncoming() {
+ JID messageJID("testling@test.com/resource1");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ boost::shared_ptr<Message> message(new Message());
+ message->setFrom(messageJID);
+ std::string body("This is a legible message. >HEH@)oeueu");
+ message->setBody(body);
+ manager_->handleIncomingMessage(message);
+ CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_);
+ }
+
+ void testSecondOpenWindowIncoming() {
+ JID messageJID1("testling@test.com/resource1");
+
+ MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
+
+ boost::shared_ptr<Message> message1(new Message());
+ message1->setFrom(messageJID1);
+ std::string body1("This is a legible message. >HEH@)oeueu");
+ message1->setBody(body1);
+ manager_->handleIncomingMessage(message1);
+ CPPUNIT_ASSERT_EQUAL(body1, window1->lastMessageBody_);
+
+ JID messageJID2("testling@test.com/resource2");
+
+ //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2);
+
+ boost::shared_ptr<Message> message2(new Message());
+ message2->setFrom(messageJID2);
+ std::string body2("This is a legible message. .cmaulm.chul");
+ message2->setBody(body2);
+ manager_->handleIncomingMessage(message2);
+ CPPUNIT_ASSERT_EQUAL(body2, window1->lastMessageBody_);
+ }
+
+ void testFirstOpenWindowOutgoing() {
+ std::string messageJIDString("testling@test.com");
+
+ ChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString), uiEventStream_).Return(window);
+
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString))));
+ }
+
+
+ void testFirstOpenWindowBareToFull() {
+ std::string bareJIDString("testling@test.com");
+ std::string fullJIDString("testling@test.com/resource1");
+
+ MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(bareJIDString))));
+
+ boost::shared_ptr<Message> message(new Message());
+ message->setFrom(JID(fullJIDString));
+ std::string body("This is a legible message. mjuga3089gm8G(*>M)@*(");
+ message->setBody(body);
+ manager_->handleIncomingMessage(message);
+ CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_);
+ }
+
+ void testSecondWindow() {
+ std::string messageJIDString1("testling1@test.com");
+ ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
+
+ std::string messageJIDString2("testling2@test.com");
+ ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
+
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString2))));
+ }
+
+ /** Complete cycle.
+ Create unbound window.
+ Bind it.
+ Unbind it.
+ Rebind it.
+ */
+ void testUnbindRebind() {
+ std::string bareJIDString("testling@test.com");
+ std::string fullJIDString1("testling@test.com/resource1");
+ std::string fullJIDString2("testling@test.com/resource2");
+
+ MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(bareJIDString))));
+
+ boost::shared_ptr<Message> message1(new Message());
+ message1->setFrom(JID(fullJIDString1));
+ std::string messageBody1("This is a legible message.");
+ message1->setBody(messageBody1);
+ manager_->handleIncomingMessage(message1);
+ CPPUNIT_ASSERT_EQUAL(messageBody1, window->lastMessageBody_);
+
+ boost::shared_ptr<Presence> jid1Online(new Presence());
+ jid1Online->setFrom(JID(fullJIDString1));
+ boost::shared_ptr<Presence> jid1Offline(new Presence());
+ jid1Offline->setFrom(JID(fullJIDString1));
+ jid1Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid1Offline);
+
+ boost::shared_ptr<Message> message2(new Message());
+ message2->setFrom(JID(fullJIDString2));
+ std::string messageBody2("This is another legible message.");
+ message2->setBody(messageBody2);
+ manager_->handleIncomingMessage(message2);
+ CPPUNIT_ASSERT_EQUAL(messageBody2, window->lastMessageBody_);
+ }
+
+ /**
+ * Test that MUC PMs get opened in the right windows
+ */
+ void testThreeMUCWindows() {
+ JID muc("testling@test.com");
+ ChatWindow* mucWindow = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc, uiEventStream_).Return(mucWindow);
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(muc, std::string("nick")));
+
+
+ std::string messageJIDString1("testling@test.com/1");
+ ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
+
+ std::string messageJIDString2("testling@test.com/2");
+ ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
+
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString2))));
+
+ std::string messageJIDString3("testling@test.com/3");
+ ChatWindow* window3 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3);
+
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString3))));
+
+ /* Refetch an earlier window */
+ /* We do not expect a new window to be created */
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
+
+ }
+
+ /**
+ Test that a second window isn't unbound where there's already an unbound one.
+ Bind 1
+ Bind 2
+ Unbind 1
+ Unbind 2 (but it doesn't)
+ Sent to bound 2
+ Rebind 1
+ */
+ void testNoDuplicateUnbind() {
+ JID messageJID1("testling@test.com/resource1");
+
+ MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
+
+ boost::shared_ptr<Message> message1(new Message());
+ message1->setFrom(messageJID1);
+ message1->setBody("This is a legible message1.");
+ manager_->handleIncomingMessage(message1);
+
+ JID messageJID2("testling@test.com/resource2");
+
+ //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2);
+
+ boost::shared_ptr<Message> message2(new Message());
+ message2->setFrom(messageJID2);
+ message2->setBody("This is a legible message2.");
+ manager_->handleIncomingMessage(message2);
+
+ boost::shared_ptr<Presence> jid1Online(new Presence());
+ jid1Online->setFrom(JID(messageJID1));
+ boost::shared_ptr<Presence> jid1Offline(new Presence());
+ jid1Offline->setFrom(JID(messageJID1));
+ jid1Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid1Offline);
+
+ boost::shared_ptr<Presence> jid2Online(new Presence());
+ jid2Online->setFrom(JID(messageJID2));
+ boost::shared_ptr<Presence> jid2Offline(new Presence());
+ jid2Offline->setFrom(JID(messageJID2));
+ jid2Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid2Offline);
+
+ JID messageJID3("testling@test.com/resource3");
+
+ boost::shared_ptr<Message> message3(new Message());
+ message3->setFrom(messageJID3);
+ std::string body3("This is a legible message3.");
+ message3->setBody(body3);
+ manager_->handleIncomingMessage(message3);
+ CPPUNIT_ASSERT_EQUAL(body3, window1->lastMessageBody_);
+
+ boost::shared_ptr<Message> message2b(new Message());
+ message2b->setFrom(messageJID2);
+ std::string body2b("This is a legible message2b.");
+ message2b->setBody(body2b);
+ manager_->handleIncomingMessage(message2b);
+ CPPUNIT_ASSERT_EQUAL(body2b, window1->lastMessageBody_);
+ }
+
+ /**
+ * Test that ChatController doesn't send receipts anymore after removal of the contact from the roster.
+ */
+ void testChatControllerPresenceAccessUpdatedOnRemoveFromRoster() {
+ JID messageJID("testling@test.com/resource1");
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), RosterItemPayload::Both);
+
+ MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
+
+ xmppRoster_->removeContact(messageJID);
+
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
+ }
+
+ /**
+ * Test that ChatController sends receipts after the contact has been added to the roster.
+ */
+ void testChatControllerPresenceAccessUpdatedOnAddToRoster() {
+ JID messageJID("testling@test.com/resource1");
+
+ MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size());
+
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), RosterItemPayload::Both);
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
+ }
+
+ /**
+ * 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(boost::make_shared<RequestChatUIEvent>(sender));
+
+ foreach(const JID& senderJID, senderResource) {
+ // The sender supports delivery receipts.
+ DiscoInfo::ref disco = boost::make_shared<DiscoInfo>();
+ disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
+ entityCapsProvider_->caps[senderJID] = disco;
+
+ // The sender is online.
+ Presence::ref senderPresence = boost::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>(0)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(0)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ foreach(const JID& senderJID, senderResource) {
+ Message::ref receiptReply = boost::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ boost::shared_ptr<DeliveryReceipt> receipt = boost::make_shared<DeliveryReceipt>();
+ receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(0)->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) {
+ Message::ref receiptReply = boost::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ boost::shared_ptr<DeliveryReceipt> receipt = boost::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 = boost::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>(2)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
+
+ // Receive random receipt from second sender resource.
+ reply = boost::make_shared<Message>();
+ reply->setFrom(senderResource[1]);
+ reply->setTo(ownJID);
+
+ boost::shared_ptr<DeliveryReceipt> receipt = boost::make_shared<DeliveryReceipt>();
+ receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(2)->getID());
+ reply->addPayload(receipt);
+ manager_->handleIncomingMessage(reply);
+
+ // Send forth message.
+ window->onSendMessageRequest("what else is new?", 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>(3)->getPayload<DeliveryReceiptRequest>());
+
+ // Reply with a message including a body text from second resource.
+ reply = boost::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>(4)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(4)->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(boost::make_shared<RequestChatUIEvent>(sender));
+
+ foreach(const JID& senderJID, senderResource) {
+ // The sender supports delivery receipts.
+ DiscoInfo::ref disco = boost::make_shared<DiscoInfo>();
+ disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
+ entityCapsProvider_->caps[senderJID] = disco;
+
+ // The sender is online.
+ Presence::ref senderPresence = boost::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>(0)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(0)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ foreach(const JID& senderJID, senderResource) {
+ Message::ref reply = boost::make_shared<Message>();
+ reply->setFrom(senderJID);
+ reply->setTo(ownJID);
+
+ boost::shared_ptr<ChatState> csn = boost::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) {
+ Message::ref receiptReply = boost::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ boost::shared_ptr<DeliveryReceipt> receipt = boost::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 = boost::make_shared<Message>();
+ reply->setFrom(senderResource[0]);
+ reply->setTo(ownJID);
+
+ boost::shared_ptr<ChatState> csn = boost::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>(2)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
+
+ // Reply with a message including a CSN from the other resource.
+ reply = boost::make_shared<Message>();
+ reply->setFrom(senderResource[1]);
+ reply->setTo(ownJID);
+
+ csn = boost::make_shared<ChatState>();
+ csn->setChatState(ChatState::Composing);
+ reply->addPayload(csn);
+ manager_->handleIncomingMessage(reply);
+
+ // Send third message.
+ window->onSendMessageRequest("ping.", false);
+
+ // The chat session is now bound to the full JID of the second resource due to its recent composing message.
+ CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(3)->getPayload<DeliveryReceiptRequest>());
+ }
+
+ void testChatControllerPMPresenceHandling() {
+ JID participantA = JID("test@rooms.test.com/participantA");
+ JID participantB = JID("test@rooms.test.com/participantB");
+
+ mucRegistry_->addMUC("test@rooms.test.com");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(participantA, uiEventStream_).Return(window);
+
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(participantA))));
+
+ Presence::ref presence = Presence::create();
+ presence->setFrom(participantA);
+ presence->setShow(StatusShow::Online);
+ stanzaChannel_->onPresenceReceived(presence);
+ CPPUNIT_ASSERT_EQUAL(std::string("participantA has become available."), MockChatWindow::bodyFromMessage(window->lastAddedPresence_));
+
+ presence = Presence::create();
+ presence->setFrom(participantB);
+ presence->setShow(StatusShow::Away);
+ stanzaChannel_->onPresenceReceived(presence);
+
+ presence = Presence::create();
+ presence->setFrom(participantA);
+ presence->setShow(StatusShow::None);
+ presence->setType(Presence::Unavailable);
+ stanzaChannel_->onPresenceReceived(presence);
+ CPPUNIT_ASSERT_EQUAL(std::string("participantA has gone offline."), MockChatWindow::bodyFromMessage(window->lastReplacedMessage_));
+ }
+
+ void testLocalMUCServiceDiscoveryResetOnDisconnect() {
+ JID ownJID("test@test.com/resource");
+ JID sender("foo@test.com");
+
+ manager_->setOnline(true);
+
+ // Open chat window to a sender.
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
+
+ uiEventStream_->send(boost::make_shared<RequestChatUIEvent>(sender));
+
+ CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_);
+
+ boost::shared_ptr<IQ> infoRequest= iqChannel_->iqs_[1];
+ boost::shared_ptr<IQ> infoResponse = IQ::createResult(infoRequest->getFrom(), infoRequest->getTo(), infoRequest->getID());
+
+ DiscoInfo info;
+ info.addIdentity(DiscoInfo::Identity("Shakespearean Chat Service", "conference", "text"));
+ info.addFeature("http://jabber.org/protocol/muc");
+ infoResponse->addPayload(boost::make_shared<DiscoInfo>(info));
+ iqChannel_->onIQReceived(infoResponse);
+
+ CPPUNIT_ASSERT_EQUAL(true, window->impromptuMUCSupported_);
+ manager_->setOnline(false);
+ CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_);
+ }
+
+ void testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::Subscription from, RosterItemPayload::Subscription to) {
+ JID messageJID("testling@test.com/resource1");
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), from);
+
+ MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ boost::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size());
+
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), to);
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size());
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(0);
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != 0);
+ }
+
+ void testChatControllerHighlightingNotificationTesting() {
+ HighlightRule keywordRuleA;
+ keywordRuleA.setMatchChat(true);
+ std::vector<std::string> keywordsA;
+ keywordsA.push_back("Romeo");
+ keywordRuleA.setKeywords(keywordsA);
+ keywordRuleA.getAction().setTextColor("yellow");
+ keywordRuleA.getAction().setPlaySound(true);
+ highlightManager_->insertRule(0, keywordRuleA);
+
+ HighlightRule keywordRuleB;
+ keywordRuleB.setMatchChat(true);
+ std::vector<std::string> keywordsB;
+ keywordsB.push_back("Juliet");
+ keywordRuleB.setKeywords(keywordsB);
+ keywordRuleB.getAction().setTextColor("green");
+ keywordRuleB.getAction().setPlaySound(true);
+ keywordRuleB.getAction().setSoundFile("/tmp/someotherfile.wav");
+ highlightManager_->insertRule(0, keywordRuleB);
+
+ JID messageJID = JID("testling@test.com");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ boost::shared_ptr<Message> message(new Message());
+ message->setFrom(messageJID);
+ std::string body("This message should cause two sounds: Juliet and Romeo.");
+ message->setBody(body);
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(2, handledHighlightActions_);
+ CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end());
+ CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end());
+ }
+
+ void testChatControllerHighlightingNotificationDeduplicateSounds() {
+ HighlightRule keywordRuleA;
+ keywordRuleA.setMatchChat(true);
+ std::vector<std::string> keywordsA;
+ keywordsA.push_back("Romeo");
+ keywordRuleA.setKeywords(keywordsA);
+ keywordRuleA.getAction().setTextColor("yellow");
+ keywordRuleA.getAction().setPlaySound(true);
+ highlightManager_->insertRule(0, keywordRuleA);
+
+ HighlightRule keywordRuleB;
+ keywordRuleB.setMatchChat(true);
+ std::vector<std::string> keywordsB;
+ keywordsB.push_back("Juliet");
+ keywordRuleB.setKeywords(keywordsB);
+ keywordRuleB.getAction().setTextColor("green");
+ keywordRuleB.getAction().setPlaySound(true);
+ highlightManager_->insertRule(0, keywordRuleB);
+
+ JID messageJID = JID("testling@test.com");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ boost::shared_ptr<Message> message(new Message());
+ message->setFrom(messageJID);
+ std::string body("This message should cause one sound, because both actions have the same sound: Juliet and Romeo.");
+ message->setBody(body);
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(1, handledHighlightActions_);
+ CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end());
+ CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end());
+ }
private:
- boost::shared_ptr<Message> makeDeliveryReceiptTestMessage(const JID& from, const std::string& id) {
- boost::shared_ptr<Message> message = boost::make_shared<Message>();
- message->setFrom(from);
- message->setID(id);
- message->setBody("This will cause the window to open");
- message->addPayload(boost::make_shared<DeliveryReceiptRequest>());
- return message;
- }
-
- size_t st(int i) {
- return static_cast<size_t>(i);
- }
-
- void handleHighlightAction(const HighlightAction& action) {
- handledHighlightActions_++;
- if (action.playSound()) {
- soundsPlayed_.insert(action.getSoundFile());
- }
- }
+ boost::shared_ptr<Message> makeDeliveryReceiptTestMessage(const JID& from, const std::string& id) {
+ boost::shared_ptr<Message> message = boost::make_shared<Message>();
+ message->setFrom(from);
+ message->setID(id);
+ message->setBody("This will cause the window to open");
+ message->addPayload(boost::make_shared<DeliveryReceiptRequest>());
+ return message;
+ }
+
+ size_t st(int i) {
+ return static_cast<size_t>(i);
+ }
+
+ void handleHighlightAction(const HighlightAction& action) {
+ handledHighlightActions_++;
+ if (action.playSound()) {
+ soundsPlayed_.insert(action.getSoundFile());
+ }
+ }
private:
- JID jid_;
- ChatsManager* manager_;
- DummyStanzaChannel* stanzaChannel_;
- DummyIQChannel* iqChannel_;
- IQRouter* iqRouter_;
- EventController* eventController_;
- ChatWindowFactory* chatWindowFactory_;
- JoinMUCWindowFactory* joinMUCWindowFactory_;
- NickResolver* nickResolver_;
- PresenceOracle* presenceOracle_;
- AvatarManager* avatarManager_;
- boost::shared_ptr<DiscoInfo> serverDiscoInfo_;
- XMPPRosterImpl* xmppRoster_;
- PresenceSender* presenceSender_;
- MockRepository* mocks_;
- UIEventStream* uiEventStream_;
- ChatListWindowFactory* chatListWindowFactory_;
- WhiteboardWindowFactory* whiteboardWindowFactory_;
- MUCSearchWindowFactory* mucSearchWindowFactory_;
- MUCRegistry* mucRegistry_;
- DirectedPresenceSender* directedPresenceSender_;
- DummyEntityCapsProvider* entityCapsProvider_;
- MUCManager* mucManager_;
- DummySettingsProvider* settings_;
- ProfileSettingsProvider* profileSettings_;
- ChatListWindow* chatListWindow_;
- FileTransferOverview* ftOverview_;
- FileTransferManager* ftManager_;
- WhiteboardSessionManager* wbSessionManager_;
- WhiteboardManager* wbManager_;
- HighlightManager* highlightManager_;
- ClientBlockListManager* clientBlockListManager_;
- VCardManager* vcardManager_;
- CryptoProvider* crypto_;
- VCardStorage* vcardStorage_;
- std::map<std::string, std::string> emoticons_;
- int handledHighlightActions_;
- std::set<std::string> soundsPlayed_;
+ JID jid_;
+ ChatsManager* manager_;
+ DummyStanzaChannel* stanzaChannel_;
+ DummyIQChannel* iqChannel_;
+ IQRouter* iqRouter_;
+ EventController* eventController_;
+ ChatWindowFactory* chatWindowFactory_;
+ JoinMUCWindowFactory* joinMUCWindowFactory_;
+ NickResolver* nickResolver_;
+ PresenceOracle* presenceOracle_;
+ AvatarManager* avatarManager_;
+ boost::shared_ptr<DiscoInfo> serverDiscoInfo_;
+ XMPPRosterImpl* xmppRoster_;
+ PresenceSender* presenceSender_;
+ MockRepository* mocks_;
+ UIEventStream* uiEventStream_;
+ ChatListWindowFactory* chatListWindowFactory_;
+ WhiteboardWindowFactory* whiteboardWindowFactory_;
+ MUCSearchWindowFactory* mucSearchWindowFactory_;
+ MUCRegistry* mucRegistry_;
+ DirectedPresenceSender* directedPresenceSender_;
+ DummyEntityCapsProvider* entityCapsProvider_;
+ MUCManager* mucManager_;
+ DummySettingsProvider* settings_;
+ ProfileSettingsProvider* profileSettings_;
+ ChatListWindow* chatListWindow_;
+ FileTransferOverview* ftOverview_;
+ FileTransferManager* ftManager_;
+ WhiteboardSessionManager* wbSessionManager_;
+ WhiteboardManager* wbManager_;
+ HighlightManager* highlightManager_;
+ ClientBlockListManager* clientBlockListManager_;
+ VCardManager* vcardManager_;
+ CryptoProvider* crypto_;
+ VCardStorage* vcardStorage_;
+ std::map<std::string, std::string> emoticons_;
+ int handledHighlightActions_;
+ std::set<std::string> soundsPlayed_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChatsManagerTest);
diff --git a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
index e8fc41d..db9bcdc 100644
--- a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
@@ -48,509 +48,509 @@
using namespace Swift;
class MUCControllerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MUCControllerTest);
- CPPUNIT_TEST(testJoinPartStringContructionSimple);
- CPPUNIT_TEST(testJoinPartStringContructionMixed);
- CPPUNIT_TEST(testAppendToJoinParts);
- CPPUNIT_TEST(testAddressedToSelf);
- CPPUNIT_TEST(testNotAddressedToSelf);
- CPPUNIT_TEST(testAddressedToSelfBySelf);
- CPPUNIT_TEST(testMessageWithEmptyLabelItem);
- CPPUNIT_TEST(testMessageWithLabelItem);
- CPPUNIT_TEST(testCorrectMessageWithLabelItem);
- CPPUNIT_TEST(testRoleAffiliationStates);
- CPPUNIT_TEST(testSubjectChangeCorrect);
- CPPUNIT_TEST(testSubjectChangeIncorrectA);
- CPPUNIT_TEST(testSubjectChangeIncorrectB);
- CPPUNIT_TEST(testSubjectChangeIncorrectC);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(MUCControllerTest);
+ CPPUNIT_TEST(testJoinPartStringContructionSimple);
+ CPPUNIT_TEST(testJoinPartStringContructionMixed);
+ CPPUNIT_TEST(testAppendToJoinParts);
+ CPPUNIT_TEST(testAddressedToSelf);
+ CPPUNIT_TEST(testNotAddressedToSelf);
+ CPPUNIT_TEST(testAddressedToSelfBySelf);
+ CPPUNIT_TEST(testMessageWithEmptyLabelItem);
+ CPPUNIT_TEST(testMessageWithLabelItem);
+ CPPUNIT_TEST(testCorrectMessageWithLabelItem);
+ CPPUNIT_TEST(testRoleAffiliationStates);
+ CPPUNIT_TEST(testSubjectChangeCorrect);
+ CPPUNIT_TEST(testSubjectChangeIncorrectA);
+ CPPUNIT_TEST(testSubjectChangeIncorrectB);
+ CPPUNIT_TEST(testSubjectChangeIncorrectC);
+ CPPUNIT_TEST_SUITE_END();
public:
- void setUp() {
- crypto_ = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- self_ = JID("girl@wonderland.lit/rabbithole");
- nick_ = "aLiCe";
- mucJID_ = JID("teaparty@rooms.wonderland.lit");
- mocks_ = new MockRepository();
- stanzaChannel_ = new DummyStanzaChannel();
- iqChannel_ = new DummyIQChannel();
- iqRouter_ = new IQRouter(iqChannel_);
- eventController_ = new EventController();
- chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
- userSearchWindowFactory_ = mocks_->InterfaceMock<UserSearchWindowFactory>();
- xmppRoster_ = new XMPPRosterImpl();
- presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
- presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
- directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
- uiEventStream_ = new UIEventStream();
- avatarManager_ = new NullAvatarManager();
- TimerFactory* timerFactory = NULL;
- window_ = new MockChatWindow();
- mucRegistry_ = new MUCRegistry();
- entityCapsProvider_ = new DummyEntityCapsProvider();
- settings_ = new DummySettingsProvider();
- highlightManager_ = new HighlightManager(settings_);
- muc_ = boost::make_shared<MockMUC>(mucJID_);
- mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc_->getJID(), uiEventStream_).Return(window_);
- chatMessageParser_ = boost::make_shared<ChatMessageParser>(std::map<std::string, std::string>(), highlightManager_->getRules(), true);
- vcardStorage_ = new VCardMemoryStorage(crypto_.get());
- vcardManager_ = new VCardManager(self_, iqRouter_, vcardStorage_);
- clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
- mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_);
- controller_ = new MUCController (self_, muc_, boost::optional<std::string>(), nick_, stanzaChannel_, iqRouter_, chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory, eventController_, entityCapsProvider_, NULL, NULL, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser_, false, NULL, vcardManager_, mucBookmarkManager_);
- }
-
- void tearDown() {
- delete controller_;
- delete mucBookmarkManager_;
- delete clientBlockListManager_;
- delete vcardManager_;
- delete vcardStorage_;
- delete highlightManager_;
- delete settings_;
- delete entityCapsProvider_;
- delete eventController_;
- delete presenceOracle_;
- delete xmppRoster_;
- delete mocks_;
- delete uiEventStream_;
- delete stanzaChannel_;
- delete presenceSender_;
- delete directedPresenceSender_;
- delete iqRouter_;
- delete iqChannel_;
- delete mucRegistry_;
- delete avatarManager_;
- }
-
- void finishJoin() {
- Presence::ref presence(new Presence());
- presence->setFrom(JID(muc_->getJID().toString() + "/" + nick_));
- MUCUserPayload::ref status(new MUCUserPayload());
- MUCUserPayload::StatusCode code;
- code.code = 110;
- status->addStatusCode(code);
- presence->addPayload(status);
- stanzaChannel_->onPresenceReceived(presence);
- }
-
- void testAddressedToSelf() {
- finishJoin();
- Message::ref message(new Message());
-
- message = Message::ref(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/otherperson"));
- message->setBody("basic " + nick_ + " test.");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)1, eventController_->getEvents().size());
-
- message = Message::ref(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/otherperson"));
- message->setBody(nick_ + ": hi there");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)2, eventController_->getEvents().size());
-
- message->setFrom(JID(muc_->getJID().toString() + "/other"));
- message->setBody("Hi there " + nick_);
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)3, eventController_->getEvents().size());
-
- message = Message::ref(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/other2"));
- message->setBody("Hi " + boost::to_lower_copy(nick_) + ".");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
-
- message = Message::ref(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/other3"));
- message->setBody("Hi bert.");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
-
- message = Message::ref(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/other2"));
- message->setBody("Hi " + boost::to_lower_copy(nick_) + "ie.");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
- }
-
- void testNotAddressedToSelf() {
- finishJoin();
- Message::ref message(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/other3"));
- message->setBody("Hi there Hatter");
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size());
- }
-
- void testAddressedToSelfBySelf() {
- finishJoin();
- Message::ref message(new Message());
- message->setFrom(JID(muc_->getJID().toString() + "/" + nick_));
- message->setBody("Hi there " + nick_);
- message->setType(Message::Groupchat);
- controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
- CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size());
- }
-
- void testMessageWithEmptyLabelItem() {
- SecurityLabelsCatalog::Item label;
- label.setSelector("Bob");
- window_->label_ = label;
- boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
- features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
- controller_->setAvailableServerFeatures(features);
- IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
- SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
- labelPayload->addItem(label);
- IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
- iqChannel_->onIQReceived(result);
- std::string messageBody("agamemnon");
- window_->onSendMessageRequest(messageBody, false);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
- CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
- CPPUNIT_ASSERT(window_->labelsEnabled_);
- CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
- CPPUNIT_ASSERT(message);
- CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
- CPPUNIT_ASSERT(!message->getPayload<SecurityLabel>());
- }
-
- void testMessageWithLabelItem() {
- boost::shared_ptr<SecurityLabel> label = boost::make_shared<SecurityLabel>();
- label->setLabel("a");
- SecurityLabelsCatalog::Item labelItem;
- labelItem.setSelector("Bob");
- labelItem.setLabel(label);
- window_->label_ = labelItem;
- boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
- features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
- controller_->setAvailableServerFeatures(features);
- IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
- SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
- labelPayload->addItem(labelItem);
- IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
- iqChannel_->onIQReceived(result);
- std::string messageBody("agamemnon");
- window_->onSendMessageRequest(messageBody, false);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
- CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
- CPPUNIT_ASSERT(window_->labelsEnabled_);
- CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
- CPPUNIT_ASSERT(message);
- CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
- }
-
- void testCorrectMessageWithLabelItem() {
- boost::shared_ptr<SecurityLabel> label = boost::make_shared<SecurityLabel>();
- label->setLabel("a");
- SecurityLabelsCatalog::Item labelItem;
- labelItem.setSelector("Bob");
- labelItem.setLabel(label);
- boost::shared_ptr<SecurityLabel> label2 = boost::make_shared<SecurityLabel>();
- label->setLabel("b");
- SecurityLabelsCatalog::Item labelItem2;
- labelItem2.setSelector("Charlie");
- labelItem2.setLabel(label2);
- window_->label_ = labelItem;
- boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
- features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
- controller_->setAvailableServerFeatures(features);
- IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
- SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
- labelPayload->addItem(labelItem);
- IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
- iqChannel_->onIQReceived(result);
- std::string messageBody("agamemnon");
- window_->onSendMessageRequest(messageBody, false);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
- CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
- CPPUNIT_ASSERT(window_->labelsEnabled_);
- CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
- CPPUNIT_ASSERT(message);
- CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
- window_->label_ = labelItem2;
- window_->onSendMessageRequest(messageBody, true);
- rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- message = boost::dynamic_pointer_cast<Message>(rawStanza);
- CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
- }
-
- void checkEqual(const std::vector<NickJoinPart>& expected, const std::vector<NickJoinPart>& actual) {
- CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
- for (size_t i = 0; i < expected.size(); i++) {
- CPPUNIT_ASSERT_EQUAL(expected[i].nick, actual[i].nick);
- CPPUNIT_ASSERT_EQUAL(expected[i].type, actual[i].type);
- }
- }
-
- void testAppendToJoinParts() {
- std::vector<NickJoinPart> list;
- std::vector<NickJoinPart> gold;
- MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join));
- gold.push_back(NickJoinPart("Kev", Join));
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Remko", Join));
- gold.push_back(NickJoinPart("Remko", Join));
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Bert", Join));
- gold.push_back(NickJoinPart("Bert", Join));
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Bert", Part));
- gold[2].type = JoinThenPart;
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Kev", Part));
- gold[0].type = JoinThenPart;
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Remko", Part));
- gold[1].type = JoinThenPart;
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part));
- gold.push_back(NickJoinPart("Ernie", Part));
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Join));
- gold[3].type = PartThenJoin;
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join));
- gold[0].type = Join;
- checkEqual(gold, list);
- MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part));
- gold[3].type = Part;
- checkEqual(gold, list);
-
- }
-
- void testJoinPartStringContructionSimple() {
- std::vector<NickJoinPart> list;
- list.push_back(NickJoinPart("Kev", Join));
- CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room"), MUCController::generateJoinPartString(list, false));
- list.push_back(NickJoinPart("Remko", Part));
- CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false));
- list.push_back(NickJoinPart("Bert", Join));
- CPPUNIT_ASSERT_EQUAL(std::string("Kev and Bert have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false));
- 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) {
- 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) {
- /* 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);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::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 = boost::make_shared<Message>();
- message->setType(Message::Groupchat);
- message->setTo(self_);
- message->setFrom(mucJID_.withResource("SomeNickname"));
- message->setID(iqChannel_->getNewIQID());
- message->setSubject("New Room Subject");
-
- controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
- CPPUNIT_ASSERT_EQUAL(std::string("The room subject is now: New Room Subject"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
- }
- }
-
- /*
- * Test that message stanzas with subject element and non-empty body element do not cause a subject change.
- */
- void testSubjectChangeIncorrectA() {
- std::string messageBody("test message");
- window_->onSendMessageRequest(messageBody, false);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::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 = boost::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("Some body text that prevents this stanza from being a subject change.");
-
- controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
- CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
- }
- }
-
- /*
- * Test that message stanzas with subject element and thread element do not cause a subject change.
- */
- void testSubjectChangeIncorrectB() {
- std::string messageBody("test message");
- window_->onSendMessageRequest(messageBody, false);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::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 = boost::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->addPayload(boost::make_shared<Thread>("Thread that prevents the subject change."));
-
- controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
- CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
- }
- }
-
- /*
- * 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);
- boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
- Message::ref message = boost::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 = boost::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(boost::make_shared<MessageEvent>(message));
- CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::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()) {
- GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(rosterItem);
- CPPUNIT_ASSERT(child);
- foreach(RosterItem* 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());
- }
- }
- }
+ void setUp() {
+ crypto_ = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ self_ = JID("girl@wonderland.lit/rabbithole");
+ nick_ = "aLiCe";
+ mucJID_ = JID("teaparty@rooms.wonderland.lit");
+ mocks_ = new MockRepository();
+ stanzaChannel_ = new DummyStanzaChannel();
+ iqChannel_ = new DummyIQChannel();
+ iqRouter_ = new IQRouter(iqChannel_);
+ eventController_ = new EventController();
+ chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
+ userSearchWindowFactory_ = mocks_->InterfaceMock<UserSearchWindowFactory>();
+ xmppRoster_ = new XMPPRosterImpl();
+ presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
+ presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
+ directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
+ uiEventStream_ = new UIEventStream();
+ avatarManager_ = new NullAvatarManager();
+ TimerFactory* timerFactory = NULL;
+ window_ = new MockChatWindow();
+ mucRegistry_ = new MUCRegistry();
+ entityCapsProvider_ = new DummyEntityCapsProvider();
+ settings_ = new DummySettingsProvider();
+ highlightManager_ = new HighlightManager(settings_);
+ muc_ = boost::make_shared<MockMUC>(mucJID_);
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc_->getJID(), uiEventStream_).Return(window_);
+ chatMessageParser_ = boost::make_shared<ChatMessageParser>(std::map<std::string, std::string>(), highlightManager_->getRules(), true);
+ vcardStorage_ = new VCardMemoryStorage(crypto_.get());
+ vcardManager_ = new VCardManager(self_, iqRouter_, vcardStorage_);
+ clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
+ mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_);
+ controller_ = new MUCController (self_, muc_, boost::optional<std::string>(), nick_, stanzaChannel_, iqRouter_, chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory, eventController_, entityCapsProvider_, NULL, NULL, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser_, false, NULL, vcardManager_, mucBookmarkManager_);
+ }
+
+ void tearDown() {
+ delete controller_;
+ delete mucBookmarkManager_;
+ delete clientBlockListManager_;
+ delete vcardManager_;
+ delete vcardStorage_;
+ delete highlightManager_;
+ delete settings_;
+ delete entityCapsProvider_;
+ delete eventController_;
+ delete presenceOracle_;
+ delete xmppRoster_;
+ delete mocks_;
+ delete uiEventStream_;
+ delete stanzaChannel_;
+ delete presenceSender_;
+ delete directedPresenceSender_;
+ delete iqRouter_;
+ delete iqChannel_;
+ delete mucRegistry_;
+ delete avatarManager_;
+ }
+
+ void finishJoin() {
+ Presence::ref presence(new Presence());
+ presence->setFrom(JID(muc_->getJID().toString() + "/" + nick_));
+ MUCUserPayload::ref status(new MUCUserPayload());
+ MUCUserPayload::StatusCode code;
+ code.code = 110;
+ status->addStatusCode(code);
+ presence->addPayload(status);
+ stanzaChannel_->onPresenceReceived(presence);
+ }
+
+ void testAddressedToSelf() {
+ finishJoin();
+ Message::ref message(new Message());
+
+ message = Message::ref(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/otherperson"));
+ message->setBody("basic " + nick_ + " test.");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)1, eventController_->getEvents().size());
+
+ message = Message::ref(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/otherperson"));
+ message->setBody(nick_ + ": hi there");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)2, eventController_->getEvents().size());
+
+ message->setFrom(JID(muc_->getJID().toString() + "/other"));
+ message->setBody("Hi there " + nick_);
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)3, eventController_->getEvents().size());
+
+ message = Message::ref(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/other2"));
+ message->setBody("Hi " + boost::to_lower_copy(nick_) + ".");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
+
+ message = Message::ref(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/other3"));
+ message->setBody("Hi bert.");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
+
+ message = Message::ref(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/other2"));
+ message->setBody("Hi " + boost::to_lower_copy(nick_) + "ie.");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size());
+ }
+
+ void testNotAddressedToSelf() {
+ finishJoin();
+ Message::ref message(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/other3"));
+ message->setBody("Hi there Hatter");
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size());
+ }
+
+ void testAddressedToSelfBySelf() {
+ finishJoin();
+ Message::ref message(new Message());
+ message->setFrom(JID(muc_->getJID().toString() + "/" + nick_));
+ message->setBody("Hi there " + nick_);
+ message->setType(Message::Groupchat);
+ controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message)));
+ CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size());
+ }
+
+ void testMessageWithEmptyLabelItem() {
+ SecurityLabelsCatalog::Item label;
+ label.setSelector("Bob");
+ window_->label_ = label;
+ boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
+ labelPayload->addItem(label);
+ IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
+ iqChannel_->onIQReceived(result);
+ std::string messageBody("agamemnon");
+ window_->onSendMessageRequest(messageBody, false);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
+ CPPUNIT_ASSERT(window_->labelsEnabled_);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
+ CPPUNIT_ASSERT(!message->getPayload<SecurityLabel>());
+ }
+
+ void testMessageWithLabelItem() {
+ boost::shared_ptr<SecurityLabel> label = boost::make_shared<SecurityLabel>();
+ label->setLabel("a");
+ SecurityLabelsCatalog::Item labelItem;
+ labelItem.setSelector("Bob");
+ labelItem.setLabel(label);
+ window_->label_ = labelItem;
+ boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
+ labelPayload->addItem(labelItem);
+ IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
+ iqChannel_->onIQReceived(result);
+ std::string messageBody("agamemnon");
+ window_->onSendMessageRequest(messageBody, false);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
+ CPPUNIT_ASSERT(window_->labelsEnabled_);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
+ }
+
+ void testCorrectMessageWithLabelItem() {
+ boost::shared_ptr<SecurityLabel> label = boost::make_shared<SecurityLabel>();
+ label->setLabel("a");
+ SecurityLabelsCatalog::Item labelItem;
+ labelItem.setSelector("Bob");
+ labelItem.setLabel(label);
+ boost::shared_ptr<SecurityLabel> label2 = boost::make_shared<SecurityLabel>();
+ label->setLabel("b");
+ SecurityLabelsCatalog::Item labelItem2;
+ labelItem2.setSelector("Charlie");
+ labelItem2.setLabel(label2);
+ window_->label_ = labelItem;
+ boost::shared_ptr<DiscoInfo> features = boost::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = boost::make_shared<SecurityLabelsCatalog>();
+ labelPayload->addItem(labelItem);
+ IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload);
+ iqChannel_->onIQReceived(result);
+ std::string messageBody("agamemnon");
+ window_->onSendMessageRequest(messageBody, false);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom());
+ CPPUNIT_ASSERT(window_->labelsEnabled_);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
+ window_->label_ = labelItem2;
+ window_->onSendMessageRequest(messageBody, true);
+ rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ message = boost::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(label, message->getPayload<SecurityLabel>());
+ }
+
+ void checkEqual(const std::vector<NickJoinPart>& expected, const std::vector<NickJoinPart>& actual) {
+ CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ CPPUNIT_ASSERT_EQUAL(expected[i].nick, actual[i].nick);
+ CPPUNIT_ASSERT_EQUAL(expected[i].type, actual[i].type);
+ }
+ }
+
+ void testAppendToJoinParts() {
+ std::vector<NickJoinPart> list;
+ std::vector<NickJoinPart> gold;
+ MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join));
+ gold.push_back(NickJoinPart("Kev", Join));
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Remko", Join));
+ gold.push_back(NickJoinPart("Remko", Join));
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Bert", Join));
+ gold.push_back(NickJoinPart("Bert", Join));
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Bert", Part));
+ gold[2].type = JoinThenPart;
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Kev", Part));
+ gold[0].type = JoinThenPart;
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Remko", Part));
+ gold[1].type = JoinThenPart;
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part));
+ gold.push_back(NickJoinPart("Ernie", Part));
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Join));
+ gold[3].type = PartThenJoin;
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join));
+ gold[0].type = Join;
+ checkEqual(gold, list);
+ MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part));
+ gold[3].type = Part;
+ checkEqual(gold, list);
+
+ }
+
+ void testJoinPartStringContructionSimple() {
+ std::vector<NickJoinPart> list;
+ list.push_back(NickJoinPart("Kev", Join));
+ CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room"), MUCController::generateJoinPartString(list, false));
+ list.push_back(NickJoinPart("Remko", Part));
+ CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false));
+ list.push_back(NickJoinPart("Bert", Join));
+ CPPUNIT_ASSERT_EQUAL(std::string("Kev and Bert have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false));
+ 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) {
+ 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) {
+ /* 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);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::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 = boost::make_shared<Message>();
+ message->setType(Message::Groupchat);
+ message->setTo(self_);
+ message->setFrom(mucJID_.withResource("SomeNickname"));
+ message->setID(iqChannel_->getNewIQID());
+ message->setSubject("New Room Subject");
+
+ controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("The room subject is now: New Room Subject"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ /*
+ * Test that message stanzas with subject element and non-empty body element do not cause a subject change.
+ */
+ void testSubjectChangeIncorrectA() {
+ std::string messageBody("test message");
+ window_->onSendMessageRequest(messageBody, false);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::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 = boost::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("Some body text that prevents this stanza from being a subject change.");
+
+ controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ /*
+ * Test that message stanzas with subject element and thread element do not cause a subject change.
+ */
+ void testSubjectChangeIncorrectB() {
+ std::string messageBody("test message");
+ window_->onSendMessageRequest(messageBody, false);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::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 = boost::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->addPayload(boost::make_shared<Thread>("Thread that prevents the subject change."));
+
+ controller_->handleIncomingMessage(boost::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ /*
+ * 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);
+ boost::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = boost::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 = boost::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(boost::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::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()) {
+ GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(rosterItem);
+ CPPUNIT_ASSERT(child);
+ foreach(RosterItem* 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_;
- MUCRegistry* mucRegistry_;
- DummyEntityCapsProvider* entityCapsProvider_;
- DummySettingsProvider* settings_;
- HighlightManager* highlightManager_;
- boost::shared_ptr<ChatMessageParser> chatMessageParser_;
- boost::shared_ptr<CryptoProvider> crypto_;
- VCardManager* vcardManager_;
- VCardMemoryStorage* vcardStorage_;
- ClientBlockListManager* clientBlockListManager_;
- MUCBookmarkManager* mucBookmarkManager_;
- XMPPRoster* xmppRoster_;
+ 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_;
+ MUCRegistry* mucRegistry_;
+ DummyEntityCapsProvider* entityCapsProvider_;
+ DummySettingsProvider* settings_;
+ HighlightManager* highlightManager_;
+ boost::shared_ptr<ChatMessageParser> chatMessageParser_;
+ boost::shared_ptr<CryptoProvider> crypto_;
+ VCardManager* vcardManager_;
+ VCardMemoryStorage* vcardStorage_;
+ ClientBlockListManager* clientBlockListManager_;
+ MUCBookmarkManager* mucBookmarkManager_;
+ XMPPRoster* xmppRoster_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MUCControllerTest);
diff --git a/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h b/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h
index 0754749..395b050 100644
--- a/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h
+++ b/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h
@@ -10,19 +10,19 @@
namespace Swift {
- class MockChatListWindow : public ChatListWindow {
- public:
- MockChatListWindow() {}
- virtual ~MockChatListWindow() {}
- void addMUCBookmark(const MUCBookmark& /*bookmark*/) {}
- void removeMUCBookmark(const MUCBookmark& /*bookmark*/) {}
- void addWhiteboardSession(const ChatListWindow::Chat& /*chat*/) {}
- void removeWhiteboardSession(const JID& /*jid*/) {}
- void setBookmarksEnabled(bool /*enabled*/) {}
- void setRecents(const std::list<ChatListWindow::Chat>& /*recents*/) {}
- void setUnreadCount(int /*unread*/) {}
- void clearBookmarks() {}
- void setOnline(bool /*isOnline*/) {}
- };
+ class MockChatListWindow : public ChatListWindow {
+ public:
+ MockChatListWindow() {}
+ virtual ~MockChatListWindow() {}
+ void addMUCBookmark(const MUCBookmark& /*bookmark*/) {}
+ void removeMUCBookmark(const MUCBookmark& /*bookmark*/) {}
+ void addWhiteboardSession(const ChatListWindow::Chat& /*chat*/) {}
+ void removeWhiteboardSession(const JID& /*jid*/) {}
+ void setBookmarksEnabled(bool /*enabled*/) {}
+ void setRecents(const std::list<ChatListWindow::Chat>& /*recents*/) {}
+ void setUnreadCount(int /*unread*/) {}
+ void clearBookmarks() {}
+ void setOnline(bool /*isOnline*/) {}
+ };
}
diff --git a/Swift/Controllers/Chat/UserSearchController.cpp b/Swift/Controllers/Chat/UserSearchController.cpp
index e08912a..216488a 100644
--- a/Swift/Controllers/Chat/UserSearchController.cpp
+++ b/Swift/Controllers/Chat/UserSearchController.cpp
@@ -36,357 +36,357 @@ 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_ = NULL;
- discoWalker_ = NULL;
- loadSavedDirectories();
+ 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_ = NULL;
+ discoWalker_ = NULL;
+ loadSavedDirectories();
}
UserSearchController::~UserSearchController() {
- endDiscoWalker();
- delete discoWalker_;
- if (window_) {
- window_->onNameSuggestionRequested.disconnect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1));
- window_->onFormRequested.disconnect(boost::bind(&UserSearchController::handleFormRequested, this, _1));
- window_->onSearchRequested.disconnect(boost::bind(&UserSearchController::handleSearch, this, _1, _2));
- window_->onContactSuggestionsRequested.disconnect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1));
- window_->onJIDUpdateRequested.disconnect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1));
- window_->onJIDAddRequested.disconnect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1));
- window_->onJIDEditFieldChanged.disconnect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1));
- delete window_;
- }
- presenceOracle_->onPresenceChange.disconnect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1));
- avatarManager_->onAvatarChanged.disconnect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1));
- vcardManager_->onVCardChanged.disconnect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2));
- uiEventStream_->onUIEvent.disconnect(boost::bind(&UserSearchController::handleUIEvent, this, _1));
+ endDiscoWalker();
+ delete discoWalker_;
+ if (window_) {
+ window_->onNameSuggestionRequested.disconnect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1));
+ window_->onFormRequested.disconnect(boost::bind(&UserSearchController::handleFormRequested, this, _1));
+ window_->onSearchRequested.disconnect(boost::bind(&UserSearchController::handleSearch, this, _1, _2));
+ window_->onContactSuggestionsRequested.disconnect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1));
+ window_->onJIDUpdateRequested.disconnect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1));
+ window_->onJIDAddRequested.disconnect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1));
+ window_->onJIDEditFieldChanged.disconnect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1));
+ delete window_;
+ }
+ presenceOracle_->onPresenceChange.disconnect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1));
+ avatarManager_->onAvatarChanged.disconnect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1));
+ vcardManager_->onVCardChanged.disconnect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2));
+ uiEventStream_->onUIEvent.disconnect(boost::bind(&UserSearchController::handleUIEvent, this, _1));
}
UserSearchWindow* UserSearchController::getUserSearchWindow() {
- initializeUserWindow();
- assert(window_);
- return window_;
+ initializeUserWindow();
+ assert(window_);
+ return window_;
}
void UserSearchController::setCanInitiateImpromptuMUC(bool supportsImpromptu) {
- if (!window_) {
- initializeUserWindow();
- }
- if (window_) {
- window_->setCanStartImpromptuChats(supportsImpromptu);
- } // Else doesn't support search
+ if (!window_) {
+ initializeUserWindow();
+ }
+ if (window_) {
+ window_->setCanStartImpromptuChats(supportsImpromptu);
+ } // Else doesn't support search
}
void UserSearchController::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- bool handle = false;
- boost::shared_ptr<RequestAddUserDialogUIEvent> addUserRequest = boost::shared_ptr<RequestAddUserDialogUIEvent>();
- RequestInviteToMUCUIEvent::ref inviteToMUCRequest = RequestInviteToMUCUIEvent::ref();
- switch (type_) {
- case AddContact:
- if ((addUserRequest = boost::dynamic_pointer_cast<RequestAddUserDialogUIEvent>(event))) {
- handle = true;
- }
- break;
- case StartChat:
- if (boost::dynamic_pointer_cast<RequestChatWithUserDialogUIEvent>(event)) {
- handle = true;
- }
- break;
- case InviteToChat:
- if ((inviteToMUCRequest = boost::dynamic_pointer_cast<RequestInviteToMUCUIEvent>(event))) {
- handle = true;
- }
- break;
- }
- if (handle) {
- initializeUserWindow();
- window_->show();
- window_->addSavedServices(savedDirectories_);
- if (addUserRequest) {
- const std::string& name = addUserRequest->getPredefinedName();
- const JID& jid = addUserRequest->getPredefinedJID();
- if (!name.empty() && jid.isValid()) {
- window_->prepopulateJIDAndName(jid, name);
- }
- } else if (inviteToMUCRequest) {
- window_->setCanSupplyDescription(!inviteToMUCRequest->isImpromptu());
- window_->setJIDs(inviteToMUCRequest->getInvites());
- window_->setRoomJID(inviteToMUCRequest->getRoom());
- }
- return;
- }
+ bool handle = false;
+ boost::shared_ptr<RequestAddUserDialogUIEvent> addUserRequest = boost::shared_ptr<RequestAddUserDialogUIEvent>();
+ RequestInviteToMUCUIEvent::ref inviteToMUCRequest = RequestInviteToMUCUIEvent::ref();
+ switch (type_) {
+ case AddContact:
+ if ((addUserRequest = boost::dynamic_pointer_cast<RequestAddUserDialogUIEvent>(event))) {
+ handle = true;
+ }
+ break;
+ case StartChat:
+ if (boost::dynamic_pointer_cast<RequestChatWithUserDialogUIEvent>(event)) {
+ handle = true;
+ }
+ break;
+ case InviteToChat:
+ if ((inviteToMUCRequest = boost::dynamic_pointer_cast<RequestInviteToMUCUIEvent>(event))) {
+ handle = true;
+ }
+ break;
+ }
+ if (handle) {
+ initializeUserWindow();
+ window_->show();
+ window_->addSavedServices(savedDirectories_);
+ if (addUserRequest) {
+ const std::string& name = addUserRequest->getPredefinedName();
+ const JID& jid = addUserRequest->getPredefinedJID();
+ if (!name.empty() && jid.isValid()) {
+ window_->prepopulateJIDAndName(jid, name);
+ }
+ } else if (inviteToMUCRequest) {
+ window_->setCanSupplyDescription(!inviteToMUCRequest->isImpromptu());
+ window_->setJIDs(inviteToMUCRequest->getInvites());
+ 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();
+ 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));
- }
+ 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, boost::shared_ptr<DiscoInfo> info) {
- //bool isUserDirectory = false;
- bool supports55 = false;
- foreach (DiscoInfo::Identity 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();
- boost::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, boost::make_shared<SearchPayload>(), iqRouter_));
- searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2));
- searchRequest->send();
- }
+ //bool isUserDirectory = false;
+ bool supports55 = false;
+ foreach (DiscoInfo::Identity 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();
+ boost::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, boost::make_shared<SearchPayload>(), iqRouter_));
+ searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2));
+ searchRequest->send();
+ }
}
void UserSearchController::handleFormResponse(boost::shared_ptr<SearchPayload> fields, ErrorPayload::ref error) {
- if (error || !fields) {
- window_->setServerSupportsSearch(false);
- return;
- }
- window_->setSearchFields(fields);
+ if (error || !fields) {
+ window_->setServerSupportsSearch(false);
+ return;
+ }
+ window_->setSearchFields(fields);
}
void UserSearchController::handleSearch(boost::shared_ptr<SearchPayload> fields, const JID& jid) {
- addToSavedDirectories(jid);
- boost::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();
+ addToSavedDirectories(jid);
+ boost::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(boost::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()) {
- 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);
- }
+ 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()) {
+ 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);
- }
+ 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."));
- }
+ 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) {
- 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);
+ 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) {
+ 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));
+ 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));
+ handleJIDUpdateRequested(std::vector<JID>(1, jid));
}
void UserSearchController::handlePresenceChanged(Presence::ref presence) {
- handleJIDUpdateRequested(std::vector<JID>(1, presence->getFrom().toBare()));
+ 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) {
- updates.push_back(convertJIDtoContact(jid));
- }
- window_->updateContacts(updates);
- }
+ if (window_) {
+ std::vector<Contact::ref> updates;
+ foreach(const JID& 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) {
- contacts.push_back(convertJIDtoContact(jid));
- }
- window_->addContacts(contacts);
+ std::vector<Contact::ref> contacts;
+ foreach(const JID& jid, jids) {
+ contacts.push_back(convertJIDtoContact(jid));
+ }
+ window_->addContacts(contacts);
}
Contact::ref UserSearchController::convertJIDtoContact(const JID& jid) {
- Contact::ref contact = boost::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;
- }
-
- // avatar lookup
- contact->avatarPath = avatarManager_->getAvatarPath(jid);
- return contact;
+ Contact::ref contact = boost::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;
+ }
+
+ // avatar lookup
+ contact->avatarPath = avatarManager_->getAvatarPath(jid);
+ return contact;
}
void UserSearchController::handleDiscoWalkFinished() {
- window_->setServerSupportsSearch(false);
- endDiscoWalker();
+ window_->setServerSupportsSearch(false);
+ endDiscoWalker();
}
void UserSearchController::initializeUserWindow() {
- if (!window_) {
- UserSearchWindow::Type windowType = UserSearchWindow::AddContact;
- switch(type_) {
- 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();
- }
+ if (!window_) {
+ UserSearchWindow::Type windowType = UserSearchWindow::AddContact;
+ switch(type_) {
+ 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')) {
- if(!stringItem.empty()) {
- savedDirectories_.push_back(JID(stringItem));
- }
- }
+ savedDirectories_.clear();
+ foreach (std::string 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_) {
- if (i >= 15) {
- break;
- }
- if (!collapsed.empty()) {
- collapsed += "\n";
- }
- collapsed += jidItem.toString();
- ++i;
- }
- settings_->storeString(SEARCHED_DIRECTORIES, collapsed);
- window_->addSavedServices(savedDirectories_);
+ 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_) {
+ 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/Chat/UserSearchController.h b/Swift/Controllers/Chat/UserSearchController.h
index 0423a65..71b8331 100644
--- a/Swift/Controllers/Chat/UserSearchController.h
+++ b/Swift/Controllers/Chat/UserSearchController.h
@@ -24,76 +24,76 @@
#include <Swift/Controllers/Contact.h>
namespace Swift {
- class UIEventStream;
- class UIEvent;
- class UserSearchWindow;
- class UserSearchWindowFactory;
- class IQRouter;
- class DiscoServiceWalker;
- class RosterController;
- class VCardManager;
- class ContactSuggester;
- class AvatarManager;
- class PresenceOracle;
- class ProfileSettingsProvider;
+ class UIEventStream;
+ class UIEvent;
+ class UserSearchWindow;
+ class UserSearchWindowFactory;
+ class IQRouter;
+ class DiscoServiceWalker;
+ class RosterController;
+ class VCardManager;
+ class ContactSuggester;
+ class AvatarManager;
+ class PresenceOracle;
+ class ProfileSettingsProvider;
- class UserSearchResult {
- public:
- UserSearchResult(const JID& jid, const std::map<std::string, std::string>& fields) : jid_(jid), fields_(fields) {}
- const JID& getJID() const {return jid_;}
- const std::map<std::string, std::string>& getFields() const {return fields_;}
- private:
- JID jid_;
- std::map<std::string, std::string> fields_;
- };
+ class UserSearchResult {
+ public:
+ UserSearchResult(const JID& jid, const std::map<std::string, std::string>& fields) : jid_(jid), fields_(fields) {}
+ const JID& getJID() const {return jid_;}
+ const std::map<std::string, std::string>& getFields() const {return fields_;}
+ private:
+ JID jid_;
+ std::map<std::string, std::string> fields_;
+ };
- class UserSearchController {
- public:
- enum Type {AddContact, StartChat, InviteToChat};
- UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* userSearchWindowFactory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings);
- ~UserSearchController();
+ class UserSearchController {
+ public:
+ enum Type {AddContact, StartChat, InviteToChat};
+ UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* userSearchWindowFactory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings);
+ ~UserSearchController();
- UserSearchWindow* getUserSearchWindow();
- void setCanInitiateImpromptuMUC(bool supportsImpromptu);
+ UserSearchWindow* getUserSearchWindow();
+ void setCanInitiateImpromptuMUC(bool supportsImpromptu);
- private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleFormRequested(const JID& service);
- void handleDiscoServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> info);
- void handleDiscoWalkFinished();
- void handleFormResponse(boost::shared_ptr<SearchPayload> items, ErrorPayload::ref error);
- void handleSearch(boost::shared_ptr<SearchPayload> fields, const JID& jid);
- void handleSearchResponse(boost::shared_ptr<SearchPayload> results, ErrorPayload::ref error);
- void handleNameSuggestionRequest(const JID& jid);
- void handleContactSuggestionsRequested(std::string text);
- void handleVCardChanged(const JID& jid, VCard::ref vcard);
- void handleAvatarChanged(const JID& jid);
- void handlePresenceChanged(Presence::ref presence);
- void handleJIDUpdateRequested(const std::vector<JID>& jids);
- void handleJIDAddRequested(const std::vector<JID>& jids);
- void handleJIDEditingFinished(const JID& jid);
- Contact::ref convertJIDtoContact(const JID& jid);
- void endDiscoWalker();
- void initializeUserWindow();
+ private:
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleFormRequested(const JID& service);
+ void handleDiscoServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> info);
+ void handleDiscoWalkFinished();
+ void handleFormResponse(boost::shared_ptr<SearchPayload> items, ErrorPayload::ref error);
+ void handleSearch(boost::shared_ptr<SearchPayload> fields, const JID& jid);
+ void handleSearchResponse(boost::shared_ptr<SearchPayload> results, ErrorPayload::ref error);
+ void handleNameSuggestionRequest(const JID& jid);
+ void handleContactSuggestionsRequested(std::string text);
+ void handleVCardChanged(const JID& jid, VCard::ref vcard);
+ void handleAvatarChanged(const JID& jid);
+ void handlePresenceChanged(Presence::ref presence);
+ void handleJIDUpdateRequested(const std::vector<JID>& jids);
+ void handleJIDAddRequested(const std::vector<JID>& jids);
+ void handleJIDEditingFinished(const JID& jid);
+ Contact::ref convertJIDtoContact(const JID& jid);
+ void endDiscoWalker();
+ void initializeUserWindow();
- void loadSavedDirectories();
- void addToSavedDirectories(const JID& jid);
+ void loadSavedDirectories();
+ void addToSavedDirectories(const JID& jid);
- private:
- Type type_;
- JID jid_;
- JID suggestionsJID_;
- UIEventStream* uiEventStream_;
- VCardManager* vcardManager_;
- UserSearchWindowFactory* factory_;
- IQRouter* iqRouter_;
- RosterController* rosterController_;
- UserSearchWindow* window_;
- DiscoServiceWalker* discoWalker_;
- ContactSuggester* contactSuggester_;
- AvatarManager* avatarManager_;
- PresenceOracle* presenceOracle_;
- std::vector<JID> savedDirectories_;
- ProfileSettingsProvider* settings_;
- };
+ private:
+ Type type_;
+ JID jid_;
+ JID suggestionsJID_;
+ UIEventStream* uiEventStream_;
+ VCardManager* vcardManager_;
+ UserSearchWindowFactory* factory_;
+ IQRouter* iqRouter_;
+ RosterController* rosterController_;
+ UserSearchWindow* window_;
+ DiscoServiceWalker* discoWalker_;
+ ContactSuggester* contactSuggester_;
+ AvatarManager* avatarManager_;
+ PresenceOracle* presenceOracle_;
+ std::vector<JID> savedDirectories_;
+ ProfileSettingsProvider* settings_;
+ };
}
diff --git a/Swift/Controllers/ChatMessageSummarizer.cpp b/Swift/Controllers/ChatMessageSummarizer.cpp
index a0ae6d1..6b630e7 100644
--- a/Swift/Controllers/ChatMessageSummarizer.cpp
+++ b/Swift/Controllers/ChatMessageSummarizer.cpp
@@ -15,32 +15,32 @@ 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) {
- if (unread.first == current) {
- currentUnread += unread.second;
- } else {
- if (unread.second > 0) {
- otherCount += unread.second;
- others.push_back(unread);
- }
- }
- }
- string myString(current);
+ vector<UnreadPair> others;
+ int currentUnread = 0;
+ int otherCount = 0;
+ foreach (UnreadPair 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 (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;
+ 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/ChatMessageSummarizer.h b/Swift/Controllers/ChatMessageSummarizer.h
index 9ed867d..0b4df21 100644
--- a/Swift/Controllers/ChatMessageSummarizer.h
+++ b/Swift/Controllers/ChatMessageSummarizer.h
@@ -13,8 +13,8 @@
namespace Swift {
typedef std::pair<std::string, int> UnreadPair;
- class ChatMessageSummarizer {
- public:
- std::string getSummary(const std::string& current, const std::vector<UnreadPair>& unreads);
- };
+ class ChatMessageSummarizer {
+ public:
+ std::string getSummary(const std::string& current, const std::vector<UnreadPair>& unreads);
+ };
}
diff --git a/Swift/Controllers/ConnectionSettings.h b/Swift/Controllers/ConnectionSettings.h
index 6a2fded..7ce45cd 100644
--- a/Swift/Controllers/ConnectionSettings.h
+++ b/Swift/Controllers/ConnectionSettings.h
@@ -9,32 +9,32 @@
#include <string>
struct ConnectionSettings {
- enum Method {
- Automatic,
- Manual,
- BOSH
- };
- enum ProxyType {
- None,
- System,
- SOCKS5,
- HTTPConnect
- };
+ enum Method {
+ Automatic,
+ Manual,
+ BOSH
+ };
+ enum ProxyType {
+ None,
+ System,
+ SOCKS5,
+ HTTPConnect
+ };
- Method method;
- struct {
- bool useManualServer;
- std::string manualServerHostname;
- int manualServerPort;
- ProxyType proxyType;
- bool useManualProxy;
- std::string manualProxyHostname;
- int manualProxyPort;
- } manualSettings;
- struct {
- std::string boshURI;
- bool useManualProxy;
- std::string manualProxyHostname;
- int manualProxyPort;
- } boshSettings;
+ Method method;
+ struct {
+ bool useManualServer;
+ std::string manualServerHostname;
+ int manualServerPort;
+ ProxyType proxyType;
+ bool useManualProxy;
+ std::string manualProxyHostname;
+ int manualProxyPort;
+ } manualSettings;
+ struct {
+ std::string boshURI;
+ bool useManualProxy;
+ std::string manualProxyHostname;
+ int manualProxyPort;
+ } boshSettings;
};
diff --git a/Swift/Controllers/Contact.cpp b/Swift/Controllers/Contact.cpp
index bda1239..b9b98c3 100644
--- a/Swift/Controllers/Contact.cpp
+++ b/Swift/Controllers/Contact.cpp
@@ -24,54 +24,54 @@ Contact::Contact(const std::string& name, const JID& jid, StatusShow::Type statu
}
bool Contact::lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b) {
- if (a->jid.isValid() && b->jid.isValid()) {
- return a->jid < b->jid;
- } else {
- return a->name < b->name;
- }
+ if (a->jid.isValid() && b->jid.isValid()) {
+ return a->jid < b->jid;
+ } else {
+ return a->name < b->name;
+ }
}
bool Contact::equalityPredicate(const Contact::ref& a, const Contact::ref& b) {
- if (a->jid.isValid() && b->jid.isValid()) {
- return a->jid == b->jid;
- } else {
- return a->name == b->name;
- }
+ if (a->jid.isValid() && b->jid.isValid()) {
+ return a->jid == b->jid;
+ } else {
+ return a->name == b->name;
+ }
}
bool Contact::sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search) {
- /* perform case insensitive comparisons */
- std::string aLower = a->name;
- boost::to_lower(aLower);
- std::string bLower = b->name;
- boost::to_lower(bLower);
- std::string searchLower = search;
- boost::to_lower(searchLower);
+ /* perform case insensitive comparisons */
+ std::string aLower = a->name;
+ boost::to_lower(aLower);
+ std::string bLower = b->name;
+ boost::to_lower(bLower);
+ std::string searchLower = search;
+ boost::to_lower(searchLower);
- /* name starts with the search term */
- if (aLower.find(searchLower) == 0 && bLower.find(searchLower) != 0) {
- return true;
- } else if (bLower.find(searchLower) == 0 && aLower.find(searchLower) != 0) {
- return false;
- }
+ /* name starts with the search term */
+ if (aLower.find(searchLower) == 0 && bLower.find(searchLower) != 0) {
+ return true;
+ } else if (bLower.find(searchLower) == 0 && aLower.find(searchLower) != 0) {
+ return false;
+ }
- /* name contains search term */
- if (aLower.find(searchLower) != std::string::npos && bLower.find(searchLower) == std::string::npos) {
- return true;
- } else if (bLower.find(searchLower) != std::string::npos && aLower.find(searchLower) == std::string::npos) {
- return false;
- }
+ /* name contains search term */
+ if (aLower.find(searchLower) != std::string::npos && bLower.find(searchLower) == std::string::npos) {
+ return true;
+ } else if (bLower.find(searchLower) != std::string::npos && aLower.find(searchLower) == std::string::npos) {
+ return false;
+ }
- /* Levenshtein should be done here */
- /* if edit distances are equal, fall through to the tests below */
+ /* Levenshtein should be done here */
+ /* if edit distances are equal, fall through to the tests below */
- /* lexicographical sort */
- if (a->statusType == b->statusType) {
- return aLower.compare(bLower) < 0;
- }
+ /* lexicographical sort */
+ if (a->statusType == b->statusType) {
+ return aLower.compare(bLower) < 0;
+ }
- /* online status */
- return a->statusType < b->statusType;
+ /* online status */
+ return a->statusType < b->statusType;
}
}
diff --git a/Swift/Controllers/Contact.h b/Swift/Controllers/Contact.h
index b03a118..4aa6999 100644
--- a/Swift/Controllers/Contact.h
+++ b/Swift/Controllers/Contact.h
@@ -21,21 +21,21 @@
namespace Swift {
class Contact : public boost::enable_shared_from_this<Contact> {
- public:
- typedef boost::shared_ptr<Contact> ref;
+ public:
+ typedef boost::shared_ptr<Contact> ref;
- Contact();
- Contact(const std::string& name, const JID& jid, StatusShow::Type statusType, const boost::filesystem::path& path);
+ Contact();
+ Contact(const std::string& name, const JID& jid, StatusShow::Type statusType, const boost::filesystem::path& path);
- static bool lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b);
- static bool equalityPredicate(const Contact::ref& a, const Contact::ref& b);
- static bool sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search);
+ static bool lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b);
+ static bool equalityPredicate(const Contact::ref& a, const Contact::ref& b);
+ static bool sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search);
- public:
- std::string name;
- JID jid;
- StatusShow::Type statusType;
- boost::filesystem::path avatarPath;
+ public:
+ std::string name;
+ JID jid;
+ StatusShow::Type statusType;
+ boost::filesystem::path avatarPath;
};
}
diff --git a/Swift/Controllers/ContactEditController.cpp b/Swift/Controllers/ContactEditController.cpp
index 704e3bc..734ef79 100644
--- a/Swift/Controllers/ContactEditController.cpp
+++ b/Swift/Controllers/ContactEditController.cpp
@@ -21,89 +21,89 @@
namespace Swift {
ContactEditController::ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream) : rosterController(rosterController), vcardManager(vcardManager), contactEditWindowFactory(contactEditWindowFactory), uiEventStream(uiEventStream), contactEditWindow(NULL) {
- uiEventStream->onUIEvent.connect(boost::bind(&ContactEditController::handleUIEvent, this, _1));
- vcardManager->onVCardChanged.connect(boost::bind(&ContactEditController::handleVCardChanged, this, _1, _2));
+ uiEventStream->onUIEvent.connect(boost::bind(&ContactEditController::handleUIEvent, this, _1));
+ vcardManager->onVCardChanged.connect(boost::bind(&ContactEditController::handleVCardChanged, this, _1, _2));
}
ContactEditController::~ContactEditController() {
- if (contactEditWindow) {
- contactEditWindow->onChangeContactRequest.disconnect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2));
- contactEditWindow->onRemoveContactRequest.disconnect(boost::bind(&ContactEditController::handleRemoveContactRequest, this));
- delete contactEditWindow;
- }
- uiEventStream->onUIEvent.disconnect(boost::bind(&ContactEditController::handleUIEvent, this, _1));
+ if (contactEditWindow) {
+ contactEditWindow->onChangeContactRequest.disconnect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2));
+ contactEditWindow->onRemoveContactRequest.disconnect(boost::bind(&ContactEditController::handleRemoveContactRequest, this));
+ delete contactEditWindow;
+ }
+ uiEventStream->onUIEvent.disconnect(boost::bind(&ContactEditController::handleUIEvent, this, _1));
}
void ContactEditController::handleUIEvent(UIEvent::ref event) {
- RequestContactEditorUIEvent::ref editEvent = boost::dynamic_pointer_cast<RequestContactEditorUIEvent>(event);
- if (!editEvent) {
- return;
- }
-
- if (!contactEditWindow) {
- contactEditWindow = contactEditWindowFactory->createContactEditWindow();
- contactEditWindow->onRemoveContactRequest.connect(boost::bind(&ContactEditController::handleRemoveContactRequest, this));
- contactEditWindow->onChangeContactRequest.connect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2));
- }
- currentContact = rosterController->getItem(editEvent->getJID());
- assert(currentContact);
- jid = rosterController->getItem(editEvent->getJID())->getJID();
- contactEditWindow->setContact(jid, currentContact->getName(), currentContact->getGroups(), rosterController->getGroups());
- contactEditWindow->show();
-
- if (vcardManager) {
- VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(jid);
- if (vcard) {
- handleVCardChanged(jid, vcard);
- }
- }
+ RequestContactEditorUIEvent::ref editEvent = boost::dynamic_pointer_cast<RequestContactEditorUIEvent>(event);
+ if (!editEvent) {
+ return;
+ }
+
+ if (!contactEditWindow) {
+ contactEditWindow = contactEditWindowFactory->createContactEditWindow();
+ contactEditWindow->onRemoveContactRequest.connect(boost::bind(&ContactEditController::handleRemoveContactRequest, this));
+ contactEditWindow->onChangeContactRequest.connect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2));
+ }
+ currentContact = rosterController->getItem(editEvent->getJID());
+ assert(currentContact);
+ jid = rosterController->getItem(editEvent->getJID())->getJID();
+ contactEditWindow->setContact(jid, currentContact->getName(), currentContact->getGroups(), rosterController->getGroups());
+ contactEditWindow->show();
+
+ if (vcardManager) {
+ VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(jid);
+ if (vcard) {
+ handleVCardChanged(jid, vcard);
+ }
+ }
}
void ContactEditController::handleVCardChanged(const JID &jid, VCard::ref vcard) {
- if (jid == this->jid) {
- contactEditWindow->setNameSuggestions(nameSuggestionsFromVCard(vcard));
- }
+ if (jid == this->jid) {
+ contactEditWindow->setNameSuggestions(nameSuggestionsFromVCard(vcard));
+ }
}
void ContactEditController::setAvailable(bool b) {
- if (contactEditWindow) {
- contactEditWindow->setEnabled(b);
- }
+ if (contactEditWindow) {
+ contactEditWindow->setEnabled(b);
+ }
}
std::vector<std::string> ContactEditController::nameSuggestionsFromVCard(VCard::ref vcard) {
- std::vector<std::string> suggestions;
- if (!vcard->getNickname().empty()) {
- suggestions.push_back(vcard->getNickname());
- }
- if (!vcard->getFullName().empty()) {
- suggestions.push_back(vcard->getFullName());
- }
- if (!vcard->getGivenName().empty()) {
- std::string suggestedName;
- suggestedName = vcard->getGivenName();
- boost::algorithm::trim(suggestedName);
- suggestions.push_back(suggestedName);
- }
- return suggestions;
+ std::vector<std::string> suggestions;
+ if (!vcard->getNickname().empty()) {
+ suggestions.push_back(vcard->getNickname());
+ }
+ if (!vcard->getFullName().empty()) {
+ suggestions.push_back(vcard->getFullName());
+ }
+ if (!vcard->getGivenName().empty()) {
+ std::string suggestedName;
+ suggestedName = vcard->getGivenName();
+ boost::algorithm::trim(suggestedName);
+ suggestions.push_back(suggestedName);
+ }
+ return suggestions;
}
void ContactEditController::handleRemoveContactRequest() {
- assert(currentContact);
- uiEventStream->send(boost::make_shared<RemoveRosterItemUIEvent>(currentContact->getJID()));
- contactEditWindow->hide();
+ assert(currentContact);
+ uiEventStream->send(boost::make_shared<RemoveRosterItemUIEvent>(currentContact->getJID()));
+ contactEditWindow->hide();
}
void ContactEditController::handleChangeContactRequest(const std::string& name, const std::set<std::string>& newGroups) {
- std::vector<std::string> oldGroupsVector = currentContact->getGroups();
- std::set<std::string> oldGroups(oldGroupsVector.begin(), oldGroupsVector.end());
- if (oldGroups != newGroups || currentContact->getName() != name) {
- XMPPRosterItem newContact(*currentContact);
- newContact.setName(name);
- newContact.setGroups(std::vector<std::string>(newGroups.begin(), newGroups.end()));
- rosterController->updateItem(newContact);
- }
- contactEditWindow->hide();
+ std::vector<std::string> oldGroupsVector = currentContact->getGroups();
+ std::set<std::string> oldGroups(oldGroupsVector.begin(), oldGroupsVector.end());
+ if (oldGroups != newGroups || currentContact->getName() != name) {
+ XMPPRosterItem newContact(*currentContact);
+ newContact.setName(name);
+ newContact.setGroups(std::vector<std::string>(newGroups.begin(), newGroups.end()));
+ rosterController->updateItem(newContact);
+ }
+ contactEditWindow->hide();
}
}
diff --git a/Swift/Controllers/ContactEditController.h b/Swift/Controllers/ContactEditController.h
index 671fe38..ab2b52e 100644
--- a/Swift/Controllers/ContactEditController.h
+++ b/Swift/Controllers/ContactEditController.h
@@ -19,38 +19,38 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class UIEventStream;
- class ContactEditWindowFactory;
- class ContactEditWindow;
- class RosterController;
- class VCardManager;
-
- class ContactEditController {
- public:
- ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream);
- ~ContactEditController();
-
- void setAvailable(bool b);
-
- public:
- static std::vector<std::string> nameSuggestionsFromVCard(VCard::ref vcard);
-
- private:
- void handleRemoveContactRequest();
- void handleChangeContactRequest(const std::string& name, const std::set<std::string>& groups);
-
- private:
- void handleUIEvent(UIEvent::ref event);
- void handleVCardChanged(const JID& jid, VCard::ref vcard);
-
- private:
- boost::optional<XMPPRosterItem> currentContact;
- RosterController* rosterController;
- VCardManager* vcardManager;
- ContactEditWindowFactory* contactEditWindowFactory;
- UIEventStream* uiEventStream;
- JID jid;
- ContactEditWindow* contactEditWindow;
- };
+ class UIEventStream;
+ class ContactEditWindowFactory;
+ class ContactEditWindow;
+ class RosterController;
+ class VCardManager;
+
+ class ContactEditController {
+ public:
+ ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream);
+ ~ContactEditController();
+
+ void setAvailable(bool b);
+
+ public:
+ static std::vector<std::string> nameSuggestionsFromVCard(VCard::ref vcard);
+
+ private:
+ void handleRemoveContactRequest();
+ void handleChangeContactRequest(const std::string& name, const std::set<std::string>& groups);
+
+ private:
+ void handleUIEvent(UIEvent::ref event);
+ void handleVCardChanged(const JID& jid, VCard::ref vcard);
+
+ private:
+ boost::optional<XMPPRosterItem> currentContact;
+ RosterController* rosterController;
+ VCardManager* vcardManager;
+ ContactEditWindowFactory* contactEditWindowFactory;
+ UIEventStream* uiEventStream;
+ JID jid;
+ ContactEditWindow* contactEditWindow;
+ };
}
diff --git a/Swift/Controllers/ContactProvider.h b/Swift/Controllers/ContactProvider.h
index 08812d5..423f8a3 100644
--- a/Swift/Controllers/ContactProvider.h
+++ b/Swift/Controllers/ContactProvider.h
@@ -19,9 +19,9 @@
namespace Swift {
class ContactProvider {
- public:
- virtual ~ContactProvider();
- virtual std::vector<Contact::ref> getContacts(bool withMUCNicks) = 0;
+ public:
+ virtual ~ContactProvider();
+ virtual std::vector<Contact::ref> getContacts(bool withMUCNicks) = 0;
};
}
diff --git a/Swift/Controllers/ContactSuggester.cpp b/Swift/Controllers/ContactSuggester.cpp
index a2b605a..04e9dc4 100644
--- a/Swift/Controllers/ContactSuggester.cpp
+++ b/Swift/Controllers/ContactSuggester.cpp
@@ -39,49 +39,49 @@ ContactSuggester::~ContactSuggester() {
}
void ContactSuggester::addContactProvider(ContactProvider* provider) {
- contactProviders_.push_back(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;
+ 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;
+ std::vector<Contact::ref> results;
- foreach(ContactProvider* provider, contactProviders_) {
- append(results, provider->getContacts(withMUCNicks));
- }
+ foreach(ContactProvider* 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));
+ 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;
+ 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 (size_t i = 0; i < lowerMatch.length(); ++i) {
- size_t where = lowerText.find_first_of(lowerMatch[i], lastMatch);
- if (where == std::string::npos) {
- return false;
- }
- lastMatch = where + 1;
- }
- return true;
+ std::string lowerText = text;
+ boost::algorithm::to_lower(lowerText);
+ std::string lowerMatch = match;
+ boost::algorithm::to_lower(lowerMatch);
+ size_t lastMatch = 0;
+ for (size_t i = 0; i < lowerMatch.length(); ++i) {
+ size_t where = lowerText.find_first_of(lowerMatch[i], lastMatch);
+ if (where == std::string::npos) {
+ return false;
+ }
+ lastMatch = where + 1;
+ }
+ return true;
}
}
diff --git a/Swift/Controllers/ContactSuggester.h b/Swift/Controllers/ContactSuggester.h
index a57f638..f91879d 100644
--- a/Swift/Controllers/ContactSuggester.h
+++ b/Swift/Controllers/ContactSuggester.h
@@ -20,24 +20,24 @@
class ContactSuggesterTest;
namespace Swift {
- class ContactProvider;
-
- class ContactSuggester {
- public:
- ContactSuggester();
- ~ContactSuggester();
-
- void addContactProvider(ContactProvider* provider);
-
- std::vector<Contact::ref> getSuggestions(const std::string& search, bool withMUCNicks) const;
- public:
- static bool matchContact(const std::string& search, const Contact::ref& c);
- /**
- * Performs fuzzy matching on the string text. Matches when each character of match string is present in sequence in text string.
- */
- static bool fuzzyMatch(std::string text, std::string match);
-
- private:
- std::vector<ContactProvider*> contactProviders_;
- };
+ class ContactProvider;
+
+ class ContactSuggester {
+ public:
+ ContactSuggester();
+ ~ContactSuggester();
+
+ void addContactProvider(ContactProvider* provider);
+
+ std::vector<Contact::ref> getSuggestions(const std::string& search, bool withMUCNicks) const;
+ public:
+ static bool matchContact(const std::string& search, const Contact::ref& c);
+ /**
+ * Performs fuzzy matching on the string text. Matches when each character of match string is present in sequence in text string.
+ */
+ static bool fuzzyMatch(std::string text, std::string match);
+
+ private:
+ std::vector<ContactProvider*> contactProviders_;
+ };
}
diff --git a/Swift/Controllers/ContactsFromXMPPRoster.cpp b/Swift/Controllers/ContactsFromXMPPRoster.cpp
index 1cab9b1..1aa4424 100644
--- a/Swift/Controllers/ContactsFromXMPPRoster.cpp
+++ b/Swift/Controllers/ContactsFromXMPPRoster.cpp
@@ -27,15 +27,15 @@ 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) {
- Contact::ref contact = boost::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;
+ std::vector<Contact::ref> results;
+ std::vector<XMPPRosterItem> rosterItems = roster_->getItems();
+ foreach(const XMPPRosterItem& rosterItem, rosterItems) {
+ Contact::ref contact = boost::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/ContactsFromXMPPRoster.h b/Swift/Controllers/ContactsFromXMPPRoster.h
index 43d4985..2782dcc 100644
--- a/Swift/Controllers/ContactsFromXMPPRoster.h
+++ b/Swift/Controllers/ContactsFromXMPPRoster.h
@@ -21,15 +21,15 @@ class AvatarManager;
class XMPPRoster;
class ContactsFromXMPPRoster : public ContactProvider {
- public:
- ContactsFromXMPPRoster(XMPPRoster* roster, AvatarManager* avatarManager, PresenceOracle* presenceOracle);
- virtual ~ContactsFromXMPPRoster();
-
- virtual std::vector<Contact::ref> getContacts(bool withMUCNicks);
- private:
- XMPPRoster* roster_;
- AvatarManager* avatarManager_;
- PresenceOracle* presenceOracle_;
+ public:
+ ContactsFromXMPPRoster(XMPPRoster* roster, AvatarManager* avatarManager, PresenceOracle* presenceOracle);
+ virtual ~ContactsFromXMPPRoster();
+
+ virtual std::vector<Contact::ref> getContacts(bool withMUCNicks);
+ private:
+ XMPPRoster* roster_;
+ AvatarManager* avatarManager_;
+ PresenceOracle* presenceOracle_;
};
}
diff --git a/Swift/Controllers/DummySoundPlayer.h b/Swift/Controllers/DummySoundPlayer.h
index 2d99fb9..e297cae 100644
--- a/Swift/Controllers/DummySoundPlayer.h
+++ b/Swift/Controllers/DummySoundPlayer.h
@@ -9,8 +9,8 @@
#include <Swift/Controllers/SoundPlayer.h>
namespace Swift {
- class DummySoundPlayer : public SoundPlayer {
- public:
- void playSound(SoundEffect /*sound*/, const std::string& /*soundResource*/) {}
- };
+ class DummySoundPlayer : public SoundPlayer {
+ public:
+ void playSound(SoundEffect /*sound*/, const std::string& /*soundResource*/) {}
+ };
}
diff --git a/Swift/Controllers/DummySystemTray.h b/Swift/Controllers/DummySystemTray.h
index b413737..b36ed28 100644
--- a/Swift/Controllers/DummySystemTray.h
+++ b/Swift/Controllers/DummySystemTray.h
@@ -9,10 +9,10 @@
#include <Swift/Controllers/SystemTray.h>
namespace Swift {
- class DummySystemTray : public SystemTray {
- public:
- void setUnreadMessages(bool /*some*/) {}
- void setStatusType(StatusShow::Type /*type*/) {}
- void setConnecting() {}
- };
+ class DummySystemTray : public SystemTray {
+ public:
+ void setUnreadMessages(bool /*some*/) {}
+ void setStatusType(StatusShow::Type /*type*/) {}
+ void setConnecting() {}
+ };
}
diff --git a/Swift/Controllers/EventNotifier.cpp b/Swift/Controllers/EventNotifier.cpp
index 6615448..f4a9c2f 100644
--- a/Swift/Controllers/EventNotifier.cpp
+++ b/Swift/Controllers/EventNotifier.cpp
@@ -28,53 +28,53 @@
namespace Swift {
EventNotifier::EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver) : eventController(eventController), notifier(notifier), avatarManager(avatarManager), nickResolver(nickResolver) {
- eventController->onEventQueueEventAdded.connect(boost::bind(&EventNotifier::handleEventAdded, this, _1));
+ eventController->onEventQueueEventAdded.connect(boost::bind(&EventNotifier::handleEventAdded, this, _1));
}
EventNotifier::~EventNotifier() {
- notifier->purgeCallbacks();
- eventController->onEventQueueEventAdded.disconnect(boost::bind(&EventNotifier::handleEventAdded, this, _1));
+ notifier->purgeCallbacks();
+ eventController->onEventQueueEventAdded.disconnect(boost::bind(&EventNotifier::handleEventAdded, this, _1));
}
void EventNotifier::handleEventAdded(boost::shared_ptr<StanzaEvent> event) {
- if (event->getConcluded()) {
- return;
- }
- if (boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event)) {
- JID jid = messageEvent->getStanza()->getFrom();
- std::string title = nickResolver->jidToNick(jid);
- if (!messageEvent->getStanza()->isError() && !messageEvent->getStanza()->getBody().get_value_or("").empty()) {
- JID activationJID = jid;
- if (messageEvent->getStanza()->getType() == Message::Groupchat) {
- activationJID = jid.toBare();
- }
- std::string messageText = messageEvent->getStanza()->getBody().get_value_or("");
- if (boost::starts_with(messageText, "/me ")) {
- messageText = "*" + String::getSplittedAtFirst(messageText, ' ').second + "*";
- }
- notifier->showMessage(Notifier::IncomingMessage, title, messageText, avatarManager->getAvatarPath(jid), boost::bind(&EventNotifier::handleNotificationActivated, this, activationJID));
- }
- }
- else if(boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event)) {
- JID jid = subscriptionEvent->getJID();
- std::string title = jid;
- std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% wants to add you to his/her contact list")) % nickResolver->jidToNick(jid));
- notifier->showMessage(Notifier::SystemMessage, title, message, boost::filesystem::path(), boost::function<void()>());
- }
- else if(boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event)) {
- notifier->showMessage(Notifier::SystemMessage, QT_TRANSLATE_NOOP("", "Error"), errorEvent->getText(), boost::filesystem::path(), boost::function<void()>());
- }
- else if (boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event)) {
- std::string title = mucInviteEvent->getInviter();
- std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% has invited you to enter the %2% room")) % nickResolver->jidToNick(mucInviteEvent->getInviter()) % mucInviteEvent->getRoomJID());
- // FIXME: not show avatar or greyed out avatar for mediated invites
- notifier->showMessage(Notifier::SystemMessage, title, message, avatarManager->getAvatarPath(mucInviteEvent->getInviter()), boost::bind(&EventNotifier::handleNotificationActivated, this, mucInviteEvent->getInviter()));
- }
+ if (event->getConcluded()) {
+ return;
+ }
+ if (boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event)) {
+ JID jid = messageEvent->getStanza()->getFrom();
+ std::string title = nickResolver->jidToNick(jid);
+ if (!messageEvent->getStanza()->isError() && !messageEvent->getStanza()->getBody().get_value_or("").empty()) {
+ JID activationJID = jid;
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ activationJID = jid.toBare();
+ }
+ std::string messageText = messageEvent->getStanza()->getBody().get_value_or("");
+ if (boost::starts_with(messageText, "/me ")) {
+ messageText = "*" + String::getSplittedAtFirst(messageText, ' ').second + "*";
+ }
+ notifier->showMessage(Notifier::IncomingMessage, title, messageText, avatarManager->getAvatarPath(jid), boost::bind(&EventNotifier::handleNotificationActivated, this, activationJID));
+ }
+ }
+ else if(boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event)) {
+ JID jid = subscriptionEvent->getJID();
+ std::string title = jid;
+ std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% wants to add you to his/her contact list")) % nickResolver->jidToNick(jid));
+ notifier->showMessage(Notifier::SystemMessage, title, message, boost::filesystem::path(), boost::function<void()>());
+ }
+ else if(boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event)) {
+ notifier->showMessage(Notifier::SystemMessage, QT_TRANSLATE_NOOP("", "Error"), errorEvent->getText(), boost::filesystem::path(), boost::function<void()>());
+ }
+ else if (boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event)) {
+ std::string title = mucInviteEvent->getInviter();
+ std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% has invited you to enter the %2% room")) % nickResolver->jidToNick(mucInviteEvent->getInviter()) % mucInviteEvent->getRoomJID());
+ // FIXME: not show avatar or greyed out avatar for mediated invites
+ notifier->showMessage(Notifier::SystemMessage, title, message, avatarManager->getAvatarPath(mucInviteEvent->getInviter()), boost::bind(&EventNotifier::handleNotificationActivated, this, mucInviteEvent->getInviter()));
+ }
}
void EventNotifier::handleNotificationActivated(JID jid) {
- onNotificationActivated(jid);
+ onNotificationActivated(jid);
}
}
diff --git a/Swift/Controllers/EventNotifier.h b/Swift/Controllers/EventNotifier.h
index 2ecff6a..4661c46 100644
--- a/Swift/Controllers/EventNotifier.h
+++ b/Swift/Controllers/EventNotifier.h
@@ -16,29 +16,29 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class EventController;
- class Notifier;
- class AvatarManager;
- class NickResolver;
- class JID;
- class UIEventStream;
- class SettingsProvider;
-
- class EventNotifier {
- public:
- EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver);
- ~EventNotifier();
-
- boost::signal<void (const JID&)> onNotificationActivated;
-
- private:
- void handleEventAdded(boost::shared_ptr<StanzaEvent>);
- void handleNotificationActivated(JID jid);
-
- private:
- EventController* eventController;
- Notifier* notifier;
- AvatarManager* avatarManager;
- NickResolver* nickResolver;
- };
+ class EventController;
+ class Notifier;
+ class AvatarManager;
+ class NickResolver;
+ class JID;
+ class UIEventStream;
+ class SettingsProvider;
+
+ class EventNotifier {
+ public:
+ EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver);
+ ~EventNotifier();
+
+ boost::signal<void (const JID&)> onNotificationActivated;
+
+ private:
+ void handleEventAdded(boost::shared_ptr<StanzaEvent>);
+ void handleNotificationActivated(JID jid);
+
+ private:
+ EventController* eventController;
+ Notifier* notifier;
+ AvatarManager* avatarManager;
+ NickResolver* nickResolver;
+ };
}
diff --git a/Swift/Controllers/EventWindowController.cpp b/Swift/Controllers/EventWindowController.cpp
index 91fedd2..2739a87 100644
--- a/Swift/Controllers/EventWindowController.cpp
+++ b/Swift/Controllers/EventWindowController.cpp
@@ -14,41 +14,41 @@
namespace Swift {
EventWindowController::EventWindowController(EventController* eventController, EventWindowFactory* windowFactory) {
- eventController_ = eventController;
- windowFactory_ = windowFactory;
- window_ = windowFactory_->createEventWindow();
- eventAddedConnection_ = eventController_->onEventQueueEventAdded.connect(boost::bind(&EventWindowController::handleEventQueueEventAdded, this, _1));
+ eventController_ = eventController;
+ windowFactory_ = windowFactory;
+ window_ = windowFactory_->createEventWindow();
+ eventAddedConnection_ = eventController_->onEventQueueEventAdded.connect(boost::bind(&EventWindowController::handleEventQueueEventAdded, this, _1));
}
EventWindowController::~EventWindowController() {
- if (window_->canDelete()) {
- delete window_;
- }
+ if (window_->canDelete()) {
+ delete window_;
+ }
}
void EventWindowController::handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event) {
- if (event->getConcluded()) {
- handleEventConcluded(event);
- } else {
- boost::shared_ptr<MessageEvent> message = boost::dynamic_pointer_cast<MessageEvent>(event);
- if (!(message && message->isReadable())) {
- event->onConclusion.connect(boost::bind(&EventWindowController::handleEventConcluded, this, event));
- window_->addEvent(event, true);
- }
- }
+ if (event->getConcluded()) {
+ handleEventConcluded(event);
+ } else {
+ boost::shared_ptr<MessageEvent> message = boost::dynamic_pointer_cast<MessageEvent>(event);
+ if (!(message && message->isReadable())) {
+ event->onConclusion.connect(boost::bind(&EventWindowController::handleEventConcluded, this, event));
+ window_->addEvent(event, true);
+ }
+ }
}
void EventWindowController::handleEventConcluded(boost::shared_ptr<StanzaEvent> event) {
- window_->removeEvent(event);
- bool includeAsCompleted = true;
- /* Because subscription requests get duplicated, don't add them back */
- if (boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event) || boost::dynamic_pointer_cast<MessageEvent>(event)) {
- includeAsCompleted = false;
- }
- if (includeAsCompleted) {
- window_->addEvent(event, false);
- }
- event->onConclusion.disconnect(boost::bind(&EventWindowController::handleEventConcluded, this, event));
+ window_->removeEvent(event);
+ bool includeAsCompleted = true;
+ /* Because subscription requests get duplicated, don't add them back */
+ if (boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event) || boost::dynamic_pointer_cast<MessageEvent>(event)) {
+ includeAsCompleted = false;
+ }
+ if (includeAsCompleted) {
+ window_->addEvent(event, false);
+ }
+ event->onConclusion.disconnect(boost::bind(&EventWindowController::handleEventConcluded, this, event));
}
}
diff --git a/Swift/Controllers/EventWindowController.h b/Swift/Controllers/EventWindowController.h
index 1c50830..eba07ca 100644
--- a/Swift/Controllers/EventWindowController.h
+++ b/Swift/Controllers/EventWindowController.h
@@ -12,18 +12,18 @@
namespace Swift {
- class EventWindowController {
- public:
- EventWindowController(EventController* eventController, EventWindowFactory* windowFactory);
- ~EventWindowController();
- private:
- void handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event);
- void handleEventConcluded(boost::shared_ptr<StanzaEvent> event);
+ class EventWindowController {
+ public:
+ EventWindowController(EventController* eventController, EventWindowFactory* windowFactory);
+ ~EventWindowController();
+ private:
+ void handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event);
+ void handleEventConcluded(boost::shared_ptr<StanzaEvent> event);
- EventController* eventController_;
- EventWindowFactory* windowFactory_;
- EventWindow* window_;
- boost::bsignals::scoped_connection eventAddedConnection_;
- };
+ EventController* eventController_;
+ EventWindowFactory* windowFactory_;
+ EventWindow* window_;
+ boost::bsignals::scoped_connection eventAddedConnection_;
+ };
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferController.cpp b/Swift/Controllers/FileTransfer/FileTransferController.cpp
index 89e9a91..fd13d99 100644
--- a/Swift/Controllers/FileTransfer/FileTransferController.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferController.cpp
@@ -28,135 +28,135 @@
namespace Swift {
FileTransferController::FileTransferController(const JID& receipient, const std::string& filename, FileTransferManager* fileTransferManager) :
- sending(true), otherParty(receipient), filename(filename), ftManager(fileTransferManager), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) {
-
+ sending(true), otherParty(receipient), filename(filename), ftManager(fileTransferManager), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) {
+
}
FileTransferController::FileTransferController(IncomingFileTransfer::ref transfer) :
- sending(false), otherParty(transfer->getSender()), filename(transfer->getFileName()), transfer(transfer), ftManager(0), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) {
- transfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
+ sending(false), otherParty(transfer->getSender()), filename(transfer->getFileName()), transfer(transfer), ftManager(0), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) {
+ transfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
}
FileTransferController::~FileTransferController() {
- delete ftProgressInfo;
- transfer->onStateChanged.disconnect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
+ delete ftProgressInfo;
+ transfer->onStateChanged.disconnect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
}
const JID &FileTransferController::getOtherParty() const {
- return otherParty;
+ return otherParty;
}
std::string FileTransferController::setChatWindow(ChatWindow* wnd, std::string nickname) {
- chatWindow = wnd;
- if (sending) {
- uiID = wnd->addFileTransfer(QT_TRANSLATE_NOOP("", "me"), true, filename, boost::filesystem::file_size(boost::filesystem::path(filename)), "");
- } else {
- uiID = wnd->addFileTransfer(nickname, false, filename, transfer->getFileSizeInBytes(), transfer->getDescription());
- }
- return uiID;
+ chatWindow = wnd;
+ if (sending) {
+ uiID = wnd->addFileTransfer(QT_TRANSLATE_NOOP("", "me"), true, filename, boost::filesystem::file_size(boost::filesystem::path(filename)), "");
+ } else {
+ uiID = wnd->addFileTransfer(nickname, false, filename, transfer->getFileSizeInBytes(), transfer->getDescription());
+ }
+ return uiID;
}
void FileTransferController::setReceipient(const JID& receipient) {
- this->otherParty = receipient;
+ this->otherParty = receipient;
}
bool FileTransferController::isIncoming() const {
- return !sending;
+ return !sending;
}
FileTransfer::State FileTransferController::getState() const {
- return currentState;
+ return currentState;
}
int FileTransferController::getProgress() const {
- return ftProgressInfo ? ftProgressInfo->getPercentage() : 0;
+ return ftProgressInfo ? ftProgressInfo->getPercentage() : 0;
}
boost::uintmax_t FileTransferController::getSize() const {
- if (transfer) {
- return transfer->getFileSizeInBytes();
- } else {
- return 0;
- }
+ if (transfer) {
+ return transfer->getFileSizeInBytes();
+ } else {
+ return 0;
+ }
}
void FileTransferController::start(std::string& description) {
- SWIFT_LOG(debug) << "FileTransferController::start" << std::endl;
- fileReadStream = boost::make_shared<FileReadBytestream>(boost::filesystem::path(filename));
- OutgoingFileTransfer::ref outgoingTransfer = ftManager->createOutgoingFileTransfer(otherParty, boost::filesystem::path(filename), description, fileReadStream);
- if (outgoingTransfer) {
- ftProgressInfo = new FileTransferProgressInfo(outgoingTransfer->getFileSizeInBytes());
- ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1));
- outgoingTransfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
- outgoingTransfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1));
- outgoingTransfer->start();
- transfer = outgoingTransfer;
- } else {
- std::cerr << "File transfer not supported!" << std::endl;
- }
+ SWIFT_LOG(debug) << "FileTransferController::start" << std::endl;
+ fileReadStream = boost::make_shared<FileReadBytestream>(boost::filesystem::path(filename));
+ OutgoingFileTransfer::ref outgoingTransfer = ftManager->createOutgoingFileTransfer(otherParty, boost::filesystem::path(filename), description, fileReadStream);
+ if (outgoingTransfer) {
+ ftProgressInfo = new FileTransferProgressInfo(outgoingTransfer->getFileSizeInBytes());
+ ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1));
+ outgoingTransfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1));
+ outgoingTransfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1));
+ outgoingTransfer->start();
+ transfer = outgoingTransfer;
+ } else {
+ std::cerr << "File transfer not supported!" << std::endl;
+ }
}
void FileTransferController::accept(std::string& file) {
- SWIFT_LOG(debug) << "FileTransferController::accept" << std::endl;
- IncomingFileTransfer::ref incomingTransfer = boost::dynamic_pointer_cast<IncomingFileTransfer>(transfer);
- if (incomingTransfer) {
- fileWriteStream = boost::make_shared<FileWriteBytestream>(boost::filesystem::path(file));
+ SWIFT_LOG(debug) << "FileTransferController::accept" << std::endl;
+ IncomingFileTransfer::ref incomingTransfer = boost::dynamic_pointer_cast<IncomingFileTransfer>(transfer);
+ if (incomingTransfer) {
+ fileWriteStream = boost::make_shared<FileWriteBytestream>(boost::filesystem::path(file));
- ftProgressInfo = new FileTransferProgressInfo(transfer->getFileSizeInBytes());
- ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1));
- transfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1));
- incomingTransfer->accept(fileWriteStream);
- } else {
- std::cerr << "Expected an incoming transfer in this situation!" << std::endl;
- }
+ ftProgressInfo = new FileTransferProgressInfo(transfer->getFileSizeInBytes());
+ ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1));
+ transfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1));
+ incomingTransfer->accept(fileWriteStream);
+ } else {
+ std::cerr << "Expected an incoming transfer in this situation!" << std::endl;
+ }
}
void FileTransferController::cancel() {
- if (transfer) {
- transfer->cancel();
- } else {
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled);
- }
+ if (transfer) {
+ transfer->cancel();
+ } else {
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled);
+ }
}
void FileTransferController::handleFileTransferStateChange(FileTransfer::State state) {
- currentState = state;
- onStateChanged();
- switch(state.type) {
- case FileTransfer::State::Initial:
- assert(false);
- return;
- case FileTransfer::State::Negotiating:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Negotiating);
- return;
- case FileTransfer::State::Transferring:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Transferring);
- return;
- case FileTransfer::State::Canceled:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled);
- return;
- case FileTransfer::State::Finished:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Finished);
- if (fileWriteStream) {
- fileWriteStream->close();
- }
- return;
- case FileTransfer::State::Failed:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::FTFailed);
- return;
- case FileTransfer::State::WaitingForAccept:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::WaitingForAccept);
- return;
- case FileTransfer::State::WaitingForStart:
- chatWindow->setFileTransferStatus(uiID, ChatWindow::Initialisation);
- return;
- }
- assert(false);
+ currentState = state;
+ onStateChanged();
+ switch(state.type) {
+ case FileTransfer::State::Initial:
+ assert(false);
+ return;
+ case FileTransfer::State::Negotiating:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Negotiating);
+ return;
+ case FileTransfer::State::Transferring:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Transferring);
+ return;
+ case FileTransfer::State::Canceled:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled);
+ return;
+ case FileTransfer::State::Finished:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Finished);
+ if (fileWriteStream) {
+ fileWriteStream->close();
+ }
+ return;
+ case FileTransfer::State::Failed:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::FTFailed);
+ return;
+ case FileTransfer::State::WaitingForAccept:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::WaitingForAccept);
+ return;
+ case FileTransfer::State::WaitingForStart:
+ chatWindow->setFileTransferStatus(uiID, ChatWindow::Initialisation);
+ return;
+ }
+ assert(false);
}
void FileTransferController::handleProgressPercentageChange(int percentage) {
- onProgressChange();
- chatWindow->setFileTransferProgress(uiID, percentage);
+ onProgressChange();
+ chatWindow->setFileTransferProgress(uiID, percentage);
}
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferController.h b/Swift/Controllers/FileTransfer/FileTransferController.h
index 490773d..a25abee 100644
--- a/Swift/Controllers/FileTransfer/FileTransferController.h
+++ b/Swift/Controllers/FileTransfer/FileTransferController.h
@@ -32,49 +32,49 @@ class ChatWindow;
class FileTransferController {
public:
- /**
- * For outgoing file transfers. It'll create a file transfer via FileTransferManager as soon as the descriptive information is available.
- */
- FileTransferController(const JID&, const std::string&, FileTransferManager*);
+ /**
+ * For outgoing file transfers. It'll create a file transfer via FileTransferManager as soon as the descriptive information is available.
+ */
+ FileTransferController(const JID&, const std::string&, FileTransferManager*);
- /**
- * For incoming file transfers.
- */
- FileTransferController(IncomingFileTransfer::ref transfer);
- ~FileTransferController();
+ /**
+ * For incoming file transfers.
+ */
+ FileTransferController(IncomingFileTransfer::ref transfer);
+ ~FileTransferController();
- std::string setChatWindow(ChatWindow*, std::string nickname);
- void setReceipient(const JID& otherParty);
+ std::string setChatWindow(ChatWindow*, std::string nickname);
+ void setReceipient(const JID& otherParty);
- void start(std::string& description);
- void accept(std::string& file);
- void cancel();
+ void start(std::string& description);
+ void accept(std::string& file);
+ void cancel();
- const JID &getOtherParty() const;
- bool isIncoming() const;
- FileTransfer::State getState() const;
- int getProgress() const;
- boost::uintmax_t getSize() const;
+ const JID &getOtherParty() const;
+ bool isIncoming() const;
+ FileTransfer::State getState() const;
+ int getProgress() const;
+ boost::uintmax_t getSize() const;
- boost::signal<void ()> onStateChanged;
- boost::signal<void ()> onProgressChange;
+ boost::signal<void ()> onStateChanged;
+ boost::signal<void ()> onProgressChange;
private:
- void handleFileTransferStateChange(FileTransfer::State);
- void handleProgressPercentageChange(int percentage);
+ void handleFileTransferStateChange(FileTransfer::State);
+ void handleProgressPercentageChange(int percentage);
private:
- bool sending;
- JID otherParty;
- std::string filename;
- FileTransfer::ref transfer;
- boost::shared_ptr<FileReadBytestream> fileReadStream;
- boost::shared_ptr<FileWriteBytestream> fileWriteStream;
- FileTransferManager* ftManager;
- FileTransferProgressInfo* ftProgressInfo;
- ChatWindow* chatWindow;
- std::string uiID;
- FileTransfer::State currentState;
+ bool sending;
+ JID otherParty;
+ std::string filename;
+ FileTransfer::ref transfer;
+ boost::shared_ptr<FileReadBytestream> fileReadStream;
+ boost::shared_ptr<FileWriteBytestream> fileWriteStream;
+ FileTransferManager* ftManager;
+ FileTransferProgressInfo* ftProgressInfo;
+ ChatWindow* chatWindow;
+ std::string uiID;
+ FileTransfer::State currentState;
};
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
index 8616c1e..a53b000 100644
--- a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
@@ -23,70 +23,70 @@
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));
+ 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) {
- controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
- }
+ onNewFileTransferController.disconnect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1));
+ fileTransferManager->onIncomingFileTransfer.disconnect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1));
+ foreach(FileTransferController* 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);
- }
+ 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);
+ FileTransferController* controller = new FileTransferController(transfer);
+ onNewFileTransferController(controller);
}
void FileTransferOverview::handleNewFileTransferController(FileTransferController* controller) {
- fileTransfers.push_back(controller);
- controller->onStateChanged.connect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
+ fileTransfers.push_back(controller);
+ controller->onStateChanged.connect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
}
void FileTransferOverview::handleFileTransferStateChanged() {
- onFileTransferListChanged();
+ onFileTransferListChanged();
}
const std::vector<FileTransferController*>& FileTransferOverview::getFileTransfers() const {
- return fileTransfers;
+ 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();
+ 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) {
- if(controller->getState().type == FileTransfer::State::Finished
- || controller->getState().type == FileTransfer::State::Failed
- || controller->getState().type == FileTransfer::State::Canceled) {
- isClearable = true;
- break;
- }
- }
- return isClearable;
+ bool isClearable = false;
+ foreach (FileTransferController* 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/FileTransfer/FileTransferOverview.h b/Swift/Controllers/FileTransfer/FileTransferOverview.h
index e3cbf81..a55727c 100644
--- a/Swift/Controllers/FileTransfer/FileTransferOverview.h
+++ b/Swift/Controllers/FileTransfer/FileTransferOverview.h
@@ -25,25 +25,25 @@ class FileTransferManager;
class FileTransferOverview {
public:
- FileTransferOverview(FileTransferManager*);
- ~FileTransferOverview();
-
- void sendFile(const JID&, const std::string&);
- const std::vector<FileTransferController*>& getFileTransfers() const;
- void clearFinished();
- bool isClearable() const;
+ FileTransferOverview(FileTransferManager*);
+ ~FileTransferOverview();
- boost::signal<void (FileTransferController*)> onNewFileTransferController;
- boost::signal<void ()> onFileTransferListChanged;
+ void sendFile(const JID&, const std::string&);
+ const std::vector<FileTransferController*>& getFileTransfers() const;
+ void clearFinished();
+ bool isClearable() const;
+
+ boost::signal<void (FileTransferController*)> onNewFileTransferController;
+ boost::signal<void ()> onFileTransferListChanged;
private:
- void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer);
- void handleNewFileTransferController(FileTransferController* controller);
- void handleFileTransferStateChanged();
+ void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer);
+ void handleNewFileTransferController(FileTransferController* controller);
+ void handleFileTransferStateChanged();
private:
- std::vector<FileTransferController*> fileTransfers;
- FileTransferManager *fileTransferManager;
+ std::vector<FileTransferController*> fileTransfers;
+ FileTransferManager *fileTransferManager;
};
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp
index a2fff03..b073017 100644
--- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp
@@ -19,21 +19,21 @@
namespace Swift {
FileTransferProgressInfo::FileTransferProgressInfo(boost::uintmax_t completeBytes) : completeBytes(completeBytes), completedBytes(0), percentage(0) {
- onProgressPercentage(0);
+ onProgressPercentage(0);
}
void FileTransferProgressInfo::setBytesProcessed(int processedBytes) {
- int oldPercentage = int(double(completedBytes) / double(completeBytes) * 100.0);
- completedBytes += boost::numeric_cast<boost::uintmax_t>(processedBytes);
- int newPercentage = int(double(completedBytes) / double(completeBytes) * 100.0);
- if (oldPercentage != newPercentage) {
- onProgressPercentage(newPercentage);
- }
- percentage = newPercentage;
+ int oldPercentage = int(double(completedBytes) / double(completeBytes) * 100.0);
+ completedBytes += boost::numeric_cast<boost::uintmax_t>(processedBytes);
+ int newPercentage = int(double(completedBytes) / double(completeBytes) * 100.0);
+ if (oldPercentage != newPercentage) {
+ onProgressPercentage(newPercentage);
+ }
+ percentage = newPercentage;
}
int FileTransferProgressInfo::getPercentage() const {
- return percentage;
+ return percentage;
}
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h
index ea88657..783874a 100644
--- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h
+++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h
@@ -20,18 +20,18 @@ namespace Swift {
class FileTransferProgressInfo {
public:
- FileTransferProgressInfo(boost::uintmax_t completeBytes);
+ FileTransferProgressInfo(boost::uintmax_t completeBytes);
public:
- void setBytesProcessed(int processedBytes);
+ void setBytesProcessed(int processedBytes);
- int getPercentage() const;
- boost::signal<void (int)> onProgressPercentage;
+ int getPercentage() const;
+ boost::signal<void (int)> onProgressPercentage;
private:
- boost::uintmax_t completeBytes;
- boost::uintmax_t completedBytes;
- int percentage;
+ boost::uintmax_t completeBytes;
+ boost::uintmax_t completedBytes;
+ int percentage;
};
}
diff --git a/Swift/Controllers/FileTransferListController.cpp b/Swift/Controllers/FileTransferListController.cpp
index 6e84435..a383ae5 100644
--- a/Swift/Controllers/FileTransferListController.cpp
+++ b/Swift/Controllers/FileTransferListController.cpp
@@ -20,32 +20,32 @@
namespace Swift {
FileTransferListController::FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory) : fileTransferListWidgetFactory(fileTransferListWidgetFactory), fileTransferListWidget(NULL), fileTransferOverview(0) {
- uiEventStream->onUIEvent.connect(boost::bind(&FileTransferListController::handleUIEvent, this, _1));
+ uiEventStream->onUIEvent.connect(boost::bind(&FileTransferListController::handleUIEvent, this, _1));
}
FileTransferListController::~FileTransferListController() {
- delete fileTransferListWidget;
+ delete fileTransferListWidget;
}
void FileTransferListController::setFileTransferOverview(FileTransferOverview *overview) {
- fileTransferOverview = overview;
- if (fileTransferListWidget) {
- fileTransferListWidget->setFileTransferOverview(fileTransferOverview);
- }
+ fileTransferOverview = overview;
+ if (fileTransferListWidget) {
+ fileTransferListWidget->setFileTransferOverview(fileTransferOverview);
+ }
}
void FileTransferListController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent) {
- boost::shared_ptr<RequestFileTransferListUIEvent> event = boost::dynamic_pointer_cast<RequestFileTransferListUIEvent>(rawEvent);
- if (event != NULL) {
- if (fileTransferListWidget == NULL) {
- fileTransferListWidget = fileTransferListWidgetFactory->createFileTransferListWidget();
- if (fileTransferOverview) {
- fileTransferListWidget->setFileTransferOverview(fileTransferOverview);
- }
- }
- fileTransferListWidget->show();
- fileTransferListWidget->activate();
- }
+ boost::shared_ptr<RequestFileTransferListUIEvent> event = boost::dynamic_pointer_cast<RequestFileTransferListUIEvent>(rawEvent);
+ if (event != NULL) {
+ if (fileTransferListWidget == NULL) {
+ fileTransferListWidget = fileTransferListWidgetFactory->createFileTransferListWidget();
+ if (fileTransferOverview) {
+ fileTransferListWidget->setFileTransferOverview(fileTransferOverview);
+ }
+ }
+ fileTransferListWidget->show();
+ fileTransferListWidget->activate();
+ }
}
}
diff --git a/Swift/Controllers/FileTransferListController.h b/Swift/Controllers/FileTransferListController.h
index 079cd35..df79d1f 100644
--- a/Swift/Controllers/FileTransferListController.h
+++ b/Swift/Controllers/FileTransferListController.h
@@ -24,18 +24,18 @@ class FileTransferOverview;
class FileTransferListController {
public:
- FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory);
- ~FileTransferListController();
+ FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory);
+ ~FileTransferListController();
- void setFileTransferOverview(FileTransferOverview* overview);
+ void setFileTransferOverview(FileTransferOverview* overview);
private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
private:
- FileTransferListWidgetFactory* fileTransferListWidgetFactory;
- FileTransferListWidget* fileTransferListWidget;
- FileTransferOverview* fileTransferOverview;
+ FileTransferListWidgetFactory* fileTransferListWidgetFactory;
+ FileTransferListWidget* fileTransferListWidget;
+ FileTransferOverview* fileTransferOverview;
};
}
diff --git a/Swift/Controllers/HighlightAction.cpp b/Swift/Controllers/HighlightAction.cpp
index 4603408..3ea2c86 100644
--- a/Swift/Controllers/HighlightAction.cpp
+++ b/Swift/Controllers/HighlightAction.cpp
@@ -16,47 +16,47 @@ namespace Swift {
void HighlightAction::setHighlightWholeMessage(bool highlightText)
{
- highlightWholeMessage_ = highlightText;
- if (!highlightWholeMessage_) {
- textColor_.clear();
- textBackground_.clear();
- }
+ highlightWholeMessage_ = highlightText;
+ if (!highlightWholeMessage_) {
+ textColor_.clear();
+ textBackground_.clear();
+ }
}
void HighlightAction::setPlaySound(bool playSound)
{
- playSound_ = playSound;
- if (!playSound_) {
- soundFile_.clear();
- }
+ playSound_ = playSound;
+ if (!playSound_) {
+ soundFile_.clear();
+ }
}
bool operator ==(HighlightAction const& a, HighlightAction const& b) {
- if (a.highlightWholeMessage() != b.highlightWholeMessage()) {
- return false;
- }
+ if (a.highlightWholeMessage() != b.highlightWholeMessage()) {
+ return false;
+ }
- if (a.getTextColor() != b.getTextColor()) {
- return false;
- }
+ if (a.getTextColor() != b.getTextColor()) {
+ return false;
+ }
- if (a.getTextBackground() != b.getTextBackground()) {
- return false;
- }
+ if (a.getTextBackground() != b.getTextBackground()) {
+ return false;
+ }
- if (a.playSound() != b.playSound()) {
- return false;
- }
+ if (a.playSound() != b.playSound()) {
+ return false;
+ }
- if (a.getSoundFile() != b.getSoundFile()) {
- return false;
- }
+ if (a.getSoundFile() != b.getSoundFile()) {
+ return false;
+ }
- return true;
+ return true;
}
bool operator !=(HighlightAction const& a, HighlightAction const& b) {
- return !(a == b);
+ return !(a == b);
}
}
diff --git a/Swift/Controllers/HighlightAction.h b/Swift/Controllers/HighlightAction.h
index 3930eee..b9d4539 100644
--- a/Swift/Controllers/HighlightAction.h
+++ b/Swift/Controllers/HighlightAction.h
@@ -19,64 +19,64 @@
namespace Swift {
- class HighlightRule;
-
- class HighlightAction {
- public:
- HighlightAction() : highlightWholeMessage_(false), playSound_(false) {}
-
- /**
- * Gets the flag that indicates the entire message should be highlighted.
- */
- bool highlightWholeMessage() const { return highlightWholeMessage_; }
- void setHighlightWholeMessage(bool highlightText);
-
- /**
- * Gets the foreground highlight color.
- */
- const std::string& getTextColor() const { return textColor_; }
- void setTextColor(const std::string& textColor) { textColor_ = textColor; }
-
- /**
- * Gets the background highlight color.
- */
- const std::string& getTextBackground() const { return textBackground_; }
- void setTextBackground(const std::string& textBackground) { textBackground_ = textBackground; }
-
- bool playSound() const { return playSound_; }
- void setPlaySound(bool playSound);
-
- /**
- * Gets the sound filename. If the string is empty, assume a default sound file.
- */
- const std::string& getSoundFile() const { return soundFile_; }
- void setSoundFile(const std::string& soundFile) { soundFile_ = soundFile; }
-
- bool isEmpty() const { return !highlightWholeMessage_ && !playSound_; }
-
- private:
- friend class boost::serialization::access;
- template<class Archive> void serialize(Archive & ar, const unsigned int version);
-
- bool highlightWholeMessage_;
- std::string textColor_;
- std::string textBackground_;
-
- bool playSound_;
- std::string soundFile_;
- };
-
- bool operator ==(HighlightAction const& a, HighlightAction const& b);
- bool operator !=(HighlightAction const& a, HighlightAction const& b);
-
- template<class Archive>
- void HighlightAction::serialize(Archive& ar, const unsigned int /*version*/)
- {
- ar & highlightWholeMessage_;
- ar & textColor_;
- ar & textBackground_;
- ar & playSound_;
- ar & soundFile_;
- }
+ class HighlightRule;
+
+ class HighlightAction {
+ public:
+ HighlightAction() : highlightWholeMessage_(false), playSound_(false) {}
+
+ /**
+ * Gets the flag that indicates the entire message should be highlighted.
+ */
+ bool highlightWholeMessage() const { return highlightWholeMessage_; }
+ void setHighlightWholeMessage(bool highlightText);
+
+ /**
+ * Gets the foreground highlight color.
+ */
+ const std::string& getTextColor() const { return textColor_; }
+ void setTextColor(const std::string& textColor) { textColor_ = textColor; }
+
+ /**
+ * Gets the background highlight color.
+ */
+ const std::string& getTextBackground() const { return textBackground_; }
+ void setTextBackground(const std::string& textBackground) { textBackground_ = textBackground; }
+
+ bool playSound() const { return playSound_; }
+ void setPlaySound(bool playSound);
+
+ /**
+ * Gets the sound filename. If the string is empty, assume a default sound file.
+ */
+ const std::string& getSoundFile() const { return soundFile_; }
+ void setSoundFile(const std::string& soundFile) { soundFile_ = soundFile; }
+
+ bool isEmpty() const { return !highlightWholeMessage_ && !playSound_; }
+
+ private:
+ friend class boost::serialization::access;
+ template<class Archive> void serialize(Archive & ar, const unsigned int version);
+
+ bool highlightWholeMessage_;
+ std::string textColor_;
+ std::string textBackground_;
+
+ bool playSound_;
+ std::string soundFile_;
+ };
+
+ bool operator ==(HighlightAction const& a, HighlightAction const& b);
+ bool operator !=(HighlightAction const& a, HighlightAction const& b);
+
+ template<class Archive>
+ void HighlightAction::serialize(Archive& ar, const unsigned int /*version*/)
+ {
+ ar & highlightWholeMessage_;
+ ar & textColor_;
+ ar & textBackground_;
+ ar & playSound_;
+ ar & soundFile_;
+ }
}
diff --git a/Swift/Controllers/HighlightEditorController.cpp b/Swift/Controllers/HighlightEditorController.cpp
index ebda81c..bf5dbc4 100644
--- a/Swift/Controllers/HighlightEditorController.cpp
+++ b/Swift/Controllers/HighlightEditorController.cpp
@@ -25,33 +25,33 @@ namespace Swift {
HighlightEditorController::HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager)
: highlightEditorWindowFactory_(highlightEditorWindowFactory), highlightEditorWindow_(NULL), highlightManager_(highlightManager), contactSuggester_(0)
{
- uiEventStream->onUIEvent.connect(boost::bind(&HighlightEditorController::handleUIEvent, this, _1));
+ uiEventStream->onUIEvent.connect(boost::bind(&HighlightEditorController::handleUIEvent, this, _1));
}
HighlightEditorController::~HighlightEditorController()
{
- delete highlightEditorWindow_;
- highlightEditorWindow_ = NULL;
+ delete highlightEditorWindow_;
+ highlightEditorWindow_ = NULL;
}
void HighlightEditorController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent)
{
- boost::shared_ptr<RequestHighlightEditorUIEvent> event = boost::dynamic_pointer_cast<RequestHighlightEditorUIEvent>(rawEvent);
- if (event) {
- if (!highlightEditorWindow_) {
- highlightEditorWindow_ = highlightEditorWindowFactory_->createHighlightEditorWindow();
- highlightEditorWindow_->setHighlightManager(highlightManager_);
- highlightEditorWindow_->onContactSuggestionsRequested.connect(boost::bind(&HighlightEditorController::handleContactSuggestionsRequested, this, _1));
- }
- highlightEditorWindow_->show();
- }
+ boost::shared_ptr<RequestHighlightEditorUIEvent> event = boost::dynamic_pointer_cast<RequestHighlightEditorUIEvent>(rawEvent);
+ if (event) {
+ if (!highlightEditorWindow_) {
+ highlightEditorWindow_ = highlightEditorWindowFactory_->createHighlightEditorWindow();
+ highlightEditorWindow_->setHighlightManager(highlightManager_);
+ highlightEditorWindow_->onContactSuggestionsRequested.connect(boost::bind(&HighlightEditorController::handleContactSuggestionsRequested, this, _1));
+ }
+ highlightEditorWindow_->show();
+ }
}
void HighlightEditorController::handleContactSuggestionsRequested(const std::string& text)
{
- if (contactSuggester_) {
- highlightEditorWindow_->setContactSuggestions(contactSuggester_->getSuggestions(text, true));
- }
+ if (contactSuggester_) {
+ highlightEditorWindow_->setContactSuggestions(contactSuggester_->getSuggestions(text, true));
+ }
}
}
diff --git a/Swift/Controllers/HighlightEditorController.h b/Swift/Controllers/HighlightEditorController.h
index 52587c2..24ad9c2 100644
--- a/Swift/Controllers/HighlightEditorController.h
+++ b/Swift/Controllers/HighlightEditorController.h
@@ -18,31 +18,31 @@
namespace Swift {
- class UIEventStream;
+ class UIEventStream;
- class HighlightEditorWindowFactory;
- class HighlightEditorWindow;
+ class HighlightEditorWindowFactory;
+ class HighlightEditorWindow;
- class HighlightManager;
- class ContactSuggester;
+ class HighlightManager;
+ class ContactSuggester;
- class HighlightEditorController {
- public:
- HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager);
- ~HighlightEditorController();
+ class HighlightEditorController {
+ public:
+ HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager);
+ ~HighlightEditorController();
- HighlightManager* getHighlightManager() const { return highlightManager_; }
- void setContactSuggester(ContactSuggester *suggester) { contactSuggester_ = suggester; }
+ HighlightManager* getHighlightManager() const { return highlightManager_; }
+ void setContactSuggester(ContactSuggester *suggester) { contactSuggester_ = suggester; }
- private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleContactSuggestionsRequested(const std::string& text);
+ private:
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleContactSuggestionsRequested(const std::string& text);
- private:
- HighlightEditorWindowFactory* highlightEditorWindowFactory_;
- HighlightEditorWindow* highlightEditorWindow_;
- HighlightManager* highlightManager_;
- ContactSuggester* contactSuggester_;
- };
+ private:
+ HighlightEditorWindowFactory* highlightEditorWindowFactory_;
+ HighlightEditorWindow* highlightEditorWindow_;
+ HighlightManager* highlightManager_;
+ ContactSuggester* contactSuggester_;
+ };
}
diff --git a/Swift/Controllers/HighlightManager.cpp b/Swift/Controllers/HighlightManager.cpp
index 07f8e54..45b800a 100644
--- a/Swift/Controllers/HighlightManager.cpp
+++ b/Swift/Controllers/HighlightManager.cpp
@@ -48,102 +48,102 @@
namespace Swift {
HighlightManager::HighlightManager(SettingsProvider* settings)
- : settings_(settings)
- , storingSettings_(false) {
- rules_ = boost::make_shared<HighlightRulesList>();
- loadSettings();
- handleSettingChangedConnection_ = settings_->onSettingChanged.connect(boost::bind(&HighlightManager::handleSettingChanged, this, _1));
+ : settings_(settings)
+ , storingSettings_(false) {
+ rules_ = boost::make_shared<HighlightRulesList>();
+ loadSettings();
+ handleSettingChangedConnection_ = settings_->onSettingChanged.connect(boost::bind(&HighlightManager::handleSettingChanged, this, _1));
}
void HighlightManager::handleSettingChanged(const std::string& settingPath) {
- if (!storingSettings_ && SettingConstants::HIGHLIGHT_RULES.getKey() == settingPath) {
- loadSettings();
- }
+ if (!storingSettings_ && SettingConstants::HIGHLIGHT_RULES.getKey() == settingPath) {
+ loadSettings();
+ }
}
std::string HighlightManager::rulesToString() const {
- std::stringstream stream;
- boost::archive::text_oarchive archive(stream);
- archive << rules_->list_;
- return stream.str();
+ std::stringstream stream;
+ boost::archive::text_oarchive archive(stream);
+ archive << rules_->list_;
+ return stream.str();
}
std::vector<HighlightRule> HighlightManager::getDefaultRules() {
- std::vector<HighlightRule> rules;
-
- HighlightRule chatNotificationRule;
- chatNotificationRule.setMatchChat(true);
- chatNotificationRule.getAction().setPlaySound(true);
- chatNotificationRule.setMatchWholeWords(true);
- rules.push_back(chatNotificationRule);
-
- HighlightRule selfMentionMUCRule;
- selfMentionMUCRule.setMatchMUC(true);
- selfMentionMUCRule.getAction().setPlaySound(true);
- selfMentionMUCRule.setNickIsKeyword(true);
- selfMentionMUCRule.setMatchCase(true);
- selfMentionMUCRule.setMatchWholeWords(true);
- rules.push_back(selfMentionMUCRule);
-
- return rules;
+ std::vector<HighlightRule> rules;
+
+ HighlightRule chatNotificationRule;
+ chatNotificationRule.setMatchChat(true);
+ chatNotificationRule.getAction().setPlaySound(true);
+ chatNotificationRule.setMatchWholeWords(true);
+ rules.push_back(chatNotificationRule);
+
+ HighlightRule selfMentionMUCRule;
+ selfMentionMUCRule.setMatchMUC(true);
+ selfMentionMUCRule.getAction().setPlaySound(true);
+ selfMentionMUCRule.setNickIsKeyword(true);
+ selfMentionMUCRule.setMatchCase(true);
+ selfMentionMUCRule.setMatchWholeWords(true);
+ rules.push_back(selfMentionMUCRule);
+
+ return rules;
}
HighlightRule HighlightManager::getRule(int index) const {
- assert(index >= 0 && static_cast<size_t>(index) < rules_->getSize());
- return rules_->getRule(static_cast<size_t>(index));
+ assert(index >= 0 && static_cast<size_t>(index) < rules_->getSize());
+ return rules_->getRule(static_cast<size_t>(index));
}
void HighlightManager::setRule(int index, const HighlightRule& rule) {
- assert(index >= 0 && static_cast<size_t>(index) < rules_->getSize());
- rules_->list_[static_cast<size_t>(index)] = rule;
+ assert(index >= 0 && static_cast<size_t>(index) < rules_->getSize());
+ rules_->list_[static_cast<size_t>(index)] = rule;
}
void HighlightManager::insertRule(int index, const HighlightRule& rule) {
- assert(index >= 0 && boost::numeric_cast<std::vector<std::string>::size_type>(index) <= rules_->getSize());
- rules_->list_.insert(rules_->list_.begin() + index, rule);
+ assert(index >= 0 && boost::numeric_cast<std::vector<std::string>::size_type>(index) <= rules_->getSize());
+ rules_->list_.insert(rules_->list_.begin() + index, rule);
}
void HighlightManager::removeRule(int index) {
- assert(index >= 0 && boost::numeric_cast<std::vector<std::string>::size_type>(index) < rules_->getSize());
- rules_->list_.erase(rules_->list_.begin() + index);
+ assert(index >= 0 && boost::numeric_cast<std::vector<std::string>::size_type>(index) < rules_->getSize());
+ rules_->list_.erase(rules_->list_.begin() + index);
}
void HighlightManager::swapRules(const size_t first, const size_t second) {
- assert(first < rules_->getSize());
- assert(second < rules_->getSize());
- const HighlightRule swap = rules_->getRule(first);
- rules_->setRule(first, rules_->getRule(second));
- rules_->setRule(second, swap);
+ assert(first < rules_->getSize());
+ assert(second < rules_->getSize());
+ const HighlightRule swap = rules_->getRule(first);
+ rules_->setRule(first, rules_->getRule(second));
+ rules_->setRule(second, swap);
}
void HighlightManager::storeSettings() {
- storingSettings_ = true; // don't reload settings while saving
- settings_->storeSetting(SettingConstants::HIGHLIGHT_RULES, rulesToString());
- storingSettings_ = false;
+ storingSettings_ = true; // don't reload settings while saving
+ settings_->storeSetting(SettingConstants::HIGHLIGHT_RULES, rulesToString());
+ storingSettings_ = false;
}
void HighlightManager::loadSettings() {
- std::string rulesString = settings_->getSetting(SettingConstants::HIGHLIGHT_RULES);
- std::stringstream stream;
- stream << rulesString;
- try {
- boost::archive::text_iarchive archive(stream);
- archive >> rules_->list_;
- } catch (boost::archive::archive_exception&) {
- rules_->list_ = getDefaultRules();
- }
+ std::string rulesString = settings_->getSetting(SettingConstants::HIGHLIGHT_RULES);
+ std::stringstream stream;
+ stream << rulesString;
+ try {
+ boost::archive::text_iarchive archive(stream);
+ archive >> rules_->list_;
+ } catch (boost::archive::archive_exception&) {
+ rules_->list_ = getDefaultRules();
+ }
}
Highlighter* HighlightManager::createHighlighter() {
- return new Highlighter(this);
+ return new Highlighter(this);
}
bool HighlightManager::isDefaultRulesList() const {
- return getDefaultRules() == rules_->list_;
+ return getDefaultRules() == rules_->list_;
}
void HighlightManager::resetToDefaultRulesList() {
- rules_->list_ = getDefaultRules();
+ rules_->list_ = getDefaultRules();
}
}
diff --git a/Swift/Controllers/HighlightManager.h b/Swift/Controllers/HighlightManager.h
index 180f7a3..1d2eb8a 100644
--- a/Swift/Controllers/HighlightManager.h
+++ b/Swift/Controllers/HighlightManager.h
@@ -21,61 +21,61 @@
namespace Swift {
- class SettingsProvider;
- class Highlighter;
-
- class HighlightManager {
- public:
-
- class HighlightRulesList {
- public:
- friend class HighlightManager;
- size_t getSize() const { return list_.size(); }
- const HighlightRule& getRule(const size_t index) const { return list_[index]; }
- void addRule(const HighlightRule& rule) { list_.push_back(rule); }
- void combineRules(const HighlightRulesList& rhs) {
- list_.insert(list_.end(), rhs.list_.begin(), rhs.list_.end());
- }
- void setRule(const size_t index, const HighlightRule& rule) {
- list_[index] = rule;
- }
- private:
- std::vector<HighlightRule> list_;
- };
-
- HighlightManager(SettingsProvider* settings);
-
- Highlighter* createHighlighter();
-
- boost::shared_ptr<const HighlightManager::HighlightRulesList> getRules() const { return rules_; }
-
- bool isDefaultRulesList() const;
- void resetToDefaultRulesList();
-
- HighlightRule getRule(int index) const;
- void setRule(int index, const HighlightRule& rule);
- void insertRule(int index, const HighlightRule& rule);
- void removeRule(int index);
- void swapRules(const size_t first, const size_t second);
- void storeSettings();
- void loadSettings();
-
- boost::signal<void (const HighlightAction&)> onHighlight;
-
- private:
- void handleSettingChanged(const std::string& settingPath);
-
- std::string rulesToString() const;
- static std::vector<HighlightRule> getDefaultRules();
-
- private:
- SettingsProvider* settings_;
- bool storingSettings_;
-
- boost::shared_ptr<HighlightManager::HighlightRulesList> rules_;
- boost::bsignals::scoped_connection handleSettingChangedConnection_;
- };
-
- typedef boost::shared_ptr<const HighlightManager::HighlightRulesList> HighlightRulesListPtr;
+ class SettingsProvider;
+ class Highlighter;
+
+ class HighlightManager {
+ public:
+
+ class HighlightRulesList {
+ public:
+ friend class HighlightManager;
+ size_t getSize() const { return list_.size(); }
+ const HighlightRule& getRule(const size_t index) const { return list_[index]; }
+ void addRule(const HighlightRule& rule) { list_.push_back(rule); }
+ void combineRules(const HighlightRulesList& rhs) {
+ list_.insert(list_.end(), rhs.list_.begin(), rhs.list_.end());
+ }
+ void setRule(const size_t index, const HighlightRule& rule) {
+ list_[index] = rule;
+ }
+ private:
+ std::vector<HighlightRule> list_;
+ };
+
+ HighlightManager(SettingsProvider* settings);
+
+ Highlighter* createHighlighter();
+
+ boost::shared_ptr<const HighlightManager::HighlightRulesList> getRules() const { return rules_; }
+
+ bool isDefaultRulesList() const;
+ void resetToDefaultRulesList();
+
+ HighlightRule getRule(int index) const;
+ void setRule(int index, const HighlightRule& rule);
+ void insertRule(int index, const HighlightRule& rule);
+ void removeRule(int index);
+ void swapRules(const size_t first, const size_t second);
+ void storeSettings();
+ void loadSettings();
+
+ boost::signal<void (const HighlightAction&)> onHighlight;
+
+ private:
+ void handleSettingChanged(const std::string& settingPath);
+
+ std::string rulesToString() const;
+ static std::vector<HighlightRule> getDefaultRules();
+
+ private:
+ SettingsProvider* settings_;
+ bool storingSettings_;
+
+ boost::shared_ptr<HighlightManager::HighlightRulesList> rules_;
+ boost::bsignals::scoped_connection handleSettingChangedConnection_;
+ };
+
+ typedef boost::shared_ptr<const HighlightManager::HighlightRulesList> HighlightRulesListPtr;
}
diff --git a/Swift/Controllers/HighlightRule.cpp b/Swift/Controllers/HighlightRule.cpp
index 021e15d..86ac5f7 100644
--- a/Swift/Controllers/HighlightRule.cpp
+++ b/Swift/Controllers/HighlightRule.cpp
@@ -23,179 +23,179 @@
namespace Swift {
HighlightRule::HighlightRule()
- : nickIsKeyword_(false)
- , matchCase_(false)
- , matchWholeWords_(false)
- , matchChat_(false)
- , matchMUC_(false)
+ : 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);
+ 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_) {
- keywordRegex_.push_back(regexFromString(k));
- }
- senderRegex_.clear();
- foreach (const std::string & s, senders_) {
- senderRegex_.push_back(regexFromString(s));
- }
+ keywordRegex_.clear();
+ foreach (const std::string & k, keywords_) {
+ keywordRegex_.push_back(regexFromString(k));
+ }
+ senderRegex_.clear();
+ foreach (const std::string & s, senders_) {
+ senderRegex_.push_back(regexFromString(s));
+ }
}
std::string HighlightRule::boolToString(bool b)
{
- return b ? "1" : "0";
+ return b ? "1" : "0";
}
bool HighlightRule::boolFromString(const std::string& s)
{
- return s == "1";
+ 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_) {
- if (boost::regex_search(body, keyword)) {
- matchesKeyword = true;
- break;
- }
- }
- }
- }
-
- foreach (const boost::regex & rx, senderRegex_) {
- if (boost::regex_search(sender, rx)) {
- matchesSender = true;
- break;
- }
- }
-
- if (matchesKeyword && matchesSender) {
- return true;
- }
- }
-
- return false;
+ 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_) {
+ if (boost::regex_search(body, keyword)) {
+ matchesKeyword = true;
+ break;
+ }
+ }
+ }
+ }
+
+ foreach (const boost::regex & 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();
+ senders_ = senders;
+ updateRegex();
}
void HighlightRule::setKeywords(const std::vector<std::string>& keywords)
{
- keywords_ = keywords;
- updateRegex();
+ keywords_ = keywords;
+ updateRegex();
}
std::vector<boost::regex> HighlightRule::getKeywordRegex(const std::string& nick) const {
- if (nickIsKeyword_) {
- std::vector<boost::regex> regex;
- if (!nick.empty()) {
- regex.push_back(regexFromString(nick));
- }
- return regex;
- } else {
- return keywordRegex_;
- }
+ if (nickIsKeyword_) {
+ std::vector<boost::regex> regex;
+ if (!nick.empty()) {
+ regex.push_back(regexFromString(nick));
+ }
+ return regex;
+ } else {
+ return keywordRegex_;
+ }
}
void HighlightRule::setNickIsKeyword(bool nickIsKeyword)
{
- nickIsKeyword_ = nickIsKeyword;
- updateRegex();
+ nickIsKeyword_ = nickIsKeyword;
+ updateRegex();
}
void HighlightRule::setMatchCase(bool matchCase)
{
- matchCase_ = matchCase;
- updateRegex();
+ matchCase_ = matchCase;
+ updateRegex();
}
void HighlightRule::setMatchWholeWords(bool matchWholeWords)
{
- matchWholeWords_ = matchWholeWords;
- updateRegex();
+ matchWholeWords_ = matchWholeWords;
+ updateRegex();
}
void HighlightRule::setMatchChat(bool matchChat)
{
- matchChat_ = matchChat;
- updateRegex();
+ matchChat_ = matchChat;
+ updateRegex();
}
void HighlightRule::setMatchMUC(bool matchMUC)
{
- matchMUC_ = matchMUC;
- updateRegex();
+ matchMUC_ = matchMUC;
+ updateRegex();
}
bool HighlightRule::isEmpty() const
{
- return senders_.empty() && keywords_.empty() && !nickIsKeyword_ && !matchChat_ && !matchMUC_ && action_.isEmpty();
+ return senders_.empty() && keywords_.empty() && !nickIsKeyword_ && !matchChat_ && !matchMUC_ && action_.isEmpty();
}
bool operator ==(HighlightRule const& a, HighlightRule const& b) {
- if (a.getSenders() != b.getSenders()) {
- return false;
- }
+ if (a.getSenders() != b.getSenders()) {
+ return false;
+ }
- if (a.getKeywords() != b.getKeywords()) {
- return false;
- }
+ if (a.getKeywords() != b.getKeywords()) {
+ return false;
+ }
- if (a.getNickIsKeyword() != b.getNickIsKeyword()) {
- return false;
- }
+ if (a.getNickIsKeyword() != b.getNickIsKeyword()) {
+ return false;
+ }
- if (a.getMatchChat() != b.getMatchChat()) {
- return false;
- }
+ if (a.getMatchChat() != b.getMatchChat()) {
+ return false;
+ }
- if (a.getMatchMUC() != b.getMatchMUC()) {
- return false;
- }
+ if (a.getMatchMUC() != b.getMatchMUC()) {
+ return false;
+ }
- if (a.getMatchCase() != b.getMatchCase()) {
- return false;
- }
+ if (a.getMatchCase() != b.getMatchCase()) {
+ return false;
+ }
- if (a.getMatchWholeWords() != b.getMatchWholeWords()) {
- return false;
- }
+ if (a.getMatchWholeWords() != b.getMatchWholeWords()) {
+ return false;
+ }
- if (a.getAction() != b.getAction()) {
- return false;
- }
+ if (a.getAction() != b.getAction()) {
+ return false;
+ }
- return true;
+ return true;
}
}
diff --git a/Swift/Controllers/HighlightRule.h b/Swift/Controllers/HighlightRule.h
index caacaee..bffdc41 100644
--- a/Swift/Controllers/HighlightRule.h
+++ b/Swift/Controllers/HighlightRule.h
@@ -23,81 +23,81 @@
namespace Swift {
- class HighlightRule {
- public:
- HighlightRule();
+ class HighlightRule {
+ public:
+ HighlightRule();
- enum MessageType { ChatMessage, MUCMessage };
+ enum MessageType { ChatMessage, MUCMessage };
- bool isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType) const;
+ bool isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType) const;
- const HighlightAction& getAction() const { return action_; }
- HighlightAction& getAction() { return action_; }
+ const HighlightAction& getAction() const { return action_; }
+ HighlightAction& getAction() { return action_; }
- const std::vector<std::string>& getSenders() const { return senders_; }
- void setSenders(const std::vector<std::string>&);
- const std::vector<boost::regex>& getSenderRegex() const { return senderRegex_; }
+ const std::vector<std::string>& getSenders() const { return senders_; }
+ void setSenders(const std::vector<std::string>&);
+ const std::vector<boost::regex>& getSenderRegex() const { return senderRegex_; }
- const std::vector<std::string>& getKeywords() const { return keywords_; }
- void setKeywords(const std::vector<std::string>&);
- std::vector<boost::regex> getKeywordRegex(const std::string& nick) const;
+ const std::vector<std::string>& getKeywords() const { return keywords_; }
+ void setKeywords(const std::vector<std::string>&);
+ std::vector<boost::regex> getKeywordRegex(const std::string& nick) const;
- bool getNickIsKeyword() const { return nickIsKeyword_; }
- void setNickIsKeyword(bool);
+ bool getNickIsKeyword() const { return nickIsKeyword_; }
+ void setNickIsKeyword(bool);
- bool getMatchCase() const { return matchCase_; }
- void setMatchCase(bool);
+ bool getMatchCase() const { return matchCase_; }
+ void setMatchCase(bool);
- bool getMatchWholeWords() const { return matchWholeWords_; }
- void setMatchWholeWords(bool);
+ bool getMatchWholeWords() const { return matchWholeWords_; }
+ void setMatchWholeWords(bool);
- bool getMatchChat() const { return matchChat_; }
- void setMatchChat(bool);
+ bool getMatchChat() const { return matchChat_; }
+ void setMatchChat(bool);
- bool getMatchMUC() const { return matchMUC_; }
- void setMatchMUC(bool);
+ bool getMatchMUC() const { return matchMUC_; }
+ void setMatchMUC(bool);
- bool isEmpty() const;
+ bool isEmpty() const;
- private:
- friend class boost::serialization::access;
- template<class Archive> void serialize(Archive & ar, const unsigned int version);
+ private:
+ friend class boost::serialization::access;
+ template<class Archive> void serialize(Archive & ar, const unsigned int version);
- static std::string boolToString(bool);
- static bool boolFromString(const std::string&);
+ static std::string boolToString(bool);
+ static bool boolFromString(const std::string&);
- std::vector<std::string> senders_;
- std::vector<std::string> keywords_;
- bool nickIsKeyword_;
+ std::vector<std::string> senders_;
+ std::vector<std::string> keywords_;
+ bool nickIsKeyword_;
- mutable std::vector<boost::regex> senderRegex_;
- mutable std::vector<boost::regex> keywordRegex_;
- void updateRegex() const;
- boost::regex regexFromString(const std::string&) const;
+ mutable std::vector<boost::regex> senderRegex_;
+ mutable std::vector<boost::regex> keywordRegex_;
+ void updateRegex() const;
+ boost::regex regexFromString(const std::string&) const;
- bool matchCase_;
- bool matchWholeWords_;
+ bool matchCase_;
+ bool matchWholeWords_;
- bool matchChat_;
- bool matchMUC_;
+ bool matchChat_;
+ bool matchMUC_;
- HighlightAction action_;
- };
+ HighlightAction action_;
+ };
- bool operator ==(HighlightRule const& a, HighlightRule const& b);
+ bool operator ==(HighlightRule const& a, HighlightRule const& b);
- template<class Archive>
- void HighlightRule::serialize(Archive& ar, const unsigned int /*version*/)
- {
- ar & senders_;
- ar & keywords_;
- ar & nickIsKeyword_;
- ar & matchChat_;
- ar & matchMUC_;
- ar & matchCase_;
- ar & matchWholeWords_;
- ar & action_;
- updateRegex();
- }
+ template<class Archive>
+ void HighlightRule::serialize(Archive& ar, const unsigned int /*version*/)
+ {
+ ar & senders_;
+ ar & keywords_;
+ ar & nickIsKeyword_;
+ ar & matchChat_;
+ ar & matchMUC_;
+ ar & matchCase_;
+ ar & matchWholeWords_;
+ ar & action_;
+ updateRegex();
+ }
}
diff --git a/Swift/Controllers/Highlighter.cpp b/Swift/Controllers/Highlighter.cpp
index 40f92ba..3499217 100644
--- a/Swift/Controllers/Highlighter.cpp
+++ b/Swift/Controllers/Highlighter.cpp
@@ -19,35 +19,35 @@
namespace Swift {
Highlighter::Highlighter(HighlightManager* manager)
- : manager_(manager)
+ : manager_(manager)
{
- setMode(ChatMode);
+ setMode(ChatMode);
}
void Highlighter::setMode(Mode mode)
{
- mode_ = mode;
- messageType_ = mode_ == ChatMode ? HighlightRule::ChatMessage : HighlightRule::MUCMessage;
+ 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;
+ 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;
}
void Highlighter::handleHighlightAction(const HighlightAction& action)
{
- manager_->onHighlight(action);
+ manager_->onHighlight(action);
}
}
diff --git a/Swift/Controllers/Highlighter.h b/Swift/Controllers/Highlighter.h
index 5d5f531..9ad3339 100644
--- a/Swift/Controllers/Highlighter.h
+++ b/Swift/Controllers/Highlighter.h
@@ -19,27 +19,27 @@
namespace Swift {
- class HighlightManager;
+ class HighlightManager;
- class Highlighter {
- public:
- Highlighter(HighlightManager* manager);
+ class Highlighter {
+ public:
+ Highlighter(HighlightManager* manager);
- enum Mode { ChatMode, MUCMode };
- void setMode(Mode mode);
+ enum Mode { ChatMode, MUCMode };
+ void setMode(Mode mode);
- void setNick(const std::string& nick) { nick_ = nick; }
- std::string getNick() const { return nick_; }
+ void setNick(const std::string& nick) { nick_ = nick; }
+ std::string getNick() const { return nick_; }
- HighlightAction findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const;
+ HighlightAction findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const;
- void handleHighlightAction(const HighlightAction& action);
+ void handleHighlightAction(const HighlightAction& action);
- private:
- HighlightManager* manager_;
- Mode mode_;
- HighlightRule::MessageType messageType_;
- std::string nick_;
- };
+ private:
+ HighlightManager* manager_;
+ Mode mode_;
+ HighlightRule::MessageType messageType_;
+ std::string nick_;
+ };
}
diff --git a/Swift/Controllers/HistoryController.cpp b/Swift/Controllers/HistoryController.cpp
index f439429..1e5830c 100644
--- a/Swift/Controllers/HistoryController.cpp
+++ b/Swift/Controllers/HistoryController.cpp
@@ -28,39 +28,39 @@ HistoryController::~HistoryController() {
}
void HistoryController::addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp) {
- // note: using localtime timestamps
- boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(timeStamp);
- int offset = (localTime - timeStamp).hours();
+ // note: using localtime timestamps
+ boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(timeStamp);
+ int offset = (localTime - timeStamp).hours();
- HistoryMessage historyMessage(message, fromJID, toJID, type, localTime, offset);
+ HistoryMessage historyMessage(message, fromJID, toJID, type, localTime, offset);
- localHistory_->addMessage(historyMessage);
- onNewMessage(historyMessage);
+ localHistory_->addMessage(historyMessage);
+ onNewMessage(historyMessage);
}
std::vector<HistoryMessage> HistoryController::getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- return localHistory_->getMessagesFromDate(selfJID, contactJID, type, date);
+ return localHistory_->getMessagesFromDate(selfJID, contactJID, type, date);
}
std::vector<HistoryMessage> HistoryController::getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const {
- boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(timeStamp);
- return getMessagesFromDate(selfJID, mucJID, HistoryMessage::Groupchat, localTime.date());
+ boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(timeStamp);
+ return getMessagesFromDate(selfJID, mucJID, HistoryMessage::Groupchat, localTime.date());
}
std::vector<HistoryMessage> HistoryController::getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- return localHistory_->getMessagesFromPreviousDate(selfJID, contactJID, type, date);
+ return localHistory_->getMessagesFromPreviousDate(selfJID, contactJID, type, date);
}
std::vector<HistoryMessage> HistoryController::getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- return localHistory_->getMessagesFromNextDate(selfJID, contactJID, type, date);
+ return localHistory_->getMessagesFromNextDate(selfJID, contactJID, type, date);
}
ContactsMap HistoryController::getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const {
- return localHistory_->getContacts(selfJID, type, keyword);
+ return localHistory_->getContacts(selfJID, type, keyword);
}
boost::posix_time::ptime HistoryController::getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) {
- return localHistory_->getLastTimeStampFromMUC(selfJID, mucJID);
+ return localHistory_->getLastTimeStampFromMUC(selfJID, mucJID);
}
}
diff --git a/Swift/Controllers/HistoryController.h b/Swift/Controllers/HistoryController.h
index 0bdbb35..f1f613f 100644
--- a/Swift/Controllers/HistoryController.h
+++ b/Swift/Controllers/HistoryController.h
@@ -21,25 +21,25 @@
#include <Swiften/History/HistoryStorage.h>
namespace Swift {
- class JID;
+ class JID;
- class HistoryController {
- public:
- HistoryController(HistoryStorage* localHistoryStorage);
- ~HistoryController();
+ class HistoryController {
+ public:
+ HistoryController(HistoryStorage* localHistoryStorage);
+ ~HistoryController();
- void addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp);
- std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword = std::string()) const;
- std::vector<HistoryMessage> getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const;
+ void addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp);
+ std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword = std::string()) const;
+ std::vector<HistoryMessage> getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const;
- boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID);
+ boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID);
- boost::signal<void (const HistoryMessage&)> onNewMessage;
+ boost::signal<void (const HistoryMessage&)> onNewMessage;
- private:
- HistoryStorage* localHistory_;
- };
+ private:
+ HistoryStorage* localHistory_;
+ };
}
diff --git a/Swift/Controllers/HistoryViewController.cpp b/Swift/Controllers/HistoryViewController.cpp
index 2d56b9e..d0ccc66 100644
--- a/Swift/Controllers/HistoryViewController.cpp
+++ b/Swift/Controllers/HistoryViewController.cpp
@@ -25,335 +25,335 @@
#include <Swift/Controllers/UIInterfaces/HistoryWindowFactory.h>
namespace Swift {
- static const std::string category[] = { "Contacts", "MUC", "Contacts" };
+ 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_(NULL),
- selectedItem_(NULL),
- currentResultDate_(boost::gregorian::not_a_date_time) {
- uiEventStream_->onUIEvent.connect(boost::bind(&HistoryViewController::handleUIEvent, this, _1));
-
- roster_ = new Roster(false, true);
+ 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_(NULL),
+ selectedItem_(NULL),
+ currentResultDate_(boost::gregorian::not_a_date_time) {
+ uiEventStream_->onUIEvent.connect(boost::bind(&HistoryViewController::handleUIEvent, this, _1));
+
+ roster_ = new Roster(false, true);
}
HistoryViewController::~HistoryViewController() {
- uiEventStream_->onUIEvent.disconnect(boost::bind(&HistoryViewController::handleUIEvent, this, _1));
- if (historyWindow_) {
- historyWindow_->onSelectedContactChanged.disconnect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1));
- historyWindow_->onReturnPressed.disconnect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1));
- historyWindow_->onScrollReachedTop.disconnect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1));
- historyWindow_->onScrollReachedBottom.disconnect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1));
- historyWindow_->onPreviousButtonClicked.disconnect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this));
- historyWindow_->onNextButtonClicked.disconnect(boost::bind(&HistoryViewController::handleNextButtonClicked, this));
- historyWindow_->onCalendarClicked.disconnect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1));
- historyController_->onNewMessage.disconnect(boost::bind(&HistoryViewController::handleNewMessage, this, _1));
-
- presenceOracle_->onPresenceChange.disconnect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1));
- avatarManager_->onAvatarChanged.disconnect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1));
-
- delete historyWindow_;
- }
- delete roster_;
+ uiEventStream_->onUIEvent.disconnect(boost::bind(&HistoryViewController::handleUIEvent, this, _1));
+ if (historyWindow_) {
+ historyWindow_->onSelectedContactChanged.disconnect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1));
+ historyWindow_->onReturnPressed.disconnect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1));
+ historyWindow_->onScrollReachedTop.disconnect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1));
+ historyWindow_->onScrollReachedBottom.disconnect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1));
+ historyWindow_->onPreviousButtonClicked.disconnect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this));
+ historyWindow_->onNextButtonClicked.disconnect(boost::bind(&HistoryViewController::handleNextButtonClicked, this));
+ historyWindow_->onCalendarClicked.disconnect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1));
+ historyController_->onNewMessage.disconnect(boost::bind(&HistoryViewController::handleNewMessage, this, _1));
+
+ presenceOracle_->onPresenceChange.disconnect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1));
+ avatarManager_->onAvatarChanged.disconnect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1));
+
+ delete historyWindow_;
+ }
+ delete roster_;
}
void HistoryViewController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent) {
- boost::shared_ptr<RequestHistoryUIEvent> event = boost::dynamic_pointer_cast<RequestHistoryUIEvent>(rawEvent);
- if (event != NULL) {
- if (historyWindow_ == NULL) {
- historyWindow_ = historyWindowFactory_->createHistoryWindow(uiEventStream_);
- historyWindow_->onSelectedContactChanged.connect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1));
- historyWindow_->onReturnPressed.connect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1));
- historyWindow_->onScrollReachedTop.connect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1));
- historyWindow_->onScrollReachedBottom.connect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1));
- historyWindow_->onPreviousButtonClicked.connect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this));
- historyWindow_->onNextButtonClicked.connect(boost::bind(&HistoryViewController::handleNextButtonClicked, this));
- historyWindow_->onCalendarClicked.connect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1));
- historyController_->onNewMessage.connect(boost::bind(&HistoryViewController::handleNewMessage, this, _1));
-
- presenceOracle_->onPresenceChange.connect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1));
- avatarManager_->onAvatarChanged.connect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1));
-
- historyWindow_->setRosterModel(roster_);
- }
-
- // populate roster by doing an empty search
- handleReturnPressed(std::string());
-
- historyWindow_->activate();
- }
+ boost::shared_ptr<RequestHistoryUIEvent> event = boost::dynamic_pointer_cast<RequestHistoryUIEvent>(rawEvent);
+ if (event != NULL) {
+ if (historyWindow_ == NULL) {
+ historyWindow_ = historyWindowFactory_->createHistoryWindow(uiEventStream_);
+ historyWindow_->onSelectedContactChanged.connect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1));
+ historyWindow_->onReturnPressed.connect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1));
+ historyWindow_->onScrollReachedTop.connect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1));
+ historyWindow_->onScrollReachedBottom.connect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1));
+ historyWindow_->onPreviousButtonClicked.connect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this));
+ historyWindow_->onNextButtonClicked.connect(boost::bind(&HistoryViewController::handleNextButtonClicked, this));
+ historyWindow_->onCalendarClicked.connect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1));
+ historyController_->onNewMessage.connect(boost::bind(&HistoryViewController::handleNewMessage, this, _1));
+
+ presenceOracle_->onPresenceChange.connect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1));
+ avatarManager_->onAvatarChanged.connect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1));
+
+ historyWindow_->setRosterModel(roster_);
+ }
+
+ // populate roster by doing an empty search
+ handleReturnPressed(std::string());
+
+ historyWindow_->activate();
+ }
}
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) {
- addNewMessage(message, false);
- }
+ // 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) {
+ 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));
- }
-
- contacts_[message.getType()][displayJID].insert(message.getTime().date());
+ 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));
+ }
+
+ contacts_[message.getType()][displayJID].insert(message.getTime().date());
}
void HistoryViewController::addNewMessage(const HistoryMessage& message, bool addAtTheTop) {
- bool senderIsSelf = message.getFromJID().toBare() == selfJID_;
- std::string avatarPath = pathToString(avatarManager_->getAvatarPath(message.getFromJID()));
+ bool senderIsSelf = message.getFromJID().toBare() == selfJID_;
+ std::string avatarPath = pathToString(avatarManager_->getAvatarPath(message.getFromJID()));
- std::string nick = message.getType() != HistoryMessage::Groupchat ? nickResolver_->jidToNick(message.getFromJID()) : message.getFromJID().getResource();
- historyWindow_->addMessage(message.getMessage(), nick, senderIsSelf, avatarPath, message.getTime(), addAtTheTop);
+ std::string nick = message.getType() != HistoryMessage::Groupchat ? nickResolver_->jidToNick(message.getFromJID()) : message.getFromJID().getResource();
+ historyWindow_->addMessage(message.getMessage(), nick, senderIsSelf, avatarPath, message.getTime(), addAtTheTop);
}
void HistoryViewController::handleReturnPressed(const std::string& keyword) {
- reset();
-
- for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) {
- HistoryMessage::Type type = static_cast<HistoryMessage::Type>(it);
-
- 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);
- }
- }
- }
+ reset();
+
+ for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) {
+ HistoryMessage::Type type = static_cast<HistoryMessage::Type>(it);
+
+ 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;
- }
+ if (!selectedItem_) {
+ return;
+ }
- std::vector<HistoryMessage> messages = historyController_->getMessagesFromPreviousDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
+ std::vector<HistoryMessage> messages = historyController_->getMessagesFromPreviousDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
- foreach (const HistoryMessage& message, messages) {
- addNewMessage(message, true);
- }
- historyWindow_->resetConversationViewTopInsertPoint();
+ foreach (const HistoryMessage& message, messages) {
+ addNewMessage(message, true);
+ }
+ historyWindow_->resetConversationViewTopInsertPoint();
}
void HistoryViewController::handleScrollReachedBottom(const boost::gregorian::date& date) {
- if (!selectedItem_) {
- return;
- }
+ if (!selectedItem_) {
+ return;
+ }
- std::vector<HistoryMessage> messages = historyController_->getMessagesFromNextDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
+ std::vector<HistoryMessage> messages = historyController_->getMessagesFromNextDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date);
- foreach (const HistoryMessage& message, messages) {
- addNewMessage(message, false);
- }
+ foreach (const HistoryMessage& message, messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::handleNextButtonClicked() {
- if (!selectedItem_) {
- return;
- }
+ if (!selectedItem_) {
+ return;
+ }
- std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
+ std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
- if (*date == *contacts_[selectedItemType_][selectedItem_->getJID()].rbegin()) {
- return;
- }
+ 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_);
+ historyWindow_->resetConversationView();
+ currentResultDate_ = *(++date);
+ std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
+ historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
- addNewMessage(message, false);
- }
+ foreach (const HistoryMessage& message, messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::handlePreviousButtonClicked() {
- if (!selectedItem_) {
- return;
- }
+ if (!selectedItem_) {
+ return;
+ }
- std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
+ std::set<boost::gregorian::date>::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_);
- if (date == contacts_[selectedItemType_][selectedItem_->getJID()].begin()) {
- return;
- }
+ 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_);
+ historyWindow_->resetConversationView();
+ currentResultDate_ = *(--date);
+ std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
+ historyWindow_->setDate(currentResultDate_);
- foreach (const HistoryMessage& message, messages) {
- addNewMessage(message, false);
- }
+ foreach (const HistoryMessage& message, messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::reset() {
- roster_->removeAll();
- contacts_.clear();
- selectedItem_ = NULL;
- historyWindow_->resetConversationView();
+ roster_->removeAll();
+ contacts_.clear();
+ selectedItem_ = NULL;
+ 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()]) {
- if (current > date) {
- newDate = current;
- break;
- }
- }
- }
- else {
- reverse_foreach(const boost::gregorian::date& current, 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) {
- addNewMessage(message, false);
- }
+ 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()]) {
+ if (current > date) {
+ newDate = current;
+ break;
+ }
+ }
+ }
+ else {
+ reverse_foreach(const boost::gregorian::date& current, 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) {
+ 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 = boost::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));
- }
+ 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 = boost::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)));
+ roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid)));
}
Presence::ref HistoryViewController::getPresence(const JID& jid, bool isMUC) {
- if (jid.isBare() && !isMUC) {
- return presenceOracle_->getHighestPriorityPresence(jid);
- }
+ if (jid.isBare() && !isMUC) {
+ return presenceOracle_->getHighestPriorityPresence(jid);
+ }
- std::vector<Presence::ref> mucPresence = presenceOracle_->getAllPresence(jid.toBare());
+ std::vector<Presence::ref> mucPresence = presenceOracle_->getAllPresence(jid.toBare());
- if (isMUC && !mucPresence.empty()) {
- Presence::ref presence = boost::make_shared<Presence>(Presence());
- presence->setFrom(jid);
- return presence;
- }
+ if (isMUC && !mucPresence.empty()) {
+ Presence::ref presence = boost::make_shared<Presence>(Presence());
+ presence->setFrom(jid);
+ return presence;
+ }
- foreach (Presence::ref presence, mucPresence) {
- if (presence.get() && presence->getFrom() == jid) {
- return presence;
- }
- }
+ foreach (Presence::ref presence, mucPresence) {
+ if (presence.get() && presence->getFrom() == jid) {
+ return presence;
+ }
+ }
- return Presence::create();
+ return Presence::create();
}
}
diff --git a/Swift/Controllers/HistoryViewController.h b/Swift/Controllers/HistoryViewController.h
index b388160..463ee06 100644
--- a/Swift/Controllers/HistoryViewController.h
+++ b/Swift/Controllers/HistoryViewController.h
@@ -25,51 +25,51 @@
#include <Swift/Controllers/UIEvents/UIEventStream.h>
namespace Swift {
- class HistoryWindowFactory;
- class HistoryWindow;
- class Roster;
- class RosterItem;
- class ContactRosterItem;
- class HistoryController;
- class NickResolver;
- class AvatarManager;
+ class HistoryWindowFactory;
+ class HistoryWindow;
+ class Roster;
+ class RosterItem;
+ class ContactRosterItem;
+ class HistoryController;
+ class NickResolver;
+ class AvatarManager;
- class HistoryViewController {
- public:
- HistoryViewController(const JID& selfJID, UIEventStream* uiEventStream, HistoryController* historyController, NickResolver* nickResolver, AvatarManager* avatarManager, PresenceOracle* presenceOracle, HistoryWindowFactory* historyWindowFactory);
- ~HistoryViewController();
+ class HistoryViewController {
+ public:
+ HistoryViewController(const JID& selfJID, UIEventStream* uiEventStream, HistoryController* historyController, NickResolver* nickResolver, AvatarManager* avatarManager, PresenceOracle* presenceOracle, HistoryWindowFactory* historyWindowFactory);
+ ~HistoryViewController();
- private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleSelectedContactChanged(RosterItem* item);
- void handleNewMessage(const HistoryMessage& message);
- void handleReturnPressed(const std::string& keyword);
- void handleScrollReachedTop(const boost::gregorian::date& date);
- void handleScrollReachedBottom(const boost::gregorian::date& date);
- void handlePreviousButtonClicked();
- void handleNextButtonClicked();
- void handleCalendarClicked(const boost::gregorian::date& date);
- void handlePresenceChanged(Presence::ref presence);
- void handleAvatarChanged(const JID& jid);
+ private:
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleSelectedContactChanged(RosterItem* item);
+ void handleNewMessage(const HistoryMessage& message);
+ void handleReturnPressed(const std::string& keyword);
+ void handleScrollReachedTop(const boost::gregorian::date& date);
+ void handleScrollReachedBottom(const boost::gregorian::date& date);
+ void handlePreviousButtonClicked();
+ void handleNextButtonClicked();
+ void handleCalendarClicked(const boost::gregorian::date& date);
+ void handlePresenceChanged(Presence::ref presence);
+ void handleAvatarChanged(const JID& jid);
- void addNewMessage(const HistoryMessage& message, bool addAtTheTop);
- void reset();
- Presence::ref getPresence(const JID& jid, bool isMUC);
+ void addNewMessage(const HistoryMessage& message, bool addAtTheTop);
+ void reset();
+ Presence::ref getPresence(const JID& jid, bool isMUC);
- private:
- JID selfJID_;
- UIEventStream* uiEventStream_;
- HistoryController* historyController_;
- NickResolver* nickResolver_;
- AvatarManager* avatarManager_;
- PresenceOracle* presenceOracle_;
- HistoryWindowFactory* historyWindowFactory_;
- HistoryWindow* historyWindow_;
- Roster* roster_;
+ private:
+ JID selfJID_;
+ UIEventStream* uiEventStream_;
+ HistoryController* historyController_;
+ NickResolver* nickResolver_;
+ AvatarManager* avatarManager_;
+ PresenceOracle* presenceOracle_;
+ HistoryWindowFactory* historyWindowFactory_;
+ HistoryWindow* historyWindow_;
+ Roster* roster_;
- std::map<HistoryMessage::Type, ContactsMap> contacts_;
- ContactRosterItem* selectedItem_;
- HistoryMessage::Type selectedItemType_;
- boost::gregorian::date currentResultDate_;
- };
+ std::map<HistoryMessage::Type, ContactsMap> contacts_;
+ ContactRosterItem* selectedItem_;
+ HistoryMessage::Type selectedItemType_;
+ boost::gregorian::date currentResultDate_;
+ };
}
diff --git a/Swift/Controllers/Intl.h b/Swift/Controllers/Intl.h
index 386696a..c599493 100644
--- a/Swift/Controllers/Intl.h
+++ b/Swift/Controllers/Intl.h
@@ -8,4 +8,4 @@
#include <Swift/Controllers/Translator.h>
#define QT_TRANSLATE_NOOP(context, text) \
- Swift::Translator::getInstance()->translate(text, context)
+ Swift::Translator::getInstance()->translate(text, context)
diff --git a/Swift/Controllers/MainController.cpp b/Swift/Controllers/MainController.cpp
index 9f61b2b..b48059c 100644
--- a/Swift/Controllers/MainController.cpp
+++ b/Swift/Controllers/MainController.cpp
@@ -99,749 +99,749 @@ static const std::string CLIENT_NODE = "http://swift.im";
MainController::MainController(
- EventLoop* eventLoop,
- NetworkFactories* networkFactories,
- UIFactory* uiFactories,
- SettingsProvider* settings,
- SystemTray* systemTray,
- SoundPlayer* soundPlayer,
- StoragesFactory* storagesFactory,
- CertificateStorageFactory* certificateStorageFactory,
- Dock* dock,
- Notifier* notifier,
- URIHandler* uriHandler,
- IdleDetector* idleDetector,
- const std::map<std::string, std::string>& emoticons,
- bool useDelayForLatency) :
- eventLoop_(eventLoop),
- networkFactories_(networkFactories),
- uiFactory_(uiFactories),
- storagesFactory_(storagesFactory),
- certificateStorageFactory_(certificateStorageFactory),
- settings_(settings),
- uriHandler_(uriHandler),
- idleDetector_(idleDetector),
- loginWindow_(NULL) ,
- useDelayForLatency_(useDelayForLatency),
- ftOverview_(NULL),
- emoticons_(emoticons) {
- storages_ = NULL;
- certificateStorage_ = NULL;
- certificateTrustChecker_ = NULL;
- statusTracker_ = NULL;
- presenceNotifier_ = NULL;
- eventNotifier_ = NULL;
- rosterController_ = NULL;
- chatsManager_ = NULL;
- historyController_ = NULL;
- historyViewController_ = NULL;
- eventWindowController_ = NULL;
- profileController_ = NULL;
- blockListController_ = NULL;
- showProfileController_ = NULL;
- contactEditController_ = NULL;
- userSearchControllerChat_ = NULL;
- userSearchControllerAdd_ = NULL;
- userSearchControllerInvite_ = NULL;
- contactsFromRosterProvider_ = NULL;
- contactSuggesterWithoutRoster_ = NULL;
- contactSuggesterWithRoster_ = NULL;
- whiteboardManager_ = NULL;
- adHocManager_ = NULL;
- quitRequested_ = false;
- clientInitialized_ = false;
- offlineRequested_ = false;
-
- timeBeforeNextReconnect_ = -1;
- dock_ = dock;
- uiEventStream_ = new UIEventStream();
-
- notifier_ = new TogglableNotifier(notifier);
- notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- eventController_ = new EventController();
- eventController_->onEventQueueLengthChange.connect(boost::bind(&MainController::handleEventQueueLengthChange, this, _1));
-
- systemTrayController_ = new SystemTrayController(eventController_, systemTray);
- loginWindow_ = uiFactory_->createLoginWindow(uiEventStream_);
- loginWindow_->setShowNotificationToggle(!notifier->isExternallyConfigured());
-
- highlightManager_ = new HighlightManager(settings_);
- highlightEditorController_ = new HighlightEditorController(uiEventStream_, uiFactory_, highlightManager_);
-
- soundEventController_ = new SoundEventController(eventController_, soundPlayer, settings, highlightManager_);
-
- xmppURIController_ = new XMPPURIController(uriHandler_, uiEventStream_);
-
- std::string selectedLoginJID = settings_->getSetting(SettingConstants::LAST_LOGIN_JID);
- bool loginAutomatically = settings_->getSetting(SettingConstants::LOGIN_AUTOMATICALLY);
- std::string cachedPassword;
- std::string cachedCertificate;
- ClientOptions cachedOptions;
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- if (!eagle) {
- foreach (std::string profile, settings->getAvailableProfiles()) {
- ProfileSettingsProvider profileSettings(profile, settings);
- std::string password = profileSettings.getStringSetting("pass");
- std::string certificate = profileSettings.getStringSetting("certificate");
- std::string jid = profileSettings.getStringSetting("jid");
- ClientOptions clientOptions = parseClientOptions(profileSettings.getStringSetting("options"));
+ EventLoop* eventLoop,
+ NetworkFactories* networkFactories,
+ UIFactory* uiFactories,
+ SettingsProvider* settings,
+ SystemTray* systemTray,
+ SoundPlayer* soundPlayer,
+ StoragesFactory* storagesFactory,
+ CertificateStorageFactory* certificateStorageFactory,
+ Dock* dock,
+ Notifier* notifier,
+ URIHandler* uriHandler,
+ IdleDetector* idleDetector,
+ const std::map<std::string, std::string>& emoticons,
+ bool useDelayForLatency) :
+ eventLoop_(eventLoop),
+ networkFactories_(networkFactories),
+ uiFactory_(uiFactories),
+ storagesFactory_(storagesFactory),
+ certificateStorageFactory_(certificateStorageFactory),
+ settings_(settings),
+ uriHandler_(uriHandler),
+ idleDetector_(idleDetector),
+ loginWindow_(NULL) ,
+ useDelayForLatency_(useDelayForLatency),
+ ftOverview_(NULL),
+ emoticons_(emoticons) {
+ storages_ = NULL;
+ certificateStorage_ = NULL;
+ certificateTrustChecker_ = NULL;
+ statusTracker_ = NULL;
+ presenceNotifier_ = NULL;
+ eventNotifier_ = NULL;
+ rosterController_ = NULL;
+ chatsManager_ = NULL;
+ historyController_ = NULL;
+ historyViewController_ = NULL;
+ eventWindowController_ = NULL;
+ profileController_ = NULL;
+ blockListController_ = NULL;
+ showProfileController_ = NULL;
+ contactEditController_ = NULL;
+ userSearchControllerChat_ = NULL;
+ userSearchControllerAdd_ = NULL;
+ userSearchControllerInvite_ = NULL;
+ contactsFromRosterProvider_ = NULL;
+ contactSuggesterWithoutRoster_ = NULL;
+ contactSuggesterWithRoster_ = NULL;
+ whiteboardManager_ = NULL;
+ adHocManager_ = NULL;
+ quitRequested_ = false;
+ clientInitialized_ = false;
+ offlineRequested_ = false;
+
+ timeBeforeNextReconnect_ = -1;
+ dock_ = dock;
+ uiEventStream_ = new UIEventStream();
+
+ notifier_ = new TogglableNotifier(notifier);
+ notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ eventController_ = new EventController();
+ eventController_->onEventQueueLengthChange.connect(boost::bind(&MainController::handleEventQueueLengthChange, this, _1));
+
+ systemTrayController_ = new SystemTrayController(eventController_, systemTray);
+ loginWindow_ = uiFactory_->createLoginWindow(uiEventStream_);
+ loginWindow_->setShowNotificationToggle(!notifier->isExternallyConfigured());
+
+ highlightManager_ = new HighlightManager(settings_);
+ highlightEditorController_ = new HighlightEditorController(uiEventStream_, uiFactory_, highlightManager_);
+
+ soundEventController_ = new SoundEventController(eventController_, soundPlayer, settings, highlightManager_);
+
+ xmppURIController_ = new XMPPURIController(uriHandler_, uiEventStream_);
+
+ std::string selectedLoginJID = settings_->getSetting(SettingConstants::LAST_LOGIN_JID);
+ bool loginAutomatically = settings_->getSetting(SettingConstants::LOGIN_AUTOMATICALLY);
+ std::string cachedPassword;
+ std::string cachedCertificate;
+ ClientOptions cachedOptions;
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ if (!eagle) {
+ foreach (std::string profile, settings->getAvailableProfiles()) {
+ ProfileSettingsProvider profileSettings(profile, settings);
+ std::string password = profileSettings.getStringSetting("pass");
+ std::string certificate = profileSettings.getStringSetting("certificate");
+ std::string jid = profileSettings.getStringSetting("jid");
+ ClientOptions clientOptions = parseClientOptions(profileSettings.getStringSetting("options"));
#ifdef SWIFTEN_PLATFORM_WIN32
- clientOptions.singleSignOn = settings_->getSetting(SettingConstants::SINGLE_SIGN_ON);
+ clientOptions.singleSignOn = settings_->getSetting(SettingConstants::SINGLE_SIGN_ON);
#endif
- loginWindow_->addAvailableAccount(jid, password, certificate, clientOptions);
- if (jid == selectedLoginJID) {
- cachedPassword = password;
- cachedCertificate = certificate;
- cachedOptions = clientOptions;
- }
- }
- loginWindow_->selectUser(selectedLoginJID);
- loginWindow_->setLoginAutomatically(loginAutomatically);
- }
+ loginWindow_->addAvailableAccount(jid, password, certificate, clientOptions);
+ if (jid == selectedLoginJID) {
+ cachedPassword = password;
+ cachedCertificate = certificate;
+ cachedOptions = clientOptions;
+ }
+ }
+ loginWindow_->selectUser(selectedLoginJID);
+ loginWindow_->setLoginAutomatically(loginAutomatically);
+ }
- loginWindow_->onLoginRequest.connect(boost::bind(&MainController::handleLoginRequest, this, _1, _2, _3, _4, _5, _6, _7));
- loginWindow_->onPurgeSavedLoginRequest.connect(boost::bind(&MainController::handlePurgeSavedLoginRequest, this, _1));
- loginWindow_->onCancelLoginRequest.connect(boost::bind(&MainController::handleCancelLoginRequest, this));
- loginWindow_->onQuitRequest.connect(boost::bind(&MainController::handleQuitRequest, this));
+ loginWindow_->onLoginRequest.connect(boost::bind(&MainController::handleLoginRequest, this, _1, _2, _3, _4, _5, _6, _7));
+ loginWindow_->onPurgeSavedLoginRequest.connect(boost::bind(&MainController::handlePurgeSavedLoginRequest, this, _1));
+ loginWindow_->onCancelLoginRequest.connect(boost::bind(&MainController::handleCancelLoginRequest, this));
+ loginWindow_->onQuitRequest.connect(boost::bind(&MainController::handleQuitRequest, this));
- idleDetector_->setIdleTimeSeconds(settings->getSetting(SettingConstants::IDLE_TIMEOUT));
- idleDetector_->onIdleChanged.connect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
+ idleDetector_->setIdleTimeSeconds(settings->getSetting(SettingConstants::IDLE_TIMEOUT));
+ idleDetector_->onIdleChanged.connect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
- xmlConsoleController_ = new XMLConsoleController(uiEventStream_, uiFactory_);
+ xmlConsoleController_ = new XMLConsoleController(uiEventStream_, uiFactory_);
- fileTransferListController_ = new FileTransferListController(uiEventStream_, uiFactory_);
+ fileTransferListController_ = new FileTransferListController(uiEventStream_, uiFactory_);
- settings_->onSettingChanged.connect(boost::bind(&MainController::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.connect(boost::bind(&MainController::handleSettingChanged, this, _1));
- if (loginAutomatically) {
- profileSettings_ = new ProfileSettingsProvider(selectedLoginJID, settings_);
- /* FIXME: deal with autologin with a cert*/
- handleLoginRequest(selectedLoginJID, cachedPassword, cachedCertificate, CertificateWithKey::ref(), cachedOptions, true, true);
- } else {
- profileSettings_ = NULL;
- }
+ if (loginAutomatically) {
+ profileSettings_ = new ProfileSettingsProvider(selectedLoginJID, settings_);
+ /* FIXME: deal with autologin with a cert*/
+ handleLoginRequest(selectedLoginJID, cachedPassword, cachedCertificate, CertificateWithKey::ref(), cachedOptions, true, true);
+ } else {
+ profileSettings_ = NULL;
+ }
}
MainController::~MainController() {
- idleDetector_->onIdleChanged.disconnect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
-
- purgeCachedCredentials();
- //setManagersOffline();
- eventController_->disconnectAll();
-
- resetClient();
- delete highlightEditorController_;
- delete highlightManager_;
- delete fileTransferListController_;
- delete xmlConsoleController_;
- delete xmppURIController_;
- delete soundEventController_;
- delete systemTrayController_;
- delete eventController_;
- delete notifier_;
- delete uiEventStream_;
+ idleDetector_->onIdleChanged.disconnect(boost::bind(&MainController::handleInputIdleChanged, this, _1));
+
+ purgeCachedCredentials();
+ //setManagersOffline();
+ eventController_->disconnectAll();
+
+ resetClient();
+ delete highlightEditorController_;
+ delete highlightManager_;
+ delete fileTransferListController_;
+ delete xmlConsoleController_;
+ delete xmppURIController_;
+ delete soundEventController_;
+ delete systemTrayController_;
+ delete eventController_;
+ delete notifier_;
+ delete uiEventStream_;
}
void MainController::purgeCachedCredentials() {
- safeClear(password_);
+ safeClear(password_);
}
void MainController::resetClient() {
- purgeCachedCredentials();
- resetCurrentError();
- resetPendingReconnects();
- vCardPhotoHash_.clear();
- delete contactEditController_;
- contactEditController_ = NULL;
- delete profileController_;
- profileController_ = NULL;
- delete showProfileController_;
- showProfileController_ = NULL;
- delete eventWindowController_;
- eventWindowController_ = NULL;
- delete chatsManager_;
- chatsManager_ = NULL;
+ purgeCachedCredentials();
+ resetCurrentError();
+ resetPendingReconnects();
+ vCardPhotoHash_.clear();
+ delete contactEditController_;
+ contactEditController_ = NULL;
+ delete profileController_;
+ profileController_ = NULL;
+ delete showProfileController_;
+ showProfileController_ = NULL;
+ delete eventWindowController_;
+ eventWindowController_ = NULL;
+ delete chatsManager_;
+ chatsManager_ = NULL;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- delete historyViewController_;
- historyViewController_ = NULL;
- delete historyController_;
- historyController_ = NULL;
+ delete historyViewController_;
+ historyViewController_ = NULL;
+ delete historyController_;
+ historyController_ = NULL;
#endif
- fileTransferListController_->setFileTransferOverview(NULL);
- delete ftOverview_;
- ftOverview_ = NULL;
- delete blockListController_;
- blockListController_ = NULL;
- delete rosterController_;
- rosterController_ = NULL;
- delete eventNotifier_;
- eventNotifier_ = NULL;
- delete presenceNotifier_;
- presenceNotifier_ = NULL;
- delete certificateTrustChecker_;
- certificateTrustChecker_ = NULL;
- delete certificateStorage_;
- certificateStorage_ = NULL;
- delete storages_;
- storages_ = NULL;
- delete statusTracker_;
- statusTracker_ = NULL;
- delete profileSettings_;
- profileSettings_ = NULL;
- delete userSearchControllerChat_;
- userSearchControllerChat_ = NULL;
- delete userSearchControllerAdd_;
- userSearchControllerAdd_ = NULL;
- delete userSearchControllerInvite_;
- userSearchControllerInvite_ = NULL;
- delete contactSuggesterWithoutRoster_;
- contactSuggesterWithoutRoster_ = NULL;
- delete contactSuggesterWithRoster_;
- contactSuggesterWithRoster_ = NULL;
- delete contactsFromRosterProvider_;
- contactsFromRosterProvider_ = NULL;
- delete adHocManager_;
- adHocManager_ = NULL;
- delete whiteboardManager_;
- whiteboardManager_ = NULL;
- clientInitialized_ = false;
+ fileTransferListController_->setFileTransferOverview(NULL);
+ delete ftOverview_;
+ ftOverview_ = NULL;
+ delete blockListController_;
+ blockListController_ = NULL;
+ delete rosterController_;
+ rosterController_ = NULL;
+ delete eventNotifier_;
+ eventNotifier_ = NULL;
+ delete presenceNotifier_;
+ presenceNotifier_ = NULL;
+ delete certificateTrustChecker_;
+ certificateTrustChecker_ = NULL;
+ delete certificateStorage_;
+ certificateStorage_ = NULL;
+ delete storages_;
+ storages_ = NULL;
+ delete statusTracker_;
+ statusTracker_ = NULL;
+ delete profileSettings_;
+ profileSettings_ = NULL;
+ delete userSearchControllerChat_;
+ userSearchControllerChat_ = NULL;
+ delete userSearchControllerAdd_;
+ userSearchControllerAdd_ = NULL;
+ delete userSearchControllerInvite_;
+ userSearchControllerInvite_ = NULL;
+ delete contactSuggesterWithoutRoster_;
+ contactSuggesterWithoutRoster_ = NULL;
+ delete contactSuggesterWithRoster_;
+ contactSuggesterWithRoster_ = NULL;
+ delete contactsFromRosterProvider_;
+ contactsFromRosterProvider_ = NULL;
+ delete adHocManager_;
+ adHocManager_ = NULL;
+ delete whiteboardManager_;
+ whiteboardManager_ = NULL;
+ clientInitialized_ = false;
}
void MainController::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
- notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- }
+ if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
+ notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ }
}
void MainController::resetPendingReconnects() {
- timeBeforeNextReconnect_ = -1;
- if (reconnectTimer_) {
- reconnectTimer_->stop();
- reconnectTimer_.reset();
- }
- resetCurrentError();
+ timeBeforeNextReconnect_ = -1;
+ if (reconnectTimer_) {
+ reconnectTimer_->stop();
+ reconnectTimer_.reset();
+ }
+ resetCurrentError();
}
void MainController::resetCurrentError() {
- if (lastDisconnectError_) {
- lastDisconnectError_->conclude();
- lastDisconnectError_ = boost::shared_ptr<ErrorEvent>();
- }
+ if (lastDisconnectError_) {
+ lastDisconnectError_->conclude();
+ lastDisconnectError_ = boost::shared_ptr<ErrorEvent>();
+ }
}
void MainController::handleConnected() {
- boundJID_ = client_->getJID();
- resetCurrentError();
- resetPendingReconnects();
-
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- purgeCachedCredentials();
- }
-
- bool freshLogin = rosterController_ == NULL;
- myStatusLooksOnline_ = true;
- if (freshLogin) {
- profileController_ = new ProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
- showProfileController_ = new ShowProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
- ftOverview_ = new FileTransferOverview(client_->getFileTransferManager());
- fileTransferListController_->setFileTransferOverview(ftOverview_);
- rosterController_ = new RosterController(boundJID_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager());
- rosterController_->onChangeStatusRequest.connect(boost::bind(&MainController::handleChangeStatusRequest, this, _1, _2));
- rosterController_->onSignOutRequest.connect(boost::bind(&MainController::signOut, this));
- rosterController_->getWindow()->onShowCertificateRequest.connect(boost::bind(&MainController::handleShowCertificateRequest, this));
-
- blockListController_ = new BlockListController(client_->getClientBlockListManager(), uiEventStream_, uiFactory_, eventController_);
-
- contactEditController_ = new ContactEditController(rosterController_, client_->getVCardManager(), uiFactory_, uiEventStream_);
- whiteboardManager_ = new WhiteboardManager(uiFactory_, uiEventStream_, client_->getNickResolver(), client_->getWhiteboardSessionManager());
-
- /* Doing this early as an ordering fix. Various things later will
- * want to have the user's nick available and this means it will
- * be before they receive stanzas that need it (e.g. bookmarks).*/
- client_->getVCardManager()->requestOwnVCard();
-
- contactSuggesterWithoutRoster_ = new ContactSuggester();
- contactSuggesterWithRoster_ = new ContactSuggester();
-
- userSearchControllerInvite_ = new UserSearchController(UserSearchController::InviteToChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
+ boundJID_ = client_->getJID();
+ resetCurrentError();
+ resetPendingReconnects();
+
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ purgeCachedCredentials();
+ }
+
+ bool freshLogin = rosterController_ == NULL;
+ myStatusLooksOnline_ = true;
+ if (freshLogin) {
+ profileController_ = new ProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
+ showProfileController_ = new ShowProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_);
+ ftOverview_ = new FileTransferOverview(client_->getFileTransferManager());
+ fileTransferListController_->setFileTransferOverview(ftOverview_);
+ rosterController_ = new RosterController(boundJID_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager());
+ rosterController_->onChangeStatusRequest.connect(boost::bind(&MainController::handleChangeStatusRequest, this, _1, _2));
+ rosterController_->onSignOutRequest.connect(boost::bind(&MainController::signOut, this));
+ rosterController_->getWindow()->onShowCertificateRequest.connect(boost::bind(&MainController::handleShowCertificateRequest, this));
+
+ blockListController_ = new BlockListController(client_->getClientBlockListManager(), uiEventStream_, uiFactory_, eventController_);
+
+ contactEditController_ = new ContactEditController(rosterController_, client_->getVCardManager(), uiFactory_, uiEventStream_);
+ whiteboardManager_ = new WhiteboardManager(uiFactory_, uiEventStream_, client_->getNickResolver(), client_->getWhiteboardSessionManager());
+
+ /* Doing this early as an ordering fix. Various things later will
+ * want to have the user's nick available and this means it will
+ * be before they receive stanzas that need it (e.g. bookmarks).*/
+ client_->getVCardManager()->requestOwnVCard();
+
+ contactSuggesterWithoutRoster_ = new ContactSuggester();
+ contactSuggesterWithRoster_ = new ContactSuggester();
+
+ userSearchControllerInvite_ = new UserSearchController(UserSearchController::InviteToChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- historyController_ = new HistoryController(storages_->getHistoryStorage());
- historyViewController_ = new HistoryViewController(jid_, uiEventStream_, historyController_, client_->getNickResolver(), client_->getAvatarManager(), client_->getPresenceOracle(), uiFactory_);
- chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, historyController_, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager());
+ historyController_ = new HistoryController(storages_->getHistoryStorage());
+ historyViewController_ = new HistoryViewController(jid_, uiEventStream_, historyController_, client_->getNickResolver(), client_->getAvatarManager(), client_->getPresenceOracle(), uiFactory_);
+ chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, historyController_, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager());
#else
- chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, NULL, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager());
+ chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, NULL, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager());
#endif
- contactsFromRosterProvider_ = new ContactsFromXMPPRoster(client_->getRoster(), client_->getAvatarManager(), client_->getPresenceOracle());
- contactSuggesterWithoutRoster_->addContactProvider(chatsManager_);
- contactSuggesterWithRoster_->addContactProvider(chatsManager_);
- contactSuggesterWithRoster_->addContactProvider(contactsFromRosterProvider_);
- highlightEditorController_->setContactSuggester(contactSuggesterWithoutRoster_);
+ contactsFromRosterProvider_ = new ContactsFromXMPPRoster(client_->getRoster(), client_->getAvatarManager(), client_->getPresenceOracle());
+ contactSuggesterWithoutRoster_->addContactProvider(chatsManager_);
+ contactSuggesterWithRoster_->addContactProvider(chatsManager_);
+ contactSuggesterWithRoster_->addContactProvider(contactsFromRosterProvider_);
+ highlightEditorController_->setContactSuggester(contactSuggesterWithoutRoster_);
- client_->onMessageReceived.connect(boost::bind(&ChatsManager::handleIncomingMessage, chatsManager_, _1));
- chatsManager_->setAvatarManager(client_->getAvatarManager());
+ client_->onMessageReceived.connect(boost::bind(&ChatsManager::handleIncomingMessage, chatsManager_, _1));
+ chatsManager_->setAvatarManager(client_->getAvatarManager());
- eventWindowController_ = new EventWindowController(eventController_, uiFactory_);
+ eventWindowController_ = new EventWindowController(eventController_, uiFactory_);
- loginWindow_->morphInto(rosterController_->getWindow());
+ loginWindow_->morphInto(rosterController_->getWindow());
- DiscoInfo discoInfo;
- discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
- discoInfo.addFeature(DiscoInfo::ChatStatesFeature);
- discoInfo.addFeature(DiscoInfo::SecurityLabelsFeature);
- discoInfo.addFeature(DiscoInfo::MessageCorrectionFeature);
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
+ discoInfo.addFeature(DiscoInfo::ChatStatesFeature);
+ discoInfo.addFeature(DiscoInfo::SecurityLabelsFeature);
+ discoInfo.addFeature(DiscoInfo::MessageCorrectionFeature);
#ifdef SWIFT_EXPERIMENTAL_FT
- discoInfo.addFeature(DiscoInfo::JingleFeature);
- discoInfo.addFeature(DiscoInfo::JingleFTFeature);
- discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
- discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
- discoInfo.addFeature(DiscoInfo::WhiteboardFeature);
+ discoInfo.addFeature(DiscoInfo::WhiteboardFeature);
#endif
- discoInfo.addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
- client_->getDiscoManager()->setCapsNode(CLIENT_NODE);
- client_->getDiscoManager()->setDiscoInfo(discoInfo);
-
- userSearchControllerChat_ = new UserSearchController(UserSearchController::StartChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
- userSearchControllerAdd_ = new UserSearchController(UserSearchController::AddContact, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithoutRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
- adHocManager_ = new AdHocManager(JID(boundJID_.getDomain()), uiFactory_, client_->getIQRouter(), uiEventStream_, rosterController_->getWindow());
-
- chatsManager_->onImpromptuMUCServiceDiscovered.connect(boost::bind(&UserSearchController::setCanInitiateImpromptuMUC, userSearchControllerChat_, _1));
- }
- loginWindow_->setIsLoggingIn(false);
-
- client_->requestRoster();
-
- GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(boundJID_.getDomain()), client_->getIQRouter());
- discoInfoRequest->onResponse.connect(boost::bind(&MainController::handleServerDiscoInfoResponse, this, _1, _2));
- discoInfoRequest->send();
-
- client_->getVCardManager()->requestOwnVCard();
-
- rosterController_->setJID(boundJID_);
- rosterController_->setEnabled(true);
- rosterController_->getWindow()->setStreamEncryptionStatus(client_->isStreamEncrypted());
- profileController_->setAvailable(true);
- contactEditController_->setAvailable(true);
- /* Send presence later to catch all the incoming presences. */
- sendPresence(statusTracker_->getNextPresence());
-
- /* Enable chats last of all, so rejoining MUCs has the right sent presence */
- assert(chatsManager_);
- chatsManager_->setOnline(true);
- adHocManager_->setOnline(true);
+ discoInfo.addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
+ client_->getDiscoManager()->setCapsNode(CLIENT_NODE);
+ client_->getDiscoManager()->setDiscoInfo(discoInfo);
+
+ userSearchControllerChat_ = new UserSearchController(UserSearchController::StartChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
+ userSearchControllerAdd_ = new UserSearchController(UserSearchController::AddContact, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithoutRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_);
+ adHocManager_ = new AdHocManager(JID(boundJID_.getDomain()), uiFactory_, client_->getIQRouter(), uiEventStream_, rosterController_->getWindow());
+
+ chatsManager_->onImpromptuMUCServiceDiscovered.connect(boost::bind(&UserSearchController::setCanInitiateImpromptuMUC, userSearchControllerChat_, _1));
+ }
+ loginWindow_->setIsLoggingIn(false);
+
+ client_->requestRoster();
+
+ GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(boundJID_.getDomain()), client_->getIQRouter());
+ discoInfoRequest->onResponse.connect(boost::bind(&MainController::handleServerDiscoInfoResponse, this, _1, _2));
+ discoInfoRequest->send();
+
+ client_->getVCardManager()->requestOwnVCard();
+
+ rosterController_->setJID(boundJID_);
+ rosterController_->setEnabled(true);
+ rosterController_->getWindow()->setStreamEncryptionStatus(client_->isStreamEncrypted());
+ profileController_->setAvailable(true);
+ contactEditController_->setAvailable(true);
+ /* Send presence later to catch all the incoming presences. */
+ sendPresence(statusTracker_->getNextPresence());
+
+ /* Enable chats last of all, so rejoining MUCs has the right sent presence */
+ assert(chatsManager_);
+ chatsManager_->setOnline(true);
+ adHocManager_->setOnline(true);
}
void MainController::handleEventQueueLengthChange(int count) {
- dock_->setNumberOfPendingMessages(count);
+ dock_->setNumberOfPendingMessages(count);
}
void MainController::reconnectAfterError() {
- if (reconnectTimer_) {
- reconnectTimer_->stop();
- }
- performLoginFromCachedCredentials();
+ if (reconnectTimer_) {
+ reconnectTimer_->stop();
+ }
+ performLoginFromCachedCredentials();
}
void MainController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
- boost::shared_ptr<Presence> presence(new Presence());
- if (show == StatusShow::None) {
- // Note: this is misleading, None doesn't mean unavailable on the wire.
- presence->setType(Presence::Unavailable);
- resetPendingReconnects();
- myStatusLooksOnline_ = false;
- offlineRequested_ = true;
- }
- else {
- offlineRequested_ = false;
- presence->setShow(show);
- }
- presence->setStatus(statusText);
- statusTracker_->setRequestedPresence(presence);
- if (presence->getType() != Presence::Unavailable) {
- profileSettings_->storeInt("lastShow", presence->getShow());
- profileSettings_->storeString("lastStatus", presence->getStatus());
- }
- if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) {
- performLoginFromCachedCredentials();
- } else {
- sendPresence(presence);
- }
+ boost::shared_ptr<Presence> presence(new Presence());
+ if (show == StatusShow::None) {
+ // Note: this is misleading, None doesn't mean unavailable on the wire.
+ presence->setType(Presence::Unavailable);
+ resetPendingReconnects();
+ myStatusLooksOnline_ = false;
+ offlineRequested_ = true;
+ }
+ else {
+ offlineRequested_ = false;
+ presence->setShow(show);
+ }
+ presence->setStatus(statusText);
+ statusTracker_->setRequestedPresence(presence);
+ if (presence->getType() != Presence::Unavailable) {
+ profileSettings_->storeInt("lastShow", presence->getShow());
+ profileSettings_->storeString("lastStatus", presence->getStatus());
+ }
+ if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) {
+ performLoginFromCachedCredentials();
+ } else {
+ sendPresence(presence);
+ }
}
void MainController::sendPresence(boost::shared_ptr<Presence> presence) {
- rosterController_->getWindow()->setMyStatusType(presence->getShow());
- rosterController_->getWindow()->setMyStatusText(presence->getStatus());
- systemTrayController_->setMyStatusType(presence->getShow());
- notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND);
-
- // Add information and send
- presence->updatePayload(boost::make_shared<VCardUpdate>(vCardPhotoHash_));
- client_->getPresenceSender()->sendPresence(presence);
- if (presence->getType() == Presence::Unavailable) {
- logout();
- }
+ rosterController_->getWindow()->setMyStatusType(presence->getShow());
+ rosterController_->getWindow()->setMyStatusText(presence->getStatus());
+ systemTrayController_->setMyStatusType(presence->getShow());
+ notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND);
+
+ // Add information and send
+ presence->updatePayload(boost::make_shared<VCardUpdate>(vCardPhotoHash_));
+ client_->getPresenceSender()->sendPresence(presence);
+ if (presence->getType() == Presence::Unavailable) {
+ logout();
+ }
}
void MainController::handleInputIdleChanged(bool idle) {
- if (!statusTracker_) {
- //Haven't logged in yet.
- return;
- }
-
- if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) {
- if (idle) {
- logout();
- }
- }
- else {
- if (idle) {
- if (statusTracker_->goAutoAway(idleDetector_->getIdleTimeSeconds())) {
- if (client_ && client_->isAvailable()) {
- sendPresence(statusTracker_->getNextPresence());
- }
- }
- } else {
- if (statusTracker_->goAutoUnAway()) {
- if (client_ && client_->isAvailable()) {
- sendPresence(statusTracker_->getNextPresence());
- }
- }
- }
- }
+ if (!statusTracker_) {
+ //Haven't logged in yet.
+ return;
+ }
+
+ if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) {
+ if (idle) {
+ logout();
+ }
+ }
+ else {
+ if (idle) {
+ if (statusTracker_->goAutoAway(idleDetector_->getIdleTimeSeconds())) {
+ if (client_ && client_->isAvailable()) {
+ sendPresence(statusTracker_->getNextPresence());
+ }
+ }
+ } else {
+ if (statusTracker_->goAutoUnAway()) {
+ if (client_ && client_->isAvailable()) {
+ sendPresence(statusTracker_->getNextPresence());
+ }
+ }
+ }
+ }
}
void MainController::handleShowCertificateRequest() {
- std::vector<Certificate::ref> chain = client_->getStanzaChannel()->getPeerCertificateChain();
- rosterController_->getWindow()->openCertificateDialog(chain);
+ std::vector<Certificate::ref> chain = client_->getStanzaChannel()->getPeerCertificateChain();
+ rosterController_->getWindow()->openCertificateDialog(chain);
}
void MainController::handleLoginRequest(const std::string &username, const std::string &password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically) {
- jid_ = JID(username);
- if (options.singleSignOn && (!jid_.isValid() || !jid_.getNode().empty())) {
- loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'wonderland.lit'"));
- loginWindow_->setIsLoggingIn(false);
- } else if (!options.singleSignOn && (!jid_.isValid() || jid_.getNode().empty())) {
- loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'alice@wonderland.lit'"));
- loginWindow_->setIsLoggingIn(false);
- } else {
+ jid_ = JID(username);
+ if (options.singleSignOn && (!jid_.isValid() || !jid_.getNode().empty())) {
+ loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'wonderland.lit'"));
+ loginWindow_->setIsLoggingIn(false);
+ } else if (!options.singleSignOn && (!jid_.isValid() || jid_.getNode().empty())) {
+ loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'alice@wonderland.lit'"));
+ loginWindow_->setIsLoggingIn(false);
+ } else {
#ifdef SWIFTEN_PLATFORM_WIN32
- if (options.singleSignOn) {
- std::string userName;
- std::string clientName;
- std::string serverName;
- boost::shared_ptr<boost::system::error_code> errorCode = getUserNameEx(userName, clientName, serverName);
-
- if (!errorCode) {
- /* Create JID using the Windows logon name and user provided domain name */
- jid_ = JID(clientName, username);
- }
- else {
- loginWindow_->setMessage(str(format(QT_TRANSLATE_NOOP("", "Error obtaining Windows user name (%1%)")) % errorCode->message()));
- loginWindow_->setIsLoggingIn(false);
- return;
- }
- }
+ if (options.singleSignOn) {
+ std::string userName;
+ std::string clientName;
+ std::string serverName;
+ boost::shared_ptr<boost::system::error_code> errorCode = getUserNameEx(userName, clientName, serverName);
+
+ if (!errorCode) {
+ /* Create JID using the Windows logon name and user provided domain name */
+ jid_ = JID(clientName, username);
+ }
+ else {
+ loginWindow_->setMessage(str(format(QT_TRANSLATE_NOOP("", "Error obtaining Windows user name (%1%)")) % errorCode->message()));
+ loginWindow_->setIsLoggingIn(false);
+ return;
+ }
+ }
#endif
- loginWindow_->setMessage("");
- loginWindow_->setIsLoggingIn(true);
- profileSettings_ = new ProfileSettingsProvider(username, settings_);
- if (!settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- profileSettings_->storeString("jid", username);
- profileSettings_->storeString("certificate", certificatePath);
- profileSettings_->storeString("pass", (remember || loginAutomatically) ? password : "");
- std::string optionString = serializeClientOptions(options);
- profileSettings_->storeString("options", optionString);
- settings_->storeSetting(SettingConstants::LAST_LOGIN_JID, username);
- settings_->storeSetting(SettingConstants::LOGIN_AUTOMATICALLY, loginAutomatically);
- loginWindow_->addAvailableAccount(profileSettings_->getStringSetting("jid"), profileSettings_->getStringSetting("pass"), profileSettings_->getStringSetting("certificate"), options);
- }
-
- password_ = password;
- certificate_ = certificate;
- clientOptions_ = options;
- performLoginFromCachedCredentials();
- }
+ loginWindow_->setMessage("");
+ loginWindow_->setIsLoggingIn(true);
+ profileSettings_ = new ProfileSettingsProvider(username, settings_);
+ if (!settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ profileSettings_->storeString("jid", username);
+ profileSettings_->storeString("certificate", certificatePath);
+ profileSettings_->storeString("pass", (remember || loginAutomatically) ? password : "");
+ std::string optionString = serializeClientOptions(options);
+ profileSettings_->storeString("options", optionString);
+ settings_->storeSetting(SettingConstants::LAST_LOGIN_JID, username);
+ settings_->storeSetting(SettingConstants::LOGIN_AUTOMATICALLY, loginAutomatically);
+ loginWindow_->addAvailableAccount(profileSettings_->getStringSetting("jid"), profileSettings_->getStringSetting("pass"), profileSettings_->getStringSetting("certificate"), options);
+ }
+
+ password_ = password;
+ certificate_ = certificate;
+ clientOptions_ = options;
+ performLoginFromCachedCredentials();
+ }
}
void MainController::handlePurgeSavedLoginRequest(const std::string& username) {
- settings_->removeProfile(username);
- loginWindow_->removeAvailableAccount(username);
+ settings_->removeProfile(username);
+ loginWindow_->removeAvailableAccount(username);
}
void MainController::performLoginFromCachedCredentials() {
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) {
- /* Then we can't try to login again. */
- return;
- }
- /* If we logged in with a bare JID, and we have a full bound JID, re-login with the
- * bound JID to try and keep dynamically assigned resources */
- JID clientJID = jid_;
- if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) {
- clientJID = boundJID_;
- }
-
- if (!statusTracker_) {
- statusTracker_ = new StatusTracker();
- }
- if (!clientInitialized_) {
- storages_ = storagesFactory_->createStorages(jid_.toBare());
- certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare());
- certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_);
-
- client_ = boost::make_shared<Swift::Client>(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_);
- clientInitialized_ = true;
- client_->setCertificateTrustChecker(certificateTrustChecker_);
- client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1));
- client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1));
- client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1));
- client_->onConnected.connect(boost::bind(&MainController::handleConnected, this));
-
- client_->setSoftwareVersion(CLIENT_NAME, buildVersion);
-
- client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2));
- presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory());
- presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
- eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver());
- eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
- if (certificate_) {
- client_->setCertificate(certificate_);
- }
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setShow(static_cast<StatusShow::Type>(profileSettings_->getIntSetting("lastShow", StatusShow::Online)));
- presence->setStatus(profileSettings_->getStringSetting("lastStatus"));
- statusTracker_->setRequestedPresence(presence);
- } else {
- /* In case we're in the middle of another login, make sure they don't overlap */
- client_->disconnect();
- }
- systemTrayController_->setConnecting();
- if (rosterController_) {
- rosterController_->getWindow()->setConnecting();
- }
- ClientOptions clientOptions = clientOptions_;
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- clientOptions.forgetPassword = eagle;
- clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS;
- client_->connect(clientOptions);
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) {
+ /* Then we can't try to login again. */
+ return;
+ }
+ /* If we logged in with a bare JID, and we have a full bound JID, re-login with the
+ * bound JID to try and keep dynamically assigned resources */
+ JID clientJID = jid_;
+ if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) {
+ clientJID = boundJID_;
+ }
+
+ if (!statusTracker_) {
+ statusTracker_ = new StatusTracker();
+ }
+ if (!clientInitialized_) {
+ storages_ = storagesFactory_->createStorages(jid_.toBare());
+ certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare());
+ certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_);
+
+ client_ = boost::make_shared<Swift::Client>(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_);
+ clientInitialized_ = true;
+ client_->setCertificateTrustChecker(certificateTrustChecker_);
+ client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1));
+ client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1));
+ client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1));
+ client_->onConnected.connect(boost::bind(&MainController::handleConnected, this));
+
+ client_->setSoftwareVersion(CLIENT_NAME, buildVersion);
+
+ client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2));
+ presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory());
+ presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
+ eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver());
+ eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
+ if (certificate_) {
+ client_->setCertificate(certificate_);
+ }
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setShow(static_cast<StatusShow::Type>(profileSettings_->getIntSetting("lastShow", StatusShow::Online)));
+ presence->setStatus(profileSettings_->getStringSetting("lastStatus"));
+ statusTracker_->setRequestedPresence(presence);
+ } else {
+ /* In case we're in the middle of another login, make sure they don't overlap */
+ client_->disconnect();
+ }
+ systemTrayController_->setConnecting();
+ if (rosterController_) {
+ rosterController_->getWindow()->setConnecting();
+ }
+ ClientOptions clientOptions = clientOptions_;
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ clientOptions.forgetPassword = eagle;
+ clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS;
+ client_->connect(clientOptions);
}
void MainController::handleDisconnected(const boost::optional<ClientError>& error) {
- if (rosterController_) {
- rosterController_->getWindow()->setStreamEncryptionStatus(false);
- }
- if (adHocManager_) {
- adHocManager_->setOnline(false);
- }
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- purgeCachedCredentials();
- }
- if (quitRequested_) {
- resetClient();
- loginWindow_->quit();
- }
- else if (error) {
- std::string message;
- std::string certificateErrorMessage;
- bool forceSignout = false;
- switch(error->getType()) {
- case ClientError::UnknownError: message = QT_TRANSLATE_NOOP("", "Unknown Error"); break;
- case ClientError::DomainNameResolveError: message = QT_TRANSLATE_NOOP("", "Unable to find server"); break;
- case ClientError::ConnectionError: message = QT_TRANSLATE_NOOP("", "Error connecting to server"); break;
- case ClientError::ConnectionReadError: message = QT_TRANSLATE_NOOP("", "Error while receiving server data"); break;
- case ClientError::ConnectionWriteError: message = QT_TRANSLATE_NOOP("", "Error while sending data to the server"); break;
- case ClientError::XMLError: message = QT_TRANSLATE_NOOP("", "Error parsing server data"); break;
- case ClientError::AuthenticationFailedError: message = QT_TRANSLATE_NOOP("", "Login/password invalid"); break;
- case ClientError::CompressionFailedError: message = QT_TRANSLATE_NOOP("", "Error while compressing stream"); break;
- case ClientError::ServerVerificationFailedError: message = QT_TRANSLATE_NOOP("", "Server verification failed"); break;
- case ClientError::NoSupportedAuthMechanismsError: message = QT_TRANSLATE_NOOP("", "Authentication mechanisms not supported"); break;
- case ClientError::UnexpectedElementError: message = QT_TRANSLATE_NOOP("", "Unexpected response"); break;
- case ClientError::ResourceBindError: message = QT_TRANSLATE_NOOP("", "Error binding resource"); break;
- case ClientError::SessionStartError: message = QT_TRANSLATE_NOOP("", "Error starting session"); break;
- case ClientError::StreamError: message = QT_TRANSLATE_NOOP("", "Stream error"); break;
- case ClientError::TLSError: message = QT_TRANSLATE_NOOP("", "Encryption error"); break;
- case ClientError::ClientCertificateLoadError: message = QT_TRANSLATE_NOOP("", "Error loading certificate (Invalid file or password?)"); break;
- case ClientError::ClientCertificateError: message = QT_TRANSLATE_NOOP("", "Certificate not authorized"); break;
- case ClientError::CertificateCardRemoved: message = QT_TRANSLATE_NOOP("", "Certificate card removed"); forceSignout = true; break;
-
- case ClientError::UnknownCertificateError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unknown certificate"); break;
- case ClientError::CertificateExpiredError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has expired"); break;
- case ClientError::CertificateNotYetValidError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not yet valid"); break;
- case ClientError::CertificateSelfSignedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is self-signed"); break;
- case ClientError::CertificateRejectedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been rejected"); break;
- case ClientError::CertificateUntrustedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not trusted"); break;
- case ClientError::InvalidCertificatePurposeError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate cannot be used for encrypting your connection"); break;
- case ClientError::CertificatePathLengthExceededError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate path length constraint exceeded"); break;
- case ClientError::InvalidCertificateSignatureError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid certificate signature"); break;
- case ClientError::InvalidCAError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid Certificate Authority"); break;
- case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break;
- case ClientError::RevokedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been revoked"); break;
- case ClientError::RevocationCheckFailedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unable to determine certificate revocation state"); break;
- }
- bool forceReconnectAfterCertificateTrust = false;
- if (!certificateErrorMessage.empty()) {
- std::vector<Certificate::ref> certificates = certificateTrustChecker_->getLastCertificateChain();
- if (!certificates.empty() && loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificates)) {
- certificateStorage_->addCertificate(certificates[0]);
- forceReconnectAfterCertificateTrust = true;
- }
- else {
- message = QT_TRANSLATE_NOOP("", "Certificate error");
- }
- }
-
- if (!message.empty() && error->getErrorCode()) {
- message = str(format(QT_TRANSLATE_NOOP("", "%1% (%2%)")) % message % error->getErrorCode()->message());
- }
-
- if (forceReconnectAfterCertificateTrust && settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- forceReconnectAfterCertificateTrust = false;
- forceSignout = true;
- message = QT_TRANSLATE_NOOP("", "Re-enter credentials and retry");
- }
-
- if (forceReconnectAfterCertificateTrust) {
- performLoginFromCachedCredentials();
- }
- else if (forceSignout || !rosterController_) { //hasn't been logged in yet or permanent error
- signOut();
- loginWindow_->setMessage(message);
- loginWindow_->setIsLoggingIn(false);
- } else {
- logout();
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message);
- } else {
- if (!offlineRequested_) {
- setReconnectTimer();
- }
- if (lastDisconnectError_) {
- message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast<std::string>(timeBeforeNextReconnect_));
- lastDisconnectError_->conclude();
- } else {
- message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message);
- }
- lastDisconnectError_ = boost::make_shared<ErrorEvent>(JID(jid_.getDomain()), message);
- eventController_->handleIncomingEvent(lastDisconnectError_);
- }
- }
- }
- else if (!rosterController_) { //hasn't been logged in yet
- loginWindow_->setIsLoggingIn(false);
- }
+ if (rosterController_) {
+ rosterController_->getWindow()->setStreamEncryptionStatus(false);
+ }
+ if (adHocManager_) {
+ adHocManager_->setOnline(false);
+ }
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ purgeCachedCredentials();
+ }
+ if (quitRequested_) {
+ resetClient();
+ loginWindow_->quit();
+ }
+ else if (error) {
+ std::string message;
+ std::string certificateErrorMessage;
+ bool forceSignout = false;
+ switch(error->getType()) {
+ case ClientError::UnknownError: message = QT_TRANSLATE_NOOP("", "Unknown Error"); break;
+ case ClientError::DomainNameResolveError: message = QT_TRANSLATE_NOOP("", "Unable to find server"); break;
+ case ClientError::ConnectionError: message = QT_TRANSLATE_NOOP("", "Error connecting to server"); break;
+ case ClientError::ConnectionReadError: message = QT_TRANSLATE_NOOP("", "Error while receiving server data"); break;
+ case ClientError::ConnectionWriteError: message = QT_TRANSLATE_NOOP("", "Error while sending data to the server"); break;
+ case ClientError::XMLError: message = QT_TRANSLATE_NOOP("", "Error parsing server data"); break;
+ case ClientError::AuthenticationFailedError: message = QT_TRANSLATE_NOOP("", "Login/password invalid"); break;
+ case ClientError::CompressionFailedError: message = QT_TRANSLATE_NOOP("", "Error while compressing stream"); break;
+ case ClientError::ServerVerificationFailedError: message = QT_TRANSLATE_NOOP("", "Server verification failed"); break;
+ case ClientError::NoSupportedAuthMechanismsError: message = QT_TRANSLATE_NOOP("", "Authentication mechanisms not supported"); break;
+ case ClientError::UnexpectedElementError: message = QT_TRANSLATE_NOOP("", "Unexpected response"); break;
+ case ClientError::ResourceBindError: message = QT_TRANSLATE_NOOP("", "Error binding resource"); break;
+ case ClientError::SessionStartError: message = QT_TRANSLATE_NOOP("", "Error starting session"); break;
+ case ClientError::StreamError: message = QT_TRANSLATE_NOOP("", "Stream error"); break;
+ case ClientError::TLSError: message = QT_TRANSLATE_NOOP("", "Encryption error"); break;
+ case ClientError::ClientCertificateLoadError: message = QT_TRANSLATE_NOOP("", "Error loading certificate (Invalid file or password?)"); break;
+ case ClientError::ClientCertificateError: message = QT_TRANSLATE_NOOP("", "Certificate not authorized"); break;
+ case ClientError::CertificateCardRemoved: message = QT_TRANSLATE_NOOP("", "Certificate card removed"); forceSignout = true; break;
+
+ case ClientError::UnknownCertificateError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unknown certificate"); break;
+ case ClientError::CertificateExpiredError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has expired"); break;
+ case ClientError::CertificateNotYetValidError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not yet valid"); break;
+ case ClientError::CertificateSelfSignedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is self-signed"); break;
+ case ClientError::CertificateRejectedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been rejected"); break;
+ case ClientError::CertificateUntrustedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not trusted"); break;
+ case ClientError::InvalidCertificatePurposeError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate cannot be used for encrypting your connection"); break;
+ case ClientError::CertificatePathLengthExceededError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate path length constraint exceeded"); break;
+ case ClientError::InvalidCertificateSignatureError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid certificate signature"); break;
+ case ClientError::InvalidCAError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid Certificate Authority"); break;
+ case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break;
+ case ClientError::RevokedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been revoked"); break;
+ case ClientError::RevocationCheckFailedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unable to determine certificate revocation state"); break;
+ }
+ bool forceReconnectAfterCertificateTrust = false;
+ if (!certificateErrorMessage.empty()) {
+ std::vector<Certificate::ref> certificates = certificateTrustChecker_->getLastCertificateChain();
+ if (!certificates.empty() && loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificates)) {
+ certificateStorage_->addCertificate(certificates[0]);
+ forceReconnectAfterCertificateTrust = true;
+ }
+ else {
+ message = QT_TRANSLATE_NOOP("", "Certificate error");
+ }
+ }
+
+ if (!message.empty() && error->getErrorCode()) {
+ message = str(format(QT_TRANSLATE_NOOP("", "%1% (%2%)")) % message % error->getErrorCode()->message());
+ }
+
+ if (forceReconnectAfterCertificateTrust && settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ forceReconnectAfterCertificateTrust = false;
+ forceSignout = true;
+ message = QT_TRANSLATE_NOOP("", "Re-enter credentials and retry");
+ }
+
+ if (forceReconnectAfterCertificateTrust) {
+ performLoginFromCachedCredentials();
+ }
+ else if (forceSignout || !rosterController_) { //hasn't been logged in yet or permanent error
+ signOut();
+ loginWindow_->setMessage(message);
+ loginWindow_->setIsLoggingIn(false);
+ } else {
+ logout();
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message);
+ } else {
+ if (!offlineRequested_) {
+ setReconnectTimer();
+ }
+ if (lastDisconnectError_) {
+ message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast<std::string>(timeBeforeNextReconnect_));
+ lastDisconnectError_->conclude();
+ } else {
+ message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message);
+ }
+ lastDisconnectError_ = boost::make_shared<ErrorEvent>(JID(jid_.getDomain()), message);
+ eventController_->handleIncomingEvent(lastDisconnectError_);
+ }
+ }
+ }
+ else if (!rosterController_) { //hasn't been logged in yet
+ loginWindow_->setIsLoggingIn(false);
+ }
}
void MainController::setReconnectTimer() {
- if (timeBeforeNextReconnect_ < 0) {
- timeBeforeNextReconnect_ = 1;
- } else {
- timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis
- }
- if (reconnectTimer_) {
- reconnectTimer_->stop();
- }
- reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000);
- reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this));
- reconnectTimer_->start();
+ if (timeBeforeNextReconnect_ < 0) {
+ timeBeforeNextReconnect_ = 1;
+ } else {
+ timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis
+ }
+ if (reconnectTimer_) {
+ reconnectTimer_->stop();
+ }
+ reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000);
+ reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this));
+ reconnectTimer_->start();
}
void MainController::handleCancelLoginRequest() {
- signOut();
+ signOut();
}
void MainController::signOut() {
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- purgeCachedCredentials();
- }
- eventController_->clear();
- logout();
- loginWindow_->loggedOut();
- resetClient();
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ purgeCachedCredentials();
+ }
+ eventController_->clear();
+ logout();
+ loginWindow_->loggedOut();
+ resetClient();
}
void MainController::logout() {
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
- purgeCachedCredentials();
- }
- systemTrayController_->setMyStatusType(StatusShow::None);
- if (clientInitialized_ /*&& client_->isAvailable()*/) {
- client_->disconnect();
- }
- if (rosterController_ && myStatusLooksOnline_) {
- rosterController_->getWindow()->setMyStatusType(StatusShow::None);
- rosterController_->getWindow()->setMyStatusText("");
- myStatusLooksOnline_ = false;
- }
- setManagersOffline();
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
+ purgeCachedCredentials();
+ }
+ systemTrayController_->setMyStatusType(StatusShow::None);
+ if (clientInitialized_ /*&& client_->isAvailable()*/) {
+ client_->disconnect();
+ }
+ if (rosterController_ && myStatusLooksOnline_) {
+ rosterController_->getWindow()->setMyStatusType(StatusShow::None);
+ rosterController_->getWindow()->setMyStatusText("");
+ myStatusLooksOnline_ = false;
+ }
+ setManagersOffline();
}
void MainController::setManagersOffline() {
- if (chatsManager_) {
- chatsManager_->setOnline(false);
- }
- if (rosterController_) {
- rosterController_->setEnabled(false);
- }
- if (profileController_) {
- profileController_->setAvailable(false);
- }
- if (contactEditController_) {
- contactEditController_->setAvailable(false);
- }
+ if (chatsManager_) {
+ chatsManager_->setOnline(false);
+ }
+ if (rosterController_) {
+ rosterController_->setEnabled(false);
+ }
+ if (profileController_) {
+ profileController_->setAvailable(false);
+ }
+ if (contactEditController_) {
+ contactEditController_->setAvailable(false);
+ }
}
void MainController::handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error) {
- if (!error) {
- chatsManager_->setServerDiscoInfo(info);
- adHocManager_->setServerDiscoInfo(info);
- if (info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
- rosterController_->getWindow()->setBlockingCommandAvailable(true);
- rosterController_->initBlockingCommand();
- }
- }
+ if (!error) {
+ chatsManager_->setServerDiscoInfo(info);
+ adHocManager_->setServerDiscoInfo(info);
+ if (info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
+ rosterController_->getWindow()->setBlockingCommandAvailable(true);
+ rosterController_->initBlockingCommand();
+ }
+ }
}
void MainController::handleVCardReceived(const JID& jid, VCard::ref vCard) {
- if (!jid.equals(jid_, JID::WithoutResource) || !vCard) {
- return;
- }
- std::string hash;
- if (!vCard->getPhoto().empty()) {
- hash = Hexify::hexify(networkFactories_->getCryptoProvider()->getSHA1Hash(vCard->getPhoto()));
- }
- if (hash != vCardPhotoHash_) {
- vCardPhotoHash_ = hash;
- if (client_ && client_->isAvailable()) {
- sendPresence(statusTracker_->getNextPresence());
- }
- }
+ if (!jid.equals(jid_, JID::WithoutResource) || !vCard) {
+ return;
+ }
+ std::string hash;
+ if (!vCard->getPhoto().empty()) {
+ hash = Hexify::hexify(networkFactories_->getCryptoProvider()->getSHA1Hash(vCard->getPhoto()));
+ }
+ if (hash != vCardPhotoHash_) {
+ vCardPhotoHash_ = hash;
+ if (client_ && client_->isAvailable()) {
+ sendPresence(statusTracker_->getNextPresence());
+ }
+ }
}
void MainController::handleNotificationClicked(const JID& jid) {
- assert(chatsManager_);
- if (clientInitialized_) {
- if (client_->getMUCRegistry()->isMUC(jid)) {
- uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(jid));
- }
- else {
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(jid)));
- }
- }
+ assert(chatsManager_);
+ if (clientInitialized_) {
+ if (client_->getMUCRegistry()->isMUC(jid)) {
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(jid));
+ }
+ else {
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(jid)));
+ }
+ }
}
void MainController::handleQuitRequest() {
- if (client_ && client_->isActive()) {
- quitRequested_ = true;
- client_->disconnect();
- }
- else {
- resetClient();
- loginWindow_->quit();
- }
+ if (client_ && client_->isActive()) {
+ quitRequested_ = true;
+ client_->disconnect();
+ }
+ else {
+ resetClient();
+ loginWindow_->quit();
+ }
}
#define SERIALIZE_BOOL(option) result += options.option ? "1" : "0"; result += ",";
@@ -851,34 +851,34 @@ void MainController::handleQuitRequest() {
#define SERIALIZE_URL(option) SERIALIZE_STRING(option.toString())
std::string MainController::serializeClientOptions(const ClientOptions& options) {
- std::string result;
- SERIALIZE_BOOL(useStreamCompression);
- switch (options.useTLS) {
- case ClientOptions::NeverUseTLS: result += "1";break;
- case ClientOptions::UseTLSWhenAvailable: result += "2";break;
- case ClientOptions::RequireTLS: result += "3";break;
- }
- result += ",";
- SERIALIZE_BOOL(allowPLAINWithoutTLS);
- SERIALIZE_BOOL(useStreamResumption);
- SERIALIZE_BOOL(useAcks);
- SERIALIZE_STRING(manualHostname);
- SERIALIZE_INT(manualPort);
- switch (options.proxyType) {
- case ClientOptions::NoProxy: result += "1";break;
- case ClientOptions::SystemConfiguredProxy: result += "2";break;
- case ClientOptions::SOCKS5Proxy: result += "3";break;
- case ClientOptions::HTTPConnectProxy: result += "4";break;
- }
- result += ",";
- SERIALIZE_STRING(manualProxyHostname);
- SERIALIZE_INT(manualProxyPort);
- SERIALIZE_URL(boshURL);
- SERIALIZE_URL(boshHTTPConnectProxyURL);
- SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID);
- SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
- SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround);
- return result;
+ std::string result;
+ SERIALIZE_BOOL(useStreamCompression);
+ switch (options.useTLS) {
+ case ClientOptions::NeverUseTLS: result += "1";break;
+ case ClientOptions::UseTLSWhenAvailable: result += "2";break;
+ case ClientOptions::RequireTLS: result += "3";break;
+ }
+ result += ",";
+ SERIALIZE_BOOL(allowPLAINWithoutTLS);
+ SERIALIZE_BOOL(useStreamResumption);
+ SERIALIZE_BOOL(useAcks);
+ SERIALIZE_STRING(manualHostname);
+ SERIALIZE_INT(manualPort);
+ switch (options.proxyType) {
+ case ClientOptions::NoProxy: result += "1";break;
+ case ClientOptions::SystemConfiguredProxy: result += "2";break;
+ case ClientOptions::SOCKS5Proxy: result += "3";break;
+ case ClientOptions::HTTPConnectProxy: result += "4";break;
+ }
+ result += ",";
+ SERIALIZE_STRING(manualProxyHostname);
+ SERIALIZE_INT(manualProxyPort);
+ SERIALIZE_URL(boshURL);
+ SERIALIZE_URL(boshHTTPConnectProxyURL);
+ SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID);
+ SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
+ SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround);
+ return result;
}
#define CHECK_PARSE_LENGTH if (i >= segments.size()) {return result;}
@@ -893,41 +893,41 @@ std::string MainController::serializeClientOptions(const ClientOptions& options)
ClientOptions MainController::parseClientOptions(const std::string& optionString) {
- ClientOptions result;
- size_t i = 0;
- int intVal = 0;
- std::string stringVal;
- std::vector<std::string> segments = String::split(optionString, ',');
-
- PARSE_BOOL(useStreamCompression, 1);
- PARSE_INT_RAW(-1);
- switch (intVal) {
- case 1: result.useTLS = ClientOptions::NeverUseTLS;break;
- case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable;break;
- case 3: result.useTLS = ClientOptions::RequireTLS;break;
- default:;
- }
- PARSE_BOOL(allowPLAINWithoutTLS, 0);
- PARSE_BOOL(useStreamResumption, 0);
- PARSE_BOOL(useAcks, 1);
- PARSE_STRING(manualHostname);
- PARSE_INT(manualPort, -1);
- PARSE_INT_RAW(-1);
- switch (intVal) {
- case 1: result.proxyType = ClientOptions::NoProxy;break;
- case 2: result.proxyType = ClientOptions::SystemConfiguredProxy;break;
- case 3: result.proxyType = ClientOptions::SOCKS5Proxy;break;
- case 4: result.proxyType = ClientOptions::HTTPConnectProxy;break;
- }
- PARSE_STRING(manualProxyHostname);
- PARSE_INT(manualProxyPort, -1);
- PARSE_URL(boshURL);
- PARSE_URL(boshHTTPConnectProxyURL);
- PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID);
- PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
- PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false);
-
- return result;
+ ClientOptions result;
+ size_t i = 0;
+ int intVal = 0;
+ std::string stringVal;
+ std::vector<std::string> segments = String::split(optionString, ',');
+
+ PARSE_BOOL(useStreamCompression, 1);
+ PARSE_INT_RAW(-1);
+ switch (intVal) {
+ case 1: result.useTLS = ClientOptions::NeverUseTLS;break;
+ case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable;break;
+ case 3: result.useTLS = ClientOptions::RequireTLS;break;
+ default:;
+ }
+ PARSE_BOOL(allowPLAINWithoutTLS, 0);
+ PARSE_BOOL(useStreamResumption, 0);
+ PARSE_BOOL(useAcks, 1);
+ PARSE_STRING(manualHostname);
+ PARSE_INT(manualPort, -1);
+ PARSE_INT_RAW(-1);
+ switch (intVal) {
+ case 1: result.proxyType = ClientOptions::NoProxy;break;
+ case 2: result.proxyType = ClientOptions::SystemConfiguredProxy;break;
+ case 3: result.proxyType = ClientOptions::SOCKS5Proxy;break;
+ case 4: result.proxyType = ClientOptions::HTTPConnectProxy;break;
+ }
+ PARSE_STRING(manualProxyHostname);
+ PARSE_INT(manualProxyPort, -1);
+ PARSE_URL(boshURL);
+ PARSE_URL(boshHTTPConnectProxyURL);
+ PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID);
+ PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
+ PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false);
+
+ return result;
}
}
diff --git a/Swift/Controllers/MainController.h b/Swift/Controllers/MainController.h
index e8a915e..ed7765a 100644
--- a/Swift/Controllers/MainController.h
+++ b/Swift/Controllers/MainController.h
@@ -29,171 +29,171 @@
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
namespace Swift {
- class IdleDetector;
- class UIFactory;
- class EventLoop;
- class Client;
- class ChatController;
- class ChatsManager;
- class CertificateStorageFactory;
- class CertificateStorage;
- class CertificateStorageTrustChecker;
- class EventController;
- class MainWindow;
- class RosterController;
- class LoginWindow;
- class EventLoop;
- class MUCController;
- class Notifier;
- class ProfileController;
- class ShowProfileController;
- class ContactEditController;
- class TogglableNotifier;
- class PresenceNotifier;
- class EventNotifier;
- class SystemTray;
- class SystemTrayController;
- class SoundEventController;
- class SoundPlayer;
- class XMLConsoleController;
- class HistoryViewController;
- class HistoryController;
- class FileTransferListController;
- class UIEventStream;
- class EventWindowFactory;
- class EventWindowController;
- class MUCSearchController;
- class UserSearchController;
- class StatusTracker;
- class Dock;
- class Storages;
- class StoragesFactory;
- class NetworkFactories;
- class URIHandler;
- class XMPPURIController;
- class AdHocManager;
- class AdHocCommandWindowFactory;
- class FileTransferOverview;
- class WhiteboardManager;
- class HighlightManager;
- class HighlightEditorController;
- class BlockListController;
- class ContactSuggester;
- class ContactsFromXMPPRoster;
+ class IdleDetector;
+ class UIFactory;
+ class EventLoop;
+ class Client;
+ class ChatController;
+ class ChatsManager;
+ class CertificateStorageFactory;
+ class CertificateStorage;
+ class CertificateStorageTrustChecker;
+ class EventController;
+ class MainWindow;
+ class RosterController;
+ class LoginWindow;
+ class EventLoop;
+ class MUCController;
+ class Notifier;
+ class ProfileController;
+ class ShowProfileController;
+ class ContactEditController;
+ class TogglableNotifier;
+ class PresenceNotifier;
+ class EventNotifier;
+ class SystemTray;
+ class SystemTrayController;
+ class SoundEventController;
+ class SoundPlayer;
+ class XMLConsoleController;
+ class HistoryViewController;
+ class HistoryController;
+ class FileTransferListController;
+ class UIEventStream;
+ class EventWindowFactory;
+ class EventWindowController;
+ class MUCSearchController;
+ class UserSearchController;
+ class StatusTracker;
+ class Dock;
+ class Storages;
+ class StoragesFactory;
+ class NetworkFactories;
+ class URIHandler;
+ class XMPPURIController;
+ class AdHocManager;
+ class AdHocCommandWindowFactory;
+ class FileTransferOverview;
+ class WhiteboardManager;
+ class HighlightManager;
+ class HighlightEditorController;
+ class BlockListController;
+ class ContactSuggester;
+ class ContactsFromXMPPRoster;
- class MainController {
- public:
- MainController(
- EventLoop* eventLoop,
- NetworkFactories* networkFactories,
- UIFactory* uiFactories,
- SettingsProvider *settings,
- SystemTray* systemTray,
- SoundPlayer* soundPlayer,
- StoragesFactory* storagesFactory,
- CertificateStorageFactory* certificateStorageFactory,
- Dock* dock,
- Notifier* notifier,
- URIHandler* uriHandler,
- IdleDetector* idleDetector,
- const std::map<std::string, std::string>& emoticons,
- bool useDelayForLatency);
- ~MainController();
+ class MainController {
+ public:
+ MainController(
+ EventLoop* eventLoop,
+ NetworkFactories* networkFactories,
+ UIFactory* uiFactories,
+ SettingsProvider *settings,
+ SystemTray* systemTray,
+ SoundPlayer* soundPlayer,
+ StoragesFactory* storagesFactory,
+ CertificateStorageFactory* certificateStorageFactory,
+ Dock* dock,
+ Notifier* notifier,
+ URIHandler* uriHandler,
+ IdleDetector* idleDetector,
+ const std::map<std::string, std::string>& emoticons,
+ bool useDelayForLatency);
+ ~MainController();
- private:
- void resetClient();
- void handleConnected();
- void handleLoginRequest(const std::string& username, const std::string& password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically);
- void handleCancelLoginRequest();
- void handleQuitRequest();
- void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText);
- void handleDisconnected(const boost::optional<ClientError>& error);
- void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo>, ErrorPayload::ref);
- void handleEventQueueLengthChange(int count);
- void handleVCardReceived(const JID& j, VCard::ref vCard);
- void handleSettingChanged(const std::string& settingPath);
- void handlePurgeSavedLoginRequest(const std::string& username);
- void sendPresence(boost::shared_ptr<Presence> presence);
- void handleInputIdleChanged(bool);
- void handleShowCertificateRequest();
- void logout();
- void signOut();
- void setReconnectTimer();
- void resetPendingReconnects();
- void resetCurrentError();
-
- void performLoginFromCachedCredentials();
- void reconnectAfterError();
- void setManagersOffline();
- void handleNotificationClicked(const JID& jid);
- void handleForceQuit();
- void purgeCachedCredentials();
- std::string serializeClientOptions(const ClientOptions& options);
- ClientOptions parseClientOptions(const std::string& optionString);
+ private:
+ void resetClient();
+ void handleConnected();
+ void handleLoginRequest(const std::string& username, const std::string& password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically);
+ void handleCancelLoginRequest();
+ void handleQuitRequest();
+ void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText);
+ void handleDisconnected(const boost::optional<ClientError>& error);
+ void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo>, ErrorPayload::ref);
+ void handleEventQueueLengthChange(int count);
+ void handleVCardReceived(const JID& j, VCard::ref vCard);
+ void handleSettingChanged(const std::string& settingPath);
+ void handlePurgeSavedLoginRequest(const std::string& username);
+ void sendPresence(boost::shared_ptr<Presence> presence);
+ void handleInputIdleChanged(bool);
+ void handleShowCertificateRequest();
+ void logout();
+ void signOut();
+ void setReconnectTimer();
+ void resetPendingReconnects();
+ void resetCurrentError();
- private:
- EventLoop* eventLoop_;
- NetworkFactories* networkFactories_;
- UIFactory* uiFactory_;
- StoragesFactory* storagesFactory_;
- Storages* storages_;
- CertificateStorageFactory* certificateStorageFactory_;
- CertificateStorage* certificateStorage_;
- CertificateStorageTrustChecker* certificateTrustChecker_;
- bool clientInitialized_;
- boost::shared_ptr<Client> client_;
- SettingsProvider *settings_;
- ProfileSettingsProvider* profileSettings_;
- Dock* dock_;
- URIHandler* uriHandler_;
- IdleDetector* idleDetector_;
- TogglableNotifier* notifier_;
- PresenceNotifier* presenceNotifier_;
- EventNotifier* eventNotifier_;
- RosterController* rosterController_;
- EventController* eventController_;
- EventWindowController* eventWindowController_;
- AdHocManager* adHocManager_;
- LoginWindow* loginWindow_;
- UIEventStream* uiEventStream_;
- XMLConsoleController* xmlConsoleController_;
- HistoryViewController* historyViewController_;
- HistoryController* historyController_;
- FileTransferListController* fileTransferListController_;
- BlockListController* blockListController_;
- ChatsManager* chatsManager_;
- ProfileController* profileController_;
- ShowProfileController* showProfileController_;
- ContactEditController* contactEditController_;
- ContactsFromXMPPRoster* contactsFromRosterProvider_;
- ContactSuggester* contactSuggesterWithoutRoster_;
- ContactSuggester* contactSuggesterWithRoster_;
- JID jid_;
- JID boundJID_;
- SystemTrayController* systemTrayController_;
- SoundEventController* soundEventController_;
- XMPPURIController* xmppURIController_;
- std::string vCardPhotoHash_;
- std::string password_;
- CertificateWithKey::ref certificate_;
- ClientOptions clientOptions_;
- boost::shared_ptr<ErrorEvent> lastDisconnectError_;
- bool useDelayForLatency_;
- UserSearchController* userSearchControllerChat_;
- UserSearchController* userSearchControllerAdd_;
- UserSearchController* userSearchControllerInvite_;
- int timeBeforeNextReconnect_;
- Timer::ref reconnectTimer_;
- StatusTracker* statusTracker_;
- bool myStatusLooksOnline_;
- bool quitRequested_;
- bool offlineRequested_;
- static const int SecondsToWaitBeforeForceQuitting;
- FileTransferOverview* ftOverview_;
- WhiteboardManager* whiteboardManager_;
- HighlightManager* highlightManager_;
- HighlightEditorController* highlightEditorController_;
- std::map<std::string, std::string> emoticons_;
- };
+ void performLoginFromCachedCredentials();
+ void reconnectAfterError();
+ void setManagersOffline();
+ void handleNotificationClicked(const JID& jid);
+ void handleForceQuit();
+ void purgeCachedCredentials();
+ std::string serializeClientOptions(const ClientOptions& options);
+ ClientOptions parseClientOptions(const std::string& optionString);
+
+ private:
+ EventLoop* eventLoop_;
+ NetworkFactories* networkFactories_;
+ UIFactory* uiFactory_;
+ StoragesFactory* storagesFactory_;
+ Storages* storages_;
+ CertificateStorageFactory* certificateStorageFactory_;
+ CertificateStorage* certificateStorage_;
+ CertificateStorageTrustChecker* certificateTrustChecker_;
+ bool clientInitialized_;
+ boost::shared_ptr<Client> client_;
+ SettingsProvider *settings_;
+ ProfileSettingsProvider* profileSettings_;
+ Dock* dock_;
+ URIHandler* uriHandler_;
+ IdleDetector* idleDetector_;
+ TogglableNotifier* notifier_;
+ PresenceNotifier* presenceNotifier_;
+ EventNotifier* eventNotifier_;
+ RosterController* rosterController_;
+ EventController* eventController_;
+ EventWindowController* eventWindowController_;
+ AdHocManager* adHocManager_;
+ LoginWindow* loginWindow_;
+ UIEventStream* uiEventStream_;
+ XMLConsoleController* xmlConsoleController_;
+ HistoryViewController* historyViewController_;
+ HistoryController* historyController_;
+ FileTransferListController* fileTransferListController_;
+ BlockListController* blockListController_;
+ ChatsManager* chatsManager_;
+ ProfileController* profileController_;
+ ShowProfileController* showProfileController_;
+ ContactEditController* contactEditController_;
+ ContactsFromXMPPRoster* contactsFromRosterProvider_;
+ ContactSuggester* contactSuggesterWithoutRoster_;
+ ContactSuggester* contactSuggesterWithRoster_;
+ JID jid_;
+ JID boundJID_;
+ SystemTrayController* systemTrayController_;
+ SoundEventController* soundEventController_;
+ XMPPURIController* xmppURIController_;
+ std::string vCardPhotoHash_;
+ std::string password_;
+ CertificateWithKey::ref certificate_;
+ ClientOptions clientOptions_;
+ boost::shared_ptr<ErrorEvent> lastDisconnectError_;
+ bool useDelayForLatency_;
+ UserSearchController* userSearchControllerChat_;
+ UserSearchController* userSearchControllerAdd_;
+ UserSearchController* userSearchControllerInvite_;
+ int timeBeforeNextReconnect_;
+ Timer::ref reconnectTimer_;
+ StatusTracker* statusTracker_;
+ bool myStatusLooksOnline_;
+ bool quitRequested_;
+ bool offlineRequested_;
+ static const int SecondsToWaitBeforeForceQuitting;
+ FileTransferOverview* ftOverview_;
+ WhiteboardManager* whiteboardManager_;
+ HighlightManager* highlightManager_;
+ HighlightEditorController* highlightEditorController_;
+ std::map<std::string, std::string> emoticons_;
+ };
}
diff --git a/Swift/Controllers/PresenceNotifier.cpp b/Swift/Controllers/PresenceNotifier.cpp
index b579187..c000107 100644
--- a/Swift/Controllers/PresenceNotifier.cpp
+++ b/Swift/Controllers/PresenceNotifier.cpp
@@ -21,117 +21,117 @@
namespace Swift {
PresenceNotifier::PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory) : stanzaChannel(stanzaChannel), notifier(notifier), mucRegistry(mucRegistry), avatarManager(avatarManager), nickResolver(nickResolver), presenceOracle(presenceOracle), timerFactory(timerFactory) {
- justInitialized = true;
- inQuietPeriod = false;
- stanzaChannel->onPresenceReceived.connect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1));
- stanzaChannel->onAvailableChanged.connect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1));
- setInitialQuietPeriodMS(3000);
+ justInitialized = true;
+ inQuietPeriod = false;
+ stanzaChannel->onPresenceReceived.connect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1));
+ stanzaChannel->onAvailableChanged.connect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1));
+ setInitialQuietPeriodMS(3000);
}
PresenceNotifier::~PresenceNotifier() {
- if (timer) {
- timer->stop();
- timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this));
- timer.reset();
- }
- stanzaChannel->onAvailableChanged.disconnect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1));
- stanzaChannel->onPresenceReceived.disconnect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1));
+ if (timer) {
+ timer->stop();
+ timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this));
+ timer.reset();
+ }
+ stanzaChannel->onAvailableChanged.disconnect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1));
+ stanzaChannel->onPresenceReceived.disconnect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1));
}
void PresenceNotifier::handlePresenceReceived(boost::shared_ptr<Presence> presence) {
- JID from = presence->getFrom();
-
- if (mucRegistry->isMUC(from.toBare())) {
- return;
- }
-
- if (justInitialized) {
- justInitialized = false;
- if (timer) {
- inQuietPeriod = true;
- }
- }
-
- if (inQuietPeriod) {
- timer->stop();
- timer->start();
- return;
- }
-
- std::set<JID>::iterator i = availableUsers.find(from);
- if (presence->isAvailable()) {
- if (i != availableUsers.end()) {
- showNotification(from, Notifier::ContactStatusChange);
- }
- else {
- showNotification(from, Notifier::ContactAvailable);
- availableUsers.insert(from);
- }
- }
- else {
- if (i != availableUsers.end()) {
- showNotification(from, Notifier::ContactUnavailable);
- availableUsers.erase(i);
- }
- }
+ JID from = presence->getFrom();
+
+ if (mucRegistry->isMUC(from.toBare())) {
+ return;
+ }
+
+ if (justInitialized) {
+ justInitialized = false;
+ if (timer) {
+ inQuietPeriod = true;
+ }
+ }
+
+ if (inQuietPeriod) {
+ timer->stop();
+ timer->start();
+ return;
+ }
+
+ std::set<JID>::iterator i = availableUsers.find(from);
+ if (presence->isAvailable()) {
+ if (i != availableUsers.end()) {
+ showNotification(from, Notifier::ContactStatusChange);
+ }
+ else {
+ showNotification(from, Notifier::ContactAvailable);
+ availableUsers.insert(from);
+ }
+ }
+ else {
+ if (i != availableUsers.end()) {
+ showNotification(from, Notifier::ContactUnavailable);
+ availableUsers.erase(i);
+ }
+ }
}
void PresenceNotifier::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- availableUsers.clear();
- justInitialized = true;
- if (timer) {
- timer->stop();
- }
- }
+ if (available) {
+ availableUsers.clear();
+ justInitialized = true;
+ if (timer) {
+ timer->stop();
+ }
+ }
}
void PresenceNotifier::showNotification(const JID& jid, Notifier::Type type) {
- std::string name = nickResolver->jidToNick(jid);
- std::string title = name + " (" + getStatusType(jid) + ")";
- std::string message = getStatusMessage(jid);
- notifier->showMessage(type, title, message, avatarManager->getAvatarPath(jid), boost::bind(&PresenceNotifier::handleNotificationActivated, this, jid));
+ std::string name = nickResolver->jidToNick(jid);
+ std::string title = name + " (" + getStatusType(jid) + ")";
+ std::string message = getStatusMessage(jid);
+ notifier->showMessage(type, title, message, avatarManager->getAvatarPath(jid), boost::bind(&PresenceNotifier::handleNotificationActivated, this, jid));
}
void PresenceNotifier::handleNotificationActivated(JID jid) {
- onNotificationActivated(jid);
+ onNotificationActivated(jid);
}
std::string PresenceNotifier::getStatusType(const JID& jid) const {
- Presence::ref presence = presenceOracle->getLastPresence(jid);
- if (presence) {
- return statusShowTypeToFriendlyName(presence->getShow());
- }
- else {
- return "Unavailable";
- }
+ Presence::ref presence = presenceOracle->getLastPresence(jid);
+ if (presence) {
+ return statusShowTypeToFriendlyName(presence->getShow());
+ }
+ else {
+ return "Unavailable";
+ }
}
std::string PresenceNotifier::getStatusMessage(const JID& jid) const {
- Presence::ref presence = presenceOracle->getLastPresence(jid);
- if (presence) {
- return presence->getStatus();
- }
- else {
- return std::string();
- }
+ Presence::ref presence = presenceOracle->getLastPresence(jid);
+ if (presence) {
+ return presence->getStatus();
+ }
+ else {
+ return std::string();
+ }
}
void PresenceNotifier::setInitialQuietPeriodMS(int ms) {
- if (timer) {
- timer->stop();
- timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this));
- timer.reset();
- }
- if (ms > 0) {
- timer = timerFactory->createTimer(ms);
- timer->onTick.connect(boost::bind(&PresenceNotifier::handleTimerTick, this));
- }
+ if (timer) {
+ timer->stop();
+ timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this));
+ timer.reset();
+ }
+ if (ms > 0) {
+ timer = timerFactory->createTimer(ms);
+ timer->onTick.connect(boost::bind(&PresenceNotifier::handleTimerTick, this));
+ }
}
void PresenceNotifier::handleTimerTick() {
- inQuietPeriod = false;
- timer->stop();
+ inQuietPeriod = false;
+ timer->stop();
}
diff --git a/Swift/Controllers/PresenceNotifier.h b/Swift/Controllers/PresenceNotifier.h
index b02f8a2..3d498bd 100644
--- a/Swift/Controllers/PresenceNotifier.h
+++ b/Swift/Controllers/PresenceNotifier.h
@@ -19,44 +19,44 @@
#include <SwifTools/Notifier/Notifier.h>
namespace Swift {
- class TimerFactory;
- class StanzaChannel;
- class MUCRegistry;
- class NickResolver;
- class PresenceOracle;
-
- class PresenceNotifier {
- public:
- PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory);
- ~PresenceNotifier();
-
- void setInitialQuietPeriodMS(int ms);
-
- boost::signal<void (const JID&)> onNotificationActivated;
-
- private:
- void handlePresenceReceived(boost::shared_ptr<Presence>);
- void handleStanzaChannelAvailableChanged(bool);
- void handleNotificationActivated(JID jid);
- void handleTimerTick();
- std::string getStatusType(const JID&) const;
- std::string getStatusMessage(const JID&) const;
-
- private:
- void showNotification(const JID& jid, Notifier::Type type);
-
- private:
- StanzaChannel* stanzaChannel;
- Notifier* notifier;
- const MUCRegistry* mucRegistry;
- AvatarManager* avatarManager;
- NickResolver* nickResolver;
- const PresenceOracle* presenceOracle;
- TimerFactory* timerFactory;
- boost::shared_ptr<Timer> timer;
- bool justInitialized;
- bool inQuietPeriod;
- std::set<JID> availableUsers;
- };
+ class TimerFactory;
+ class StanzaChannel;
+ class MUCRegistry;
+ class NickResolver;
+ class PresenceOracle;
+
+ class PresenceNotifier {
+ public:
+ PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory);
+ ~PresenceNotifier();
+
+ void setInitialQuietPeriodMS(int ms);
+
+ boost::signal<void (const JID&)> onNotificationActivated;
+
+ private:
+ void handlePresenceReceived(boost::shared_ptr<Presence>);
+ void handleStanzaChannelAvailableChanged(bool);
+ void handleNotificationActivated(JID jid);
+ void handleTimerTick();
+ std::string getStatusType(const JID&) const;
+ std::string getStatusMessage(const JID&) const;
+
+ private:
+ void showNotification(const JID& jid, Notifier::Type type);
+
+ private:
+ StanzaChannel* stanzaChannel;
+ Notifier* notifier;
+ const MUCRegistry* mucRegistry;
+ AvatarManager* avatarManager;
+ NickResolver* nickResolver;
+ const PresenceOracle* presenceOracle;
+ TimerFactory* timerFactory;
+ boost::shared_ptr<Timer> timer;
+ bool justInitialized;
+ bool inQuietPeriod;
+ std::set<JID> availableUsers;
+ };
}
diff --git a/Swift/Controllers/PreviousStatusStore.cpp b/Swift/Controllers/PreviousStatusStore.cpp
index 6564ab5..4806f9c 100644
--- a/Swift/Controllers/PreviousStatusStore.cpp
+++ b/Swift/Controllers/PreviousStatusStore.cpp
@@ -19,35 +19,35 @@ PreviousStatusStore::~PreviousStatusStore() {
}
void PreviousStatusStore::addStatus(StatusShow::Type status, const std::string& message) {
- //FIXME: remove old entries
- store_.push_back(TypeStringPair(status, 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> 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_) {
- 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;
+ std::vector<TypeStringPair> suggestions;
+ foreach (TypeStringPair 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 51c2dd9..eb1fb59 100644
--- a/Swift/Controllers/PreviousStatusStore.h
+++ b/Swift/Controllers/PreviousStatusStore.h
@@ -13,16 +13,16 @@
#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);
+ 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_;
- };
+ private:
+ std::vector<TypeStringPair> exactMatchSuggestions(StatusShow::Type status, const std::string& message);
+ std::vector<TypeStringPair> store_;
+ };
}
diff --git a/Swift/Controllers/ProfileController.cpp b/Swift/Controllers/ProfileController.cpp
index a1aa5f9..756aaff 100644
--- a/Swift/Controllers/ProfileController.cpp
+++ b/Swift/Controllers/ProfileController.cpp
@@ -18,97 +18,97 @@
namespace Swift {
ProfileController::ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream) : vcardManager(vcardManager), profileWindowFactory(profileWindowFactory), uiEventStream(uiEventStream), available(true), profileWindow(NULL), gettingVCard(false) {
- uiEventStream->onUIEvent.connect(boost::bind(&ProfileController::handleUIEvent, this, _1));
+ uiEventStream->onUIEvent.connect(boost::bind(&ProfileController::handleUIEvent, this, _1));
}
ProfileController::~ProfileController() {
- if (profileWindow) {
- vcardManager->onOwnVCardChanged.disconnect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1));
- vcardManager->onVCardRetrievalError.disconnect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2));
- profileWindow->onVCardChangeRequest.disconnect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1));
- profileWindow->onWindowAboutToBeClosed.disconnect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1));
- }
- uiEventStream->onUIEvent.disconnect(boost::bind(&ProfileController::handleUIEvent, this, _1));
- delete profileWindow;
+ if (profileWindow) {
+ vcardManager->onOwnVCardChanged.disconnect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1));
+ vcardManager->onVCardRetrievalError.disconnect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2));
+ profileWindow->onVCardChangeRequest.disconnect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1));
+ profileWindow->onWindowAboutToBeClosed.disconnect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1));
+ }
+ uiEventStream->onUIEvent.disconnect(boost::bind(&ProfileController::handleUIEvent, this, _1));
+ delete profileWindow;
}
void ProfileController::handleUIEvent(UIEvent::ref event) {
- if (!boost::dynamic_pointer_cast<RequestProfileEditorUIEvent>(event)) {
- return;
- }
-
- if (!profileWindow) {
- profileWindow = profileWindowFactory->createProfileWindow();
- profileWindow->setEditable(true);
- profileWindow->onVCardChangeRequest.connect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1));
- profileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1));
- vcardManager->onOwnVCardChanged.connect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1));
- vcardManager->onVCardRetrievalError.connect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2));
- }
- gettingVCard = true;
- updateDialogStatus();
- vcardManager->requestOwnVCard();
- profileWindow->show();
+ if (!boost::dynamic_pointer_cast<RequestProfileEditorUIEvent>(event)) {
+ return;
+ }
+
+ if (!profileWindow) {
+ profileWindow = profileWindowFactory->createProfileWindow();
+ profileWindow->setEditable(true);
+ profileWindow->onVCardChangeRequest.connect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1));
+ profileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1));
+ vcardManager->onOwnVCardChanged.connect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1));
+ vcardManager->onVCardRetrievalError.connect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2));
+ }
+ gettingVCard = true;
+ updateDialogStatus();
+ vcardManager->requestOwnVCard();
+ profileWindow->show();
}
void ProfileController::handleVCardChangeRequest(VCard::ref vcard) {
- assert(!pendingSetVCardRequest);
- profileWindow->setError("");
- pendingSetVCardRequest = vcardManager->createSetVCardRequest(vcard);
- pendingSetVCardRequest->onResponse.connect(boost::bind(&ProfileController::handleSetVCardResponse, this, _2));
- pendingSetVCardRequest->send();
- updateDialogStatus();
+ assert(!pendingSetVCardRequest);
+ profileWindow->setError("");
+ pendingSetVCardRequest = vcardManager->createSetVCardRequest(vcard);
+ pendingSetVCardRequest->onResponse.connect(boost::bind(&ProfileController::handleSetVCardResponse, this, _2));
+ pendingSetVCardRequest->send();
+ updateDialogStatus();
}
void ProfileController::handleSetVCardResponse(ErrorPayload::ref error) {
- pendingSetVCardRequest.reset();
- updateDialogStatus();
- if (error) {
- profileWindow->setVCard(vcardBeforeEdit);
- profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error publishing your profile data"));
- }
- else {
- profileWindow->setError("");
- profileWindow->hide();
- }
+ pendingSetVCardRequest.reset();
+ updateDialogStatus();
+ if (error) {
+ profileWindow->setVCard(vcardBeforeEdit);
+ profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error publishing your profile data"));
+ }
+ else {
+ profileWindow->setError("");
+ profileWindow->hide();
+ }
}
void ProfileController::handleVCardRetrievalError(const JID& jid, ErrorPayload::ref /* error */) {
- if ((jid == JID()) && profileWindow) {
- profileWindow->setProcessing(false);
- profileWindow->setEnabled(false);
- profileWindow->setVCard(boost::make_shared<VCard>());
- profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error fetching your current profile data"));
- }
+ if ((jid == JID()) && profileWindow) {
+ profileWindow->setProcessing(false);
+ profileWindow->setEnabled(false);
+ profileWindow->setVCard(boost::make_shared<VCard>());
+ profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error fetching your current profile data"));
+ }
}
void ProfileController::handleOwnVCardChanged(VCard::ref vcard) {
- if (profileWindow) {
- profileWindow->setVCard(vcard);
- vcardBeforeEdit = vcard;
- gettingVCard = false;
- updateDialogStatus();
- }
+ if (profileWindow) {
+ profileWindow->setVCard(vcard);
+ vcardBeforeEdit = vcard;
+ gettingVCard = false;
+ updateDialogStatus();
+ }
}
void ProfileController::handleProfileWindowAboutToBeClosed(const JID&) {
- profileWindow = NULL;
+ profileWindow = NULL;
}
void ProfileController::setAvailable(bool b) {
- available = b;
- if (!available) {
- pendingSetVCardRequest.reset();
- }
- updateDialogStatus();
+ available = b;
+ if (!available) {
+ pendingSetVCardRequest.reset();
+ }
+ updateDialogStatus();
}
void ProfileController::updateDialogStatus() {
- if (profileWindow) {
- profileWindow->setEnabled(available && !gettingVCard && !pendingSetVCardRequest);
- profileWindow->setProcessing(gettingVCard || pendingSetVCardRequest);
- }
+ if (profileWindow) {
+ profileWindow->setEnabled(available && !gettingVCard && !pendingSetVCardRequest);
+ profileWindow->setProcessing(gettingVCard || pendingSetVCardRequest);
+ }
}
}
diff --git a/Swift/Controllers/ProfileController.h b/Swift/Controllers/ProfileController.h
index ebb569d..3bb1fce 100644
--- a/Swift/Controllers/ProfileController.h
+++ b/Swift/Controllers/ProfileController.h
@@ -13,36 +13,36 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class ProfileWindow;
- class ProfileWindowFactory;
- class UIEventStream;
- class VCardManager;
-
- class ProfileController {
- public:
- ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream);
- ~ProfileController();
-
- void setAvailable(bool b);
-
- private:
- void handleUIEvent(UIEvent::ref event);
- void handleVCardChangeRequest(VCard::ref vcard);
- void handleSetVCardResponse(ErrorPayload::ref);
- void handleOwnVCardChanged(VCard::ref vcard);
- void handleVCardRetrievalError(const JID& jid, ErrorPayload::ref error);
- void handleProfileWindowAboutToBeClosed(const JID&);
- void updateDialogStatus();
-
- private:
- VCardManager* vcardManager;
- ProfileWindowFactory* profileWindowFactory;
- UIEventStream* uiEventStream;
- bool available;
- SetVCardRequest::ref pendingSetVCardRequest;
- ProfileWindow* profileWindow;
- bool gettingVCard;
- VCard::ref vcardBeforeEdit;
- };
+ class ProfileWindow;
+ class ProfileWindowFactory;
+ class UIEventStream;
+ class VCardManager;
+
+ class ProfileController {
+ public:
+ ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream);
+ ~ProfileController();
+
+ void setAvailable(bool b);
+
+ private:
+ void handleUIEvent(UIEvent::ref event);
+ void handleVCardChangeRequest(VCard::ref vcard);
+ void handleSetVCardResponse(ErrorPayload::ref);
+ void handleOwnVCardChanged(VCard::ref vcard);
+ void handleVCardRetrievalError(const JID& jid, ErrorPayload::ref error);
+ void handleProfileWindowAboutToBeClosed(const JID&);
+ void updateDialogStatus();
+
+ private:
+ VCardManager* vcardManager;
+ ProfileWindowFactory* profileWindowFactory;
+ UIEventStream* uiEventStream;
+ bool available;
+ SetVCardRequest::ref pendingSetVCardRequest;
+ ProfileWindow* profileWindow;
+ bool gettingVCard;
+ VCard::ref vcardBeforeEdit;
+ };
}
diff --git a/Swift/Controllers/ProfileSettingsProvider.cpp b/Swift/Controllers/ProfileSettingsProvider.cpp
index 86f4c99..bb186fc 100644
--- a/Swift/Controllers/ProfileSettingsProvider.cpp
+++ b/Swift/Controllers/ProfileSettingsProvider.cpp
@@ -9,58 +9,58 @@
namespace Swift {
ProfileSettingsProvider::ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider) :
- profile_(profile) {
- provider_ = provider;
- bool found = false;
- foreach (std::string existingProfile, provider->getAvailableProfiles()) {
- if (existingProfile == profile) {
- found = true;
- }
- }
- if (!found) {
- provider_->createProfile(profile);
- }
+ profile_(profile) {
+ provider_ = provider;
+ bool found = false;
+ foreach (std::string 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);
+ //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);
- }
+ //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);
+ //FIXME: Remove shim
+ SettingsProvider::Setting<int> setting(profileSettingPath(settingPath), defaultValue);
+ return provider_->getSetting(setting);
}
void ProfileSettingsProvider::storeInt(const std::string& settingPath, int settingValue) {
- //FIXME: Remove shim
- if (!getIsSettingFinal(settingPath)) {
- SettingsProvider::Setting<int> setting(profileSettingPath(settingPath), 0);
- provider_->storeSetting(setting, settingValue);
- }
+ //FIXME: Remove shim
+ if (!getIsSettingFinal(settingPath)) {
+ SettingsProvider::Setting<int> setting(profileSettingPath(settingPath), 0);
+ provider_->storeSetting(setting, settingValue);
+ }
}
bool ProfileSettingsProvider::getIsSettingFinal(const std::string& settingPath) {
- //FIXME: Remove shim
- SettingsProvider::Setting<int> setting(settingPath, 0);
- return provider_->getIsSettingFinal(setting);
+ //FIXME: Remove shim
+ SettingsProvider::Setting<int> setting(settingPath, 0);
+ return provider_->getIsSettingFinal(setting);
}
std::string ProfileSettingsProvider::profileSettingPath(const std::string &settingPath) {
- return profile_ + ":" + settingPath;
+ return profile_ + ":" + settingPath;
}
diff --git a/Swift/Controllers/ProfileSettingsProvider.h b/Swift/Controllers/ProfileSettingsProvider.h
index 02e1e81..f3c3156 100644
--- a/Swift/Controllers/ProfileSettingsProvider.h
+++ b/Swift/Controllers/ProfileSettingsProvider.h
@@ -13,20 +13,20 @@
namespace Swift {
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);
- SettingsProvider* provider_;
- std::string profile_;
+ 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);
+ SettingsProvider* provider_;
+ std::string profile_;
};
}
diff --git a/Swift/Controllers/Roster/ContactRosterItem.cpp b/Swift/Controllers/Roster/ContactRosterItem.cpp
index 3258fb5..89053e6 100644
--- a/Swift/Controllers/Roster/ContactRosterItem.cpp
+++ b/Swift/Controllers/Roster/ContactRosterItem.cpp
@@ -27,149 +27,149 @@ ContactRosterItem::~ContactRosterItem() {
}
StatusShow::Type ContactRosterItem::getStatusShow() const {
- return presence_ ? presence_->getShow() : StatusShow::None;
+ 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;
- }
- assert(false);
- return StatusShow::None;
+ 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;
+ }
+ assert(false);
+ return StatusShow::None;
}
std::string ContactRosterItem::getStatusText() const {
- return presence_ ? presence_->getStatus() : "";
+ return presence_ ? presence_->getStatus() : "";
}
std::string ContactRosterItem::getIdleText() const {
- Idle::ref idle = presence_ ? presence_->getPayload<Idle>() : Idle::ref();
- if (!idle || idle->getSince().is_not_a_date_time()) {
- return "";
- } else {
- return dateTimeToLocalString(idle->getSince());
- }
+ Idle::ref idle = presence_ ? presence_->getPayload<Idle>() : Idle::ref();
+ if (!idle || idle->getSince().is_not_a_date_time()) {
+ return "";
+ } else {
+ return dateTimeToLocalString(idle->getSince());
+ }
}
std::string ContactRosterItem::getOfflineSinceText() const {
- if (presence_ && presence_->getType() == Presence::Unavailable) {
- boost::optional<boost::posix_time::ptime> delay = presence_->getTimestamp();
- if (delay) {
- return dateTimeToLocalString(*delay);
- }
- }
- return "";
+ if (presence_ && presence_->getType() == Presence::Unavailable) {
+ boost::optional<boost::posix_time::ptime> delay = presence_->getTimestamp();
+ if (delay) {
+ return dateTimeToLocalString(*delay);
+ }
+ }
+ return "";
}
void ContactRosterItem::setAvatarPath(const boost::filesystem::path& path) {
- avatarPath_ = path;
- onDataChanged();
+ avatarPath_ = path;
+ onDataChanged();
}
const boost::filesystem::path& ContactRosterItem::getAvatarPath() const {
- return avatarPath_;
+ return avatarPath_;
}
const JID& ContactRosterItem::getJID() const {
- return jid_;
+ return jid_;
}
void ContactRosterItem::setDisplayJID(const JID& jid) {
- displayJID_ = jid;
+ displayJID_ = jid;
}
const JID& ContactRosterItem::getDisplayJID() const {
- return displayJID_;
+ return displayJID_;
}
typedef std::pair<std::string, boost::shared_ptr<Presence> > StringPresencePair;
void ContactRosterItem::clearPresence() {
- presence_.reset();
- onDataChanged();
+ presence_.reset();
+ onDataChanged();
}
void ContactRosterItem::applyPresence(boost::shared_ptr<Presence> presence) {
- presence_ = presence;
- onDataChanged();
+ presence_ = presence;
+ onDataChanged();
}
const std::vector<std::string>& ContactRosterItem::getGroups() const {
- return groups_;
+ return groups_;
}
/** Only used so a contact can know about the groups it's in*/
void ContactRosterItem::addGroup(const std::string& group) {
- groups_.push_back(group);
+ groups_.push_back(group);
}
void ContactRosterItem::removeGroup(const std::string& group) {
- groups_.erase(std::remove(groups_.begin(), groups_.end(), group), groups_.end());
+ groups_.erase(std::remove(groups_.begin(), groups_.end(), group), groups_.end());
}
MUCOccupant::Role ContactRosterItem::getMUCRole() const
{
- return mucRole_;
+ return mucRole_;
}
void ContactRosterItem::setMUCRole(const MUCOccupant::Role& role)
{
- mucRole_ = role;
+ mucRole_ = role;
}
MUCOccupant::Affiliation ContactRosterItem::getMUCAffiliation() const
{
- return mucAffiliation_;
+ return mucAffiliation_;
}
void ContactRosterItem::setMUCAffiliation(const MUCOccupant::Affiliation& affiliation)
{
- mucAffiliation_ = affiliation;
+ mucAffiliation_ = affiliation;
}
std::string ContactRosterItem::getMUCAffiliationText() const
{
- std::string affiliationString;
- switch (mucAffiliation_) {
- case MUCOccupant::Owner: affiliationString = QT_TRANSLATE_NOOP("", "Owner"); break;
- case MUCOccupant::Admin: affiliationString = QT_TRANSLATE_NOOP("", "Admin"); break;
- case MUCOccupant::Member: affiliationString = QT_TRANSLATE_NOOP("", "Member"); break;
- case MUCOccupant::Outcast: affiliationString = QT_TRANSLATE_NOOP("", "Outcast"); break;
- case MUCOccupant::NoAffiliation: affiliationString = ""; break;
- }
+ std::string affiliationString;
+ switch (mucAffiliation_) {
+ case MUCOccupant::Owner: affiliationString = QT_TRANSLATE_NOOP("", "Owner"); break;
+ case MUCOccupant::Admin: affiliationString = QT_TRANSLATE_NOOP("", "Admin"); break;
+ case MUCOccupant::Member: affiliationString = QT_TRANSLATE_NOOP("", "Member"); break;
+ case MUCOccupant::Outcast: affiliationString = QT_TRANSLATE_NOOP("", "Outcast"); break;
+ case MUCOccupant::NoAffiliation: affiliationString = ""; break;
+ }
- return affiliationString;
+ return affiliationString;
}
void ContactRosterItem::setSupportedFeatures(const std::set<Feature>& features) {
- features_ = features;
- onDataChanged();
+ features_ = features;
+ onDataChanged();
}
bool ContactRosterItem::supportsFeature(const Feature feature) const {
- return features_.find(feature) != features_.end();
+ return features_.find(feature) != features_.end();
}
void ContactRosterItem::setBlockState(BlockState state) {
- blockState_ = state;
- onDataChanged();
+ blockState_ = state;
+ onDataChanged();
}
ContactRosterItem::BlockState ContactRosterItem::blockState() const {
- return blockState_;
+ return blockState_;
}
VCard::ref ContactRosterItem::getVCard() const {
- return vcard_;
+ return vcard_;
}
void ContactRosterItem::setVCard(VCard::ref vcard) {
- vcard_ = vcard;
- onDataChanged();
+ vcard_ = vcard;
+ onDataChanged();
}
}
diff --git a/Swift/Controllers/Roster/ContactRosterItem.h b/Swift/Controllers/Roster/ContactRosterItem.h
index d21935c..d77ba2d 100644
--- a/Swift/Controllers/Roster/ContactRosterItem.h
+++ b/Swift/Controllers/Roster/ContactRosterItem.h
@@ -28,69 +28,69 @@ namespace Swift {
class GroupRosterItem;
class ContactRosterItem : public RosterItem {
- public:
- enum Feature {
- FileTransferFeature,
- WhiteboardFeature
- };
-
- enum BlockState {
- BlockingNotSupported,
- IsBlocked,
- IsUnblocked,
- IsDomainBlocked
- };
-
- public:
- ContactRosterItem(const JID& jid, const JID& displayJID, const std::string& name, GroupRosterItem* parent);
- virtual ~ContactRosterItem();
-
- StatusShow::Type getStatusShow() const;
- StatusShow::Type getSimplifiedStatusShow() const;
- std::string getStatusText() const;
- std::string getIdleText() const;
- std::string getOfflineSinceText() const;
- void setAvatarPath(const boost::filesystem::path& path);
- const boost::filesystem::path& getAvatarPath() const;
- const JID& getJID() const;
- void setDisplayJID(const JID& jid);
- const JID& getDisplayJID() const;
- void applyPresence(boost::shared_ptr<Presence> presence);
- const std::vector<std::string>& getGroups() const;
- /** Only used so a contact can know about the groups it's in*/
- void addGroup(const std::string& group);
- void removeGroup(const std::string& group);
- void clearPresence();
-
- MUCOccupant::Role getMUCRole() const;
- void setMUCRole(const MUCOccupant::Role& role);
- MUCOccupant::Affiliation getMUCAffiliation() const;
- void setMUCAffiliation(const MUCOccupant::Affiliation& affiliation);
- std::string getMUCAffiliationText() const;
-
- void setSupportedFeatures(const std::set<Feature>& features);
- bool supportsFeature(Feature feature) const;
-
- void setBlockState(BlockState state);
- BlockState blockState() const;
-
- VCard::ref getVCard() const;
- void setVCard(VCard::ref vcard);
-
- boost::signal<void ()> onVCardRequested;
-
- private:
- JID jid_;
- JID displayJID_;
- boost::posix_time::ptime lastAvailableTime_;
- boost::filesystem::path avatarPath_;
- boost::shared_ptr<Presence> presence_;
- std::vector<std::string> groups_;
- MUCOccupant::Role mucRole_;
- MUCOccupant::Affiliation mucAffiliation_;
- std::set<Feature> features_;
- BlockState blockState_;
- VCard::ref vcard_;
+ public:
+ enum Feature {
+ FileTransferFeature,
+ WhiteboardFeature
+ };
+
+ enum BlockState {
+ BlockingNotSupported,
+ IsBlocked,
+ IsUnblocked,
+ IsDomainBlocked
+ };
+
+ public:
+ ContactRosterItem(const JID& jid, const JID& displayJID, const std::string& name, GroupRosterItem* parent);
+ virtual ~ContactRosterItem();
+
+ StatusShow::Type getStatusShow() const;
+ StatusShow::Type getSimplifiedStatusShow() const;
+ std::string getStatusText() const;
+ std::string getIdleText() const;
+ std::string getOfflineSinceText() const;
+ void setAvatarPath(const boost::filesystem::path& path);
+ const boost::filesystem::path& getAvatarPath() const;
+ const JID& getJID() const;
+ void setDisplayJID(const JID& jid);
+ const JID& getDisplayJID() const;
+ void applyPresence(boost::shared_ptr<Presence> presence);
+ const std::vector<std::string>& getGroups() const;
+ /** Only used so a contact can know about the groups it's in*/
+ void addGroup(const std::string& group);
+ void removeGroup(const std::string& group);
+ void clearPresence();
+
+ MUCOccupant::Role getMUCRole() const;
+ void setMUCRole(const MUCOccupant::Role& role);
+ MUCOccupant::Affiliation getMUCAffiliation() const;
+ void setMUCAffiliation(const MUCOccupant::Affiliation& affiliation);
+ std::string getMUCAffiliationText() const;
+
+ void setSupportedFeatures(const std::set<Feature>& features);
+ bool supportsFeature(Feature feature) const;
+
+ void setBlockState(BlockState state);
+ BlockState blockState() const;
+
+ VCard::ref getVCard() const;
+ void setVCard(VCard::ref vcard);
+
+ boost::signal<void ()> onVCardRequested;
+
+ private:
+ JID jid_;
+ JID displayJID_;
+ boost::posix_time::ptime lastAvailableTime_;
+ boost::filesystem::path avatarPath_;
+ boost::shared_ptr<Presence> presence_;
+ std::vector<std::string> groups_;
+ MUCOccupant::Role mucRole_;
+ MUCOccupant::Affiliation mucAffiliation_;
+ std::set<Feature> features_;
+ BlockState blockState_;
+ VCard::ref vcard_;
};
}
diff --git a/Swift/Controllers/Roster/FuzzyRosterFilter.h b/Swift/Controllers/Roster/FuzzyRosterFilter.h
index 14e0f62..8c45935 100644
--- a/Swift/Controllers/Roster/FuzzyRosterFilter.h
+++ b/Swift/Controllers/Roster/FuzzyRosterFilter.h
@@ -22,21 +22,21 @@
namespace Swift {
class FuzzyRosterFilter : public RosterFilter {
- public:
- FuzzyRosterFilter(const std::string& query) : query_(query) { }
- virtual ~FuzzyRosterFilter() {}
- virtual bool operator() (RosterItem* item) const {
- ContactRosterItem *contactItem = dynamic_cast<ContactRosterItem*>(item);
- if (contactItem) {
- const bool itemMatched = ContactSuggester::fuzzyMatch(contactItem->getDisplayName(), query_) || ContactSuggester::fuzzyMatch(contactItem->getDisplayJID(), query_);
- return !itemMatched;
- } else {
- return false;
- }
- }
-
- private:
- std::string query_;
+ public:
+ FuzzyRosterFilter(const std::string& query) : query_(query) { }
+ virtual ~FuzzyRosterFilter() {}
+ virtual bool operator() (RosterItem* item) const {
+ ContactRosterItem *contactItem = dynamic_cast<ContactRosterItem*>(item);
+ if (contactItem) {
+ const bool itemMatched = ContactSuggester::fuzzyMatch(contactItem->getDisplayName(), query_) || ContactSuggester::fuzzyMatch(contactItem->getDisplayJID(), query_);
+ return !itemMatched;
+ } else {
+ return false;
+ }
+ }
+
+ private:
+ std::string query_;
};
}
diff --git a/Swift/Controllers/Roster/GroupRosterItem.cpp b/Swift/Controllers/Roster/GroupRosterItem.cpp
index 6c68851..82e43df 100644
--- a/Swift/Controllers/Roster/GroupRosterItem.cpp
+++ b/Swift/Controllers/Roster/GroupRosterItem.cpp
@@ -12,7 +12,7 @@
namespace Swift {
GroupRosterItem::GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus) : RosterItem(name, parent), sortByStatus_(sortByStatus), manualSort_(false) {
- expanded_ = true;
+ expanded_ = true;
}
GroupRosterItem::~GroupRosterItem() {
@@ -20,77 +20,77 @@ GroupRosterItem::~GroupRosterItem() {
}
void GroupRosterItem::setManualSort(const std::string& manualSortValue) {
- manualSort_ = true;
- bool changed = manualSortValue_ != manualSortValue;
- manualSortValue_ = manualSortValue;
- if (changed) {
- onChildrenChanged();
- onDataChanged();
- }
+ manualSort_ = true;
+ bool changed = manualSortValue_ != manualSortValue;
+ manualSortValue_ = manualSortValue;
+ if (changed) {
+ onChildrenChanged();
+ onDataChanged();
+ }
}
const std::string& GroupRosterItem::getSortableDisplayName() const {
- return manualSort_ ? manualSortValue_ : RosterItem::getSortableDisplayName();
+ return manualSort_ ? manualSortValue_ : RosterItem::getSortableDisplayName();
}
bool GroupRosterItem::isExpanded() const {
- return expanded_;
+ return expanded_;
}
/**
- This has no effect, and is only used by the UI.
- If reTransmit is specified, dataChanged will be emitted on a change -
- This may be undesireable if called from the UI, so you can use reTransmit=false
- to avoid a loop in this case.
+ This has no effect, and is only used by the UI.
+ If reTransmit is specified, dataChanged will be emitted on a change -
+ This may be undesireable if called from the UI, so you can use reTransmit=false
+ to avoid a loop in this case.
*/
void GroupRosterItem::setExpanded(bool expanded) {
- bool old = expanded_;
- expanded_ = expanded;
- if (expanded != old) {
- onExpandedChanged(expanded);
- }
+ bool old = expanded_;
+ expanded_ = expanded;
+ if (expanded != old) {
+ onExpandedChanged(expanded);
+ }
}
const std::vector<RosterItem*>& GroupRosterItem::getChildren() const {
- return children_;
+ return children_;
}
const std::vector<RosterItem*>& GroupRosterItem::getDisplayedChildren() const {
- return displayedChildren_;
+ return displayedChildren_;
}
void GroupRosterItem::addChild(RosterItem* item) {
- children_.push_back(item);
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- if (group) {
- group->onChildrenChanged.connect(boost::bind(&GroupRosterItem::handleChildrenChanged, this, group));
- } else {
- item->onDataChanged.connect(boost::bind(&GroupRosterItem::handleDataChanged, this, item));
- }
- onChildrenChanged();
- onDataChanged();
+ children_.push_back(item);
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ if (group) {
+ group->onChildrenChanged.connect(boost::bind(&GroupRosterItem::handleChildrenChanged, this, group));
+ } else {
+ item->onDataChanged.connect(boost::bind(&GroupRosterItem::handleDataChanged, this, item));
+ }
+ onChildrenChanged();
+ onDataChanged();
}
/**
* Does not emit a changed signal.
*/
void GroupRosterItem::removeAll() {
- std::vector<RosterItem*>::iterator it = children_.begin();
- displayedChildren_.clear();
- while (it != children_.end()) {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(*it);
- if (contact) {
- delete contact;
- } else {
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
- if (group) {
- group->removeAll();
- delete group;
- }
- }
- ++it;
- }
- children_.clear();
+ std::vector<RosterItem*>::iterator it = children_.begin();
+ displayedChildren_.clear();
+ while (it != children_.end()) {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(*it);
+ if (contact) {
+ delete contact;
+ } else {
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
+ if (group) {
+ group->removeAll();
+ delete group;
+ }
+ }
+ ++it;
+ }
+ children_.clear();
}
/**
@@ -98,136 +98,136 @@ void GroupRosterItem::removeAll() {
* the return result is undefined.
*/
ContactRosterItem* GroupRosterItem::removeChild(const JID& jid) {
- std::vector<RosterItem*>::iterator it = children_.begin();
- ContactRosterItem* removed = NULL;
- while (it != children_.end()) {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(*it);
- if (contact && contact->getJID() == jid) {
- displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), contact), displayedChildren_.end());
- removed = contact;
- delete contact;
- it = children_.erase(it);
- continue;
- }
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
- if (group) {
- ContactRosterItem* groupRemoved = group->removeChild(jid);
- if (groupRemoved) {
- removed = groupRemoved;
- }
- }
- ++it;
- }
- onChildrenChanged();
- onDataChanged();
- return removed;
+ std::vector<RosterItem*>::iterator it = children_.begin();
+ ContactRosterItem* removed = NULL;
+ while (it != children_.end()) {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(*it);
+ if (contact && contact->getJID() == jid) {
+ displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), contact), displayedChildren_.end());
+ removed = contact;
+ delete contact;
+ it = children_.erase(it);
+ continue;
+ }
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
+ if (group) {
+ ContactRosterItem* groupRemoved = group->removeChild(jid);
+ if (groupRemoved) {
+ removed = groupRemoved;
+ }
+ }
+ ++it;
+ }
+ onChildrenChanged();
+ onDataChanged();
+ return removed;
}
GroupRosterItem* GroupRosterItem::removeGroupChild(const std::string& groupName) {
- std::vector<RosterItem*>::iterator it = children_.begin();
- GroupRosterItem* removed = NULL;
- while (it != children_.end()) {
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
- if (group && group->getDisplayName() == groupName) {
- displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end());
- removed = group;
- delete group;
- it = children_.erase(it);
- continue;
- }
- ++it;
- }
- onChildrenChanged();
- onDataChanged();
- return removed;
+ std::vector<RosterItem*>::iterator it = children_.begin();
+ GroupRosterItem* removed = NULL;
+ while (it != children_.end()) {
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
+ if (group && group->getDisplayName() == groupName) {
+ displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end());
+ removed = group;
+ delete group;
+ it = children_.erase(it);
+ continue;
+ }
+ ++it;
+ }
+ onChildrenChanged();
+ onDataChanged();
+ return removed;
}
/**
* Returns false if the list didn't need a resort
*/
bool GroupRosterItem::sortDisplayed() {
- /* Not doing this until we import boost::algorithm*/
-// if (boost::is_sorted(displayedChildren_begin(), displayedChildren_.end(), itemLessThan)) {
-// return false;
-// }
- //Sholudn't need stable_sort here
- std::sort(displayedChildren_.begin(), displayedChildren_.end(), sortByStatus_? itemLessThanWithStatus : itemLessThanWithoutStatus);
- return true;
+ /* Not doing this until we import boost::algorithm*/
+// if (boost::is_sorted(displayedChildren_begin(), displayedChildren_.end(), itemLessThan)) {
+// return false;
+// }
+ //Sholudn't need stable_sort here
+ std::sort(displayedChildren_.begin(), displayedChildren_.end(), sortByStatus_? itemLessThanWithStatus : itemLessThanWithoutStatus);
+ return true;
}
bool GroupRosterItem::itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right) {
- return left->getSortableDisplayName() < right->getSortableDisplayName();
+ return left->getSortableDisplayName() < right->getSortableDisplayName();
}
bool GroupRosterItem::itemLessThanWithStatus(const RosterItem* left, const RosterItem* right) {
- const ContactRosterItem* leftContact = dynamic_cast<const ContactRosterItem*>(left);
- const ContactRosterItem* rightContact = dynamic_cast<const ContactRosterItem*>(right);
- if (leftContact) {
- if (!rightContact) {
- return false;
- }
- StatusShow::Type leftType = leftContact->getSimplifiedStatusShow();
- StatusShow::Type rightType = rightContact->getSimplifiedStatusShow();
- if (leftType == rightType) {
- return left->getSortableDisplayName() < right->getSortableDisplayName();
- } else {
- return leftType < rightType;
- }
- } else {
- if (rightContact) {
- return true;
- }
- return left->getSortableDisplayName() < right->getSortableDisplayName();
- }
+ const ContactRosterItem* leftContact = dynamic_cast<const ContactRosterItem*>(left);
+ const ContactRosterItem* rightContact = dynamic_cast<const ContactRosterItem*>(right);
+ if (leftContact) {
+ if (!rightContact) {
+ return false;
+ }
+ StatusShow::Type leftType = leftContact->getSimplifiedStatusShow();
+ StatusShow::Type rightType = rightContact->getSimplifiedStatusShow();
+ if (leftType == rightType) {
+ return left->getSortableDisplayName() < right->getSortableDisplayName();
+ } else {
+ return leftType < rightType;
+ }
+ } else {
+ if (rightContact) {
+ return true;
+ }
+ return left->getSortableDisplayName() < right->getSortableDisplayName();
+ }
}
void GroupRosterItem::setDisplayed(RosterItem* item, bool displayed) {
- bool found = false;
- for (size_t i = 0; i < displayedChildren_.size(); i++) {
- if (displayedChildren_[i] == item) {
- found = true;
- }
- }
- if (found == displayed) {
- return;
- }
- if (displayed) {
- displayedChildren_.push_back(item);
- sortDisplayed();
- } else {
- displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), item), displayedChildren_.end());
- }
- onChildrenChanged();
- onDataChanged();
+ bool found = false;
+ for (size_t i = 0; i < displayedChildren_.size(); i++) {
+ if (displayedChildren_[i] == item) {
+ found = true;
+ }
+ }
+ if (found == displayed) {
+ return;
+ }
+ if (displayed) {
+ displayedChildren_.push_back(item);
+ sortDisplayed();
+ } else {
+ displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), item), displayedChildren_.end());
+ }
+ onChildrenChanged();
+ onDataChanged();
}
void GroupRosterItem::handleDataChanged(RosterItem* /*item*/) {
- if (sortDisplayed()) {
- onChildrenChanged();
- }
+ if (sortDisplayed()) {
+ onChildrenChanged();
+ }
}
void GroupRosterItem::handleChildrenChanged(GroupRosterItem* group) {
- size_t oldSize = getDisplayedChildren().size();
- if (group->getDisplayedChildren().size() > 0) {
- bool found = false;
- for (size_t i = 0; i < displayedChildren_.size(); i++) {
- if (displayedChildren_[i] == group) {
- found = true;
- }
- }
- if (!found) {
- displayedChildren_.push_back(group);
- sortDisplayed();
- }
- } else {
- displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end());
- }
-
- if (oldSize != getDisplayedChildren().size() || sortDisplayed()) {
- onChildrenChanged();
- onDataChanged();
- }
+ size_t oldSize = getDisplayedChildren().size();
+ if (group->getDisplayedChildren().size() > 0) {
+ bool found = false;
+ for (size_t i = 0; i < displayedChildren_.size(); i++) {
+ if (displayedChildren_[i] == group) {
+ found = true;
+ }
+ }
+ if (!found) {
+ displayedChildren_.push_back(group);
+ sortDisplayed();
+ }
+ } else {
+ displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end());
+ }
+
+ if (oldSize != getDisplayedChildren().size() || sortDisplayed()) {
+ onChildrenChanged();
+ onDataChanged();
+ }
}
diff --git a/Swift/Controllers/Roster/GroupRosterItem.h b/Swift/Controllers/Roster/GroupRosterItem.h
index 9b4024f..760b008 100644
--- a/Swift/Controllers/Roster/GroupRosterItem.h
+++ b/Swift/Controllers/Roster/GroupRosterItem.h
@@ -15,35 +15,35 @@
namespace Swift {
class GroupRosterItem : public RosterItem {
- public:
- GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus);
- virtual ~GroupRosterItem();
- const std::vector<RosterItem*>& getChildren() const;
- const std::vector<RosterItem*>& getDisplayedChildren() const;
- void addChild(RosterItem* item);
- ContactRosterItem* removeChild(const JID& jid);
- GroupRosterItem* removeGroupChild(const std::string& group);
- void removeAll();
- void setDisplayed(RosterItem* item, bool displayed);
- boost::signal<void ()> onChildrenChanged;
- static bool itemLessThanWithStatus(const RosterItem* left, const RosterItem* right);
- static bool itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right);
- void setExpanded(bool expanded);
- bool isExpanded() const;
- boost::signal<void (bool)> onExpandedChanged;
- void setManualSort(const std::string& manualSortValue);
- virtual const std::string& getSortableDisplayName() const;
- private:
- void handleChildrenChanged(GroupRosterItem* group);
- void handleDataChanged(RosterItem* item);
- bool sortDisplayed();
- std::string name_;
- bool expanded_;
- std::vector<RosterItem*> children_;
- std::vector<RosterItem*> displayedChildren_;
- bool sortByStatus_;
- bool manualSort_;
- std::string manualSortValue_;
+ public:
+ GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus);
+ virtual ~GroupRosterItem();
+ const std::vector<RosterItem*>& getChildren() const;
+ const std::vector<RosterItem*>& getDisplayedChildren() const;
+ void addChild(RosterItem* item);
+ ContactRosterItem* removeChild(const JID& jid);
+ GroupRosterItem* removeGroupChild(const std::string& group);
+ void removeAll();
+ void setDisplayed(RosterItem* item, bool displayed);
+ boost::signal<void ()> onChildrenChanged;
+ static bool itemLessThanWithStatus(const RosterItem* left, const RosterItem* right);
+ static bool itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right);
+ void setExpanded(bool expanded);
+ bool isExpanded() const;
+ boost::signal<void (bool)> onExpandedChanged;
+ void setManualSort(const std::string& manualSortValue);
+ virtual const std::string& getSortableDisplayName() const;
+ private:
+ void handleChildrenChanged(GroupRosterItem* group);
+ void handleDataChanged(RosterItem* item);
+ bool sortDisplayed();
+ std::string name_;
+ bool expanded_;
+ std::vector<RosterItem*> children_;
+ std::vector<RosterItem*> displayedChildren_;
+ bool sortByStatus_;
+ bool manualSort_;
+ std::string manualSortValue_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/AppearOffline.h b/Swift/Controllers/Roster/ItemOperations/AppearOffline.h
index e59e01b..c57974b 100644
--- a/Swift/Controllers/Roster/ItemOperations/AppearOffline.h
+++ b/Swift/Controllers/Roster/ItemOperations/AppearOffline.h
@@ -14,16 +14,16 @@ namespace Swift {
class RosterItem;
class AppearOffline : public RosterItemOperation {
- public:
- AppearOffline() {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- contact->clearPresence();
- }
- }
+ public:
+ AppearOffline() {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ contact->clearPresence();
+ }
+ }
};
diff --git a/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h b/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h
index 833c863..76227c0 100644
--- a/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h
+++ b/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h
@@ -11,20 +11,20 @@
namespace Swift {
class RosterItemOperation {
- public:
- RosterItemOperation(bool requiresLookup = false, const JID& lookupJID = JID()) : requiresLookup_(requiresLookup), lookupJID_(lookupJID) {}
- virtual ~RosterItemOperation() {}
- bool requiresLookup() const {return requiresLookup_;}
- const JID& lookupJID() const {return lookupJID_;}
- /**
- * This is called when iterating over possible subjects, so must check it's
- * applying to the right items - even if requiresLookup() is true an item
- * with the same bare JID but different full JID may be passed.
- */
- virtual void operator() (RosterItem*) const = 0;
- private:
- bool requiresLookup_;
- JID lookupJID_;
+ public:
+ RosterItemOperation(bool requiresLookup = false, const JID& lookupJID = JID()) : requiresLookup_(requiresLookup), lookupJID_(lookupJID) {}
+ virtual ~RosterItemOperation() {}
+ bool requiresLookup() const {return requiresLookup_;}
+ const JID& lookupJID() const {return lookupJID_;}
+ /**
+ * This is called when iterating over possible subjects, so must check it's
+ * applying to the right items - even if requiresLookup() is true an item
+ * with the same bare JID but different full JID may be passed.
+ */
+ virtual void operator() (RosterItem*) const = 0;
+ private:
+ bool requiresLookup_;
+ JID lookupJID_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h b/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h
index b19b95a..29f9722 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h
@@ -22,21 +22,21 @@ namespace Swift {
class RosterItem;
class SetAvailableFeatures : public RosterItemOperation {
- public:
- SetAvailableFeatures(const JID& jid, const std::set<ContactRosterItem::Feature>& availableFeatures, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), availableFeatures_(availableFeatures), compareType_(compareType) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(jid_, compareType_)) {
- contact->setSupportedFeatures(availableFeatures_);
- }
- }
-
- private:
- JID jid_;
- std::set<ContactRosterItem::Feature> availableFeatures_;
- JID::CompareType compareType_;
+ public:
+ SetAvailableFeatures(const JID& jid, const std::set<ContactRosterItem::Feature>& availableFeatures, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), availableFeatures_(availableFeatures), compareType_(compareType) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(jid_, compareType_)) {
+ contact->setSupportedFeatures(availableFeatures_);
+ }
+ }
+
+ private:
+ JID jid_;
+ std::set<ContactRosterItem::Feature> availableFeatures_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetAvatar.h b/Swift/Controllers/Roster/ItemOperations/SetAvatar.h
index 211321e..d47c921 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetAvatar.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetAvatar.h
@@ -19,21 +19,21 @@ namespace Swift {
class RosterItem;
class SetAvatar : public RosterItemOperation {
- public:
- SetAvatar(const JID& jid, const boost::filesystem::path& path, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), path_(path), compareType_(compareType) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(jid_, compareType_)) {
- contact->setAvatarPath(path_);
- }
- }
-
- private:
- JID jid_;
- boost::filesystem::path path_;
- JID::CompareType compareType_;
+ public:
+ SetAvatar(const JID& jid, const boost::filesystem::path& path, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), path_(path), compareType_(compareType) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(jid_, compareType_)) {
+ contact->setAvatarPath(path_);
+ }
+ }
+
+ private:
+ JID jid_;
+ boost::filesystem::path path_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h b/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h
index 098eeb5..818d9b4 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h
@@ -22,30 +22,30 @@ namespace Swift {
class RosterItem;
class SetBlockingState : public RosterItemOperation {
- public:
- SetBlockingState(const JID& jid, ContactRosterItem::BlockState state, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(!jid.getNode().empty(), jid), jid_(jid), state_(state), compareType_(compareType) {
- if (state_ == ContactRosterItem::IsBlocked && jid.getNode().empty()) {
- state_ = ContactRosterItem::IsDomainBlocked;
- }
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (jid_.getNode().empty()) {
- if (contact && contact->getJID().getDomain() == jid_.getDomain()) {
- contact->setBlockState(state_);
- }
- } else {
- if (contact && contact->getJID().equals(jid_, compareType_)) {
- contact->setBlockState(state_);
- }
- }
- }
-
- private:
- JID jid_;
- ContactRosterItem::BlockState state_;
- JID::CompareType compareType_;
+ public:
+ SetBlockingState(const JID& jid, ContactRosterItem::BlockState state, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(!jid.getNode().empty(), jid), jid_(jid), state_(state), compareType_(compareType) {
+ if (state_ == ContactRosterItem::IsBlocked && jid.getNode().empty()) {
+ state_ = ContactRosterItem::IsDomainBlocked;
+ }
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (jid_.getNode().empty()) {
+ if (contact && contact->getJID().getDomain() == jid_.getDomain()) {
+ contact->setBlockState(state_);
+ }
+ } else {
+ if (contact && contact->getJID().equals(jid_, compareType_)) {
+ contact->setBlockState(state_);
+ }
+ }
+ }
+
+ private:
+ JID jid_;
+ ContactRosterItem::BlockState state_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetMUC.h b/Swift/Controllers/Roster/ItemOperations/SetMUC.h
index 8a4a0c6..7640c24 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetMUC.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetMUC.h
@@ -16,23 +16,23 @@ namespace Swift {
class RosterItem;
class SetMUC : public RosterItemOperation {
- public:
- SetMUC(const JID& jid, const MUCOccupant::Role& role, const MUCOccupant::Affiliation& affiliation)
- : RosterItemOperation(true, jid), jid_(jid), mucRole_(role), mucAffiliation_(affiliation) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(jid_, JID::WithResource)) {
- contact->setMUCRole(mucRole_);
- contact->setMUCAffiliation(mucAffiliation_);
- }
- }
-
- private:
- JID jid_;
- MUCOccupant::Role mucRole_;
- MUCOccupant::Affiliation mucAffiliation_;
+ public:
+ SetMUC(const JID& jid, const MUCOccupant::Role& role, const MUCOccupant::Affiliation& affiliation)
+ : RosterItemOperation(true, jid), jid_(jid), mucRole_(role), mucAffiliation_(affiliation) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(jid_, JID::WithResource)) {
+ contact->setMUCRole(mucRole_);
+ contact->setMUCAffiliation(mucAffiliation_);
+ }
+ }
+
+ private:
+ JID jid_;
+ MUCOccupant::Role mucRole_;
+ MUCOccupant::Affiliation mucAffiliation_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetName.h b/Swift/Controllers/Roster/ItemOperations/SetName.h
index 9f8a0b9..fa0694d 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetName.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetName.h
@@ -16,21 +16,21 @@ namespace Swift {
class RosterItem;
class SetName : public RosterItemOperation {
- public:
- SetName(const std::string& name, const JID& jid, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), name_(name), jid_(jid), compareType_(compareType) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(jid_, compareType_)) {
- contact->setDisplayName(name_);
- }
- }
-
- private:
- std::string name_;
- JID jid_;
- JID::CompareType compareType_;
+ public:
+ SetName(const std::string& name, const JID& jid, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), name_(name), jid_(jid), compareType_(compareType) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(jid_, compareType_)) {
+ contact->setDisplayName(name_);
+ }
+ }
+
+ private:
+ std::string name_;
+ JID jid_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetPresence.h b/Swift/Controllers/Roster/ItemOperations/SetPresence.h
index 2b5bbbe..fc39e5c 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetPresence.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetPresence.h
@@ -17,20 +17,20 @@ namespace Swift {
class RosterItem;
class SetPresence : public RosterItemOperation {
- public:
- SetPresence(Presence::ref presence, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, compareType == JID::WithoutResource ? presence->getFrom().toBare() : presence->getFrom()), presence_(presence), compareType_(compareType) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(presence_->getFrom(), compareType_)) {
- contact->applyPresence(presence_);
- }
- }
-
- private:
- Presence::ref presence_;
- JID::CompareType compareType_;
+ public:
+ SetPresence(Presence::ref presence, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, compareType == JID::WithoutResource ? presence->getFrom().toBare() : presence->getFrom()), presence_(presence), compareType_(compareType) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(presence_->getFrom(), compareType_)) {
+ contact->applyPresence(presence_);
+ }
+ }
+
+ private:
+ Presence::ref presence_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/ItemOperations/SetVCard.h b/Swift/Controllers/Roster/ItemOperations/SetVCard.h
index e1744b9..278ae56 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetVCard.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetVCard.h
@@ -23,21 +23,21 @@ namespace Swift {
class RosterItem;
class SetVCard : public RosterItemOperation {
- public:
- SetVCard(const JID& jid, VCard::ref vcard, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), vcard_(vcard), compareType_(compareType) {
- }
-
- virtual void operator() (RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && contact->getJID().equals(jid_, compareType_)) {
- contact->setVCard(vcard_);
- }
- }
-
- private:
- JID jid_;
- VCard::ref vcard_;
- JID::CompareType compareType_;
+ public:
+ SetVCard(const JID& jid, VCard::ref vcard, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), vcard_(vcard), compareType_(compareType) {
+ }
+
+ virtual void operator() (RosterItem* item) const {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && contact->getJID().equals(jid_, compareType_)) {
+ contact->setVCard(vcard_);
+ }
+ }
+
+ private:
+ JID jid_;
+ VCard::ref vcard_;
+ JID::CompareType compareType_;
};
}
diff --git a/Swift/Controllers/Roster/LeastCommonSubsequence.h b/Swift/Controllers/Roster/LeastCommonSubsequence.h
index e7b9370..8daa20c 100644
--- a/Swift/Controllers/Roster/LeastCommonSubsequence.h
+++ b/Swift/Controllers/Roster/LeastCommonSubsequence.h
@@ -11,98 +11,98 @@
#include <boost/numeric/conversion/cast.hpp>
namespace Swift {
- using std::equal_to;
+ using std::equal_to;
- namespace Detail {
- template<typename XIt, typename YIt, typename Length, typename Predicate>
- void computeLeastCommonSubsequenceMatrix(XIt xBegin, XIt xEnd, YIt yBegin, YIt yEnd, std::vector<Length>& result) {
- size_t width = static_cast<size_t>(std::distance(xBegin, xEnd) + 1);
- size_t height = static_cast<size_t>(std::distance(yBegin, yEnd) + 1);
- result.resize(width * height);
+ namespace Detail {
+ template<typename XIt, typename YIt, typename Length, typename Predicate>
+ void computeLeastCommonSubsequenceMatrix(XIt xBegin, XIt xEnd, YIt yBegin, YIt yEnd, std::vector<Length>& result) {
+ size_t width = static_cast<size_t>(std::distance(xBegin, xEnd) + 1);
+ size_t height = static_cast<size_t>(std::distance(yBegin, yEnd) + 1);
+ result.resize(width * height);
- // Initialize first row & column
- for (size_t i = 0; i < width; ++i) {
- result[i] = 0;
- }
- for (size_t j = 0; j < height; ++j) {
- result[j*width] = 0;
- }
+ // Initialize first row & column
+ for (size_t i = 0; i < width; ++i) {
+ result[i] = 0;
+ }
+ for (size_t j = 0; j < height; ++j) {
+ result[j*width] = 0;
+ }
- // Compute the LCS lengths for subsets
- Predicate predicate;
- for (size_t i = 1; i < width; ++i) {
- for (size_t j = 1; j < height; ++j) {
- result[i + j*width] = predicate(*(xBegin + boost::numeric_cast<long long>(i)-1), *(yBegin + boost::numeric_cast<long long >(j)-1)) ? result[(i-1) + (j-1)*width] + 1 : std::max(result[i + (j-1)*width], result[i-1 + (j*width)]);
- }
- }
- }
- }
+ // Compute the LCS lengths for subsets
+ Predicate predicate;
+ for (size_t i = 1; i < width; ++i) {
+ for (size_t j = 1; j < height; ++j) {
+ result[i + j*width] = predicate(*(xBegin + boost::numeric_cast<long long>(i)-1), *(yBegin + boost::numeric_cast<long long >(j)-1)) ? result[(i-1) + (j-1)*width] + 1 : std::max(result[i + (j-1)*width], result[i-1 + (j*width)]);
+ }
+ }
+ }
+ }
- template<typename X, typename InsertRemovePredicate, typename UpdatePredicate>
- void computeIndexDiff(const std::vector<X>& x, const std::vector<X>& y, std::vector<size_t>& updates, std::vector<size_t>& postUpdates, std::vector<size_t>& removes, std::vector<size_t>& inserts) {
- InsertRemovePredicate insertRemovePredicate;
- UpdatePredicate updatePredicate;
+ template<typename X, typename InsertRemovePredicate, typename UpdatePredicate>
+ void computeIndexDiff(const std::vector<X>& x, const std::vector<X>& y, std::vector<size_t>& updates, std::vector<size_t>& postUpdates, std::vector<size_t>& removes, std::vector<size_t>& inserts) {
+ InsertRemovePredicate insertRemovePredicate;
+ UpdatePredicate updatePredicate;
- // Find & handle common prefix (Optimization to reduce LCS matrix size)
- typename std::vector<X>::const_iterator xBegin = x.begin();
- typename std::vector<X>::const_iterator yBegin = y.begin();
- while (xBegin < x.end() && yBegin < y.end() && insertRemovePredicate(*xBegin, *yBegin)) {
- if (updatePredicate(*xBegin, *yBegin)) {
- updates.push_back(static_cast<size_t>(std::distance(x.begin(), xBegin)));
- postUpdates.push_back(static_cast<size_t>(std::distance(y.begin(), yBegin)));
- }
- ++xBegin;
- ++yBegin;
- }
- size_t prefixLength = static_cast<size_t>(std::distance(x.begin(), xBegin));
+ // Find & handle common prefix (Optimization to reduce LCS matrix size)
+ typename std::vector<X>::const_iterator xBegin = x.begin();
+ typename std::vector<X>::const_iterator yBegin = y.begin();
+ while (xBegin < x.end() && yBegin < y.end() && insertRemovePredicate(*xBegin, *yBegin)) {
+ if (updatePredicate(*xBegin, *yBegin)) {
+ updates.push_back(static_cast<size_t>(std::distance(x.begin(), xBegin)));
+ postUpdates.push_back(static_cast<size_t>(std::distance(y.begin(), yBegin)));
+ }
+ ++xBegin;
+ ++yBegin;
+ }
+ size_t prefixLength = static_cast<size_t>(std::distance(x.begin(), xBegin));
- // Find & handle common suffix (Optimization to reduce LCS matrix size)
- typename std::vector<X>::const_reverse_iterator xEnd = x.rbegin();
- typename std::vector<X>::const_reverse_iterator yEnd = y.rbegin();
- while (xEnd.base() > xBegin && yEnd.base() > yBegin && insertRemovePredicate(*xEnd, *yEnd)) {
- if (updatePredicate(*xEnd, *yEnd)) {
- updates.push_back(static_cast<size_t>(std::distance(x.begin(), xEnd.base()) - 1));
- postUpdates.push_back(static_cast<size_t>(std::distance(y.begin(), yEnd.base()) - 1));
- }
- ++xEnd;
- ++yEnd;
- }
+ // Find & handle common suffix (Optimization to reduce LCS matrix size)
+ typename std::vector<X>::const_reverse_iterator xEnd = x.rbegin();
+ typename std::vector<X>::const_reverse_iterator yEnd = y.rbegin();
+ while (xEnd.base() > xBegin && yEnd.base() > yBegin && insertRemovePredicate(*xEnd, *yEnd)) {
+ if (updatePredicate(*xEnd, *yEnd)) {
+ updates.push_back(static_cast<size_t>(std::distance(x.begin(), xEnd.base()) - 1));
+ postUpdates.push_back(static_cast<size_t>(std::distance(y.begin(), yEnd.base()) - 1));
+ }
+ ++xEnd;
+ ++yEnd;
+ }
- // Compute lengths
- size_t xLength = static_cast<size_t>(std::distance(xBegin, xEnd.base()));
- size_t yLength = static_cast<size_t>(std::distance(yBegin, yEnd.base()));
+ // Compute lengths
+ size_t xLength = static_cast<size_t>(std::distance(xBegin, xEnd.base()));
+ size_t yLength = static_cast<size_t>(std::distance(yBegin, yEnd.base()));
- // Compute LCS matrix
- std::vector<unsigned int> lcs;
- Detail::computeLeastCommonSubsequenceMatrix<typename std::vector<X>::const_iterator, typename std::vector<X>::const_iterator, unsigned int, InsertRemovePredicate>(xBegin, xEnd.base(), yBegin, yEnd.base(), lcs);
+ // Compute LCS matrix
+ std::vector<unsigned int> lcs;
+ Detail::computeLeastCommonSubsequenceMatrix<typename std::vector<X>::const_iterator, typename std::vector<X>::const_iterator, unsigned int, InsertRemovePredicate>(xBegin, xEnd.base(), yBegin, yEnd.base(), lcs);
- // Process LCS matrix
- size_t i = xLength;
- size_t j = yLength;
- size_t width = xLength + 1;
- while (true) {
- if (i > 0 && j > 0 && insertRemovePredicate(x[prefixLength + i-1], y[prefixLength + j-1])) {
- // x[i-1] same
- if (updatePredicate(x[prefixLength + i - 1], y[prefixLength + j - 1])) {
- updates.push_back(prefixLength + i-1);
- postUpdates.push_back(prefixLength + j-1);
- }
- i -= 1;
- j -= 1;
- }
- else if (j > 0 && (i == 0 || lcs[i + (j-1)*width] >= lcs[i-1 + j*width])) {
- // y[j-1] added
- inserts.push_back(prefixLength + j-1);
- j -= 1;
- }
- else if (i > 0 && (j == 0 || lcs[i + (j-1)*width] < lcs[i-1 + j*width])) {
- // x[i-1] removed
- removes.push_back(prefixLength + i-1);
- i -= 1;
- }
- else {
- break;
- }
- }
- }
+ // Process LCS matrix
+ size_t i = xLength;
+ size_t j = yLength;
+ size_t width = xLength + 1;
+ while (true) {
+ if (i > 0 && j > 0 && insertRemovePredicate(x[prefixLength + i-1], y[prefixLength + j-1])) {
+ // x[i-1] same
+ if (updatePredicate(x[prefixLength + i - 1], y[prefixLength + j - 1])) {
+ updates.push_back(prefixLength + i-1);
+ postUpdates.push_back(prefixLength + j-1);
+ }
+ i -= 1;
+ j -= 1;
+ }
+ else if (j > 0 && (i == 0 || lcs[i + (j-1)*width] >= lcs[i-1 + j*width])) {
+ // y[j-1] added
+ inserts.push_back(prefixLength + j-1);
+ j -= 1;
+ }
+ else if (i > 0 && (j == 0 || lcs[i + (j-1)*width] < lcs[i-1 + j*width])) {
+ // x[i-1] removed
+ removes.push_back(prefixLength + i-1);
+ i -= 1;
+ }
+ else {
+ break;
+ }
+ }
+ }
}
diff --git a/Swift/Controllers/Roster/OfflineRosterFilter.h b/Swift/Controllers/Roster/OfflineRosterFilter.h
index d25d073..033eecb 100644
--- a/Swift/Controllers/Roster/OfflineRosterFilter.h
+++ b/Swift/Controllers/Roster/OfflineRosterFilter.h
@@ -15,12 +15,12 @@
namespace Swift {
class OfflineRosterFilter : public RosterFilter {
- public:
- virtual ~OfflineRosterFilter() {}
- virtual bool operator() (RosterItem *item) const {
- ContactRosterItem *contactItem = dynamic_cast<ContactRosterItem*>(item);
- return contactItem && contactItem->getStatusShow() == StatusShow::None;
- }
+ public:
+ virtual ~OfflineRosterFilter() {}
+ virtual bool operator() (RosterItem *item) const {
+ ContactRosterItem *contactItem = dynamic_cast<ContactRosterItem*>(item);
+ return contactItem && contactItem->getStatusShow() == StatusShow::None;
+ }
};
}
diff --git a/Swift/Controllers/Roster/Roster.cpp b/Swift/Controllers/Roster/Roster.cpp
index 77d6b78..2e68fd4 100644
--- a/Swift/Controllers/Roster/Roster.cpp
+++ b/Swift/Controllers/Roster/Roster.cpp
@@ -23,252 +23,252 @@
namespace Swift {
Roster::Roster(bool sortByStatus, bool fullJIDMapping) : blockingSupported_(false) {
- sortByStatus_ = sortByStatus;
- fullJIDMapping_ = fullJIDMapping;
- root_ = new GroupRosterItem("Dummy-Root", NULL, sortByStatus_);
- root_->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, root_));
+ sortByStatus_ = sortByStatus;
+ fullJIDMapping_ = fullJIDMapping;
+ root_ = new GroupRosterItem("Dummy-Root", NULL, sortByStatus_);
+ root_->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, root_));
}
Roster::~Roster() {
- std::deque<RosterItem*> queue;
- queue.push_back(root_);
- while (!queue.empty()) {
- RosterItem* item = *queue.begin();
- queue.pop_front();
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- if (group) {
- queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
- }
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- contact->onVCardRequested.disconnect(boost::bind(boost::ref(onVCardUpdateRequested), contact->getJID()));
- }
- delete item;
- }
+ std::deque<RosterItem*> queue;
+ queue.push_back(root_);
+ while (!queue.empty()) {
+ RosterItem* item = *queue.begin();
+ queue.pop_front();
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ if (group) {
+ queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
+ }
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ contact->onVCardRequested.disconnect(boost::bind(boost::ref(onVCardUpdateRequested), contact->getJID()));
+ }
+ delete item;
+ }
}
GroupRosterItem* Roster::getRoot() const {
- return root_;
+ return root_;
}
std::set<JID> Roster::getJIDs() const {
- std::set<JID> jids;
-
- std::deque<RosterItem*> queue;
- queue.push_back(root_);
- while (!queue.empty()) {
- RosterItem* item = *queue.begin();
- queue.pop_front();
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- ContactRosterItem *contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- jids.insert(contact->getJID());
- jids.insert(contact->getDisplayJID());
- }
- else if (group) {
- queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
- }
- }
-
- return jids;
+ std::set<JID> jids;
+
+ std::deque<RosterItem*> queue;
+ queue.push_back(root_);
+ while (!queue.empty()) {
+ RosterItem* item = *queue.begin();
+ queue.pop_front();
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ ContactRosterItem *contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ jids.insert(contact->getJID());
+ jids.insert(contact->getDisplayJID());
+ }
+ else if (group) {
+ queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
+ }
+ }
+
+ return jids;
}
GroupRosterItem* Roster::getGroup(const std::string& groupName) {
- foreach (RosterItem *item, root_->getChildren()) {
- GroupRosterItem *group = dynamic_cast<GroupRosterItem*>(item);
- if (group && group->getDisplayName() == groupName) {
- return group;
- }
- }
- GroupRosterItem* group = new GroupRosterItem(groupName, root_, sortByStatus_);
- root_->addChild(group);
- group->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, group));
- group->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, group));
- return group;
+ foreach (RosterItem *item, root_->getChildren()) {
+ GroupRosterItem *group = dynamic_cast<GroupRosterItem*>(item);
+ if (group && group->getDisplayName() == groupName) {
+ return group;
+ }
+ }
+ GroupRosterItem* group = new GroupRosterItem(groupName, root_, sortByStatus_);
+ root_->addChild(group);
+ group->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, group));
+ group->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, group));
+ return group;
}
void Roster::setBlockingSupported(bool isSupported) {
- if (!blockingSupported_) {
- foreach(ItemMap::value_type i, itemMap_) {
- foreach(ContactRosterItem* item, i.second) {
- item->setBlockState(ContactRosterItem::IsUnblocked);
- }
- }
- }
- blockingSupported_ = isSupported;
+ if (!blockingSupported_) {
+ foreach(ItemMap::value_type i, itemMap_) {
+ foreach(ContactRosterItem* item, i.second) {
+ item->setBlockState(ContactRosterItem::IsUnblocked);
+ }
+ }
+ }
+ blockingSupported_ = isSupported;
}
void Roster::removeGroup(const std::string& group) {
- root_->removeGroupChild(group);
+ root_->removeGroupChild(group);
}
void Roster::handleDataChanged(RosterItem* item) {
- onDataChanged(item);
+ onDataChanged(item);
}
void Roster::handleChildrenChanged(GroupRosterItem* item) {
- onChildrenChanged(item);
+ onChildrenChanged(item);
}
void Roster::addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& groupName, const boost::filesystem::path& avatarPath) {
- GroupRosterItem* group(getGroup(groupName));
- ContactRosterItem *item = new ContactRosterItem(jid, displayJID, name, group);
- item->onVCardRequested.connect(boost::bind(boost::ref(onVCardUpdateRequested), jid));
- item->setAvatarPath(avatarPath);
- if (blockingSupported_) {
- item->setBlockState(ContactRosterItem::IsUnblocked);
- }
- group->addChild(item);
- ItemMap::iterator i = itemMap_.insert(std::make_pair(fullJIDMapping_ ? jid : jid.toBare(), std::vector<ContactRosterItem*>())).first;
- if (!i->second.empty()) {
- foreach (const std::string& existingGroup, i->second[0]->getGroups()) {
- item->addGroup(existingGroup);
- }
- }
- i->second.push_back(item);
- item->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, item));
- filterContact(item, group);
-
- foreach (ContactRosterItem* item, i->second) {
- item->addGroup(groupName);
- }
+ GroupRosterItem* group(getGroup(groupName));
+ ContactRosterItem *item = new ContactRosterItem(jid, displayJID, name, group);
+ item->onVCardRequested.connect(boost::bind(boost::ref(onVCardUpdateRequested), jid));
+ item->setAvatarPath(avatarPath);
+ if (blockingSupported_) {
+ item->setBlockState(ContactRosterItem::IsUnblocked);
+ }
+ group->addChild(item);
+ ItemMap::iterator i = itemMap_.insert(std::make_pair(fullJIDMapping_ ? jid : jid.toBare(), std::vector<ContactRosterItem*>())).first;
+ if (!i->second.empty()) {
+ foreach (const std::string& existingGroup, i->second[0]->getGroups()) {
+ item->addGroup(existingGroup);
+ }
+ }
+ i->second.push_back(item);
+ item->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, item));
+ filterContact(item, group);
+
+ foreach (ContactRosterItem* item, i->second) {
+ item->addGroup(groupName);
+ }
}
struct JIDEqualsTo {
- JIDEqualsTo(const JID& jid) : jid(jid) {}
- bool operator()(ContactRosterItem* i) const { return jid == i->getJID(); }
- JID jid;
+ JIDEqualsTo(const JID& jid) : jid(jid) {}
+ bool operator()(ContactRosterItem* i) const { return jid == i->getJID(); }
+ JID jid;
};
void Roster::removeAll() {
- root_->removeAll();
- itemMap_.clear();
- onChildrenChanged(root_);
- onDataChanged(root_);
+ root_->removeAll();
+ itemMap_.clear();
+ onChildrenChanged(root_);
+ onDataChanged(root_);
}
void Roster::removeContact(const JID& jid) {
- ItemMap::iterator item = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
- if (item != itemMap_.end()) {
- std::vector<ContactRosterItem*>& items = item->second;
- items.erase(std::remove_if(items.begin(), items.end(), JIDEqualsTo(jid)), items.end());
- if (items.empty()) {
- itemMap_.erase(item);
- }
- }
- //Causes the delete
- root_->removeChild(jid);
+ ItemMap::iterator item = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
+ if (item != itemMap_.end()) {
+ std::vector<ContactRosterItem*>& items = item->second;
+ items.erase(std::remove_if(items.begin(), items.end(), JIDEqualsTo(jid)), items.end());
+ if (items.empty()) {
+ itemMap_.erase(item);
+ }
+ }
+ //Causes the delete
+ root_->removeChild(jid);
}
void Roster::removeContactFromGroup(const JID& jid, const std::string& groupName) {
- std::vector<RosterItem*> children = root_->getChildren();
- std::vector<RosterItem*>::iterator it = children.begin();
- ItemMap::iterator itemIt = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
- while (it != children.end()) {
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
- if (group && group->getDisplayName() == groupName) {
- ContactRosterItem* deleted = group->removeChild(jid);
- if (itemIt != itemMap_.end()) {
- std::vector<ContactRosterItem*>& items = itemIt->second;
- items.erase(std::remove(items.begin(), items.end(), deleted), items.end());
- }
- }
- ++it;
- }
-
- if (itemIt != itemMap_.end()) {
- foreach (ContactRosterItem* item, itemIt->second) {
- item->removeGroup(groupName);
- }
- }
+ std::vector<RosterItem*> children = root_->getChildren();
+ std::vector<RosterItem*>::iterator it = children.begin();
+ ItemMap::iterator itemIt = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
+ while (it != children.end()) {
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(*it);
+ if (group && group->getDisplayName() == groupName) {
+ ContactRosterItem* deleted = group->removeChild(jid);
+ if (itemIt != itemMap_.end()) {
+ std::vector<ContactRosterItem*>& items = itemIt->second;
+ items.erase(std::remove(items.begin(), items.end(), deleted), items.end());
+ }
+ }
+ ++it;
+ }
+
+ if (itemIt != itemMap_.end()) {
+ foreach (ContactRosterItem* item, itemIt->second) {
+ item->removeGroup(groupName);
+ }
+ }
}
void Roster::applyOnItems(const RosterItemOperation& operation) {
- if (operation.requiresLookup()) {
- applyOnItem(operation, operation.lookupJID());
- } else {
- applyOnAllItems(operation);
- }
+ if (operation.requiresLookup()) {
+ applyOnItem(operation, operation.lookupJID());
+ } else {
+ applyOnAllItems(operation);
+ }
}
void Roster::applyOnItem(const RosterItemOperation& operation, const JID& jid) {
- ItemMap::iterator i = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
- if (i == itemMap_.end()) {
- return;
- }
- foreach (ContactRosterItem* item, i->second) {
- operation(item);
- filterContact(item, item->getParent());
- }
+ ItemMap::iterator i = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare());
+ if (i == itemMap_.end()) {
+ return;
+ }
+ foreach (ContactRosterItem* item, i->second) {
+ operation(item);
+ filterContact(item, item->getParent());
+ }
}
void Roster::applyOnAllItems(const RosterItemOperation& operation) {
- std::deque<RosterItem*> queue;
- queue.push_back(root_);
- while (!queue.empty()) {
- RosterItem* item = *queue.begin();
- queue.pop_front();
- operation(item);
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- if (group) {
- queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
- }
- }
- filterAll();
+ std::deque<RosterItem*> queue;
+ queue.push_back(root_);
+ while (!queue.empty()) {
+ RosterItem* item = *queue.begin();
+ queue.pop_front();
+ operation(item);
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ if (group) {
+ queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
+ }
+ }
+ filterAll();
}
void Roster::addFilter(RosterFilter* filter) {
- filters_.push_back(filter);
- filterAll();
- onFilterAdded(filter);
+ filters_.push_back(filter);
+ filterAll();
+ onFilterAdded(filter);
}
void Roster::removeFilter(RosterFilter* filter) {
- for (unsigned int i = 0; i < filters_.size(); i++) {
- if (filters_[i] == filter) {
- filters_.erase(filters_.begin() + i);
- break;
- }
- }
- filterAll();
- onFilterRemoved(filter);
+ for (unsigned int i = 0; i < filters_.size(); i++) {
+ if (filters_[i] == filter) {
+ filters_.erase(filters_.begin() + i);
+ break;
+ }
+ }
+ filterAll();
+ onFilterRemoved(filter);
}
void Roster::filterContact(ContactRosterItem* contact, GroupRosterItem* group) {
- size_t oldDisplayedSize = group->getDisplayedChildren().size();
- bool hide = true;
- foreach (RosterFilter *filter, filters_) {
- hide &= (*filter)(contact);
- }
- group->setDisplayed(contact, filters_.empty() || !hide);
- size_t newDisplayedSize = group->getDisplayedChildren().size();
- if (oldDisplayedSize == 0 && newDisplayedSize > 0) {
- onGroupAdded(group);
- }
+ size_t oldDisplayedSize = group->getDisplayedChildren().size();
+ bool hide = true;
+ foreach (RosterFilter *filter, filters_) {
+ hide &= (*filter)(contact);
+ }
+ group->setDisplayed(contact, filters_.empty() || !hide);
+ size_t newDisplayedSize = group->getDisplayedChildren().size();
+ if (oldDisplayedSize == 0 && newDisplayedSize > 0) {
+ onGroupAdded(group);
+ }
}
void Roster::filterGroup(GroupRosterItem* group) {
- foreach (RosterItem* child, group->getChildren()) {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(child);
- if (contact) {
- filterContact(contact, group);
- }
- }
+ foreach (RosterItem* child, group->getChildren()) {
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(child);
+ if (contact) {
+ filterContact(contact, group);
+ }
+ }
}
void Roster::filterAll() {
- std::deque<RosterItem*> queue;
- queue.push_back(root_);
- while (!queue.empty()) {
- RosterItem *item = *queue.begin();
- queue.pop_front();
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- if (group) {
- queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
- filterGroup(group);
- }
- }
+ std::deque<RosterItem*> queue;
+ queue.push_back(root_);
+ while (!queue.empty()) {
+ RosterItem *item = *queue.begin();
+ queue.pop_front();
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ if (group) {
+ queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end());
+ filterGroup(group);
+ }
+ }
}
}
diff --git a/Swift/Controllers/Roster/Roster.h b/Swift/Controllers/Roster/Roster.h
index 269ec4d..70e5bab 100644
--- a/Swift/Controllers/Roster/Roster.h
+++ b/Swift/Controllers/Roster/Roster.h
@@ -27,46 +27,46 @@ class GroupRosterItem;
class ContactRosterItem;
class Roster {
- public:
- Roster(bool sortByStatus = true, bool fullJIDMapping = false);
- ~Roster();
+ public:
+ Roster(bool sortByStatus = true, bool fullJIDMapping = false);
+ ~Roster();
- void addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& group, const boost::filesystem::path& avatarPath);
- void removeContact(const JID& jid);
- void removeContactFromGroup(const JID& jid, const std::string& group);
- void removeGroup(const std::string& group);
- void removeAll();
- void applyOnItems(const RosterItemOperation& operation);
- void applyOnAllItems(const RosterItemOperation& operation);
- void applyOnItem(const RosterItemOperation& operation, const JID& jid);
- void addFilter(RosterFilter* filter);
- void removeFilter(RosterFilter* filter);
- GroupRosterItem* getRoot() const;
- std::set<JID> getJIDs() const;
+ void addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& group, const boost::filesystem::path& avatarPath);
+ void removeContact(const JID& jid);
+ void removeContactFromGroup(const JID& jid, const std::string& group);
+ void removeGroup(const std::string& group);
+ void removeAll();
+ void applyOnItems(const RosterItemOperation& operation);
+ void applyOnAllItems(const RosterItemOperation& operation);
+ void applyOnItem(const RosterItemOperation& operation, const JID& jid);
+ void addFilter(RosterFilter* filter);
+ void removeFilter(RosterFilter* filter);
+ GroupRosterItem* getRoot() const;
+ std::set<JID> getJIDs() const;
- std::vector<RosterFilter*> getFilters() {return filters_;}
- boost::signal<void (GroupRosterItem*)> onChildrenChanged;
- boost::signal<void (GroupRosterItem*)> onGroupAdded;
- boost::signal<void (RosterItem*)> onDataChanged;
- boost::signal<void (JID&)> onVCardUpdateRequested;
- boost::signal<void (RosterFilter* filter)> onFilterAdded;
- boost::signal<void (RosterFilter* filter)> onFilterRemoved;
- GroupRosterItem* getGroup(const std::string& groupName);
- void setBlockingSupported(bool isSupported);
+ std::vector<RosterFilter*> getFilters() {return filters_;}
+ boost::signal<void (GroupRosterItem*)> onChildrenChanged;
+ boost::signal<void (GroupRosterItem*)> onGroupAdded;
+ boost::signal<void (RosterItem*)> onDataChanged;
+ boost::signal<void (JID&)> onVCardUpdateRequested;
+ boost::signal<void (RosterFilter* filter)> onFilterAdded;
+ boost::signal<void (RosterFilter* filter)> onFilterRemoved;
+ GroupRosterItem* getGroup(const std::string& groupName);
+ void setBlockingSupported(bool isSupported);
- private:
- void handleDataChanged(RosterItem* item);
- void handleChildrenChanged(GroupRosterItem* item);
- void filterGroup(GroupRosterItem* item);
- void filterContact(ContactRosterItem* contact, GroupRosterItem* group);
- void filterAll();
- GroupRosterItem* root_;
- std::vector<RosterFilter*> filters_;
- typedef std::map<JID, std::vector<ContactRosterItem*> > ItemMap;
- ItemMap itemMap_;
- bool fullJIDMapping_;
- bool sortByStatus_;
- bool blockingSupported_;
+ private:
+ void handleDataChanged(RosterItem* item);
+ void handleChildrenChanged(GroupRosterItem* item);
+ void filterGroup(GroupRosterItem* item);
+ void filterContact(ContactRosterItem* contact, GroupRosterItem* group);
+ void filterAll();
+ GroupRosterItem* root_;
+ std::vector<RosterFilter*> filters_;
+ typedef std::map<JID, std::vector<ContactRosterItem*> > ItemMap;
+ ItemMap itemMap_;
+ bool fullJIDMapping_;
+ bool sortByStatus_;
+ bool blockingSupported_;
};
}
diff --git a/Swift/Controllers/Roster/RosterController.cpp b/Swift/Controllers/Roster/RosterController.cpp
index 4fbdea4..e391f41 100644
--- a/Swift/Controllers/Roster/RosterController.cpp
+++ b/Swift/Controllers/Roster/RosterController.cpp
@@ -62,354 +62,354 @@ namespace Swift {
* The controller does not gain ownership of these parameters.
*/
RosterController::RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsManager, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager)
- : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), vcardManager_(vcardManager), avatarManager_(avatarManager), nickManager_(nickManager), nickResolver_(nickResolver), presenceOracle_(presenceOracle), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) {
- assert(fileTransferOverview);
- iqRouter_ = iqRouter;
- subscriptionManager_ = subscriptionManager;
- eventController_ = eventController;
- settings_ = settings;
- expandiness_ = new RosterGroupExpandinessPersister(roster_, settings);
- mainWindow_->setRosterModel(roster_);
- rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithoutResource);
-
- changeStatusConnection_ = mainWindow_->onChangeStatusRequest.connect(boost::bind(&RosterController::handleChangeStatusRequest, this, _1, _2));
- signOutConnection_ = mainWindow_->onSignOutRequest.connect(boost::bind(boost::ref(onSignOutRequest)));
- xmppRoster_->onJIDAdded.connect(boost::bind(&RosterController::handleOnJIDAdded, this, _1));
- xmppRoster_->onJIDUpdated.connect(boost::bind(&RosterController::handleOnJIDUpdated, this, _1, _2, _3));
- xmppRoster_->onJIDRemoved.connect(boost::bind(&RosterController::handleOnJIDRemoved, this, _1));
- xmppRoster_->onRosterCleared.connect(boost::bind(&RosterController::handleRosterCleared, this));
- subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&RosterController::handleSubscriptionRequest, this, _1, _2));
- uiEventConnection_ = uiEventStream->onUIEvent.connect(boost::bind(&RosterController::handleUIEvent, this, _1));
-
- vcardManager_->onOwnVCardChanged.connect(boost::bind(&RosterController::handleOwnVCardChanged, this, _1));
- avatarManager_->onAvatarChanged.connect(boost::bind(&RosterController::handleAvatarChanged, this, _1));
- presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handlePresenceChanged, this, _1));
- mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
-
- nickManager_->onOwnNickChanged.connect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
- mainWindow_->setMyJID(jid);
- mainWindow_->setMyNick(nickManager_->getOwnNick());
-
- entityCapsManager_->onCapsChanged.connect(boost::bind(&RosterController::handleOnCapsChanged, this, _1));
-
- settings_->onSettingChanged.connect(boost::bind(&RosterController::handleSettingChanged, this, _1));
-
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
-
- ownContact_ = boost::make_shared<ContactRosterItem>(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), static_cast<GroupRosterItem*>(0));
- ownContact_->setVCard(vcardManager_->getVCard(myJID_.toBare()));
- ownContact_->setAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
- mainWindow_->setMyContactRosterItem(ownContact_);
+ : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), vcardManager_(vcardManager), avatarManager_(avatarManager), nickManager_(nickManager), nickResolver_(nickResolver), presenceOracle_(presenceOracle), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) {
+ assert(fileTransferOverview);
+ iqRouter_ = iqRouter;
+ subscriptionManager_ = subscriptionManager;
+ eventController_ = eventController;
+ settings_ = settings;
+ expandiness_ = new RosterGroupExpandinessPersister(roster_, settings);
+ mainWindow_->setRosterModel(roster_);
+ rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithoutResource);
+
+ changeStatusConnection_ = mainWindow_->onChangeStatusRequest.connect(boost::bind(&RosterController::handleChangeStatusRequest, this, _1, _2));
+ signOutConnection_ = mainWindow_->onSignOutRequest.connect(boost::bind(boost::ref(onSignOutRequest)));
+ xmppRoster_->onJIDAdded.connect(boost::bind(&RosterController::handleOnJIDAdded, this, _1));
+ xmppRoster_->onJIDUpdated.connect(boost::bind(&RosterController::handleOnJIDUpdated, this, _1, _2, _3));
+ xmppRoster_->onJIDRemoved.connect(boost::bind(&RosterController::handleOnJIDRemoved, this, _1));
+ xmppRoster_->onRosterCleared.connect(boost::bind(&RosterController::handleRosterCleared, this));
+ subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&RosterController::handleSubscriptionRequest, this, _1, _2));
+ uiEventConnection_ = uiEventStream->onUIEvent.connect(boost::bind(&RosterController::handleUIEvent, this, _1));
+
+ vcardManager_->onOwnVCardChanged.connect(boost::bind(&RosterController::handleOwnVCardChanged, this, _1));
+ avatarManager_->onAvatarChanged.connect(boost::bind(&RosterController::handleAvatarChanged, this, _1));
+ presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handlePresenceChanged, this, _1));
+ mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
+
+ nickManager_->onOwnNickChanged.connect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
+ mainWindow_->setMyJID(jid);
+ mainWindow_->setMyNick(nickManager_->getOwnNick());
+
+ entityCapsManager_->onCapsChanged.connect(boost::bind(&RosterController::handleOnCapsChanged, this, _1));
+
+ settings_->onSettingChanged.connect(boost::bind(&RosterController::handleSettingChanged, this, _1));
+
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+
+ ownContact_ = boost::make_shared<ContactRosterItem>(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), static_cast<GroupRosterItem*>(0));
+ ownContact_->setVCard(vcardManager_->getVCard(myJID_.toBare()));
+ ownContact_->setAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare())));
+ mainWindow_->setMyContactRosterItem(ownContact_);
}
-RosterController::~RosterController() {
- settings_->onSettingChanged.disconnect(boost::bind(&RosterController::handleSettingChanged, this, _1));
- nickManager_->onOwnNickChanged.disconnect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
-
- delete offlineFilter_;
- delete expandiness_;
+RosterController::~RosterController() {
+ settings_->onSettingChanged.disconnect(boost::bind(&RosterController::handleSettingChanged, this, _1));
+ nickManager_->onOwnNickChanged.disconnect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1));
- mainWindow_->setRosterModel(NULL);
- if (mainWindow_->canDelete()) {
- delete mainWindow_;
- }
- delete rosterVCardProvider_;
- delete roster_;
+ delete offlineFilter_;
+ delete expandiness_;
+
+ mainWindow_->setRosterModel(NULL);
+ if (mainWindow_->canDelete()) {
+ delete mainWindow_;
+ }
+ delete rosterVCardProvider_;
+ delete roster_;
}
void RosterController::setEnabled(bool enabled) {
- if (!enabled) {
- roster_->applyOnItems(AppearOffline());
- }
+ if (!enabled) {
+ roster_->applyOnItems(AppearOffline());
+ }
}
void RosterController::handleShowOfflineToggled(bool state) {
- if (state) {
- roster_->removeFilter(offlineFilter_);
- } else {
- roster_->addFilter(offlineFilter_);
- }
+ if (state) {
+ roster_->removeFilter(offlineFilter_);
+ } else {
+ roster_->addFilter(offlineFilter_);
+ }
}
void RosterController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
- onChangeStatusRequest(show, statusText);
+ onChangeStatusRequest(show, statusText);
}
void RosterController::handleOnJIDAdded(const JID& jid) {
- std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
- std::string name = nickResolver_->jidToNick(jid);
- if (!groups.empty()) {
- foreach(const std::string& group, groups) {
- roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
- }
- }
- else {
- roster_->addContact(jid, jid, name, QT_TRANSLATE_NOOP("", "Contacts"), avatarManager_->getAvatarPath(jid));
- }
- applyAllPresenceTo(jid);
+ std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
+ std::string name = nickResolver_->jidToNick(jid);
+ if (!groups.empty()) {
+ foreach(const std::string& group, groups) {
+ roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
+ }
+ }
+ else {
+ roster_->addContact(jid, jid, name, QT_TRANSLATE_NOOP("", "Contacts"), avatarManager_->getAvatarPath(jid));
+ }
+ applyAllPresenceTo(jid);
}
void RosterController::applyAllPresenceTo(const JID& jid) {
- foreach (Presence::ref presence, presenceOracle_->getAllPresence(jid)) {
- roster_->applyOnItems(SetPresence(presence));
- }
+ foreach (Presence::ref presence, presenceOracle_->getAllPresence(jid)) {
+ roster_->applyOnItems(SetPresence(presence));
+ }
}
void RosterController::handleRosterCleared() {
- roster_->removeAll();
+ roster_->removeAll();
}
void RosterController::handleOnJIDRemoved(const JID& jid) {
- roster_->removeContact(jid);
+ roster_->removeContact(jid);
}
void RosterController::handleOnJIDUpdated(const JID& jid, const std::string& oldName, const std::vector<std::string>& passedOldGroups) {
- if (oldName != xmppRoster_->getNameForJID(jid)) {
- roster_->applyOnItems(SetName(nickResolver_->jidToNick(jid), jid));
- }
- std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
- std::vector<std::string> oldGroups = passedOldGroups;
- std::string name = nickResolver_->jidToNick(jid);
- std::string contactsGroup = QT_TRANSLATE_NOOP("", "Contacts");
- if (oldGroups.empty()) {
- oldGroups.push_back(contactsGroup);
- }
- if (groups.empty()) {
- groups.push_back(contactsGroup);
- }
- foreach(const std::string& group, groups) {
- if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) {
- roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
- }
- }
- foreach(const std::string& group, oldGroups) {
- if (std::find(groups.begin(), groups.end(), group) == groups.end()) {
- roster_->removeContactFromGroup(jid, group);
- if (roster_->getGroup(group)->getChildren().size() == 0) {
- roster_->removeGroup(group);
- }
- }
- }
- applyAllPresenceTo(jid);
+ if (oldName != xmppRoster_->getNameForJID(jid)) {
+ roster_->applyOnItems(SetName(nickResolver_->jidToNick(jid), jid));
+ }
+ std::vector<std::string> groups = xmppRoster_->getGroupsForJID(jid);
+ std::vector<std::string> oldGroups = passedOldGroups;
+ std::string name = nickResolver_->jidToNick(jid);
+ std::string contactsGroup = QT_TRANSLATE_NOOP("", "Contacts");
+ if (oldGroups.empty()) {
+ oldGroups.push_back(contactsGroup);
+ }
+ if (groups.empty()) {
+ groups.push_back(contactsGroup);
+ }
+ foreach(const std::string& group, groups) {
+ if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) {
+ roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
+ }
+ }
+ foreach(const std::string& group, oldGroups) {
+ if (std::find(groups.begin(), groups.end(), group) == groups.end()) {
+ roster_->removeContactFromGroup(jid, group);
+ if (roster_->getGroup(group)->getChildren().size() == 0) {
+ roster_->removeGroup(group);
+ }
+ }
+ }
+ applyAllPresenceTo(jid);
}
void RosterController::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
- }
+ if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+ }
}
void RosterController::handleBlockingStateChanged() {
- if (clientBlockListManager_->getBlockList()->getState() == BlockList::Available) {
- foreach(const JID& jid, clientBlockListManager_->getBlockList()->getItems()) {
- roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
- }
- }
+ if (clientBlockListManager_->getBlockList()->getState() == BlockList::Available) {
+ foreach(const JID& jid, clientBlockListManager_->getBlockList()->getItems()) {
+ roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
+ }
+ }
}
void RosterController::handleBlockingItemAdded(const JID& jid) {
- roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
+ roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
}
void RosterController::handleBlockingItemRemoved(const JID& jid) {
- roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsUnblocked));
+ roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsUnblocked));
}
void RosterController::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- if (boost::shared_ptr<AddContactUIEvent> addContactEvent = boost::dynamic_pointer_cast<AddContactUIEvent>(event)) {
- RosterItemPayload item;
- item.setName(addContactEvent->getName());
- item.setJID(addContactEvent->getJID());
- item.setGroups(std::vector<std::string>(addContactEvent->getGroups().begin(), addContactEvent->getGroups().end()));
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->addItem(item);
- SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
- request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
- request->send();
- subscriptionManager_->requestSubscription(addContactEvent->getJID());
- }
- else if (boost::shared_ptr<RemoveRosterItemUIEvent> removeEvent = boost::dynamic_pointer_cast<RemoveRosterItemUIEvent>(event)) {
- RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove);
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->addItem(item);
- SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
- request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
- request->send();
-
- }
- else if (boost::shared_ptr<RenameRosterItemUIEvent> renameEvent = boost::dynamic_pointer_cast<RenameRosterItemUIEvent>(event)) {
- JID contact(renameEvent->getJID());
- RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact));
- item.setGroups(xmppRoster_->getGroupsForJID(contact));
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->addItem(item);
- SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
- request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
- request->send();
- }
- else if (boost::shared_ptr<RenameGroupUIEvent> renameGroupEvent = boost::dynamic_pointer_cast<RenameGroupUIEvent>(event)) {
- std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
- std::string group = renameGroupEvent->getGroup();
- // FIXME: We should handle contacts groups specially to avoid clashes
- if (group == QT_TRANSLATE_NOOP("", "Contacts")) {
- group = "";
- }
- foreach(XMPPRosterItem& item, items) {
- std::vector<std::string> groups = item.getGroups();
- if ( (group.empty() && groups.empty()) || std::find(groups.begin(), groups.end(), group) != groups.end()) {
- groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end());
- if (std::find(groups.begin(), groups.end(), renameGroupEvent->getNewName()) == groups.end()) {
- groups.push_back(renameGroupEvent->getNewName());
- }
- item.setGroups(groups);
- updateItem(item);
- }
- }
- }
- else if (boost::shared_ptr<SendFileUIEvent> sendFileEvent = boost::dynamic_pointer_cast<SendFileUIEvent>(event)) {
- //TODO add send file dialog to ChatView of receipient jid
- ftOverview_->sendFile(sendFileEvent->getJID(), sendFileEvent->getFilename());
- }
+ if (boost::shared_ptr<AddContactUIEvent> addContactEvent = boost::dynamic_pointer_cast<AddContactUIEvent>(event)) {
+ RosterItemPayload item;
+ item.setName(addContactEvent->getName());
+ item.setJID(addContactEvent->getJID());
+ item.setGroups(std::vector<std::string>(addContactEvent->getGroups().begin(), addContactEvent->getGroups().end()));
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(item);
+ SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
+ request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
+ request->send();
+ subscriptionManager_->requestSubscription(addContactEvent->getJID());
+ }
+ else if (boost::shared_ptr<RemoveRosterItemUIEvent> removeEvent = boost::dynamic_pointer_cast<RemoveRosterItemUIEvent>(event)) {
+ RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove);
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(item);
+ SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
+ request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
+ request->send();
+
+ }
+ else if (boost::shared_ptr<RenameRosterItemUIEvent> renameEvent = boost::dynamic_pointer_cast<RenameRosterItemUIEvent>(event)) {
+ JID contact(renameEvent->getJID());
+ RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact));
+ item.setGroups(xmppRoster_->getGroupsForJID(contact));
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(item);
+ SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
+ request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster));
+ request->send();
+ }
+ else if (boost::shared_ptr<RenameGroupUIEvent> renameGroupEvent = boost::dynamic_pointer_cast<RenameGroupUIEvent>(event)) {
+ std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
+ std::string group = renameGroupEvent->getGroup();
+ // FIXME: We should handle contacts groups specially to avoid clashes
+ if (group == QT_TRANSLATE_NOOP("", "Contacts")) {
+ group = "";
+ }
+ foreach(XMPPRosterItem& item, items) {
+ std::vector<std::string> groups = item.getGroups();
+ if ( (group.empty() && groups.empty()) || std::find(groups.begin(), groups.end(), group) != groups.end()) {
+ groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end());
+ if (std::find(groups.begin(), groups.end(), renameGroupEvent->getNewName()) == groups.end()) {
+ groups.push_back(renameGroupEvent->getNewName());
+ }
+ item.setGroups(groups);
+ updateItem(item);
+ }
+ }
+ }
+ else if (boost::shared_ptr<SendFileUIEvent> sendFileEvent = boost::dynamic_pointer_cast<SendFileUIEvent>(event)) {
+ //TODO add send file dialog to ChatView of receipient jid
+ ftOverview_->sendFile(sendFileEvent->getJID(), sendFileEvent->getFilename());
+ }
}
void RosterController::setContactGroups(const JID& jid, const std::vector<std::string>& groups) {
- updateItem(XMPPRosterItem(jid, xmppRoster_->getNameForJID(jid), groups, xmppRoster_->getSubscriptionStateForJID(jid)));
+ updateItem(XMPPRosterItem(jid, xmppRoster_->getNameForJID(jid), groups, xmppRoster_->getSubscriptionStateForJID(jid)));
}
void RosterController::updateItem(const XMPPRosterItem& item) {
- RosterItemPayload itemPayload(item.getJID(), item.getName(), item.getSubscription());
- itemPayload.setGroups(item.getGroups());
+ RosterItemPayload itemPayload(item.getJID(), item.getName(), item.getSubscription());
+ itemPayload.setGroups(item.getGroups());
- RosterPayload::ref roster = boost::make_shared<RosterPayload>();
- roster->addItem(itemPayload);
+ RosterPayload::ref roster = boost::make_shared<RosterPayload>();
+ roster->addItem(itemPayload);
- SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
- request->onResponse.connect(boost::bind(&RosterController::handleRosterItemUpdated, this, _1, roster));
- request->send();
+ SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_);
+ request->onResponse.connect(boost::bind(&RosterController::handleRosterItemUpdated, this, _1, roster));
+ request->send();
}
void RosterController::initBlockingCommand() {
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
-
- blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&RosterController::handleBlockingStateChanged, this));
- blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&RosterController::handleBlockingItemAdded, this, _1));
- blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&RosterController::handleBlockingItemRemoved, this, _1));
- roster_->setBlockingSupported(true);
- if (blockList->getState() == BlockList::Available) {
- foreach(const JID& jid, blockList->getItems()) {
- roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
- }
- }
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
+
+ blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&RosterController::handleBlockingStateChanged, this));
+ blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&RosterController::handleBlockingItemAdded, this, _1));
+ blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&RosterController::handleBlockingItemRemoved, this, _1));
+ roster_->setBlockingSupported(true);
+ if (blockList->getState() == BlockList::Available) {
+ foreach(const JID& jid, blockList->getItems()) {
+ roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked));
+ }
+ }
}
void RosterController::handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload) {
- if (!!error) {
- handleRosterSetError(error, rosterPayload);
- }
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
- std::vector<RosterItemPayload> items = rosterPayload->getItems();
- if (blockList->getState() == BlockList::Available && items.size() > 0) {
- std::vector<JID> jids = blockList->getItems();
- if (std::find(jids.begin(), jids.end(), items[0].getJID()) != jids.end()) {
- roster_->applyOnItems(SetBlockingState(items[0].getJID(), ContactRosterItem::IsBlocked));
- }
- }
+ if (!!error) {
+ handleRosterSetError(error, rosterPayload);
+ }
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ std::vector<RosterItemPayload> items = rosterPayload->getItems();
+ if (blockList->getState() == BlockList::Available && items.size() > 0) {
+ std::vector<JID> jids = blockList->getItems();
+ if (std::find(jids.begin(), jids.end(), items[0].getJID()) != jids.end()) {
+ roster_->applyOnItems(SetBlockingState(items[0].getJID(), ContactRosterItem::IsBlocked));
+ }
+ }
}
void RosterController::handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload) {
- if (!error) {
- return;
- }
- std::string text = str(format(QT_TRANSLATE_NOOP("", "Server %1% rejected contact list change to item '%2%'")) % myJID_.getDomain() % rosterPayload->getItems()[0].getJID().toString());
- if (!error->getText().empty()) {
- text += ": " + error->getText();
- }
- boost::shared_ptr<ErrorEvent> errorEvent(new ErrorEvent(JID(myJID_.getDomain()), text));
- eventController_->handleIncomingEvent(errorEvent);
+ if (!error) {
+ return;
+ }
+ std::string text = str(format(QT_TRANSLATE_NOOP("", "Server %1% rejected contact list change to item '%2%'")) % myJID_.getDomain() % rosterPayload->getItems()[0].getJID().toString());
+ if (!error->getText().empty()) {
+ text += ": " + error->getText();
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent(new ErrorEvent(JID(myJID_.getDomain()), text));
+ eventController_->handleIncomingEvent(errorEvent);
}
void RosterController::handleIncomingPresence(Presence::ref newPresence) {
- if (newPresence->getType() == Presence::Error) {
- return;
- }
- Presence::ref accountPresence = presenceOracle_->getAccountPresence(newPresence->getFrom().toBare());
- if (!accountPresence) {
- accountPresence = Presence::create();
- accountPresence->setFrom(newPresence->getFrom());
- accountPresence->setType(Presence::Unavailable);
- }
- roster_->applyOnItems(SetPresence(accountPresence));
+ if (newPresence->getType() == Presence::Error) {
+ return;
+ }
+ Presence::ref accountPresence = presenceOracle_->getAccountPresence(newPresence->getFrom().toBare());
+ if (!accountPresence) {
+ accountPresence = Presence::create();
+ accountPresence->setFrom(newPresence->getFrom());
+ accountPresence->setType(Presence::Unavailable);
+ }
+ roster_->applyOnItems(SetPresence(accountPresence));
}
void RosterController::handleSubscriptionRequest(const JID& jid, const std::string& message) {
- if (xmppRoster_->containsJID(jid) && (xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::To || xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::Both)) {
- subscriptionManager_->confirmSubscription(jid);
- return;
- }
- SubscriptionRequestEvent* eventPointer = new SubscriptionRequestEvent(jid, message);
- eventPointer->onAccept.connect(boost::bind(&RosterController::handleSubscriptionRequestAccepted, this, eventPointer));
- eventPointer->onDecline.connect(boost::bind(&RosterController::handleSubscriptionRequestDeclined, this, eventPointer));
- boost::shared_ptr<StanzaEvent> event(eventPointer);
- eventController_->handleIncomingEvent(event);
+ if (xmppRoster_->containsJID(jid) && (xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::To || xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::Both)) {
+ subscriptionManager_->confirmSubscription(jid);
+ return;
+ }
+ SubscriptionRequestEvent* eventPointer = new SubscriptionRequestEvent(jid, message);
+ eventPointer->onAccept.connect(boost::bind(&RosterController::handleSubscriptionRequestAccepted, this, eventPointer));
+ eventPointer->onDecline.connect(boost::bind(&RosterController::handleSubscriptionRequestDeclined, this, eventPointer));
+ boost::shared_ptr<StanzaEvent> event(eventPointer);
+ eventController_->handleIncomingEvent(event);
}
void RosterController::handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event) {
- subscriptionManager_->confirmSubscription(event->getJID());
- if (!xmppRoster_->containsJID(event->getJID()) || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::None || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::From) {
- subscriptionManager_->requestSubscription(event->getJID());
- }
+ subscriptionManager_->confirmSubscription(event->getJID());
+ if (!xmppRoster_->containsJID(event->getJID()) || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::None || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::From) {
+ subscriptionManager_->requestSubscription(event->getJID());
+ }
}
void RosterController::handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event) {
- subscriptionManager_->cancelSubscription(event->getJID());
+ subscriptionManager_->cancelSubscription(event->getJID());
}
void RosterController::handleOwnVCardChanged(VCard::ref vcard) {
- ownContact_->setVCard(vcard);
- mainWindow_->setMyContactRosterItem(ownContact_);
+ ownContact_->setVCard(vcard);
+ mainWindow_->setMyContactRosterItem(ownContact_);
}
void RosterController::handleAvatarChanged(const JID& jid) {
- boost::filesystem::path path = avatarManager_->getAvatarPath(jid);
- roster_->applyOnItems(SetAvatar(jid, path));
- if (jid.equals(myJID_, JID::WithoutResource)) {
- mainWindow_->setMyAvatarPath(pathToString(path));
- ownContact_->setAvatarPath(pathToString(path));
- mainWindow_->setMyContactRosterItem(ownContact_);
- }
+ boost::filesystem::path path = avatarManager_->getAvatarPath(jid);
+ roster_->applyOnItems(SetAvatar(jid, path));
+ if (jid.equals(myJID_, JID::WithoutResource)) {
+ mainWindow_->setMyAvatarPath(pathToString(path));
+ ownContact_->setAvatarPath(pathToString(path));
+ mainWindow_->setMyContactRosterItem(ownContact_);
+ }
}
void RosterController::handlePresenceChanged(Presence::ref presence) {
- if (presence->getFrom().equals(myJID_, JID::WithResource)) {
- ownContact_->applyPresence(presence);
- mainWindow_->setMyContactRosterItem(ownContact_);
- }
- else {
- handleIncomingPresence(presence);
- }
+ if (presence->getFrom().equals(myJID_, JID::WithResource)) {
+ ownContact_->applyPresence(presence);
+ mainWindow_->setMyContactRosterItem(ownContact_);
+ }
+ else {
+ handleIncomingPresence(presence);
+ }
}
boost::optional<XMPPRosterItem> RosterController::getItem(const JID& jid) const {
- return xmppRoster_->getItem(jid);
+ return xmppRoster_->getItem(jid);
}
std::set<std::string> RosterController::getGroups() const {
- return xmppRoster_->getGroups();
+ return xmppRoster_->getGroups();
}
void RosterController::handleOnCapsChanged(const JID& jid) {
- DiscoInfo::ref info = entityCapsManager_->getCaps(jid);
- if (info) {
- std::set<ContactRosterItem::Feature> features;
- if (FileTransferManager::isSupportedBy(info)) {
- features.insert(ContactRosterItem::FileTransferFeature);
- }
- if (info->hasFeature(DiscoInfo::WhiteboardFeature)) {
- features.insert(ContactRosterItem::WhiteboardFeature);
- }
- roster_->applyOnItems(SetAvailableFeatures(jid, features));
- }
+ DiscoInfo::ref info = entityCapsManager_->getCaps(jid);
+ if (info) {
+ std::set<ContactRosterItem::Feature> features;
+ if (FileTransferManager::isSupportedBy(info)) {
+ features.insert(ContactRosterItem::FileTransferFeature);
+ }
+ if (info->hasFeature(DiscoInfo::WhiteboardFeature)) {
+ features.insert(ContactRosterItem::WhiteboardFeature);
+ }
+ roster_->applyOnItems(SetAvailableFeatures(jid, features));
+ }
}
}
diff --git a/Swift/Controllers/Roster/RosterController.h b/Swift/Controllers/Roster/RosterController.h
index 545abfc..f1660a8 100644
--- a/Swift/Controllers/Roster/RosterController.h
+++ b/Swift/Controllers/Roster/RosterController.h
@@ -23,104 +23,104 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class AvatarManager;
- class ClientBlockListManager;
- class EntityCapsProvider;
- class EventController;
- class FileTransferManager;
- class FileTransferOverview;
- class IQRouter;
- class MainWindow;
- class MainWindowFactory;
- class NickManager;
- class NickResolver;
- class OfflineRosterFilter;
- class PresenceOracle;
- class Roster;
- class RosterGroupExpandinessPersister;
- class RosterVCardProvider;
- class SettingsProvider;
- class SubscriptionManager;
- class SubscriptionRequestEvent;
- class UIEventStream;
- class VCardManager;
- class XMPPRoster;
- class XMPPRosterItem;
+ class AvatarManager;
+ class ClientBlockListManager;
+ class EntityCapsProvider;
+ class EventController;
+ class FileTransferManager;
+ class FileTransferOverview;
+ class IQRouter;
+ class MainWindow;
+ class MainWindowFactory;
+ class NickManager;
+ class NickResolver;
+ class OfflineRosterFilter;
+ class PresenceOracle;
+ class Roster;
+ class RosterGroupExpandinessPersister;
+ class RosterVCardProvider;
+ class SettingsProvider;
+ class SubscriptionManager;
+ class SubscriptionRequestEvent;
+ class UIEventStream;
+ class VCardManager;
+ class XMPPRoster;
+ class XMPPRosterItem;
- class RosterController {
- public:
- RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsProvider, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager);
- ~RosterController();
- void showRosterWindow();
- void setJID(const JID& jid) { myJID_ = jid; }
- MainWindow* getWindow() {return mainWindow_;}
- boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
- boost::signal<void ()> onSignOutRequest;
- void handleOwnVCardChanged(VCard::ref vcard);
- void handleAvatarChanged(const JID& jid);
- void handlePresenceChanged(Presence::ref presence);
- void setEnabled(bool enabled);
+ class RosterController {
+ public:
+ RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsProvider, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager);
+ ~RosterController();
+ void showRosterWindow();
+ void setJID(const JID& jid) { myJID_ = jid; }
+ MainWindow* getWindow() {return mainWindow_;}
+ boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
+ boost::signal<void ()> onSignOutRequest;
+ void handleOwnVCardChanged(VCard::ref vcard);
+ void handleAvatarChanged(const JID& jid);
+ void handlePresenceChanged(Presence::ref presence);
+ void setEnabled(bool enabled);
- boost::optional<XMPPRosterItem> getItem(const JID&) const;
- std::set<std::string> getGroups() const;
+ boost::optional<XMPPRosterItem> getItem(const JID&) const;
+ std::set<std::string> getGroups() const;
- void setContactGroups(const JID& jid, const std::vector<std::string>& groups);
- void updateItem(const XMPPRosterItem&);
+ void setContactGroups(const JID& jid, const std::vector<std::string>& groups);
+ void updateItem(const XMPPRosterItem&);
- void initBlockingCommand();
+ void initBlockingCommand();
- private:
- void handleOnJIDAdded(const JID &jid);
- void handleRosterCleared();
- void handleOnJIDRemoved(const JID &jid);
- void handleOnJIDUpdated(const JID &jid, const std::string& oldName, const std::vector<std::string>& oldGroups);
- void handleStartChatRequest(const JID& contact);
- void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText);
- void handleShowOfflineToggled(bool state);
- void handleIncomingPresence(boost::shared_ptr<Presence> newPresence);
- void handleSubscriptionRequest(const JID& jid, const std::string& message);
- void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event);
- void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event);
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload);
- void handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload);
- void applyAllPresenceTo(const JID& jid);
- void handleEditProfileRequest();
- void handleOnCapsChanged(const JID& jid);
- void handleSettingChanged(const std::string& settingPath);
+ private:
+ void handleOnJIDAdded(const JID &jid);
+ void handleRosterCleared();
+ void handleOnJIDRemoved(const JID &jid);
+ void handleOnJIDUpdated(const JID &jid, const std::string& oldName, const std::vector<std::string>& oldGroups);
+ void handleStartChatRequest(const JID& contact);
+ void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText);
+ void handleShowOfflineToggled(bool state);
+ void handleIncomingPresence(boost::shared_ptr<Presence> newPresence);
+ void handleSubscriptionRequest(const JID& jid, const std::string& message);
+ void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event);
+ void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event);
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload);
+ void handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr<RosterPayload> rosterPayload);
+ void applyAllPresenceTo(const JID& jid);
+ void handleEditProfileRequest();
+ void handleOnCapsChanged(const JID& jid);
+ void handleSettingChanged(const std::string& settingPath);
- void handleBlockingStateChanged();
- void handleBlockingItemAdded(const JID& jid);
- void handleBlockingItemRemoved(const JID& jid);
+ void handleBlockingStateChanged();
+ void handleBlockingItemAdded(const JID& jid);
+ void handleBlockingItemRemoved(const JID& jid);
- JID myJID_;
- XMPPRoster* xmppRoster_;
- MainWindowFactory* mainWindowFactory_;
- MainWindow* mainWindow_;
- Roster* roster_;
- OfflineRosterFilter* offlineFilter_;
- VCardManager* vcardManager_;
- AvatarManager* avatarManager_;
- NickManager* nickManager_;
- NickResolver* nickResolver_;
- PresenceOracle* presenceOracle_;
- SubscriptionManager* subscriptionManager_;
- EventController* eventController_;
- RosterGroupExpandinessPersister* expandiness_;
- IQRouter* iqRouter_;
- SettingsProvider* settings_;
- UIEventStream* uiEventStream_;
- EntityCapsProvider* entityCapsManager_;
- FileTransferOverview* ftOverview_;
- ClientBlockListManager* clientBlockListManager_;
- RosterVCardProvider* rosterVCardProvider_;
- boost::shared_ptr<ContactRosterItem> ownContact_;
-
- boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
- boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
- boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
- boost::bsignals::scoped_connection changeStatusConnection_;
- boost::bsignals::scoped_connection signOutConnection_;
- boost::bsignals::scoped_connection uiEventConnection_;
- };
+ JID myJID_;
+ XMPPRoster* xmppRoster_;
+ MainWindowFactory* mainWindowFactory_;
+ MainWindow* mainWindow_;
+ Roster* roster_;
+ OfflineRosterFilter* offlineFilter_;
+ VCardManager* vcardManager_;
+ AvatarManager* avatarManager_;
+ NickManager* nickManager_;
+ NickResolver* nickResolver_;
+ PresenceOracle* presenceOracle_;
+ SubscriptionManager* subscriptionManager_;
+ EventController* eventController_;
+ RosterGroupExpandinessPersister* expandiness_;
+ IQRouter* iqRouter_;
+ SettingsProvider* settings_;
+ UIEventStream* uiEventStream_;
+ EntityCapsProvider* entityCapsManager_;
+ FileTransferOverview* ftOverview_;
+ ClientBlockListManager* clientBlockListManager_;
+ RosterVCardProvider* rosterVCardProvider_;
+ boost::shared_ptr<ContactRosterItem> ownContact_;
+
+ boost::bsignals::scoped_connection blockingOnStateChangedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemAddedConnection_;
+ boost::bsignals::scoped_connection blockingOnItemRemovedConnection_;
+ boost::bsignals::scoped_connection changeStatusConnection_;
+ boost::bsignals::scoped_connection signOutConnection_;
+ boost::bsignals::scoped_connection uiEventConnection_;
+ };
}
diff --git a/Swift/Controllers/Roster/RosterFilter.h b/Swift/Controllers/Roster/RosterFilter.h
index e68ab57..6075c66 100644
--- a/Swift/Controllers/Roster/RosterFilter.h
+++ b/Swift/Controllers/Roster/RosterFilter.h
@@ -11,9 +11,9 @@
namespace Swift {
class RosterFilter {
- public:
- virtual ~RosterFilter() {}
- virtual bool operator() (RosterItem* item) const = 0;
+ public:
+ virtual ~RosterFilter() {}
+ virtual bool operator() (RosterItem* item) const = 0;
};
}
diff --git a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
index a39667c..af89b54 100644
--- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
+++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
@@ -19,45 +19,45 @@
namespace Swift {
RosterGroupExpandinessPersister::RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings) : roster_(roster), settings_(settings) {
- load();
- roster_->onGroupAdded.connect(boost::bind(&RosterGroupExpandinessPersister::handleGroupAdded, this, _1));
+ 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));
+ 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();
+ 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_) {
- if (!setting.empty()) {
- setting += "\n";
- }
- setting += group;
- }
- settings_->storeSetting(SettingConstants::EXPANDED_ROSTER_GROUPS, setting);
+ std::string setting;
+ foreach (const std::string& 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());
+ 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/RosterGroupExpandinessPersister.h b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h
index c3d5c12..4cc08a7 100644
--- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h
+++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h
@@ -12,16 +12,16 @@
#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
- class RosterGroupExpandinessPersister {
- public:
- RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings);
- private:
- void handleExpandedChanged(GroupRosterItem* group, bool expanded);
- void handleGroupAdded(GroupRosterItem* group);
- void load();
- void save();
- std::set<std::string> collapsed_;
- Roster* roster_;
- SettingsProvider* settings_;
- };
+ class RosterGroupExpandinessPersister {
+ public:
+ RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings);
+ private:
+ void handleExpandedChanged(GroupRosterItem* group, bool expanded);
+ void handleGroupAdded(GroupRosterItem* group);
+ void load();
+ void save();
+ std::set<std::string> collapsed_;
+ Roster* roster_;
+ SettingsProvider* settings_;
+ };
}
diff --git a/Swift/Controllers/Roster/RosterItem.cpp b/Swift/Controllers/Roster/RosterItem.cpp
index 51478c3..685613f 100644
--- a/Swift/Controllers/Roster/RosterItem.cpp
+++ b/Swift/Controllers/Roster/RosterItem.cpp
@@ -13,10 +13,10 @@
namespace Swift {
RosterItem::RosterItem(const std::string& name, GroupRosterItem* parent) : name_(name), sortableDisplayName_(boost::to_lower_copy(name_)), parent_(parent) {
- /* The following would be good, but because of C++'s inheritance not working in constructors, it's not going to work. */
- //if (parent) {
- // parent_->addChild(this);
- //}
+ /* The following would be good, but because of C++'s inheritance not working in constructors, it's not going to work. */
+ //if (parent) {
+ // parent_->addChild(this);
+ //}
}
RosterItem::~RosterItem() {
@@ -24,21 +24,21 @@ RosterItem::~RosterItem() {
}
GroupRosterItem* RosterItem::getParent() const {
- return parent_;
+ return parent_;
}
void RosterItem::setDisplayName(const std::string& name) {
- name_ = name;
- sortableDisplayName_ = boost::to_lower_copy(name_);
- onDataChanged();
+ name_ = name;
+ sortableDisplayName_ = boost::to_lower_copy(name_);
+ onDataChanged();
}
const std::string& RosterItem::getDisplayName() const {
- return name_;
+ return name_;
}
const std::string& RosterItem::getSortableDisplayName() const {
- return sortableDisplayName_;
+ return sortableDisplayName_;
}
diff --git a/Swift/Controllers/Roster/RosterItem.h b/Swift/Controllers/Roster/RosterItem.h
index 736c6af..e7a3e20 100644
--- a/Swift/Controllers/Roster/RosterItem.h
+++ b/Swift/Controllers/Roster/RosterItem.h
@@ -15,18 +15,18 @@
namespace Swift {
class GroupRosterItem;
class RosterItem {
- public:
- RosterItem(const std::string& name, GroupRosterItem* parent);
- virtual ~RosterItem();
- boost::signal<void ()> onDataChanged;
- GroupRosterItem* getParent() const;
- void setDisplayName(const std::string& name);
- const std::string& getDisplayName() const;
- virtual const std::string& getSortableDisplayName() const;
- private:
- std::string name_;
- std::string sortableDisplayName_;
- GroupRosterItem* parent_;
+ public:
+ RosterItem(const std::string& name, GroupRosterItem* parent);
+ virtual ~RosterItem();
+ boost::signal<void ()> onDataChanged;
+ GroupRosterItem* getParent() const;
+ void setDisplayName(const std::string& name);
+ const std::string& getDisplayName() const;
+ virtual const std::string& getSortableDisplayName() const;
+ private:
+ std::string name_;
+ std::string sortableDisplayName_;
+ GroupRosterItem* parent_;
};
}
diff --git a/Swift/Controllers/Roster/RosterVCardProvider.cpp b/Swift/Controllers/Roster/RosterVCardProvider.cpp
index d00d318..2aa82a9 100644
--- a/Swift/Controllers/Roster/RosterVCardProvider.cpp
+++ b/Swift/Controllers/Roster/RosterVCardProvider.cpp
@@ -20,22 +20,22 @@
namespace Swift {
RosterVCardProvider::RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType) : roster_(roster), vcardManager_(vcardManager), compareType_(compareType) {
- vcardUpdateRequestedConnection = roster_->onVCardUpdateRequested.connect(boost::bind(&RosterVCardProvider::handleVCardUpdateRequested, this, _1));
- vcardChangedConnection = vcardManager_->onVCardChanged.connect(boost::bind(&RosterVCardProvider::handleVCardChanged, this, _1, _2));
+ vcardUpdateRequestedConnection = roster_->onVCardUpdateRequested.connect(boost::bind(&RosterVCardProvider::handleVCardUpdateRequested, this, _1));
+ vcardChangedConnection = vcardManager_->onVCardChanged.connect(boost::bind(&RosterVCardProvider::handleVCardChanged, this, _1, _2));
}
RosterVCardProvider::~RosterVCardProvider() {
}
void RosterVCardProvider::handleVCardUpdateRequested(const JID& jid) {
- VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid);
- if (vcard) {
- handleVCardChanged(jid, vcard);
- }
+ VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid);
+ if (vcard) {
+ handleVCardChanged(jid, vcard);
+ }
}
void RosterVCardProvider::handleVCardChanged(const JID& jid, VCard::ref vcard) {
- roster_->applyOnItem(SetVCard(jid, vcard, compareType_), jid);
+ roster_->applyOnItem(SetVCard(jid, vcard, compareType_), jid);
}
diff --git a/Swift/Controllers/Roster/RosterVCardProvider.h b/Swift/Controllers/Roster/RosterVCardProvider.h
index da41298..a697dae 100644
--- a/Swift/Controllers/Roster/RosterVCardProvider.h
+++ b/Swift/Controllers/Roster/RosterVCardProvider.h
@@ -18,20 +18,20 @@ class Roster;
class VCardManager;
class RosterVCardProvider {
- public:
- RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType);
- ~RosterVCardProvider();
-
- private:
- void handleVCardUpdateRequested(const JID& jid);
- void handleVCardChanged(const JID& jid, VCard::ref vcard);
-
- private:
- Roster* roster_;
- VCardManager* vcardManager_;
- JID::CompareType compareType_;
- boost::bsignals::scoped_connection vcardUpdateRequestedConnection;
- boost::bsignals::scoped_connection vcardChangedConnection;
+ public:
+ RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType);
+ ~RosterVCardProvider();
+
+ private:
+ void handleVCardUpdateRequested(const JID& jid);
+ void handleVCardChanged(const JID& jid, VCard::ref vcard);
+
+ private:
+ Roster* roster_;
+ VCardManager* vcardManager_;
+ JID::CompareType compareType_;
+ boost::bsignals::scoped_connection vcardUpdateRequestedConnection;
+ boost::bsignals::scoped_connection vcardChangedConnection;
};
}
diff --git a/Swift/Controllers/Roster/TableRoster.cpp b/Swift/Controllers/Roster/TableRoster.cpp
index fde3304..f164a4d 100644
--- a/Swift/Controllers/Roster/TableRoster.cpp
+++ b/Swift/Controllers/Roster/TableRoster.cpp
@@ -21,167 +21,167 @@
#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 {
- return i1.status != i2.status || i1.description != i2.description || i1.name != i2.name || i1.avatarPath.empty() != i2.avatarPath.empty();
- }
- };
-
- struct CreateIndexForSection {
- CreateIndexForSection(size_t section) : section(section) {
- }
-
- TableRoster::Index operator()(size_t row) const {
- return TableRoster::Index(section, row);
- }
-
- size_t section;
- };
+ 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 {
+ return i1.status != i2.status || i1.description != i2.description || i1.name != i2.name || i1.avatarPath.empty() != i2.avatarPath.empty();
+ }
+ };
+
+ struct CreateIndexForSection {
+ CreateIndexForSection(size_t section) : section(section) {
+ }
+
+ TableRoster::Index operator()(size_t row) const {
+ return TableRoster::Index(section, row);
+ }
+
+ size_t section;
+ };
}
using namespace Swift;
TableRoster::TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay) : model(model), updatePending(false) {
- updateTimer = timerFactory->createTimer(updateDelay);
- updateTimer->onTick.connect(boost::bind(&TableRoster::handleUpdateTimerTick, this));
- if (model) {
- model->onChildrenChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this));
- model->onGroupAdded.connect(boost::bind(&TableRoster::scheduleUpdate, this));
- model->onDataChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this));
- }
+ updateTimer = timerFactory->createTimer(updateDelay);
+ updateTimer->onTick.connect(boost::bind(&TableRoster::handleUpdateTimerTick, this));
+ if (model) {
+ model->onChildrenChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this));
+ model->onGroupAdded.connect(boost::bind(&TableRoster::scheduleUpdate, this));
+ model->onDataChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this));
+ }
}
TableRoster::~TableRoster() {
- updateTimer->stop();
- updateTimer->onTick.disconnect(boost::bind(&TableRoster::handleUpdateTimerTick, this));
- 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));
- }
+ updateTimer->stop();
+ updateTimer->onTick.disconnect(boost::bind(&TableRoster::handleUpdateTimerTick, this));
+ 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();
+ return sections.size();
}
const std::string& TableRoster::getSectionTitle(size_t section) {
- return sections[section].name;
+ return sections[section].name;
}
size_t TableRoster::getNumberOfRowsInSection(size_t section) const {
- return sections[section].items.size();
+ return sections[section].items.size();
}
const TableRoster::Item& TableRoster::getItem(const Index& index) const {
- return sections[index.section].items[index.row];
+ 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()) {
- if (GroupRosterItem* groupItem = boost::polymorphic_downcast<GroupRosterItem*>(item)) {
- //std::cerr << "* " << groupItem->getDisplayName() << std::endl;
- Section section(groupItem->getDisplayName());
- foreach(RosterItem* 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]));
- end = update.updatedRows.size();
- update.updatedRows.resize(update.updatedRows.size() + itemUpdates.size());
- std::transform(itemUpdates.begin(), itemUpdates.end(), update.updatedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionPostUpdates[i]));
- }
-
- // Switch the old model with the new
- sections.swap(newSections);
-
- /*
- std::cerr << "-S: ";
- for (size_t i = 0; i < update.deletedSections.size(); ++i) {
- std::cerr << update.deletedSections[i] << " ";
- }
- std::cerr << std::endl;
- std::cerr << "+S: ";
- for (size_t i = 0; i < update.insertedSections.size(); ++i) {
- std::cerr << update.insertedSections[i] << " ";
- }
- std::cerr << std::endl;
- std::cerr << "-R: ";
- for (size_t i = 0; i < update.deletedRows.size(); ++i) {
- std::cerr << update.deletedRows[i].section << "," << update.deletedRows[i].row << " ";
- }
- std::cerr << std::endl;
- std::cerr << "*R: ";
- for (size_t i = 0; i < update.updatedRows.size(); ++i) {
- std::cerr << update.updatedRows[i].section << "," << update.updatedRows[i].row << " ";
- }
- std::cerr << std::endl;
- std::cerr << "+R: ";
- for (size_t i = 0; i < update.insertedRows.size(); ++i) {
- std::cerr << update.insertedRows[i].section << "," << update.insertedRows[i].row << " ";
- }
- std::cerr << std::endl;
- */
-
- // Emit the update
- onUpdate(update);
+ updateTimer->stop();
+ updatePending = false;
+
+ // Get a model for the new roster
+ std::vector<Section> newSections;
+ if (model) {
+ foreach(RosterItem* 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()) {
+ 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]));
+ end = update.updatedRows.size();
+ update.updatedRows.resize(update.updatedRows.size() + itemUpdates.size());
+ std::transform(itemUpdates.begin(), itemUpdates.end(), update.updatedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionPostUpdates[i]));
+ }
+
+ // Switch the old model with the new
+ sections.swap(newSections);
+
+ /*
+ std::cerr << "-S: ";
+ for (size_t i = 0; i < update.deletedSections.size(); ++i) {
+ std::cerr << update.deletedSections[i] << " ";
+ }
+ std::cerr << std::endl;
+ std::cerr << "+S: ";
+ for (size_t i = 0; i < update.insertedSections.size(); ++i) {
+ std::cerr << update.insertedSections[i] << " ";
+ }
+ std::cerr << std::endl;
+ std::cerr << "-R: ";
+ for (size_t i = 0; i < update.deletedRows.size(); ++i) {
+ std::cerr << update.deletedRows[i].section << "," << update.deletedRows[i].row << " ";
+ }
+ std::cerr << std::endl;
+ std::cerr << "*R: ";
+ for (size_t i = 0; i < update.updatedRows.size(); ++i) {
+ std::cerr << update.updatedRows[i].section << "," << update.updatedRows[i].row << " ";
+ }
+ std::cerr << std::endl;
+ std::cerr << "+R: ";
+ for (size_t i = 0; i < update.insertedRows.size(); ++i) {
+ std::cerr << update.insertedRows[i].section << "," << update.insertedRows[i].row << " ";
+ }
+ std::cerr << std::endl;
+ */
+
+ // Emit the update
+ onUpdate(update);
}
void TableRoster::scheduleUpdate() {
- if (!updatePending) {
- updatePending = true;
- updateTimer->start();
- }
+ if (!updatePending) {
+ updatePending = true;
+ updateTimer->start();
+ }
}
diff --git a/Swift/Controllers/Roster/TableRoster.h b/Swift/Controllers/Roster/TableRoster.h
index 87f9e75..3d336ef 100644
--- a/Swift/Controllers/Roster/TableRoster.h
+++ b/Swift/Controllers/Roster/TableRoster.h
@@ -16,70 +16,70 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class Roster;
- class TimerFactory;
- class Timer;
-
- class TableRoster {
- public:
- struct Item {
- Item(const std::string& name, const std::string& description, const JID& jid, StatusShow::Type status, const boost::filesystem::path& avatarPath) : name(name), description(description), jid(jid), status(status), avatarPath(avatarPath) {
- }
- std::string name;
- std::string description;
- JID jid;
- StatusShow::Type status;
- boost::filesystem::path avatarPath;
- };
-
- struct Index {
- Index(size_t section = 0, size_t row = 0) : section(section), row(row) {
- }
- size_t section;
- size_t row;
-
- bool operator==(const Index& o) const {
- return o.section == section && o.row == row;
- }
- };
-
- struct Update {
- std::vector<Index> updatedRows;
- std::vector<Index> insertedRows;
- std::vector<Index> deletedRows;
- std::vector<size_t> insertedSections;
- std::vector<size_t> deletedSections;
- };
-
- TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay);
- ~TableRoster();
-
- size_t getNumberOfSections() const;
- size_t getNumberOfRowsInSection(size_t section) const;
-
- const std::string& getSectionTitle(size_t);
-
- const Item& getItem(const Index&) const;
-
- boost::signal<void (const Update&)> onUpdate;
-
- private:
- void handleUpdateTimerTick();
- void scheduleUpdate();
-
- private:
- friend struct SectionNameEquals;
- struct Section {
- Section(const std::string& name) : name(name) {
- }
-
- std::string name;
- std::vector<Item> items;
- };
-
- Roster* model;
- std::vector<Section> sections;
- bool updatePending;
- boost::shared_ptr<Timer> updateTimer;
- };
+ class Roster;
+ class TimerFactory;
+ class Timer;
+
+ class TableRoster {
+ public:
+ struct Item {
+ Item(const std::string& name, const std::string& description, const JID& jid, StatusShow::Type status, const boost::filesystem::path& avatarPath) : name(name), description(description), jid(jid), status(status), avatarPath(avatarPath) {
+ }
+ std::string name;
+ std::string description;
+ JID jid;
+ StatusShow::Type status;
+ boost::filesystem::path avatarPath;
+ };
+
+ struct Index {
+ Index(size_t section = 0, size_t row = 0) : section(section), row(row) {
+ }
+ size_t section;
+ size_t row;
+
+ bool operator==(const Index& o) const {
+ return o.section == section && o.row == row;
+ }
+ };
+
+ struct Update {
+ std::vector<Index> updatedRows;
+ std::vector<Index> insertedRows;
+ std::vector<Index> deletedRows;
+ std::vector<size_t> insertedSections;
+ std::vector<size_t> deletedSections;
+ };
+
+ TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay);
+ ~TableRoster();
+
+ size_t getNumberOfSections() const;
+ size_t getNumberOfRowsInSection(size_t section) const;
+
+ const std::string& getSectionTitle(size_t);
+
+ const Item& getItem(const Index&) const;
+
+ boost::signal<void (const Update&)> onUpdate;
+
+ private:
+ void handleUpdateTimerTick();
+ void scheduleUpdate();
+
+ private:
+ friend struct SectionNameEquals;
+ struct Section {
+ Section(const std::string& name) : name(name) {
+ }
+
+ std::string name;
+ std::vector<Item> items;
+ };
+
+ Roster* model;
+ std::vector<Section> sections;
+ bool updatePending;
+ boost::shared_ptr<Timer> updateTimer;
+ };
}
diff --git a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
index 144de77..5844ebe 100644
--- a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
@@ -18,294 +18,294 @@
using namespace Swift;
struct IsBOrC {
- bool operator()(char c, char c2) const {
- CPPUNIT_ASSERT_EQUAL(c, c2);
- return c == 'b' || c == 'c';
- }
+ bool operator()(char c, char c2) const {
+ CPPUNIT_ASSERT_EQUAL(c, c2);
+ return c == 'b' || c == 'c';
+ }
};
struct IsXOrY {
- bool operator()(char c, char c2) const {
- CPPUNIT_ASSERT_EQUAL(c, c2);
- return c == 'x' || c == 'y';
- }
+ bool operator()(char c, char c2) const {
+ CPPUNIT_ASSERT_EQUAL(c, c2);
+ return c == 'x' || c == 'y';
+ }
};
struct IsArizonaOrNewJersey {
- bool operator()(const std::string& s, const std::string& s2) const {
- CPPUNIT_ASSERT_EQUAL(s, s2);
- return s == "Arizona" || s == "New Jersey";
- }
+ bool operator()(const std::string& s, const std::string& s2) const {
+ CPPUNIT_ASSERT_EQUAL(s, s2);
+ return s == "Arizona" || s == "New Jersey";
+ }
};
class LeastCommonSubsequenceTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LeastCommonSubsequenceTest);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_1);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_2);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence1Empty);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence2Empty);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_NoCommonSequence);
- CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_SameSequences);
- CPPUNIT_TEST(testComputeIndexDiff_1);
- CPPUNIT_TEST(testComputeIndexDiff_2);
- CPPUNIT_TEST(testComputeIndexDiff_Sequence1Empty);
- CPPUNIT_TEST(testComputeIndexDiff_Sequence2Empty);
- CPPUNIT_TEST(testComputeIndexDiff_BothSequencesEmpty);
- CPPUNIT_TEST(testComputeIndexDiff_NoCommonSequence);
- CPPUNIT_TEST(testComputeIndexDiff_SameSequences);
- CPPUNIT_TEST(testComputeIndexDiff_CommonPrefixAndSuffix);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testComputeLeastCommonSubsequenceMatrix_1() {
- std::vector<char> x = boost::assign::list_of('x')('m')('j')('y')('a')('u')('z');
- std::vector<char> y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u');
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)(0)(0)(0)(0)(0)(0)(0)
- (0)(0)(1)(1)(1)(1)(1)(1)
- (0)(0)(1)(1)(1)(1)(1)(2)
- (0)(0)(1)(2)(2)(2)(2)(2)
- (0)(0)(1)(2)(2)(3)(3)(3)
- (0)(0)(1)(2)(2)(3)(3)(3)
- (0)(1)(1)(2)(2)(3)(3)(3)
- (0)(1)(1)(2)(2)(3)(4)(4);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_2() {
- std::vector<char> x = boost::assign::list_of('x')('x')('x')('m')('j')('y')('a')('u')('z');
- std::vector<char> y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u');
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)(0)(0)(0)(0)(0)(0)(0)(0)(0)
- (0)(0)(0)(0)(1)(1)(1)(1)(1)(1)
- (0)(0)(0)(0)(1)(1)(1)(1)(1)(2)
- (0)(0)(0)(0)(1)(2)(2)(2)(2)(2)
- (0)(0)(0)(0)(1)(2)(2)(3)(3)(3)
- (0)(0)(0)(0)(1)(2)(2)(3)(3)(3)
- (0)(1)(1)(1)(1)(2)(2)(3)(3)(3)
- (0)(1)(1)(1)(1)(2)(2)(3)(4)(4);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_Sequence1Empty() {
- std::vector<char> x;
- std::vector<char> y = boost::assign::list_of('a')('b')('c');
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)
- (0)
- (0)
- (0);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_Sequence2Empty() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y;
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)(0)(0)(0);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty() {
- std::vector<char> x;
- std::vector<char> y;
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of(0);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_NoCommonSequence() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y = boost::assign::list_of('d')('e')('f')('g');
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)(0)(0)(0)
- (0)(0)(0)(0)
- (0)(0)(0)(0)
- (0)(0)(0)(0)
- (0)(0)(0)(0);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeLeastCommonSubsequenceMatrix_SameSequences() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y = boost::assign::list_of('a')('b')('c');
-
- std::vector<int> result;
- Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
-
- std::vector<int> expected = boost::assign::list_of
- (0)(0)(0)(0)
- (0)(1)(1)(1)
- (0)(1)(2)(2)
- (0)(1)(2)(3);
- CPPUNIT_ASSERT_EQUAL(expected, result);
- }
-
- void testComputeIndexDiff_1() {
- std::vector<std::string> x = boost::assign::list_of("Arizona")("California")("Delaware")("New Jersey")("Washington");
- std::vector<std::string> y = boost::assign::list_of("Alaska")("Arizona")("California")("Georgia")("New Jersey")("Virginia");
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<std::string, std::equal_to<std::string>, IsArizonaOrNewJersey >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedUpdates = boost::assign::list_of(3)(0);
- std::vector<size_t> expectedPostUpdates = boost::assign::list_of(4)(1);
- std::vector<size_t> expectedRemoves = boost::assign::list_of(4)(2);
- std::vector<size_t> expectedInserts = boost::assign::list_of(5)(3)(0);
- CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
- CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates);
- CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
- CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
- }
-
- void testComputeIndexDiff_2() {
- std::vector<char> x = boost::assign::list_of('x')('y');
- std::vector<char> y = boost::assign::list_of('x');
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedRemoves = boost::assign::list_of(1);
- CPPUNIT_ASSERT(updates.empty());
- CPPUNIT_ASSERT(postUpdates.empty());
- CPPUNIT_ASSERT(inserts.empty());
- CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
- }
-
- void testComputeIndexDiff_Sequence1Empty() {
- std::vector<char> x;
- std::vector<char> y = boost::assign::list_of('a')('b')('c');
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedInserts = boost::assign::list_of(2)(1)(0);
- CPPUNIT_ASSERT(updates.empty());
- CPPUNIT_ASSERT(postUpdates.empty());
- CPPUNIT_ASSERT(removes.empty());
- CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
- }
-
- void testComputeIndexDiff_Sequence2Empty() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y;
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedRemoves = boost::assign::list_of(2)(1)(0);
- CPPUNIT_ASSERT(updates.empty());
- CPPUNIT_ASSERT(postUpdates.empty());
- CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
- CPPUNIT_ASSERT(inserts.empty());
- }
-
- void testComputeIndexDiff_BothSequencesEmpty() {
- std::vector<char> x;
- std::vector<char> y;
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- CPPUNIT_ASSERT(updates.empty());
- CPPUNIT_ASSERT(postUpdates.empty());
- CPPUNIT_ASSERT(removes.empty());
- CPPUNIT_ASSERT(inserts.empty());
- }
-
- void testComputeIndexDiff_NoCommonSequence() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y = boost::assign::list_of('d')('e')('f')('g');
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedRemoves = boost::assign::list_of(2)(1)(0);
- std::vector<size_t> expectedInserts = boost::assign::list_of(3)(2)(1)(0);
- CPPUNIT_ASSERT(updates.empty());
- CPPUNIT_ASSERT(postUpdates.empty());
- CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
- CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
- }
-
- void testComputeIndexDiff_SameSequences() {
- std::vector<char> x = boost::assign::list_of('a')('b')('c');
- std::vector<char> y = boost::assign::list_of('a')('b')('c');
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedUpdates = boost::assign::list_of(1)(2);
- CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
- CPPUNIT_ASSERT_EQUAL(expectedUpdates, postUpdates);
- CPPUNIT_ASSERT(removes.empty());
- CPPUNIT_ASSERT(inserts.empty());
- }
-
- void testComputeIndexDiff_CommonPrefixAndSuffix() {
- std::vector<char> x = boost::assign::list_of('x')('x')('x')('x')('a')('b')('c')('d')('e')('y')('y')('y');
- std::vector<char> y = boost::assign::list_of('x')('x')('x')('x')('e')('a')('b')('f')('d')('g')('y')('y')('y');
-
- std::vector<size_t> updates;
- std::vector<size_t> postUpdates;
- std::vector<size_t> removes;
- std::vector<size_t> inserts;
- computeIndexDiff<char, std::equal_to<char>, IsXOrY >(x, y, updates, postUpdates, removes, inserts);
-
- std::vector<size_t> expectedUpdates = boost::assign::list_of(0)(1)(2)(3)(11)(10)(9);
- std::vector<size_t> expectedPostUpdates = boost::assign::list_of(0)(1)(2)(3)(12)(11)(10);
- std::vector<size_t> expectedRemoves = boost::assign::list_of(8)(6);
- std::vector<size_t> expectedInserts = boost::assign::list_of(9)(7)(4);
- CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
- CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates);
- CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
- CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
- }
+ CPPUNIT_TEST_SUITE(LeastCommonSubsequenceTest);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_1);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_2);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence1Empty);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence2Empty);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_NoCommonSequence);
+ CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_SameSequences);
+ CPPUNIT_TEST(testComputeIndexDiff_1);
+ CPPUNIT_TEST(testComputeIndexDiff_2);
+ CPPUNIT_TEST(testComputeIndexDiff_Sequence1Empty);
+ CPPUNIT_TEST(testComputeIndexDiff_Sequence2Empty);
+ CPPUNIT_TEST(testComputeIndexDiff_BothSequencesEmpty);
+ CPPUNIT_TEST(testComputeIndexDiff_NoCommonSequence);
+ CPPUNIT_TEST(testComputeIndexDiff_SameSequences);
+ CPPUNIT_TEST(testComputeIndexDiff_CommonPrefixAndSuffix);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testComputeLeastCommonSubsequenceMatrix_1() {
+ std::vector<char> x = boost::assign::list_of('x')('m')('j')('y')('a')('u')('z');
+ std::vector<char> y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u');
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)(0)(0)(0)(0)(0)(0)(0)
+ (0)(0)(1)(1)(1)(1)(1)(1)
+ (0)(0)(1)(1)(1)(1)(1)(2)
+ (0)(0)(1)(2)(2)(2)(2)(2)
+ (0)(0)(1)(2)(2)(3)(3)(3)
+ (0)(0)(1)(2)(2)(3)(3)(3)
+ (0)(1)(1)(2)(2)(3)(3)(3)
+ (0)(1)(1)(2)(2)(3)(4)(4);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_2() {
+ std::vector<char> x = boost::assign::list_of('x')('x')('x')('m')('j')('y')('a')('u')('z');
+ std::vector<char> y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u');
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)(0)(0)(0)(0)(0)(0)(0)(0)(0)
+ (0)(0)(0)(0)(1)(1)(1)(1)(1)(1)
+ (0)(0)(0)(0)(1)(1)(1)(1)(1)(2)
+ (0)(0)(0)(0)(1)(2)(2)(2)(2)(2)
+ (0)(0)(0)(0)(1)(2)(2)(3)(3)(3)
+ (0)(0)(0)(0)(1)(2)(2)(3)(3)(3)
+ (0)(1)(1)(1)(1)(2)(2)(3)(3)(3)
+ (0)(1)(1)(1)(1)(2)(2)(3)(4)(4);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_Sequence1Empty() {
+ std::vector<char> x;
+ std::vector<char> y = boost::assign::list_of('a')('b')('c');
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)
+ (0)
+ (0)
+ (0);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_Sequence2Empty() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y;
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)(0)(0)(0);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty() {
+ std::vector<char> x;
+ std::vector<char> y;
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of(0);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_NoCommonSequence() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y = boost::assign::list_of('d')('e')('f')('g');
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)(0)(0)(0)
+ (0)(0)(0)(0)
+ (0)(0)(0)(0)
+ (0)(0)(0)(0)
+ (0)(0)(0)(0);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeLeastCommonSubsequenceMatrix_SameSequences() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y = boost::assign::list_of('a')('b')('c');
+
+ std::vector<int> result;
+ Detail::computeLeastCommonSubsequenceMatrix<std::vector<char>::const_iterator, std::vector<char>::const_iterator, int, std::equal_to<char> >(x.begin(), x.end(), y.begin(), y.end(), result);
+
+ std::vector<int> expected = boost::assign::list_of
+ (0)(0)(0)(0)
+ (0)(1)(1)(1)
+ (0)(1)(2)(2)
+ (0)(1)(2)(3);
+ CPPUNIT_ASSERT_EQUAL(expected, result);
+ }
+
+ void testComputeIndexDiff_1() {
+ std::vector<std::string> x = boost::assign::list_of("Arizona")("California")("Delaware")("New Jersey")("Washington");
+ std::vector<std::string> y = boost::assign::list_of("Alaska")("Arizona")("California")("Georgia")("New Jersey")("Virginia");
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<std::string, std::equal_to<std::string>, IsArizonaOrNewJersey >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedUpdates = boost::assign::list_of(3)(0);
+ std::vector<size_t> expectedPostUpdates = boost::assign::list_of(4)(1);
+ std::vector<size_t> expectedRemoves = boost::assign::list_of(4)(2);
+ std::vector<size_t> expectedInserts = boost::assign::list_of(5)(3)(0);
+ CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
+ CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates);
+ CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
+ CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
+ }
+
+ void testComputeIndexDiff_2() {
+ std::vector<char> x = boost::assign::list_of('x')('y');
+ std::vector<char> y = boost::assign::list_of('x');
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedRemoves = boost::assign::list_of(1);
+ CPPUNIT_ASSERT(updates.empty());
+ CPPUNIT_ASSERT(postUpdates.empty());
+ CPPUNIT_ASSERT(inserts.empty());
+ CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
+ }
+
+ void testComputeIndexDiff_Sequence1Empty() {
+ std::vector<char> x;
+ std::vector<char> y = boost::assign::list_of('a')('b')('c');
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedInserts = boost::assign::list_of(2)(1)(0);
+ CPPUNIT_ASSERT(updates.empty());
+ CPPUNIT_ASSERT(postUpdates.empty());
+ CPPUNIT_ASSERT(removes.empty());
+ CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
+ }
+
+ void testComputeIndexDiff_Sequence2Empty() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y;
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedRemoves = boost::assign::list_of(2)(1)(0);
+ CPPUNIT_ASSERT(updates.empty());
+ CPPUNIT_ASSERT(postUpdates.empty());
+ CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
+ CPPUNIT_ASSERT(inserts.empty());
+ }
+
+ void testComputeIndexDiff_BothSequencesEmpty() {
+ std::vector<char> x;
+ std::vector<char> y;
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ CPPUNIT_ASSERT(updates.empty());
+ CPPUNIT_ASSERT(postUpdates.empty());
+ CPPUNIT_ASSERT(removes.empty());
+ CPPUNIT_ASSERT(inserts.empty());
+ }
+
+ void testComputeIndexDiff_NoCommonSequence() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y = boost::assign::list_of('d')('e')('f')('g');
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedRemoves = boost::assign::list_of(2)(1)(0);
+ std::vector<size_t> expectedInserts = boost::assign::list_of(3)(2)(1)(0);
+ CPPUNIT_ASSERT(updates.empty());
+ CPPUNIT_ASSERT(postUpdates.empty());
+ CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
+ CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
+ }
+
+ void testComputeIndexDiff_SameSequences() {
+ std::vector<char> x = boost::assign::list_of('a')('b')('c');
+ std::vector<char> y = boost::assign::list_of('a')('b')('c');
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsBOrC >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedUpdates = boost::assign::list_of(1)(2);
+ CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
+ CPPUNIT_ASSERT_EQUAL(expectedUpdates, postUpdates);
+ CPPUNIT_ASSERT(removes.empty());
+ CPPUNIT_ASSERT(inserts.empty());
+ }
+
+ void testComputeIndexDiff_CommonPrefixAndSuffix() {
+ std::vector<char> x = boost::assign::list_of('x')('x')('x')('x')('a')('b')('c')('d')('e')('y')('y')('y');
+ std::vector<char> y = boost::assign::list_of('x')('x')('x')('x')('e')('a')('b')('f')('d')('g')('y')('y')('y');
+
+ std::vector<size_t> updates;
+ std::vector<size_t> postUpdates;
+ std::vector<size_t> removes;
+ std::vector<size_t> inserts;
+ computeIndexDiff<char, std::equal_to<char>, IsXOrY >(x, y, updates, postUpdates, removes, inserts);
+
+ std::vector<size_t> expectedUpdates = boost::assign::list_of(0)(1)(2)(3)(11)(10)(9);
+ std::vector<size_t> expectedPostUpdates = boost::assign::list_of(0)(1)(2)(3)(12)(11)(10);
+ std::vector<size_t> expectedRemoves = boost::assign::list_of(8)(6);
+ std::vector<size_t> expectedInserts = boost::assign::list_of(9)(7)(4);
+ CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates);
+ CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates);
+ CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes);
+ CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(LeastCommonSubsequenceTest);
diff --git a/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp
index d774e6d..551bd6b 100644
--- a/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp
@@ -46,351 +46,351 @@ using namespace Swift;
#define CHILDREN mainWindow_->roster->getRoot()->getChildren()
class DummyCapsProvider : public CapsProvider {
- DiscoInfo::ref getCaps(const std::string&) const {return DiscoInfo::ref(new DiscoInfo());}
+ DiscoInfo::ref getCaps(const std::string&) const {return DiscoInfo::ref(new DiscoInfo());}
};
class RosterControllerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(RosterControllerTest);
- CPPUNIT_TEST(testAdd);
- CPPUNIT_TEST(testAddSubscription);
- CPPUNIT_TEST(testReceiveRename);
- CPPUNIT_TEST(testReceiveRegroup);
- CPPUNIT_TEST(testSendRename);
- CPPUNIT_TEST(testPresence);
- CPPUNIT_TEST(testHighestPresence);
- CPPUNIT_TEST(testNotHighestPresence);
- CPPUNIT_TEST(testUnavailablePresence);
- CPPUNIT_TEST(testRemoveResultsInUnavailablePresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- jid_ = JID("testjid@swift.im/swift");
- xmppRoster_ = new XMPPRosterImpl();
- avatarManager_ = new NullAvatarManager();
- mainWindowFactory_ = new MockMainWindowFactory();
- mucRegistry_ = new MUCRegistry();
- nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_);
- channel_ = new DummyIQChannel();
- router_ = new IQRouter(channel_);
- stanzaChannel_ = new DummyStanzaChannel();
- presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
- subscriptionManager_ = new SubscriptionManager(stanzaChannel_);
- eventController_ = new EventController();
- uiEventStream_ = new UIEventStream();
- settings_ = new DummySettingsProvider();
- nickManager_ = new DummyNickManager();
- capsProvider_ = new DummyCapsProvider();
- entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_);
- jingleSessionManager_ = new JingleSessionManager(router_);
-
- ftManager_ = new DummyFileTransferManager();
- ftOverview_ = new FileTransferOverview(ftManager_);
- clientBlockListManager_ = new ClientBlockListManager(router_);
- crypto_ = PlatformCryptoProvider::create();
- vcardStorage_ = new VCardMemoryStorage(crypto_);
- vcardManager_ = new VCardManager(jid_, router_, vcardStorage_);
- rosterController_ = new RosterController(jid_, xmppRoster_, avatarManager_, mainWindowFactory_, nickManager_, nickResolver_, presenceOracle_, subscriptionManager_, eventController_, uiEventStream_, router_, settings_, entityCapsManager_, ftOverview_, clientBlockListManager_, vcardManager_);
- mainWindow_ = mainWindowFactory_->last;
- }
-
- void tearDown() {
- delete rosterController_;
- delete vcardManager_;
- delete vcardStorage_;
- delete crypto_;
- delete clientBlockListManager_;
- delete ftOverview_;
- delete ftManager_;
- delete jingleSessionManager_;
- delete entityCapsManager_;
- delete capsProvider_;
- delete nickManager_;
- delete nickResolver_;
- delete mucRegistry_;
- delete mainWindowFactory_;
- delete avatarManager_;
- delete router_;
- delete channel_;
- delete eventController_;
- delete subscriptionManager_;
- delete presenceOracle_;
- delete stanzaChannel_;
- delete uiEventStream_;
- delete settings_;
- delete xmppRoster_;
- }
-
- GroupRosterItem* groupChild(size_t i) {
- return dynamic_cast<GroupRosterItem*>(CHILDREN[i]);
- }
-
- JID withResource(const JID& jid, const std::string& resource) {
- return JID(jid.toBare().toString() + "/" + resource);
- }
-
- void testPresence() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- groups.push_back("testGroup2");
- JID from("test@testdomain.com");
- xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
- Presence::ref presence(new Presence());
- presence->setFrom(withResource(from, "bob"));
- presence->setPriority(2);
- presence->setStatus("So totally here");
- stanzaChannel_->onPresenceReceived(presence);
- ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText());
- ContactRosterItem* item2 = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[1])->getChildren()[0]);
- CPPUNIT_ASSERT(item2);
- CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item2->getStatusText());
-
- }
-
- void testHighestPresence() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- JID from("test@testdomain.com");
- xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
- Presence::ref lowPresence(new Presence());
- lowPresence->setFrom(withResource(from, "bob"));
- lowPresence->setPriority(2);
- lowPresence->setStatus("Not here");
- Presence::ref highPresence(new Presence());
- highPresence->setFrom(withResource(from, "bert"));
- highPresence->setPriority(10);
- highPresence->setStatus("So totally here");
- stanzaChannel_->onPresenceReceived(lowPresence);
- stanzaChannel_->onPresenceReceived(highPresence);
- ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText());
- }
-
- void testNotHighestPresence() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- JID from("test@testdomain.com");
- xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
- Presence::ref lowPresence(new Presence());
- lowPresence->setFrom(withResource(from, "bob"));
- lowPresence->setPriority(2);
- lowPresence->setStatus("Not here");
- Presence::ref highPresence(new Presence());
- highPresence->setFrom(withResource(from, "bert"));
- highPresence->setPriority(10);
- highPresence->setStatus("So totally here");
- stanzaChannel_->onPresenceReceived(highPresence);
- stanzaChannel_->onPresenceReceived(lowPresence);
- ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
- CPPUNIT_ASSERT(item);
- CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText());
- }
-
- void testUnavailablePresence() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- JID from("test@testdomain.com");
- xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
-
- Presence::ref lowPresence(new Presence());
- lowPresence->setFrom(withResource(from, "bob"));
- lowPresence->setPriority(2);
- lowPresence->setShow(StatusShow::Away);
- lowPresence->setStatus("Not here");
- Presence::ref lowPresenceOffline(new Presence());
- lowPresenceOffline->setFrom(withResource(from, "bob"));
- lowPresenceOffline->setStatus("Signing out");
- lowPresenceOffline->setType(Presence::Unavailable);
-
- Presence::ref highPresence(new Presence());
- highPresence->setFrom(withResource(from, "bert"));
- highPresence->setPriority(10);
- highPresence->setStatus("So totally here");
- Presence::ref highPresenceOffline(new Presence());
- highPresenceOffline->setFrom(withResource(from, "bert"));
- highPresenceOffline->setType(Presence::Unavailable);
-
- stanzaChannel_->onPresenceReceived(lowPresence);
- Presence::ref accountPresence = presenceOracle_->getAccountPresence(from);
- CPPUNIT_ASSERT_EQUAL(StatusShow::Away, accountPresence->getShow());
-
- stanzaChannel_->onPresenceReceived(highPresence);
- accountPresence = presenceOracle_->getAccountPresence(from);
- CPPUNIT_ASSERT_EQUAL(StatusShow::Online, accountPresence->getShow());
-
- stanzaChannel_->onPresenceReceived(highPresenceOffline);
-
- // After this, the roster should show the low presence.
- ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
- CPPUNIT_ASSERT(item);
-
- Presence::ref low = presenceOracle_->getAccountPresence(from);
-
- CPPUNIT_ASSERT_EQUAL(Presence::Available, low->getType());
- CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), low->getStatus());
- CPPUNIT_ASSERT_EQUAL(lowPresence->getShow(), item->getStatusShow());
- CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), item->getStatusText());
- stanzaChannel_->onPresenceReceived(lowPresenceOffline);
- item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
- CPPUNIT_ASSERT(item);
- /* A verification that if the test fails, it's the RosterController, not the PresenceOracle. */
- low = presenceOracle_->getHighestPriorityPresence(from);
- CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, low->getType());
- CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), low->getStatus());
- CPPUNIT_ASSERT_EQUAL(StatusShow::None, item->getStatusShow());
- CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), item->getStatusText());
- }
-
- void testAdd() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- groups.push_back("testGroup2");
- xmppRoster_->addContact(JID("test@testdomain.com/bob"), "name", groups, RosterItemPayload::Both);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(CHILDREN.size()));
- //CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(JID("foo@bar.com")));
- }
-
- void testAddSubscription() {
- std::vector<std::string> groups;
- JID jid("test@testdomain.com");
- xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::None);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::To);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
-
- xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
-
- }
-
- void testReceiveRename() {
- std::vector<std::string> groups;
- JID jid("test@testdomain.com");
- xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("name"), groupChild(0)->getChildren()[0]->getDisplayName());
- xmppRoster_->addContact(jid, "NewName", groups, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("NewName"), groupChild(0)->getChildren()[0]->getDisplayName());
- }
-
- void testReceiveRegroup() {
- std::vector<std::string> oldGroups;
- std::vector<std::string> newGroups;
- newGroups.push_back("A Group");
- std::vector<std::string> newestGroups;
- newestGroups.push_back("Best Group");
- JID jid("test@testdomain.com");
- xmppRoster_->addContact(jid, "", oldGroups, RosterItemPayload::Both);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(jid.toString(), groupChild(0)->getChildren()[0]->getDisplayName());
-
- xmppRoster_->addContact(jid, "new name", newGroups, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("A Group"), groupChild(0)->getDisplayName());
-
- xmppRoster_->addContact(jid, "new name", newestGroups, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Best Group"), groupChild(0)->getDisplayName());
- }
-
- void testSendRename() {
- JID jid("testling@wonderland.lit");
- std::vector<std::string> groups;
- groups.push_back("Friends");
- groups.push_back("Enemies");
- xmppRoster_->addContact(jid, "Bob", groups, RosterItemPayload::From);
- CPPUNIT_ASSERT_EQUAL(groups.size(), xmppRoster_->getGroupsForJID(jid).size());
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RenameRosterItemUIEvent(jid, "Robert")));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), channel_->iqs_.size());
- CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType());
- boost::shared_ptr<RosterPayload> payload = channel_->iqs_[0]->getPayload<RosterPayload>();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getItems().size());
- RosterItemPayload item = payload->getItems()[0];
- CPPUNIT_ASSERT_EQUAL(jid, item.getJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Robert"), item.getName());
-
- CPPUNIT_ASSERT_EQUAL(groups.size(), item.getGroups().size());
- assertVectorsEqual(groups, item.getGroups(), __LINE__);
- }
-
- void testRemoveResultsInUnavailablePresence() {
- std::vector<std::string> groups;
- groups.push_back("testGroup1");
- JID from("test@testdomain.com");
- xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
- Presence::ref lowPresence(new Presence());
- lowPresence->setFrom(withResource(from, "bob"));
- lowPresence->setPriority(2);
- lowPresence->setStatus("Not here");
- Presence::ref highPresence(new Presence());
- highPresence->setFrom(withResource(from, "bert"));
- highPresence->setPriority(10);
- highPresence->setStatus("So totally here");
- stanzaChannel_->onPresenceReceived(highPresence);
- stanzaChannel_->onPresenceReceived(lowPresence);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), presenceOracle_->getAllPresence("test@testdomain.com").size());
-
- xmppRoster_->onJIDRemoved(JID("test@testdomain.com"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), presenceOracle_->getAllPresence("test@testdomain.com").size());
- CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presenceOracle_->getAllPresence("test@testdomain.com")[0]->getType());
- }
-
- void assertVectorsEqual(const std::vector<std::string>& v1, const std::vector<std::string>& v2, int line) {
- foreach (const std::string& entry, v1) {
- if (std::find(v2.begin(), v2.end(), entry) == v2.end()) {
- std::stringstream stream;
- stream << "Couldn't find " << entry << " in v2 (line " << line << ")";
- CPPUNIT_FAIL(stream.str());
- }
- }
- }
-
- private:
- JID jid_;
- XMPPRosterImpl* xmppRoster_;
- MUCRegistry* mucRegistry_;
- AvatarManager* avatarManager_;
- MockMainWindowFactory* mainWindowFactory_;
- NickManager* nickManager_;
- NickResolver* nickResolver_;
- RosterController* rosterController_;
- DummyIQChannel* channel_;
- DummyStanzaChannel* stanzaChannel_;
- IQRouter* router_;
- PresenceOracle* presenceOracle_;
- SubscriptionManager* subscriptionManager_;
- EventController* eventController_;
- UIEventStream* uiEventStream_;
- MockMainWindow* mainWindow_;
- DummySettingsProvider* settings_;
- DummyCapsProvider* capsProvider_;
- EntityCapsManager* entityCapsManager_;
- JingleSessionManager* jingleSessionManager_;
- FileTransferManager* ftManager_;
- FileTransferOverview* ftOverview_;
- ClientBlockListManager* clientBlockListManager_;
- CryptoProvider* crypto_;
- VCardStorage* vcardStorage_;
- VCardManager* vcardManager_;
+ CPPUNIT_TEST_SUITE(RosterControllerTest);
+ CPPUNIT_TEST(testAdd);
+ CPPUNIT_TEST(testAddSubscription);
+ CPPUNIT_TEST(testReceiveRename);
+ CPPUNIT_TEST(testReceiveRegroup);
+ CPPUNIT_TEST(testSendRename);
+ CPPUNIT_TEST(testPresence);
+ CPPUNIT_TEST(testHighestPresence);
+ CPPUNIT_TEST(testNotHighestPresence);
+ CPPUNIT_TEST(testUnavailablePresence);
+ CPPUNIT_TEST(testRemoveResultsInUnavailablePresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ jid_ = JID("testjid@swift.im/swift");
+ xmppRoster_ = new XMPPRosterImpl();
+ avatarManager_ = new NullAvatarManager();
+ mainWindowFactory_ = new MockMainWindowFactory();
+ mucRegistry_ = new MUCRegistry();
+ nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_);
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ stanzaChannel_ = new DummyStanzaChannel();
+ presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
+ subscriptionManager_ = new SubscriptionManager(stanzaChannel_);
+ eventController_ = new EventController();
+ uiEventStream_ = new UIEventStream();
+ settings_ = new DummySettingsProvider();
+ nickManager_ = new DummyNickManager();
+ capsProvider_ = new DummyCapsProvider();
+ entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_);
+ jingleSessionManager_ = new JingleSessionManager(router_);
+
+ ftManager_ = new DummyFileTransferManager();
+ ftOverview_ = new FileTransferOverview(ftManager_);
+ clientBlockListManager_ = new ClientBlockListManager(router_);
+ crypto_ = PlatformCryptoProvider::create();
+ vcardStorage_ = new VCardMemoryStorage(crypto_);
+ vcardManager_ = new VCardManager(jid_, router_, vcardStorage_);
+ rosterController_ = new RosterController(jid_, xmppRoster_, avatarManager_, mainWindowFactory_, nickManager_, nickResolver_, presenceOracle_, subscriptionManager_, eventController_, uiEventStream_, router_, settings_, entityCapsManager_, ftOverview_, clientBlockListManager_, vcardManager_);
+ mainWindow_ = mainWindowFactory_->last;
+ }
+
+ void tearDown() {
+ delete rosterController_;
+ delete vcardManager_;
+ delete vcardStorage_;
+ delete crypto_;
+ delete clientBlockListManager_;
+ delete ftOverview_;
+ delete ftManager_;
+ delete jingleSessionManager_;
+ delete entityCapsManager_;
+ delete capsProvider_;
+ delete nickManager_;
+ delete nickResolver_;
+ delete mucRegistry_;
+ delete mainWindowFactory_;
+ delete avatarManager_;
+ delete router_;
+ delete channel_;
+ delete eventController_;
+ delete subscriptionManager_;
+ delete presenceOracle_;
+ delete stanzaChannel_;
+ delete uiEventStream_;
+ delete settings_;
+ delete xmppRoster_;
+ }
+
+ GroupRosterItem* groupChild(size_t i) {
+ return dynamic_cast<GroupRosterItem*>(CHILDREN[i]);
+ }
+
+ JID withResource(const JID& jid, const std::string& resource) {
+ return JID(jid.toBare().toString() + "/" + resource);
+ }
+
+ void testPresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ groups.push_back("testGroup2");
+ JID from("test@testdomain.com");
+ xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
+ Presence::ref presence(new Presence());
+ presence->setFrom(withResource(from, "bob"));
+ presence->setPriority(2);
+ presence->setStatus("So totally here");
+ stanzaChannel_->onPresenceReceived(presence);
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText());
+ ContactRosterItem* item2 = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[1])->getChildren()[0]);
+ CPPUNIT_ASSERT(item2);
+ CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item2->getStatusText());
+
+ }
+
+ void testHighestPresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ JID from("test@testdomain.com");
+ xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
+ Presence::ref lowPresence(new Presence());
+ lowPresence->setFrom(withResource(from, "bob"));
+ lowPresence->setPriority(2);
+ lowPresence->setStatus("Not here");
+ Presence::ref highPresence(new Presence());
+ highPresence->setFrom(withResource(from, "bert"));
+ highPresence->setPriority(10);
+ highPresence->setStatus("So totally here");
+ stanzaChannel_->onPresenceReceived(lowPresence);
+ stanzaChannel_->onPresenceReceived(highPresence);
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText());
+ }
+
+ void testNotHighestPresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ JID from("test@testdomain.com");
+ xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
+ Presence::ref lowPresence(new Presence());
+ lowPresence->setFrom(withResource(from, "bob"));
+ lowPresence->setPriority(2);
+ lowPresence->setStatus("Not here");
+ Presence::ref highPresence(new Presence());
+ highPresence->setFrom(withResource(from, "bert"));
+ highPresence->setPriority(10);
+ highPresence->setStatus("So totally here");
+ stanzaChannel_->onPresenceReceived(highPresence);
+ stanzaChannel_->onPresenceReceived(lowPresence);
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText());
+ }
+
+ void testUnavailablePresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ JID from("test@testdomain.com");
+ xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
+
+ Presence::ref lowPresence(new Presence());
+ lowPresence->setFrom(withResource(from, "bob"));
+ lowPresence->setPriority(2);
+ lowPresence->setShow(StatusShow::Away);
+ lowPresence->setStatus("Not here");
+ Presence::ref lowPresenceOffline(new Presence());
+ lowPresenceOffline->setFrom(withResource(from, "bob"));
+ lowPresenceOffline->setStatus("Signing out");
+ lowPresenceOffline->setType(Presence::Unavailable);
+
+ Presence::ref highPresence(new Presence());
+ highPresence->setFrom(withResource(from, "bert"));
+ highPresence->setPriority(10);
+ highPresence->setStatus("So totally here");
+ Presence::ref highPresenceOffline(new Presence());
+ highPresenceOffline->setFrom(withResource(from, "bert"));
+ highPresenceOffline->setType(Presence::Unavailable);
+
+ stanzaChannel_->onPresenceReceived(lowPresence);
+ Presence::ref accountPresence = presenceOracle_->getAccountPresence(from);
+ CPPUNIT_ASSERT_EQUAL(StatusShow::Away, accountPresence->getShow());
+
+ stanzaChannel_->onPresenceReceived(highPresence);
+ accountPresence = presenceOracle_->getAccountPresence(from);
+ CPPUNIT_ASSERT_EQUAL(StatusShow::Online, accountPresence->getShow());
+
+ stanzaChannel_->onPresenceReceived(highPresenceOffline);
+
+ // After this, the roster should show the low presence.
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+
+ Presence::ref low = presenceOracle_->getAccountPresence(from);
+
+ CPPUNIT_ASSERT_EQUAL(Presence::Available, low->getType());
+ CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), low->getStatus());
+ CPPUNIT_ASSERT_EQUAL(lowPresence->getShow(), item->getStatusShow());
+ CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), item->getStatusText());
+ stanzaChannel_->onPresenceReceived(lowPresenceOffline);
+ item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(CHILDREN[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ /* A verification that if the test fails, it's the RosterController, not the PresenceOracle. */
+ low = presenceOracle_->getHighestPriorityPresence(from);
+ CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, low->getType());
+ CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), low->getStatus());
+ CPPUNIT_ASSERT_EQUAL(StatusShow::None, item->getStatusShow());
+ CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), item->getStatusText());
+ }
+
+ void testAdd() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ groups.push_back("testGroup2");
+ xmppRoster_->addContact(JID("test@testdomain.com/bob"), "name", groups, RosterItemPayload::Both);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(CHILDREN.size()));
+ //CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(JID("foo@bar.com")));
+ }
+
+ void testAddSubscription() {
+ std::vector<std::string> groups;
+ JID jid("test@testdomain.com");
+ xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::None);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::To);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+
+ xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+
+ }
+
+ void testReceiveRename() {
+ std::vector<std::string> groups;
+ JID jid("test@testdomain.com");
+ xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("name"), groupChild(0)->getChildren()[0]->getDisplayName());
+ xmppRoster_->addContact(jid, "NewName", groups, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName"), groupChild(0)->getChildren()[0]->getDisplayName());
+ }
+
+ void testReceiveRegroup() {
+ std::vector<std::string> oldGroups;
+ std::vector<std::string> newGroups;
+ newGroups.push_back("A Group");
+ std::vector<std::string> newestGroups;
+ newestGroups.push_back("Best Group");
+ JID jid("test@testdomain.com");
+ xmppRoster_->addContact(jid, "", oldGroups, RosterItemPayload::Both);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(jid.toString(), groupChild(0)->getChildren()[0]->getDisplayName());
+
+ xmppRoster_->addContact(jid, "new name", newGroups, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("A Group"), groupChild(0)->getDisplayName());
+
+ xmppRoster_->addContact(jid, "new name", newestGroups, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(CHILDREN.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(groupChild(0)->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Best Group"), groupChild(0)->getDisplayName());
+ }
+
+ void testSendRename() {
+ JID jid("testling@wonderland.lit");
+ std::vector<std::string> groups;
+ groups.push_back("Friends");
+ groups.push_back("Enemies");
+ xmppRoster_->addContact(jid, "Bob", groups, RosterItemPayload::From);
+ CPPUNIT_ASSERT_EQUAL(groups.size(), xmppRoster_->getGroupsForJID(jid).size());
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RenameRosterItemUIEvent(jid, "Robert")));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), channel_->iqs_.size());
+ CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType());
+ boost::shared_ptr<RosterPayload> payload = channel_->iqs_[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getItems().size());
+ RosterItemPayload item = payload->getItems()[0];
+ CPPUNIT_ASSERT_EQUAL(jid, item.getJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Robert"), item.getName());
+
+ CPPUNIT_ASSERT_EQUAL(groups.size(), item.getGroups().size());
+ assertVectorsEqual(groups, item.getGroups(), __LINE__);
+ }
+
+ void testRemoveResultsInUnavailablePresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ JID from("test@testdomain.com");
+ xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both);
+ Presence::ref lowPresence(new Presence());
+ lowPresence->setFrom(withResource(from, "bob"));
+ lowPresence->setPriority(2);
+ lowPresence->setStatus("Not here");
+ Presence::ref highPresence(new Presence());
+ highPresence->setFrom(withResource(from, "bert"));
+ highPresence->setPriority(10);
+ highPresence->setStatus("So totally here");
+ stanzaChannel_->onPresenceReceived(highPresence);
+ stanzaChannel_->onPresenceReceived(lowPresence);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), presenceOracle_->getAllPresence("test@testdomain.com").size());
+
+ xmppRoster_->onJIDRemoved(JID("test@testdomain.com"));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), presenceOracle_->getAllPresence("test@testdomain.com").size());
+ CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presenceOracle_->getAllPresence("test@testdomain.com")[0]->getType());
+ }
+
+ void assertVectorsEqual(const std::vector<std::string>& v1, const std::vector<std::string>& v2, int line) {
+ foreach (const std::string& entry, v1) {
+ if (std::find(v2.begin(), v2.end(), entry) == v2.end()) {
+ std::stringstream stream;
+ stream << "Couldn't find " << entry << " in v2 (line " << line << ")";
+ CPPUNIT_FAIL(stream.str());
+ }
+ }
+ }
+
+ private:
+ JID jid_;
+ XMPPRosterImpl* xmppRoster_;
+ MUCRegistry* mucRegistry_;
+ AvatarManager* avatarManager_;
+ MockMainWindowFactory* mainWindowFactory_;
+ NickManager* nickManager_;
+ NickResolver* nickResolver_;
+ RosterController* rosterController_;
+ DummyIQChannel* channel_;
+ DummyStanzaChannel* stanzaChannel_;
+ IQRouter* router_;
+ PresenceOracle* presenceOracle_;
+ SubscriptionManager* subscriptionManager_;
+ EventController* eventController_;
+ UIEventStream* uiEventStream_;
+ MockMainWindow* mainWindow_;
+ DummySettingsProvider* settings_;
+ DummyCapsProvider* capsProvider_;
+ EntityCapsManager* entityCapsManager_;
+ JingleSessionManager* jingleSessionManager_;
+ FileTransferManager* ftManager_;
+ FileTransferOverview* ftOverview_;
+ ClientBlockListManager* clientBlockListManager_;
+ CryptoProvider* crypto_;
+ VCardStorage* vcardStorage_;
+ VCardManager* vcardManager_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterControllerTest);
diff --git a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
index 314b5c6..dd22cb7 100644
--- a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
@@ -16,130 +16,130 @@
using namespace Swift;
class RosterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(RosterTest);
- CPPUNIT_TEST(testGetGroup);
- CPPUNIT_TEST(testRemoveContact);
- CPPUNIT_TEST(testRemoveSecondContact);
- CPPUNIT_TEST(testRemoveSecondContactSameBare);
- CPPUNIT_TEST(testApplyPresenceLikeMUC);
- CPPUNIT_TEST(testReSortLikeMUC);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- jid1_ = JID("a@b.c");
- jid2_ = JID("b@c.d");
- jid3_ = JID("c@d.e");
- roster_ = new Roster();
- }
-
- void tearDown() {
- delete roster_;
- }
-
- void testGetGroup() {
- roster_->addContact(jid1_, JID(), "Bert", "group1", "");
- roster_->addContact(jid2_, JID(), "Ernie", "group2", "");
- roster_->addContact(jid3_, JID(), "Cookie", "group1", "");
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(roster_->getRoot()->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("group1"), roster_->getRoot()->getChildren()[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("group2"), roster_->getRoot()->getChildren()[1]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[1])->getChildren()[0]->getDisplayName());
-
- }
-
- void testRemoveContact() {
- roster_->addContact(jid1_, jid1_, "Bert", "group1", "");
- CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
-
- roster_->removeContact(jid1_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
- }
-
- void testRemoveSecondContact() {
- roster_->addContact(jid1_, jid1_, "Bert", "group1", "");
- roster_->addContact(jid2_, jid2_, "Cookie", "group1", "");
- CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
-
- roster_->removeContact(jid2_);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
- }
-
- void testRemoveSecondContactSameBare() {
- JID jid4a("a@b/c");
- JID jid4b("a@b/d");
- roster_->addContact(jid4a, JID(), "Bert", "group1", "");
- roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
- CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
-
- roster_->removeContact(jid4b);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
- }
-
- void testApplyPresenceLikeMUC() {
- JID jid4a("a@b/c");
- JID jid4b("a@b/d");
- JID jid4c("a@b/e");
- roster_->addContact(jid4a, JID(), "Bird", "group1", "");
- roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
- roster_->removeContact(jid4b);
- roster_->addContact(jid4c, JID(), "Bert", "group1", "");
- roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setShow(StatusShow::DND);
- presence->setFrom(jid4a);
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
- presence->setFrom(jid4b);
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
- presence->setFrom(jid4c);
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
-
- presence = boost::make_shared<Presence>();
- presence->setFrom(jid4b);
- presence->setShow(StatusShow::Online);
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
- std::vector<RosterItem*> children = static_cast<GroupRosterItem*>(roster_->getRoot()->getDisplayedChildren()[0])->getDisplayedChildren();
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(children.size()));
-
- /* Check order */
- CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), children[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Bert"), children[1]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("Bird"), children[2]->getDisplayName());
-
- presence = boost::make_shared<Presence>();
- presence->setFrom(jid4c);
- presence->setType(Presence::Unavailable);
- roster_->removeContact(jid4c);
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
-
- }
-
- void testReSortLikeMUC() {
- JID jid4a("a@b/c");
- JID jid4b("a@b/d");
- JID jid4c("a@b/e");
- roster_->addContact(jid4a, JID(), "Bird", "group1", "");
- roster_->addContact(jid4b, JID(), "Cookie", "group2", "");
- roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
- roster_->getGroup("group1")->setManualSort("2");
- roster_->getGroup("group2")->setManualSort("1");
- GroupRosterItem* root = roster_->getRoot();
- const std::vector<RosterItem*> kids = root->getDisplayedChildren();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), kids.size());
- CPPUNIT_ASSERT_EQUAL(std::string("group2"), kids[0]->getDisplayName());
- CPPUNIT_ASSERT_EQUAL(std::string("group1"), kids[1]->getDisplayName());
- }
-
- private:
- Roster *roster_;
- JID jid1_;
- JID jid2_;
- JID jid3_;
+ CPPUNIT_TEST_SUITE(RosterTest);
+ CPPUNIT_TEST(testGetGroup);
+ CPPUNIT_TEST(testRemoveContact);
+ CPPUNIT_TEST(testRemoveSecondContact);
+ CPPUNIT_TEST(testRemoveSecondContactSameBare);
+ CPPUNIT_TEST(testApplyPresenceLikeMUC);
+ CPPUNIT_TEST(testReSortLikeMUC);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ jid1_ = JID("a@b.c");
+ jid2_ = JID("b@c.d");
+ jid3_ = JID("c@d.e");
+ roster_ = new Roster();
+ }
+
+ void tearDown() {
+ delete roster_;
+ }
+
+ void testGetGroup() {
+ roster_->addContact(jid1_, JID(), "Bert", "group1", "");
+ roster_->addContact(jid2_, JID(), "Ernie", "group2", "");
+ roster_->addContact(jid3_, JID(), "Cookie", "group1", "");
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(roster_->getRoot()->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("group1"), roster_->getRoot()->getChildren()[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("group2"), roster_->getRoot()->getChildren()[1]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[1])->getChildren()[0]->getDisplayName());
+
+ }
+
+ void testRemoveContact() {
+ roster_->addContact(jid1_, jid1_, "Bert", "group1", "");
+ CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
+
+ roster_->removeContact(jid1_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
+ }
+
+ void testRemoveSecondContact() {
+ roster_->addContact(jid1_, jid1_, "Bert", "group1", "");
+ roster_->addContact(jid2_, jid2_, "Cookie", "group1", "");
+ CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
+
+ roster_->removeContact(jid2_);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
+ }
+
+ void testRemoveSecondContactSameBare() {
+ JID jid4a("a@b/c");
+ JID jid4b("a@b/d");
+ roster_->addContact(jid4a, JID(), "Bert", "group1", "");
+ roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
+ CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
+
+ roster_->removeContact(jid4b);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
+ }
+
+ void testApplyPresenceLikeMUC() {
+ JID jid4a("a@b/c");
+ JID jid4b("a@b/d");
+ JID jid4c("a@b/e");
+ roster_->addContact(jid4a, JID(), "Bird", "group1", "");
+ roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
+ roster_->removeContact(jid4b);
+ roster_->addContact(jid4c, JID(), "Bert", "group1", "");
+ roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setShow(StatusShow::DND);
+ presence->setFrom(jid4a);
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+ presence->setFrom(jid4b);
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+ presence->setFrom(jid4c);
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+
+ presence = boost::make_shared<Presence>();
+ presence->setFrom(jid4b);
+ presence->setShow(StatusShow::Online);
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+ std::vector<RosterItem*> children = static_cast<GroupRosterItem*>(roster_->getRoot()->getDisplayedChildren()[0])->getDisplayedChildren();
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(children.size()));
+
+ /* Check order */
+ CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), children[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Bert"), children[1]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Bird"), children[2]->getDisplayName());
+
+ presence = boost::make_shared<Presence>();
+ presence->setFrom(jid4c);
+ presence->setType(Presence::Unavailable);
+ roster_->removeContact(jid4c);
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+
+ }
+
+ void testReSortLikeMUC() {
+ JID jid4a("a@b/c");
+ JID jid4b("a@b/d");
+ JID jid4c("a@b/e");
+ roster_->addContact(jid4a, JID(), "Bird", "group1", "");
+ roster_->addContact(jid4b, JID(), "Cookie", "group2", "");
+ roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
+ roster_->getGroup("group1")->setManualSort("2");
+ roster_->getGroup("group2")->setManualSort("1");
+ GroupRosterItem* root = roster_->getRoot();
+ const std::vector<RosterItem*> kids = root->getDisplayedChildren();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), kids.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("group2"), kids[0]->getDisplayName());
+ CPPUNIT_ASSERT_EQUAL(std::string("group1"), kids[1]->getDisplayName());
+ }
+
+ private:
+ Roster *roster_;
+ JID jid1_;
+ JID jid2_;
+ JID jid3_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterTest);
diff --git a/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp b/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp
index 10030ef..086bd6f 100644
--- a/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp
@@ -9,8 +9,8 @@
std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i);
std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i) {
- os << "(" << i.section << ", " << i.row << ")";
- return os;
+ os << "(" << i.section << ", " << i.row << ")";
+ return os;
}
#include <cppunit/extensions/HelperMacros.h>
@@ -27,67 +27,67 @@ std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i) {
using namespace Swift;
class TableRosterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(TableRosterTest);
- CPPUNIT_TEST(testAddContact_EmptyRoster);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- timerFactory = new DummyTimerFactory();
- roster = new Roster();
- jid1 = JID("jid1@example.com");
- jid2 = JID("jid2@example.com");
- }
-
- void tearDown() {
- delete roster;
- delete timerFactory;
- }
-
- void testAddContact_EmptyRoster() {
- /*
- boost::shared_ptr<TableRoster> tableRoster(createTestling());
-
- addContact(jid1, "1", "group1");
-
- CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(events.size()));
- CPPUNIT_ASSERT(boost::get<BeginUpdatesEvent>(&events[0]));
- CPPUNIT_ASSERT(boost::get<SectionsInsertedEvent>(&events[1]));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(boost::get<SectionsInsertedEvent>(events[1]).sections.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(boost::get<SectionsInsertedEvent>(events[1]).sections[0]));
- CPPUNIT_ASSERT(boost::get<RowsInsertedEvent>(&events[2]));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(boost::get<RowsInsertedEvent>(events[2]).rows.size()));
- CPPUNIT_ASSERT_EQUAL(TableRoster::Index(0, 0), boost::get<RowsInsertedEvent>(events[2]).rows[0]);
- CPPUNIT_ASSERT(boost::get<EndUpdatesEvent>(&events[3]));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tableRoster->getNumberOfSections()));
- CPPUNIT_ASSERT_EQUAL(std::string("group1"), tableRoster->getSectionTitle(0));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tableRoster->getNumberOfRowsInSection(0)));
- CPPUNIT_ASSERT_EQUAL(jid1, tableRoster->getItem(TableRoster::Index(0, 0)).jid);
- */
- }
-
- private:
- void addContact(const JID& jid, const std::string& name, const std::string& group) {
- roster->addContact(jid, JID(), name, group, "");
- }
-
- TableRoster* createTestling() {
- TableRoster* result = new TableRoster(roster, timerFactory, 10);
- result->onUpdate.connect(boost::bind(&TableRosterTest::handleUpdate, this, _1));
- return result;
- }
-
- void handleUpdate(const TableRoster::Update& update) {
- updates.push_back(update);
- }
-
- private:
- DummyTimerFactory* timerFactory;
- Roster* roster;
- JID jid1;
- JID jid2;
- std::vector<TableRoster::Update> updates;
+ CPPUNIT_TEST_SUITE(TableRosterTest);
+ CPPUNIT_TEST(testAddContact_EmptyRoster);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ timerFactory = new DummyTimerFactory();
+ roster = new Roster();
+ jid1 = JID("jid1@example.com");
+ jid2 = JID("jid2@example.com");
+ }
+
+ void tearDown() {
+ delete roster;
+ delete timerFactory;
+ }
+
+ void testAddContact_EmptyRoster() {
+ /*
+ boost::shared_ptr<TableRoster> tableRoster(createTestling());
+
+ addContact(jid1, "1", "group1");
+
+ CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(events.size()));
+ CPPUNIT_ASSERT(boost::get<BeginUpdatesEvent>(&events[0]));
+ CPPUNIT_ASSERT(boost::get<SectionsInsertedEvent>(&events[1]));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(boost::get<SectionsInsertedEvent>(events[1]).sections.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(boost::get<SectionsInsertedEvent>(events[1]).sections[0]));
+ CPPUNIT_ASSERT(boost::get<RowsInsertedEvent>(&events[2]));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(boost::get<RowsInsertedEvent>(events[2]).rows.size()));
+ CPPUNIT_ASSERT_EQUAL(TableRoster::Index(0, 0), boost::get<RowsInsertedEvent>(events[2]).rows[0]);
+ CPPUNIT_ASSERT(boost::get<EndUpdatesEvent>(&events[3]));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tableRoster->getNumberOfSections()));
+ CPPUNIT_ASSERT_EQUAL(std::string("group1"), tableRoster->getSectionTitle(0));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(tableRoster->getNumberOfRowsInSection(0)));
+ CPPUNIT_ASSERT_EQUAL(jid1, tableRoster->getItem(TableRoster::Index(0, 0)).jid);
+ */
+ }
+
+ private:
+ void addContact(const JID& jid, const std::string& name, const std::string& group) {
+ roster->addContact(jid, JID(), name, group, "");
+ }
+
+ TableRoster* createTestling() {
+ TableRoster* result = new TableRoster(roster, timerFactory, 10);
+ result->onUpdate.connect(boost::bind(&TableRosterTest::handleUpdate, this, _1));
+ return result;
+ }
+
+ void handleUpdate(const TableRoster::Update& update) {
+ updates.push_back(update);
+ }
+
+ private:
+ DummyTimerFactory* timerFactory;
+ Roster* roster;
+ JID jid1;
+ JID jid2;
+ std::vector<TableRoster::Update> updates;
};
CPPUNIT_TEST_SUITE_REGISTRATION(TableRosterTest);
diff --git a/Swift/Controllers/SettingConstants.h b/Swift/Controllers/SettingConstants.h
index c4ac4ad..9343b7b 100644
--- a/Swift/Controllers/SettingConstants.h
+++ b/Swift/Controllers/SettingConstants.h
@@ -9,100 +9,100 @@
#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
- /**
- * This class contains the major setting keys for Swift.
- */
- class SettingConstants {
- public:
- /**
- * The #IDLE_GOES_OFFLINE setting specifies whether to close the XMPP connection when
- * the user went idle.
- *
- * True for automatic close of the XMPP connection and false for only changing the presence on idle.
- */
- static const SettingsProvider::Setting<bool> IDLE_GOES_OFFLINE;
- /**
- * The #IDLE_TIMEOUT setting specifieds the seconds the user has to be inactive at the
- * desktop so the user is regarded as idle.
- */
- static const SettingsProvider::Setting<int> IDLE_TIMEOUT;
- static const SettingsProvider::Setting<bool> SHOW_NOTIFICATIONS;
- /**
- * The #REQUEST_DELIVERYRECEIPTS settings specifies whether to request delivery receipts
- * for messages to contacts that support message receipts.
- */
- static const SettingsProvider::Setting<bool> REQUEST_DELIVERYRECEIPTS;
- static const SettingsProvider::Setting<bool> FORGET_PASSWORDS;
- static const SettingsProvider::Setting<bool> REMEMBER_RECENT_CHATS;
- static const SettingsProvider::Setting<std::string> LAST_LOGIN_JID;
- static const SettingsProvider::Setting<bool> LOGIN_AUTOMATICALLY;
- /**
- * The #SHOW_OFFLINE setting specifies whether or not to show offline contacts in the
- * roster.
- *
- * If set true Swift will show offline contacts; else not.
- */
- static const SettingsProvider::Setting<bool> SHOW_OFFLINE;
- /**
- * The #EXPANDED_ROSTER_GROUPS setting specifies the list of groups that are expanded
- * in the roster UI.
- *
- * Its value is a string with group names seperated by newlines.
- */
- static const SettingsProvider::Setting<std::string> EXPANDED_ROSTER_GROUPS;
- static const SettingsProvider::Setting<bool> PLAY_SOUNDS;
- /**
- * The #HIGHLIGHT_RULES setting specifies the highlight rules and the associated actions.
- *
- * Its value is a Boost serialized representation.
- */
- static const SettingsProvider::Setting<std::string> HIGHLIGHT_RULES;
- static const SettingsProvider::Setting<bool> SPELL_CHECKER;
- static const SettingsProvider::Setting<std::string> DICT_PATH;
- static const SettingsProvider::Setting<std::string> PERSONAL_DICT_PATH;
- static const SettingsProvider::Setting<std::string> DICT_FILE;
- /**
- * The #INVITE_AUTO_ACCEPT_MODE setting specifies how to handle invites to chat rooms.
- *
- * Supported values are:
- * - "no" : It is up to the user whether to accept the invitation and enter a room or not.
- * - "presence" : The invitation is automatically accepted if it is from a contact that is
- * already allowed to see the user's presence status.
- * - "domain" : The invitation is automatically accepted if it is from a contact that is
- * already allowed to see the user's presence status or from a contact of user's domain.
- */
- static const SettingsProvider::Setting<std::string> INVITE_AUTO_ACCEPT_MODE;
- /**
- * The #TRELLIS_GRID_SIZE setting specifies the dimensions of the grid used for the trellis
- * layout.
- *
- * Its value is a Qt serialized representation.
- */
- static const SettingsProvider::Setting<std::string> TRELLIS_GRID_SIZE;
- /**
- * The #TRELLIS_GRID_POSITIONS setting specifies where conversations to contacts or rooms go
- * in the trellis grid.
- *
- * Its value is a Qt serialized representation.
- */
- static const SettingsProvider::Setting<std::string> TRELLIS_GRID_POSITIONS;
- /**
- * The #DISCONNECT_ON_CARD_REMOVAL setting
- * specifies whether or not to sign out the user when
- * the smartcard is removed.
- *
- * If set true Swift will sign out the user when the
- * smart card is removed; else not.
- */
- static const SettingsProvider::Setting<bool> DISCONNECT_ON_CARD_REMOVAL;
- /**
- * The #SINGLE_SIGN_ON setting
- * specifies whether to log in using Single Sign On.
- * This is currently supported on Windows.
- *
- * If set true Swift will use GSSAPI authentication to
- * log in the user; else not.
- */
- static const SettingsProvider::Setting<bool> SINGLE_SIGN_ON;
- };
+ /**
+ * This class contains the major setting keys for Swift.
+ */
+ class SettingConstants {
+ public:
+ /**
+ * The #IDLE_GOES_OFFLINE setting specifies whether to close the XMPP connection when
+ * the user went idle.
+ *
+ * True for automatic close of the XMPP connection and false for only changing the presence on idle.
+ */
+ static const SettingsProvider::Setting<bool> IDLE_GOES_OFFLINE;
+ /**
+ * The #IDLE_TIMEOUT setting specifieds the seconds the user has to be inactive at the
+ * desktop so the user is regarded as idle.
+ */
+ static const SettingsProvider::Setting<int> IDLE_TIMEOUT;
+ static const SettingsProvider::Setting<bool> SHOW_NOTIFICATIONS;
+ /**
+ * The #REQUEST_DELIVERYRECEIPTS settings specifies whether to request delivery receipts
+ * for messages to contacts that support message receipts.
+ */
+ static const SettingsProvider::Setting<bool> REQUEST_DELIVERYRECEIPTS;
+ static const SettingsProvider::Setting<bool> FORGET_PASSWORDS;
+ static const SettingsProvider::Setting<bool> REMEMBER_RECENT_CHATS;
+ static const SettingsProvider::Setting<std::string> LAST_LOGIN_JID;
+ static const SettingsProvider::Setting<bool> LOGIN_AUTOMATICALLY;
+ /**
+ * The #SHOW_OFFLINE setting specifies whether or not to show offline contacts in the
+ * roster.
+ *
+ * If set true Swift will show offline contacts; else not.
+ */
+ static const SettingsProvider::Setting<bool> SHOW_OFFLINE;
+ /**
+ * The #EXPANDED_ROSTER_GROUPS setting specifies the list of groups that are expanded
+ * in the roster UI.
+ *
+ * Its value is a string with group names seperated by newlines.
+ */
+ static const SettingsProvider::Setting<std::string> EXPANDED_ROSTER_GROUPS;
+ static const SettingsProvider::Setting<bool> PLAY_SOUNDS;
+ /**
+ * The #HIGHLIGHT_RULES setting specifies the highlight rules and the associated actions.
+ *
+ * Its value is a Boost serialized representation.
+ */
+ static const SettingsProvider::Setting<std::string> HIGHLIGHT_RULES;
+ static const SettingsProvider::Setting<bool> SPELL_CHECKER;
+ static const SettingsProvider::Setting<std::string> DICT_PATH;
+ static const SettingsProvider::Setting<std::string> PERSONAL_DICT_PATH;
+ static const SettingsProvider::Setting<std::string> DICT_FILE;
+ /**
+ * The #INVITE_AUTO_ACCEPT_MODE setting specifies how to handle invites to chat rooms.
+ *
+ * Supported values are:
+ * - "no" : It is up to the user whether to accept the invitation and enter a room or not.
+ * - "presence" : The invitation is automatically accepted if it is from a contact that is
+ * already allowed to see the user's presence status.
+ * - "domain" : The invitation is automatically accepted if it is from a contact that is
+ * already allowed to see the user's presence status or from a contact of user's domain.
+ */
+ static const SettingsProvider::Setting<std::string> INVITE_AUTO_ACCEPT_MODE;
+ /**
+ * The #TRELLIS_GRID_SIZE setting specifies the dimensions of the grid used for the trellis
+ * layout.
+ *
+ * Its value is a Qt serialized representation.
+ */
+ static const SettingsProvider::Setting<std::string> TRELLIS_GRID_SIZE;
+ /**
+ * The #TRELLIS_GRID_POSITIONS setting specifies where conversations to contacts or rooms go
+ * in the trellis grid.
+ *
+ * Its value is a Qt serialized representation.
+ */
+ static const SettingsProvider::Setting<std::string> TRELLIS_GRID_POSITIONS;
+ /**
+ * The #DISCONNECT_ON_CARD_REMOVAL setting
+ * specifies whether or not to sign out the user when
+ * the smartcard is removed.
+ *
+ * If set true Swift will sign out the user when the
+ * smart card is removed; else not.
+ */
+ static const SettingsProvider::Setting<bool> DISCONNECT_ON_CARD_REMOVAL;
+ /**
+ * The #SINGLE_SIGN_ON setting
+ * specifies whether to log in using Single Sign On.
+ * This is currently supported on Windows.
+ *
+ * If set true Swift will use GSSAPI authentication to
+ * log in the user; else not.
+ */
+ static const SettingsProvider::Setting<bool> SINGLE_SIGN_ON;
+ };
}
diff --git a/Swift/Controllers/Settings/DummySettingsProvider.h b/Swift/Controllers/Settings/DummySettingsProvider.h
index 605153e..63c0767 100644
--- a/Swift/Controllers/Settings/DummySettingsProvider.h
+++ b/Swift/Controllers/Settings/DummySettingsProvider.h
@@ -13,44 +13,44 @@
namespace Swift {
class DummySettingsProvider : public SettingsProvider {
- public:
- virtual ~DummySettingsProvider() {}
- virtual std::string getSetting(const Setting<std::string>& setting) {
- return stringValues.find(setting.getKey()) != stringValues.end() ? stringValues[setting.getKey()] : setting.getDefaultValue();
- }
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value) {
- stringValues[setting.getKey()] = value;
- onSettingChanged(setting.getKey());
- }
- virtual bool getSetting(const Setting<bool>& setting) {
- return boolValues.find(setting.getKey()) != boolValues.end() ? boolValues[setting.getKey()] : setting.getDefaultValue();
- }
- virtual void storeSetting(const Setting<bool>& setting, const bool& value) {
- boolValues[setting.getKey()] = value;
- onSettingChanged(setting.getKey());
- }
- virtual int getSetting(const Setting<int>& setting) {
- return intValues.find(setting.getKey()) != intValues.end() ? intValues[setting.getKey()] : setting.getDefaultValue();
- }
- virtual void storeSetting(const Setting<int>& setting, const int& value) {
- intValues[setting.getKey()] = value;
- onSettingChanged(setting.getKey());
- }
- virtual std::vector<std::string> getAvailableProfiles() {return std::vector<std::string>();}
- virtual void createProfile(const std::string& ) {}
- virtual void removeProfile(const std::string& ) {}
- virtual bool getIsSettingFinal(const std::string& settingPath) {return finals.count(settingPath);}
- void setFinal(const std::string& settingPath) {
- finals.insert(settingPath);
- }
- virtual bool hasSetting(const std::string& key) {
- return stringValues.find(key) != stringValues.end() || intValues.find(key) != intValues.end() || boolValues.find(key) != boolValues.end();
- }
- private:
- std::map<std::string, std::string> stringValues;
- std::map<std::string, int> intValues;
- std::map<std::string, bool> boolValues;
- std::set<std::string> finals;
+ public:
+ virtual ~DummySettingsProvider() {}
+ virtual std::string getSetting(const Setting<std::string>& setting) {
+ return stringValues.find(setting.getKey()) != stringValues.end() ? stringValues[setting.getKey()] : setting.getDefaultValue();
+ }
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value) {
+ stringValues[setting.getKey()] = value;
+ onSettingChanged(setting.getKey());
+ }
+ virtual bool getSetting(const Setting<bool>& setting) {
+ return boolValues.find(setting.getKey()) != boolValues.end() ? boolValues[setting.getKey()] : setting.getDefaultValue();
+ }
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value) {
+ boolValues[setting.getKey()] = value;
+ onSettingChanged(setting.getKey());
+ }
+ virtual int getSetting(const Setting<int>& setting) {
+ return intValues.find(setting.getKey()) != intValues.end() ? intValues[setting.getKey()] : setting.getDefaultValue();
+ }
+ virtual void storeSetting(const Setting<int>& setting, const int& value) {
+ intValues[setting.getKey()] = value;
+ onSettingChanged(setting.getKey());
+ }
+ virtual std::vector<std::string> getAvailableProfiles() {return std::vector<std::string>();}
+ virtual void createProfile(const std::string& ) {}
+ virtual void removeProfile(const std::string& ) {}
+ virtual bool getIsSettingFinal(const std::string& settingPath) {return finals.count(settingPath);}
+ void setFinal(const std::string& settingPath) {
+ finals.insert(settingPath);
+ }
+ virtual bool hasSetting(const std::string& key) {
+ return stringValues.find(key) != stringValues.end() || intValues.find(key) != intValues.end() || boolValues.find(key) != boolValues.end();
+ }
+ private:
+ std::map<std::string, std::string> stringValues;
+ std::map<std::string, int> intValues;
+ std::map<std::string, bool> boolValues;
+ std::set<std::string> finals;
};
}
diff --git a/Swift/Controllers/Settings/SettingsProvider.h b/Swift/Controllers/Settings/SettingsProvider.h
index 29e26b5..a804235 100644
--- a/Swift/Controllers/Settings/SettingsProvider.h
+++ b/Swift/Controllers/Settings/SettingsProvider.h
@@ -15,57 +15,57 @@ namespace Swift {
class SettingsProvider {
- public:
- template <typename T>
- class Setting {
- public:
- Setting(const std::string& key, const T& defaultValue) : key(key), defaultValue(defaultValue) {
-
- }
-
- const std::string& getKey() const {
- return key;
- }
-
- const T& getDefaultValue() const {
- return defaultValue;
- }
-
- private:
- std::string key;
- T defaultValue;
- };
-
- public:
- virtual ~SettingsProvider() {}
- virtual std::string getSetting(const Setting<std::string>& setting) = 0;
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value) = 0;
- virtual bool getSetting(const Setting<bool>& setting) = 0;
- virtual void storeSetting(const Setting<bool>& setting, const bool& value) = 0;
- virtual int getSetting(const Setting<int>& setting) = 0;
- virtual void storeSetting(const Setting<int>& setting, const int& value) = 0;
-
- virtual std::vector<std::string> getAvailableProfiles() = 0;
- virtual void createProfile(const std::string& profile) = 0;
- virtual void removeProfile(const std::string& profile) = 0;
- /** A final setting is one that this settings provider says may not be overriden by lower priority profiles.
- * e.g. An Administrator-set configuration to disallow saving user passwords could not be overridden by the user.
- */
- template<typename T>
- bool getIsSettingFinal(const Setting<T>& setting) {
- return getIsSettingFinal(setting.getKey());
- }
- virtual bool hasSetting(const std::string& key) = 0;
-
- friend class SettingsProviderHierachy;
- protected:
- virtual bool getIsSettingFinal(const std::string& settingPath) = 0;
-
- public:
- /**
- * Emitted when a setting is changed.
- */
- boost::signal<void (const std::string& /*Setting's Path*/)> onSettingChanged;
+ public:
+ template <typename T>
+ class Setting {
+ public:
+ Setting(const std::string& key, const T& defaultValue) : key(key), defaultValue(defaultValue) {
+
+ }
+
+ const std::string& getKey() const {
+ return key;
+ }
+
+ const T& getDefaultValue() const {
+ return defaultValue;
+ }
+
+ private:
+ std::string key;
+ T defaultValue;
+ };
+
+ public:
+ virtual ~SettingsProvider() {}
+ virtual std::string getSetting(const Setting<std::string>& setting) = 0;
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value) = 0;
+ virtual bool getSetting(const Setting<bool>& setting) = 0;
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value) = 0;
+ virtual int getSetting(const Setting<int>& setting) = 0;
+ virtual void storeSetting(const Setting<int>& setting, const int& value) = 0;
+
+ virtual std::vector<std::string> getAvailableProfiles() = 0;
+ virtual void createProfile(const std::string& profile) = 0;
+ virtual void removeProfile(const std::string& profile) = 0;
+ /** A final setting is one that this settings provider says may not be overriden by lower priority profiles.
+ * e.g. An Administrator-set configuration to disallow saving user passwords could not be overridden by the user.
+ */
+ template<typename T>
+ bool getIsSettingFinal(const Setting<T>& setting) {
+ return getIsSettingFinal(setting.getKey());
+ }
+ virtual bool hasSetting(const std::string& key) = 0;
+
+ friend class SettingsProviderHierachy;
+ protected:
+ virtual bool getIsSettingFinal(const std::string& settingPath) = 0;
+
+ public:
+ /**
+ * Emitted when a setting is changed.
+ */
+ boost::signal<void (const std::string& /*Setting's Path*/)> onSettingChanged;
};
}
diff --git a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
index a349417..5156d14 100644
--- a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
+++ b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
@@ -14,102 +14,102 @@ SettingsProviderHierachy::~SettingsProviderHierachy() {
}
bool SettingsProviderHierachy::hasSetting(const std::string& key) {
- foreach (SettingsProvider* provider, providers_) {
- if (provider->hasSetting(key)) {
- return true;
- }
- }
- return false;
+ foreach (SettingsProvider* 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_) {
- std::string providerSetting = provider->getSetting(setting);
- if (provider->hasSetting(setting.getKey())) {
- value = providerSetting;
- }
- if (provider->getIsSettingFinal(setting.getKey())) {
- return value;
- }
- }
- return value;
+ std::string value = setting.getDefaultValue();
+ foreach (SettingsProvider* 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);
- }
+ if (!getIsSettingFinal(setting.getKey())) {
+ getWritableProvider()->storeSetting(setting, settingValue);
+ }
}
bool SettingsProviderHierachy::getSetting(const Setting<bool>& setting) {
- bool value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
- bool providerSetting = provider->getSetting(setting);
- if (provider->hasSetting(setting.getKey())) {
- value = providerSetting;
- if (provider->getIsSettingFinal(setting.getKey())) {
- return providerSetting;
- }
- }
- }
- return value;
+ bool value = setting.getDefaultValue();
+ foreach (SettingsProvider* 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);
- }
+ if (!getIsSettingFinal(setting.getKey())) {
+ getWritableProvider()->storeSetting(setting, settingValue);
+ }
}
int SettingsProviderHierachy::getSetting(const Setting<int>& setting) {
- int value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
- int providerSetting = provider->getSetting(setting);
- if (provider->hasSetting(setting.getKey())) {
- value = providerSetting;
- if (provider->getIsSettingFinal(setting.getKey())) {
- return providerSetting;
- }
- }
- }
- return value;
+ int value = setting.getDefaultValue();
+ foreach (SettingsProvider* 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);
- }
+ if (!getIsSettingFinal(setting.getKey())) {
+ getWritableProvider()->storeSetting(setting, settingValue);
+ }
}
std::vector<std::string> SettingsProviderHierachy::getAvailableProfiles() {
- /* Always pull profiles from the topmost */
- return getWritableProvider()->getAvailableProfiles();
+ /* Always pull profiles from the topmost */
+ return getWritableProvider()->getAvailableProfiles();
}
void SettingsProviderHierachy::createProfile(const std::string& profile) {
- return getWritableProvider()->createProfile(profile);
+ return getWritableProvider()->createProfile(profile);
}
void SettingsProviderHierachy::removeProfile(const std::string& profile) {
- return getWritableProvider()->removeProfile(profile);
+ return getWritableProvider()->removeProfile(profile);
}
bool SettingsProviderHierachy::getIsSettingFinal(const std::string& settingPath) {
- bool isFinal = false;
- foreach (SettingsProvider* provider, providers_) {
- isFinal |= provider->getIsSettingFinal(settingPath);
- }
- return isFinal;
+ bool isFinal = false;
+ foreach (SettingsProvider* provider, providers_) {
+ isFinal |= provider->getIsSettingFinal(settingPath);
+ }
+ return isFinal;
}
SettingsProvider* SettingsProviderHierachy::getWritableProvider() {
- return providers_.back();
+ return providers_.back();
}
void SettingsProviderHierachy::addProviderToTopOfStack(SettingsProvider* provider) {
- providers_.push_back(provider);
- provider->onSettingChanged.connect(onSettingChanged);
+ providers_.push_back(provider);
+ provider->onSettingChanged.connect(onSettingChanged);
}
}
diff --git a/Swift/Controllers/Settings/SettingsProviderHierachy.h b/Swift/Controllers/Settings/SettingsProviderHierachy.h
index 9efbdcb..a68ff36 100644
--- a/Swift/Controllers/Settings/SettingsProviderHierachy.h
+++ b/Swift/Controllers/Settings/SettingsProviderHierachy.h
@@ -11,34 +11,34 @@
namespace Swift {
class SettingsProviderHierachy : public SettingsProvider {
- public:
- virtual ~SettingsProviderHierachy();
- virtual std::string getSetting(const Setting<std::string>& setting);
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
- virtual bool getSetting(const Setting<bool>& setting);
- virtual void storeSetting(const Setting<bool>& setting, const bool& value);
- virtual int getSetting(const Setting<int>& setting);
- virtual void storeSetting(const Setting<int>& setting, const int& value);
- virtual std::vector<std::string> getAvailableProfiles();
- virtual void createProfile(const std::string& profile);
- virtual void removeProfile(const std::string& profile);
- virtual bool hasSetting(const std::string& key);
- protected:
- virtual bool getIsSettingFinal(const std::string& settingPath);
-
- public:
- /**
- * Adds a provider less significant than any already added.
- * This means that if an existing provider has a setting, this provider won't be asked.
- * Any settings will be pushed into the topmost (least significant) provider.
- * Does not take ownership of provider.
- */
- void addProviderToTopOfStack(SettingsProvider* provider);
- private:
- SettingsProvider* getWritableProvider();
- private:
- /* Start/Left is most significant (lowest), left overrides right.*/
- std::vector<SettingsProvider*> providers_;
+ public:
+ virtual ~SettingsProviderHierachy();
+ virtual std::string getSetting(const Setting<std::string>& setting);
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
+ virtual bool getSetting(const Setting<bool>& setting);
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value);
+ virtual int getSetting(const Setting<int>& setting);
+ virtual void storeSetting(const Setting<int>& setting, const int& value);
+ virtual std::vector<std::string> getAvailableProfiles();
+ virtual void createProfile(const std::string& profile);
+ virtual void removeProfile(const std::string& profile);
+ virtual bool hasSetting(const std::string& key);
+ protected:
+ virtual bool getIsSettingFinal(const std::string& settingPath);
+
+ public:
+ /**
+ * Adds a provider less significant than any already added.
+ * This means that if an existing provider has a setting, this provider won't be asked.
+ * Any settings will be pushed into the topmost (least significant) provider.
+ * Does not take ownership of provider.
+ */
+ void addProviderToTopOfStack(SettingsProvider* provider);
+ private:
+ SettingsProvider* getWritableProvider();
+ private:
+ /* Start/Left is most significant (lowest), left overrides right.*/
+ std::vector<SettingsProvider*> providers_;
};
}
diff --git a/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp b/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp
index 11d5c11..5822add 100644
--- a/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp
+++ b/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp
@@ -15,77 +15,77 @@ using namespace Swift;
using namespace std;
class SettingsProviderHierachyTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SettingsProviderHierachyTest);
- CPPUNIT_TEST(testEmpty);
- CPPUNIT_TEST(testTop);
- CPPUNIT_TEST(testBottom);
- CPPUNIT_TEST(testBoth);
- CPPUNIT_TEST(testTopDefault);
- CPPUNIT_TEST(testBottomOverrides);
- CPPUNIT_TEST(testFinal);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SettingsProviderHierachyTest);
+ CPPUNIT_TEST(testEmpty);
+ CPPUNIT_TEST(testTop);
+ CPPUNIT_TEST(testBottom);
+ CPPUNIT_TEST(testBoth);
+ CPPUNIT_TEST(testTopDefault);
+ CPPUNIT_TEST(testBottomOverrides);
+ CPPUNIT_TEST(testFinal);
+ CPPUNIT_TEST_SUITE_END();
public:
- SettingsProviderHierachyTest() : setting1("somekey", 42) {}
+ SettingsProviderHierachyTest() : setting1("somekey", 42) {}
- void setUp() {
- bottom = new DummySettingsProvider();
- top = new DummySettingsProvider();
- testling = new SettingsProviderHierachy();
- testling->addProviderToTopOfStack(bottom);
- testling->addProviderToTopOfStack(top);
- }
+ void setUp() {
+ bottom = new DummySettingsProvider();
+ top = new DummySettingsProvider();
+ testling = new SettingsProviderHierachy();
+ testling->addProviderToTopOfStack(bottom);
+ testling->addProviderToTopOfStack(top);
+ }
- void tearDown() {
- delete testling;
- delete top;
- delete bottom;
- }
+ void tearDown() {
+ delete testling;
+ delete top;
+ delete bottom;
+ }
- void testEmpty() {
- CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1));
- }
+ void testEmpty() {
+ CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1));
+ }
- void testTop() {
- top->storeSetting(setting1, 37);
- CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1));
- }
+ void testTop() {
+ top->storeSetting(setting1, 37);
+ CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1));
+ }
- void testBottom() {
- bottom->storeSetting(setting1, 17);
- CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
- }
+ void testBottom() {
+ bottom->storeSetting(setting1, 17);
+ CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
+ }
- void testBoth() {
- bottom->storeSetting(setting1, 17);
- top->storeSetting(setting1, 37);
- CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1));
- }
+ void testBoth() {
+ bottom->storeSetting(setting1, 17);
+ top->storeSetting(setting1, 37);
+ CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1));
+ }
- void testTopDefault() {
- bottom->storeSetting(setting1, 17);
- top->storeSetting(setting1, 42);
- CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1));
- }
+ void testTopDefault() {
+ bottom->storeSetting(setting1, 17);
+ top->storeSetting(setting1, 42);
+ CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1));
+ }
- void testBottomOverrides() {
- bottom->storeSetting(setting1, 17);
- bottom->setFinal(setting1.getKey());
- top->storeSetting(setting1, 5);
- CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
- }
+ void testBottomOverrides() {
+ bottom->storeSetting(setting1, 17);
+ bottom->setFinal(setting1.getKey());
+ top->storeSetting(setting1, 5);
+ CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
+ }
- void testFinal() {
- bottom->storeSetting(setting1, 17);
- bottom->setFinal(setting1.getKey());
- testling->storeSetting(setting1, 5);
- CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
- }
+ void testFinal() {
+ bottom->storeSetting(setting1, 17);
+ bottom->setFinal(setting1.getKey());
+ testling->storeSetting(setting1, 5);
+ CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1));
+ }
private:
- SettingsProviderHierachy* testling;
- DummySettingsProvider* bottom;
- DummySettingsProvider* top;
- SettingsProvider::Setting<int> setting1;
+ SettingsProviderHierachy* testling;
+ DummySettingsProvider* bottom;
+ DummySettingsProvider* top;
+ SettingsProvider::Setting<int> setting1;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SettingsProviderHierachyTest);
diff --git a/Swift/Controllers/Settings/XMLSettingsProvider.cpp b/Swift/Controllers/Settings/XMLSettingsProvider.cpp
index 548f36f..4dfb8bd 100644
--- a/Swift/Controllers/Settings/XMLSettingsProvider.cpp
+++ b/Swift/Controllers/Settings/XMLSettingsProvider.cpp
@@ -16,20 +16,20 @@
namespace Swift {
XMLSettingsProvider::XMLSettingsProvider(const std::string& xmlConfig) : level_(0) {
- if (!xmlConfig.empty()) {
- PlatformXMLParserFactory factory;
- XMLParser* parser = factory.createXMLParser(this);
- if (parser->parse(xmlConfig)) {
- SWIFT_LOG(debug) << "Found and parsed system config" << std::endl;
- }
- else {
- SWIFT_LOG(debug) << "Found invalid system config" << std::endl;
- }
- delete parser;
- }
- else {
- SWIFT_LOG(debug) << "No system config found" << std::endl;
- }
+ if (!xmlConfig.empty()) {
+ PlatformXMLParserFactory factory;
+ XMLParser* parser = factory.createXMLParser(this);
+ if (parser->parse(xmlConfig)) {
+ SWIFT_LOG(debug) << "Found and parsed system config" << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "Found invalid system config" << std::endl;
+ }
+ delete parser;
+ }
+ else {
+ SWIFT_LOG(debug) << "No system config found" << std::endl;
+ }
}
XMLSettingsProvider::~XMLSettingsProvider() {
@@ -37,89 +37,89 @@ XMLSettingsProvider::~XMLSettingsProvider() {
}
bool XMLSettingsProvider::hasSetting(const std::string& key) {
- return (values_.find(key) != values_.end());
+ return (values_.find(key) != values_.end());
}
std::string XMLSettingsProvider::getSetting(const Setting<std::string>& setting) {
- if (values_.find(setting.getKey()) != values_.end()) {
- std::string value = values_[setting.getKey()];
- return value;
- }
- return setting.getDefaultValue();
+ if (values_.find(setting.getKey()) != values_.end()) {
+ std::string value = values_[setting.getKey()];
+ return value;
+ }
+ return setting.getDefaultValue();
}
void XMLSettingsProvider::storeSetting(const Setting<std::string>& /*settingPath*/, const std::string& /*settingValue*/) {
- assert(false);
+ assert(false);
}
bool XMLSettingsProvider::getSetting(const Setting<bool>& setting) {
- if (values_.find(setting.getKey()) != values_.end()) {
- std::string value = values_[setting.getKey()];
- return boost::iequals(value, "true") || value == "1";
- }
- return setting.getDefaultValue();
+ if (values_.find(setting.getKey()) != values_.end()) {
+ std::string value = values_[setting.getKey()];
+ return boost::iequals(value, "true") || value == "1";
+ }
+ return setting.getDefaultValue();
}
void XMLSettingsProvider::storeSetting(const Setting<bool>& /*settingPath*/, const bool& /*settingValue*/) {
- assert(false);
+ assert(false);
}
int XMLSettingsProvider::getSetting(const Setting<int>& setting) {
- if (values_.find(setting.getKey()) != values_.end()) {
- std::string value = values_[setting.getKey()];
- try {
- return value.empty() ? setting.getDefaultValue() : boost::lexical_cast<int>(value);;
- }
- catch(boost::bad_lexical_cast &) {}
- }
- return setting.getDefaultValue();
+ if (values_.find(setting.getKey()) != values_.end()) {
+ std::string value = values_[setting.getKey()];
+ try {
+ return value.empty() ? setting.getDefaultValue() : boost::lexical_cast<int>(value);;
+ }
+ catch(boost::bad_lexical_cast &) {}
+ }
+ return setting.getDefaultValue();
}
void XMLSettingsProvider::storeSetting(const Setting<int>& /*settingPath*/, const int& /*settingValue*/) {
- assert(false);
+ assert(false);
}
std::vector<std::string> XMLSettingsProvider::getAvailableProfiles() {
- assert(false);
- return std::vector<std::string>();
+ assert(false);
+ return std::vector<std::string>();
}
void XMLSettingsProvider::createProfile(const std::string& /*profile*/) {
- assert(false);
+ assert(false);
}
void XMLSettingsProvider::removeProfile(const std::string& /*profile*/) {
- assert(false);
+ assert(false);
}
bool XMLSettingsProvider::getIsSettingFinal(const std::string& settingPath) {
- return finals_.count(settingPath);
+ return finals_.count(settingPath);
}
void XMLSettingsProvider::handleStartElement(const std::string& element, const std::string& /*ns*/, const AttributeMap& attributes) {
- level_++;
- if (level_ == SettingLevel) {
- if (attributes.getBoolAttribute("final", false)) {
- finals_.insert(element);
- }
- currentElement_ = element;
- currentText_ = "";
- }
+ level_++;
+ if (level_ == SettingLevel) {
+ if (attributes.getBoolAttribute("final", false)) {
+ finals_.insert(element);
+ }
+ currentElement_ = element;
+ currentText_ = "";
+ }
}
void XMLSettingsProvider::handleEndElement(const std::string& /*element*/, const std::string& /*ns*/) {
- if (level_ == SettingLevel) {
- values_[currentElement_] = currentText_;
- SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_ << std::endl;
- }
- level_--;
+ if (level_ == SettingLevel) {
+ values_[currentElement_] = currentText_;
+ SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_ << std::endl;
+ }
+ level_--;
}
void XMLSettingsProvider::handleCharacterData(const std::string& data) {
- if (level_ >= SettingLevel) {
- currentText_ += data;
- }
+ if (level_ >= SettingLevel) {
+ currentText_ += data;
+ }
}
diff --git a/Swift/Controllers/Settings/XMLSettingsProvider.h b/Swift/Controllers/Settings/XMLSettingsProvider.h
index 2dbb23c..5fd82cf 100644
--- a/Swift/Controllers/Settings/XMLSettingsProvider.h
+++ b/Swift/Controllers/Settings/XMLSettingsProvider.h
@@ -16,40 +16,40 @@
namespace Swift {
class XMLSettingsProvider : public SettingsProvider, public XMLParserClient {
- public:
- XMLSettingsProvider(const std::string& xmlConfig);
- virtual ~XMLSettingsProvider();
- virtual std::string getSetting(const Setting<std::string>& setting);
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
- virtual bool getSetting(const Setting<bool>& setting);
- virtual void storeSetting(const Setting<bool>& setting, const bool& value);
- virtual int getSetting(const Setting<int>& setting);
- virtual void storeSetting(const Setting<int>& setting, const int& value);
- virtual std::vector<std::string> getAvailableProfiles();
- virtual void createProfile(const std::string& profile);
- virtual void removeProfile(const std::string& profile);
- virtual bool hasSetting(const std::string& key);
-
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string& ns);
- virtual void handleCharacterData(const std::string& data);
-
- protected:
- virtual bool getIsSettingFinal(const std::string& settingPath);
- private:
- std::map<std::string /*settingPath*/, std::string /*settingValue*/> values_;
- /* Settings that are final*/
- std::set<std::string /*settingPath*/> finals_;
-
- enum Level {
- TopLevel = 0,
- SettingLevel = 2
- };
-
- int level_;
- std::string currentElement_;
- std::string currentText_;
+ public:
+ XMLSettingsProvider(const std::string& xmlConfig);
+ virtual ~XMLSettingsProvider();
+ virtual std::string getSetting(const Setting<std::string>& setting);
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
+ virtual bool getSetting(const Setting<bool>& setting);
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value);
+ virtual int getSetting(const Setting<int>& setting);
+ virtual void storeSetting(const Setting<int>& setting, const int& value);
+ virtual std::vector<std::string> getAvailableProfiles();
+ virtual void createProfile(const std::string& profile);
+ virtual void removeProfile(const std::string& profile);
+ virtual bool hasSetting(const std::string& key);
+
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string& ns);
+ virtual void handleCharacterData(const std::string& data);
+
+ protected:
+ virtual bool getIsSettingFinal(const std::string& settingPath);
+ private:
+ std::map<std::string /*settingPath*/, std::string /*settingValue*/> values_;
+ /* Settings that are final*/
+ std::set<std::string /*settingPath*/> finals_;
+
+ enum Level {
+ TopLevel = 0,
+ SettingLevel = 2
+ };
+
+ int level_;
+ std::string currentElement_;
+ std::string currentText_;
};
}
diff --git a/Swift/Controllers/ShowProfileController.cpp b/Swift/Controllers/ShowProfileController.cpp
index 9e94392..bf5eb1e 100644
--- a/Swift/Controllers/ShowProfileController.cpp
+++ b/Swift/Controllers/ShowProfileController.cpp
@@ -25,57 +25,57 @@
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));
+ 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) {
- jidWndPair.second->onWindowAboutToBeClosed.disconnect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1));
- delete jidWndPair.second;
- }
+ typedef std::pair<JID, ProfileWindow*> JIDProfileWindowPair;
+ foreach(const JIDProfileWindowPair& 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));
+ 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 = boost::dynamic_pointer_cast<ShowProfileForRosterItemUIEvent>(event);
- if (!showProfileEvent) {
- return;
- }
+ ShowProfileForRosterItemUIEvent::ref showProfileEvent = boost::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();
- }
+ 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();
+ }
}
void ShowProfileController::handleVCardChanged(const JID& jid, VCard::ref vcard) {
- if (openedProfileWindows.find(jid) == openedProfileWindows.end()) {
- return;
- }
+ if (openedProfileWindows.find(jid) == openedProfileWindows.end()) {
+ return;
+ }
- ProfileWindow* profileWindow = openedProfileWindows[jid];
- profileWindow->setVCard(vcard);
- profileWindow->setProcessing(false);
- profileWindow->show();
+ ProfileWindow* profileWindow = openedProfileWindows[jid];
+ profileWindow->setVCard(vcard);
+ profileWindow->setProcessing(false);
+ profileWindow->show();
}
void ShowProfileController::handleProfileWindowAboutToBeClosed(const JID& profileJid) {
- openedProfileWindows.erase(profileJid);
+ openedProfileWindows.erase(profileJid);
}
}
diff --git a/Swift/Controllers/ShowProfileController.h b/Swift/Controllers/ShowProfileController.h
index 37fb615..4f23c19 100644
--- a/Swift/Controllers/ShowProfileController.h
+++ b/Swift/Controllers/ShowProfileController.h
@@ -18,25 +18,25 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class VCardManager;
- class ProfileWindow;
- class ProfileWindowFactory;
- class UIEventStream;
-
- class ShowProfileController {
- public:
- ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream);
- ~ShowProfileController();
-
- private:
- void handleUIEvent(UIEvent::ref event);
- void handleVCardChanged(const JID&, VCard::ref);
- void handleProfileWindowAboutToBeClosed(const JID& profileJid);
-
- private:
- VCardManager* vcardManager;
- ProfileWindowFactory* profileWindowFactory;
- UIEventStream* uiEventStream;
- std::map<JID, ProfileWindow*> openedProfileWindows;
- };
+ class VCardManager;
+ class ProfileWindow;
+ class ProfileWindowFactory;
+ class UIEventStream;
+
+ class ShowProfileController {
+ public:
+ ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream);
+ ~ShowProfileController();
+
+ private:
+ void handleUIEvent(UIEvent::ref event);
+ void handleVCardChanged(const JID&, VCard::ref);
+ void handleProfileWindowAboutToBeClosed(const JID& profileJid);
+
+ private:
+ VCardManager* vcardManager;
+ ProfileWindowFactory* profileWindowFactory;
+ UIEventStream* uiEventStream;
+ std::map<JID, ProfileWindow*> openedProfileWindows;
+ };
}
diff --git a/Swift/Controllers/SoundEventController.cpp b/Swift/Controllers/SoundEventController.cpp
index 43c8ed0..433937b 100644
--- a/Swift/Controllers/SoundEventController.cpp
+++ b/Swift/Controllers/SoundEventController.cpp
@@ -18,39 +18,39 @@
namespace Swift {
SoundEventController::SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager) {
- settings_ = settings;
- eventController_ = eventController;
- soundPlayer_ = soundPlayer;
- eventController_->onEventQueueEventAdded.connect(boost::bind(&SoundEventController::handleEventQueueEventAdded, this, _1));
- highlightManager_ = highlightManager;
- highlightManager_->onHighlight.connect(boost::bind(&SoundEventController::handleHighlight, this, _1));
+ settings_ = settings;
+ eventController_ = eventController;
+ soundPlayer_ = soundPlayer;
+ eventController_->onEventQueueEventAdded.connect(boost::bind(&SoundEventController::handleEventQueueEventAdded, this, _1));
+ highlightManager_ = highlightManager;
+ highlightManager_->onHighlight.connect(boost::bind(&SoundEventController::handleHighlight, this, _1));
- settings_->onSettingChanged.connect(boost::bind(&SoundEventController::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.connect(boost::bind(&SoundEventController::handleSettingChanged, this, _1));
- playSounds_ = settings->getSetting(SettingConstants::PLAY_SOUNDS);
+ playSounds_ = settings->getSetting(SettingConstants::PLAY_SOUNDS);
}
void SoundEventController::handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event) {
- if (playSounds_ && boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event)) {
- soundPlayer_->playSound(SoundPlayer::MessageReceived, "");
- }
+ if (playSounds_ && boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event)) {
+ soundPlayer_->playSound(SoundPlayer::MessageReceived, "");
+ }
}
void SoundEventController::handleHighlight(const HighlightAction& action) {
- if (playSounds_ && action.playSound()) {
- soundPlayer_->playSound(SoundPlayer::MessageReceived, action.getSoundFile());
- }
+ if (playSounds_ && action.playSound()) {
+ soundPlayer_->playSound(SoundPlayer::MessageReceived, action.getSoundFile());
+ }
}
void SoundEventController::setPlaySounds(bool playSounds) {
- playSounds_ = playSounds;
- settings_->storeSetting(SettingConstants::PLAY_SOUNDS, playSounds);
+ playSounds_ = playSounds;
+ settings_->storeSetting(SettingConstants::PLAY_SOUNDS, playSounds);
}
void SoundEventController::handleSettingChanged(const std::string& settingPath) {
- if (SettingConstants::PLAY_SOUNDS.getKey() == settingPath) {
- playSounds_ = settings_->getSetting(SettingConstants::PLAY_SOUNDS);
- }
+ if (SettingConstants::PLAY_SOUNDS.getKey() == settingPath) {
+ playSounds_ = settings_->getSetting(SettingConstants::PLAY_SOUNDS);
+ }
}
}
diff --git a/Swift/Controllers/SoundEventController.h b/Swift/Controllers/SoundEventController.h
index 88c7b00..3ea682a 100644
--- a/Swift/Controllers/SoundEventController.h
+++ b/Swift/Controllers/SoundEventController.h
@@ -13,22 +13,22 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class EventController;
- class SoundPlayer;
- class HighlightManager;
- class SoundEventController {
- public:
- SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager);
- void setPlaySounds(bool playSounds);
- bool getSoundEnabled() {return playSounds_;}
- private:
- void handleSettingChanged(const std::string& settingPath);
- void handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event);
- void handleHighlight(const HighlightAction& action);
- EventController* eventController_;
- SoundPlayer* soundPlayer_;
- bool playSounds_;
- SettingsProvider* settings_;
- HighlightManager* highlightManager_;
- };
+ class EventController;
+ class SoundPlayer;
+ class HighlightManager;
+ class SoundEventController {
+ public:
+ SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager);
+ void setPlaySounds(bool playSounds);
+ bool getSoundEnabled() {return playSounds_;}
+ private:
+ void handleSettingChanged(const std::string& settingPath);
+ void handleEventQueueEventAdded(boost::shared_ptr<StanzaEvent> event);
+ void handleHighlight(const HighlightAction& action);
+ EventController* eventController_;
+ SoundPlayer* soundPlayer_;
+ bool playSounds_;
+ SettingsProvider* settings_;
+ HighlightManager* highlightManager_;
+ };
}
diff --git a/Swift/Controllers/SoundPlayer.h b/Swift/Controllers/SoundPlayer.h
index e38cd7c..8525c6c 100644
--- a/Swift/Controllers/SoundPlayer.h
+++ b/Swift/Controllers/SoundPlayer.h
@@ -9,10 +9,10 @@
#include <string>
namespace Swift {
- class SoundPlayer {
- public:
- virtual ~SoundPlayer() {}
- enum SoundEffect{MessageReceived};
- virtual void playSound(SoundEffect sound, const std::string& soundResource) = 0;
- };
+ class SoundPlayer {
+ public:
+ virtual ~SoundPlayer() {}
+ enum SoundEffect{MessageReceived};
+ virtual void playSound(SoundEffect sound, const std::string& soundResource) = 0;
+ };
}
diff --git a/Swift/Controllers/StatusCache.cpp b/Swift/Controllers/StatusCache.cpp
index d00d7f6..ce4391d 100644
--- a/Swift/Controllers/StatusCache.cpp
+++ b/Swift/Controllers/StatusCache.cpp
@@ -24,9 +24,9 @@ namespace Swift {
static const size_t MAX_ENTRIES = 200;
StatusCache::StatusCache(ApplicationPathProvider* paths) {
- paths_ = paths;
- path_ = paths_->getDataDir() / "StatusCache";
- loadRecents();
+ paths_ = paths;
+ path_ = paths_->getDataDir() / "StatusCache";
+ loadRecents();
}
StatusCache::~StatusCache() {
@@ -34,71 +34,71 @@ StatusCache::~StatusCache() {
}
std::vector<StatusCache::PreviousStatus> StatusCache::getMatches(const std::string& substring, size_t maxCount) const {
- std::vector<PreviousStatus> matches;
- foreach (const PreviousStatus& status, previousStatuses_) {
- if (substring.empty() || (boost::algorithm::ifind_first(status.first, substring) && substring != status.first)) {
- matches.push_back(status);
- if (matches.size() == maxCount) {
- break;
- }
- }
- }
- return matches;
+ std::vector<PreviousStatus> matches;
+ foreach (const PreviousStatus& status, previousStatuses_) {
+ if (substring.empty() || (boost::algorithm::ifind_first(status.first, substring) && substring != status.first)) {
+ matches.push_back(status);
+ if (matches.size() == maxCount) {
+ break;
+ }
+ }
+ }
+ return matches;
}
void StatusCache::addRecent(const std::string& text, StatusShow::Type type) {
- if (text.empty()) {
- return;
- }
- previousStatuses_.remove_if(lambda::bind(&PreviousStatus::first, lambda::_1) == text && lambda::bind(&PreviousStatus::second, lambda::_1) == type);
- previousStatuses_.push_front(PreviousStatus(text, type));
- for (size_t i = previousStatuses_.size(); i > MAX_ENTRIES; i--) {
- previousStatuses_.pop_back();
- }
- saveRecents();
+ if (text.empty()) {
+ return;
+ }
+ previousStatuses_.remove_if(lambda::bind(&PreviousStatus::first, lambda::_1) == text && lambda::bind(&PreviousStatus::second, lambda::_1) == type);
+ previousStatuses_.push_front(PreviousStatus(text, type));
+ for (size_t i = previousStatuses_.size(); i > MAX_ENTRIES; i--) {
+ previousStatuses_.pop_back();
+ }
+ saveRecents();
}
void StatusCache::loadRecents() {
- try {
- if (boost::filesystem::exists(path_)) {
- ByteArray data;
- readByteArrayFromFile(data, path_);
- std::string stringData = byteArrayToString(data);
- std::vector<std::string> lines;
- boost::split(lines, stringData, boost::is_any_of("\n"));
- foreach (const std::string& line, lines) {
- std::vector<std::string> bits;
- boost::split(bits, line, boost::is_any_of("\t"));
- if (bits.size() < 2) {
- continue;
- }
- StatusShow::Type type;
- type = static_cast<StatusShow::Type>(boost::lexical_cast<size_t>(bits[0]));
- previousStatuses_.push_back(PreviousStatus(boost::trim_copy(bits[1]), type));
- }
- }
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
+ try {
+ if (boost::filesystem::exists(path_)) {
+ ByteArray data;
+ readByteArrayFromFile(data, path_);
+ std::string stringData = byteArrayToString(data);
+ std::vector<std::string> lines;
+ boost::split(lines, stringData, boost::is_any_of("\n"));
+ foreach (const std::string& line, lines) {
+ std::vector<std::string> bits;
+ boost::split(bits, line, boost::is_any_of("\t"));
+ if (bits.size() < 2) {
+ continue;
+ }
+ StatusShow::Type type;
+ type = static_cast<StatusShow::Type>(boost::lexical_cast<size_t>(bits[0]));
+ previousStatuses_.push_back(PreviousStatus(boost::trim_copy(bits[1]), type));
+ }
+ }
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
}
void StatusCache::saveRecents() {
- try {
- if (!boost::filesystem::exists(path_.parent_path())) {
- boost::filesystem::create_directories(path_.parent_path());
- }
- boost::filesystem::ofstream file(path_);
- foreach (const PreviousStatus& recent, previousStatuses_) {
- std::string message = recent.first;
- boost::replace_all(message, "\t", " ");
- file << recent.second << "\t" << message << std::endl;
- }
- file.close();
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
+ try {
+ if (!boost::filesystem::exists(path_.parent_path())) {
+ boost::filesystem::create_directories(path_.parent_path());
+ }
+ boost::filesystem::ofstream file(path_);
+ foreach (const PreviousStatus& recent, previousStatuses_) {
+ std::string message = recent.first;
+ boost::replace_all(message, "\t", " ");
+ file << recent.second << "\t" << message << std::endl;
+ }
+ file.close();
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
}
}
diff --git a/Swift/Controllers/StatusCache.h b/Swift/Controllers/StatusCache.h
index 0ed85d6..033cde0 100644
--- a/Swift/Controllers/StatusCache.h
+++ b/Swift/Controllers/StatusCache.h
@@ -17,24 +17,24 @@
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
- class ApplicationPathProvider;
- class StatusCache {
- public:
- typedef std::pair<std::string, StatusShow::Type> PreviousStatus;
- public:
- StatusCache(ApplicationPathProvider* paths);
- ~StatusCache();
-
- std::vector<PreviousStatus> getMatches(const std::string& substring, size_t maxCount) const;
- void addRecent(const std::string& text, StatusShow::Type type);
- private:
- void saveRecents();
- void loadRecents();
- private:
- boost::filesystem::path path_;
- std::list<PreviousStatus> previousStatuses_;
- ApplicationPathProvider* paths_;
- };
+ class ApplicationPathProvider;
+ class StatusCache {
+ public:
+ typedef std::pair<std::string, StatusShow::Type> PreviousStatus;
+ public:
+ StatusCache(ApplicationPathProvider* paths);
+ ~StatusCache();
+
+ std::vector<PreviousStatus> getMatches(const std::string& substring, size_t maxCount) const;
+ void addRecent(const std::string& text, StatusShow::Type type);
+ private:
+ void saveRecents();
+ void loadRecents();
+ private:
+ boost::filesystem::path path_;
+ std::list<PreviousStatus> previousStatuses_;
+ ApplicationPathProvider* paths_;
+ };
}
diff --git a/Swift/Controllers/StatusTracker.cpp b/Swift/Controllers/StatusTracker.cpp
index e42b99e..51db328 100644
--- a/Swift/Controllers/StatusTracker.cpp
+++ b/Swift/Controllers/StatusTracker.cpp
@@ -13,46 +13,46 @@
namespace Swift {
StatusTracker::StatusTracker() {
- isAutoAway_ = false;
- queuedPresence_ = boost::make_shared<Presence>();
+ isAutoAway_ = false;
+ queuedPresence_ = boost::make_shared<Presence>();
}
boost::shared_ptr<Presence> StatusTracker::getNextPresence() {
- boost::shared_ptr<Presence> presence;
- if (isAutoAway_) {
- presence = boost::make_shared<Presence>();
- presence->setShow(StatusShow::Away);
- presence->setStatus(queuedPresence_->getStatus());
- presence->addPayload(boost::make_shared<Idle>(isAutoAwaySince_));
- } else {
- presence = queuedPresence_;
- }
- return presence;
+ boost::shared_ptr<Presence> presence;
+ if (isAutoAway_) {
+ presence = boost::make_shared<Presence>();
+ presence->setShow(StatusShow::Away);
+ presence->setStatus(queuedPresence_->getStatus());
+ presence->addPayload(boost::make_shared<Idle>(isAutoAwaySince_));
+ } else {
+ presence = queuedPresence_;
+ }
+ return presence;
}
void StatusTracker::setRequestedPresence(boost::shared_ptr<Presence> presence) {
- isAutoAway_ = false;
- queuedPresence_ = presence;
-// if (presence->getType() == Presence::Unavailable) {
-// queuedPresence_ = boost::make_shared<Presence>();
-// }
+ isAutoAway_ = false;
+ queuedPresence_ = presence;
+// if (presence->getType() == Presence::Unavailable) {
+// queuedPresence_ = boost::make_shared<Presence>();
+// }
}
bool StatusTracker::goAutoAway(const int& seconds) {
- if (queuedPresence_->getShow() != StatusShow::Online) {
- return false;
- }
- isAutoAway_ = true;
- isAutoAwaySince_ = boost::posix_time::second_clock::universal_time() - boost::posix_time::seconds(seconds);
- return true;
+ if (queuedPresence_->getShow() != StatusShow::Online) {
+ return false;
+ }
+ isAutoAway_ = true;
+ isAutoAwaySince_ = boost::posix_time::second_clock::universal_time() - boost::posix_time::seconds(seconds);
+ return true;
}
bool StatusTracker::goAutoUnAway() {
- if (!isAutoAway_) {
- return false;
- }
- isAutoAway_ = false;
- return true;
+ if (!isAutoAway_) {
+ return false;
+ }
+ isAutoAway_ = false;
+ return true;
}
}
diff --git a/Swift/Controllers/StatusTracker.h b/Swift/Controllers/StatusTracker.h
index 092ce43..cf92781 100644
--- a/Swift/Controllers/StatusTracker.h
+++ b/Swift/Controllers/StatusTracker.h
@@ -13,16 +13,16 @@
namespace Swift {
- class StatusTracker {
- public:
- StatusTracker();
- boost::shared_ptr<Presence> getNextPresence();
- void setRequestedPresence(boost::shared_ptr<Presence> presence);
- bool goAutoAway(const int& seconds);
- bool goAutoUnAway();
- private:
- boost::shared_ptr<Presence> queuedPresence_;
- bool isAutoAway_;
- boost::posix_time::ptime isAutoAwaySince_;
- };
+ class StatusTracker {
+ public:
+ StatusTracker();
+ boost::shared_ptr<Presence> getNextPresence();
+ void setRequestedPresence(boost::shared_ptr<Presence> presence);
+ bool goAutoAway(const int& seconds);
+ bool goAutoUnAway();
+ private:
+ boost::shared_ptr<Presence> queuedPresence_;
+ bool isAutoAway_;
+ boost::posix_time::ptime isAutoAwaySince_;
+ };
}
diff --git a/Swift/Controllers/StatusUtil.cpp b/Swift/Controllers/StatusUtil.cpp
index 0c5bc21..1034863 100644
--- a/Swift/Controllers/StatusUtil.cpp
+++ b/Swift/Controllers/StatusUtil.cpp
@@ -13,16 +13,16 @@
namespace Swift {
std::string statusShowTypeToFriendlyName(StatusShow::Type type) {
- switch (type) {
- case StatusShow::Online: return QT_TRANSLATE_NOOP("", "Available");
- case StatusShow::FFC: return QT_TRANSLATE_NOOP("", "Available");
- case StatusShow::Away: return QT_TRANSLATE_NOOP("", "Away");
- case StatusShow::XA: return QT_TRANSLATE_NOOP("", "Away");
- case StatusShow::DND: return QT_TRANSLATE_NOOP("", "Busy");
- case StatusShow::None: return QT_TRANSLATE_NOOP("", "Offline");
- }
- assert(false);
- return "";
+ switch (type) {
+ case StatusShow::Online: return QT_TRANSLATE_NOOP("", "Available");
+ case StatusShow::FFC: return QT_TRANSLATE_NOOP("", "Available");
+ case StatusShow::Away: return QT_TRANSLATE_NOOP("", "Away");
+ case StatusShow::XA: return QT_TRANSLATE_NOOP("", "Away");
+ case StatusShow::DND: return QT_TRANSLATE_NOOP("", "Busy");
+ case StatusShow::None: return QT_TRANSLATE_NOOP("", "Offline");
+ }
+ assert(false);
+ return "";
}
}
diff --git a/Swift/Controllers/StatusUtil.h b/Swift/Controllers/StatusUtil.h
index 871ca0a..6872bf7 100644
--- a/Swift/Controllers/StatusUtil.h
+++ b/Swift/Controllers/StatusUtil.h
@@ -11,6 +11,6 @@
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
- std::string statusShowTypeToFriendlyName(StatusShow::Type type);
+ std::string statusShowTypeToFriendlyName(StatusShow::Type type);
}
diff --git a/Swift/Controllers/Storages/AvatarFileStorage.cpp b/Swift/Controllers/Storages/AvatarFileStorage.cpp
index 56e27e1..cded945 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.cpp
+++ b/Swift/Controllers/Storages/AvatarFileStorage.cpp
@@ -19,88 +19,88 @@
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;
- }
- }
+ 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;
+ }
+ }
}
-bool AvatarFileStorage::hasAvatar(const std::string& hash) const {
- return boost::filesystem::exists(getAvatarPath(hash));
+bool AvatarFileStorage::hasAvatar(const std::string& hash) const {
+ return boost::filesystem::exists(getAvatarPath(hash));
}
void AvatarFileStorage::addAvatar(const std::string& hash, const ByteArray& avatar) {
- assert(Hexify::hexify(crypto->getSHA1Hash(avatar)) == hash);
+ assert(Hexify::hexify(crypto->getSHA1Hash(avatar)) == hash);
- boost::filesystem::path avatarPath = getAvatarPath(hash);
- if (!boost::filesystem::exists(avatarPath.parent_path())) {
- try {
- boost::filesystem::create_directories(avatarPath.parent_path());
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- }
- boost::filesystem::ofstream file(avatarPath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out);
- file.write(reinterpret_cast<const char*>(vecptr(avatar)), static_cast<std::streamsize>(avatar.size()));
- file.close();
+ boost::filesystem::path avatarPath = getAvatarPath(hash);
+ if (!boost::filesystem::exists(avatarPath.parent_path())) {
+ try {
+ boost::filesystem::create_directories(avatarPath.parent_path());
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
+ }
+ boost::filesystem::ofstream file(avatarPath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out);
+ file.write(reinterpret_cast<const char*>(vecptr(avatar)), static_cast<std::streamsize>(avatar.size()));
+ file.close();
}
boost::filesystem::path AvatarFileStorage::getAvatarPath(const std::string& hash) const {
- return avatarsDir / hash;
+ return avatarsDir / hash;
}
ByteArray AvatarFileStorage::getAvatar(const std::string& hash) const {
- ByteArray data;
- readByteArrayFromFile(data, getAvatarPath(hash));
- return data;
+ ByteArray data;
+ readByteArrayFromFile(data, getAvatarPath(hash));
+ return data;
}
void AvatarFileStorage::setAvatarForJID(const JID& jid, const std::string& hash) {
- std::pair<JIDAvatarMap::iterator, bool> r = jidAvatars.insert(std::make_pair(jid, hash));
- if (r.second) {
- saveJIDAvatars();
- }
- else if (r.first->second != hash) {
- r.first->second = hash;
- saveJIDAvatars();
- }
+ std::pair<JIDAvatarMap::iterator, bool> r = jidAvatars.insert(std::make_pair(jid, hash));
+ if (r.second) {
+ saveJIDAvatars();
+ }
+ else if (r.first->second != hash) {
+ r.first->second = hash;
+ saveJIDAvatars();
+ }
}
std::string AvatarFileStorage::getAvatarForJID(const JID& jid) const {
- JIDAvatarMap::const_iterator i = jidAvatars.find(jid);
- return i == jidAvatars.end() ? "" : i->second;
+ JIDAvatarMap::const_iterator i = jidAvatars.find(jid);
+ return i == jidAvatars.end() ? "" : i->second;
}
void AvatarFileStorage::saveJIDAvatars() {
- try {
- boost::filesystem::ofstream file(avatarsFile);
- for (JIDAvatarMap::const_iterator i = jidAvatars.begin(); i != jidAvatars.end(); ++i) {
- file << i->second << " " << i->first.toString() << std::endl;
- }
- file.close();
- }
- catch (...) {
- std::cerr << "Error writing avatars file" << std::endl;
- }
+ try {
+ boost::filesystem::ofstream file(avatarsFile);
+ for (JIDAvatarMap::const_iterator i = jidAvatars.begin(); i != jidAvatars.end(); ++i) {
+ file << i->second << " " << i->first.toString() << std::endl;
+ }
+ file.close();
+ }
+ catch (...) {
+ std::cerr << "Error writing avatars file" << std::endl;
+ }
}
}
diff --git a/Swift/Controllers/Storages/AvatarFileStorage.h b/Swift/Controllers/Storages/AvatarFileStorage.h
index 9c6f617..41c7106 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.h
+++ b/Swift/Controllers/Storages/AvatarFileStorage.h
@@ -16,30 +16,30 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class AvatarFileStorage : public AvatarStorage {
- public:
- AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto);
+ class AvatarFileStorage : public AvatarStorage {
+ public:
+ AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto);
- virtual bool hasAvatar(const std::string& hash) const;
- virtual void addAvatar(const std::string& hash, const ByteArray& avatar);
- virtual ByteArray getAvatar(const std::string& hash) const;
+ virtual bool hasAvatar(const std::string& hash) const;
+ virtual void addAvatar(const std::string& hash, const ByteArray& avatar);
+ virtual ByteArray getAvatar(const std::string& hash) const;
- virtual boost::filesystem::path getAvatarPath(const std::string& hash) const;
+ virtual boost::filesystem::path getAvatarPath(const std::string& hash) const;
- virtual void setAvatarForJID(const JID& jid, const std::string& hash);
- virtual std::string getAvatarForJID(const JID& jid) const;
+ virtual void setAvatarForJID(const JID& jid, const std::string& hash);
+ virtual std::string getAvatarForJID(const JID& jid) const;
- private:
- void saveJIDAvatars();
+ private:
+ void saveJIDAvatars();
- private:
- boost::filesystem::path avatarsDir;
- boost::filesystem::path avatarsFile;
- CryptoProvider* crypto;
- typedef std::map<JID, std::string> JIDAvatarMap;
- JIDAvatarMap jidAvatars;
- };
+ private:
+ boost::filesystem::path avatarsDir;
+ boost::filesystem::path avatarsFile;
+ CryptoProvider* crypto;
+ typedef std::map<JID, std::string> JIDAvatarMap;
+ JIDAvatarMap jidAvatars;
+ };
}
diff --git a/Swift/Controllers/Storages/CapsFileStorage.cpp b/Swift/Controllers/Storages/CapsFileStorage.cpp
index 7b99fe0..21a99bc 100644
--- a/Swift/Controllers/Storages/CapsFileStorage.cpp
+++ b/Swift/Controllers/Storages/CapsFileStorage.cpp
@@ -20,15 +20,15 @@ CapsFileStorage::CapsFileStorage(const boost::filesystem::path& path) : path(pat
}
DiscoInfo::ref CapsFileStorage::getDiscoInfo(const std::string& hash) const {
- return DiscoInfoPersister().loadPayloadGeneric(getCapsPath(hash));
+ return DiscoInfoPersister().loadPayloadGeneric(getCapsPath(hash));
}
void CapsFileStorage::setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) {
- DiscoInfo::ref bareDiscoInfo(new DiscoInfo(*discoInfo.get()));
- bareDiscoInfo->setNode("");
- DiscoInfoPersister().savePayload(bareDiscoInfo, getCapsPath(hash));
+ DiscoInfo::ref bareDiscoInfo(new DiscoInfo(*discoInfo.get()));
+ bareDiscoInfo->setNode("");
+ DiscoInfoPersister().savePayload(bareDiscoInfo, getCapsPath(hash));
}
boost::filesystem::path CapsFileStorage::getCapsPath(const std::string& hash) const {
- return path / (Hexify::hexify(Base64::decode(hash)) + ".xml");
+ return path / (Hexify::hexify(Base64::decode(hash)) + ".xml");
}
diff --git a/Swift/Controllers/Storages/CapsFileStorage.h b/Swift/Controllers/Storages/CapsFileStorage.h
index 06dfd91..7df23f1 100644
--- a/Swift/Controllers/Storages/CapsFileStorage.h
+++ b/Swift/Controllers/Storages/CapsFileStorage.h
@@ -13,17 +13,17 @@
#include <Swiften/Disco/CapsStorage.h>
namespace Swift {
- class CapsFileStorage : public CapsStorage {
- public:
- CapsFileStorage(const boost::filesystem::path& path);
+ class CapsFileStorage : public CapsStorage {
+ public:
+ CapsFileStorage(const boost::filesystem::path& path);
- virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const;
- virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo);
+ virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const;
+ virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo);
- private:
- boost::filesystem::path getCapsPath(const std::string& hash) const;
+ private:
+ boost::filesystem::path getCapsPath(const std::string& hash) const;
- private:
- boost::filesystem::path path;
- };
+ private:
+ boost::filesystem::path path;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateFileStorage.cpp b/Swift/Controllers/Storages/CertificateFileStorage.cpp
index a549165..3fe6d54 100644
--- a/Swift/Controllers/Storages/CertificateFileStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateFileStorage.cpp
@@ -22,42 +22,42 @@ CertificateFileStorage::CertificateFileStorage(const boost::filesystem::path& pa
}
bool CertificateFileStorage::hasCertificate(Certificate::ref certificate) const {
- boost::filesystem::path certificatePath = getCertificatePath(certificate);
- if (boost::filesystem::exists(certificatePath)) {
- ByteArray data;
- readByteArrayFromFile(data, certificatePath);
- Certificate::ref storedCertificate(certificateFactory->createCertificateFromDER(data));
- if (storedCertificate && storedCertificate->toDER() == certificate->toDER()) {
- return true;
- }
- else {
- SWIFT_LOG(warning) << "Stored certificate does not match received certificate" << std::endl;
- return false;
- }
- }
- else {
- return false;
- }
+ boost::filesystem::path certificatePath = getCertificatePath(certificate);
+ if (boost::filesystem::exists(certificatePath)) {
+ ByteArray data;
+ readByteArrayFromFile(data, certificatePath);
+ Certificate::ref storedCertificate(certificateFactory->createCertificateFromDER(data));
+ if (storedCertificate && storedCertificate->toDER() == certificate->toDER()) {
+ return true;
+ }
+ else {
+ SWIFT_LOG(warning) << "Stored certificate does not match received certificate" << std::endl;
+ return false;
+ }
+ }
+ else {
+ return false;
+ }
}
void CertificateFileStorage::addCertificate(Certificate::ref certificate) {
- boost::filesystem::path certificatePath = getCertificatePath(certificate);
- if (!boost::filesystem::exists(certificatePath.parent_path())) {
- try {
- boost::filesystem::create_directories(certificatePath.parent_path());
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- }
- boost::filesystem::ofstream file(certificatePath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out);
- ByteArray data = certificate->toDER();
- file.write(reinterpret_cast<const char*>(vecptr(data)), boost::numeric_cast<std::streamsize>(data.size()));
- file.close();
+ boost::filesystem::path certificatePath = getCertificatePath(certificate);
+ if (!boost::filesystem::exists(certificatePath.parent_path())) {
+ try {
+ boost::filesystem::create_directories(certificatePath.parent_path());
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
+ }
+ boost::filesystem::ofstream file(certificatePath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out);
+ ByteArray data = certificate->toDER();
+ file.write(reinterpret_cast<const char*>(vecptr(data)), boost::numeric_cast<std::streamsize>(data.size()));
+ file.close();
}
boost::filesystem::path CertificateFileStorage::getCertificatePath(Certificate::ref certificate) const {
- return path / Hexify::hexify(crypto->getSHA1Hash(certificate->toDER()));
+ return path / Hexify::hexify(crypto->getSHA1Hash(certificate->toDER()));
}
}
diff --git a/Swift/Controllers/Storages/CertificateFileStorage.h b/Swift/Controllers/Storages/CertificateFileStorage.h
index f7d3cb3..d2c228d 100644
--- a/Swift/Controllers/Storages/CertificateFileStorage.h
+++ b/Swift/Controllers/Storages/CertificateFileStorage.h
@@ -11,23 +11,23 @@
#include <Swift/Controllers/Storages/CertificateStorage.h>
namespace Swift {
- class CertificateFactory;
- class CryptoProvider;
+ class CertificateFactory;
+ class CryptoProvider;
- class CertificateFileStorage : public CertificateStorage {
- public:
- CertificateFileStorage(const boost::filesystem::path& path, CertificateFactory* certificateFactory, CryptoProvider* crypto);
+ class CertificateFileStorage : public CertificateStorage {
+ public:
+ CertificateFileStorage(const boost::filesystem::path& path, CertificateFactory* certificateFactory, CryptoProvider* crypto);
- virtual bool hasCertificate(Certificate::ref certificate) const;
- virtual void addCertificate(Certificate::ref certificate);
+ virtual bool hasCertificate(Certificate::ref certificate) const;
+ virtual void addCertificate(Certificate::ref certificate);
- private:
- boost::filesystem::path getCertificatePath(Certificate::ref certificate) const;
+ private:
+ boost::filesystem::path getCertificatePath(Certificate::ref certificate) const;
- private:
- boost::filesystem::path path;
- CertificateFactory* certificateFactory;
- CryptoProvider* crypto;
- };
+ private:
+ boost::filesystem::path path;
+ CertificateFactory* certificateFactory;
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateFileStorageFactory.h b/Swift/Controllers/Storages/CertificateFileStorageFactory.h
index da8e66e..8ab99f4 100644
--- a/Swift/Controllers/Storages/CertificateFileStorageFactory.h
+++ b/Swift/Controllers/Storages/CertificateFileStorageFactory.h
@@ -10,21 +10,21 @@
#include <Swift/Controllers/Storages/CertificateStorageFactory.h>
namespace Swift {
- class CertificateFactory;
- class CryptoProvider;
+ class CertificateFactory;
+ class CryptoProvider;
- class CertificateFileStorageFactory : public CertificateStorageFactory {
- public:
- CertificateFileStorageFactory(const boost::filesystem::path& basePath, CertificateFactory* certificateFactory, CryptoProvider* crypto) : basePath(basePath), certificateFactory(certificateFactory), crypto(crypto) {}
+ class CertificateFileStorageFactory : public CertificateStorageFactory {
+ public:
+ CertificateFileStorageFactory(const boost::filesystem::path& basePath, CertificateFactory* certificateFactory, CryptoProvider* crypto) : basePath(basePath), certificateFactory(certificateFactory), crypto(crypto) {}
- virtual CertificateStorage* createCertificateStorage(const JID& profile) const {
- boost::filesystem::path profilePath = basePath / profile.toString();
- return new CertificateFileStorage(profilePath / "certificates", certificateFactory, crypto);
- }
+ virtual CertificateStorage* createCertificateStorage(const JID& profile) const {
+ boost::filesystem::path profilePath = basePath / profile.toString();
+ return new CertificateFileStorage(profilePath / "certificates", certificateFactory, crypto);
+ }
- private:
- boost::filesystem::path basePath;
- CertificateFactory* certificateFactory;
- CryptoProvider* crypto;
- };
+ private:
+ boost::filesystem::path basePath;
+ CertificateFactory* certificateFactory;
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
index cd3c8fa..08c6ee7 100644
--- a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
@@ -14,14 +14,14 @@ CertificateMemoryStorage::CertificateMemoryStorage() {
}
bool CertificateMemoryStorage::hasCertificate(Certificate::ref certificate) const {
- foreach(Certificate::ref storedCert, certificates) {
- if (storedCert->toDER() == certificate->toDER()) {
- return true;
- }
- }
- return false;
+ foreach(Certificate::ref storedCert, certificates) {
+ if (storedCert->toDER() == certificate->toDER()) {
+ return true;
+ }
+ }
+ return false;
}
void CertificateMemoryStorage::addCertificate(Certificate::ref certificate) {
- certificates.push_back(certificate);
+ certificates.push_back(certificate);
}
diff --git a/Swift/Controllers/Storages/CertificateMemoryStorage.h b/Swift/Controllers/Storages/CertificateMemoryStorage.h
index 8bf7986..4870385 100644
--- a/Swift/Controllers/Storages/CertificateMemoryStorage.h
+++ b/Swift/Controllers/Storages/CertificateMemoryStorage.h
@@ -11,15 +11,15 @@
#include <Swift/Controllers/Storages/CertificateStorage.h>
namespace Swift {
- class CertificateMemoryStorage : public CertificateStorage {
- public:
- CertificateMemoryStorage();
+ class CertificateMemoryStorage : public CertificateStorage {
+ public:
+ CertificateMemoryStorage();
- virtual bool hasCertificate(Certificate::ref certificate) const;
- virtual void addCertificate(Certificate::ref certificate);
+ virtual bool hasCertificate(Certificate::ref certificate) const;
+ virtual void addCertificate(Certificate::ref certificate);
- private:
- std::vector<Certificate::ref> certificates;
- };
+ private:
+ std::vector<Certificate::ref> certificates;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateStorage.h b/Swift/Controllers/Storages/CertificateStorage.h
index 470b420..87a566b 100644
--- a/Swift/Controllers/Storages/CertificateStorage.h
+++ b/Swift/Controllers/Storages/CertificateStorage.h
@@ -11,12 +11,12 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class CertificateStorage {
- public:
- virtual ~CertificateStorage();
+ class CertificateStorage {
+ public:
+ virtual ~CertificateStorage();
- virtual bool hasCertificate(Certificate::ref certificate) const = 0;
- virtual void addCertificate(Certificate::ref certificate) = 0;
- };
+ virtual bool hasCertificate(Certificate::ref certificate) const = 0;
+ virtual void addCertificate(Certificate::ref certificate) = 0;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateStorageFactory.h b/Swift/Controllers/Storages/CertificateStorageFactory.h
index 44605df..25fa232 100644
--- a/Swift/Controllers/Storages/CertificateStorageFactory.h
+++ b/Swift/Controllers/Storages/CertificateStorageFactory.h
@@ -7,13 +7,13 @@
#pragma once
namespace Swift {
- class CertificateStorage;
- class JID;
+ class CertificateStorage;
+ class JID;
- class CertificateStorageFactory {
- public:
- virtual ~CertificateStorageFactory();
+ class CertificateStorageFactory {
+ public:
+ virtual ~CertificateStorageFactory();
- virtual CertificateStorage* createCertificateStorage(const JID& profile) const = 0;
- };
+ virtual CertificateStorage* createCertificateStorage(const JID& profile) const = 0;
+ };
}
diff --git a/Swift/Controllers/Storages/CertificateStorageTrustChecker.h b/Swift/Controllers/Storages/CertificateStorageTrustChecker.h
index 7f2f43e..3c708a3 100644
--- a/Swift/Controllers/Storages/CertificateStorageTrustChecker.h
+++ b/Swift/Controllers/Storages/CertificateStorageTrustChecker.h
@@ -11,25 +11,25 @@
#include <Swift/Controllers/Storages/CertificateStorage.h>
namespace Swift {
- /**
- * A certificate trust checker that trusts certificates in a certificate storage.
- */
- class CertificateStorageTrustChecker : public CertificateTrustChecker {
- public:
- CertificateStorageTrustChecker(CertificateStorage* storage) : storage(storage) {
- }
+ /**
+ * A certificate trust checker that trusts certificates in a certificate storage.
+ */
+ class CertificateStorageTrustChecker : public CertificateTrustChecker {
+ public:
+ CertificateStorageTrustChecker(CertificateStorage* storage) : storage(storage) {
+ }
- virtual bool isCertificateTrusted(const std::vector<Certificate::ref>& certificateChain) {
- lastCertificateChain = std::vector<Certificate::ref>(certificateChain.begin(), certificateChain.end());
- return certificateChain.empty() ? false : storage->hasCertificate(certificateChain[0]);
- }
+ virtual bool isCertificateTrusted(const std::vector<Certificate::ref>& certificateChain) {
+ lastCertificateChain = std::vector<Certificate::ref>(certificateChain.begin(), certificateChain.end());
+ return certificateChain.empty() ? false : storage->hasCertificate(certificateChain[0]);
+ }
- const std::vector<Certificate::ref>& getLastCertificateChain() const {
- return lastCertificateChain;
- }
+ const std::vector<Certificate::ref>& getLastCertificateChain() const {
+ return lastCertificateChain;
+ }
- private:
- CertificateStorage* storage;
- std::vector<Certificate::ref> lastCertificateChain;
- };
+ private:
+ CertificateStorage* storage;
+ std::vector<Certificate::ref> lastCertificateChain;
+ };
}
diff --git a/Swift/Controllers/Storages/FileStorages.cpp b/Swift/Controllers/Storages/FileStorages.cpp
index 7e564bf..7ba2b0f 100644
--- a/Swift/Controllers/Storages/FileStorages.cpp
+++ b/Swift/Controllers/Storages/FileStorages.cpp
@@ -17,47 +17,47 @@
namespace Swift {
FileStorages::FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider* crypto) {
- boost::filesystem::path profile = stringToPath(jid.toBare());
- vcardStorage = new VCardFileStorage(baseDir / profile / "vcards", crypto);
- capsStorage = new CapsFileStorage(baseDir / "caps");
- avatarStorage = new AvatarFileStorage(baseDir / "avatars", baseDir / profile / "avatars", crypto);
- rosterStorage = new RosterFileStorage(baseDir / profile / "roster.xml");
+ boost::filesystem::path profile = stringToPath(jid.toBare());
+ vcardStorage = new VCardFileStorage(baseDir / profile / "vcards", crypto);
+ capsStorage = new CapsFileStorage(baseDir / "caps");
+ avatarStorage = new AvatarFileStorage(baseDir / "avatars", baseDir / profile / "avatars", crypto);
+ rosterStorage = new RosterFileStorage(baseDir / profile / "roster.xml");
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- historyStorage = new SQLiteHistoryStorage(baseDir / "history.db");
+ historyStorage = new SQLiteHistoryStorage(baseDir / "history.db");
#else
- historyStorage = NULL;
+ historyStorage = NULL;
#endif
}
FileStorages::~FileStorages() {
- delete rosterStorage;
- delete avatarStorage;
- delete capsStorage;
- delete vcardStorage;
- delete historyStorage;
+ delete rosterStorage;
+ delete avatarStorage;
+ delete capsStorage;
+ delete vcardStorage;
+ delete historyStorage;
}
VCardStorage* FileStorages::getVCardStorage() const {
- return vcardStorage;
+ return vcardStorage;
}
CapsStorage* FileStorages::getCapsStorage() const {
- return capsStorage;
+ return capsStorage;
}
AvatarStorage* FileStorages::getAvatarStorage() const {
- return avatarStorage;
+ return avatarStorage;
}
RosterStorage* FileStorages::getRosterStorage() const {
- return rosterStorage;
+ return rosterStorage;
}
HistoryStorage* FileStorages::getHistoryStorage() const {
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- return historyStorage;
+ return historyStorage;
#else
- return NULL;
+ return NULL;
#endif
}
diff --git a/Swift/Controllers/Storages/FileStorages.h b/Swift/Controllers/Storages/FileStorages.h
index 195d0fa..e71d665 100644
--- a/Swift/Controllers/Storages/FileStorages.h
+++ b/Swift/Controllers/Storages/FileStorages.h
@@ -11,47 +11,47 @@
#include <Swiften/Client/Storages.h>
namespace Swift {
- class VCardFileStorage;
- class AvatarFileStorage;
- class CapsFileStorage;
- class RosterFileStorage;
- class HistoryStorage;
- class JID;
- class CryptoProvider;
+ class VCardFileStorage;
+ class AvatarFileStorage;
+ class CapsFileStorage;
+ class RosterFileStorage;
+ class HistoryStorage;
+ class JID;
+ class CryptoProvider;
- /**
- * A storages implementation that stores all controller data on disk.
- */
- class FileStorages : public Storages {
- public:
- /**
- * Creates the storages interface.
- *
- * All data will be stored relative to a base directory, and
- * for some controllers, in a subdirectory for the given profile.
- * The data is stored in the following places:
- * - Avatars: $basedir/avatars
- * - VCards: $basedir/$profile/vcards
- * - Entity capabilities: $basedir/caps
- *
- * \param baseDir the base dir to store data relative to
- * \param jid the subdir in which profile-specific data will be stored.
- * The bare JID will be used as the subdir name.
- */
- FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider*);
- ~FileStorages();
+ /**
+ * A storages implementation that stores all controller data on disk.
+ */
+ class FileStorages : public Storages {
+ public:
+ /**
+ * Creates the storages interface.
+ *
+ * All data will be stored relative to a base directory, and
+ * for some controllers, in a subdirectory for the given profile.
+ * The data is stored in the following places:
+ * - Avatars: $basedir/avatars
+ * - VCards: $basedir/$profile/vcards
+ * - Entity capabilities: $basedir/caps
+ *
+ * \param baseDir the base dir to store data relative to
+ * \param jid the subdir in which profile-specific data will be stored.
+ * The bare JID will be used as the subdir name.
+ */
+ FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider*);
+ ~FileStorages();
- virtual VCardStorage* getVCardStorage() const;
- virtual AvatarStorage* getAvatarStorage() const;
- virtual CapsStorage* getCapsStorage() const;
- virtual RosterStorage* getRosterStorage() const;
- virtual HistoryStorage* getHistoryStorage() const;
+ virtual VCardStorage* getVCardStorage() const;
+ virtual AvatarStorage* getAvatarStorage() const;
+ virtual CapsStorage* getCapsStorage() const;
+ virtual RosterStorage* getRosterStorage() const;
+ virtual HistoryStorage* getHistoryStorage() const;
- private:
- VCardFileStorage* vcardStorage;
- AvatarFileStorage* avatarStorage;
- CapsFileStorage* capsStorage;
- RosterFileStorage* rosterStorage;
- HistoryStorage* historyStorage;
- };
+ private:
+ VCardFileStorage* vcardStorage;
+ AvatarFileStorage* avatarStorage;
+ CapsFileStorage* capsStorage;
+ RosterFileStorage* rosterStorage;
+ HistoryStorage* historyStorage;
+ };
}
diff --git a/Swift/Controllers/Storages/FileStoragesFactory.h b/Swift/Controllers/Storages/FileStoragesFactory.h
index 66b3841..ec0106e 100644
--- a/Swift/Controllers/Storages/FileStoragesFactory.h
+++ b/Swift/Controllers/Storages/FileStoragesFactory.h
@@ -10,18 +10,18 @@
#include <Swift/Controllers/Storages/StoragesFactory.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class FileStoragesFactory : public StoragesFactory {
- public:
- FileStoragesFactory(const boost::filesystem::path& basePath, CryptoProvider* crypto) : basePath(basePath), crypto(crypto) {}
+ class FileStoragesFactory : public StoragesFactory {
+ public:
+ FileStoragesFactory(const boost::filesystem::path& basePath, CryptoProvider* crypto) : basePath(basePath), crypto(crypto) {}
- virtual Storages* createStorages(const JID& profile) const {
- return new FileStorages(basePath, profile, crypto);
- }
+ virtual Storages* createStorages(const JID& profile) const {
+ return new FileStorages(basePath, profile, crypto);
+ }
- private:
- boost::filesystem::path basePath;
- CryptoProvider* crypto;
- };
+ private:
+ boost::filesystem::path basePath;
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swift/Controllers/Storages/MemoryStoragesFactory.h b/Swift/Controllers/Storages/MemoryStoragesFactory.h
index 6f6523c..28e9138 100644
--- a/Swift/Controllers/Storages/MemoryStoragesFactory.h
+++ b/Swift/Controllers/Storages/MemoryStoragesFactory.h
@@ -11,17 +11,17 @@
#include <Swift/Controllers/Storages/StoragesFactory.h>
namespace Swift {
- class JID;
- class CryptoProvider;
+ class JID;
+ class CryptoProvider;
- class MemoryStoragesFactory : public StoragesFactory {
- public:
- MemoryStoragesFactory(CryptoProvider* cryptoProvider) : cryptoProvider_(cryptoProvider) {}
+ class MemoryStoragesFactory : public StoragesFactory {
+ public:
+ MemoryStoragesFactory(CryptoProvider* cryptoProvider) : cryptoProvider_(cryptoProvider) {}
- virtual Storages* createStorages(const JID& /*profile*/) const {
- return new MemoryStorages(cryptoProvider_);
- }
- private:
- CryptoProvider* cryptoProvider_;
- };
+ virtual Storages* createStorages(const JID& /*profile*/) const {
+ return new MemoryStorages(cryptoProvider_);
+ }
+ private:
+ CryptoProvider* cryptoProvider_;
+ };
}
diff --git a/Swift/Controllers/Storages/RosterFileStorage.cpp b/Swift/Controllers/Storages/RosterFileStorage.cpp
index c55bcf1..6cc5c61 100644
--- a/Swift/Controllers/Storages/RosterFileStorage.cpp
+++ b/Swift/Controllers/Storages/RosterFileStorage.cpp
@@ -18,9 +18,9 @@ RosterFileStorage::RosterFileStorage(const boost::filesystem::path& path) : path
}
boost::shared_ptr<RosterPayload> RosterFileStorage::getRoster() const {
- return RosterPersister().loadPayloadGeneric(path);
+ return RosterPersister().loadPayloadGeneric(path);
}
void RosterFileStorage::setRoster(boost::shared_ptr<RosterPayload> roster) {
- RosterPersister().savePayload(roster, path);
+ RosterPersister().savePayload(roster, path);
}
diff --git a/Swift/Controllers/Storages/RosterFileStorage.h b/Swift/Controllers/Storages/RosterFileStorage.h
index d100793..dd1a6c9 100644
--- a/Swift/Controllers/Storages/RosterFileStorage.h
+++ b/Swift/Controllers/Storages/RosterFileStorage.h
@@ -11,14 +11,14 @@
#include <Swiften/Roster/RosterStorage.h>
namespace Swift {
- class RosterFileStorage : public RosterStorage {
- public:
- RosterFileStorage(const boost::filesystem::path& path);
+ class RosterFileStorage : public RosterStorage {
+ public:
+ RosterFileStorage(const boost::filesystem::path& path);
- virtual boost::shared_ptr<RosterPayload> getRoster() const;
- virtual void setRoster(boost::shared_ptr<RosterPayload>);
+ virtual boost::shared_ptr<RosterPayload> getRoster() const;
+ virtual void setRoster(boost::shared_ptr<RosterPayload>);
- private:
- boost::filesystem::path path;
- };
+ private:
+ boost::filesystem::path path;
+ };
}
diff --git a/Swift/Controllers/Storages/StoragesFactory.h b/Swift/Controllers/Storages/StoragesFactory.h
index 4eb991b..771230b 100644
--- a/Swift/Controllers/Storages/StoragesFactory.h
+++ b/Swift/Controllers/Storages/StoragesFactory.h
@@ -7,13 +7,13 @@
#pragma once
namespace Swift {
- class Storages;
- class JID;
+ class Storages;
+ class JID;
- class StoragesFactory {
- public:
- virtual ~StoragesFactory() {}
+ class StoragesFactory {
+ public:
+ virtual ~StoragesFactory() {}
- virtual Storages* createStorages(const JID& profile) const = 0;
- };
+ virtual Storages* createStorages(const JID& profile) const = 0;
+ };
}
diff --git a/Swift/Controllers/Storages/VCardFileStorage.cpp b/Swift/Controllers/Storages/VCardFileStorage.cpp
index a93e286..720165a 100644
--- a/Swift/Controllers/Storages/VCardFileStorage.cpp
+++ b/Swift/Controllers/Storages/VCardFileStorage.cpp
@@ -28,100 +28,100 @@ 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;
- }
- }
- }
- }
- catch (...) {
- std::cerr << "Error reading phashes file" << std::endl;
- }
- }
+ 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;
+ }
+ }
+ }
+ }
+ catch (...) {
+ std::cerr << "Error reading phashes file" << std::endl;
+ }
+ }
}
boost::shared_ptr<VCard> VCardFileStorage::getVCard(const JID& jid) const {
- boost::shared_ptr<VCard> result = VCardPersister().loadPayloadGeneric(getVCardPath(jid));
- getAndUpdatePhotoHash(jid, result);
- return result;
+ boost::shared_ptr<VCard> result = VCardPersister().loadPayloadGeneric(getVCardPath(jid));
+ getAndUpdatePhotoHash(jid, result);
+ return result;
}
boost::posix_time::ptime VCardFileStorage::getVCardWriteTime(const JID& jid) const {
- if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) {
- return boost::posix_time::ptime();
- }
- else {
- return vcardWriteTimes.at(jid);
- }
+ if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) {
+ return boost::posix_time::ptime();
+ }
+ else {
+ return vcardWriteTimes.at(jid);
+ }
}
void VCardFileStorage::setVCard(const JID& jid, VCard::ref v) {
- vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time();
- VCardPersister().savePayload(v, getVCardPath(jid));
- getAndUpdatePhotoHash(jid, v);
+ vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time();
+ VCardPersister().savePayload(v, getVCardPath(jid));
+ getAndUpdatePhotoHash(jid, v);
}
boost::filesystem::path VCardFileStorage::getVCardPath(const JID& jid) const {
- try {
- std::string file(jid.toString());
- String::replaceAll(file, '/', "%2f");
- return boost::filesystem::path(vcardsPath / stringToPath(file + ".xml"));
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- return boost::filesystem::path();
- }
+ try {
+ std::string file(jid.toString());
+ String::replaceAll(file, '/', "%2f");
+ return boost::filesystem::path(vcardsPath / stringToPath(file + ".xml"));
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ return boost::filesystem::path();
+ }
}
std::string VCardFileStorage::getPhotoHash(const JID& jid) const {
- PhotoHashMap::const_iterator i = photoHashes.find(jid);
- if (i != photoHashes.end()) {
- return i->second;
- }
- else {
- VCard::ref vCard = getVCard(jid);
- return getAndUpdatePhotoHash(jid, vCard);
- }
+ PhotoHashMap::const_iterator i = photoHashes.find(jid);
+ if (i != photoHashes.end()) {
+ return i->second;
+ }
+ else {
+ VCard::ref vCard = getVCard(jid);
+ return getAndUpdatePhotoHash(jid, vCard);
+ }
}
std::string VCardFileStorage::getAndUpdatePhotoHash(const JID& jid, VCard::ref vCard) const {
- std::string hash;
- if (vCard && !vCard->getPhoto().empty()) {
- hash = Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto()));
- }
- std::pair<PhotoHashMap::iterator, bool> r = photoHashes.insert(std::make_pair(jid, hash));
- if (r.second) {
- savePhotoHashes();
- }
- else if (r.first->second != hash) {
- r.first->second = hash;
- savePhotoHashes();
- }
- return hash;
+ std::string hash;
+ if (vCard && !vCard->getPhoto().empty()) {
+ hash = Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto()));
+ }
+ std::pair<PhotoHashMap::iterator, bool> r = photoHashes.insert(std::make_pair(jid, hash));
+ if (r.second) {
+ savePhotoHashes();
+ }
+ else if (r.first->second != hash) {
+ r.first->second = hash;
+ savePhotoHashes();
+ }
+ return hash;
}
void VCardFileStorage::savePhotoHashes() const {
- try {
- boost::filesystem::ofstream file(cacheFile);
- for (PhotoHashMap::const_iterator i = photoHashes.begin(); i != photoHashes.end(); ++i) {
- file << i->second << " " << i->first.toString() << std::endl;
- }
- file.close();
- }
- catch (...) {
- std::cerr << "Error writing vcards file" << std::endl;
- }
+ try {
+ boost::filesystem::ofstream file(cacheFile);
+ for (PhotoHashMap::const_iterator i = photoHashes.begin(); i != photoHashes.end(); ++i) {
+ file << i->second << " " << i->first.toString() << std::endl;
+ }
+ file.close();
+ }
+ catch (...) {
+ std::cerr << "Error writing vcards file" << std::endl;
+ }
}
diff --git a/Swift/Controllers/Storages/VCardFileStorage.h b/Swift/Controllers/Storages/VCardFileStorage.h
index 56e06f2..971a3f9 100644
--- a/Swift/Controllers/Storages/VCardFileStorage.h
+++ b/Swift/Controllers/Storages/VCardFileStorage.h
@@ -15,30 +15,30 @@
#include <Swiften/VCards/VCardStorage.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class VCardFileStorage : public VCardStorage {
- public:
- VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto);
+ class VCardFileStorage : public VCardStorage {
+ public:
+ VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto);
- virtual VCard::ref getVCard(const JID& jid) const;
- virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const;
- virtual void setVCard(const JID& jid, VCard::ref v);
+ virtual VCard::ref getVCard(const JID& jid) const;
+ virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const;
+ virtual void setVCard(const JID& jid, VCard::ref v);
- virtual std::string getPhotoHash(const JID&) const;
+ virtual std::string getPhotoHash(const JID&) const;
- private:
- boost::filesystem::path getVCardPath(const JID&) const;
+ private:
+ boost::filesystem::path getVCardPath(const JID&) const;
- std::string getAndUpdatePhotoHash(const JID& jid, VCard::ref vcard) const;
- void savePhotoHashes() const;
+ std::string getAndUpdatePhotoHash(const JID& jid, VCard::ref vcard) const;
+ void savePhotoHashes() const;
- private:
- boost::filesystem::path vcardsPath;
- CryptoProvider* crypto;
- boost::filesystem::path cacheFile;
- typedef std::map<JID, std::string> PhotoHashMap;
- mutable PhotoHashMap photoHashes;
- std::map<JID, boost::posix_time::ptime> vcardWriteTimes;
- };
+ private:
+ boost::filesystem::path vcardsPath;
+ CryptoProvider* crypto;
+ boost::filesystem::path cacheFile;
+ typedef std::map<JID, std::string> PhotoHashMap;
+ mutable PhotoHashMap photoHashes;
+ std::map<JID, boost::posix_time::ptime> vcardWriteTimes;
+ };
}
diff --git a/Swift/Controllers/SystemTray.h b/Swift/Controllers/SystemTray.h
index fd8fe01..094857f 100644
--- a/Swift/Controllers/SystemTray.h
+++ b/Swift/Controllers/SystemTray.h
@@ -9,11 +9,11 @@
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
- class SystemTray {
- public:
- virtual ~SystemTray(){}
- virtual void setUnreadMessages(bool some) = 0;
- virtual void setStatusType(StatusShow::Type type) = 0;
- virtual void setConnecting() = 0;
- };
+ class SystemTray {
+ public:
+ virtual ~SystemTray(){}
+ virtual void setUnreadMessages(bool some) = 0;
+ virtual void setStatusType(StatusShow::Type type) = 0;
+ virtual void setConnecting() = 0;
+ };
}
diff --git a/Swift/Controllers/SystemTrayController.cpp b/Swift/Controllers/SystemTrayController.cpp
index e4029e0..72d3403 100644
--- a/Swift/Controllers/SystemTrayController.cpp
+++ b/Swift/Controllers/SystemTrayController.cpp
@@ -14,29 +14,29 @@
namespace Swift {
SystemTrayController::SystemTrayController(EventController* eventController, SystemTray* systemTray) {
- systemTray_ = systemTray;
- eventController_ = eventController;
- eventController_->onEventQueueLengthChange.connect(boost::bind(&SystemTrayController::handleEventQueueLengthChange, this, _1));
+ systemTray_ = systemTray;
+ eventController_ = eventController;
+ eventController_->onEventQueueLengthChange.connect(boost::bind(&SystemTrayController::handleEventQueueLengthChange, this, _1));
}
void SystemTrayController::handleEventQueueLengthChange(int /*length*/) {
- EventList events = eventController_->getEvents();
- bool found = false;
- for (EventList::iterator it = events.begin(); it != events.end(); ++it) {
- if (boost::dynamic_pointer_cast<MessageEvent>(*it)) {
- found = true;
- break;
- }
- }
- systemTray_->setUnreadMessages(found);
+ EventList events = eventController_->getEvents();
+ bool found = false;
+ for (EventList::iterator it = events.begin(); it != events.end(); ++it) {
+ if (boost::dynamic_pointer_cast<MessageEvent>(*it)) {
+ found = true;
+ break;
+ }
+ }
+ systemTray_->setUnreadMessages(found);
}
void SystemTrayController::setMyStatusType(StatusShow::Type type) {
- systemTray_->setStatusType(type);
+ systemTray_->setStatusType(type);
}
void SystemTrayController::setConnecting() {
- systemTray_->setConnecting();
+ systemTray_->setConnecting();
}
}
diff --git a/Swift/Controllers/SystemTrayController.h b/Swift/Controllers/SystemTrayController.h
index f19b127..850ac71 100644
--- a/Swift/Controllers/SystemTrayController.h
+++ b/Swift/Controllers/SystemTrayController.h
@@ -9,19 +9,19 @@
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
- class EventController;
- class SystemTray;
+ class EventController;
+ class SystemTray;
- class SystemTrayController {
- public:
- SystemTrayController(EventController* eventController, SystemTray* systemTray);
- void setMyStatusType(StatusShow::Type type);
- void setConnecting();
- private:
- void handleEventQueueLengthChange(int length);
+ class SystemTrayController {
+ public:
+ SystemTrayController(EventController* eventController, SystemTray* systemTray);
+ void setMyStatusType(StatusShow::Type type);
+ void setConnecting();
+ private:
+ void handleEventQueueLengthChange(int length);
- private:
- EventController* eventController_;
- SystemTray* systemTray_;
- };
+ private:
+ EventController* eventController_;
+ SystemTray* systemTray_;
+ };
}
diff --git a/Swift/Controllers/Translator.cpp b/Swift/Controllers/Translator.cpp
index 13230ab..b62fd28 100644
--- a/Swift/Controllers/Translator.cpp
+++ b/Swift/Controllers/Translator.cpp
@@ -11,9 +11,9 @@
namespace Swift {
static struct DefaultTranslator : public Translator {
- virtual std::string translate(const std::string& text, const std::string&) {
- return text;
- }
+ virtual std::string translate(const std::string& text, const std::string&) {
+ return text;
+ }
} defaultTranslator;
Translator* Translator::translator = &defaultTranslator;
@@ -22,7 +22,7 @@ Translator::~Translator() {
}
void Translator::setInstance(Translator* t) {
- translator = t;
+ translator = t;
}
}
diff --git a/Swift/Controllers/Translator.h b/Swift/Controllers/Translator.h
index 801e8b5..5c52e9f 100644
--- a/Swift/Controllers/Translator.h
+++ b/Swift/Controllers/Translator.h
@@ -9,19 +9,19 @@
#include <string>
namespace Swift {
- class Translator {
- public:
- virtual ~Translator();
+ class Translator {
+ public:
+ virtual ~Translator();
- virtual std::string translate(const std::string& text, const std::string& context) = 0;
+ virtual std::string translate(const std::string& text, const std::string& context) = 0;
- static void setInstance(Translator* translator);
+ static void setInstance(Translator* translator);
- static Translator* getInstance() {
- return translator;
- }
+ static Translator* getInstance() {
+ return translator;
+ }
- private:
- static Translator* translator;
- };
+ private:
+ static Translator* translator;
+ };
}
diff --git a/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h b/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h
index 93cad03..b46774c 100644
--- a/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h
+++ b/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h
@@ -13,12 +13,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class AcceptWhiteboardSessionUIEvent : public UIEvent {
- typedef boost::shared_ptr<AcceptWhiteboardSessionUIEvent> ref;
- public:
- AcceptWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {}
- const JID& getContact() const {return jid_;}
- private:
- JID jid_;
- };
+ class AcceptWhiteboardSessionUIEvent : public UIEvent {
+ typedef boost::shared_ptr<AcceptWhiteboardSessionUIEvent> ref;
+ public:
+ AcceptWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {}
+ const JID& getContact() const {return jid_;}
+ private:
+ JID jid_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/AddContactUIEvent.h b/Swift/Controllers/UIEvents/AddContactUIEvent.h
index 127dba2..d2176ac 100644
--- a/Swift/Controllers/UIEvents/AddContactUIEvent.h
+++ b/Swift/Controllers/UIEvents/AddContactUIEvent.h
@@ -12,25 +12,25 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class AddContactUIEvent : public UIEvent {
- public:
- AddContactUIEvent(const JID& jid, const std::string& name, const std::set<std::string>& groups) : jid_(jid), name_(name), groups_(groups) {}
-
- const std::string& getName() const {
- return name_;
- }
-
- const JID& getJID() const {
- return jid_;
- }
-
- const std::set<std::string>& getGroups() const {
- return groups_;
- }
-
- private:
- JID jid_;
- std::string name_;
- std::set<std::string> groups_;
- };
+ class AddContactUIEvent : public UIEvent {
+ public:
+ AddContactUIEvent(const JID& jid, const std::string& name, const std::set<std::string>& groups) : jid_(jid), name_(name), groups_(groups) {}
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ const JID& getJID() const {
+ return jid_;
+ }
+
+ const std::set<std::string>& getGroups() const {
+ return groups_;
+ }
+
+ private:
+ JID jid_;
+ std::string name_;
+ std::set<std::string> groups_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h
index d19a402..526fc0d 100644
--- a/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h
@@ -13,12 +13,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class AddMUCBookmarkUIEvent : public UIEvent {
- public:
- AddMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {}
- const MUCBookmark& getBookmark() { return bookmark; }
+ class AddMUCBookmarkUIEvent : public UIEvent {
+ public:
+ AddMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {}
+ const MUCBookmark& getBookmark() { return bookmark; }
- private:
- MUCBookmark bookmark;
- };
+ private:
+ MUCBookmark bookmark;
+ };
}
diff --git a/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h b/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h
index f5c3b0e..62751b6 100644
--- a/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h
+++ b/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h
@@ -13,12 +13,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class CancelWhiteboardSessionUIEvent : public UIEvent {
- typedef boost::shared_ptr<CancelWhiteboardSessionUIEvent> ref;
- public:
- CancelWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {}
- const JID& getContact() const {return jid_;}
- private:
- JID jid_;
- };
+ class CancelWhiteboardSessionUIEvent : public UIEvent {
+ typedef boost::shared_ptr<CancelWhiteboardSessionUIEvent> ref;
+ public:
+ CancelWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {}
+ const JID& getContact() const {return jid_;}
+ private:
+ JID jid_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h b/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h
index 57e181d..b566be6 100644
--- a/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h
@@ -11,16 +11,16 @@
namespace Swift {
class CreateImpromptuMUCUIEvent : public UIEvent {
- public:
- CreateImpromptuMUCUIEvent(const std::vector<JID>& jids, const JID& roomJID = JID(), const std::string reason = "") : jids_(jids), roomJID_(roomJID), reason_(reason) { }
+ public:
+ CreateImpromptuMUCUIEvent(const std::vector<JID>& jids, const JID& roomJID = JID(), const std::string reason = "") : jids_(jids), roomJID_(roomJID), reason_(reason) { }
- std::vector<JID> getJIDs() const { return jids_; }
- JID getRoomJID() const { return roomJID_; }
- std::string getReason() const { return reason_; }
- private:
- std::vector<JID> jids_;
- JID roomJID_;
- std::string reason_;
+ std::vector<JID> getJIDs() const { return jids_; }
+ JID getRoomJID() const { return roomJID_; }
+ std::string getReason() const { return reason_; }
+ private:
+ std::vector<JID> jids_;
+ JID roomJID_;
+ std::string reason_;
};
}
diff --git a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
index 602f45e..b3d3118 100644
--- a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
@@ -13,15 +13,15 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class EditMUCBookmarkUIEvent : public UIEvent {
- public:
- EditMUCBookmarkUIEvent(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) : oldBookmark(oldBookmark) , newBookmark(newBookmark) {}
+ class EditMUCBookmarkUIEvent : public UIEvent {
+ public:
+ EditMUCBookmarkUIEvent(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) : oldBookmark(oldBookmark) , newBookmark(newBookmark) {}
- const MUCBookmark& getOldBookmark() {return oldBookmark;}
- const MUCBookmark& getNewBookmark() {return newBookmark;}
+ const MUCBookmark& getOldBookmark() {return oldBookmark;}
+ const MUCBookmark& getNewBookmark() {return newBookmark;}
- private:
- MUCBookmark oldBookmark;
- MUCBookmark newBookmark;
- };
+ private:
+ MUCBookmark oldBookmark;
+ MUCBookmark newBookmark;
+ };
}
diff --git a/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h b/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h
index 70c46b0..e1416de 100644
--- a/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h
@@ -21,28 +21,28 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class InviteToMUCUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<InviteToMUCUIEvent> ref;
-
- InviteToMUCUIEvent(const JID& room, const std::vector<JID>& JIDsToInvite, const std::string& reason) : room_(room), invite_(JIDsToInvite), reason_(reason) {
- }
-
- const JID& getRoom() const {
- return room_;
- }
-
- const std::vector<JID> getInvites() const {
- return invite_;
- }
-
- const std::string getReason() const {
- return reason_;
- }
-
- private:
- JID room_;
- std::vector<JID> invite_;
- std::string reason_;
- };
+ class InviteToMUCUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<InviteToMUCUIEvent> ref;
+
+ InviteToMUCUIEvent(const JID& room, const std::vector<JID>& JIDsToInvite, const std::string& reason) : room_(room), invite_(JIDsToInvite), reason_(reason) {
+ }
+
+ const JID& getRoom() const {
+ return room_;
+ }
+
+ const std::vector<JID> getInvites() const {
+ return invite_;
+ }
+
+ const std::string getReason() const {
+ return reason_;
+ }
+
+ private:
+ JID room_;
+ std::vector<JID> invite_;
+ std::string reason_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
index 8d74858..076b5b6 100644
--- a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
@@ -16,25 +16,25 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class JoinMUCUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<JoinMUCUIEvent> ref;
- JoinMUCUIEvent(const JID& jid, const boost::optional<std::string>& password = boost::optional<std::string>(), const boost::optional<std::string>& nick = boost::optional<std::string>(), bool joinAutomaticallyInFuture = false, bool createAsReservedRoomIfNew = false, bool isImpromptu = false, bool isContinuation = false) : jid_(jid), nick_(nick), joinAutomatically_(joinAutomaticallyInFuture), createAsReservedRoomIfNew_(createAsReservedRoomIfNew), password_(password), isImpromptuMUC_(isImpromptu), isContinuation_(isContinuation) {}
- const boost::optional<std::string>& getNick() const {return nick_;}
- const JID& getJID() const {return jid_;}
- bool getShouldJoinAutomatically() const {return joinAutomatically_;}
- bool getCreateAsReservedRoomIfNew() const {return createAsReservedRoomIfNew_;}
- const boost::optional<std::string>& getPassword() const {return password_;}
- bool isImpromptu() const {return isImpromptuMUC_;}
- bool isContinuation() const {return isContinuation_;}
+ class JoinMUCUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<JoinMUCUIEvent> ref;
+ JoinMUCUIEvent(const JID& jid, const boost::optional<std::string>& password = boost::optional<std::string>(), const boost::optional<std::string>& nick = boost::optional<std::string>(), bool joinAutomaticallyInFuture = false, bool createAsReservedRoomIfNew = false, bool isImpromptu = false, bool isContinuation = false) : jid_(jid), nick_(nick), joinAutomatically_(joinAutomaticallyInFuture), createAsReservedRoomIfNew_(createAsReservedRoomIfNew), password_(password), isImpromptuMUC_(isImpromptu), isContinuation_(isContinuation) {}
+ const boost::optional<std::string>& getNick() const {return nick_;}
+ const JID& getJID() const {return jid_;}
+ bool getShouldJoinAutomatically() const {return joinAutomatically_;}
+ bool getCreateAsReservedRoomIfNew() const {return createAsReservedRoomIfNew_;}
+ const boost::optional<std::string>& getPassword() const {return password_;}
+ bool isImpromptu() const {return isImpromptuMUC_;}
+ bool isContinuation() const {return isContinuation_;}
- private:
- JID jid_;
- boost::optional<std::string> nick_;
- bool joinAutomatically_;
- bool createAsReservedRoomIfNew_;
- boost::optional<std::string> password_;
- bool isImpromptuMUC_;
- bool isContinuation_;
- };
+ private:
+ JID jid_;
+ boost::optional<std::string> nick_;
+ bool joinAutomatically_;
+ bool createAsReservedRoomIfNew_;
+ boost::optional<std::string> password_;
+ bool isImpromptuMUC_;
+ bool isContinuation_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h
index f6655e4..2803197 100644
--- a/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h
@@ -13,12 +13,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RemoveMUCBookmarkUIEvent : public UIEvent {
- public:
- RemoveMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {}
- const MUCBookmark& getBookmark() { return bookmark; }
+ class RemoveMUCBookmarkUIEvent : public UIEvent {
+ public:
+ RemoveMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {}
+ const MUCBookmark& getBookmark() { return bookmark; }
- private:
- MUCBookmark bookmark;
- };
+ private:
+ MUCBookmark bookmark;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h b/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h
index 95b59b1..0f4a89d 100644
--- a/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h
@@ -13,12 +13,12 @@
namespace Swift {
class RemoveRosterItemUIEvent : public UIEvent {
- public:
- RemoveRosterItemUIEvent(const JID& jid) : jid_(jid) {}
- virtual ~RemoveRosterItemUIEvent() {}
- JID getJID() {return jid_;}
- private:
- JID jid_;
+ public:
+ RemoveRosterItemUIEvent(const JID& jid) : jid_(jid) {}
+ virtual ~RemoveRosterItemUIEvent() {}
+ JID getJID() {return jid_;}
+ private:
+ JID jid_;
};
diff --git a/Swift/Controllers/UIEvents/RenameGroupUIEvent.h b/Swift/Controllers/UIEvents/RenameGroupUIEvent.h
index cea1afc..ea19efe 100644
--- a/Swift/Controllers/UIEvents/RenameGroupUIEvent.h
+++ b/Swift/Controllers/UIEvents/RenameGroupUIEvent.h
@@ -11,21 +11,21 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RenameGroupUIEvent : public UIEvent {
- public:
- RenameGroupUIEvent(const std::string& group, const std::string& newName) : group(group), newName(newName) {
- }
+ class RenameGroupUIEvent : public UIEvent {
+ public:
+ RenameGroupUIEvent(const std::string& group, const std::string& newName) : group(group), newName(newName) {
+ }
- const std::string& getGroup() const {
- return group;
- }
+ const std::string& getGroup() const {
+ return group;
+ }
- const std::string& getNewName() const {
- return newName;
- }
+ const std::string& getNewName() const {
+ return newName;
+ }
- private:
- std::string group;
- std::string newName;
- };
+ private:
+ std::string group;
+ std::string newName;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h b/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h
index fbf3814..7d370e2 100644
--- a/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h
@@ -13,15 +13,15 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RenameRosterItemUIEvent : public UIEvent {
- public:
- RenameRosterItemUIEvent(const JID& jid, const std::string& newName) : jid_(jid), newName_(newName) {}
+ class RenameRosterItemUIEvent : public UIEvent {
+ public:
+ RenameRosterItemUIEvent(const JID& jid, const std::string& newName) : jid_(jid), newName_(newName) {}
- const JID& getJID() const {return jid_;}
- const std::string& getNewName() const {return newName_;}
+ const JID& getJID() const {return jid_;}
+ const std::string& getNewName() const {return newName_;}
- private:
- JID jid_;
- std::string newName_;
- };
+ private:
+ JID jid_;
+ std::string newName_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h b/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h
index afc0a34..f6fa1c7 100644
--- a/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h
@@ -10,11 +10,11 @@
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
namespace Swift {
- class RequestAdHocUIEvent : public UIEvent {
- public:
- RequestAdHocUIEvent(const DiscoItems::Item& command) : command_(command) {}
- const DiscoItems::Item& getCommand() const {return command_;}
- private:
- DiscoItems::Item command_;
- };
+ class RequestAdHocUIEvent : public UIEvent {
+ public:
+ RequestAdHocUIEvent(const DiscoItems::Item& command) : command_(command) {}
+ const DiscoItems::Item& getCommand() const {return command_;}
+ private:
+ DiscoItems::Item command_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h b/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h
index 5c7e97a..8d8bd19 100644
--- a/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h
@@ -9,13 +9,13 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestAdHocWithJIDUIEvent : public UIEvent {
- public:
- RequestAdHocWithJIDUIEvent(const JID& jid, const std::string& node) : jid_(jid), node_(node) {}
- JID getJID() const { return jid_; }
- std::string getNode() const { return node_; }
- private:
- JID jid_;
- std::string node_;
- };
+ class RequestAdHocWithJIDUIEvent : public UIEvent {
+ public:
+ RequestAdHocWithJIDUIEvent(const JID& jid, const std::string& node) : jid_(jid), node_(node) {}
+ JID getJID() const { return jid_; }
+ std::string getNode() const { return node_; }
+ private:
+ JID jid_;
+ std::string node_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h b/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h
index 73ad20e..474d155 100644
--- a/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h
@@ -13,18 +13,18 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestAddUserDialogUIEvent : public UIEvent {
+ class RequestAddUserDialogUIEvent : public UIEvent {
- public:
- RequestAddUserDialogUIEvent(const JID& predefinedJID, const std::string& predefinedName) : preJID_(predefinedJID), preName_(predefinedName) {}
- RequestAddUserDialogUIEvent() : preJID_(), preName_() {}
+ public:
+ RequestAddUserDialogUIEvent(const JID& predefinedJID, const std::string& predefinedName) : preJID_(predefinedJID), preName_(predefinedName) {}
+ RequestAddUserDialogUIEvent() : preJID_(), preName_() {}
- const JID& getPredefinedJID() const { return preJID_; }
- const std::string& getPredefinedName() const { return preName_; }
+ const JID& getPredefinedJID() const { return preJID_; }
+ const std::string& getPredefinedName() const { return preName_; }
- private:
- JID preJID_;
- std::string preName_;
+ private:
+ JID preJID_;
+ std::string preName_;
- };
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h b/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h
index 6594897..4dcf8be 100644
--- a/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h
@@ -19,25 +19,25 @@
namespace Swift {
class RequestChangeBlockStateUIEvent : public UIEvent {
- public:
- enum BlockState {
- Blocked,
- Unblocked
- };
-
- public:
- RequestChangeBlockStateUIEvent(BlockState newState, const JID& contact) : state_(newState), contact_(contact) {}
-
- BlockState getBlockState() const {
- return state_;
- }
-
- JID getContact() const {
- return contact_;
- }
- private:
- BlockState state_;
- JID contact_;
+ public:
+ enum BlockState {
+ Blocked,
+ Unblocked
+ };
+
+ public:
+ RequestChangeBlockStateUIEvent(BlockState newState, const JID& contact) : state_(newState), contact_(contact) {}
+
+ BlockState getBlockState() const {
+ return state_;
+ }
+
+ JID getContact() const {
+ return contact_;
+ }
+ private:
+ BlockState state_;
+ JID contact_;
};
}
diff --git a/Swift/Controllers/UIEvents/RequestChatUIEvent.h b/Swift/Controllers/UIEvents/RequestChatUIEvent.h
index 95d6075..4eca5d4 100644
--- a/Swift/Controllers/UIEvents/RequestChatUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChatUIEvent.h
@@ -11,11 +11,11 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestChatUIEvent : public UIEvent {
- public:
- RequestChatUIEvent(const JID& contact) : contact_(contact) {}
- JID getContact() {return contact_;}
- private:
- JID contact_;
- };
+ class RequestChatUIEvent : public UIEvent {
+ public:
+ RequestChatUIEvent(const JID& contact) : contact_(contact) {}
+ JID getContact() {return contact_;}
+ private:
+ JID contact_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h b/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h
index 76aa1f7..08804f4 100644
--- a/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h
@@ -9,7 +9,7 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestChatWithUserDialogUIEvent : public UIEvent {
+ class RequestChatWithUserDialogUIEvent : public UIEvent {
- };
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h
index 61ddbe9..5693ab1 100644
--- a/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h
@@ -11,18 +11,18 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestContactEditorUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<RequestContactEditorUIEvent> ref;
+ class RequestContactEditorUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<RequestContactEditorUIEvent> ref;
- RequestContactEditorUIEvent(const JID& jid) : jid(jid) {
- }
+ RequestContactEditorUIEvent(const JID& jid) : jid(jid) {
+ }
- const JID& getJID() const {
- return jid;
- }
+ const JID& getJID() const {
+ return jid;
+ }
- private:
- JID jid;
- };
+ private:
+ JID jid;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h
index 42e22a2..0bfa458 100644
--- a/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h
@@ -10,7 +10,7 @@
namespace Swift {
- class RequestHighlightEditorUIEvent : public UIEvent {
- };
+ class RequestHighlightEditorUIEvent : public UIEvent {
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h b/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h
index 025e91f..8282204 100644
--- a/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h
@@ -9,6 +9,6 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestHistoryUIEvent : public UIEvent {
- };
+ class RequestHistoryUIEvent : public UIEvent {
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h b/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h
index 3733532..9a1abb1 100644
--- a/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h
@@ -21,34 +21,34 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestInviteToMUCUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<RequestInviteToMUCUIEvent> ref;
-
- enum ImpromptuMode {
- Impromptu,
- NotImpromptu
- };
-
- RequestInviteToMUCUIEvent(const JID& room, const std::vector<JID>& JIDsToInvite, ImpromptuMode impromptu) : room_(room), invite_(JIDsToInvite) {
- isImpromptu_ = impromptu == Impromptu;
- }
-
- const JID& getRoom() const {
- return room_;
- }
-
- const std::vector<JID> getInvites() const {
- return invite_;
- }
-
- bool isImpromptu() const {
- return isImpromptu_;
- }
-
- private:
- JID room_;
- std::vector<JID> invite_;
- bool isImpromptu_;
- };
+ class RequestInviteToMUCUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<RequestInviteToMUCUIEvent> ref;
+
+ enum ImpromptuMode {
+ Impromptu,
+ NotImpromptu
+ };
+
+ RequestInviteToMUCUIEvent(const JID& room, const std::vector<JID>& JIDsToInvite, ImpromptuMode impromptu) : room_(room), invite_(JIDsToInvite) {
+ isImpromptu_ = impromptu == Impromptu;
+ }
+
+ const JID& getRoom() const {
+ return room_;
+ }
+
+ const std::vector<JID> getInvites() const {
+ return invite_;
+ }
+
+ bool isImpromptu() const {
+ return isImpromptu_;
+ }
+
+ private:
+ JID room_;
+ std::vector<JID> invite_;
+ bool isImpromptu_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
index a3ba6c8..a2a4183 100644
--- a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
@@ -15,18 +15,18 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestJoinMUCUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<RequestJoinMUCUIEvent> ref;
+ class RequestJoinMUCUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<RequestJoinMUCUIEvent> ref;
- RequestJoinMUCUIEvent(const JID& room = JID()) : room(room) {
- }
+ RequestJoinMUCUIEvent(const JID& room = JID()) : room(room) {
+ }
- const JID& getRoom() const {
- return room;
- }
+ const JID& getRoom() const {
+ return room;
+ }
- private:
- JID room;
- };
+ private:
+ JID room;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h
index 1907242..1a02af4 100644
--- a/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h
@@ -9,8 +9,8 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestProfileEditorUIEvent : public UIEvent {
- public:
- RequestProfileEditorUIEvent() {}
- };
+ class RequestProfileEditorUIEvent : public UIEvent {
+ public:
+ RequestProfileEditorUIEvent() {}
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h b/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h
index 625736f..9c2b01d 100644
--- a/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h
@@ -17,11 +17,11 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestWhiteboardUIEvent : public UIEvent {
- public:
- RequestWhiteboardUIEvent(const JID& contact) : contact_(contact) {}
- const JID& getContact() const {return contact_;}
- private:
- JID contact_;
- };
+ class RequestWhiteboardUIEvent : public UIEvent {
+ public:
+ RequestWhiteboardUIEvent(const JID& contact) : contact_(contact) {}
+ const JID& getContact() const {return contact_;}
+ private:
+ JID contact_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h b/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h
index 41eecc4..4d780be 100644
--- a/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h
@@ -9,6 +9,6 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class RequestXMLConsoleUIEvent : public UIEvent {
- };
+ class RequestXMLConsoleUIEvent : public UIEvent {
+ };
}
diff --git a/Swift/Controllers/UIEvents/SendFileUIEvent.h b/Swift/Controllers/UIEvents/SendFileUIEvent.h
index ea29453..72452df 100644
--- a/Swift/Controllers/UIEvents/SendFileUIEvent.h
+++ b/Swift/Controllers/UIEvents/SendFileUIEvent.h
@@ -19,23 +19,23 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class SendFileUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<SendFileUIEvent> ref;
-
- SendFileUIEvent(const JID& jid, const std::string& filename) : jid(jid), filename(filename) {
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- const std::string& getFilename() const {
- return filename;
- }
-
- private:
- JID jid;
- std::string filename;
- };
+ class SendFileUIEvent : public UIEvent {
+ public:
+ typedef boost::shared_ptr<SendFileUIEvent> ref;
+
+ SendFileUIEvent(const JID& jid, const std::string& filename) : jid(jid), filename(filename) {
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ const std::string& getFilename() const {
+ return filename;
+ }
+
+ private:
+ JID jid;
+ std::string filename;
+ };
}
diff --git a/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h b/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h
index 586f036..88528d7 100644
--- a/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h
@@ -19,14 +19,14 @@
namespace Swift {
class ShowProfileForRosterItemUIEvent : public UIEvent {
- public:
- typedef boost::shared_ptr<ShowProfileForRosterItemUIEvent> ref;
- public:
- ShowProfileForRosterItemUIEvent(const JID& jid) : jid_(jid) {}
- virtual ~ShowProfileForRosterItemUIEvent() {}
- JID getJID() const {return jid_;}
- private:
- JID jid_;
+ public:
+ typedef boost::shared_ptr<ShowProfileForRosterItemUIEvent> ref;
+ public:
+ ShowProfileForRosterItemUIEvent(const JID& jid) : jid_(jid) {}
+ virtual ~ShowProfileForRosterItemUIEvent() {}
+ JID getJID() const {return jid_;}
+ private:
+ JID jid_;
};
}
diff --git a/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h b/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h
index 0d16cb6..a1b6efb 100644
--- a/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h
+++ b/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h
@@ -17,12 +17,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class ShowWhiteboardUIEvent : public UIEvent {
- public:
- ShowWhiteboardUIEvent(const JID& contact) : contact_(contact) {}
- const JID& getContact() const {return contact_;}
- private:
- JID contact_;
- };
+ class ShowWhiteboardUIEvent : public UIEvent {
+ public:
+ ShowWhiteboardUIEvent(const JID& contact) : contact_(contact) {}
+ const JID& getContact() const {return contact_;}
+ private:
+ JID contact_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/UIEvent.h b/Swift/Controllers/UIEvents/UIEvent.h
index 548f356..333582d 100644
--- a/Swift/Controllers/UIEvents/UIEvent.h
+++ b/Swift/Controllers/UIEvents/UIEvent.h
@@ -9,10 +9,10 @@
#include <boost/shared_ptr.hpp>
namespace Swift {
- class UIEvent {
- public:
- typedef boost::shared_ptr<UIEvent> ref;
+ class UIEvent {
+ public:
+ typedef boost::shared_ptr<UIEvent> ref;
- virtual ~UIEvent();
- };
+ virtual ~UIEvent();
+ };
}
diff --git a/Swift/Controllers/UIEvents/UIEventStream.h b/Swift/Controllers/UIEvents/UIEventStream.h
index a630522..7ff1b54 100644
--- a/Swift/Controllers/UIEvents/UIEventStream.h
+++ b/Swift/Controllers/UIEvents/UIEventStream.h
@@ -13,12 +13,12 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class UIEventStream {
- public:
- boost::signal<void (boost::shared_ptr<UIEvent>)> onUIEvent;
+ class UIEventStream {
+ public:
+ boost::signal<void (boost::shared_ptr<UIEvent>)> onUIEvent;
- void send(boost::shared_ptr<UIEvent> event) {
- onUIEvent(event);
- }
- };
+ void send(boost::shared_ptr<UIEvent> event) {
+ onUIEvent(event);
+ }
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
index e5d95fa..06d3988 100644
--- a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
+++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
@@ -9,10 +9,10 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class AdHocCommandWindow {
- public:
- virtual ~AdHocCommandWindow() {}
- virtual void setOnline(bool /*online*/) {}
- boost::signal<void ()> onClosing;
- };
+ class AdHocCommandWindow {
+ public:
+ virtual ~AdHocCommandWindow() {}
+ virtual void setOnline(bool /*online*/) {}
+ boost::signal<void ()> onClosing;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
index d7b456d..d3003f7 100644
--- a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
@@ -12,9 +12,9 @@
namespace Swift {
class AdHocCommandWindow;
- class AdHocCommandWindowFactory {
- public:
- virtual ~AdHocCommandWindowFactory() {}
- virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) = 0;
- };
+ class AdHocCommandWindowFactory {
+ public:
+ virtual ~AdHocCommandWindowFactory() {}
+ virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
index 201377d..ebfa0c4 100644
--- a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
+++ b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
@@ -19,22 +19,22 @@
namespace Swift {
- class ClientBlockListManager;
+ class ClientBlockListManager;
- class BlockListEditorWidget {
- public:
- virtual ~BlockListEditorWidget() {}
+ class BlockListEditorWidget {
+ public:
+ virtual ~BlockListEditorWidget() {}
- virtual void show() = 0;
- virtual void hide() = 0;
+ virtual void show() = 0;
+ virtual void hide() = 0;
- virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs) = 0;
- virtual void setBusy(bool isBusy) = 0;
- virtual void setError(const std::string&) = 0;
+ virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs) = 0;
+ virtual void setBusy(bool isBusy) = 0;
+ virtual void setError(const std::string&) = 0;
- virtual std::vector<JID> getCurrentBlockList() const = 0;
+ virtual std::vector<JID> getCurrentBlockList() const = 0;
- boost::signal<void (const std::vector<JID>& /* blockedJID */)> onSetNewBlockList;
- };
+ boost::signal<void (const std::vector<JID>& /* blockedJID */)> onSetNewBlockList;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h b/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h
index eb91ac1..05e7f3a 100644
--- a/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h
@@ -8,13 +8,13 @@
namespace Swift {
- class BlockListEditorWidget;
+ class BlockListEditorWidget;
- class BlockListEditorWidgetFactory {
- public:
- virtual ~BlockListEditorWidgetFactory() {}
+ class BlockListEditorWidgetFactory {
+ public:
+ virtual ~BlockListEditorWidgetFactory() {}
- virtual BlockListEditorWidget* createBlockListEditorWidget() = 0;
- };
+ virtual BlockListEditorWidget* createBlockListEditorWidget() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ChatListWindow.h b/Swift/Controllers/UIInterfaces/ChatListWindow.h
index 8b5036b..a94e14e 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindow.h
+++ b/Swift/Controllers/UIInterfaces/ChatListWindow.h
@@ -19,83 +19,83 @@
#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) {
- bool found = false;
- foreach (const JIDMap::value_type& 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) {
- 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();
+ 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) {
+ bool found = false;
+ foreach (const JIDMap::value_type& 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) {
+ 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;
- virtual void setOnline(bool isOnline) = 0;
+ 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;
+ virtual void setOnline(bool isOnline) = 0;
- boost::signal<void (const MUCBookmark&)> onMUCBookmarkActivated;
- boost::signal<void (const Chat&)> onRecentActivated;
- boost::signal<void (const JID&)> onWhiteboardActivated;
- boost::signal<void ()> onClearRecentsRequested;
- };
+ boost::signal<void (const MUCBookmark&)> onMUCBookmarkActivated;
+ boost::signal<void (const Chat&)> onRecentActivated;
+ boost::signal<void (const JID&)> onWhiteboardActivated;
+ boost::signal<void ()> onClearRecentsRequested;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
index fcd979b..3ae1ec6 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
@@ -9,10 +9,10 @@
#include <Swift/Controllers/UIInterfaces/ChatListWindow.h>
namespace Swift {
- class UIEventStream;
- class ChatListWindowFactory {
- public:
- virtual ~ChatListWindowFactory() {}
- virtual ChatListWindow* createChatListWindow(UIEventStream* uiEventStream) = 0;
- };
+ class UIEventStream;
+ class ChatListWindowFactory {
+ public:
+ virtual ~ChatListWindowFactory() {}
+ virtual ChatListWindow* createChatListWindow(UIEventStream* uiEventStream) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ChatWindow.h b/Swift/Controllers/UIInterfaces/ChatWindow.h
index 05331bb..310c967 100644
--- a/Swift/Controllers/UIInterfaces/ChatWindow.h
+++ b/Swift/Controllers/UIInterfaces/ChatWindow.h
@@ -26,233 +26,233 @@
#include <Swift/Controllers/HighlightManager.h>
namespace Swift {
- class AvatarManager;
- class TreeWidget;
- class Roster;
- class TabComplete;
- class RosterItem;
- class ContactRosterItem;
- class FileTransferController;
- class UserSearchWindow;
-
-
- class ChatWindow {
- public:
- class ChatMessagePart {
- public:
- virtual ~ChatMessagePart() {}
- };
-
- class ChatMessage {
- public:
- ChatMessage() {}
- ChatMessage(const std::string& text) {
- append(boost::make_shared<ChatTextMessagePart>(text));
- }
- void append(const boost::shared_ptr<ChatMessagePart>& part) {
- parts_.push_back(part);
- }
-
- const std::vector<boost::shared_ptr<ChatMessagePart> >& getParts() const {
- return parts_;
- }
-
- void setFullMessageHighlightAction(const HighlightAction& action) {
- fullMessageHighlightAction_ = action;
- }
-
- const HighlightAction& getFullMessageHighlightAction() const {
- return fullMessageHighlightAction_;
- }
-
- bool isMeCommand() const {
- bool isMeCommand = false;
- if (!parts_.empty()) {
- boost::shared_ptr<ChatTextMessagePart> textPart = boost::dynamic_pointer_cast<ChatTextMessagePart>(parts_[0]);
- if (textPart) {
- if (boost::starts_with(textPart->text, "/me ")) {
- isMeCommand = true;
- }
- }
- }
- return isMeCommand;
- }
-
- private:
- std::vector<boost::shared_ptr<ChatMessagePart> > parts_;
- HighlightAction fullMessageHighlightAction_;
- };
-
- class ChatTextMessagePart : public ChatMessagePart {
- public:
- ChatTextMessagePart(const std::string& text) : text(text) {}
- std::string text;
- };
-
- class ChatURIMessagePart : public ChatMessagePart {
- public:
- ChatURIMessagePart(const std::string& target) : target(target) {}
- std::string target;
- };
-
- class ChatEmoticonMessagePart : public ChatMessagePart {
- public:
- std::string imagePath;
- std::string alternativeText;
- };
-
- class ChatHighlightingMessagePart : public ChatMessagePart {
- public:
- HighlightAction action;
- std::string text;
- };
-
-
- enum AckState {Pending, Received, Failed};
- enum ReceiptState {ReceiptRequested, ReceiptReceived, ReceiptFailed};
- enum OccupantAction {Kick, Ban, MakeModerator, MakeParticipant, MakeVisitor, AddContact, ShowProfile};
- enum RoomAction {ChangeSubject, Configure, Affiliations, Destroy, Invite};
- enum FileTransferState {
- Initialisation, ///< Collecting information required for sending the request out.
- WaitingForAccept, ///< The file transfer request was send out.
- Negotiating, ///< The other party accepted the file transfer request and a suitable transfer method is negotiated.
- Transferring, ///< The negotiation was successful and the file is currently transferred.
- Canceled, ///< Someone actively canceled the transfer.
- Finished, ///< The file was transferred successfully.
- FTFailed ///< The negotiation, the transfer itself or the verification failed.
- };
- enum WhiteboardSessionState {WhiteboardAccepted, WhiteboardTerminated, WhiteboardRejected};
- enum BlockingState {BlockingUnsupported, IsBlocked, IsUnblocked};
- enum Direction { UnknownDirection, DefaultDirection };
- enum MUCType { StandardMUC, ImpromptuMUC };
- enum TimestampBehaviour { KeepTimestamp, UpdateTimestamp };
- enum RoomBookmarkState { RoomNotBookmarked, RoomBookmarked, RoomAutoJoined };
-
- ChatWindow() {}
- virtual ~ChatWindow() {}
-
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
-
- /** Adds system message to window
- * @return id of added message (for replacement)
- */
- virtual std::string addSystemMessage(const ChatMessage& message, Direction direction) = 0;
- virtual void addPresenceMessage(const ChatMessage& message, Direction direction) = 0;
-
- virtual void addErrorMessage(const ChatMessage& message) = 0;
- virtual void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
- virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour) = 0;
- virtual void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
-
- // File transfer related stuff
- virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
- virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
- virtual void setFileTransferStatus(std::string, const FileTransferState state, const std::string& msg = "") = 0;
- virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false) = 0;
-
- virtual std::string addWhiteboardRequest(bool senderIsSelf) = 0;
- virtual void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) = 0;
-
- // message receipts
- virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
-
- virtual void setContactChatState(ChatState::ChatStateType state) = 0;
- virtual void setName(const std::string& name) = 0;
- virtual void show() = 0;
- virtual bool isVisible() const = 0;
- virtual void activate() = 0;
- virtual void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) = 0;
- virtual void setSecurityLabelsEnabled(bool enabled) = 0;
- virtual void setCorrectionEnabled(Tristate enabled) = 0;
- virtual void setFileTransferEnabled(Tristate enabled) = 0;
- virtual void setUnreadMessageCount(int count) = 0;
- virtual void convertToMUC(MUCType mucType) = 0;
-// virtual TreeWidget *getTreeWidget() = 0;
- virtual void setSecurityLabelsError() = 0;
- virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() = 0;
- virtual void setOnline(bool online) = 0;
- virtual void setRosterModel(Roster* model) = 0;
- virtual void setTabComplete(TabComplete* completer) = 0;
- virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) = 0;
- virtual void setAckState(const std::string& id, AckState state) = 0;
- virtual void flash() = 0;
- virtual void setSubject(const std::string& subject) = 0;
- virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&) = 0;
- virtual void setAvailableRoomActions(const std::vector<RoomAction> &actions) = 0;
- virtual void setBlockingState(BlockingState state) = 0;
- virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) = 0;
- virtual void showBookmarkWindow(const MUCBookmark& bookmark) = 0;
- virtual void setBookmarkState(RoomBookmarkState bookmarkState) = 0;
-
- /**
- * A handle that uniquely identities an alert message.
- */
- typedef int AlertID;
- /**
- * Set an alert on the window.
- * @param alertText Description of alert (required).
- * @param buttonText Button text to use (optional, no button is shown if empty).
- * @return A handle to the alert message.
- */
- virtual AlertID addAlert(const std::string& alertText) = 0;
- /**
- * Removes an alert.
- * @param id An alert ID previously returned from setAlert
- */
- virtual void removeAlert(const AlertID id) = 0;
-
- /**
- * Actions that can be performed on the selected occupant.
- */
- virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions) = 0;
-
- /**
- * A room configuration has been requested, show the form.
- * If the form is cancelled, must emit onConfigurationFormCancelled().
- */
- virtual void showRoomConfigurationForm(Form::ref) = 0;
-
- boost::signal<void ()> onClosed;
- boost::signal<void ()> onAllMessagesRead;
- boost::signal<void (const std::string&, bool isCorrection)> onSendMessageRequest;
- boost::signal<void ()> onSendCorrectionMessageRequest;
- boost::signal<void ()> onUserTyping;
- boost::signal<void ()> onUserCancelsTyping;
- boost::signal<void ()> onAlertButtonClicked;
- boost::signal<void (ContactRosterItem*)> onOccupantSelectionChanged;
- boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
- boost::signal<void (const std::string&)> onChangeSubjectRequest;
- boost::signal<void ()> onBookmarkRequest;
- boost::signal<void (Form::ref)> onConfigureRequest;
- boost::signal<void ()> onDestroyRequest;
- boost::signal<void (const std::vector<JID>&)> onInviteToChat;
- boost::signal<void ()> onConfigurationFormCancelled;
- boost::signal<void ()> onGetAffiliationsRequest;
- boost::signal<void (MUCOccupant::Affiliation, const JID&)> onSetAffiliationRequest;
- boost::signal<void (const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes)> onChangeAffiliationsRequest;
- boost::signal<void ()> onLogCleared;
-
- // File transfer related
- boost::signal<void (std::string /* id */)> onFileTransferCancel;
- boost::signal<void (std::string /* id */, std::string /* description */)> onFileTransferStart;
- boost::signal<void (std::string /* id */, std::string /* path */)> onFileTransferAccept;
- boost::signal<void (std::string /* path */)> onSendFileRequest;
-
- //Whiteboard related
- boost::signal<void ()> onWhiteboardSessionAccept;
- boost::signal<void ()> onWhiteboardSessionCancel;
- boost::signal<void ()> onWhiteboardWindowShow;
-
- // Blocking Command related
- boost::signal<void ()> onBlockUserRequest;
- boost::signal<void ()> onUnblockUserRequest;
- };
+ class AvatarManager;
+ class TreeWidget;
+ class Roster;
+ class TabComplete;
+ class RosterItem;
+ class ContactRosterItem;
+ class FileTransferController;
+ class UserSearchWindow;
+
+
+ class ChatWindow {
+ public:
+ class ChatMessagePart {
+ public:
+ virtual ~ChatMessagePart() {}
+ };
+
+ class ChatMessage {
+ public:
+ ChatMessage() {}
+ ChatMessage(const std::string& text) {
+ append(boost::make_shared<ChatTextMessagePart>(text));
+ }
+ void append(const boost::shared_ptr<ChatMessagePart>& part) {
+ parts_.push_back(part);
+ }
+
+ const std::vector<boost::shared_ptr<ChatMessagePart> >& getParts() const {
+ return parts_;
+ }
+
+ void setFullMessageHighlightAction(const HighlightAction& action) {
+ fullMessageHighlightAction_ = action;
+ }
+
+ const HighlightAction& getFullMessageHighlightAction() const {
+ return fullMessageHighlightAction_;
+ }
+
+ bool isMeCommand() const {
+ bool isMeCommand = false;
+ if (!parts_.empty()) {
+ boost::shared_ptr<ChatTextMessagePart> textPart = boost::dynamic_pointer_cast<ChatTextMessagePart>(parts_[0]);
+ if (textPart) {
+ if (boost::starts_with(textPart->text, "/me ")) {
+ isMeCommand = true;
+ }
+ }
+ }
+ return isMeCommand;
+ }
+
+ private:
+ std::vector<boost::shared_ptr<ChatMessagePart> > parts_;
+ HighlightAction fullMessageHighlightAction_;
+ };
+
+ class ChatTextMessagePart : public ChatMessagePart {
+ public:
+ ChatTextMessagePart(const std::string& text) : text(text) {}
+ std::string text;
+ };
+
+ class ChatURIMessagePart : public ChatMessagePart {
+ public:
+ ChatURIMessagePart(const std::string& target) : target(target) {}
+ std::string target;
+ };
+
+ class ChatEmoticonMessagePart : public ChatMessagePart {
+ public:
+ std::string imagePath;
+ std::string alternativeText;
+ };
+
+ class ChatHighlightingMessagePart : public ChatMessagePart {
+ public:
+ HighlightAction action;
+ std::string text;
+ };
+
+
+ enum AckState {Pending, Received, Failed};
+ enum ReceiptState {ReceiptRequested, ReceiptReceived, ReceiptFailed};
+ enum OccupantAction {Kick, Ban, MakeModerator, MakeParticipant, MakeVisitor, AddContact, ShowProfile};
+ enum RoomAction {ChangeSubject, Configure, Affiliations, Destroy, Invite};
+ enum FileTransferState {
+ Initialisation, ///< Collecting information required for sending the request out.
+ WaitingForAccept, ///< The file transfer request was send out.
+ Negotiating, ///< The other party accepted the file transfer request and a suitable transfer method is negotiated.
+ Transferring, ///< The negotiation was successful and the file is currently transferred.
+ Canceled, ///< Someone actively canceled the transfer.
+ Finished, ///< The file was transferred successfully.
+ FTFailed ///< The negotiation, the transfer itself or the verification failed.
+ };
+ enum WhiteboardSessionState {WhiteboardAccepted, WhiteboardTerminated, WhiteboardRejected};
+ enum BlockingState {BlockingUnsupported, IsBlocked, IsUnblocked};
+ enum Direction { UnknownDirection, DefaultDirection };
+ enum MUCType { StandardMUC, ImpromptuMUC };
+ enum TimestampBehaviour { KeepTimestamp, UpdateTimestamp };
+ enum RoomBookmarkState { RoomNotBookmarked, RoomBookmarked, RoomAutoJoined };
+
+ ChatWindow() {}
+ virtual ~ChatWindow() {}
+
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+
+ /** Adds system message to window
+ * @return id of added message (for replacement)
+ */
+ virtual std::string addSystemMessage(const ChatMessage& message, Direction direction) = 0;
+ virtual void addPresenceMessage(const ChatMessage& message, Direction direction) = 0;
+
+ virtual void addErrorMessage(const ChatMessage& message) = 0;
+ virtual void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+ virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour) = 0;
+ virtual void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+
+ // File transfer related stuff
+ virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
+ virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
+ virtual void setFileTransferStatus(std::string, const FileTransferState state, const std::string& msg = "") = 0;
+ virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false) = 0;
+
+ virtual std::string addWhiteboardRequest(bool senderIsSelf) = 0;
+ virtual void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) = 0;
+
+ // message receipts
+ virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
+
+ virtual void setContactChatState(ChatState::ChatStateType state) = 0;
+ virtual void setName(const std::string& name) = 0;
+ virtual void show() = 0;
+ virtual bool isVisible() const = 0;
+ virtual void activate() = 0;
+ virtual void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) = 0;
+ virtual void setSecurityLabelsEnabled(bool enabled) = 0;
+ virtual void setCorrectionEnabled(Tristate enabled) = 0;
+ virtual void setFileTransferEnabled(Tristate enabled) = 0;
+ virtual void setUnreadMessageCount(int count) = 0;
+ virtual void convertToMUC(MUCType mucType) = 0;
+// virtual TreeWidget *getTreeWidget() = 0;
+ virtual void setSecurityLabelsError() = 0;
+ virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() = 0;
+ virtual void setOnline(bool online) = 0;
+ virtual void setRosterModel(Roster* model) = 0;
+ virtual void setTabComplete(TabComplete* completer) = 0;
+ virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) = 0;
+ virtual void setAckState(const std::string& id, AckState state) = 0;
+ virtual void flash() = 0;
+ virtual void setSubject(const std::string& subject) = 0;
+ virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&) = 0;
+ virtual void setAvailableRoomActions(const std::vector<RoomAction> &actions) = 0;
+ virtual void setBlockingState(BlockingState state) = 0;
+ virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) = 0;
+ virtual void showBookmarkWindow(const MUCBookmark& bookmark) = 0;
+ virtual void setBookmarkState(RoomBookmarkState bookmarkState) = 0;
+
+ /**
+ * A handle that uniquely identities an alert message.
+ */
+ typedef int AlertID;
+ /**
+ * Set an alert on the window.
+ * @param alertText Description of alert (required).
+ * @param buttonText Button text to use (optional, no button is shown if empty).
+ * @return A handle to the alert message.
+ */
+ virtual AlertID addAlert(const std::string& alertText) = 0;
+ /**
+ * Removes an alert.
+ * @param id An alert ID previously returned from setAlert
+ */
+ virtual void removeAlert(const AlertID id) = 0;
+
+ /**
+ * Actions that can be performed on the selected occupant.
+ */
+ virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions) = 0;
+
+ /**
+ * A room configuration has been requested, show the form.
+ * If the form is cancelled, must emit onConfigurationFormCancelled().
+ */
+ virtual void showRoomConfigurationForm(Form::ref) = 0;
+
+ boost::signal<void ()> onClosed;
+ boost::signal<void ()> onAllMessagesRead;
+ boost::signal<void (const std::string&, bool isCorrection)> onSendMessageRequest;
+ boost::signal<void ()> onSendCorrectionMessageRequest;
+ boost::signal<void ()> onUserTyping;
+ boost::signal<void ()> onUserCancelsTyping;
+ boost::signal<void ()> onAlertButtonClicked;
+ boost::signal<void (ContactRosterItem*)> onOccupantSelectionChanged;
+ boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
+ boost::signal<void (const std::string&)> onChangeSubjectRequest;
+ boost::signal<void ()> onBookmarkRequest;
+ boost::signal<void (Form::ref)> onConfigureRequest;
+ boost::signal<void ()> onDestroyRequest;
+ boost::signal<void (const std::vector<JID>&)> onInviteToChat;
+ boost::signal<void ()> onConfigurationFormCancelled;
+ boost::signal<void ()> onGetAffiliationsRequest;
+ boost::signal<void (MUCOccupant::Affiliation, const JID&)> onSetAffiliationRequest;
+ boost::signal<void (const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes)> onChangeAffiliationsRequest;
+ boost::signal<void ()> onLogCleared;
+
+ // File transfer related
+ boost::signal<void (std::string /* id */)> onFileTransferCancel;
+ boost::signal<void (std::string /* id */, std::string /* description */)> onFileTransferStart;
+ boost::signal<void (std::string /* id */, std::string /* path */)> onFileTransferAccept;
+ boost::signal<void (std::string /* path */)> onSendFileRequest;
+
+ //Whiteboard related
+ boost::signal<void ()> onWhiteboardSessionAccept;
+ boost::signal<void ()> onWhiteboardSessionCancel;
+ boost::signal<void ()> onWhiteboardWindowShow;
+
+ // Blocking Command related
+ boost::signal<void ()> onBlockUserRequest;
+ boost::signal<void ()> onUnblockUserRequest;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ChatWindowFactory.h b/Swift/Controllers/UIInterfaces/ChatWindowFactory.h
index 7c47e2a..38706ab 100644
--- a/Swift/Controllers/UIInterfaces/ChatWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/ChatWindowFactory.h
@@ -10,17 +10,17 @@
#include "Swiften/JID/JID.h"
namespace Swift {
- class ChatWindow;
- class UIEventStream;
- class ChatWindowFactory {
- public:
- virtual ~ChatWindowFactory() {}
- /**
- * Transfers ownership of result.
- */
- virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream) = 0;
+ class ChatWindow;
+ class UIEventStream;
+ class ChatWindowFactory {
+ public:
+ virtual ~ChatWindowFactory() {}
+ /**
+ * Transfers ownership of result.
+ */
+ virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream) = 0;
- };
+ };
}
#endif
diff --git a/Swift/Controllers/UIInterfaces/ContactEditWindow.h b/Swift/Controllers/UIInterfaces/ContactEditWindow.h
index 407959a..055c0f0 100644
--- a/Swift/Controllers/UIInterfaces/ContactEditWindow.h
+++ b/Swift/Controllers/UIInterfaces/ContactEditWindow.h
@@ -15,22 +15,22 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class JID;
- class VCardManager;
+ class JID;
+ class VCardManager;
- class ContactEditWindow {
- public:
- virtual ~ContactEditWindow() {}
+ class ContactEditWindow {
+ public:
+ virtual ~ContactEditWindow() {}
- virtual void setEnabled(bool b) = 0;
+ virtual void setEnabled(bool b) = 0;
- virtual void setNameSuggestions(const std::vector<std::string>& suggestions) = 0;
- virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups) = 0;
+ virtual void setNameSuggestions(const std::vector<std::string>& suggestions) = 0;
+ virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups) = 0;
- virtual void show() = 0;
- virtual void hide() = 0;
+ virtual void show() = 0;
+ virtual void hide() = 0;
- boost::signal<void ()> onRemoveContactRequest;
- boost::signal<void (const std::string& /* name */, const std::set<std::string>& /* groups */)> onChangeContactRequest;
- };
+ boost::signal<void ()> onRemoveContactRequest;
+ boost::signal<void (const std::string& /* name */, const std::set<std::string>& /* groups */)> onChangeContactRequest;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h b/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h
index 6955a69..f5a84d5 100644
--- a/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h
@@ -9,10 +9,10 @@
#include <Swift/Controllers/UIInterfaces/ContactEditWindow.h>
namespace Swift {
- class ContactEditWindowFactory {
- public:
- virtual ~ContactEditWindowFactory() {}
+ class ContactEditWindowFactory {
+ public:
+ virtual ~ContactEditWindowFactory() {}
- virtual ContactEditWindow* createContactEditWindow() = 0;
- };
+ virtual ContactEditWindow* createContactEditWindow() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/EventWindow.h b/Swift/Controllers/UIInterfaces/EventWindow.h
index 5ce99d8..1d254f4 100644
--- a/Swift/Controllers/UIInterfaces/EventWindow.h
+++ b/Swift/Controllers/UIInterfaces/EventWindow.h
@@ -11,19 +11,19 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class EventWindow {
- public:
- EventWindow(bool candelete = true) : canDelete_(candelete) {}
+ class EventWindow {
+ public:
+ EventWindow(bool candelete = true) : canDelete_(candelete) {}
- bool canDelete() const {
- return canDelete_;
- }
+ bool canDelete() const {
+ return canDelete_;
+ }
- virtual ~EventWindow() {}
- virtual void addEvent(boost::shared_ptr<StanzaEvent> event, bool active) = 0;
- virtual void removeEvent(boost::shared_ptr<StanzaEvent> event) = 0;
+ virtual ~EventWindow() {}
+ virtual void addEvent(boost::shared_ptr<StanzaEvent> event, bool active) = 0;
+ virtual void removeEvent(boost::shared_ptr<StanzaEvent> event) = 0;
- private:
- bool canDelete_;
- };
+ private:
+ bool canDelete_;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/EventWindowFactory.h b/Swift/Controllers/UIInterfaces/EventWindowFactory.h
index 7c9c87d..76638da 100644
--- a/Swift/Controllers/UIInterfaces/EventWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/EventWindowFactory.h
@@ -7,17 +7,17 @@
#pragma once
namespace Swift {
- class EventWindow;
+ class EventWindow;
- class EventWindowFactory {
- public:
- virtual ~EventWindowFactory() {}
- /**
- * Transfers ownership of result.
- */
- virtual EventWindow* createEventWindow() = 0;
+ class EventWindowFactory {
+ public:
+ virtual ~EventWindowFactory() {}
+ /**
+ * Transfers ownership of result.
+ */
+ virtual EventWindow* createEventWindow() = 0;
- };
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/FileTransferListWidget.h b/Swift/Controllers/UIInterfaces/FileTransferListWidget.h
index 01dcfd3..5a9eaeb 100644
--- a/Swift/Controllers/UIInterfaces/FileTransferListWidget.h
+++ b/Swift/Controllers/UIInterfaces/FileTransferListWidget.h
@@ -12,12 +12,12 @@ class FileTransferOverview;
class FileTransferListWidget {
public:
- virtual ~FileTransferListWidget() {}
+ virtual ~FileTransferListWidget() {}
- virtual void show() = 0;
- virtual void activate() = 0;
+ virtual void show() = 0;
+ virtual void activate() = 0;
- virtual void setFileTransferOverview(FileTransferOverview*) = 0;
+ virtual void setFileTransferOverview(FileTransferOverview*) = 0;
};
}
diff --git a/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h b/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h
index 6da2d07..da9fd37 100644
--- a/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h
@@ -18,9 +18,9 @@ namespace Swift {
class FileTransferListWidgetFactory {
public:
- virtual ~FileTransferListWidgetFactory() {}
+ virtual ~FileTransferListWidgetFactory() {}
- virtual FileTransferListWidget* createFileTransferListWidget() = 0;
+ virtual FileTransferListWidget* createFileTransferListWidget() = 0;
};
}
diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h b/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h
index 4745035..ff888e6 100644
--- a/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h
+++ b/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h
@@ -8,15 +8,15 @@
namespace Swift {
- class HighlightManager;
+ class HighlightManager;
- class HighlightEditorWidget {
- public:
- virtual ~HighlightEditorWidget() {}
+ class HighlightEditorWidget {
+ public:
+ virtual ~HighlightEditorWidget() {}
- virtual void show() = 0;
+ virtual void show() = 0;
- virtual void setHighlightManager(HighlightManager* highlightManager) = 0;
- };
+ virtual void setHighlightManager(HighlightManager* highlightManager) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h b/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h
index ade575b..363e666 100644
--- a/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h
@@ -8,13 +8,13 @@
namespace Swift {
- class HighlightEditorWidget;
+ class HighlightEditorWidget;
- class HighlightEditorWidgetFactory {
- public:
- virtual ~HighlightEditorWidgetFactory() {}
+ class HighlightEditorWidgetFactory {
+ public:
+ virtual ~HighlightEditorWidgetFactory() {}
- virtual HighlightEditorWidget* createHighlightEditorWidget() = 0;
- };
+ virtual HighlightEditorWidget* createHighlightEditorWidget() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h b/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h
index 12adb3d..8cca4f9 100644
--- a/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h
+++ b/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h
@@ -14,14 +14,14 @@ class HighlightManager;
class HighlightEditorWindow {
public:
- HighlightEditorWindow();
- virtual ~HighlightEditorWindow();
- virtual void show() = 0;
- virtual void setHighlightManager(HighlightManager *highlightManager) = 0;
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions) = 0;
+ HighlightEditorWindow();
+ virtual ~HighlightEditorWindow();
+ virtual void show() = 0;
+ virtual void setHighlightManager(HighlightManager *highlightManager) = 0;
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions) = 0;
public:
- boost::signal<void (const std::string&)> onContactSuggestionsRequested;
+ boost::signal<void (const std::string&)> onContactSuggestionsRequested;
};
}
diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h b/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h
index 18fbeb7..ea05425 100644
--- a/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h
@@ -13,12 +13,12 @@
#pragma once
namespace Swift {
- class HighlightEditorWindow;
+ class HighlightEditorWindow;
- class HighlightEditorWindowFactory {
- public :
- virtual ~HighlightEditorWindowFactory() {}
+ class HighlightEditorWindowFactory {
+ public :
+ virtual ~HighlightEditorWindowFactory() {}
- virtual HighlightEditorWindow* createHighlightEditorWindow() = 0;
- };
+ virtual HighlightEditorWindow* createHighlightEditorWindow() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/HistoryWindow.h b/Swift/Controllers/UIInterfaces/HistoryWindow.h
index 6d50f4b..db1a4b1 100644
--- a/Swift/Controllers/UIInterfaces/HistoryWindow.h
+++ b/Swift/Controllers/UIInterfaces/HistoryWindow.h
@@ -9,26 +9,26 @@
#include <Swift/Controllers/Roster/Roster.h>
namespace Swift {
- class HistoryWindow {
- public:
- virtual ~HistoryWindow() {}
+ class HistoryWindow {
+ public:
+ virtual ~HistoryWindow() {}
- virtual void activate() = 0;
- virtual void setRosterModel(Roster*) = 0;
- virtual void addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) = 0;
- virtual void resetConversationView() = 0;
- virtual void resetConversationViewTopInsertPoint() = 0; // this is a temporary fix used in adding messages at the top
- virtual void setDate(const boost::gregorian::date& date) = 0;
+ virtual void activate() = 0;
+ virtual void setRosterModel(Roster*) = 0;
+ virtual void addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) = 0;
+ virtual void resetConversationView() = 0;
+ virtual void resetConversationViewTopInsertPoint() = 0; // this is a temporary fix used in adding messages at the top
+ virtual void setDate(const boost::gregorian::date& date) = 0;
- virtual std::string getSearchBoxText() = 0;
- virtual boost::gregorian::date getLastVisibleDate() = 0;
+ virtual std::string getSearchBoxText() = 0;
+ virtual boost::gregorian::date getLastVisibleDate() = 0;
- boost::signal<void (RosterItem*)> onSelectedContactChanged;
- boost::signal<void (const std::string&)> onReturnPressed;
- boost::signal<void (const boost::gregorian::date&)> onScrollReachedTop;
- boost::signal<void (const boost::gregorian::date&)> onScrollReachedBottom;
- boost::signal<void ()> onPreviousButtonClicked;
- boost::signal<void ()> onNextButtonClicked;
- boost::signal<void (const boost::gregorian::date&)> onCalendarClicked;
- };
+ boost::signal<void (RosterItem*)> onSelectedContactChanged;
+ boost::signal<void (const std::string&)> onReturnPressed;
+ boost::signal<void (const boost::gregorian::date&)> onScrollReachedTop;
+ boost::signal<void (const boost::gregorian::date&)> onScrollReachedBottom;
+ boost::signal<void ()> onPreviousButtonClicked;
+ boost::signal<void ()> onNextButtonClicked;
+ boost::signal<void (const boost::gregorian::date&)> onCalendarClicked;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h b/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h
index 807fec5..ab4cf0d 100644
--- a/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h
@@ -9,10 +9,10 @@
#include <Swift/Controllers/UIInterfaces/HistoryWindow.h>
namespace Swift {
- class UIEventStream;
- class HistoryWindowFactory {
- public:
- virtual ~HistoryWindowFactory() {}
- virtual HistoryWindow* createHistoryWindow(UIEventStream* eventStream) = 0;
- };
+ class UIEventStream;
+ class HistoryWindowFactory {
+ public:
+ virtual ~HistoryWindowFactory() {}
+ virtual HistoryWindow* createHistoryWindow(UIEventStream* eventStream) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/JoinMUCWindow.h b/Swift/Controllers/UIInterfaces/JoinMUCWindow.h
index 62818c5..4d6cea1 100644
--- a/Swift/Controllers/UIInterfaces/JoinMUCWindow.h
+++ b/Swift/Controllers/UIInterfaces/JoinMUCWindow.h
@@ -13,14 +13,14 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class JoinMUCWindow {
- public:
- virtual ~JoinMUCWindow() {}
+ class JoinMUCWindow {
+ public:
+ virtual ~JoinMUCWindow() {}
- virtual void setNick(const std::string& nick) = 0;
- virtual void setMUC(const std::string& nick) = 0;
- virtual void show() = 0;
+ virtual void setNick(const std::string& nick) = 0;
+ virtual void setMUC(const std::string& nick) = 0;
+ virtual void show() = 0;
- boost::signal<void ()> onSearchMUC;
- };
+ boost::signal<void ()> onSearchMUC;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h b/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h
index a711294..5e8b1d0 100644
--- a/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h
@@ -9,11 +9,11 @@
#include <Swift/Controllers/UIInterfaces/JoinMUCWindow.h>
namespace Swift {
- class UIEventStream;
- class JoinMUCWindowFactory {
- public:
- virtual ~JoinMUCWindowFactory() {}
+ class UIEventStream;
+ class JoinMUCWindowFactory {
+ public:
+ virtual ~JoinMUCWindowFactory() {}
- virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream) = 0;
- };
+ virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/LoginWindow.h b/Swift/Controllers/UIInterfaces/LoginWindow.h
index 5a7e178..cedc549 100644
--- a/Swift/Controllers/UIInterfaces/LoginWindow.h
+++ b/Swift/Controllers/UIInterfaces/LoginWindow.h
@@ -16,27 +16,27 @@
#include <Swiften/TLS/CertificateWithKey.h>
namespace Swift {
- class MainWindow;
- class LoginWindow {
- public:
- virtual ~LoginWindow() {}
- virtual void selectUser(const std::string&) = 0;
- virtual void morphInto(MainWindow *mainWindow) = 0;
- virtual void loggedOut() = 0;
- virtual void setShowNotificationToggle(bool) = 0;
- virtual void setMessage(const std::string&) = 0;
- virtual void setIsLoggingIn(bool loggingIn) = 0;
- virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) = 0;
- virtual void removeAvailableAccount(const std::string& jid) = 0;
- /** The certificate is what is used for login, the certificatePath is used for remembering paths to populate the loginwindow with*/
- boost::signal<void (const std::string&, const std::string&, const std::string& /*CertificatePath*/, CertificateWithKey::ref /* clientCertificate */, const ClientOptions& /*options*/, bool /* remember password*/, bool /* login automatically */)> onLoginRequest;
- virtual void setLoginAutomatically(bool loginAutomatically) = 0;
- virtual void quit() = 0;
- /** Blocking request whether a cert should be permanently trusted.*/
- virtual bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificateChain) = 0;
+ class MainWindow;
+ class LoginWindow {
+ public:
+ virtual ~LoginWindow() {}
+ virtual void selectUser(const std::string&) = 0;
+ virtual void morphInto(MainWindow *mainWindow) = 0;
+ virtual void loggedOut() = 0;
+ virtual void setShowNotificationToggle(bool) = 0;
+ virtual void setMessage(const std::string&) = 0;
+ virtual void setIsLoggingIn(bool loggingIn) = 0;
+ virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) = 0;
+ virtual void removeAvailableAccount(const std::string& jid) = 0;
+ /** The certificate is what is used for login, the certificatePath is used for remembering paths to populate the loginwindow with*/
+ boost::signal<void (const std::string&, const std::string&, const std::string& /*CertificatePath*/, CertificateWithKey::ref /* clientCertificate */, const ClientOptions& /*options*/, bool /* remember password*/, bool /* login automatically */)> onLoginRequest;
+ virtual void setLoginAutomatically(bool loginAutomatically) = 0;
+ virtual void quit() = 0;
+ /** Blocking request whether a cert should be permanently trusted.*/
+ virtual bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificateChain) = 0;
- boost::signal<void ()> onCancelLoginRequest;
- boost::signal<void ()> onQuitRequest;
- boost::signal<void (const std::string&)> onPurgeSavedLoginRequest;
- };
+ boost::signal<void ()> onCancelLoginRequest;
+ boost::signal<void ()> onQuitRequest;
+ boost::signal<void (const std::string&)> onPurgeSavedLoginRequest;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/LoginWindowFactory.h b/Swift/Controllers/UIInterfaces/LoginWindowFactory.h
index c040833..485f975 100644
--- a/Swift/Controllers/UIInterfaces/LoginWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/LoginWindowFactory.h
@@ -10,20 +10,20 @@
namespace Swift {
- class LoginWindow;
-
- class UIEventStream;
-
- class LoginWindowFactory {
- public:
- virtual ~LoginWindowFactory() {}
-
- /**
- * Transfers ownership of result.
- */
- virtual LoginWindow* createLoginWindow(UIEventStream* uiEventStream) = 0;
-
- };
+ class LoginWindow;
+
+ class UIEventStream;
+
+ class LoginWindowFactory {
+ public:
+ virtual ~LoginWindowFactory() {}
+
+ /**
+ * Transfers ownership of result.
+ */
+ virtual LoginWindow* createLoginWindow(UIEventStream* uiEventStream) = 0;
+
+ };
}
#endif
diff --git a/Swift/Controllers/UIInterfaces/MUCSearchWindow.h b/Swift/Controllers/UIInterfaces/MUCSearchWindow.h
index 10c6b38..d6c0065 100644
--- a/Swift/Controllers/UIInterfaces/MUCSearchWindow.h
+++ b/Swift/Controllers/UIInterfaces/MUCSearchWindow.h
@@ -18,18 +18,18 @@
namespace Swift {
- class MUCSearchWindow {
- public:
- virtual ~MUCSearchWindow() {}
+ class MUCSearchWindow {
+ public:
+ virtual ~MUCSearchWindow() {}
- virtual void clearList() = 0;
- virtual void addService(const MUCService& service) = 0;
- virtual void addSavedServices(const std::list<JID>& services) = 0;
- virtual void setSearchInProgress(bool searching) = 0;
+ virtual void clearList() = 0;
+ virtual void addService(const MUCService& service) = 0;
+ virtual void addSavedServices(const std::list<JID>& services) = 0;
+ virtual void setSearchInProgress(bool searching) = 0;
- virtual void show() = 0;
+ virtual void show() = 0;
- boost::signal<void (const JID&)> onSearchService;
- boost::signal<void (const boost::optional<JID>&)> onFinished;
- };
+ boost::signal<void (const JID&)> onSearchService;
+ boost::signal<void (const boost::optional<JID>&)> onFinished;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
index 38492cd..6e26ac3 100644
--- a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
@@ -9,11 +9,11 @@
#include <Swift/Controllers/UIInterfaces/MUCSearchWindow.h>
namespace Swift {
- class UIEventStream;
- class MUCSearchWindowFactory {
- public:
- virtual ~MUCSearchWindowFactory() {}
+ class UIEventStream;
+ class MUCSearchWindowFactory {
+ public:
+ virtual ~MUCSearchWindowFactory() {}
- virtual MUCSearchWindow* createMUCSearchWindow() = 0;
- };
+ virtual MUCSearchWindow* createMUCSearchWindow() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/MainWindow.h b/Swift/Controllers/UIInterfaces/MainWindow.h
index aa8314d..d8bcb58 100644
--- a/Swift/Controllers/UIInterfaces/MainWindow.h
+++ b/Swift/Controllers/UIInterfaces/MainWindow.h
@@ -19,36 +19,36 @@
#include <Swift/Controllers/Roster/ContactRosterItem.h>
namespace Swift {
- class Roster;
-
- class MainWindow {
- public:
- MainWindow(bool candelete = true) : canDelete_(candelete) {}
- virtual ~MainWindow() {}
-
- bool canDelete() const {
- return canDelete_;
- }
-
- virtual void setMyNick(const std::string& name) = 0;
- virtual void setMyJID(const JID& jid) = 0;
- virtual void setMyAvatarPath(const std::string& path) = 0;
- virtual void setMyStatusText(const std::string& status) = 0;
- virtual void setMyStatusType(StatusShow::Type type) = 0;
- virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) = 0;
- /** Must be able to cope with NULL to clear the roster */
- virtual void setRosterModel(Roster* roster) = 0;
- virtual void setConnecting() = 0;
- virtual void setBlockingCommandAvailable(bool isAvailable) = 0;
- virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) = 0;
- virtual void setStreamEncryptionStatus(bool tlsInPlaceAndValid) = 0;
- virtual void openCertificateDialog(const std::vector<Certificate::ref>& chain) = 0;
-
- boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
- boost::signal<void ()> onSignOutRequest;
- boost::signal<void ()> onShowCertificateRequest;
-
- private:
- bool canDelete_;
- };
+ class Roster;
+
+ class MainWindow {
+ public:
+ MainWindow(bool candelete = true) : canDelete_(candelete) {}
+ virtual ~MainWindow() {}
+
+ bool canDelete() const {
+ return canDelete_;
+ }
+
+ virtual void setMyNick(const std::string& name) = 0;
+ virtual void setMyJID(const JID& jid) = 0;
+ virtual void setMyAvatarPath(const std::string& path) = 0;
+ virtual void setMyStatusText(const std::string& status) = 0;
+ virtual void setMyStatusType(StatusShow::Type type) = 0;
+ virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) = 0;
+ /** Must be able to cope with NULL to clear the roster */
+ virtual void setRosterModel(Roster* roster) = 0;
+ virtual void setConnecting() = 0;
+ virtual void setBlockingCommandAvailable(bool isAvailable) = 0;
+ virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) = 0;
+ virtual void setStreamEncryptionStatus(bool tlsInPlaceAndValid) = 0;
+ virtual void openCertificateDialog(const std::vector<Certificate::ref>& chain) = 0;
+
+ boost::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
+ boost::signal<void ()> onSignOutRequest;
+ boost::signal<void ()> onShowCertificateRequest;
+
+ private:
+ bool canDelete_;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/MainWindowFactory.h b/Swift/Controllers/UIInterfaces/MainWindowFactory.h
index 5c24187..c0110cf 100644
--- a/Swift/Controllers/UIInterfaces/MainWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/MainWindowFactory.h
@@ -11,17 +11,17 @@
#include "Swift/Controllers/UIEvents/UIEventStream.h"
namespace Swift {
- class MainWindow;
+ class MainWindow;
- class MainWindowFactory {
- public:
- virtual ~MainWindowFactory() {}
- /**
- * Transfers ownership of result.
- */
- virtual MainWindow* createMainWindow(UIEventStream* eventStream) = 0;
+ class MainWindowFactory {
+ public:
+ virtual ~MainWindowFactory() {}
+ /**
+ * Transfers ownership of result.
+ */
+ virtual MainWindow* createMainWindow(UIEventStream* eventStream) = 0;
- };
+ };
}
#endif
diff --git a/Swift/Controllers/UIInterfaces/ProfileWindow.h b/Swift/Controllers/UIInterfaces/ProfileWindow.h
index f396499..8aa620c 100644
--- a/Swift/Controllers/UIInterfaces/ProfileWindow.h
+++ b/Swift/Controllers/UIInterfaces/ProfileWindow.h
@@ -12,24 +12,24 @@
#include <Swiften/Elements/VCard.h>
namespace Swift {
- class JID;
+ class JID;
- class ProfileWindow {
- public:
- virtual ~ProfileWindow() {}
+ class ProfileWindow {
+ public:
+ virtual ~ProfileWindow() {}
- virtual void setJID(const JID& jid) = 0;
- virtual void setVCard(VCard::ref vcard) = 0;
+ virtual void setJID(const JID& jid) = 0;
+ virtual void setVCard(VCard::ref vcard) = 0;
- virtual void setEnabled(bool b) = 0;
- virtual void setProcessing(bool b) = 0;
- virtual void setError(const std::string&) = 0;
- virtual void setEditable(bool b) = 0;
+ virtual void setEnabled(bool b) = 0;
+ virtual void setProcessing(bool b) = 0;
+ virtual void setError(const std::string&) = 0;
+ virtual void setEditable(bool b) = 0;
- virtual void show() = 0;
- virtual void hide() = 0;
+ virtual void show() = 0;
+ virtual void hide() = 0;
- boost::signal<void (VCard::ref)> onVCardChangeRequest;
- boost::signal<void (const JID&)> onWindowAboutToBeClosed;
- };
+ boost::signal<void (VCard::ref)> onVCardChangeRequest;
+ boost::signal<void (const JID&)> onWindowAboutToBeClosed;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h b/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h
index 5137151..6c2c6e5 100644
--- a/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h
@@ -9,10 +9,10 @@
#include <Swift/Controllers/UIInterfaces/ProfileWindow.h>
namespace Swift {
- class ProfileWindowFactory {
- public:
- virtual ~ProfileWindowFactory() {}
+ class ProfileWindowFactory {
+ public:
+ virtual ~ProfileWindowFactory() {}
- virtual ProfileWindow* createProfileWindow() = 0;
- };
+ virtual ProfileWindow* createProfileWindow() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/UIFactory.h b/Swift/Controllers/UIInterfaces/UIFactory.h
index dd9d0df..a0976dc 100644
--- a/Swift/Controllers/UIInterfaces/UIFactory.h
+++ b/Swift/Controllers/UIInterfaces/UIFactory.h
@@ -25,25 +25,25 @@
#include <Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h>
namespace Swift {
- class UIFactory :
- public ChatListWindowFactory,
- public ChatWindowFactory,
- public HistoryWindowFactory,
- public EventWindowFactory,
- public LoginWindowFactory,
- public MainWindowFactory,
- public MUCSearchWindowFactory,
- public XMLConsoleWidgetFactory,
- public UserSearchWindowFactory,
- public JoinMUCWindowFactory,
- public ProfileWindowFactory,
- public ContactEditWindowFactory,
- public AdHocCommandWindowFactory,
- public FileTransferListWidgetFactory,
- public WhiteboardWindowFactory,
- public HighlightEditorWindowFactory,
- public BlockListEditorWidgetFactory {
- public:
- virtual ~UIFactory() {}
- };
+ class UIFactory :
+ public ChatListWindowFactory,
+ public ChatWindowFactory,
+ public HistoryWindowFactory,
+ public EventWindowFactory,
+ public LoginWindowFactory,
+ public MainWindowFactory,
+ public MUCSearchWindowFactory,
+ public XMLConsoleWidgetFactory,
+ public UserSearchWindowFactory,
+ public JoinMUCWindowFactory,
+ public ProfileWindowFactory,
+ public ContactEditWindowFactory,
+ public AdHocCommandWindowFactory,
+ public FileTransferListWidgetFactory,
+ public WhiteboardWindowFactory,
+ public HighlightEditorWindowFactory,
+ public BlockListEditorWidgetFactory {
+ public:
+ virtual ~UIFactory() {}
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/UserSearchWindow.h b/Swift/Controllers/UIInterfaces/UserSearchWindow.h
index da33db3..4ddc29b 100644
--- a/Swift/Controllers/UIInterfaces/UserSearchWindow.h
+++ b/Swift/Controllers/UIInterfaces/UserSearchWindow.h
@@ -17,40 +17,40 @@
namespace Swift {
- class UserSearchWindow {
- public:
- enum Type {AddContact, ChatToContact, InviteToChat};
- virtual ~UserSearchWindow() {}
-
- virtual void clear() = 0;
- virtual void setResults(const std::vector<UserSearchResult>& results) = 0;
- virtual void setResultsForm(const Form::ref results) = 0;
- virtual void addSavedServices(const std::vector<JID>& services) = 0;
- virtual void setSelectedService(const JID& service) = 0;
- virtual void setServerSupportsSearch(bool support) = 0;
- virtual void setSearchError(bool support) = 0;
- virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields) = 0;
- virtual void setNameSuggestions(const std::vector<std::string>& suggestions) = 0;
- virtual void prepopulateJIDAndName(const JID& jid, const std::string& name) = 0;
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions) = 0;
- virtual void setJIDs(const std::vector<JID>&) = 0;
- virtual void setRoomJID(const JID& roomJID) = 0;
- virtual std::string getReason() const = 0;
- virtual std::vector<JID> getJIDs() const = 0;
- virtual void setCanStartImpromptuChats(bool supportsImpromptu) = 0;
- virtual void updateContacts(const std::vector<Contact::ref>& contacts) = 0;
- virtual void addContacts(const std::vector<Contact::ref>& contacts) = 0;
- virtual void setCanSupplyDescription(bool allowed) = 0;
- virtual void setWarning(const boost::optional<std::string>& message) = 0;
-
- virtual void show() = 0;
-
- boost::signal<void (const JID&)> onFormRequested;
- boost::signal<void (boost::shared_ptr<SearchPayload>, const JID&)> onSearchRequested;
- boost::signal<void (const JID&)> onNameSuggestionRequested;
- boost::signal<void (const std::string&)> onContactSuggestionsRequested;
- boost::signal<void (const std::vector<JID>&)> onJIDUpdateRequested;
- boost::signal<void (const std::vector<JID>&)> onJIDAddRequested;
- boost::signal<void (const JID&)> onJIDEditFieldChanged;
- };
+ class UserSearchWindow {
+ public:
+ enum Type {AddContact, ChatToContact, InviteToChat};
+ virtual ~UserSearchWindow() {}
+
+ virtual void clear() = 0;
+ virtual void setResults(const std::vector<UserSearchResult>& results) = 0;
+ virtual void setResultsForm(const Form::ref results) = 0;
+ virtual void addSavedServices(const std::vector<JID>& services) = 0;
+ virtual void setSelectedService(const JID& service) = 0;
+ virtual void setServerSupportsSearch(bool support) = 0;
+ virtual void setSearchError(bool support) = 0;
+ virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields) = 0;
+ virtual void setNameSuggestions(const std::vector<std::string>& suggestions) = 0;
+ virtual void prepopulateJIDAndName(const JID& jid, const std::string& name) = 0;
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions) = 0;
+ virtual void setJIDs(const std::vector<JID>&) = 0;
+ virtual void setRoomJID(const JID& roomJID) = 0;
+ virtual std::string getReason() const = 0;
+ virtual std::vector<JID> getJIDs() const = 0;
+ virtual void setCanStartImpromptuChats(bool supportsImpromptu) = 0;
+ virtual void updateContacts(const std::vector<Contact::ref>& contacts) = 0;
+ virtual void addContacts(const std::vector<Contact::ref>& contacts) = 0;
+ virtual void setCanSupplyDescription(bool allowed) = 0;
+ virtual void setWarning(const boost::optional<std::string>& message) = 0;
+
+ virtual void show() = 0;
+
+ boost::signal<void (const JID&)> onFormRequested;
+ boost::signal<void (boost::shared_ptr<SearchPayload>, const JID&)> onSearchRequested;
+ boost::signal<void (const JID&)> onNameSuggestionRequested;
+ boost::signal<void (const std::string&)> onContactSuggestionsRequested;
+ boost::signal<void (const std::vector<JID>&)> onJIDUpdateRequested;
+ boost::signal<void (const std::vector<JID>&)> onJIDAddRequested;
+ boost::signal<void (const JID&)> onJIDEditFieldChanged;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
index 4eee510..d5d6135 100644
--- a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
@@ -11,11 +11,11 @@
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
namespace Swift {
- class UIEventStream;
- class UserSearchWindowFactory {
- public:
- virtual ~UserSearchWindowFactory() {}
+ class UIEventStream;
+ class UserSearchWindowFactory {
+ public:
+ virtual ~UserSearchWindowFactory() {}
- virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups) = 0;
- };
+ virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/WhiteboardWindow.h b/Swift/Controllers/UIInterfaces/WhiteboardWindow.h
index 84aefde..f3b35db 100644
--- a/Swift/Controllers/UIInterfaces/WhiteboardWindow.h
+++ b/Swift/Controllers/UIInterfaces/WhiteboardWindow.h
@@ -17,16 +17,16 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class WhiteboardSession;
- class WhiteboardElement;
+ class WhiteboardSession;
+ class WhiteboardElement;
- class WhiteboardWindow {
- public:
- virtual ~WhiteboardWindow() {}
+ class WhiteboardWindow {
+ public:
+ virtual ~WhiteboardWindow() {}
- virtual void show() = 0;
- virtual void setSession(boost::shared_ptr<WhiteboardSession> session) = 0;
- virtual void activateWindow() = 0;
- virtual void setName(const std::string& name) = 0;
- };
+ virtual void show() = 0;
+ virtual void setSession(boost::shared_ptr<WhiteboardSession> session) = 0;
+ virtual void activateWindow() = 0;
+ virtual void setName(const std::string& name) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h b/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h
index 2be0f9c..163368b 100644
--- a/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h
@@ -7,13 +7,13 @@
#pragma once
namespace Swift {
- class WhiteboardSession;
- class WhiteboardWindow;
+ class WhiteboardSession;
+ class WhiteboardWindow;
- class WhiteboardWindowFactory {
- public :
- virtual ~WhiteboardWindowFactory() {}
+ class WhiteboardWindowFactory {
+ public :
+ virtual ~WhiteboardWindowFactory() {}
- virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession) = 0;
- };
+ virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h
index 7e477a9..872b9de 100644
--- a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h
+++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h
@@ -9,14 +9,14 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class XMLConsoleWidget {
- public:
- virtual ~XMLConsoleWidget();
+ class XMLConsoleWidget {
+ public:
+ virtual ~XMLConsoleWidget();
- virtual void handleDataRead(const SafeByteArray& data) = 0;
- virtual void handleDataWritten(const SafeByteArray& data) = 0;
+ virtual void handleDataRead(const SafeByteArray& data) = 0;
+ virtual void handleDataWritten(const SafeByteArray& data) = 0;
- virtual void show() = 0;
- virtual void activate() = 0;
- };
+ virtual void show() = 0;
+ virtual void activate() = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h b/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h
index 69b3e16..bbc055e 100644
--- a/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h
@@ -9,11 +9,11 @@
#include <Swift/Controllers/UIInterfaces/XMLConsoleWidget.h>
namespace Swift {
- class UIEventStream;
- class XMLConsoleWidgetFactory {
- public:
- virtual ~XMLConsoleWidgetFactory() {}
+ class UIEventStream;
+ class XMLConsoleWidgetFactory {
+ public:
+ virtual ~XMLConsoleWidgetFactory() {}
- virtual XMLConsoleWidget* createXMLConsoleWidget() = 0;
- };
+ virtual XMLConsoleWidget* createXMLConsoleWidget() = 0;
+ };
}
diff --git a/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp b/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp
index 118c502..59c57b9 100644
--- a/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp
+++ b/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp
@@ -13,109 +13,109 @@ using namespace Swift;
using namespace std;
class ChatMessageSummarizerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ChatMessageSummarizerTest);
- CPPUNIT_TEST(testEmpty);
- CPPUNIT_TEST(testCurrentNone);
- CPPUNIT_TEST(testCurrentCount);
- CPPUNIT_TEST(testCurrentCountOthersNone);
- CPPUNIT_TEST(testCurrentCountOtherCount);
- CPPUNIT_TEST(testCurrentNoneOtherCount);
- CPPUNIT_TEST(testCurrentCountOthersCount);
- CPPUNIT_TEST(testCurrentNoneOthersCount);
- CPPUNIT_TEST(testCurrentCountSomeOthersCount);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ChatMessageSummarizerTest);
+ CPPUNIT_TEST(testEmpty);
+ CPPUNIT_TEST(testCurrentNone);
+ CPPUNIT_TEST(testCurrentCount);
+ CPPUNIT_TEST(testCurrentCountOthersNone);
+ CPPUNIT_TEST(testCurrentCountOtherCount);
+ CPPUNIT_TEST(testCurrentNoneOtherCount);
+ CPPUNIT_TEST(testCurrentCountOthersCount);
+ CPPUNIT_TEST(testCurrentNoneOthersCount);
+ CPPUNIT_TEST(testCurrentCountSomeOthersCount);
+ CPPUNIT_TEST_SUITE_END();
public:
- ChatMessageSummarizerTest() {}
-
- void setUp() {
-
- }
-
- void testEmpty() {
- string current("");
- vector<UnreadPair> unreads;
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads));
- }
-
- void testCurrentNone() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bob", 0));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads));
- }
-
- void testCurrentCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bob", 3));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentCountOthersNone() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 0));
- unreads.push_back(UnreadPair("Bob", 3));
- unreads.push_back(UnreadPair("Betty", 0));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentCountOtherCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 0));
- unreads.push_back(UnreadPair("Bob", 3));
- unreads.push_back(UnreadPair("Betty", 7));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob (3); Betty (7)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentNoneOtherCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 0));
- unreads.push_back(UnreadPair("Bob", 0));
- unreads.push_back(UnreadPair("Betty", 7));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob; Betty (7)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentNoneOthersCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 2));
- unreads.push_back(UnreadPair("Bob", 0));
- unreads.push_back(UnreadPair("Betty", 7));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob and 2 others (9)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentCountOthersCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 2));
- unreads.push_back(UnreadPair("Bob", 11));
- unreads.push_back(UnreadPair("Betty", 7));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads));
- }
-
- void testCurrentCountSomeOthersCount() {
- string current("Bob");
- vector<UnreadPair> unreads;
- unreads.push_back(UnreadPair("Bert", 2));
- unreads.push_back(UnreadPair("Beverly", 0));
- unreads.push_back(UnreadPair("Bob", 11));
- unreads.push_back(UnreadPair("Beatrice", 0));
- unreads.push_back(UnreadPair("Betty", 7));
- ChatMessageSummarizer summary;
- CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads));
- }
+ ChatMessageSummarizerTest() {}
+
+ void setUp() {
+
+ }
+
+ void testEmpty() {
+ string current("");
+ vector<UnreadPair> unreads;
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads));
+ }
+
+ void testCurrentNone() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bob", 0));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads));
+ }
+
+ void testCurrentCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bob", 3));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentCountOthersNone() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 0));
+ unreads.push_back(UnreadPair("Bob", 3));
+ unreads.push_back(UnreadPair("Betty", 0));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentCountOtherCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 0));
+ unreads.push_back(UnreadPair("Bob", 3));
+ unreads.push_back(UnreadPair("Betty", 7));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob (3); Betty (7)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentNoneOtherCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 0));
+ unreads.push_back(UnreadPair("Bob", 0));
+ unreads.push_back(UnreadPair("Betty", 7));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob; Betty (7)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentNoneOthersCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 2));
+ unreads.push_back(UnreadPair("Bob", 0));
+ unreads.push_back(UnreadPair("Betty", 7));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob and 2 others (9)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentCountOthersCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 2));
+ unreads.push_back(UnreadPair("Bob", 11));
+ unreads.push_back(UnreadPair("Betty", 7));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads));
+ }
+
+ void testCurrentCountSomeOthersCount() {
+ string current("Bob");
+ vector<UnreadPair> unreads;
+ unreads.push_back(UnreadPair("Bert", 2));
+ unreads.push_back(UnreadPair("Beverly", 0));
+ unreads.push_back(UnreadPair("Bob", 11));
+ unreads.push_back(UnreadPair("Beatrice", 0));
+ unreads.push_back(UnreadPair("Betty", 7));
+ ChatMessageSummarizer summary;
+ CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads));
+ }
};
diff --git a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
index 9b625fe..2bfca4b 100644
--- a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
+++ b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
@@ -18,111 +18,111 @@
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();
+ 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) {
- contacts.push_back(boost::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) {
- 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) {
- 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) {
- 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) {
- CPPUNIT_ASSERT(isTransitive(boost::bind(Contact::sortPredicate, _1, _2, word)));
- }
- }
+ 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) {
+ contacts.push_back(boost::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) {
+ 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) {
+ 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) {
+ 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) {
+ CPPUNIT_ASSERT(isTransitive(boost::bind(Contact::sortPredicate, _1, _2, word)));
+ }
+ }
};
diff --git a/Swift/Controllers/UnitTest/HighlightRuleTest.cpp b/Swift/Controllers/UnitTest/HighlightRuleTest.cpp
index 62c403f..8d49d5d 100644
--- a/Swift/Controllers/UnitTest/HighlightRuleTest.cpp
+++ b/Swift/Controllers/UnitTest/HighlightRuleTest.cpp
@@ -21,304 +21,304 @@
using namespace Swift;
class HighlightRuleTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(HighlightRuleTest);
- CPPUNIT_TEST(testEmptyRuleNeverMatches);
- CPPUNIT_TEST(testKeyword);
- CPPUNIT_TEST(testNickKeyword);
- CPPUNIT_TEST(testNickWithoutOtherKeywords);
- CPPUNIT_TEST(testSender);
- CPPUNIT_TEST(testSenderAndKeyword);
- CPPUNIT_TEST(testWholeWords);
- CPPUNIT_TEST(testCase);
- CPPUNIT_TEST(testWholeWordsAndCase);
- CPPUNIT_TEST(testMUC);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- std::vector<std::string> keywords;
- keywords.push_back("keyword1");
- keywords.push_back("KEYWORD2");
-
- std::vector<std::string> senders;
- senders.push_back("sender1");
- senders.push_back("SENDER2");
-
- emptyRule = new HighlightRule();
-
- keywordRule = new HighlightRule();
- keywordRule->setKeywords(keywords);
-
- keywordChatRule = new HighlightRule();
- keywordChatRule->setKeywords(keywords);
- keywordChatRule->setMatchChat(true);
-
- keywordNickChatRule = new HighlightRule();
- keywordNickChatRule->setKeywords(keywords);
- keywordNickChatRule->setNickIsKeyword(true);
- keywordNickChatRule->setMatchChat(true);
-
- nickChatRule = new HighlightRule();
- nickChatRule->setNickIsKeyword(true);
- nickChatRule->setMatchChat(true);
-
- nickRule = new HighlightRule();
- nickRule->setNickIsKeyword(true);
-
- senderRule = new HighlightRule();
- senderRule->setSenders(senders);
-
- senderChatRule = new HighlightRule();
- senderChatRule->setSenders(senders);
- senderChatRule->setMatchChat(true);
-
- senderKeywordChatRule = new HighlightRule();
- senderKeywordChatRule->setSenders(senders);
- senderKeywordChatRule->setKeywords(keywords);
- senderKeywordChatRule->setMatchChat(true);
-
- senderKeywordNickChatRule = new HighlightRule();
- senderKeywordNickChatRule->setSenders(senders);
- senderKeywordNickChatRule->setKeywords(keywords);
- senderKeywordNickChatRule->setNickIsKeyword(true);
- senderKeywordNickChatRule->setMatchChat(true);
-
- senderKeywordNickWordChatRule = new HighlightRule();
- senderKeywordNickWordChatRule->setSenders(senders);
- senderKeywordNickWordChatRule->setKeywords(keywords);
- senderKeywordNickWordChatRule->setNickIsKeyword(true);
- senderKeywordNickWordChatRule->setMatchWholeWords(true);
- senderKeywordNickWordChatRule->setMatchChat(true);
-
- senderKeywordNickCaseChatRule = new HighlightRule();
- senderKeywordNickCaseChatRule->setSenders(senders);
- senderKeywordNickCaseChatRule->setKeywords(keywords);
- senderKeywordNickCaseChatRule->setNickIsKeyword(true);
- senderKeywordNickCaseChatRule->setMatchCase(true);
- senderKeywordNickCaseChatRule->setMatchChat(true);
-
- senderKeywordNickCaseWordChatRule = new HighlightRule();
- senderKeywordNickCaseWordChatRule->setSenders(senders);
- senderKeywordNickCaseWordChatRule->setKeywords(keywords);
- senderKeywordNickCaseWordChatRule->setNickIsKeyword(true);
- senderKeywordNickCaseWordChatRule->setMatchCase(true);
- senderKeywordNickCaseWordChatRule->setMatchWholeWords(true);
- senderKeywordNickCaseWordChatRule->setMatchChat(true);
-
- senderKeywordNickMUCRule = new HighlightRule();
- senderKeywordNickMUCRule->setSenders(senders);
- senderKeywordNickMUCRule->setKeywords(keywords);
- senderKeywordNickMUCRule->setNickIsKeyword(true);
- senderKeywordNickMUCRule->setMatchMUC(true);
- }
+ CPPUNIT_TEST_SUITE(HighlightRuleTest);
+ CPPUNIT_TEST(testEmptyRuleNeverMatches);
+ CPPUNIT_TEST(testKeyword);
+ CPPUNIT_TEST(testNickKeyword);
+ CPPUNIT_TEST(testNickWithoutOtherKeywords);
+ CPPUNIT_TEST(testSender);
+ CPPUNIT_TEST(testSenderAndKeyword);
+ CPPUNIT_TEST(testWholeWords);
+ CPPUNIT_TEST(testCase);
+ CPPUNIT_TEST(testWholeWordsAndCase);
+ CPPUNIT_TEST(testMUC);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ std::vector<std::string> keywords;
+ keywords.push_back("keyword1");
+ keywords.push_back("KEYWORD2");
+
+ std::vector<std::string> senders;
+ senders.push_back("sender1");
+ senders.push_back("SENDER2");
+
+ emptyRule = new HighlightRule();
+
+ keywordRule = new HighlightRule();
+ keywordRule->setKeywords(keywords);
+
+ keywordChatRule = new HighlightRule();
+ keywordChatRule->setKeywords(keywords);
+ keywordChatRule->setMatchChat(true);
+
+ keywordNickChatRule = new HighlightRule();
+ keywordNickChatRule->setKeywords(keywords);
+ keywordNickChatRule->setNickIsKeyword(true);
+ keywordNickChatRule->setMatchChat(true);
+
+ nickChatRule = new HighlightRule();
+ nickChatRule->setNickIsKeyword(true);
+ nickChatRule->setMatchChat(true);
+
+ nickRule = new HighlightRule();
+ nickRule->setNickIsKeyword(true);
+
+ senderRule = new HighlightRule();
+ senderRule->setSenders(senders);
+
+ senderChatRule = new HighlightRule();
+ senderChatRule->setSenders(senders);
+ senderChatRule->setMatchChat(true);
+
+ senderKeywordChatRule = new HighlightRule();
+ senderKeywordChatRule->setSenders(senders);
+ senderKeywordChatRule->setKeywords(keywords);
+ senderKeywordChatRule->setMatchChat(true);
+
+ senderKeywordNickChatRule = new HighlightRule();
+ senderKeywordNickChatRule->setSenders(senders);
+ senderKeywordNickChatRule->setKeywords(keywords);
+ senderKeywordNickChatRule->setNickIsKeyword(true);
+ senderKeywordNickChatRule->setMatchChat(true);
+
+ senderKeywordNickWordChatRule = new HighlightRule();
+ senderKeywordNickWordChatRule->setSenders(senders);
+ senderKeywordNickWordChatRule->setKeywords(keywords);
+ senderKeywordNickWordChatRule->setNickIsKeyword(true);
+ senderKeywordNickWordChatRule->setMatchWholeWords(true);
+ senderKeywordNickWordChatRule->setMatchChat(true);
+
+ senderKeywordNickCaseChatRule = new HighlightRule();
+ senderKeywordNickCaseChatRule->setSenders(senders);
+ senderKeywordNickCaseChatRule->setKeywords(keywords);
+ senderKeywordNickCaseChatRule->setNickIsKeyword(true);
+ senderKeywordNickCaseChatRule->setMatchCase(true);
+ senderKeywordNickCaseChatRule->setMatchChat(true);
+
+ senderKeywordNickCaseWordChatRule = new HighlightRule();
+ senderKeywordNickCaseWordChatRule->setSenders(senders);
+ senderKeywordNickCaseWordChatRule->setKeywords(keywords);
+ senderKeywordNickCaseWordChatRule->setNickIsKeyword(true);
+ senderKeywordNickCaseWordChatRule->setMatchCase(true);
+ senderKeywordNickCaseWordChatRule->setMatchWholeWords(true);
+ senderKeywordNickCaseWordChatRule->setMatchChat(true);
+
+ senderKeywordNickMUCRule = new HighlightRule();
+ senderKeywordNickMUCRule->setSenders(senders);
+ senderKeywordNickMUCRule->setKeywords(keywords);
+ senderKeywordNickMUCRule->setNickIsKeyword(true);
+ senderKeywordNickMUCRule->setMatchMUC(true);
+ }
- void tearDown() {
- delete emptyRule;
+ void tearDown() {
+ delete emptyRule;
- delete keywordRule;
- delete keywordChatRule;
- delete keywordNickChatRule;
- delete nickChatRule;
- delete nickRule;
-
- delete senderRule;
- delete senderChatRule;
- delete senderKeywordChatRule;
- delete senderKeywordNickChatRule;
+ delete keywordRule;
+ delete keywordChatRule;
+ delete keywordNickChatRule;
+ delete nickChatRule;
+ delete nickRule;
+
+ delete senderRule;
+ delete senderChatRule;
+ delete senderKeywordChatRule;
+ delete senderKeywordNickChatRule;
- delete senderKeywordNickWordChatRule;
- delete senderKeywordNickCaseChatRule;
- delete senderKeywordNickCaseWordChatRule;
+ delete senderKeywordNickWordChatRule;
+ delete senderKeywordNickCaseChatRule;
+ delete senderKeywordNickCaseWordChatRule;
- delete senderKeywordNickMUCRule;
- }
+ delete senderKeywordNickMUCRule;
+ }
- void testEmptyRuleNeverMatches() {
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
+ void testEmptyRuleNeverMatches() {
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::MUCMessage), false);
- }
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::MUCMessage), false);
+ }
- void testKeyword() {
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
+ void testKeyword() {
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "sender contains keyword1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "sender contains keyword1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc keyword1 xyz", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abckeyword1xyz", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc keyword1 xyz", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abckeyword1xyz", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("KEYword1", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc KEYword1 xyz", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abcKEYword1xyz", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("KEYword1", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc KEYword1 xyz", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abcKEYword1xyz", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword2", "from", "nick", HighlightRule::ChatMessage), true);
- }
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword2", "from", "nick", HighlightRule::ChatMessage), true);
+ }
- void testNickKeyword() {
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false);
+ void testNickKeyword() {
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "sender contains nick", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "sender contains nick", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains mixed-case NiCk", "sender", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains mixed-case NiCk", "sender", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false);
- }
+ CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false);
+ }
- void testNickWithoutOtherKeywords() {
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(nickRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false);
+ void testNickWithoutOtherKeywords() {
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(nickRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "sender contains nick but it does't matter", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "sender contains nick but it does't matter", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains mixed-case NiCk", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains mixed-case NiCk", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true);
- // there are no keywords in this rule and empty nick is not treated as a keyword, so we don't check for keywords to get a match
- CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), true);
- }
+ // there are no keywords in this rule and empty nick is not treated as a keyword, so we don't check for keywords to get a match
+ CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), true);
+ }
- void testSender() {
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
+ void testSender() {
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::MUCMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::MUCMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body contains sender1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body contains sender1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc sender1 xyz", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcsender1xyz", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc sender1 xyz", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcsender1xyz", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "SENDer1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc SENDer1 xyz", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcSENDer1xyz", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "SENDer1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc SENDer1 xyz", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcSENDer1xyz", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender2", "nick", HighlightRule::ChatMessage), true);
- }
+ CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender2", "nick", HighlightRule::ChatMessage), true);
+ }
- void testSenderAndKeyword() {
- CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
- }
+ void testSenderAndKeyword() {
+ CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
+ }
- void testWholeWords() {
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
+ void testWholeWords() {
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), true);
- }
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), true);
+ }
- void testCase() {
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
+ void testCase() {
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("xkeyword1", "xsender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("xkeyword1", "xsender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false);
- }
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false);
+ }
- void testWholeWordsAndCase() {
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
+ void testWholeWordsAndCase() {
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false);
- }
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false);
+ }
- void testMUC() {
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
+ void testMUC() {
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::MUCMessage), true);
- CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::MUCMessage), true);
- }
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), false);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::MUCMessage), true);
+ CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::MUCMessage), true);
+ }
- private:
- HighlightRule* emptyRule;
+ private:
+ HighlightRule* emptyRule;
- HighlightRule* keywordRule;
- HighlightRule* keywordChatRule;
- HighlightRule* keywordNickChatRule;
- HighlightRule* nickChatRule;
- HighlightRule* nickRule;
+ HighlightRule* keywordRule;
+ HighlightRule* keywordChatRule;
+ HighlightRule* keywordNickChatRule;
+ HighlightRule* nickChatRule;
+ HighlightRule* nickRule;
- HighlightRule* senderRule;
- HighlightRule* senderChatRule;
- HighlightRule* senderKeywordChatRule;
- HighlightRule* senderKeywordNickChatRule;
+ HighlightRule* senderRule;
+ HighlightRule* senderChatRule;
+ HighlightRule* senderKeywordChatRule;
+ HighlightRule* senderKeywordNickChatRule;
- HighlightRule* senderKeywordNickWordChatRule;
- HighlightRule* senderKeywordNickCaseChatRule;
- HighlightRule* senderKeywordNickCaseWordChatRule;
+ HighlightRule* senderKeywordNickWordChatRule;
+ HighlightRule* senderKeywordNickCaseChatRule;
+ HighlightRule* senderKeywordNickCaseWordChatRule;
- HighlightRule* senderKeywordNickMUCRule;
+ HighlightRule* senderKeywordNickMUCRule;
};
CPPUNIT_TEST_SUITE_REGISTRATION(HighlightRuleTest);
diff --git a/Swift/Controllers/UnitTest/MockChatWindow.h b/Swift/Controllers/UnitTest/MockChatWindow.h
index 20c51bc..b4588e7 100644
--- a/Swift/Controllers/UnitTest/MockChatWindow.h
+++ b/Swift/Controllers/UnitTest/MockChatWindow.h
@@ -13,103 +13,103 @@
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
namespace Swift {
- class MockChatWindow : public ChatWindow {
- public:
- MockChatWindow() : labelsEnabled_(false), impromptuMUCSupported_(false) {}
- virtual ~MockChatWindow();
-
- virtual std::string addMessage(const ChatMessage& message, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {
- lastMessageBody_ = bodyFromMessage(message);
- return "id";
- }
-
- virtual std::string addAction(const ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {return "id";}
-
- virtual std::string addSystemMessage(const ChatMessage& message, Direction /*direction*/) {
- lastAddedSystemMessage_ = message;
- return "id";
- }
-
- virtual void addPresenceMessage(const ChatMessage& message, Direction /*direction*/) {
- lastAddedPresence_ = message;
- }
-
- virtual void addErrorMessage(const ChatMessage& /*message*/) {}
- virtual void replaceMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {}
- virtual void replaceWithAction(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {}
- virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour /*timestampBehaviour*/) {
- lastReplacedMessage_ = message;
- }
- virtual void replaceSystemMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const TimestampBehaviour /*timestampBehaviour*/) {}
-
- // File transfer related stuff
- virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/,const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/) { return 0; }
- virtual void setFileTransferProgress(std::string /*id*/, const int /*alreadyTransferedBytes*/) { }
- virtual void setFileTransferStatus(std::string /*id*/, const FileTransferState /*state*/, const std::string& /*msg*/) { }
-
- virtual void setMessageReceiptState(const std::string &/* id */, ReceiptState /* state */) { }
-
- virtual void setContactChatState(ChatState::ChatStateType /*state*/) {}
- virtual void setName(const std::string& name) {name_ = name;}
- virtual void show() {}
- virtual bool isVisible() const { return true; }
- virtual void activate() {}
- virtual void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) {labels_ = labels;}
- virtual void setSecurityLabelsEnabled(bool enabled) {labelsEnabled_ = enabled;}
- virtual void setUnreadMessageCount(int /*count*/) {}
- virtual void convertToMUC(MUCType /*mucType*/) {}
- virtual void setSecurityLabelsError() {}
- virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() {return label_;}
- virtual void setOnline(bool /*online*/) {}
- virtual void setRosterModel(Roster* roster) { roster_ = roster; }
- Roster* getRosterModel() { return roster_; }
- virtual void setTabComplete(TabComplete*) {}
-
- void setAckState(const std::string& /*id*/, AckState /*state*/) {}
- virtual void flash() {}
- virtual AlertID addAlert(const std::string& /*alertText*/) { return 0; }
- virtual void removeAlert(const AlertID /*id*/) {}
- virtual void setCorrectionEnabled(Tristate /*enabled*/) {}
- virtual void setFileTransferEnabled(Tristate /*enabled*/) {}
- void setAvailableOccupantActions(const std::vector<OccupantAction>&/* actions*/) {}
- void setSubject(const std::string& /*subject*/) {}
- virtual void showRoomConfigurationForm(Form::ref) {}
- virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool = true, bool = false, bool = false) {}
-
- virtual std::string addWhiteboardRequest(bool) {return "";}
- virtual void setWhiteboardSessionStatus(std::string, const ChatWindow::WhiteboardSessionState){}
-
- virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&) {}
- virtual void setAvailableRoomActions(const std::vector<RoomAction> &) {}
-
- virtual void setBlockingState(BlockingState) {}
- virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) {
- impromptuMUCSupported_ = supportsImpromptu;
- }
-
- virtual void showBookmarkWindow(const MUCBookmark& /*bookmark*/) {}
- virtual void setBookmarkState(RoomBookmarkState) {}
-
- static std::string bodyFromMessage(const ChatMessage& message) {
- boost::shared_ptr<ChatTextMessagePart> text;
- foreach (boost::shared_ptr<ChatMessagePart> part, message.getParts()) {
- if ((text = boost::dynamic_pointer_cast<ChatTextMessagePart>(part))) {
- return text->text;
- }
- }
- return "";
- }
-
- std::string name_;
- std::string lastMessageBody_;
- ChatMessage lastAddedPresence_;
- ChatMessage lastReplacedMessage_;
- ChatMessage lastAddedSystemMessage_;
- std::vector<SecurityLabelsCatalog::Item> labels_;
- bool labelsEnabled_;
- bool impromptuMUCSupported_;
- SecurityLabelsCatalog::Item label_;
- Roster* roster_;
- };
+ class MockChatWindow : public ChatWindow {
+ public:
+ MockChatWindow() : labelsEnabled_(false), impromptuMUCSupported_(false) {}
+ virtual ~MockChatWindow();
+
+ virtual std::string addMessage(const ChatMessage& message, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {
+ lastMessageBody_ = bodyFromMessage(message);
+ return "id";
+ }
+
+ virtual std::string addAction(const ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {return "id";}
+
+ virtual std::string addSystemMessage(const ChatMessage& message, Direction /*direction*/) {
+ lastAddedSystemMessage_ = message;
+ return "id";
+ }
+
+ virtual void addPresenceMessage(const ChatMessage& message, Direction /*direction*/) {
+ lastAddedPresence_ = message;
+ }
+
+ virtual void addErrorMessage(const ChatMessage& /*message*/) {}
+ virtual void replaceMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {}
+ virtual void replaceWithAction(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {}
+ virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour /*timestampBehaviour*/) {
+ lastReplacedMessage_ = message;
+ }
+ virtual void replaceSystemMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const TimestampBehaviour /*timestampBehaviour*/) {}
+
+ // File transfer related stuff
+ virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/,const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/) { return 0; }
+ virtual void setFileTransferProgress(std::string /*id*/, const int /*alreadyTransferedBytes*/) { }
+ virtual void setFileTransferStatus(std::string /*id*/, const FileTransferState /*state*/, const std::string& /*msg*/) { }
+
+ virtual void setMessageReceiptState(const std::string &/* id */, ReceiptState /* state */) { }
+
+ virtual void setContactChatState(ChatState::ChatStateType /*state*/) {}
+ virtual void setName(const std::string& name) {name_ = name;}
+ virtual void show() {}
+ virtual bool isVisible() const { return true; }
+ virtual void activate() {}
+ virtual void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels) {labels_ = labels;}
+ virtual void setSecurityLabelsEnabled(bool enabled) {labelsEnabled_ = enabled;}
+ virtual void setUnreadMessageCount(int /*count*/) {}
+ virtual void convertToMUC(MUCType /*mucType*/) {}
+ virtual void setSecurityLabelsError() {}
+ virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() {return label_;}
+ virtual void setOnline(bool /*online*/) {}
+ virtual void setRosterModel(Roster* roster) { roster_ = roster; }
+ Roster* getRosterModel() { return roster_; }
+ virtual void setTabComplete(TabComplete*) {}
+
+ void setAckState(const std::string& /*id*/, AckState /*state*/) {}
+ virtual void flash() {}
+ virtual AlertID addAlert(const std::string& /*alertText*/) { return 0; }
+ virtual void removeAlert(const AlertID /*id*/) {}
+ virtual void setCorrectionEnabled(Tristate /*enabled*/) {}
+ virtual void setFileTransferEnabled(Tristate /*enabled*/) {}
+ void setAvailableOccupantActions(const std::vector<OccupantAction>&/* actions*/) {}
+ void setSubject(const std::string& /*subject*/) {}
+ virtual void showRoomConfigurationForm(Form::ref) {}
+ virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool = true, bool = false, bool = false) {}
+
+ virtual std::string addWhiteboardRequest(bool) {return "";}
+ virtual void setWhiteboardSessionStatus(std::string, const ChatWindow::WhiteboardSessionState){}
+
+ virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&) {}
+ virtual void setAvailableRoomActions(const std::vector<RoomAction> &) {}
+
+ virtual void setBlockingState(BlockingState) {}
+ virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) {
+ impromptuMUCSupported_ = supportsImpromptu;
+ }
+
+ virtual void showBookmarkWindow(const MUCBookmark& /*bookmark*/) {}
+ virtual void setBookmarkState(RoomBookmarkState) {}
+
+ static std::string bodyFromMessage(const ChatMessage& message) {
+ boost::shared_ptr<ChatTextMessagePart> text;
+ foreach (boost::shared_ptr<ChatMessagePart> part, message.getParts()) {
+ if ((text = boost::dynamic_pointer_cast<ChatTextMessagePart>(part))) {
+ return text->text;
+ }
+ }
+ return "";
+ }
+
+ std::string name_;
+ std::string lastMessageBody_;
+ ChatMessage lastAddedPresence_;
+ ChatMessage lastReplacedMessage_;
+ ChatMessage lastAddedSystemMessage_;
+ std::vector<SecurityLabelsCatalog::Item> labels_;
+ bool labelsEnabled_;
+ bool impromptuMUCSupported_;
+ SecurityLabelsCatalog::Item label_;
+ Roster* roster_;
+ };
}
diff --git a/Swift/Controllers/UnitTest/MockMainWindow.h b/Swift/Controllers/UnitTest/MockMainWindow.h
index af4267f..9177bdc 100644
--- a/Swift/Controllers/UnitTest/MockMainWindow.h
+++ b/Swift/Controllers/UnitTest/MockMainWindow.h
@@ -9,24 +9,24 @@
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
namespace Swift {
- class Roster;
- class MockMainWindow : public MainWindow {
- public:
- MockMainWindow() : roster(NULL) {}
- virtual ~MockMainWindow() {}
- virtual void setRosterModel(Roster* roster) {this->roster = roster;}
- virtual void setMyNick(const std::string& /*name*/) {}
- virtual void setMyJID(const JID& /*jid*/) {}
- virtual void setMyAvatarPath(const std::string& /*path*/) {}
- virtual void setMyStatusText(const std::string& /*status*/) {}
- virtual void setMyStatusType(StatusShow::Type /*type*/) {}
- virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> /*contact*/) {}
- virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& /*commands*/) {}
- virtual void setConnecting() {}
- virtual void setStreamEncryptionStatus(bool /*tlsInPlaceAndValid*/) {}
- virtual void openCertificateDialog(const std::vector<Certificate::ref>& /*chain*/) {}
- virtual void setBlockingCommandAvailable(bool /*isAvailable*/) {}
- Roster* roster;
+ class Roster;
+ class MockMainWindow : public MainWindow {
+ public:
+ MockMainWindow() : roster(NULL) {}
+ virtual ~MockMainWindow() {}
+ virtual void setRosterModel(Roster* roster) {this->roster = roster;}
+ virtual void setMyNick(const std::string& /*name*/) {}
+ virtual void setMyJID(const JID& /*jid*/) {}
+ virtual void setMyAvatarPath(const std::string& /*path*/) {}
+ virtual void setMyStatusText(const std::string& /*status*/) {}
+ virtual void setMyStatusType(StatusShow::Type /*type*/) {}
+ virtual void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> /*contact*/) {}
+ virtual void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& /*commands*/) {}
+ virtual void setConnecting() {}
+ virtual void setStreamEncryptionStatus(bool /*tlsInPlaceAndValid*/) {}
+ virtual void openCertificateDialog(const std::vector<Certificate::ref>& /*chain*/) {}
+ virtual void setBlockingCommandAvailable(bool /*isAvailable*/) {}
+ Roster* roster;
- };
+ };
}
diff --git a/Swift/Controllers/UnitTest/MockMainWindowFactory.h b/Swift/Controllers/UnitTest/MockMainWindowFactory.h
index 0298bf2..4af0c79 100644
--- a/Swift/Controllers/UnitTest/MockMainWindowFactory.h
+++ b/Swift/Controllers/UnitTest/MockMainWindowFactory.h
@@ -11,18 +11,18 @@
namespace Swift {
- class MockMainWindowFactory : public MainWindowFactory {
- public:
- MockMainWindowFactory() : last(NULL) {}
-
- virtual ~MockMainWindowFactory() {}
-
- /**
- * Transfers ownership of result.
- */
- virtual MainWindow* createMainWindow(UIEventStream*) {last = new MockMainWindow();return last;}
- MockMainWindow* last;
- };
+ class MockMainWindowFactory : public MainWindowFactory {
+ public:
+ MockMainWindowFactory() : last(NULL) {}
+
+ virtual ~MockMainWindowFactory() {}
+
+ /**
+ * Transfers ownership of result.
+ */
+ virtual MainWindow* createMainWindow(UIEventStream*) {last = new MockMainWindow();return last;}
+ MockMainWindow* last;
+ };
}
diff --git a/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp b/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp
index 40530dc..e1284fd 100644
--- a/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp
+++ b/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp
@@ -26,297 +26,297 @@
using namespace Swift;
class PresenceNotifierTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PresenceNotifierTest);
- CPPUNIT_TEST(testReceiveFirstPresenceCreatesAvailableNotification);
- CPPUNIT_TEST(testReceiveSecondPresenceCreatesStatusChangeNotification);
- CPPUNIT_TEST(testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification);
- CPPUNIT_TEST(testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification);
- CPPUNIT_TEST(testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification);
- CPPUNIT_TEST(testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification);
- CPPUNIT_TEST(testReceiveAvailablePresenceFromMUCDoesNotCreateNotification);
- CPPUNIT_TEST(testNotificationSubjectContainsNameForJIDInRoster);
- CPPUNIT_TEST(testNotificationSubjectContainsJIDForJIDNotInRoster);
- CPPUNIT_TEST(testNotificationSubjectContainsStatus);
- CPPUNIT_TEST(testNotificationMessageContainsStatusMessage);
- CPPUNIT_TEST(testNotificationPicture);
- CPPUNIT_TEST(testNotificationActivationEmitsSignal);
- CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotNotify);
- CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod);
- CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodDoesNotNotify);
- CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodResetsTimer);
- CPPUNIT_TEST(testReceivePresenceAfterQuietPeriodNotifies);
- CPPUNIT_TEST(testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- stanzaChannel = new DummyStanzaChannel();
- notifier = new LoggingNotifier();
- mucRegistry = new MUCRegistry();
- user1 = JID("user1@bar.com/bla");
- user2 = JID("user2@foo.com/baz");
- avatarManager = new DummyAvatarManager();
- roster = new XMPPRosterImpl();
- nickResolver = new NickResolver(JID("foo@bar.com"), roster, NULL, mucRegistry);
- presenceOracle = new PresenceOracle(stanzaChannel, roster);
- timerFactory = new DummyTimerFactory();
- }
-
- void tearDown() {
- delete timerFactory;
- delete presenceOracle;
- delete nickResolver;
- delete roster;
- delete avatarManager;
- delete mucRegistry;
- delete notifier;
- delete stanzaChannel;
- }
-
- void testReceiveFirstPresenceCreatesAvailableNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
-
- sendPresence(user1, StatusShow::Online);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
- }
-
- void testReceiveSecondPresenceCreatesStatusChangeNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
- notifier->notifications.clear();
-
- sendPresence(user1, StatusShow::Online);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(Notifier::ContactStatusChange, notifier->notifications[0].type);
- }
-
- void testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
- notifier->notifications.clear();
-
- sendUnavailablePresence(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(Notifier::ContactUnavailable, notifier->notifications[0].type);
- }
-
- void testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
-
- sendUnavailablePresence(user1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
-
- void testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
- sendUnavailablePresence(user1);
- notifier->notifications.clear();
-
- sendPresence(user1, StatusShow::Away);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
- }
-
- void testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- notifier->notifications.clear();
-
- sendPresence(user1, StatusShow::Away);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
- }
+ CPPUNIT_TEST_SUITE(PresenceNotifierTest);
+ CPPUNIT_TEST(testReceiveFirstPresenceCreatesAvailableNotification);
+ CPPUNIT_TEST(testReceiveSecondPresenceCreatesStatusChangeNotification);
+ CPPUNIT_TEST(testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification);
+ CPPUNIT_TEST(testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification);
+ CPPUNIT_TEST(testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification);
+ CPPUNIT_TEST(testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification);
+ CPPUNIT_TEST(testReceiveAvailablePresenceFromMUCDoesNotCreateNotification);
+ CPPUNIT_TEST(testNotificationSubjectContainsNameForJIDInRoster);
+ CPPUNIT_TEST(testNotificationSubjectContainsJIDForJIDNotInRoster);
+ CPPUNIT_TEST(testNotificationSubjectContainsStatus);
+ CPPUNIT_TEST(testNotificationMessageContainsStatusMessage);
+ CPPUNIT_TEST(testNotificationPicture);
+ CPPUNIT_TEST(testNotificationActivationEmitsSignal);
+ CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotNotify);
+ CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod);
+ CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodDoesNotNotify);
+ CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodResetsTimer);
+ CPPUNIT_TEST(testReceivePresenceAfterQuietPeriodNotifies);
+ CPPUNIT_TEST(testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ stanzaChannel = new DummyStanzaChannel();
+ notifier = new LoggingNotifier();
+ mucRegistry = new MUCRegistry();
+ user1 = JID("user1@bar.com/bla");
+ user2 = JID("user2@foo.com/baz");
+ avatarManager = new DummyAvatarManager();
+ roster = new XMPPRosterImpl();
+ nickResolver = new NickResolver(JID("foo@bar.com"), roster, NULL, mucRegistry);
+ presenceOracle = new PresenceOracle(stanzaChannel, roster);
+ timerFactory = new DummyTimerFactory();
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete presenceOracle;
+ delete nickResolver;
+ delete roster;
+ delete avatarManager;
+ delete mucRegistry;
+ delete notifier;
+ delete stanzaChannel;
+ }
+
+ void testReceiveFirstPresenceCreatesAvailableNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+
+ sendPresence(user1, StatusShow::Online);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
+ }
+
+ void testReceiveSecondPresenceCreatesStatusChangeNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ sendPresence(user1, StatusShow::Away);
+ notifier->notifications.clear();
+
+ sendPresence(user1, StatusShow::Online);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(Notifier::ContactStatusChange, notifier->notifications[0].type);
+ }
+
+ void testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ sendPresence(user1, StatusShow::Away);
+ notifier->notifications.clear();
+
+ sendUnavailablePresence(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(Notifier::ContactUnavailable, notifier->notifications[0].type);
+ }
+
+ void testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+
+ sendUnavailablePresence(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
+
+ void testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ sendPresence(user1, StatusShow::Away);
+ sendUnavailablePresence(user1);
+ notifier->notifications.clear();
+
+ sendPresence(user1, StatusShow::Away);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
+ }
+
+ void testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ sendPresence(user1, StatusShow::Away);
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ notifier->notifications.clear();
+
+ sendPresence(user1, StatusShow::Away);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type);
+ }
- void testReceiveAvailablePresenceFromMUCDoesNotCreateNotification() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- mucRegistry->addMUC(JID("teaparty@wonderland.lit"));
+ void testReceiveAvailablePresenceFromMUCDoesNotCreateNotification() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ mucRegistry->addMUC(JID("teaparty@wonderland.lit"));
- sendPresence(JID("teaparty@wonderland.lit/Alice"), StatusShow::Away);
+ sendPresence(JID("teaparty@wonderland.lit/Alice"), StatusShow::Away);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
- void testNotificationPicture() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- avatarManager->avatars[user1] = createByteArray("abcdef");
+ void testNotificationPicture() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ avatarManager->avatars[user1] = createByteArray("abcdef");
- sendPresence(user1, StatusShow::Online);
+ sendPresence(user1, StatusShow::Online);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT_EQUAL(boost::filesystem::path("/avatars/user1@bar.com/bla"), notifier->notifications[0].picture);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT_EQUAL(boost::filesystem::path("/avatars/user1@bar.com/bla"), notifier->notifications[0].picture);
+ }
- void testNotificationActivationEmitsSignal() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ void testNotificationActivationEmitsSignal() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Online);
- CPPUNIT_ASSERT(notifier->notifications[0].callback);
- notifier->notifications[0].callback();
+ sendPresence(user1, StatusShow::Online);
+ CPPUNIT_ASSERT(notifier->notifications[0].callback);
+ notifier->notifications[0].callback();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(activatedNotifications.size()));
- CPPUNIT_ASSERT_EQUAL(user1, activatedNotifications[0]);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(activatedNotifications.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, activatedNotifications[0]);
+ }
- void testNotificationSubjectContainsNameForJIDInRoster() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- roster->addContact(user1.toBare(), "User 1", std::vector<std::string>(), RosterItemPayload::Both);
+ void testNotificationSubjectContainsNameForJIDInRoster() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ roster->addContact(user1.toBare(), "User 1", std::vector<std::string>(), RosterItemPayload::Both);
- sendPresence(user1, StatusShow::Online);
+ sendPresence(user1, StatusShow::Online);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- std::string subject = notifier->notifications[0].subject;
- CPPUNIT_ASSERT(subject.find("User 1") != std::string::npos);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ std::string subject = notifier->notifications[0].subject;
+ CPPUNIT_ASSERT(subject.find("User 1") != std::string::npos);
+ }
- void testNotificationSubjectContainsJIDForJIDNotInRoster() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ void testNotificationSubjectContainsJIDForJIDNotInRoster() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Online);
+ sendPresence(user1, StatusShow::Online);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- std::string subject = notifier->notifications[0].subject;
- CPPUNIT_ASSERT(subject.find(user1.toBare().toString()) != std::string::npos);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ std::string subject = notifier->notifications[0].subject;
+ CPPUNIT_ASSERT(subject.find(user1.toBare().toString()) != std::string::npos);
+ }
- void testNotificationSubjectContainsStatus() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ void testNotificationSubjectContainsStatus() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
+ sendPresence(user1, StatusShow::Away);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- std::string subject = notifier->notifications[0].subject;
- CPPUNIT_ASSERT(subject.find("Away") != std::string::npos);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ std::string subject = notifier->notifications[0].subject;
+ CPPUNIT_ASSERT(subject.find("Away") != std::string::npos);
+ }
- void testNotificationMessageContainsStatusMessage() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ void testNotificationMessageContainsStatusMessage() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- sendPresence(user1, StatusShow::Away);
+ sendPresence(user1, StatusShow::Away);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- CPPUNIT_ASSERT(notifier->notifications[0].description.find("Status Message") != std::string::npos);
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ CPPUNIT_ASSERT(notifier->notifications[0].description.find("Status Message") != std::string::npos);
+ }
- void testReceiveFirstPresenceWithQuietPeriodDoesNotNotify() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
+ void testReceiveFirstPresenceWithQuietPeriodDoesNotNotify() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
- sendPresence(user1, StatusShow::Online);
+ sendPresence(user1, StatusShow::Online);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
- void testReceivePresenceDuringQuietPeriodDoesNotNotify() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
+ void testReceivePresenceDuringQuietPeriodDoesNotNotify() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
- sendPresence(user1, StatusShow::Online);
- timerFactory->setTime(1);
- sendPresence(user2, StatusShow::Away);
+ sendPresence(user1, StatusShow::Online);
+ timerFactory->setTime(1);
+ sendPresence(user2, StatusShow::Away);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
- void testReceivePresenceDuringQuietPeriodResetsTimer() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
+ void testReceivePresenceDuringQuietPeriodResetsTimer() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
- sendPresence(user1, StatusShow::Online);
- timerFactory->setTime(9);
- sendPresence(user2, StatusShow::Away);
- timerFactory->setTime(18);
- sendPresence(user1, StatusShow::Away);
+ sendPresence(user1, StatusShow::Online);
+ timerFactory->setTime(9);
+ sendPresence(user2, StatusShow::Away);
+ timerFactory->setTime(18);
+ sendPresence(user1, StatusShow::Away);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
- void testReceivePresenceAfterQuietPeriodNotifies() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
-
- sendPresence(user1, StatusShow::Online);
- timerFactory->setTime(11);
- sendPresence(user2, StatusShow::Away);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
- }
-
- void testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
-
- timerFactory->setTime(11);
- sendPresence(user1, StatusShow::Away);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
-
- void testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify() {
- boost::shared_ptr<PresenceNotifier> testling = createNotifier();
- testling->setInitialQuietPeriodMS(10);
- sendPresence(user1, StatusShow::Online);
- timerFactory->setTime(15);
- notifier->notifications.clear();
-
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- sendPresence(user1, StatusShow::Online);
- timerFactory->setTime(21);
- sendPresence(user2, StatusShow::Online);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
- }
-
-
- private:
- boost::shared_ptr<PresenceNotifier> createNotifier() {
- boost::shared_ptr<PresenceNotifier> result(new PresenceNotifier(stanzaChannel, notifier, mucRegistry, avatarManager, nickResolver, presenceOracle, timerFactory));
- result->onNotificationActivated.connect(boost::bind(&PresenceNotifierTest::handleNotificationActivated, this, _1));
- result->setInitialQuietPeriodMS(0);
- return result;
- }
-
- void sendPresence(const JID& jid, StatusShow::Type type) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setFrom(jid);
- presence->setShow(type);
- presence->setStatus("Status Message");
- stanzaChannel->onPresenceReceived(presence);
- }
-
- void sendUnavailablePresence(const JID& jid) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setType(Presence::Unavailable);
- presence->setFrom(jid);
- stanzaChannel->onPresenceReceived(presence);
- }
-
- void handleNotificationActivated(const JID& j) {
- activatedNotifications.push_back(j);
- }
-
- private:
- DummyStanzaChannel* stanzaChannel;
- LoggingNotifier* notifier;
- MUCRegistry* mucRegistry;
- DummyAvatarManager* avatarManager;
- XMPPRosterImpl* roster;
- NickResolver* nickResolver;
- PresenceOracle* presenceOracle;
- DummyTimerFactory* timerFactory;
- JID user1;
- JID user2;
- std::vector<JID> activatedNotifications;
+ void testReceivePresenceAfterQuietPeriodNotifies() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
+
+ sendPresence(user1, StatusShow::Online);
+ timerFactory->setTime(11);
+ sendPresence(user2, StatusShow::Away);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(notifier->notifications.size()));
+ }
+
+ void testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
+
+ timerFactory->setTime(11);
+ sendPresence(user1, StatusShow::Away);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
+
+ void testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify() {
+ boost::shared_ptr<PresenceNotifier> testling = createNotifier();
+ testling->setInitialQuietPeriodMS(10);
+ sendPresence(user1, StatusShow::Online);
+ timerFactory->setTime(15);
+ notifier->notifications.clear();
+
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ sendPresence(user1, StatusShow::Online);
+ timerFactory->setTime(21);
+ sendPresence(user2, StatusShow::Online);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
+
+
+ private:
+ boost::shared_ptr<PresenceNotifier> createNotifier() {
+ boost::shared_ptr<PresenceNotifier> result(new PresenceNotifier(stanzaChannel, notifier, mucRegistry, avatarManager, nickResolver, presenceOracle, timerFactory));
+ result->onNotificationActivated.connect(boost::bind(&PresenceNotifierTest::handleNotificationActivated, this, _1));
+ result->setInitialQuietPeriodMS(0);
+ return result;
+ }
+
+ void sendPresence(const JID& jid, StatusShow::Type type) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->setShow(type);
+ presence->setStatus("Status Message");
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendUnavailablePresence(const JID& jid) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setType(Presence::Unavailable);
+ presence->setFrom(jid);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void handleNotificationActivated(const JID& j) {
+ activatedNotifications.push_back(j);
+ }
+
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ LoggingNotifier* notifier;
+ MUCRegistry* mucRegistry;
+ DummyAvatarManager* avatarManager;
+ XMPPRosterImpl* roster;
+ NickResolver* nickResolver;
+ PresenceOracle* presenceOracle;
+ DummyTimerFactory* timerFactory;
+ JID user1;
+ JID user2;
+ std::vector<JID> activatedNotifications;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PresenceNotifierTest);
diff --git a/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp b/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp
index 266cd64..be35468 100644
--- a/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp
+++ b/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp
@@ -12,33 +12,33 @@
using namespace Swift;
class PreviousStatusStoreTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PreviousStatusStoreTest);
- CPPUNIT_TEST(testGetAll);
- //CPPUNIT_TEST(testGetAllLimited);
- //CPPUNIT_TEST(testGetSuggestionsInexact);
- //CPPUNIT_TEST(testGetSuggestionsExact);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PreviousStatusStoreTest);
+ CPPUNIT_TEST(testGetAll);
+ //CPPUNIT_TEST(testGetAllLimited);
+ //CPPUNIT_TEST(testGetSuggestionsInexact);
+ //CPPUNIT_TEST(testGetSuggestionsExact);
+ CPPUNIT_TEST_SUITE_END();
public:
- void setUp() {
- store_ = new PreviousStatusStore();
- store_->addStatus(StatusShow::Online, "At home in the study");
- store_->addStatus(StatusShow::DND, "In a meeting");
- store_->addStatus(StatusShow::DND, "With a client");
- store_->addStatus(StatusShow::Away, "Walking the elephant");
- store_->addStatus(StatusShow::Online, "In the office, at my desk");
- }
+ void setUp() {
+ store_ = new PreviousStatusStore();
+ store_->addStatus(StatusShow::Online, "At home in the study");
+ store_->addStatus(StatusShow::DND, "In a meeting");
+ store_->addStatus(StatusShow::DND, "With a client");
+ store_->addStatus(StatusShow::Away, "Walking the elephant");
+ store_->addStatus(StatusShow::Online, "In the office, at my desk");
+ }
- void tearDown() {
- delete store_;
- }
+ void tearDown() {
+ delete store_;
+ }
- void testGetAll() {
+ void testGetAll() {
- }
+ }
private:
- PreviousStatusStore* store_;
+ PreviousStatusStore* store_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PreviousStatusStoreTest);
diff --git a/Swift/Controllers/WhiteboardManager.cpp b/Swift/Controllers/WhiteboardManager.cpp
index f62a94a..91f01c8 100644
--- a/Swift/Controllers/WhiteboardManager.cpp
+++ b/Swift/Controllers/WhiteboardManager.cpp
@@ -25,121 +25,121 @@
#include <Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h>
namespace Swift {
- typedef std::pair<JID, WhiteboardWindow*> JIDWhiteboardWindowPair;
+ typedef std::pair<JID, WhiteboardWindow*> JIDWhiteboardWindowPair;
- WhiteboardManager::WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager) : whiteboardWindowFactory_(whiteboardWindowFactory), uiEventStream_(uiEventStream), nickResolver_(nickResolver), whiteboardSessionManager_(whiteboardSessionManager) {
+ 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));
+ 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_) {
- 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 NULL;
- }
- return whiteboardWindows_[contact.toBare()];
- }
-
- void WhiteboardManager::handleUIEvent(boost::shared_ptr<UIEvent> event) {
- boost::shared_ptr<RequestWhiteboardUIEvent> requestWhiteboardEvent = boost::dynamic_pointer_cast<RequestWhiteboardUIEvent>(event);
- if (requestWhiteboardEvent) {
- requestSession(requestWhiteboardEvent->getContact());
- }
- boost::shared_ptr<AcceptWhiteboardSessionUIEvent> sessionAcceptEvent = boost::dynamic_pointer_cast<AcceptWhiteboardSessionUIEvent>(event);
- if (sessionAcceptEvent) {
- acceptSession(sessionAcceptEvent->getContact());
- }
- boost::shared_ptr<CancelWhiteboardSessionUIEvent> sessionCancelEvent = boost::dynamic_pointer_cast<CancelWhiteboardSessionUIEvent>(event);
- if (sessionCancelEvent) {
- cancelSession(sessionCancelEvent->getContact());
- }
- boost::shared_ptr<ShowWhiteboardUIEvent> showWindowEvent = boost::dynamic_pointer_cast<ShowWhiteboardUIEvent>(event);
- if (showWindowEvent) {
- WhiteboardWindow* window = findWhiteboardWindow(showWindowEvent->getContact());
- if (window != NULL) {
- window->activateWindow();
- }
- }
- }
-
- void WhiteboardManager::acceptSession(const JID& from) {
- IncomingWhiteboardSession::ref session = boost::dynamic_pointer_cast<IncomingWhiteboardSession>(whiteboardSessionManager_->getSession(from));
- WhiteboardWindow* window = findWhiteboardWindow(from);
- if (session && window) {
- session->accept();
- window->show();
- }
- }
-
- void WhiteboardManager::requestSession(const JID& contact) {
- WhiteboardSession::ref session = whiteboardSessionManager_->requestSession(contact);
- session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1));
- session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1));
- session->onRequestRejected.connect(boost::bind(&WhiteboardManager::handleRequestReject, this, _1));
-
- WhiteboardWindow* window = findWhiteboardWindow(contact);
- if (window == NULL) {
- createNewWhiteboardWindow(contact, session);
- } else {
- window->setSession(session);
- }
- onSessionRequest(session->getTo(), true);
- }
-
- void WhiteboardManager::cancelSession(const JID& from) {
- WhiteboardSession::ref session = whiteboardSessionManager_->getSession(from);
- if (session) {
- session->cancel();
- }
- }
-
- void WhiteboardManager::handleIncomingSession(IncomingWhiteboardSession::ref session) {
- session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1));
- session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1));
-
- WhiteboardWindow* window = findWhiteboardWindow(session->getTo());
- if (window == NULL) {
- createNewWhiteboardWindow(session->getTo(), session);
- } else {
- window->setSession(session);
- }
-
- onSessionRequest(session->getTo(), false);
- }
-
- void WhiteboardManager::handleSessionTerminate(const JID& contact) {
- onSessionTerminate(contact);
- }
-
- void WhiteboardManager::handleSessionCancel(const JID& contact) {
- onSessionTerminate(contact);
- }
-
- void WhiteboardManager::handleSessionAccept(const JID& contact) {
- WhiteboardWindow* window = findWhiteboardWindow(contact);
- if (window != NULL) {
- window->show();
- }
- onRequestAccepted(contact);
- }
-
- void WhiteboardManager::handleRequestReject(const JID& contact) {
- onRequestRejected(contact);
- }
+ uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&WhiteboardManager::handleUIEvent, this, _1));
+ }
+
+ WhiteboardManager::~WhiteboardManager() {
+ foreach (JIDWhiteboardWindowPair 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 NULL;
+ }
+ return whiteboardWindows_[contact.toBare()];
+ }
+
+ void WhiteboardManager::handleUIEvent(boost::shared_ptr<UIEvent> event) {
+ boost::shared_ptr<RequestWhiteboardUIEvent> requestWhiteboardEvent = boost::dynamic_pointer_cast<RequestWhiteboardUIEvent>(event);
+ if (requestWhiteboardEvent) {
+ requestSession(requestWhiteboardEvent->getContact());
+ }
+ boost::shared_ptr<AcceptWhiteboardSessionUIEvent> sessionAcceptEvent = boost::dynamic_pointer_cast<AcceptWhiteboardSessionUIEvent>(event);
+ if (sessionAcceptEvent) {
+ acceptSession(sessionAcceptEvent->getContact());
+ }
+ boost::shared_ptr<CancelWhiteboardSessionUIEvent> sessionCancelEvent = boost::dynamic_pointer_cast<CancelWhiteboardSessionUIEvent>(event);
+ if (sessionCancelEvent) {
+ cancelSession(sessionCancelEvent->getContact());
+ }
+ boost::shared_ptr<ShowWhiteboardUIEvent> showWindowEvent = boost::dynamic_pointer_cast<ShowWhiteboardUIEvent>(event);
+ if (showWindowEvent) {
+ WhiteboardWindow* window = findWhiteboardWindow(showWindowEvent->getContact());
+ if (window != NULL) {
+ window->activateWindow();
+ }
+ }
+ }
+
+ void WhiteboardManager::acceptSession(const JID& from) {
+ IncomingWhiteboardSession::ref session = boost::dynamic_pointer_cast<IncomingWhiteboardSession>(whiteboardSessionManager_->getSession(from));
+ WhiteboardWindow* window = findWhiteboardWindow(from);
+ if (session && window) {
+ session->accept();
+ window->show();
+ }
+ }
+
+ void WhiteboardManager::requestSession(const JID& contact) {
+ WhiteboardSession::ref session = whiteboardSessionManager_->requestSession(contact);
+ session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1));
+ session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1));
+ session->onRequestRejected.connect(boost::bind(&WhiteboardManager::handleRequestReject, this, _1));
+
+ WhiteboardWindow* window = findWhiteboardWindow(contact);
+ if (window == NULL) {
+ createNewWhiteboardWindow(contact, session);
+ } else {
+ window->setSession(session);
+ }
+ onSessionRequest(session->getTo(), true);
+ }
+
+ void WhiteboardManager::cancelSession(const JID& from) {
+ WhiteboardSession::ref session = whiteboardSessionManager_->getSession(from);
+ if (session) {
+ session->cancel();
+ }
+ }
+
+ void WhiteboardManager::handleIncomingSession(IncomingWhiteboardSession::ref session) {
+ session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1));
+ session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1));
+
+ WhiteboardWindow* window = findWhiteboardWindow(session->getTo());
+ if (window == NULL) {
+ createNewWhiteboardWindow(session->getTo(), session);
+ } else {
+ window->setSession(session);
+ }
+
+ onSessionRequest(session->getTo(), false);
+ }
+
+ void WhiteboardManager::handleSessionTerminate(const JID& contact) {
+ onSessionTerminate(contact);
+ }
+
+ void WhiteboardManager::handleSessionCancel(const JID& contact) {
+ onSessionTerminate(contact);
+ }
+
+ void WhiteboardManager::handleSessionAccept(const JID& contact) {
+ WhiteboardWindow* window = findWhiteboardWindow(contact);
+ if (window != NULL) {
+ window->show();
+ }
+ onRequestAccepted(contact);
+ }
+
+ void WhiteboardManager::handleRequestReject(const JID& contact) {
+ onRequestRejected(contact);
+ }
}
diff --git a/Swift/Controllers/WhiteboardManager.h b/Swift/Controllers/WhiteboardManager.h
index 863dd60..35ed9bd 100644
--- a/Swift/Controllers/WhiteboardManager.h
+++ b/Swift/Controllers/WhiteboardManager.h
@@ -26,40 +26,40 @@
#include <Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h>
namespace Swift {
- class WhiteboardSessionManager;
- class NickResolver;
+ class WhiteboardSessionManager;
+ class NickResolver;
- class WhiteboardManager {
- public:
- WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager);
- ~WhiteboardManager();
+ class WhiteboardManager {
+ public:
+ WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager);
+ ~WhiteboardManager();
- WhiteboardWindow* createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session);
+ WhiteboardWindow* createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session);
- public:
- boost::signal< void (const JID&, bool senderIsSelf)> onSessionRequest;
- boost::signal< void (const JID&)> onSessionTerminate;
- boost::signal< void (const JID&)> onRequestAccepted;
- boost::signal< void (const JID&)> onRequestRejected;
+ public:
+ boost::signal< void (const JID&, bool senderIsSelf)> onSessionRequest;
+ boost::signal< void (const JID&)> onSessionTerminate;
+ boost::signal< void (const JID&)> onRequestAccepted;
+ boost::signal< void (const JID&)> onRequestRejected;
- private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
- void handleSessionTerminate(const JID& contact);
- void handleSessionCancel(const JID& contact);
- void handleSessionAccept(const JID& contact);
- void handleRequestReject(const JID& contact);
- void handleIncomingSession(IncomingWhiteboardSession::ref session);
- void acceptSession(const JID& from);
- void requestSession(const JID& contact);
- void cancelSession(const JID& from);
- WhiteboardWindow* findWhiteboardWindow(const JID& contact);
+ private:
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+ void handleSessionTerminate(const JID& contact);
+ void handleSessionCancel(const JID& contact);
+ void handleSessionAccept(const JID& contact);
+ void handleRequestReject(const JID& contact);
+ void handleIncomingSession(IncomingWhiteboardSession::ref session);
+ void acceptSession(const JID& from);
+ void requestSession(const JID& contact);
+ void cancelSession(const JID& from);
+ WhiteboardWindow* findWhiteboardWindow(const JID& contact);
- private:
- std::map<JID, WhiteboardWindow*> whiteboardWindows_;
- WhiteboardWindowFactory* whiteboardWindowFactory_;
- UIEventStream* uiEventStream_;
- NickResolver* nickResolver_;
- boost::bsignals::scoped_connection uiEventConnection_;
- WhiteboardSessionManager* whiteboardSessionManager_;
- };
+ private:
+ std::map<JID, WhiteboardWindow*> whiteboardWindows_;
+ WhiteboardWindowFactory* whiteboardWindowFactory_;
+ UIEventStream* uiEventStream_;
+ NickResolver* nickResolver_;
+ boost::bsignals::scoped_connection uiEventConnection_;
+ WhiteboardSessionManager* whiteboardSessionManager_;
+ };
}
diff --git a/Swift/Controllers/XMLConsoleController.cpp b/Swift/Controllers/XMLConsoleController.cpp
index 22be4f6..175a4eb 100644
--- a/Swift/Controllers/XMLConsoleController.cpp
+++ b/Swift/Controllers/XMLConsoleController.cpp
@@ -12,34 +12,34 @@
namespace Swift {
XMLConsoleController::XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory) : xmlConsoleWidgetFactory(xmlConsoleWidgetFactory), xmlConsoleWidget(NULL) {
- uiEventStream->onUIEvent.connect(boost::bind(&XMLConsoleController::handleUIEvent, this, _1));
+ uiEventStream->onUIEvent.connect(boost::bind(&XMLConsoleController::handleUIEvent, this, _1));
}
XMLConsoleController::~XMLConsoleController() {
- delete xmlConsoleWidget;
+ delete xmlConsoleWidget;
}
void XMLConsoleController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent) {
- boost::shared_ptr<RequestXMLConsoleUIEvent> event = boost::dynamic_pointer_cast<RequestXMLConsoleUIEvent>(rawEvent);
- if (event != NULL) {
- if (xmlConsoleWidget == NULL) {
- xmlConsoleWidget = xmlConsoleWidgetFactory->createXMLConsoleWidget();
- }
- xmlConsoleWidget->show();
- xmlConsoleWidget->activate();
- }
+ boost::shared_ptr<RequestXMLConsoleUIEvent> event = boost::dynamic_pointer_cast<RequestXMLConsoleUIEvent>(rawEvent);
+ if (event != NULL) {
+ if (xmlConsoleWidget == NULL) {
+ xmlConsoleWidget = xmlConsoleWidgetFactory->createXMLConsoleWidget();
+ }
+ xmlConsoleWidget->show();
+ xmlConsoleWidget->activate();
+ }
}
void XMLConsoleController::handleDataRead(const SafeByteArray& data) {
- if (xmlConsoleWidget) {
- xmlConsoleWidget->handleDataRead(data);
- }
+ if (xmlConsoleWidget) {
+ xmlConsoleWidget->handleDataRead(data);
+ }
}
void XMLConsoleController::handleDataWritten(const SafeByteArray& data) {
- if (xmlConsoleWidget) {
- xmlConsoleWidget->handleDataWritten(data);
- }
+ if (xmlConsoleWidget) {
+ xmlConsoleWidget->handleDataWritten(data);
+ }
}
}
diff --git a/Swift/Controllers/XMLConsoleController.h b/Swift/Controllers/XMLConsoleController.h
index bd4d256..eac27d3 100644
--- a/Swift/Controllers/XMLConsoleController.h
+++ b/Swift/Controllers/XMLConsoleController.h
@@ -15,24 +15,24 @@
#include <Swift/Controllers/UIEvents/UIEventStream.h>
namespace Swift {
-
- class XMLConsoleWidgetFactory;
- class XMLConsoleWidget;
-
- class XMLConsoleController {
- public:
- XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory);
- ~XMLConsoleController();
-
- public:
- void handleDataRead(const SafeByteArray& data);
- void handleDataWritten(const SafeByteArray& data);
-
- private:
- void handleUIEvent(boost::shared_ptr<UIEvent> event);
-
- private:
- XMLConsoleWidgetFactory* xmlConsoleWidgetFactory;
- XMLConsoleWidget* xmlConsoleWidget;
- };
+
+ class XMLConsoleWidgetFactory;
+ class XMLConsoleWidget;
+
+ class XMLConsoleController {
+ public:
+ XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory);
+ ~XMLConsoleController();
+
+ public:
+ void handleDataRead(const SafeByteArray& data);
+ void handleDataWritten(const SafeByteArray& data);
+
+ private:
+ void handleUIEvent(boost::shared_ptr<UIEvent> event);
+
+ private:
+ XMLConsoleWidgetFactory* xmlConsoleWidgetFactory;
+ XMLConsoleWidget* xmlConsoleWidget;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/ErrorEvent.h b/Swift/Controllers/XMPPEvents/ErrorEvent.h
index 0b18dfc..959f210 100644
--- a/Swift/Controllers/XMPPEvents/ErrorEvent.h
+++ b/Swift/Controllers/XMPPEvents/ErrorEvent.h
@@ -17,16 +17,16 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class ErrorEvent : public StanzaEvent {
- public:
- ErrorEvent(const JID& jid, const std::string& text) : jid_(jid), text_(text){}
- virtual ~ErrorEvent(){}
- const JID& getJID() const {return jid_;}
- const std::string& getText() const {return text_;}
-
- private:
- JID jid_;
- std::string text_;
- };
+ class ErrorEvent : public StanzaEvent {
+ public:
+ ErrorEvent(const JID& jid, const std::string& text) : jid_(jid), text_(text){}
+ virtual ~ErrorEvent(){}
+ const JID& getJID() const {return jid_;}
+ const std::string& getText() const {return text_;}
+
+ private:
+ JID jid_;
+ std::string text_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/EventController.cpp b/Swift/Controllers/XMPPEvents/EventController.cpp
index bbe7356..4c6b3bc 100644
--- a/Swift/Controllers/XMPPEvents/EventController.cpp
+++ b/Swift/Controllers/XMPPEvents/EventController.cpp
@@ -25,56 +25,56 @@ EventController::EventController() {
}
EventController::~EventController() {
- foreach(boost::shared_ptr<StanzaEvent> event, events_) {
- event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
- }
+ foreach(boost::shared_ptr<StanzaEvent> event, events_) {
+ event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
+ }
}
void EventController::handleIncomingEvent(boost::shared_ptr<StanzaEvent> sourceEvent) {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(sourceEvent);
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(sourceEvent);
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(sourceEvent);
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(sourceEvent);
- boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(sourceEvent);
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(sourceEvent);
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(sourceEvent);
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(sourceEvent);
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(sourceEvent);
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(sourceEvent);
- /* If it's a duplicate subscription request, remove the previous request first */
- if (subscriptionEvent) {
- EventList existingEvents(events_);
- foreach(boost::shared_ptr<StanzaEvent> existingEvent, existingEvents) {
- boost::shared_ptr<SubscriptionRequestEvent> existingSubscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(existingEvent);
- if (existingSubscriptionEvent) {
- if (existingSubscriptionEvent->getJID() == subscriptionEvent->getJID()) {
- existingEvent->conclude();
- }
- }
- }
- }
+ /* If it's a duplicate subscription request, remove the previous request first */
+ if (subscriptionEvent) {
+ EventList existingEvents(events_);
+ foreach(boost::shared_ptr<StanzaEvent> existingEvent, existingEvents) {
+ boost::shared_ptr<SubscriptionRequestEvent> existingSubscriptionEvent = boost::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);
- }
- }
+ 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(boost::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()));
+ 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();
+ onEventQueueLengthChange.disconnect_all_slots();
+ onEventQueueEventAdded.disconnect_all_slots();
}
void EventController::clear() {
- events_.clear();
- onEventQueueLengthChange(0);
+ events_.clear();
+ onEventQueueLengthChange(0);
}
}
diff --git a/Swift/Controllers/XMPPEvents/EventController.h b/Swift/Controllers/XMPPEvents/EventController.h
index 35938ac..3081449 100644
--- a/Swift/Controllers/XMPPEvents/EventController.h
+++ b/Swift/Controllers/XMPPEvents/EventController.h
@@ -16,21 +16,21 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- typedef std::vector<boost::shared_ptr<StanzaEvent> > EventList;
- class EventController {
- public:
- EventController();
- ~EventController();
-
- void handleIncomingEvent(boost::shared_ptr<StanzaEvent> sourceEvent);
- boost::signal<void (int)> onEventQueueLengthChange;
- boost::signal<void (boost::shared_ptr<StanzaEvent>)> onEventQueueEventAdded;
- const EventList& getEvents() const {return events_;}
- void disconnectAll();
- void clear();
-
- private:
- void handleEventConcluded(boost::shared_ptr<StanzaEvent> event);
- EventList events_;
- };
+ typedef std::vector<boost::shared_ptr<StanzaEvent> > EventList;
+ class EventController {
+ public:
+ EventController();
+ ~EventController();
+
+ void handleIncomingEvent(boost::shared_ptr<StanzaEvent> sourceEvent);
+ boost::signal<void (int)> onEventQueueLengthChange;
+ boost::signal<void (boost::shared_ptr<StanzaEvent>)> onEventQueueEventAdded;
+ const EventList& getEvents() const {return events_;}
+ void disconnectAll();
+ void clear();
+
+ private:
+ void handleEventConcluded(boost::shared_ptr<StanzaEvent> event);
+ EventList events_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
index 24af640..4c128e8 100644
--- a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
+++ b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
@@ -13,18 +13,18 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class IncomingFileTransferEvent : public StanzaEvent {
- public:
- typedef boost::shared_ptr<IncomingFileTransferEvent> ref;
+ class IncomingFileTransferEvent : public StanzaEvent {
+ public:
+ typedef boost::shared_ptr<IncomingFileTransferEvent> ref;
- IncomingFileTransferEvent(const JID& sender) : sender_(sender) {}
+ IncomingFileTransferEvent(const JID& sender) : sender_(sender) {}
- const JID& getSender() const {
- return sender_;
- }
+ const JID& getSender() const {
+ return sender_;
+ }
- private:
- JID sender_;
- };
+ private:
+ JID sender_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/MUCInviteEvent.h b/Swift/Controllers/XMPPEvents/MUCInviteEvent.h
index 1ae9891..7d333fb 100644
--- a/Swift/Controllers/XMPPEvents/MUCInviteEvent.h
+++ b/Swift/Controllers/XMPPEvents/MUCInviteEvent.h
@@ -22,26 +22,26 @@
namespace Swift {
- class MUCInviteEvent : public StanzaEvent {
- public:
- typedef boost::shared_ptr<MUCInviteEvent> ref;
-
- public:
- MUCInviteEvent(const JID& inviter, const JID& roomJID, const std::string& reason, const std::string& password, bool direct, bool impromptu) : inviter_(inviter), roomJID_(roomJID), reason_(reason), password_(password), direct_(direct), impromptu_(impromptu) {}
-
- const JID& getInviter() const { return inviter_; }
- const JID& getRoomJID() const { return roomJID_; }
- const std::string& getReason() const { return reason_; }
- const std::string& getPassword() const { return password_; }
- bool getDirect() const { return direct_; }
- bool getImpromptu() const { return impromptu_; }
-
- private:
- JID inviter_;
- JID roomJID_;
- std::string reason_;
- std::string password_;
- bool direct_;
- bool impromptu_;
- };
+ class MUCInviteEvent : public StanzaEvent {
+ public:
+ typedef boost::shared_ptr<MUCInviteEvent> ref;
+
+ public:
+ MUCInviteEvent(const JID& inviter, const JID& roomJID, const std::string& reason, const std::string& password, bool direct, bool impromptu) : inviter_(inviter), roomJID_(roomJID), reason_(reason), password_(password), direct_(direct), impromptu_(impromptu) {}
+
+ const JID& getInviter() const { return inviter_; }
+ const JID& getRoomJID() const { return roomJID_; }
+ const std::string& getReason() const { return reason_; }
+ const std::string& getPassword() const { return password_; }
+ bool getDirect() const { return direct_; }
+ bool getImpromptu() const { return impromptu_; }
+
+ private:
+ JID inviter_;
+ JID roomJID_;
+ std::string reason_;
+ std::string password_;
+ bool direct_;
+ bool impromptu_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/MessageEvent.h b/Swift/Controllers/XMPPEvents/MessageEvent.h
index b5b1215..4ec0406 100644
--- a/Swift/Controllers/XMPPEvents/MessageEvent.h
+++ b/Swift/Controllers/XMPPEvents/MessageEvent.h
@@ -4,7 +4,7 @@
* See the COPYING file for more information.
*/
-#pragma once
+#pragma once
#include <cassert>
@@ -15,34 +15,34 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class MessageEvent : public StanzaEvent {
- public:
- typedef boost::shared_ptr<MessageEvent> ref;
+ class MessageEvent : public StanzaEvent {
+ public:
+ typedef boost::shared_ptr<MessageEvent> ref;
- MessageEvent(boost::shared_ptr<Message> stanza) : stanza_(stanza), targetsMe_(true) {}
+ MessageEvent(boost::shared_ptr<Message> stanza) : stanza_(stanza), targetsMe_(true) {}
- boost::shared_ptr<Message> getStanza() {return stanza_;}
+ boost::shared_ptr<Message> getStanza() {return stanza_;}
- bool isReadable() {
- return getStanza()->isError() || !getStanza()->getBody().get_value_or("").empty();
- }
+ bool isReadable() {
+ return getStanza()->isError() || !getStanza()->getBody().get_value_or("").empty();
+ }
- void read() {
- assert (isReadable());
- conclude();
- }
+ void read() {
+ assert (isReadable());
+ conclude();
+ }
- void setTargetsMe(bool targetsMe) {
- targetsMe_ = targetsMe;
- }
+ void setTargetsMe(bool targetsMe) {
+ targetsMe_ = targetsMe;
+ }
- bool targetsMe() const {
- return targetsMe_;
- }
+ bool targetsMe() const {
+ return targetsMe_;
+ }
- private:
- boost::shared_ptr<Message> stanza_;
- bool targetsMe_;
- };
+ private:
+ boost::shared_ptr<Message> stanza_;
+ bool targetsMe_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/StanzaEvent.h b/Swift/Controllers/XMPPEvents/StanzaEvent.h
index e8d5eb9..fe97e23 100644
--- a/Swift/Controllers/XMPPEvents/StanzaEvent.h
+++ b/Swift/Controllers/XMPPEvents/StanzaEvent.h
@@ -12,18 +12,18 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class StanzaEvent {
- public:
- StanzaEvent() : time_(boost::posix_time::microsec_clock::universal_time()) {concluded_ = false;}
- virtual ~StanzaEvent() {}
- void conclude() {concluded_ = true; onConclusion();}
- /** Do not call this directly from outside the class.
- * If you connect to this signal, you *must* disconnect from it manually. */
- boost::signal<void()> onConclusion;
- bool getConcluded() {return concluded_;}
- boost::posix_time::ptime getTime() {return time_;}
- private:
- bool concluded_;
- boost::posix_time::ptime time_;
- };
+ class StanzaEvent {
+ public:
+ StanzaEvent() : time_(boost::posix_time::microsec_clock::universal_time()) {concluded_ = false;}
+ virtual ~StanzaEvent() {}
+ void conclude() {concluded_ = true; onConclusion();}
+ /** Do not call this directly from outside the class.
+ * If you connect to this signal, you *must* disconnect from it manually. */
+ boost::signal<void()> onConclusion;
+ bool getConcluded() {return concluded_;}
+ boost::posix_time::ptime getTime() {return time_;}
+ private:
+ bool concluded_;
+ boost::posix_time::ptime time_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h b/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h
index a22399b..92922e9 100644
--- a/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h
+++ b/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h
@@ -17,31 +17,31 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class SubscriptionRequestEvent : public StanzaEvent {
- public:
- SubscriptionRequestEvent(const JID& jid, const std::string& reason) : jid_(jid), reason_(reason){}
- virtual ~SubscriptionRequestEvent(){}
- const JID& getJID() const {return jid_;}
- const std::string& getReason() const {return reason_;}
- boost::signal<void()> onAccept;
- boost::signal<void()> onDecline;
- void accept() {
- onAccept();
- conclude();
- }
-
- void decline() {
- onDecline();
- conclude();
- }
-
- void defer() {
- conclude();
- }
-
- private:
- JID jid_;
- std::string reason_;
- };
+ class SubscriptionRequestEvent : public StanzaEvent {
+ public:
+ SubscriptionRequestEvent(const JID& jid, const std::string& reason) : jid_(jid), reason_(reason){}
+ virtual ~SubscriptionRequestEvent(){}
+ const JID& getJID() const {return jid_;}
+ const std::string& getReason() const {return reason_;}
+ boost::signal<void()> onAccept;
+ boost::signal<void()> onDecline;
+ void accept() {
+ onAccept();
+ conclude();
+ }
+
+ void decline() {
+ onDecline();
+ conclude();
+ }
+
+ void defer() {
+ conclude();
+ }
+
+ private:
+ JID jid_;
+ std::string reason_;
+ };
}
diff --git a/Swift/Controllers/XMPPURIController.cpp b/Swift/Controllers/XMPPURIController.cpp
index 3deb2d8..57c0ca4 100644
--- a/Swift/Controllers/XMPPURIController.cpp
+++ b/Swift/Controllers/XMPPURIController.cpp
@@ -19,21 +19,21 @@
using namespace Swift;
XMPPURIController::XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream) : uriHandler(uriHandler), uiEventStream(uiEventStream) {
- uriHandler->onURI.connect(boost::bind(&XMPPURIController::handleURI, this, _1));
+ uriHandler->onURI.connect(boost::bind(&XMPPURIController::handleURI, this, _1));
}
XMPPURIController::~XMPPURIController() {
- uriHandler->onURI.disconnect(boost::bind(&XMPPURIController::handleURI, this, _1));
+ uriHandler->onURI.disconnect(boost::bind(&XMPPURIController::handleURI, this, _1));
}
void XMPPURIController::handleURI(const std::string& s) {
- XMPPURI uri = XMPPURI::fromString(s);
- if (!uri.isNull()) {
- if (uri.getQueryType() == "join") {
- uiEventStream->send(boost::make_shared<RequestJoinMUCUIEvent>(uri.getPath()));
- }
- else {
- uiEventStream->send(boost::make_shared<RequestChatUIEvent>(uri.getPath()));
- }
- }
+ XMPPURI uri = XMPPURI::fromString(s);
+ if (!uri.isNull()) {
+ if (uri.getQueryType() == "join") {
+ uiEventStream->send(boost::make_shared<RequestJoinMUCUIEvent>(uri.getPath()));
+ }
+ else {
+ uiEventStream->send(boost::make_shared<RequestChatUIEvent>(uri.getPath()));
+ }
+ }
}
diff --git a/Swift/Controllers/XMPPURIController.h b/Swift/Controllers/XMPPURIController.h
index 4938ad7..4d2fb5c 100644
--- a/Swift/Controllers/XMPPURIController.h
+++ b/Swift/Controllers/XMPPURIController.h
@@ -11,23 +11,23 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class URIHandler;
- class JID;
- class UIEventStream;
+ class URIHandler;
+ class JID;
+ class UIEventStream;
- class XMPPURIController {
- public:
- XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream);
- ~XMPPURIController();
+ class XMPPURIController {
+ public:
+ XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream);
+ ~XMPPURIController();
- boost::signal<void (const JID&)> onStartChat;
- boost::signal<void (const JID&)> onJoinMUC;
+ boost::signal<void (const JID&)> onStartChat;
+ boost::signal<void (const JID&)> onJoinMUC;
- private:
- void handleURI(const std::string&);
+ private:
+ void handleURI(const std::string&);
- private:
- URIHandler* uriHandler;
- UIEventStream* uiEventStream;
- };
+ private:
+ URIHandler* uriHandler;
+ UIEventStream* uiEventStream;
+ };
}
diff --git a/Swift/QtUI/ApplicationTest/main.cpp b/Swift/QtUI/ApplicationTest/main.cpp
index 489865e..782bbf1 100644
--- a/Swift/QtUI/ApplicationTest/main.cpp
+++ b/Swift/QtUI/ApplicationTest/main.cpp
@@ -18,31 +18,31 @@
using namespace Swift;
class MyWidget : public QWidget {
- Q_OBJECT
-
- public:
- MyWidget() : application_("MyApplication") {
- QVBoxLayout *layout = new QVBoxLayout(this);
- input_ = new QLineEdit(this);
- layout->addWidget(input_);
- connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed()));
- }
-
- private slots:
- void handleReturnPressed() {
- application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text()));
- }
-
- private:
- PlatformApplication application_;
- QLineEdit* input_;
+ Q_OBJECT
+
+ public:
+ MyWidget() : application_("MyApplication") {
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ input_ = new QLineEdit(this);
+ layout->addWidget(input_);
+ connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed()));
+ }
+
+ private slots:
+ void handleReturnPressed() {
+ application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text()));
+ }
+
+ private:
+ PlatformApplication application_;
+ QLineEdit* input_;
};
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- MyWidget widget;
- widget.show();
- return app.exec();
+ QApplication app(argc, argv);
+ MyWidget widget;
+ widget.show();
+ return app.exec();
}
#include "main.moc"
diff --git a/Swift/QtUI/CAPICertificateSelector.cpp b/Swift/QtUI/CAPICertificateSelector.cpp
index 953051b..36d8c54 100644
--- a/Swift/QtUI/CAPICertificateSelector.cpp
+++ b/Swift/QtUI/CAPICertificateSelector.cpp
@@ -23,94 +23,94 @@
namespace Swift {
/////Hmm, maybe we should not exlude the "location" column
-#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN
+#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN
#define SHA1_HASH_LENGTH 20
static std::string getCertUri(PCCERT_CONTEXT cert, const char * cert_store_name) {
- DWORD cbHash = SHA1_HASH_LENGTH;
- BYTE aHash[SHA1_HASH_LENGTH];
- std::string result("certstore:");
+ DWORD cbHash = SHA1_HASH_LENGTH;
+ BYTE aHash[SHA1_HASH_LENGTH];
+ std::string result("certstore:");
- result += cert_store_name;
- result += ":sha1:";
+ result += cert_store_name;
+ result += ":sha1:";
- if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) {
- return "";
- }
+ if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) {
+ return "";
+ }
- ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash);
- result += Hexify::hexify(byteArray);
+ ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash);
+ result += Hexify::hexify(byteArray);
- return result;
+ return result;
}
std::string selectCAPICertificate() {
- const char* certStoreName = "MY";
+ const char* certStoreName = "MY";
- DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
+ DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
- HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName);
- if (!hstore) {
- return "";
- }
+ HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName);
+ if (!hstore) {
+ return "";
+ }
- HWND hwnd = GetForegroundWindow();
- if (!hwnd) {
- hwnd = GetActiveWindow();
- }
+ HWND hwnd = GetForegroundWindow();
+ if (!hwnd) {
+ hwnd = GetActiveWindow();
+ }
- std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection");
- std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication");
+ std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection");
+ std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication");
- int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0);
- int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0);
+ int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0);
+ int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0);
- wchar_t* titleChars = new wchar_t[titleLength];
- wchar_t* promptChars = new wchar_t[promptLength];
+ wchar_t* titleChars = new wchar_t[titleLength];
+ wchar_t* promptChars = new wchar_t[promptLength];
- //titleChars[titleLength] = '\0';
- //promptChars[promptLength] = '\0';
+ //titleChars[titleLength] = '\0';
+ //promptChars[promptLength] = '\0';
- titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength);
- promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength);
+ titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength);
+ promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength);
- if (titleLength == 0 || promptLength == 0) {
- int error = GetLastError();
- switch (error) {
- case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break;
- case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break;
- default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl;
+ if (titleLength == 0 || promptLength == 0) {
+ int error = GetLastError();
+ switch (error) {
+ case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break;
+ case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break;
+ case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break;
+ case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break;
+ default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl;
- }
- }
+ }
+ }
-
- /* Call Windows dialog to select a suitable certificate */
- PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL);
- delete[] titleChars;
- delete[] promptChars;
+ /* Call Windows dialog to select a suitable certificate */
+ PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL);
- if (hstore) {
- CertCloseStore(hstore, 0);
- }
+ delete[] titleChars;
+ delete[] promptChars;
- std::string result;
+ if (hstore) {
+ CertCloseStore(hstore, 0);
+ }
- if (cert) {
- result = getCertUri(cert, certStoreName);
- CertFreeCertificateContext(cert);
- }
+ std::string result;
- return result;
+ if (cert) {
+ result = getCertUri(cert, certStoreName);
+ CertFreeCertificateContext(cert);
+ }
+
+ return result;
}
bool isCAPIURI(std::string uri) {
- return (boost::iequals(uri.substr(0, 10), "certstore:"));
+ return (boost::iequals(uri.substr(0, 10), "certstore:"));
}
}
diff --git a/Swift/QtUI/CAPICertificateSelector.h b/Swift/QtUI/CAPICertificateSelector.h
index 714f1c5..8273c78 100644
--- a/Swift/QtUI/CAPICertificateSelector.h
+++ b/Swift/QtUI/CAPICertificateSelector.h
@@ -9,6 +9,6 @@
#include <string>
namespace Swift {
- std::string selectCAPICertificate();
- bool isCAPIURI(std::string uri);
+ std::string selectCAPICertificate();
+ bool isCAPIURI(std::string uri);
}
diff --git a/Swift/QtUI/ChatList/ChatListDelegate.cpp b/Swift/QtUI/ChatList/ChatListDelegate.cpp
index 5fa4e23..29eb29a 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.cpp
+++ b/Swift/QtUI/ChatList/ChatListDelegate.cpp
@@ -19,125 +19,125 @@
namespace Swift {
ChatListDelegate::ChatListDelegate(bool compact) : compact_(compact) {
- groupDelegate_ = new GroupItemDelegate();
+ groupDelegate_ = new GroupItemDelegate();
}
ChatListDelegate::~ChatListDelegate() {
- delete groupDelegate_;
+ delete groupDelegate_;
}
void ChatListDelegate::setCompact(bool compact) {
- compact_ = compact;
- emit sizeHintChanged(QModelIndex());
+ compact_ = compact;
+ emit sizeHintChanged(QModelIndex());
}
QSize ChatListDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
- if (item && dynamic_cast<ChatListMUCItem*>(item)) {
- return mucSizeHint(option, index);
- }
- else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
- return common_.contactSizeHint(option, index, compact_);
- }
- else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
- return groupDelegate_->sizeHint(option, index);
- }
- else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
- return common_.contactSizeHint(option, index, compact_);
- }
- return QStyledItemDelegate::sizeHint(option, index);
+ ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
+ if (item && dynamic_cast<ChatListMUCItem*>(item)) {
+ return mucSizeHint(option, index);
+ }
+ else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
+ return common_.contactSizeHint(option, index, compact_);
+ }
+ else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
+ return groupDelegate_->sizeHint(option, index);
+ }
+ else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ return common_.contactSizeHint(option, index, compact_);
+ }
+ return QStyledItemDelegate::sizeHint(option, index);
}
QSize ChatListDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
QSize ChatListDelegate::recentSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const {
- return mucSizeHint(option, index);
+ return mucSizeHint(option, index);
}
void ChatListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
- if (item && dynamic_cast<ChatListMUCItem*>(item)) {
- paintMUC(painter, option, dynamic_cast<ChatListMUCItem*>(item));
- }
- else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
- paintRecent(painter, option, dynamic_cast<ChatListRecentItem*>(item));
- }
- else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
- ChatListGroupItem* group = dynamic_cast<ChatListGroupItem*>(item);
- groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
- }
- else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
- paintWhiteboard(painter, option, dynamic_cast<ChatListWhiteboardItem*>(item));
- }
- else {
- QStyledItemDelegate::paint(painter, option, index);
- }
+ ChatListItem* item = static_cast<ChatListItem*>(index.internalPointer());
+ if (item && dynamic_cast<ChatListMUCItem*>(item)) {
+ paintMUC(painter, option, dynamic_cast<ChatListMUCItem*>(item));
+ }
+ else if (item && dynamic_cast<ChatListRecentItem*>(item)) {
+ paintRecent(painter, option, dynamic_cast<ChatListRecentItem*>(item));
+ }
+ else if (item && dynamic_cast<ChatListGroupItem*>(item)) {
+ ChatListGroupItem* group = dynamic_cast<ChatListGroupItem*>(item);
+ groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
+ }
+ else if (item && dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ paintWhiteboard(painter, option, dynamic_cast<ChatListWhiteboardItem*>(item));
+ }
+ else {
+ QStyledItemDelegate::paint(painter, option, index);
+ }
}
void ChatListDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString());
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString());
+
+ painter->restore();
}
void ChatListDelegate::paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value<QString>().isNull()) {
- avatarPath = item->data(ChatListRecentItem::AvatarRole).value<QString>();
- }
- QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
- ? item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- QString name = item->data(Qt::DisplayRole).toString();
- //qDebug() << "Avatar for " << name << " = " << avatarPath;
- QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value<QString>().isNull()) {
+ avatarPath = item->data(ChatListRecentItem::AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
+ ? item->data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ QString name = item->data(Qt::DisplayRole).toString();
+ //qDebug() << "Avatar for " << name << " = " << avatarPath;
+ QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
}
void ChatListDelegate::paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const {
- QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value<QString>().isNull()) {
- avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value<QString>();
- }
- QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>().isNull()
- ? item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");*/
- QString name = item->data(Qt::DisplayRole).toString();
- //qDebug() << "Avatar for " << name << " = " << avatarPath;
- QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
+ QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value<QString>().isNull()) {
+ avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>().isNull()
+ ? item->data(ChatListWhiteboardItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");*/
+ QString name = item->data(Qt::DisplayRole).toString();
+ //qDebug() << "Avatar for " << name << " = " << avatarPath;
+ QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_);
}
diff --git a/Swift/QtUI/ChatList/ChatListDelegate.h b/Swift/QtUI/ChatList/ChatListDelegate.h
index 2de209d..44ca947 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.h
+++ b/Swift/QtUI/ChatList/ChatListDelegate.h
@@ -11,28 +11,28 @@
#include <Swift/QtUI/Roster/GroupItemDelegate.h>
namespace Swift {
- class ChatListMUCItem;
- class ChatListRecentItem;
- class ChatListWhiteboardItem;
- class ChatListDelegate : public QStyledItemDelegate {
- public:
- ChatListDelegate(bool compact);
- ~ChatListDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
- private:
- void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const;
- void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const;
- void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const;
- QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ class ChatListMUCItem;
+ class ChatListRecentItem;
+ class ChatListWhiteboardItem;
+ class ChatListDelegate : public QStyledItemDelegate {
+ public:
+ ChatListDelegate(bool compact);
+ ~ChatListDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ public slots:
+ void setCompact(bool compact);
+ private:
+ void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const;
+ void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const;
+ void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const;
+ QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- bool compact_;
- DelegateCommons common_;
- GroupItemDelegate* groupDelegate_;
- };
+ bool compact_;
+ DelegateCommons common_;
+ GroupItemDelegate* groupDelegate_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListGroupItem.h b/Swift/QtUI/ChatList/ChatListGroupItem.h
index 9330505..427f00b 100644
--- a/Swift/QtUI/ChatList/ChatListGroupItem.h
+++ b/Swift/QtUI/ChatList/ChatListGroupItem.h
@@ -13,33 +13,33 @@
#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_) {
- 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_;
- };
+ 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_) {
+ 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/ChatListItem.h b/Swift/QtUI/ChatList/ChatListItem.h
index fa8b18a..c6fd762 100644
--- a/Swift/QtUI/ChatList/ChatListItem.h
+++ b/Swift/QtUI/ChatList/ChatListItem.h
@@ -11,16 +11,16 @@
#include <qdebug.h>
namespace Swift {
- class ChatListGroupItem;
- class ChatListItem {
- public:
- ChatListItem(ChatListGroupItem* parent) {parent_ = parent;}
- virtual ~ChatListItem() {}
+ class ChatListGroupItem;
+ class ChatListItem {
+ public:
+ ChatListItem(ChatListGroupItem* parent) {parent_ = parent;}
+ virtual ~ChatListItem() {}
- ChatListGroupItem* parent() {return parent_;}
- virtual QVariant data(int role) const = 0;
+ ChatListGroupItem* parent() {return parent_;}
+ virtual QVariant data(int role) const = 0;
- private:
- ChatListGroupItem* parent_;
- };
+ private:
+ ChatListGroupItem* parent_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.cpp b/Swift/QtUI/ChatList/ChatListMUCItem.cpp
index 1ad622d..7d072df 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.cpp
@@ -14,21 +14,21 @@ ChatListMUCItem::ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem*
}
const MUCBookmark& ChatListMUCItem::getBookmark() const {
- return bookmark_;
+ return bookmark_;
}
QVariant ChatListMUCItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(bookmark_.getName());
- case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString());
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;
- case AvatarRole: return avatar_;
- case PresenceIconRole: return getPresenceIcon();*/
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(bookmark_.getName());
+ case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString());
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;
+ case AvatarRole: return avatar_;
+ case PresenceIconRole: return getPresenceIcon();*/
+ default: return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.h b/Swift/QtUI/ChatList/ChatListMUCItem.h
index fb90b88..4e93600 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.h
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.h
@@ -15,19 +15,19 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListMUCItem : public ChatListItem {
- public:
- enum MUCItemRoles {
- DetailTextRole = Qt::UserRole/*,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent);
- const MUCBookmark& getBookmark() const;
- QVariant data(int role) const;
- private:
- MUCBookmark bookmark_;
- QList<ChatListItem*> items_;
- };
+ class ChatListMUCItem : public ChatListItem {
+ public:
+ enum MUCItemRoles {
+ DetailTextRole = Qt::UserRole/*,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent);
+ const MUCBookmark& getBookmark() const;
+ QVariant data(int role) const;
+ private:
+ MUCBookmark bookmark_;
+ QList<ChatListItem*> items_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListModel.cpp b/Swift/QtUI/ChatList/ChatListModel.cpp
index 2447aa1..307cdea 100644
--- a/Swift/QtUI/ChatList/ChatListModel.cpp
+++ b/Swift/QtUI/ChatList/ChatListModel.cpp
@@ -17,172 +17,172 @@
namespace Swift {
ChatListModel::ChatListModel() : whiteboards_(NULL) {
- root_ = new ChatListGroupItem("", NULL, false);
- mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_);
- recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false);
+ root_ = new ChatListGroupItem("", NULL, false);
+ mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_);
+ recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false);
#ifdef SWIFT_EXPERIMENTAL_WB
- whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false);
- root_->addItem(whiteboards_);
+ whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false);
+ root_->addItem(whiteboards_);
#endif
- root_->addItem(recents_);
- root_->addItem(mucBookmarks_);
+ root_->addItem(recents_);
+ root_->addItem(mucBookmarks_);
- QModelIndex idx = index(0, 0, QModelIndex());
- while (idx.isValid()) {
- if (idx.internalPointer() == mucBookmarks_) {
- mucBookmarksIndex_ = idx;
- } else if (idx.internalPointer() == recents_) {
- recentsIndex_ = idx;
- } else if (idx.internalPointer() == whiteboards_) {
- whiteboardsIndex_ = idx;
- }
- idx = index(idx.row() + 1, 0, QModelIndex());
- }
+ QModelIndex idx = index(0, 0, QModelIndex());
+ while (idx.isValid()) {
+ if (idx.internalPointer() == mucBookmarks_) {
+ mucBookmarksIndex_ = idx;
+ } else if (idx.internalPointer() == recents_) {
+ recentsIndex_ = idx;
+ } else if (idx.internalPointer() == whiteboards_) {
+ whiteboardsIndex_ = idx;
+ }
+ idx = index(idx.row() + 1, 0, QModelIndex());
+ }
}
Qt::ItemFlags ChatListModel::flags(const QModelIndex& index) const {
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (dynamic_cast<ChatListRecentItem*>(getItemForIndex(index))) {
- flags |= Qt::ItemIsDragEnabled;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (dynamic_cast<ChatListRecentItem*>(getItemForIndex(index))) {
+ flags |= Qt::ItemIsDragEnabled;
+ }
+ return flags;
}
void ChatListModel::clearBookmarks() {
- beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
- mucBookmarks_->clear();
- endRemoveRows();
+ beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
+ mucBookmarks_->clear();
+ endRemoveRows();
}
void ChatListModel::addMUCBookmark(const Swift::MUCBookmark& bookmark) {
- beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
- mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_));
- endInsertRows();
+ beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount());
+ mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_));
+ endInsertRows();
}
void ChatListModel::removeMUCBookmark(const Swift::MUCBookmark& bookmark) {
- for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
- ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
- if (item->getBookmark() == bookmark) {
- beginRemoveRows(mucBookmarksIndex_, i, i+1);
- mucBookmarks_->remove(i);
- endRemoveRows();
- break;
- }
- }
+ for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
+ ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
+ if (item->getBookmark() == bookmark) {
+ beginRemoveRows(mucBookmarksIndex_, i, i+1);
+ mucBookmarks_->remove(i);
+ endRemoveRows();
+ break;
+ }
+ }
}
void ChatListModel::addWhiteboardSession(const ChatListWindow::Chat& chat) {
- beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount());
- whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_));
- endInsertRows();
+ 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;
- }
- }
+ 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) {
- recents_->addItem(new ChatListRecentItem(chat, recents_));
+ beginRemoveRows(recentsIndex_, 0, recents_->rowCount());
+ recents_->clear();
+ endRemoveRows();
+ beginInsertRows(recentsIndex_, 0, recents.size());
+ foreach (const ChatListWindow::Chat chat, recents) {
+ recents_->addItem(new ChatListRecentItem(chat, recents_));
//whiteboards_->addItem(new ChatListRecentItem(chat, whiteboards_));
- }
- endInsertRows();
+ }
+ endInsertRows();
}
QMimeData* ChatListModel::mimeData(const QModelIndexList& indexes) const {
- QMimeData* data = QAbstractItemModel::mimeData(indexes);
- ChatListRecentItem *item = dynamic_cast<ChatListRecentItem*>(getItemForIndex(indexes.first()));
- if (item == NULL) {
- 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) {
- dataStream << P2QSTRING(jid.second.toString());
- }
- }
-
- data->setData(mimeType, itemData);
- return data;
+ QMimeData* data = QAbstractItemModel::mimeData(indexes);
+ ChatListRecentItem *item = dynamic_cast<ChatListRecentItem*>(getItemForIndex(indexes.first()));
+ if (item == NULL) {
+ 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) {
+ dataStream << P2QSTRING(jid.second.toString());
+ }
+ }
+
+ data->setData(mimeType, itemData);
+ return data;
}
const ChatListMUCItem* ChatListModel::getChatListMUCItem(const JID& roomJID) const {
- const ChatListMUCItem* mucItem = NULL;
- 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;
+ const ChatListMUCItem* mucItem = NULL;
+ 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;
+ return 1;
}
ChatListItem* ChatListModel::getItemForIndex(const QModelIndex& index) const {
- return index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
+ return index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
}
QVariant ChatListModel::data(const QModelIndex& index, int role) const {
- ChatListItem* item = getItemForIndex(index);
- return item ? item->data(role) : QVariant();
+ ChatListItem* item = getItemForIndex(index);
+ return item ? item->data(role) : QVariant();
}
QModelIndex ChatListModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
- ChatListGroupItem *parentItem = parent.isValid() ? static_cast<ChatListGroupItem*>(parent.internalPointer()) : root_;
+ ChatListGroupItem *parentItem = parent.isValid() ? static_cast<ChatListGroupItem*>(parent.internalPointer()) : root_;
- return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex();
+ return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex();
}
QModelIndex ChatListModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- ChatListGroupItem* parent = static_cast<ChatListGroupItem*>(index.internalPointer())->parent();
- return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent);
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ ChatListGroupItem* parent = static_cast<ChatListGroupItem*>(index.internalPointer())->parent();
+ return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent);
}
int ChatListModel::rowCount(const QModelIndex& parentIndex) const {
- ChatListGroupItem* parent = NULL;
- if (parentIndex.isValid()) {
- parent = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(parentIndex.internalPointer()));
- } else {
- parent = root_;
- }
- int count = (parent ? parent->rowCount() : 0);
- return count;
+ ChatListGroupItem* parent = NULL;
+ if (parentIndex.isValid()) {
+ parent = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(parentIndex.internalPointer()));
+ } else {
+ parent = root_;
+ }
+ int count = (parent ? parent->rowCount() : 0);
+ return count;
}
}
diff --git a/Swift/QtUI/ChatList/ChatListModel.h b/Swift/QtUI/ChatList/ChatListModel.h
index ea85efb..363b2e6 100644
--- a/Swift/QtUI/ChatList/ChatListModel.h
+++ b/Swift/QtUI/ChatList/ChatListModel.h
@@ -16,38 +16,38 @@
#include <Swift/QtUI/ChatList/ChatListGroupItem.h>
namespace Swift {
- class ChatListMUCItem;
-
- class ChatListModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- ChatListModel();
- Qt::ItemFlags flags(const QModelIndex& index) const;
- void addMUCBookmark(const MUCBookmark& bookmark);
- void removeMUCBookmark(const MUCBookmark& bookmark);
- void addWhiteboardSession(const ChatListWindow::Chat& chat);
- void removeWhiteboardSession(const JID& jid);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- ChatListItem* getItemForIndex(const QModelIndex& index) const;
- void clearBookmarks();
- void setRecents(const std::list<ChatListWindow::Chat>& recents);
- QMimeData* mimeData(const QModelIndexList& indexes) const;
-
- const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const;
-
- private:
- ChatListGroupItem* mucBookmarks_;
- ChatListGroupItem* recents_;
- ChatListGroupItem* whiteboards_;
- ChatListGroupItem* root_;
-
- QPersistentModelIndex mucBookmarksIndex_;
- QPersistentModelIndex recentsIndex_;
- QPersistentModelIndex whiteboardsIndex_;
- };
+ class ChatListMUCItem;
+
+ class ChatListModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ ChatListModel();
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ void addMUCBookmark(const MUCBookmark& bookmark);
+ void removeMUCBookmark(const MUCBookmark& bookmark);
+ void addWhiteboardSession(const ChatListWindow::Chat& chat);
+ void removeWhiteboardSession(const JID& jid);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ ChatListItem* getItemForIndex(const QModelIndex& index) const;
+ void clearBookmarks();
+ void setRecents(const std::list<ChatListWindow::Chat>& recents);
+ QMimeData* mimeData(const QModelIndexList& indexes) const;
+
+ const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const;
+
+ private:
+ ChatListGroupItem* mucBookmarks_;
+ ChatListGroupItem* recents_;
+ ChatListGroupItem* whiteboards_;
+ ChatListGroupItem* root_;
+
+ QPersistentModelIndex mucBookmarksIndex_;
+ QPersistentModelIndex recentsIndex_;
+ QPersistentModelIndex whiteboardsIndex_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.cpp b/Swift/QtUI/ChatList/ChatListRecentItem.cpp
index dc40855..383f312 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.cpp
@@ -17,25 +17,25 @@ ChatListRecentItem::ChatListRecentItem(const ChatListWindow::Chat& chat, ChatLis
}
const ChatListWindow::Chat& ChatListRecentItem::getChat() const {
- return chat_;
+ return chat_;
}
QVariant ChatListRecentItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle());
- case DetailTextRole: return P2QSTRING(chat_.activity);
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;*/
- case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
- case PresenceIconRole: return getPresenceIcon();
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle());
+ case DetailTextRole: return P2QSTRING(chat_.activity);
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;*/
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
+ case PresenceIconRole: return getPresenceIcon();
+ default: return QVariant();
+ }
}
QIcon ChatListRecentItem::getPresenceIcon() const {
- return QIcon(statusShowTypeToIconPath(chat_.statusType));
+ return QIcon(statusShowTypeToIconPath(chat_.statusType));
}
}
diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.h b/Swift/QtUI/ChatList/ChatListRecentItem.h
index 338bc43..4f0a363 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.h
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.h
@@ -18,20 +18,20 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListRecentItem : public ChatListItem {
- public:
- enum RecentItemRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2/*,
- StatusShowTypeRole = Qt::UserRole + 3,
- IdleRole = Qt::UserRole + 4*/
- };
- ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
- const ChatListWindow::Chat& getChat() const;
- QVariant data(int role) const;
- private:
- QIcon getPresenceIcon() const;
- ChatListWindow::Chat chat_;
- };
+ class ChatListRecentItem : public ChatListItem {
+ public:
+ enum RecentItemRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2/*,
+ StatusShowTypeRole = Qt::UserRole + 3,
+ IdleRole = Qt::UserRole + 4*/
+ };
+ ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
+ const ChatListWindow::Chat& getChat() const;
+ QVariant data(int role) const;
+ private:
+ QIcon getPresenceIcon() const;
+ ChatListWindow::Chat chat_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
index f6ecec1..b6f8951 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
@@ -18,30 +18,30 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
- ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) {
-
- }
-
- const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const {
- return chat_;
- }
-
- QVariant ChatListWhiteboardItem::data(int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(chat_.chatName);
- case DetailTextRole: return P2QSTRING(chat_.activity);
- /*case Qt::TextColorRole: return textColor_;
- case Qt::BackgroundColorRole: return backgroundColor_;
- case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
- case StatusTextRole: return statusText_;*/
- case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
- case PresenceIconRole: return getPresenceIcon();
- default: return QVariant();
- }
- }
-
- QIcon ChatListWhiteboardItem::getPresenceIcon() const {
- return QIcon(statusShowTypeToIconPath(chat_.statusType));
- }
+ ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) {
+
+ }
+
+ const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const {
+ return chat_;
+ }
+
+ QVariant ChatListWhiteboardItem::data(int role) const {
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(chat_.chatName);
+ case DetailTextRole: return P2QSTRING(chat_.activity);
+ /*case Qt::TextColorRole: return textColor_;
+ case Qt::BackgroundColorRole: return backgroundColor_;
+ case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant();
+ case StatusTextRole: return statusText_;*/
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath)));
+ case PresenceIconRole: return getPresenceIcon();
+ default: return QVariant();
+ }
+ }
+
+ QIcon ChatListWhiteboardItem::getPresenceIcon() const {
+ return QIcon(statusShowTypeToIconPath(chat_.statusType));
+ }
}
diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
index fbbe7c5..92acb1c 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
@@ -18,19 +18,19 @@
#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListWhiteboardItem : public ChatListItem {
- public:
- enum RecentItemRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2/*,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
- const ChatListWindow::Chat& getChat() const;
- QVariant data(int role) const;
- private:
- QIcon getPresenceIcon() const;
- ChatListWindow::Chat chat_;
- };
+ class ChatListWhiteboardItem : public ChatListItem {
+ public:
+ enum RecentItemRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2/*,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent);
+ const ChatListWindow::Chat& getChat() const;
+ QVariant data(int role) const;
+ private:
+ QIcon getPresenceIcon() const;
+ ChatListWindow::Chat chat_;
+ };
}
diff --git a/Swift/QtUI/ChatList/QtChatListWindow.cpp b/Swift/QtUI/ChatList/QtChatListWindow.cpp
index b990b84..eddd0cd 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.cpp
+++ b/Swift/QtUI/ChatList/QtChatListWindow.cpp
@@ -31,197 +31,197 @@
namespace Swift {
QtChatListWindow::QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent) : QTreeView(parent), isOnline_(false) {
- eventStream_ = uiEventStream;
- settings_ = settings;
- bookmarksEnabled_ = false;
- model_ = new ChatListModel();
- setModel(model_);
- delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- setItemDelegate(delegate_);
- setHeaderHidden(true);
+ eventStream_ = uiEventStream;
+ settings_ = settings;
+ bookmarksEnabled_ = false;
+ model_ = new ChatListModel();
+ setModel(model_);
+ delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ setItemDelegate(delegate_);
+ setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- setAlternatingRowColors(true);
+ setAlternatingRowColors(true);
#endif
- expandAll();
- setAnimated(true);
- setIndentation(0);
- setDragEnabled(true);
- setRootIsDecorated(true);
- setupContextMenus();
- connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
- connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
+ expandAll();
+ setAnimated(true);
+ setIndentation(0);
+ setDragEnabled(true);
+ setRootIsDecorated(true);
+ setupContextMenus();
+ connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
- settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
}
QtChatListWindow::~QtChatListWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
- delete model_;
- delete delegate_;
- delete mucMenu_;
- delete emptyMenu_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1));
+ delete model_;
+ delete delegate_;
+ delete mucMenu_;
+ delete emptyMenu_;
}
void QtChatListWindow::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- repaint();
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ repaint();
+ }
}
void QtChatListWindow::handleClearRecentsRequested() {
- onClearRecentsRequested();
+ onClearRecentsRequested();
}
void QtChatListWindow::setBookmarksEnabled(bool enabled) {
- bookmarksEnabled_ = enabled;
+ bookmarksEnabled_ = enabled;
}
void QtChatListWindow::handleClicked(const QModelIndex& index) {
- ChatListGroupItem* item = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(index.internalPointer()));
- if (item) {
- setExpanded(index, !isExpanded(index));
- }
+ ChatListGroupItem* item = dynamic_cast<ChatListGroupItem*>(static_cast<ChatListItem*>(index.internalPointer()));
+ if (item) {
+ setExpanded(index, !isExpanded(index));
+ }
}
void QtChatListWindow::setupContextMenus() {
- mucMenu_ = new QMenu();
- onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
- onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
- onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark()));
- emptyMenu_ = new QMenu();
- onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
+ mucMenu_ = new QMenu();
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
+ onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark()));
+ emptyMenu_ = new QMenu();
+ onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark()));
}
void QtChatListWindow::handleItemActivated(const QModelIndex& index) {
- ChatListItem* item = model_->getItemForIndex(index);
- if (ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(item)) {
- onMUCBookmarkActivated(mucItem->getBookmark());
- }
- else if (ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(item)) {
- onRecentActivated(recentItem->getChat());
- }
- else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast<ChatListWhiteboardItem*>(item)) {
- if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) {
- eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(whiteboardItem->getChat().jid));
- }
- }
+ ChatListItem* item = model_->getItemForIndex(index);
+ if (ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(item)) {
+ onMUCBookmarkActivated(mucItem->getBookmark());
+ }
+ else if (ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(item)) {
+ onRecentActivated(recentItem->getChat());
+ }
+ else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast<ChatListWhiteboardItem*>(item)) {
+ if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) {
+ eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(whiteboardItem->getChat().jid));
+ }
+ }
}
void QtChatListWindow::clearBookmarks() {
- model_->clearBookmarks();
+ model_->clearBookmarks();
}
void QtChatListWindow::addMUCBookmark(const MUCBookmark& bookmark) {
- model_->addMUCBookmark(bookmark);
+ model_->addMUCBookmark(bookmark);
}
void QtChatListWindow::removeMUCBookmark(const MUCBookmark& bookmark) {
- model_->removeMUCBookmark(bookmark);
+ model_->removeMUCBookmark(bookmark);
}
void QtChatListWindow::addWhiteboardSession(const ChatListWindow::Chat& chat) {
- model_->addWhiteboardSession(chat);
+ model_->addWhiteboardSession(chat);
}
void QtChatListWindow::removeWhiteboardSession(const JID& jid) {
- model_->removeWhiteboardSession(jid);
+ model_->removeWhiteboardSession(jid);
}
void QtChatListWindow::setRecents(const std::list<ChatListWindow::Chat>& recents) {
- model_->setRecents(recents);
+ model_->setRecents(recents);
}
void QtChatListWindow::setUnreadCount(int unread) {
- emit onCountUpdated(unread);
+ emit onCountUpdated(unread);
}
void QtChatListWindow::setOnline(bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
void QtChatListWindow::handleRemoveBookmark() {
- const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
- if (!mucItem) return;
- eventStream_->send(boost::shared_ptr<UIEvent>(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark())));
+ const ChatListMUCItem* mucItem = dynamic_cast<const ChatListMUCItem*>(contextMenuItem_);
+ if (!mucItem) return;
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark())));
}
void QtChatListWindow::handleAddBookmarkFromRecents() {
- const ChatListRecentItem* item = dynamic_cast<const ChatListRecentItem*>(contextMenuItem_);
- if (item) {
- const ChatListWindow::Chat& chat = item->getChat();
- MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString());
- bookmark.setNick(chat.nick);
- bookmark.setPassword(chat.password);
- eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(bookmark)));
- }
+ const ChatListRecentItem* item = dynamic_cast<const ChatListRecentItem*>(contextMenuItem_);
+ if (item) {
+ const ChatListWindow::Chat& chat = item->getChat();
+ MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString());
+ bookmark.setNick(chat.nick);
+ bookmark.setPassword(chat.password);
+ eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(bookmark)));
+ }
}
void QtChatListWindow::handleAddBookmark() {
- (new QtAddBookmarkWindow(eventStream_))->show();
+ (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();
+ 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();
- }
+ 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()) : NULL;
- contextMenuItem_ = baseItem;
-
- foreach(QAction* 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 = NULL;
- 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()));
- }
- bookmarkAction->setEnabled(isOnline_);
- mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
- mucRecentsMenu.exec(QCursor::pos());
- return;
- }
- }
-
- QMenu menu;
- menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
- menu.exec(event->globalPos());
+ QModelIndex index = indexAt(event->pos());
+ ChatListItem* baseItem = index.isValid() ? static_cast<ChatListItem*>(index.internalPointer()) : NULL;
+ contextMenuItem_ = baseItem;
+
+ foreach(QAction* 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 = NULL;
+ 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()));
+ }
+ bookmarkAction->setEnabled(isOnline_);
+ mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
+ mucRecentsMenu.exec(QCursor::pos());
+ return;
+ }
+ }
+
+ QMenu menu;
+ menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested()));
+ menu.exec(event->globalPos());
}
}
diff --git a/Swift/QtUI/ChatList/QtChatListWindow.h b/Swift/QtUI/ChatList/QtChatListWindow.h
index 627dcd4..61f8391 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.h
+++ b/Swift/QtUI/ChatList/QtChatListWindow.h
@@ -15,50 +15,50 @@
#include <Swift/QtUI/ChatList/ChatListModel.h>
namespace Swift {
- class SettingsProvider;
- class QtChatListWindow : public QTreeView, public ChatListWindow {
- Q_OBJECT
- public:
- QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL);
- virtual ~QtChatListWindow();
- void addMUCBookmark(const MUCBookmark& bookmark);
- void removeMUCBookmark(const MUCBookmark& bookmark);
- void addWhiteboardSession(const ChatListWindow::Chat& chat);
- void removeWhiteboardSession(const JID& jid);
- void setBookmarksEnabled(bool enabled);
- void setRecents(const std::list<ChatListWindow::Chat>& recents);
- void setUnreadCount(int unread);
- void clearBookmarks();
- virtual void setOnline(bool isOnline);
+ class SettingsProvider;
+ class QtChatListWindow : public QTreeView, public ChatListWindow {
+ Q_OBJECT
+ public:
+ QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL);
+ virtual ~QtChatListWindow();
+ void addMUCBookmark(const MUCBookmark& bookmark);
+ void removeMUCBookmark(const MUCBookmark& bookmark);
+ void addWhiteboardSession(const ChatListWindow::Chat& chat);
+ void removeWhiteboardSession(const JID& jid);
+ void setBookmarksEnabled(bool enabled);
+ void setRecents(const std::list<ChatListWindow::Chat>& recents);
+ void setUnreadCount(int unread);
+ void clearBookmarks();
+ virtual void setOnline(bool isOnline);
- signals:
- void onCountUpdated(int count);
- private slots:
- void handleItemActivated(const QModelIndex&);
- void handleAddBookmark();
- void handleEditBookmark();
- void handleRemoveBookmark();
- void handleAddBookmarkFromRecents();
- void handleClicked(const QModelIndex& index);
- void handleSettingChanged(const std::string& setting);
- void handleClearRecentsRequested();
+ signals:
+ void onCountUpdated(int count);
+ private slots:
+ void handleItemActivated(const QModelIndex&);
+ void handleAddBookmark();
+ void handleEditBookmark();
+ void handleRemoveBookmark();
+ void handleAddBookmarkFromRecents();
+ void handleClicked(const QModelIndex& index);
+ void handleSettingChanged(const std::string& setting);
+ void handleClearRecentsRequested();
- protected:
- void dragEnterEvent(QDragEnterEvent* event);
- void contextMenuEvent(QContextMenuEvent* event);
+ protected:
+ void dragEnterEvent(QDragEnterEvent* event);
+ void contextMenuEvent(QContextMenuEvent* event);
- private:
- void setupContextMenus();
- bool bookmarksEnabled_;
- UIEventStream* eventStream_;
- ChatListModel* model_;
- ChatListDelegate* delegate_;
- QMenu* mucMenu_;
- QMenu* emptyMenu_;
- const ChatListItem* contextMenuItem_;
- SettingsProvider* settings_;
- QList<QAction*> onlineOnlyActions_;
- bool isOnline_;
- };
+ private:
+ void setupContextMenus();
+ bool bookmarksEnabled_;
+ UIEventStream* eventStream_;
+ ChatListModel* model_;
+ ChatListDelegate* delegate_;
+ QMenu* mucMenu_;
+ QMenu* emptyMenu_;
+ const ChatListItem* contextMenuItem_;
+ SettingsProvider* settings_;
+ QList<QAction*> onlineOnlyActions_;
+ bool isOnline_;
+ };
}
diff --git a/Swift/QtUI/ChatSnippet.cpp b/Swift/QtUI/ChatSnippet.cpp
index d8b64c1..14e4674 100644
--- a/Swift/QtUI/ChatSnippet.cpp
+++ b/Swift/QtUI/ChatSnippet.cpp
@@ -19,79 +19,79 @@ 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));
+ 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>";
+ return "<span class='swift_resizable'>" + text + "</span>";
}
QString ChatSnippet::directionToCSS(Direction direction) {
- return direction == RTL ? QString("rtl") : QString("ltr");
+ return direction == RTL ? QString("rtl") : QString("ltr");
}
ChatSnippet::Direction ChatSnippet::getDirection(const ChatWindow::ChatMessage& message) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- std::string text = "";
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- text = textPart->text;
- break;
- }
- }
- return getDirection(text);
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ std::string text = "";
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ if ((textPart = boost::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));
+ 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:
- case QChar::DirB:
- case QChar::DirWS:
- case QChar::DirON:
- case QChar::DirS:
- case QChar::DirPDF:
- case QChar::DirNSM:
- case QChar::DirBN:
- break;
- }
- }
- return ChatSnippet::LTR;
- */
- return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR;
+ /*
+ 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:
+ case QChar::DirB:
+ case QChar::DirWS:
+ case QChar::DirON:
+ case QChar::DirS:
+ case QChar::DirPDF:
+ case QChar::DirNSM:
+ case QChar::DirBN:
+ break;
+ }
+ }
+ return ChatSnippet::LTR;
+ */
+ return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR;
}
diff --git a/Swift/QtUI/ChatSnippet.h b/Swift/QtUI/ChatSnippet.h
index 7c99928..bf2d6d2 100644
--- a/Swift/QtUI/ChatSnippet.h
+++ b/Swift/QtUI/ChatSnippet.h
@@ -18,55 +18,55 @@
#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 ""; }
-
- boost::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;");
- result.replace("%shortTime%", "%&#37;shortTime&#37;");
- result.replace("%userIconPath%", "&#37;userIconPath&#37;");
- result.replace("%id%", "&#37;id&#37;");
- result.replace("\t", " ");
- result.replace(" ", "&nbsp;&nbsp;");
- return result;
- }
-
- static QString timeToEscapedString(const QDateTime& time);
-
- static Direction getDirection(const std::string& message);
- static Direction getDirection(const ChatWindow::ChatMessage& message);
- static Direction getDirection(const QString& message);
-
- protected:
- static QString directionToCSS(Direction direction);
-
- QString wrapResizable(const QString& text);
- void setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet> continuationFallback) {
- continuationFallback_ = continuationFallback;
- }
- private:
- bool appendToPrevious_;
- boost::shared_ptr<ChatSnippet> continuationFallback_;
- };
+ class ChatSnippet {
+ public:
+ enum Direction {
+ RTL,
+ LTR
+ };
+
+ ChatSnippet(bool appendToPrevious);
+ virtual ~ChatSnippet();
+
+ virtual const QString& getContent() const = 0;
+ virtual QString getContinuationElementID() const { return ""; }
+
+ boost::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;");
+ result.replace("%shortTime%", "%&#37;shortTime&#37;");
+ result.replace("%userIconPath%", "&#37;userIconPath&#37;");
+ result.replace("%id%", "&#37;id&#37;");
+ result.replace("\t", " ");
+ result.replace(" ", "&nbsp;&nbsp;");
+ return result;
+ }
+
+ static QString timeToEscapedString(const QDateTime& time);
+
+ static Direction getDirection(const std::string& message);
+ static Direction getDirection(const ChatWindow::ChatMessage& message);
+ static Direction getDirection(const QString& message);
+
+ protected:
+ static QString directionToCSS(Direction direction);
+
+ QString wrapResizable(const QString& text);
+ void setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet> continuationFallback) {
+ continuationFallback_ = continuationFallback;
+ }
+ private:
+ bool appendToPrevious_;
+ boost::shared_ptr<ChatSnippet> continuationFallback_;
+ };
}
diff --git a/Swift/QtUI/ChatView/main.cpp b/Swift/QtUI/ChatView/main.cpp
index 4bde1ef..aa3255e 100644
--- a/Swift/QtUI/ChatView/main.cpp
+++ b/Swift/QtUI/ChatView/main.cpp
@@ -27,154 +27,154 @@ using namespace Swift;
/*
class MyNetworkReply : public QNetworkReply {
- public:
- MyNetworkReply() {
- }
-
- qint64 readData(char*, qint64) {
- return 0;
- }
-
- virtual void abort() {
- }
+ public:
+ MyNetworkReply() {
+ }
+
+ qint64 readData(char*, qint64) {
+ return 0;
+ }
+
+ virtual void abort() {
+ }
};
class MyNetworkAccessManager : public QNetworkAccessManager {
- public:
- MyNetworkAccessManager() {
- }
-
- QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) {
- assert(op == QNetworkAccessManager::GetOperation);
- qDebug() << "Requesting: " << request.url();
- return QNetworkAccessManager::createRequest(op, request, outgoingData);
- //return new MyNetworkReply();
- }
+ public:
+ MyNetworkAccessManager() {
+ }
+
+ QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) {
+ assert(op == QNetworkAccessManager::GetOperation);
+ qDebug() << "Requesting: " << request.url();
+ return QNetworkAccessManager::createRequest(op, request, outgoingData);
+ //return new MyNetworkReply();
+ }
};
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- webView_ = new QWebView(this);
-
- QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html");
- file.open(QIODevice::ReadOnly);
- QString content = QString::fromUtf8(file.readAll());
-
- webPage_ = new QWebPage(this);
- webPage_->setNetworkAccessManager(new MyNetworkAccessManager());
- webView_->setPage(webPage_);
- QString pagehtml =
- "<head>"
- //"<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
- "<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
- "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"/>"
- "<link rel=\"stylesheet\" type=\"text/css\" href=\"Variants/Alt Blue - Blue.css\"/>"
- "</head><body>" + content + "</body>";
- qDebug() << pagehtml;
- webPage_->mainFrame()->setHtml(pagehtml);
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ webView_ = new QWebView(this);
+
+ QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html");
+ file.open(QIODevice::ReadOnly);
+ QString content = QString::fromUtf8(file.readAll());
+
+ webPage_ = new QWebPage(this);
+ webPage_->setNetworkAccessManager(new MyNetworkAccessManager());
+ webView_->setPage(webPage_);
+ QString pagehtml =
+ "<head>"
+ //"<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
+ "<base href=\"file:///Users/remko/src/swift/resources/themes/Stockholm/Contents/Resources/\"/>"
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"/>"
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"Variants/Alt Blue - Blue.css\"/>"
+ "</head><body>" + content + "</body>";
+ qDebug() << pagehtml;
+ webPage_->mainFrame()->setHtml(pagehtml);
*/
/*
class ChatView : public QWidget {
- public:
- ChatView(QWidget* parent) : QWidget(parent) {
- setFocusPolicy(Qt::NoFocus);
-
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
-
- webView_ = new QWebView(this);
- webView_->setFocusPolicy(Qt::NoFocus);
- mainLayout->addWidget(webView_);
-
- webPage_ = new QWebPage(this);
- webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
- webView_->setPage(webPage_);
- connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
-
- QString pageHTML = "<head></head><body><div id=\"chat\"></div></body>";
- webPage_->mainFrame()->setHtml(pageHTML);
- }
-
- void appendHTML(const QString& html) {
- webPage_->mainFrame()->evaluateJavaScript(
- "newNode = document.createElement(\"div\");"
- "newNode.innerHTML = \"" + html + "\";"
- "chatElement = document.getElementById(\"chat\");"
- "chatElement.appendChild(newNode);");
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
- }
-
- private:
- QWebView* webView_;
- QWebPage* webPage_;
+ public:
+ ChatView(QWidget* parent) : QWidget(parent) {
+ setFocusPolicy(Qt::NoFocus);
+
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+
+ webView_ = new QWebView(this);
+ webView_->setFocusPolicy(Qt::NoFocus);
+ mainLayout->addWidget(webView_);
+
+ webPage_ = new QWebPage(this);
+ webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
+ webView_->setPage(webPage_);
+ connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
+
+ QString pageHTML = "<head></head><body><div id=\"chat\"></div></body>";
+ webPage_->mainFrame()->setHtml(pageHTML);
+ }
+
+ void appendHTML(const QString& html) {
+ webPage_->mainFrame()->evaluateJavaScript(
+ "newNode = document.createElement(\"div\");"
+ "newNode.innerHTML = \"" + html + "\";"
+ "chatElement = document.getElementById(\"chat\");"
+ "chatElement.appendChild(newNode);");
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
+ }
+
+ private:
+ QWebView* webView_;
+ QWebPage* webPage_;
};
*/
class MyWidget : public QWidget {
- Q_OBJECT
-
- public:
- MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) {
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- chatView_ = new QtChatView(this);
- mainLayout->addWidget(chatView_);
- input1_ = new QLineEdit(this);
- connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming()));
- mainLayout->addWidget(input1_);
- input2_ = new QLineEdit(this);
- connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing()));
- mainLayout->addWidget(input2_);
- input3_ = new QLineEdit(this);
- connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem()));
- mainLayout->addWidget(input3_);
-
- resize(300,200);
- }
-
- public slots:
- void addIncoming() {
- chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_));
- previousWasIncoming_ = true;
- previousWasOutgoing_ = false;
- previousWasSystem_ = false;
- input1_->clear();
- }
-
- void addOutgoing() {
- chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_));
- previousWasIncoming_ = false;
- previousWasOutgoing_ = true;
- previousWasSystem_ = false;
- input2_->clear();
- }
-
- void addSystem() {
- chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_));
- previousWasIncoming_ = false;
- previousWasOutgoing_ = false;
- previousWasSystem_ = true;
- input3_->clear();
- }
-
- private:
- bool previousWasIncoming_;
- bool previousWasOutgoing_;
- bool previousWasSystem_;
- QtChatView* chatView_;
- QLineEdit* input1_;
- QLineEdit* input2_;
- QLineEdit* input3_;
+ Q_OBJECT
+
+ public:
+ MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) {
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ chatView_ = new QtChatView(this);
+ mainLayout->addWidget(chatView_);
+ input1_ = new QLineEdit(this);
+ connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming()));
+ mainLayout->addWidget(input1_);
+ input2_ = new QLineEdit(this);
+ connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing()));
+ mainLayout->addWidget(input2_);
+ input3_ = new QLineEdit(this);
+ connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem()));
+ mainLayout->addWidget(input3_);
+
+ resize(300,200);
+ }
+
+ public slots:
+ void addIncoming() {
+ chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_));
+ previousWasIncoming_ = true;
+ previousWasOutgoing_ = false;
+ previousWasSystem_ = false;
+ input1_->clear();
+ }
+
+ void addOutgoing() {
+ chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_));
+ previousWasIncoming_ = false;
+ previousWasOutgoing_ = true;
+ previousWasSystem_ = false;
+ input2_->clear();
+ }
+
+ void addSystem() {
+ chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_));
+ previousWasIncoming_ = false;
+ previousWasOutgoing_ = false;
+ previousWasSystem_ = true;
+ input3_->clear();
+ }
+
+ private:
+ bool previousWasIncoming_;
+ bool previousWasOutgoing_;
+ bool previousWasSystem_;
+ QtChatView* chatView_;
+ QLineEdit* input1_;
+ QLineEdit* input2_;
+ QLineEdit* input3_;
};
-
+
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- MyWidget w;
- w.show();
- return app.exec();
+ QApplication app(argc, argv);
+ MyWidget w;
+ w.show();
+ return app.exec();
}
#include "main.moc"
diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.h b/Swift/QtUI/CocoaApplicationActivateHelper.h
index 2b166e2..c7aa5b3 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.h
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.h
@@ -9,20 +9,20 @@
#include <QObject>
namespace Swift {
- /**
- * This class is here as a workaround for a bug in Qt.
- * See Case #501.
- */
- class CocoaApplicationActivateHelper : public QObject {
- public:
- CocoaApplicationActivateHelper();
- virtual ~CocoaApplicationActivateHelper();
+ /**
+ * This class is here as a workaround for a bug in Qt.
+ * See Case #501.
+ */
+ class CocoaApplicationActivateHelper : public QObject {
+ public:
+ CocoaApplicationActivateHelper();
+ virtual ~CocoaApplicationActivateHelper();
- private:
- bool eventFilter(QObject* o, QEvent* e);
+ private:
+ bool eventFilter(QObject* o, QEvent* e);
- private:
- struct Private;
- Private* p;
- };
+ private:
+ struct Private;
+ Private* p;
+ };
}
diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.mm b/Swift/QtUI/CocoaApplicationActivateHelper.mm
index f9c455c..4d4409d 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.mm
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.mm
@@ -19,37 +19,37 @@
@implementation CocoaApplicationActivateHelperDelegate
- (void) handleActivate: (NSAppleEventDescriptor*) event withReply: (NSAppleEventDescriptor*) reply {
- (void) event; (void) reply;
- QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate));
+ (void) event; (void) reply;
+ QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate));
}
@end
namespace Swift {
struct CocoaApplicationActivateHelper::Private {
- CocoaApplicationActivateHelperDelegate* delegate;
- bool initialized;
+ CocoaApplicationActivateHelperDelegate* delegate;
+ bool initialized;
};
CocoaApplicationActivateHelper::CocoaApplicationActivateHelper() {
- p = new Private();
- p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init];
- p->initialized = false;
- qApp->installEventFilter(this);
+ p = new Private();
+ p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init];
+ p->initialized = false;
+ qApp->installEventFilter(this);
}
CocoaApplicationActivateHelper::~CocoaApplicationActivateHelper() {
- [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication];
- [p->delegate release];
- delete p;
+ [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication];
+ [p->delegate release];
+ delete p;
}
bool CocoaApplicationActivateHelper::eventFilter(QObject* object, QEvent* event) {
- if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) {
- [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication];
- p->initialized = true;
- }
- return QObject::eventFilter(object, event);
+ if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) {
+ [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication];
+ p->initialized = true;
+ }
+ return QObject::eventFilter(object, event);
}
diff --git a/Swift/QtUI/CocoaUIHelpers.h b/Swift/QtUI/CocoaUIHelpers.h
index f5ec457..58cd539 100644
--- a/Swift/QtUI/CocoaUIHelpers.h
+++ b/Swift/QtUI/CocoaUIHelpers.h
@@ -20,7 +20,7 @@ namespace Swift {
class CocoaUIHelpers {
public:
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
};
}
diff --git a/Swift/QtUI/CocoaUIHelpers.mm b/Swift/QtUI/CocoaUIHelpers.mm
index 3cb62f3..16fe2ce 100644
--- a/Swift/QtUI/CocoaUIHelpers.mm
+++ b/Swift/QtUI/CocoaUIHelpers.mm
@@ -21,23 +21,23 @@
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) {
- // convert chain to SecCertificateRef
- ByteArray certAsDER = cert->toDER();
- boost::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease);
- boost::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(NULL, 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:NULL contextInfo:NULL certificates:certificates showGroup:YES];
- [certificates release];
+ NSWindow* parentWindow = [((NSView*)parent->winId()) window];
+ NSMutableArray* certificates = [[NSMutableArray alloc] init];
+ foreach(Certificate::ref cert, chain) {
+ // convert chain to SecCertificateRef
+ ByteArray certAsDER = cert->toDER();
+ boost::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease);
+ boost::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(NULL, 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:NULL contextInfo:NULL certificates:certificates showGroup:YES];
+ [certificates release];
}
}
diff --git a/Swift/QtUI/EventViewer/EventDelegate.cpp b/Swift/QtUI/EventViewer/EventDelegate.cpp
index cd657b8..eff9a7b 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.cpp
+++ b/Swift/QtUI/EventViewer/EventDelegate.cpp
@@ -17,69 +17,69 @@
namespace Swift {
EventDelegate::EventDelegate() : QStyledItemDelegate(),
- messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
- subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
- errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
- mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
- incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) {
+ messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
+ subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
+ errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true),
+ mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false),
+ incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) {
}
QSize EventDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
- if (!item) {
- return QStyledItemDelegate::sizeHint(option, index);
- }
- switch (getEventType(item->getEvent())) {
- case MessageEventType: return messageDelegate_.sizeHint(option, item);
- case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item);
- case ErrorEventType: return errorDelegate_.sizeHint(option, item);
- case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item);
- case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item);
- }
- assert(false);
- return QSize();
+ QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
+ if (!item) {
+ return QStyledItemDelegate::sizeHint(option, index);
+ }
+ switch (getEventType(item->getEvent())) {
+ case MessageEventType: return messageDelegate_.sizeHint(option, item);
+ case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item);
+ case ErrorEventType: return errorDelegate_.sizeHint(option, item);
+ case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item);
+ case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item);
+ }
+ assert(false);
+ return QSize();
}
void EventDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
- if (!item) {
- QStyledItemDelegate::paint(painter, option, index);
- return;
- }
- switch (getEventType(item->getEvent())) {
- case MessageEventType: messageDelegate_.paint(painter, option, item);break;
- case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break;
- case ErrorEventType: errorDelegate_.paint(painter, option, item);break;
- case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break;
- case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break;
- }
+ QtEvent* item = static_cast<QtEvent*>(index.internalPointer());
+ if (!item) {
+ QStyledItemDelegate::paint(painter, option, index);
+ return;
+ }
+ switch (getEventType(item->getEvent())) {
+ case MessageEventType: messageDelegate_.paint(painter, option, item);break;
+ case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break;
+ case ErrorEventType: errorDelegate_.paint(painter, option, item);break;
+ case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break;
+ case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break;
+ }
}
EventType EventDelegate::getEventType(boost::shared_ptr<StanzaEvent> event) const {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event);
- if (messageEvent) {
- return MessageEventType;
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event);
- if (subscriptionEvent) {
- return SubscriptionEventType;
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event);
- if (errorEvent) {
- return ErrorEventType;
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event);
- if (mucInviteEvent) {
- return MUCInviteEventType;
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event);
- if (incomingFileTransferEvent) {
- return IncomingFileTransferEventType;
- }
- //I don't know what this is.
- assert(false);
- return MessageEventType;
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event);
+ if (messageEvent) {
+ return MessageEventType;
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event);
+ if (subscriptionEvent) {
+ return SubscriptionEventType;
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event);
+ if (errorEvent) {
+ return ErrorEventType;
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event);
+ if (mucInviteEvent) {
+ return MUCInviteEventType;
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event);
+ if (incomingFileTransferEvent) {
+ return IncomingFileTransferEventType;
+ }
+ //I don't know what this is.
+ assert(false);
+ return MessageEventType;
}
}
diff --git a/Swift/QtUI/EventViewer/EventDelegate.h b/Swift/QtUI/EventViewer/EventDelegate.h
index 6ab96e4..0804589 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.h
+++ b/Swift/QtUI/EventViewer/EventDelegate.h
@@ -12,21 +12,21 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType};
- class EventDelegate : public QStyledItemDelegate {
- Q_OBJECT
- public:
- EventDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- private:
- EventType getEventType(boost::shared_ptr<StanzaEvent> event) const;
- DelegateCommons common_;
- TwoLineDelegate messageDelegate_;
- TwoLineDelegate subscriptionDelegate_;
- TwoLineDelegate errorDelegate_;
- TwoLineDelegate mucInviteDelegate_;
- TwoLineDelegate incomingFileTransferDelegate_;
- };
+ enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType};
+ class EventDelegate : public QStyledItemDelegate {
+ Q_OBJECT
+ public:
+ EventDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ private:
+ EventType getEventType(boost::shared_ptr<StanzaEvent> event) const;
+ DelegateCommons common_;
+ TwoLineDelegate messageDelegate_;
+ TwoLineDelegate subscriptionDelegate_;
+ TwoLineDelegate errorDelegate_;
+ TwoLineDelegate mucInviteDelegate_;
+ TwoLineDelegate incomingFileTransferDelegate_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/EventModel.cpp b/Swift/QtUI/EventViewer/EventModel.cpp
index 889bcac..1568ec7 100644
--- a/Swift/QtUI/EventViewer/EventModel.cpp
+++ b/Swift/QtUI/EventViewer/EventModel.cpp
@@ -11,100 +11,100 @@
namespace Swift {
namespace {
- const int inactiveEventsLimit = 50;
+ const int inactiveEventsLimit = 50;
}
EventModel::EventModel() {
-
+
}
EventModel::~EventModel() {
- foreach (QtEvent* event, activeEvents_) {
- delete event;
- }
- foreach (QtEvent* event, inactiveEvents_) {
- delete event;
- }
+ foreach (QtEvent* event, activeEvents_) {
+ delete event;
+ }
+ foreach (QtEvent* event, inactiveEvents_) {
+ delete event;
+ }
}
QtEvent* EventModel::getItem(int row) const {
- QtEvent* event = NULL;
- 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;
+ QtEvent* event = NULL;
+ 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();
+ return activeEvents_.size();
}
QVariant EventModel::data(const QModelIndex& index, int role) const {
- if (!index.isValid()) {
- return QVariant();
- }
- QtEvent* item = getItem(index.row());
- QVariant result = item ? item->data(role) : QVariant();
- return result;
+ if (!index.isValid()) {
+ return QVariant();
+ }
+ QtEvent* item = getItem(index.row());
+ QVariant result = item ? item->data(role) : QVariant();
+ return result;
}
/*
* We only reimplement this to get the pointers inside the indices.
*/
QModelIndex EventModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent) || parent.isValid()) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent) || parent.isValid()) {
+ return QModelIndex();
+ }
- return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex();
+ return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex();
}
int EventModel::rowCount(const QModelIndex& parent) const {
- /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/
- int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size();
- return count;
+ /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/
+ int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size();
+ return count;
}
void EventModel::addEvent(boost::shared_ptr<StanzaEvent> event, bool active) {
- beginResetModel();
- if (active) {
- activeEvents_.push_front(new QtEvent(event, active));
- } else {
- inactiveEvents_.push_front(new QtEvent(event, active));
- if (inactiveEvents_.size() > inactiveEventsLimit) {
- removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent());
- }
- }
- endResetModel();
+ beginResetModel();
+ if (active) {
+ activeEvents_.push_front(new QtEvent(event, active));
+ } else {
+ inactiveEvents_.push_front(new QtEvent(event, active));
+ if (inactiveEvents_.size() > inactiveEventsLimit) {
+ removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent());
+ }
+ }
+ endResetModel();
}
void EventModel::removeEvent(boost::shared_ptr<StanzaEvent> event) {
- beginResetModel();
- for (int i = inactiveEvents_.size() - 1; i >= 0; i--) {
- if (event == inactiveEvents_[i]->getEvent()) {
- inactiveEvents_.removeAt(i);
- endResetModel();
- return;
- }
- }
-
- for (int i = 0; i < activeEvents_.size(); i++) {
- if (event == activeEvents_[i]->getEvent()) {
- activeEvents_.removeAt(i);
- endResetModel();
- return;
- }
- }
- endResetModel();
+ beginResetModel();
+ for (int i = inactiveEvents_.size() - 1; i >= 0; i--) {
+ if (event == inactiveEvents_[i]->getEvent()) {
+ inactiveEvents_.removeAt(i);
+ endResetModel();
+ return;
+ }
+ }
+
+ for (int i = 0; i < activeEvents_.size(); i++) {
+ if (event == activeEvents_[i]->getEvent()) {
+ activeEvents_.removeAt(i);
+ endResetModel();
+ return;
+ }
+ }
+ endResetModel();
}
}
diff --git a/Swift/QtUI/EventViewer/EventModel.h b/Swift/QtUI/EventViewer/EventModel.h
index 844e50f..5cd5028 100644
--- a/Swift/QtUI/EventViewer/EventModel.h
+++ b/Swift/QtUI/EventViewer/EventModel.h
@@ -17,21 +17,21 @@
namespace Swift {
class EventModel : public QAbstractListModel {
- Q_OBJECT
- public:
- EventModel();
- virtual ~EventModel();
- void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- void removeEvent(boost::shared_ptr<StanzaEvent> event);
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- QtEvent* getItem(int row) const;
- int getNewEventCount();
- protected:
- QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const;
- private:
- QList<QtEvent*> activeEvents_;
- QList<QtEvent*> inactiveEvents_;
+ Q_OBJECT
+ public:
+ EventModel();
+ virtual ~EventModel();
+ void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(boost::shared_ptr<StanzaEvent> event);
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ QtEvent* getItem(int row) const;
+ int getNewEventCount();
+ protected:
+ QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const;
+ private:
+ QList<QtEvent*> activeEvents_;
+ QList<QtEvent*> inactiveEvents_;
};
}
diff --git a/Swift/QtUI/EventViewer/EventView.cpp b/Swift/QtUI/EventViewer/EventView.cpp
index fe299b8..4d56548 100644
--- a/Swift/QtUI/EventViewer/EventView.cpp
+++ b/Swift/QtUI/EventViewer/EventView.cpp
@@ -8,7 +8,7 @@
namespace Swift {
EventView::EventView(QWidget* parent) : QListView(parent) {
-
+
}
}
diff --git a/Swift/QtUI/EventViewer/EventView.h b/Swift/QtUI/EventViewer/EventView.h
index 36c67f3..83898bd 100644
--- a/Swift/QtUI/EventViewer/EventView.h
+++ b/Swift/QtUI/EventViewer/EventView.h
@@ -9,9 +9,9 @@
#include <QListView>
namespace Swift {
- class EventView : public QListView {
- Q_OBJECT
- public:
- EventView(QWidget* parent);
- };
+ class EventView : public QListView {
+ Q_OBJECT
+ public:
+ EventView(QWidget* parent);
+ };
}
diff --git a/Swift/QtUI/EventViewer/QtEvent.cpp b/Swift/QtUI/EventViewer/QtEvent.cpp
index cc52ba6..c287c66 100644
--- a/Swift/QtUI/EventViewer/QtEvent.cpp
+++ b/Swift/QtUI/EventViewer/QtEvent.cpp
@@ -20,79 +20,79 @@
namespace Swift {
QtEvent::QtEvent(boost::shared_ptr<StanzaEvent> event, bool active) : event_(event) {
- active_ = active;
+ active_ = active;
}
QVariant QtEvent::data(int role) {
- switch (role) {
- case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString();
- case Qt::DisplayRole: return QVariant(text());
- case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray);
- case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray);
- case SenderRole: return QVariant(sender());
- /*case StatusTextRole: return statusText_;
- case AvatarRole: return avatar_;
- case PresenceIconRole: return getPresenceIcon();*/
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString();
+ case Qt::DisplayRole: return QVariant(text());
+ case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray);
+ case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray);
+ case SenderRole: return QVariant(sender());
+ /*case StatusTextRole: return statusText_;
+ case AvatarRole: return avatar_;
+ case PresenceIconRole: return getPresenceIcon();*/
+ default: return QVariant();
+ }
}
QString QtEvent::sender() {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
- if (messageEvent) {
- return P2QSTRING(messageEvent->getStanza()->getFrom().toString());
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
- if (subscriptionRequestEvent) {
- return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString());
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
- if (errorEvent) {
- return P2QSTRING(errorEvent->getJID().toBare().toString());
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
- if (mucInviteEvent) {
- return P2QSTRING(mucInviteEvent->getInviter().toString());
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
- if (incomingFTEvent) {
- return P2QSTRING(incomingFTEvent->getSender().toString());
- }
- return "";
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getFrom().toString());
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
+ if (subscriptionRequestEvent) {
+ return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString());
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getJID().toBare().toString());
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
+ if (mucInviteEvent) {
+ return P2QSTRING(mucInviteEvent->getInviter().toString());
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
+ if (incomingFTEvent) {
+ return P2QSTRING(incomingFTEvent->getSender().toString());
+ }
+ return "";
}
QString QtEvent::text() {
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
- if (messageEvent) {
- return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or(""));
- }
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
- if (subscriptionRequestEvent) {
- std::string reason = subscriptionRequestEvent->getReason();
- QString message;
- if (reason.empty()) {
- message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str());
- }
- else {
- message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str());
- }
- return message;
- }
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
- if (errorEvent) {
- return P2QSTRING(errorEvent->getText());
- }
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
- if (mucInviteEvent) {
- QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString()));
- return message;
- }
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
- if (incomingFTEvent) {
- QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString()));
- return message;
- }
- return "";
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or(""));
+ }
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
+ if (subscriptionRequestEvent) {
+ std::string reason = subscriptionRequestEvent->getReason();
+ QString message;
+ if (reason.empty()) {
+ message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str());
+ }
+ else {
+ message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str());
+ }
+ return message;
+ }
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getText());
+ }
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event_);
+ if (mucInviteEvent) {
+ QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString()));
+ return message;
+ }
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event_);
+ if (incomingFTEvent) {
+ QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString()));
+ return message;
+ }
+ return "";
}
}
diff --git a/Swift/QtUI/EventViewer/QtEvent.h b/Swift/QtUI/EventViewer/QtEvent.h
index 3be041c..d369255 100644
--- a/Swift/QtUI/EventViewer/QtEvent.h
+++ b/Swift/QtUI/EventViewer/QtEvent.h
@@ -13,20 +13,20 @@
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
namespace Swift {
- class QtEvent {
- public:
- QtEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- QVariant data(int role);
- boost::shared_ptr<StanzaEvent> getEvent() { return event_; }
- enum EventRoles {
- SenderRole = Qt::UserRole
+ class QtEvent {
+ public:
+ QtEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ QVariant data(int role);
+ boost::shared_ptr<StanzaEvent> getEvent() { return event_; }
+ enum EventRoles {
+ SenderRole = Qt::UserRole
- };
+ };
- private:
- QString text();
- QString sender();
- boost::shared_ptr<StanzaEvent> event_;
- bool active_;
- };
+ private:
+ QString text();
+ QString sender();
+ boost::shared_ptr<StanzaEvent> event_;
+ bool active_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/QtEventWindow.cpp b/Swift/QtUI/EventViewer/QtEventWindow.cpp
index f92cd07..8395a6c 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.cpp
+++ b/Swift/QtUI/EventViewer/QtEventWindow.cpp
@@ -26,97 +26,97 @@
namespace Swift {
QtEventWindow::QtEventWindow(UIEventStream* eventStream) : EventWindow(false) {
- QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(0);
-
- view_ = new QTreeView(this);
- layout->addWidget(view_);
- eventStream_ = eventStream;
- model_ = new EventModel();
- view_->setModel(model_);
- delegate_ = new EventDelegate();
- view_->setItemDelegate(delegate_);
- view_->setHeaderHidden(true);
+ QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(0);
+
+ view_ = new QTreeView(this);
+ layout->addWidget(view_);
+ eventStream_ = eventStream;
+ model_ = new EventModel();
+ view_->setModel(model_);
+ delegate_ = new EventDelegate();
+ view_->setItemDelegate(delegate_);
+ view_->setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- view_->setAlternatingRowColors(true);
+ view_->setAlternatingRowColors(true);
#endif
- view_->setAnimated(true);
- view_->setIndentation(0);
- view_->setRootIsDecorated(true);
-
- readButton_ = new QPushButton(tr("Display Notice"), this);
- layout->addWidget(readButton_);
- readButton_->setEnabled(false);
- connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked()));
- connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&)));
- connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ view_->setAnimated(true);
+ view_->setIndentation(0);
+ view_->setRootIsDecorated(true);
+
+ readButton_ = new QPushButton(tr("Display Notice"), this);
+ layout->addWidget(readButton_);
+ readButton_->setEnabled(false);
+ connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked()));
+ connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&)));
+ connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
}
QtEventWindow::~QtEventWindow() {
- delete model_;
- delete delegate_;
- /* Not view_ because this is the parent */
+ delete model_;
+ delete delegate_;
+ /* Not view_ because this is the parent */
}
void QtEventWindow::handleItemClicked(const QModelIndex&) {
- readButton_->setEnabled(true);
+ readButton_->setEnabled(true);
}
void QtEventWindow::handleReadClicked() {
- QModelIndex index = view_->currentIndex();
- if (!index.isValid()) {
- return;
- }
- handleItemActivated(index);
+ QModelIndex index = view_->currentIndex();
+ if (!index.isValid()) {
+ return;
+ }
+ handleItemActivated(index);
}
void QtEventWindow::handleItemActivated(const QModelIndex& item) {
- QtEvent* event = model_->getItem(item.row());
- boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event->getEvent());
- boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event->getEvent());
- boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event->getEvent());
- boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event->getEvent());
- boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event->getEvent());
-
- if (messageEvent) {
- if (messageEvent->getStanza()->getType() == Message::Groupchat) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource())));
- } else {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(messageEvent->getStanza()->getFrom())));
- }
- } else if (subscriptionEvent) {
- QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this);
- window->show();
- } else if (mucInviteEvent) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(mucInviteEvent->getInviter())));
- mucInviteEvent->conclude();
- } else if (incomingFTEvent) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(incomingFTEvent->getSender())));
- incomingFTEvent->conclude();
- } else {
- if (errorEvent) {
- errorEvent->conclude();
- }
- QMessageBox msgBox;
- msgBox.setText(model_->data(item, Qt::DisplayRole).toString());
- msgBox.exec();
- }
+ QtEvent* event = model_->getItem(item.row());
+ boost::shared_ptr<MessageEvent> messageEvent = boost::dynamic_pointer_cast<MessageEvent>(event->getEvent());
+ boost::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = boost::dynamic_pointer_cast<SubscriptionRequestEvent>(event->getEvent());
+ boost::shared_ptr<MUCInviteEvent> mucInviteEvent = boost::dynamic_pointer_cast<MUCInviteEvent>(event->getEvent());
+ boost::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = boost::dynamic_pointer_cast<IncomingFileTransferEvent>(event->getEvent());
+ boost::shared_ptr<ErrorEvent> errorEvent = boost::dynamic_pointer_cast<ErrorEvent>(event->getEvent());
+
+ if (messageEvent) {
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource())));
+ } else {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(messageEvent->getStanza()->getFrom())));
+ }
+ } else if (subscriptionEvent) {
+ QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this);
+ window->show();
+ } else if (mucInviteEvent) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(mucInviteEvent->getInviter())));
+ mucInviteEvent->conclude();
+ } else if (incomingFTEvent) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(incomingFTEvent->getSender())));
+ incomingFTEvent->conclude();
+ } else {
+ if (errorEvent) {
+ errorEvent->conclude();
+ }
+ QMessageBox msgBox;
+ msgBox.setText(model_->data(item, Qt::DisplayRole).toString());
+ msgBox.exec();
+ }
}
void QtEventWindow::addEvent(boost::shared_ptr<StanzaEvent> event, bool active) {
- view_->clearSelection();
- model_->addEvent(event, active);
- emit onNewEventCountUpdated(model_->getNewEventCount());
- readButton_->setEnabled(model_->rowCount() > 0);
+ view_->clearSelection();
+ model_->addEvent(event, active);
+ emit onNewEventCountUpdated(model_->getNewEventCount());
+ readButton_->setEnabled(model_->rowCount() > 0);
}
void QtEventWindow::removeEvent(boost::shared_ptr<StanzaEvent> event) {
- view_->clearSelection();
- model_->removeEvent(event);
- emit onNewEventCountUpdated(model_->getNewEventCount());
- readButton_->setEnabled(model_->rowCount() > 0);
+ view_->clearSelection();
+ model_->removeEvent(event);
+ emit onNewEventCountUpdated(model_->getNewEventCount());
+ readButton_->setEnabled(model_->rowCount() > 0);
}
}
diff --git a/Swift/QtUI/EventViewer/QtEventWindow.h b/Swift/QtUI/EventViewer/QtEventWindow.h
index 1591c15..92f8de0 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.h
+++ b/Swift/QtUI/EventViewer/QtEventWindow.h
@@ -20,26 +20,26 @@
class QPushButton;
namespace Swift {
- class QtEventWindow : public QWidget, public EventWindow {
- Q_OBJECT
- public:
- QtEventWindow(UIEventStream* eventStream);
- ~QtEventWindow();
- void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
- void removeEvent(boost::shared_ptr<StanzaEvent> event);
- signals:
- void onNewEventCountUpdated(int count);
- private slots:
- void handleItemActivated(const QModelIndex& item);
- void handleItemClicked(const QModelIndex& item);
- void handleReadClicked();
- private:
- EventModel* model_;
- EventDelegate* delegate_;
- UIEventStream* eventStream_;
- QTreeView* view_;
- QPushButton* readButton_;
- };
-
+ class QtEventWindow : public QWidget, public EventWindow {
+ Q_OBJECT
+ public:
+ QtEventWindow(UIEventStream* eventStream);
+ ~QtEventWindow();
+ void addEvent(boost::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(boost::shared_ptr<StanzaEvent> event);
+ signals:
+ void onNewEventCountUpdated(int count);
+ private slots:
+ void handleItemActivated(const QModelIndex& item);
+ void handleItemClicked(const QModelIndex& item);
+ void handleReadClicked();
+ private:
+ EventModel* model_;
+ EventDelegate* delegate_;
+ UIEventStream* eventStream_;
+ QTreeView* view_;
+ QPushButton* readButton_;
+ };
+
}
diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
index 586de55..b90acca 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
@@ -12,9 +12,9 @@
namespace Swift {
TwoLineDelegate::TwoLineDelegate(int firstRole, int secondRole, bool wrap) {
- firstRole_ = firstRole;
- secondRole_ = secondRole;
- wrap_ = wrap;
+ firstRole_ = firstRole;
+ secondRole_ = secondRole;
+ wrap_ = wrap;
}
TwoLineDelegate::~TwoLineDelegate() {
@@ -22,41 +22,41 @@ TwoLineDelegate::~TwoLineDelegate() {
}
QSize TwoLineDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, QtEvent* /*event*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
void TwoLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- QColor nameColor = event->data(Qt::TextColorRole).value<QColor>();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString());
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ QColor nameColor = event->data(Qt::TextColorRole).value<QColor>();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString());
+
+ painter->restore();
}
}
diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.h b/Swift/QtUI/EventViewer/TwoLineDelegate.h
index 9eebb68..089f97a 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.h
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.h
@@ -12,18 +12,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class TwoLineDelegate {
- public:
- TwoLineDelegate(int firstRole, int secondRole, bool wrap);
- ~TwoLineDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const;
- private:
- DelegateCommons common_;
- int firstRole_;
- int secondRole_;
- bool wrap_;
- };
+ class TwoLineDelegate {
+ public:
+ TwoLineDelegate(int firstRole, int secondRole, bool wrap);
+ ~TwoLineDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const;
+ private:
+ DelegateCommons common_;
+ int firstRole_;
+ int secondRole_;
+ bool wrap_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/main.cpp b/Swift/QtUI/EventViewer/main.cpp
index ba2ab4b..5eddd90 100644
--- a/Swift/QtUI/EventViewer/main.cpp
+++ b/Swift/QtUI/EventViewer/main.cpp
@@ -17,17 +17,17 @@
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
- Swift::UIEventStream eventStream;
- Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream);
- viewer->show();
- boost::shared_ptr<Swift::Message> message1(new Swift::Message());
- message1->setBody("Oooh, shiny");
- boost::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
- for (int i = 0; i < 100; i++) {
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
- }
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::make_shared<Swift::ErrorEvent>(Swift::JID("me@example.com"), "Something bad did happen to you.")), true);
- return app.exec();
+ QApplication app(argc, argv);
+ Swift::UIEventStream eventStream;
+ Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream);
+ viewer->show();
+ boost::shared_ptr<Swift::Message> message1(new Swift::Message());
+ message1->setBody("Oooh, shiny");
+ boost::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
+ for (int i = 0; i < 100; i++) {
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
+ }
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::make_shared<Swift::ErrorEvent>(Swift::JID("me@example.com"), "Something bad did happen to you.")), true);
+ return app.exec();
}
diff --git a/Swift/QtUI/FreeDesktopNotifier.cpp b/Swift/QtUI/FreeDesktopNotifier.cpp
index 54e0ccc..16f6a11 100644
--- a/Swift/QtUI/FreeDesktopNotifier.cpp
+++ b/Swift/QtUI/FreeDesktopNotifier.cpp
@@ -23,37 +23,37 @@ FreeDesktopNotifier::FreeDesktopNotifier(const std::string& name) : applicationN
}
void FreeDesktopNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()>) {
- QDBusConnection bus = QDBusConnection::sessionBus();
- if (!bus.isConnected()) {
- return;
- }
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
- return;
- }
-
- QString body = description.c_str();
- body = body.replace("&", "&amp;");
- body = body.replace("<", "&lt;");
- body = body.replace(">", "&gt;");
-
- int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
-
- QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify");
-
- QStringList actions;
- QMap<QString, QVariant> hints;
- hints["x-canonical-append"] = QString("allowed");
- msg << applicationName.c_str();
- msg << quint32(0); // ID of previous notification to replace
- msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display
- msg << subject.c_str(); // Summary / Header of the message to display
- msg << body; // Body of the message to display
- msg << actions; // Actions from which the user may choose
- msg << hints; // Hints to the server displaying the message
- msg << qint32(timeout*1000); // Timeout in milliseconds
-
- bus.asyncCall(msg);
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (!bus.isConnected()) {
+ return;
+ }
+ std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
+ if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
+ return;
+ }
+
+ QString body = description.c_str();
+ body = body.replace("&", "&amp;");
+ body = body.replace("<", "&lt;");
+ body = body.replace(">", "&gt;");
+
+ int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+
+ QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify");
+
+ QStringList actions;
+ QMap<QString, QVariant> hints;
+ hints["x-canonical-append"] = QString("allowed");
+ msg << applicationName.c_str();
+ msg << quint32(0); // ID of previous notification to replace
+ msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display
+ msg << subject.c_str(); // Summary / Header of the message to display
+ msg << body; // Body of the message to display
+ msg << actions; // Actions from which the user may choose
+ msg << hints; // Hints to the server displaying the message
+ msg << qint32(timeout*1000); // Timeout in milliseconds
+
+ bus.asyncCall(msg);
}
}
diff --git a/Swift/QtUI/FreeDesktopNotifier.h b/Swift/QtUI/FreeDesktopNotifier.h
index 50601a0..dab7e73 100644
--- a/Swift/QtUI/FreeDesktopNotifier.h
+++ b/Swift/QtUI/FreeDesktopNotifier.h
@@ -11,15 +11,15 @@
#include <Swift/QtUI/QtCachedImageScaler.h>
namespace Swift {
- class FreeDesktopNotifier : public Notifier {
- public:
- FreeDesktopNotifier(const std::string& name);
+ class FreeDesktopNotifier : public Notifier {
+ public:
+ FreeDesktopNotifier(const std::string& name);
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual void purgeCallbacks() {}
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual void purgeCallbacks() {}
- private:
- std::string applicationName;
- QtCachedImageScaler imageScaler;
- };
+ private:
+ std::string applicationName;
+ QtCachedImageScaler imageScaler;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
index c5f4685..0163e03 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
@@ -25,63 +25,63 @@ MUCSearchDelegate::~MUCSearchDelegate() {
}
// QSize MUCSearchDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
-// // MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
-// // if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
-// // return mucSizeHint(option, index);
-// // } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
-// // return groupDelegate_->sizeHint(option, index);
-// // }
-// return QStyledItemDelegate::sizeHint(option, index);
+// // MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+// // if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
+// // return mucSizeHint(option, index);
+// // } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
+// // return groupDelegate_->sizeHint(option, index);
+// // }
+// return QStyledItemDelegate::sizeHint(option, index);
// }
// QSize MUCSearchDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
-// QFontMetrics nameMetrics(common_.nameFont);
-// QFontMetrics statusMetrics(common_.detailFont);
-// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
-// return QSize(150, sizeByText);
+// QFontMetrics nameMetrics(common_.nameFont);
+// QFontMetrics statusMetrics(common_.detailFont);
+// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+// return QSize(150, sizeByText);
// }
// void MUCSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
-// MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
-// if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
-// paintMUC(painter, option, dynamic_cast<MUCSearchMUCItem*>(item));
-// } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
-// MUCSearchGroupItem* group = dynamic_cast<MUCSearchGroupItem*>(item);
-// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
-// } else {
-// QStyledItemDelegate::paint(painter, option, index);
-// }
+// MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+// if (item && dynamic_cast<MUCSearchMUCItem*>(item)) {
+// paintMUC(painter, option, dynamic_cast<MUCSearchMUCItem*>(item));
+// } else if (item && dynamic_cast<MUCSearchGroupItem*>(item)) {
+// MUCSearchGroupItem* group = dynamic_cast<MUCSearchGroupItem*>(item);
+// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open);
+// } else {
+// QStyledItemDelegate::paint(painter, option, index);
+// }
// }
// void MUCSearchDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const {
-// painter->save();
-// QRect fullRegion(option.rect);
-// if ( option.state & QStyle::State_Selected ) {
-// painter->fillRect(fullRegion, option.palette.highlight());
-// painter->setPen(option.palette.highlightedText().color());
-// } else {
-// QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
-// painter->setPen(QPen(nameColor));
-// }
-
-// QFontMetrics nameMetrics(common_.nameFont);
-// painter->setFont(common_.nameFont);
-// int extraFontWidth = nameMetrics.width("H");
-// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
-// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
-// int nameHeight = nameMetrics.height() + common_.verticalMargin;
-// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
-// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString());
-
-// painter->setFont(common_.detailFont);
-// painter->setPen(QPen(QColor(160,160,160)));
-
-// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
-// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString());
-
-// painter->restore();
+// painter->save();
+// QRect fullRegion(option.rect);
+// if ( option.state & QStyle::State_Selected ) {
+// painter->fillRect(fullRegion, option.palette.highlight());
+// painter->setPen(option.palette.highlightedText().color());
+// } else {
+// QColor nameColor = item->data(Qt::TextColorRole).value<QColor>();
+// painter->setPen(QPen(nameColor));
+// }
+
+// QFontMetrics nameMetrics(common_.nameFont);
+// painter->setFont(common_.nameFont);
+// int extraFontWidth = nameMetrics.width("H");
+// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+// int nameHeight = nameMetrics.height() + common_.verticalMargin;
+// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString());
+
+// painter->setFont(common_.detailFont);
+// painter->setPen(QPen(QColor(160,160,160)));
+
+// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString());
+
+// painter->restore();
// }
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
index d521d7b..5bf9646 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
@@ -11,18 +11,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class MUCSearchDelegate : public QStyledItemDelegate {
- public:
- MUCSearchDelegate();
- ~MUCSearchDelegate();
- /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */
- /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */
- private:
-// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const;
-// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
+ class MUCSearchDelegate : public QStyledItemDelegate {
+ public:
+ MUCSearchDelegate();
+ ~MUCSearchDelegate();
+ /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */
+ /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */
+ private:
+// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const;
+// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const;
- DelegateCommons common_;
- };
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
index 5ab6391..d95682c 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
@@ -13,27 +13,27 @@
namespace Swift {
MUCSearchEmptyItem::MUCSearchEmptyItem(MUCSearchServiceItem* parent) : parent(parent) {
- parent->addRoom(this);
+ parent->addRoom(this);
}
MUCSearchServiceItem* MUCSearchEmptyItem::getParent() {
- return parent;
+ return parent;
}
QVariant MUCSearchEmptyItem::data(int role) {
- switch (role) {
- case Qt::DisplayRole:
- return QVariant(QObject::tr("No rooms found"));
- case Qt::FontRole: {
- QFont font;
- font.setItalic(true);
- return font;
- }
- case Qt::ForegroundRole:
- return QColor(Qt::gray);
- default:
- return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole:
+ return QVariant(QObject::tr("No rooms found"));
+ case Qt::FontRole: {
+ QFont font;
+ font.setItalic(true);
+ return font;
+ }
+ case Qt::ForegroundRole:
+ return QColor(Qt::gray);
+ default:
+ return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
index 74e0154..ca4b2b2 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
@@ -9,17 +9,17 @@
#include <Swift/QtUI/MUCSearch/MUCSearchItem.h>
namespace Swift {
- class MUCSearchServiceItem;
+ class MUCSearchServiceItem;
- class MUCSearchEmptyItem : public MUCSearchItem {
- public:
- MUCSearchEmptyItem(MUCSearchServiceItem* parent);
+ class MUCSearchEmptyItem : public MUCSearchItem {
+ public:
+ MUCSearchEmptyItem(MUCSearchServiceItem* parent);
- MUCSearchServiceItem* getParent();
+ MUCSearchServiceItem* getParent();
- QVariant data(int role);
+ QVariant data(int role);
- private:
- MUCSearchServiceItem* parent;
- };
+ private:
+ MUCSearchServiceItem* parent;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchItem.h b/Swift/QtUI/MUCSearch/MUCSearchItem.h
index d2a2c2d..c378247 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchItem.h
@@ -9,9 +9,9 @@
#include <QVariant>
namespace Swift {
- class MUCSearchItem {
- public:
- virtual ~MUCSearchItem() {}
- virtual QVariant data(int role) = 0;
- };
+ class MUCSearchItem {
+ public:
+ virtual ~MUCSearchItem() {}
+ virtual QVariant data(int role) = 0;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
index 1a3ccc4..af6f17f 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
@@ -14,78 +14,78 @@ MUCSearchModel::MUCSearchModel() {
}
void MUCSearchModel::clear() {
- emit layoutAboutToBeChanged();
- services_.clear();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ services_.clear();
+ emit layoutChanged();
}
void MUCSearchModel::addService(MUCSearchServiceItem* service) {
- emit layoutAboutToBeChanged();
- services_.push_back(service);
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ services_.push_back(service);
+ emit layoutChanged();
}
int MUCSearchModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
QVariant MUCSearchModel::data(const QModelIndex& index, int role) const {
- return index.isValid() ? static_cast<MUCSearchItem*>(index.internalPointer())->data(role) : QVariant();
+ return index.isValid() ? static_cast<MUCSearchItem*>(index.internalPointer())->data(role) : QVariant();
}
QModelIndex MUCSearchModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
-
- if (parent.isValid()) {
- MUCSearchServiceItem* parentItem = static_cast<MUCSearchServiceItem*>(parent.internalPointer());
- return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex();
- } else {
- return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
+
+ if (parent.isValid()) {
+ MUCSearchServiceItem* parentItem = static_cast<MUCSearchServiceItem*>(parent.internalPointer());
+ return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex();
+ } else {
+ return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex();
+ }
}
QModelIndex MUCSearchModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
- if (!item) {
- return QModelIndex();
- }
- else if (dynamic_cast<MUCSearchServiceItem*>(item)) {
- return QModelIndex();
- }
-
- MUCSearchServiceItem* parent = NULL;
- if (MUCSearchRoomItem* roomItem = dynamic_cast<MUCSearchRoomItem*>(item)) {
- parent = roomItem->getParent();
- }
- else if (MUCSearchEmptyItem* emptyItem = dynamic_cast<MUCSearchEmptyItem*>(item)) {
- parent = emptyItem->getParent();
- }
- if (parent) {
- int row = services_.indexOf(parent);
- return createIndex(row, 1, parent);
- }
- else {
- return QModelIndex();
- }
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ MUCSearchItem* item = static_cast<MUCSearchItem*>(index.internalPointer());
+ if (!item) {
+ return QModelIndex();
+ }
+ else if (dynamic_cast<MUCSearchServiceItem*>(item)) {
+ return QModelIndex();
+ }
+
+ MUCSearchServiceItem* parent = NULL;
+ if (MUCSearchRoomItem* roomItem = dynamic_cast<MUCSearchRoomItem*>(item)) {
+ parent = roomItem->getParent();
+ }
+ else if (MUCSearchEmptyItem* emptyItem = dynamic_cast<MUCSearchEmptyItem*>(item)) {
+ parent = emptyItem->getParent();
+ }
+ if (parent) {
+ int row = services_.indexOf(parent);
+ return createIndex(row, 1, parent);
+ }
+ else {
+ return QModelIndex();
+ }
}
int MUCSearchModel::rowCount(const QModelIndex& parentIndex) const {
- if (!parentIndex.isValid()) {
- return services_.size();
- }
- if (dynamic_cast<MUCSearchServiceItem*>(static_cast<MUCSearchItem*>(parentIndex.internalPointer()))) {
- return services_[parentIndex.row()]->rowCount();
- }
- else {
- return 0;
- }
+ if (!parentIndex.isValid()) {
+ return services_.size();
+ }
+ if (dynamic_cast<MUCSearchServiceItem*>(static_cast<MUCSearchItem*>(parentIndex.internalPointer()))) {
+ return services_[parentIndex.row()]->rowCount();
+ }
+ else {
+ return 0;
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.h b/Swift/QtUI/MUCSearch/MUCSearchModel.h
index 4ea811f..d6a24f3 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.h
@@ -14,22 +14,22 @@
#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
namespace Swift {
- class MUCSearchModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- MUCSearchModel();
- void clear();
- void addService(MUCSearchServiceItem* service);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
-// ChatListItem* getItemForIndex(const QModelIndex& index) const;
- private:
-// ChatListGroupItem* mucBookmarks_;
-// ChatListGroupItem* root_;
- QList<MUCSearchServiceItem*> services_;
- };
+ class MUCSearchModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ MUCSearchModel();
+ void clear();
+ void addService(MUCSearchServiceItem* service);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+// ChatListItem* getItemForIndex(const QModelIndex& index) const;
+ private:
+// ChatListGroupItem* mucBookmarks_;
+// ChatListGroupItem* root_;
+ QList<MUCSearchServiceItem*> services_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
index 169ab49..cb7ee2d 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
@@ -10,17 +10,17 @@
namespace Swift {
MUCSearchRoomItem::MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent) : parent_(parent), node_(node) {
- parent_->addRoom(this);
+ parent_->addRoom(this);
}
MUCSearchServiceItem* MUCSearchRoomItem::getParent() {
- return parent_;
+ return parent_;
}
QVariant MUCSearchRoomItem::data(int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(node_);
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(node_);
+ default: return QVariant();
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
index c853221..d2b88bc 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
@@ -9,15 +9,15 @@
#include <Swift/QtUI/MUCSearch/MUCSearchItem.h>
namespace Swift {
- class MUCSearchServiceItem;
- class MUCSearchRoomItem : public MUCSearchItem {
- public:
- MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent);
- MUCSearchServiceItem* getParent();
- QVariant data(int role);
- QString getNode() const {return node_;}
- private:
- MUCSearchServiceItem* parent_;
- QString node_;
- };
+ class MUCSearchServiceItem;
+ class MUCSearchRoomItem : public MUCSearchItem {
+ public:
+ MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent);
+ MUCSearchServiceItem* getParent();
+ QVariant data(int role);
+ QString getNode() const {return node_;}
+ private:
+ MUCSearchServiceItem* parent_;
+ QString node_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
index 421ac25..cfde071 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
@@ -12,21 +12,21 @@
#include <Swift/QtUI/MUCSearch/MUCSearchRoomItem.h>
namespace Swift {
- class MUCSearchServiceItem : public MUCSearchItem {
- public:
- MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {}
- void addRoom(MUCSearchItem* room) {rooms_.push_back(room);}
- int rowCount() {return rooms_.count();}
- MUCSearchItem* getItem(int i) {return rooms_[i];}
- QVariant data(int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(jidString_);
- default: return QVariant();
- }
- }
- QString getHost() const {return jidString_;}
- private:
- QList<MUCSearchItem*> rooms_;
- QString jidString_;
- };
+ class MUCSearchServiceItem : public MUCSearchItem {
+ public:
+ MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {}
+ void addRoom(MUCSearchItem* room) {rooms_.push_back(room);}
+ int rowCount() {return rooms_.count();}
+ MUCSearchItem* getItem(int i) {return rooms_[i];}
+ QVariant data(int role) {
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(jidString_);
+ default: return QVariant();
+ }
+ }
+ QString getHost() const {return jidString_;}
+ private:
+ QList<MUCSearchItem*> rooms_;
+ QString jidString_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
index e3bd7f3..03fa582 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
@@ -24,37 +24,37 @@
namespace Swift {
QtMUCSearchWindow::QtMUCSearchWindow() {
- ui_.setupUi(this);
+ ui_.setupUi(this);
#ifndef Q_OS_MAC
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
- setModal(true);
- ui_.filter_->hide();
- model_ = new MUCSearchModel();
- delegate_ = new MUCSearchDelegate();
- ui_.results_->setModel(model_);
- ui_.results_->setItemDelegate(delegate_);
- ui_.results_->setHeaderHidden(true);
- ui_.results_->setRootIsDecorated(true);
- ui_.results_->setAnimated(true);
- ui_.results_->setAlternatingRowColors(true);
- connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
- connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&)));
- connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&)));
- connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
- connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
- // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac)
- connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept()));
- ui_.okButton->setEnabled(false);
- connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
-
- throbber_ = new QLabel(tr("Searching"), ui_.results_);
- throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_));
- throbber_->setToolTip(tr("Searching"));
-
- hasHadScrollBars_ = false;
- updateThrobberPosition();
- setSearchInProgress(false);
+ setModal(true);
+ ui_.filter_->hide();
+ model_ = new MUCSearchModel();
+ delegate_ = new MUCSearchDelegate();
+ ui_.results_->setModel(model_);
+ ui_.results_->setItemDelegate(delegate_);
+ ui_.results_->setHeaderHidden(true);
+ ui_.results_->setRootIsDecorated(true);
+ ui_.results_->setAnimated(true);
+ ui_.results_->setAlternatingRowColors(true);
+ connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
+ connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&)));
+ connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&)));
+ connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
+ connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&)));
+ // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac)
+ connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept()));
+ ui_.okButton->setEnabled(false);
+ connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
+
+ throbber_ = new QLabel(tr("Searching"), ui_.results_);
+ throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_));
+ throbber_->setToolTip(tr("Searching"));
+
+ hasHadScrollBars_ = false;
+ updateThrobberPosition();
+ setSearchInProgress(false);
}
QtMUCSearchWindow::~QtMUCSearchWindow() {
@@ -62,136 +62,136 @@ QtMUCSearchWindow::~QtMUCSearchWindow() {
}
void QtMUCSearchWindow::resizeEvent(QResizeEvent* /*event*/) {
- updateThrobberPosition();
+ updateThrobberPosition();
}
void QtMUCSearchWindow::updateThrobberPosition() {
- bool isShown = throbber_->isVisible();
- int resultWidth = ui_.results_->width();
- int resultHeight = ui_.results_->height();
- //throbberWidth = throbber_->movie()->scaledSize().width();
- //throbberHeight = throbber_->movie()->scaledSize().height();
- int throbberWidth = 16; /* This is nasty, but the above doesn't work! */
- int throbberHeight = 16;
- /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size,
- * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated.
- * This seems an acceptable workaround.
- */
- hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible();
- int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2;
- int vMargin = 2; /* We don't get horizontal scrollbars */
- throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */
- throbber_->setVisible(isShown);
+ bool isShown = throbber_->isVisible();
+ int resultWidth = ui_.results_->width();
+ int resultHeight = ui_.results_->height();
+ //throbberWidth = throbber_->movie()->scaledSize().width();
+ //throbberHeight = throbber_->movie()->scaledSize().height();
+ int throbberWidth = 16; /* This is nasty, but the above doesn't work! */
+ int throbberHeight = 16;
+ /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size,
+ * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated.
+ * This seems an acceptable workaround.
+ */
+ hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible();
+ int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2;
+ int vMargin = 2; /* We don't get horizontal scrollbars */
+ throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */
+ throbber_->setVisible(isShown);
}
void QtMUCSearchWindow::addSavedServices(const std::list<JID>& services) {
- ui_.service_->clear();
- foreach (const JID& jid, services) {
- ui_.service_->addItem(P2QSTRING(jid.toString()));
- }
- if (!services.empty()) {
- ui_.service_->setEditText(P2QSTRING(services.begin()->toString()));
- }
- else {
- ui_.service_->clearEditText();
- }
+ ui_.service_->clear();
+ foreach (const JID& jid, services) {
+ ui_.service_->addItem(P2QSTRING(jid.toString()));
+ }
+ if (!services.empty()) {
+ ui_.service_->setEditText(P2QSTRING(services.begin()->toString()));
+ }
+ else {
+ ui_.service_->clearEditText();
+ }
}
void QtMUCSearchWindow::handleActivated(const QModelIndex& index) {
- if (!index.isValid()) {
- return;
- }
- if (dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(index.internalPointer()))) {
- accept();
- }
+ if (!index.isValid()) {
+ return;
+ }
+ if (dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(index.internalPointer()))) {
+ accept();
+ }
}
void QtMUCSearchWindow::handleSearch() {
- handleSearch(ui_.service_->currentText());
+ handleSearch(ui_.service_->currentText());
}
void QtMUCSearchWindow::handleSearch(const QString& service) {
- if (!service.isEmpty()) {
- onSearchService(JID(Q2PSTRING(service)));
- }
+ if (!service.isEmpty()) {
+ onSearchService(JID(Q2PSTRING(service)));
+ }
}
void QtMUCSearchWindow::show() {
- QWidget::show();
- QWidget::activateWindow();
+ QWidget::show();
+ QWidget::activateWindow();
}
void QtMUCSearchWindow::clearList() {
- model_->clear();
+ model_->clear();
}
void QtMUCSearchWindow::addService(const MUCService& service) {
- updateThrobberPosition();
- MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString()));
- if (service.getRooms().size() > 0) {
- foreach (MUCService::MUCRoom room, service.getRooms()) {
- new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem);
- }
- }
- else {
- new MUCSearchEmptyItem(serviceItem);
- }
- model_->addService(serviceItem);
- ui_.results_->expandAll();
+ updateThrobberPosition();
+ MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString()));
+ if (service.getRooms().size() > 0) {
+ foreach (MUCService::MUCRoom room, service.getRooms()) {
+ new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem);
+ }
+ }
+ else {
+ new MUCSearchEmptyItem(serviceItem);
+ }
+ model_->addService(serviceItem);
+ ui_.results_->expandAll();
}
void QtMUCSearchWindow::setSearchInProgress(bool searching) {
- if (searching) {
- throbber_->movie()->start();
- } else {
- throbber_->movie()->stop();
- }
- throbber_->setVisible(searching);
+ if (searching) {
+ throbber_->movie()->start();
+ } else {
+ throbber_->movie()->stop();
+ }
+ throbber_->setVisible(searching);
}
void QtMUCSearchWindow::accept() {
- MUCSearchRoomItem* room = getSelectedRoom();
- if (room) {
- onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost())));
- }
- else {
- onFinished(boost::optional<JID>());
- }
- QDialog::accept();
+ MUCSearchRoomItem* room = getSelectedRoom();
+ if (room) {
+ onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost())));
+ }
+ else {
+ onFinished(boost::optional<JID>());
+ }
+ QDialog::accept();
}
void QtMUCSearchWindow::reject() {
- onFinished(boost::optional<JID>());
- QDialog::reject();
+ onFinished(boost::optional<JID>());
+ QDialog::reject();
}
void QtMUCSearchWindow::handleSelectionChanged(const QItemSelection&, const QItemSelection&) {
- ui_.okButton->setEnabled(getSelectedRoom());
+ ui_.okButton->setEnabled(getSelectedRoom());
}
MUCSearchRoomItem* QtMUCSearchWindow::getSelectedRoom() const {
- // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
- // QModelIndexList destructor.
- // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
- // was resolved by linking against the debug libs, ours isn't, and we're not alone)
- QItemSelection ranges = ui_.results_->selectionModel()->selection();
- QModelIndexList lstIndex;
- for (int i = 0; i < ranges.count(); ++i) {
- QModelIndex parent = ranges.at(i).parent();
- int right = ranges.at(i).model()->columnCount(parent) - 1;
- if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
- for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
- lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
- }
- }
- }
- if (lstIndex.isEmpty()) {
- return NULL;
- }
- else {
- return dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(lstIndex.first().internalPointer()));
- }
+ // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
+ // QModelIndexList destructor.
+ // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
+ // was resolved by linking against the debug libs, ours isn't, and we're not alone)
+ QItemSelection ranges = ui_.results_->selectionModel()->selection();
+ QModelIndexList lstIndex;
+ for (int i = 0; i < ranges.count(); ++i) {
+ QModelIndex parent = ranges.at(i).parent();
+ int right = ranges.at(i).model()->columnCount(parent) - 1;
+ if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
+ for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
+ lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
+ }
+ }
+ }
+ if (lstIndex.isEmpty()) {
+ return NULL;
+ }
+ else {
+ return dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(lstIndex.first().internalPointer()));
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
index 4ac845a..b115e6f 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
@@ -11,41 +11,41 @@
#include <Swift/QtUI/MUCSearch/ui_QtMUCSearchWindow.h>
namespace Swift {
- class MUCSearchModel;
- class MUCSearchDelegate;
- class MUCSearchRoomItem;
-
- class QtMUCSearchWindow : public QDialog, public MUCSearchWindow {
- Q_OBJECT
- public:
- QtMUCSearchWindow();
- virtual ~QtMUCSearchWindow();
-
- virtual void clearList();
- virtual void addService(const MUCService& service);
- virtual void addSavedServices(const std::list<JID>& services);
- virtual void setSearchInProgress(bool searching);
-
- virtual void show();
- virtual void accept();
- virtual void reject();
-
- protected:
- virtual void resizeEvent(QResizeEvent* event);
-
- private slots:
- void handleSearch();
- void handleSearch(const QString&);
- void handleActivated(const QModelIndex& index);
- void updateThrobberPosition();
- void handleSelectionChanged (const QItemSelection&, const QItemSelection&);
- MUCSearchRoomItem* getSelectedRoom() const;
-
- private:
- Ui::QtMUCSearchWindow ui_;
- MUCSearchModel* model_;
- MUCSearchDelegate* delegate_;
- QLabel* throbber_;
- bool hasHadScrollBars_;
- };
+ class MUCSearchModel;
+ class MUCSearchDelegate;
+ class MUCSearchRoomItem;
+
+ class QtMUCSearchWindow : public QDialog, public MUCSearchWindow {
+ Q_OBJECT
+ public:
+ QtMUCSearchWindow();
+ virtual ~QtMUCSearchWindow();
+
+ virtual void clearList();
+ virtual void addService(const MUCService& service);
+ virtual void addSavedServices(const std::list<JID>& services);
+ virtual void setSearchInProgress(bool searching);
+
+ virtual void show();
+ virtual void accept();
+ virtual void reject();
+
+ protected:
+ virtual void resizeEvent(QResizeEvent* event);
+
+ private slots:
+ void handleSearch();
+ void handleSearch(const QString&);
+ void handleActivated(const QModelIndex& index);
+ void updateThrobberPosition();
+ void handleSelectionChanged (const QItemSelection&, const QItemSelection&);
+ MUCSearchRoomItem* getSelectedRoom() const;
+
+ private:
+ Ui::QtMUCSearchWindow ui_;
+ MUCSearchModel* model_;
+ MUCSearchDelegate* delegate_;
+ QLabel* throbber_;
+ bool hasHadScrollBars_;
+ };
}
diff --git a/Swift/QtUI/MessageSnippet.cpp b/Swift/QtUI/MessageSnippet.cpp
index c2969cf..85cbdb9 100644
--- a/Swift/QtUI/MessageSnippet.cpp
+++ b/Swift/QtUI/MessageSnippet.cpp
@@ -11,33 +11,33 @@
namespace Swift {
MessageSnippet::MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction) : ChatSnippet(appendToPrevious) {
- if (appendToPrevious) {
- setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction)));
- }
- if (isIncoming) {
- if (appendToPrevious) {
- content_ = theme->getIncomingNextContent();
- }
- else {
- content_ = theme->getIncomingContent();
- }
- }
- else {
- if (appendToPrevious) {
- content_ = theme->getOutgoingNextContent();
- }
- else {
- content_ = theme->getOutgoingContent();
- }
- }
-
- content_.replace("%direction%", directionToCSS(direction));
- content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
- content_.replace("%wrapped_sender%", wrapResizable(escape(sender)));
- content_.replace("%sender%", escape(sender));
- content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
- content_.replace("%userIconPath%", escape(iconURI));
- content_.replace("%id%", id);
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction)));
+ }
+ if (isIncoming) {
+ if (appendToPrevious) {
+ content_ = theme->getIncomingNextContent();
+ }
+ else {
+ content_ = theme->getIncomingContent();
+ }
+ }
+ else {
+ if (appendToPrevious) {
+ content_ = theme->getOutgoingNextContent();
+ }
+ else {
+ content_ = theme->getOutgoingContent();
+ }
+ }
+
+ content_.replace("%direction%", directionToCSS(direction));
+ content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
+ content_.replace("%wrapped_sender%", wrapResizable(escape(sender)));
+ content_.replace("%sender%", escape(sender));
+ content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
+ content_.replace("%userIconPath%", escape(iconURI));
+ content_.replace("%id%", id);
}
MessageSnippet::~MessageSnippet() {
diff --git a/Swift/QtUI/MessageSnippet.h b/Swift/QtUI/MessageSnippet.h
index e6972a1..302785f 100644
--- a/Swift/QtUI/MessageSnippet.h
+++ b/Swift/QtUI/MessageSnippet.h
@@ -13,19 +13,19 @@
class QDateTime;
namespace Swift {
- class MessageSnippet : public ChatSnippet {
- public:
- MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
- virtual ~MessageSnippet();
- const QString& getContent() const {
- return content_;
- }
+ class MessageSnippet : public ChatSnippet {
+ public:
+ MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
+ virtual ~MessageSnippet();
+ const QString& getContent() const {
+ return content_;
+ }
- QString getContinuationElementID() const {
- return "insert";
- }
+ QString getContinuationElementID() const {
+ return "insert";
+ }
- private:
- QString content_;
- };
+ private:
+ QString content_;
+ };
}
diff --git a/Swift/QtUI/NotifierTest/NotifierTest.cpp b/Swift/QtUI/NotifierTest/NotifierTest.cpp
index 56f7985..8d2e467 100644
--- a/Swift/QtUI/NotifierTest/NotifierTest.cpp
+++ b/Swift/QtUI/NotifierTest/NotifierTest.cpp
@@ -17,12 +17,12 @@
using namespace Swift;
void notificationClicked(const std::string& message) {
- std::cout << "Notification clicked: " << message << std::endl;
+ std::cout << "Notification clicked: " << message << std::endl;
}
int main(int argc, char* argv[]) {
- QApplication app(argc, argv);
- GrowlNotifier notifier("Swift-NotifierTest");
- notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(&notificationClicked, "Message 1"));
- return app.exec();
+ QApplication app(argc, argv);
+ GrowlNotifier notifier("Swift-NotifierTest");
+ notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(&notificationClicked, "Message 1"));
+ return app.exec();
}
diff --git a/Swift/QtUI/QtAboutWidget.cpp b/Swift/QtUI/QtAboutWidget.cpp
index 9fb07ed..b69113f 100644
--- a/Swift/QtUI/QtAboutWidget.cpp
+++ b/Swift/QtUI/QtAboutWidget.cpp
@@ -22,67 +22,67 @@ namespace Swift {
QtAboutWidget::QtAboutWidget() : QDialog() {
#ifndef Q_OS_MAC
- setWindowTitle(QString(tr("About %1")).arg("Swift"));
+ setWindowTitle(QString(tr("About %1")).arg("Swift"));
#endif
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
- resize(180, 240);
- QVBoxLayout *mainLayout = new QVBoxLayout(this);
- mainLayout->setAlignment(Qt::AlignHCenter);
- setLayout(mainLayout);
-
- QLabel* iconLabel = new QLabel(this);
- iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90));
- iconLabel->setAlignment(Qt::AlignHCenter);
- mainLayout->addWidget(iconLabel);
-
- QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
- mainLayout->addWidget(appNameLabel);
-
- QLabel* versionLabel = new QLabel((QString("<center><font size='-1'>") + tr("Version %1") + "</font></center><center><font size='-1'><br/>" + QString(tr("Built with Qt %2")) + QString("<br/>") + QString(tr("Running with Qt %3")) + "</font></center>").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion()));
- versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- mainLayout->addWidget(versionLabel);
+ resize(180, 240);
+ QVBoxLayout *mainLayout = new QVBoxLayout(this);
+ mainLayout->setAlignment(Qt::AlignHCenter);
+ setLayout(mainLayout);
- if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") {
- mainLayout->addWidget(new QLabel(QString("<center><font size='-1'>") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "<br/>") + "</font></center>", this));
- }
- QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'");
+ QLabel* iconLabel = new QLabel(this);
+ iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90));
+ iconLabel->setAlignment(Qt::AlignHCenter);
+ mainLayout->addWidget(iconLabel);
+
+ QLabel* appNameLabel = new QLabel("<center><font size='+1'><b>" + QCoreApplication::applicationName() + "</b></font></center>", this);
+ mainLayout->addWidget(appNameLabel);
+
+ QLabel* versionLabel = new QLabel((QString("<center><font size='-1'>") + tr("Version %1") + "</font></center><center><font size='-1'><br/>" + QString(tr("Built with Qt %2")) + QString("<br/>") + QString(tr("Running with Qt %3")) + "</font></center>").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion()));
+ versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ mainLayout->addWidget(versionLabel);
+
+ if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") {
+ mainLayout->addWidget(new QLabel(QString("<center><font size='-1'>") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "<br/>") + "</font></center>", this));
+ }
+ QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'");
#if defined(SWIFTEN_PLATFORM_WINDOWS) || defined(SWIFTEN_PLATFORM_MACOSX)
- QPushButton* licenseButton = new QPushButton(tr("View License"), this);
- mainLayout->addWidget(licenseButton);
- connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
+ QPushButton* licenseButton = new QPushButton(tr("View License"), this);
+ mainLayout->addWidget(licenseButton);
+ connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
#else
- // Some Linux desktops have dialog window decorations without close window buttons.
- // This code adds a dedicated button to close the about window dialog.
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- mainLayout->addLayout(buttonLayout);
+ // Some Linux desktops have dialog window decorations without close window buttons.
+ // This code adds a dedicated button to close the about window dialog.
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ mainLayout->addLayout(buttonLayout);
- QPushButton* licenseButton = new QPushButton(tr("View License"), this);
- buttonLayout->addWidget(licenseButton);
- connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
+ QPushButton* licenseButton = new QPushButton(tr("View License"), this);
+ buttonLayout->addWidget(licenseButton);
+ connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked()));
- buttonLayout->addItem(new QSpacerItem(20,20));
+ buttonLayout->addItem(new QSpacerItem(20,20));
- QPushButton* closeButton = new QPushButton(tr("Close"), this);
- buttonLayout->addWidget(closeButton);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
+ QPushButton* closeButton = new QPushButton(tr("Close"), this);
+ buttonLayout->addWidget(closeButton);
+ connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
#endif
- setFixedSize(minimumSizeHint());
+ setFixedSize(minimumSizeHint());
}
void QtAboutWidget::handleLicenseClicked() {
- QTextEdit* text = new QTextEdit();
- text->setAttribute(Qt::WA_DeleteOnClose);
- text->setReadOnly(true);
- QFile file(":/COPYING");
- file.open(QIODevice::ReadOnly);
- QTextStream in(&file);
- in.setCodec("UTF-8");
- text->setPlainText(in.readAll());
- file.close();
- text->resize(500, 600);
- text->show();
- text->activateWindow();
+ QTextEdit* text = new QTextEdit();
+ text->setAttribute(Qt::WA_DeleteOnClose);
+ text->setReadOnly(true);
+ QFile file(":/COPYING");
+ file.open(QIODevice::ReadOnly);
+ QTextStream in(&file);
+ in.setCodec("UTF-8");
+ text->setPlainText(in.readAll());
+ file.close();
+ text->resize(500, 600);
+ text->show();
+ text->activateWindow();
}
}
diff --git a/Swift/QtUI/QtAboutWidget.h b/Swift/QtUI/QtAboutWidget.h
index d09010b..7d0d628 100644
--- a/Swift/QtUI/QtAboutWidget.h
+++ b/Swift/QtUI/QtAboutWidget.h
@@ -9,13 +9,13 @@
#include <QDialog>
namespace Swift {
- class QtAboutWidget : public QDialog {
- Q_OBJECT
+ class QtAboutWidget : public QDialog {
+ Q_OBJECT
- public:
- QtAboutWidget();
+ public:
+ QtAboutWidget();
- private slots:
- void handleLicenseClicked();
- };
+ private slots:
+ void handleLicenseClicked();
+ };
}
diff --git a/Swift/QtUI/QtAdHocCommandWindow.cpp b/Swift/QtUI/QtAdHocCommandWindow.cpp
index ef397f4..87b1585 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWindow.cpp
@@ -20,155 +20,155 @@ const int FormLayoutIndex = 1;
namespace Swift {
QtAdHocCommandWindow::QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) : command_(command) {
- formWidget_ = NULL;
-
- setAttribute(Qt::WA_DeleteOnClose);
- command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1));
- command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1));
- command->start();
-
- layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout_->setContentsMargins(0,0,0,0);
- layout_->setSpacing(2);
- label_ = new QLabel(this);
- label_->setTextFormat(Qt::PlainText);
- layout_->addWidget(label_);
-
- errorLabel_ = new QLabel(this);
- errorLabel_->setText(QString("<b>%1</b>").arg(tr("Unable to complete the command because you have been disconnected")));
- errorLabel_->setVisible(false);
- errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken);
- layout_->addWidget(errorLabel_);
-
- dialogButtons_ = new QDialogButtonBox(this);
- layout_->addWidget(dialogButtons_);
-
- dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
- okButton_ = dialogButtons_->button(QDialogButtonBox::Ok);
- connect(okButton_, SIGNAL(clicked()), this, SLOT(close()));
- cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel);
- connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
- // Buttons appear next to the Ok button, right of Cancel with YesRole
- completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole);
- connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked()));
- nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole);
- connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked()));
- backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole);
- connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked()));
-
- okButton_->setEnabled(false);
- okButton_->hide();
-
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
-
- actions_[Command::Next] = nextButton_;
- actions_[Command::Prev] = backButton_;
- actions_[Command::Complete] = completeButton_;
- actions_[Command::Cancel] = cancelButton_;
+ formWidget_ = NULL;
+
+ setAttribute(Qt::WA_DeleteOnClose);
+ command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1));
+ command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1));
+ command->start();
+
+ layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout_->setContentsMargins(0,0,0,0);
+ layout_->setSpacing(2);
+ label_ = new QLabel(this);
+ label_->setTextFormat(Qt::PlainText);
+ layout_->addWidget(label_);
+
+ errorLabel_ = new QLabel(this);
+ errorLabel_->setText(QString("<b>%1</b>").arg(tr("Unable to complete the command because you have been disconnected")));
+ errorLabel_->setVisible(false);
+ errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken);
+ layout_->addWidget(errorLabel_);
+
+ dialogButtons_ = new QDialogButtonBox(this);
+ layout_->addWidget(dialogButtons_);
+
+ dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
+ okButton_ = dialogButtons_->button(QDialogButtonBox::Ok);
+ connect(okButton_, SIGNAL(clicked()), this, SLOT(close()));
+ cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel);
+ connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
+ // Buttons appear next to the Ok button, right of Cancel with YesRole
+ completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole);
+ connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked()));
+ nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole);
+ connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked()));
+ backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole);
+ connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked()));
+
+ okButton_->setEnabled(false);
+ okButton_->hide();
+
+ nextButton_->setEnabled(false);
+ backButton_->setEnabled(false);
+ completeButton_->setEnabled(false);
+
+ actions_[Command::Next] = nextButton_;
+ actions_[Command::Prev] = backButton_;
+ actions_[Command::Complete] = completeButton_;
+ actions_[Command::Cancel] = cancelButton_;
}
QtAdHocCommandWindow::~QtAdHocCommandWindow() {
}
void QtAdHocCommandWindow::setOnline(bool online) {
- if (!online) {
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
- errorLabel_->setVisible(true);
- }
+ if (!online) {
+ nextButton_->setEnabled(false);
+ backButton_->setEnabled(false);
+ completeButton_->setEnabled(false);
+ errorLabel_->setVisible(true);
+ }
}
void QtAdHocCommandWindow::closeEvent(QCloseEvent*) {
- onClosing();
+ onClosing();
}
void QtAdHocCommandWindow::handleCancelClicked() {
- command_->cancel();
- close();
+ command_->cancel();
+ close();
}
void QtAdHocCommandWindow::handlePrevClicked() {
- command_->goBack();
+ command_->goBack();
}
void QtAdHocCommandWindow::handleNextClicked() {
- command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
+ command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleCompleteClicked() {
- command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
+ command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref());
}
void QtAdHocCommandWindow::handleNextStageReceived(Command::ref command) {
- QString notes;
- foreach (Command::Note 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);
+ QString notes;
+ foreach (Command::Note 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"));
+ 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();
+ form_ = form;
+ delete formWidget_;
+ formWidget_ = new QtFormWidget(form, this);
+ layout_->insertWidget(FormLayoutIndex, formWidget_);
+ show();
}
void QtAdHocCommandWindow::setNoForm(bool andHide) {
- form_.reset();
- delete formWidget_;
- formWidget_ = NULL;
- resize(minimumSize());
- setVisible(!andHide);
+ form_.reset();
+ delete formWidget_;
+ formWidget_ = NULL;
+ 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_) {
- 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);
- }
- }
+ okButton_->show();
+ okButton_->setEnabled(true);
+ foreach (ActionButton 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/QtAdHocCommandWindow.h b/Swift/QtUI/QtAdHocCommandWindow.h
index c8d493c..61cd5be 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.h
+++ b/Swift/QtUI/QtAdHocCommandWindow.h
@@ -18,41 +18,41 @@
class QBoxLayout;
namespace Swift {
- class QtFormWidget;
- class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow {
- Q_OBJECT
- public:
- QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
- virtual ~QtAdHocCommandWindow();
- virtual void setOnline(bool online);
-
- private:
- void closeEvent(QCloseEvent* event);
- void handleNextStageReceived(Command::ref command);
- void handleError(ErrorPayload::ref error);
- void setForm(Form::ref);
- void setNoForm(bool andHide);
- void setAvailableActions(Command::ref commandResult);
-
- private slots:
- void handleCancelClicked();
- void handlePrevClicked();
- void handleNextClicked();
- void handleCompleteClicked();
-
- private:
- boost::shared_ptr<OutgoingAdHocCommandSession> command_;
- QtFormWidget* formWidget_;
- Form::ref form_;
- QLabel* label_;
- QLabel* errorLabel_;
- QPushButton* backButton_;
- QPushButton* nextButton_;
- QPushButton* completeButton_;
- QPushButton* cancelButton_;
- QPushButton* okButton_;
- std::map<Command::Action, QPushButton*> actions_;
- QDialogButtonBox* dialogButtons_;
- QBoxLayout* layout_;
- };
+ class QtFormWidget;
+ class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow {
+ Q_OBJECT
+ public:
+ QtAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
+ virtual ~QtAdHocCommandWindow();
+ virtual void setOnline(bool online);
+
+ private:
+ void closeEvent(QCloseEvent* event);
+ void handleNextStageReceived(Command::ref command);
+ void handleError(ErrorPayload::ref error);
+ void setForm(Form::ref);
+ void setNoForm(bool andHide);
+ void setAvailableActions(Command::ref commandResult);
+
+ private slots:
+ void handleCancelClicked();
+ void handlePrevClicked();
+ void handleNextClicked();
+ void handleCompleteClicked();
+
+ private:
+ boost::shared_ptr<OutgoingAdHocCommandSession> command_;
+ QtFormWidget* formWidget_;
+ Form::ref form_;
+ QLabel* label_;
+ QLabel* errorLabel_;
+ QPushButton* backButton_;
+ QPushButton* nextButton_;
+ QPushButton* completeButton_;
+ QPushButton* cancelButton_;
+ QPushButton* okButton_;
+ std::map<Command::Action, QPushButton*> actions_;
+ QDialogButtonBox* dialogButtons_;
+ QBoxLayout* layout_;
+ };
}
diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
index ac2a603..69e1d68 100644
--- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
@@ -23,42 +23,42 @@
namespace Swift {
QtAdHocCommandWithJIDWindow::QtAdHocCommandWithJIDWindow(UIEventStream* uiEventStream) : uiEventStream_(uiEventStream) {
- QVBoxLayout* hlayout = new QVBoxLayout(this);
+ QVBoxLayout* hlayout = new QVBoxLayout(this);
- QLabel* jidLabel = new QLabel("JID:", this);
- hlayout->addWidget(jidLabel);
- jid_ = new QLineEdit(this);
- hlayout->addWidget(jid_);
+ QLabel* jidLabel = new QLabel("JID:", this);
+ hlayout->addWidget(jidLabel);
+ jid_ = new QLineEdit(this);
+ hlayout->addWidget(jid_);
- QLabel* commandLabel = new QLabel("Command:", this);
- hlayout->addWidget(commandLabel);
- node_ = new QLineEdit(this);
- hlayout->addWidget(node_);
+ QLabel* commandLabel = new QLabel("Command:", this);
+ hlayout->addWidget(commandLabel);
+ node_ = new QLineEdit(this);
+ hlayout->addWidget(node_);
- QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
- QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole);
- connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick()));
- QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole);
- connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick()));
- hlayout->addWidget(buttonBox);
+ QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
+ QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole);
+ connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick()));
+ QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole);
+ connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick()));
+ hlayout->addWidget(buttonBox);
- setLayout(hlayout);
- show();
+ setLayout(hlayout);
+ show();
}
QtAdHocCommandWithJIDWindow::~QtAdHocCommandWithJIDWindow() {
}
void QtAdHocCommandWithJIDWindow::handleAcceptClick() {
- const JID jid = JID(Q2PSTRING(jid_->text()));
- const std::string node = Q2PSTRING(node_->text());
- boost::shared_ptr<UIEvent> event(new RequestAdHocWithJIDUIEvent(jid, node));
- uiEventStream_->send(event);
- accept();
+ const JID jid = JID(Q2PSTRING(jid_->text()));
+ const std::string node = Q2PSTRING(node_->text());
+ boost::shared_ptr<UIEvent> event(new RequestAdHocWithJIDUIEvent(jid, node));
+ uiEventStream_->send(event);
+ accept();
}
void QtAdHocCommandWithJIDWindow::handleRejectClick() {
- reject();
+ reject();
}
}
diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
index e1f7a9c..0e83555 100644
--- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
+++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h
@@ -14,19 +14,19 @@
class QBoxLayout;
namespace Swift {
- class UIEventStream;
- class QtFormWidget;
- class QtAdHocCommandWithJIDWindow : public QDialog {
- Q_OBJECT
- public:
- QtAdHocCommandWithJIDWindow(UIEventStream* eventStream);
- virtual ~QtAdHocCommandWithJIDWindow();
- public slots:
- void handleAcceptClick();
- void handleRejectClick();
- private:
- UIEventStream* uiEventStream_;
- QLineEdit* jid_;
- QLineEdit* node_;
- };
+ class UIEventStream;
+ class QtFormWidget;
+ class QtAdHocCommandWithJIDWindow : public QDialog {
+ Q_OBJECT
+ public:
+ QtAdHocCommandWithJIDWindow(UIEventStream* eventStream);
+ virtual ~QtAdHocCommandWithJIDWindow();
+ public slots:
+ void handleAcceptClick();
+ void handleRejectClick();
+ private:
+ UIEventStream* uiEventStream_;
+ QLineEdit* jid_;
+ QLineEdit* node_;
+ };
}
diff --git a/Swift/QtUI/QtAddBookmarkWindow.cpp b/Swift/QtUI/QtAddBookmarkWindow.cpp
index 087628d..500b298 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.cpp
+++ b/Swift/QtUI/QtAddBookmarkWindow.cpp
@@ -8,23 +8,23 @@
namespace Swift {
QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream) : eventStream_(eventStream) {
- setWindowTitle(tr("Add Bookmark Details"));
+ setWindowTitle(tr("Add Bookmark Details"));
}
QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream) {
- createFormFromBookmark(bookmark);
- setWindowTitle(tr("Add Bookmark Details"));
+ createFormFromBookmark(bookmark);
+ setWindowTitle(tr("Add Bookmark Details"));
}
bool QtAddBookmarkWindow::commit() {
- boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
- if (bookmark) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(*bookmark)));
- return true;
- }
- else {
- return false;
- }
+ boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
+ if (bookmark) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new AddMUCBookmarkUIEvent(*bookmark)));
+ return true;
+ }
+ else {
+ return false;
+ }
}
}
diff --git a/Swift/QtUI/QtAddBookmarkWindow.h b/Swift/QtUI/QtAddBookmarkWindow.h
index 7b08b8e..607f647 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.h
+++ b/Swift/QtUI/QtAddBookmarkWindow.h
@@ -12,13 +12,13 @@
#include <Swift/QtUI/QtBookmarkDetailWindow.h>
namespace Swift {
- class QtAddBookmarkWindow : public QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtAddBookmarkWindow(UIEventStream* eventStream);
- QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
- bool commit();
- private:
- UIEventStream* eventStream_;
- };
+ class QtAddBookmarkWindow : public QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtAddBookmarkWindow(UIEventStream* eventStream);
+ QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
+ bool commit();
+ private:
+ UIEventStream* eventStream_;
+ };
}
diff --git a/Swift/QtUI/QtAffiliationEditor.cpp b/Swift/QtUI/QtAffiliationEditor.cpp
index d732c4e..980b26a 100644
--- a/Swift/QtUI/QtAffiliationEditor.cpp
+++ b/Swift/QtUI/QtAffiliationEditor.cpp
@@ -13,66 +13,66 @@
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()));
+ 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());
- }
+ 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_;
+ return changes_;
}
void QtAffiliationEditor::handleCurrentIndexChanged(int index) {
- ui_.list->clear();
- foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) {
- ui_.list->addItem(P2QSTRING(jid.toString()));
- }
+ ui_.list->clear();
+ foreach (const JID& 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);
- }
+ 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());
- }
+ 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;
- case 1: return MUCOccupant::Admin;
- case 2: return MUCOccupant::Member;
- case 3: return MUCOccupant::Outcast;
- default: return MUCOccupant::Outcast;
- }
+ switch (affiliation) {
+ case 0: return MUCOccupant::Owner;
+ case 1: return MUCOccupant::Admin;
+ case 2: return MUCOccupant::Member;
+ case 3: return MUCOccupant::Outcast;
+ default: return MUCOccupant::Outcast;
+ }
}
}
diff --git a/Swift/QtUI/QtAffiliationEditor.h b/Swift/QtUI/QtAffiliationEditor.h
index d706926..3b7e548 100644
--- a/Swift/QtUI/QtAffiliationEditor.h
+++ b/Swift/QtUI/QtAffiliationEditor.h
@@ -17,22 +17,22 @@
#include <Swift/QtUI/ui_QtAffiliationEditor.h>
namespace Swift {
- class QtAffiliationEditor : public QDialog {
- Q_OBJECT
- public:
- QtAffiliationEditor(QWidget* parent = NULL);
- ~QtAffiliationEditor();
- void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>& jids);
- const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& getChanges() const;
- private slots:
- void handleCurrentIndexChanged(int);
- void handleAddClicked();
- void handleRemoveClicked();
- private:
- typedef std::pair<MUCOccupant::Affiliation, JID> ChangePair;
- MUCOccupant::Affiliation affiliationFromIndex(int affiliation);
- Ui::QtAffiliationEditor ui_;
- std::map<MUCOccupant::Affiliation, std::vector<JID> > affiliations_;
- std::vector<ChangePair> changes_;
- };
+ class QtAffiliationEditor : public QDialog {
+ Q_OBJECT
+ public:
+ QtAffiliationEditor(QWidget* parent = NULL);
+ ~QtAffiliationEditor();
+ void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>& jids);
+ const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& getChanges() const;
+ private slots:
+ void handleCurrentIndexChanged(int);
+ void handleAddClicked();
+ void handleRemoveClicked();
+ private:
+ typedef std::pair<MUCOccupant::Affiliation, JID> ChangePair;
+ MUCOccupant::Affiliation affiliationFromIndex(int affiliation);
+ Ui::QtAffiliationEditor ui_;
+ std::map<MUCOccupant::Affiliation, std::vector<JID> > affiliations_;
+ std::vector<ChangePair> changes_;
+ };
}
diff --git a/Swift/QtUI/QtAvatarWidget.cpp b/Swift/QtUI/QtAvatarWidget.cpp
index 2474e80..7f6e275 100644
--- a/Swift/QtUI/QtAvatarWidget.cpp
+++ b/Swift/QtUI/QtAvatarWidget.cpp
@@ -27,85 +27,85 @@
namespace Swift {
QtAvatarWidget::QtAvatarWidget(QWidget* parent) : QWidget(parent), editable(false) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setContentsMargins(0,0,0,0);
-
- QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed);
- sp.setHorizontalStretch(0);
- sp.setVerticalStretch(0);
- setSizePolicy(sp);
- setMinimumSize(QSize(96, 96));
- setMaximumSize(QSize(96, 96));
-
- label = new QLabel(this);
- label->setWordWrap(true);
- label->setSizePolicy(sp);
- label->setMinimumSize(QSize(96, 96));
- label->setMaximumSize(QSize(96, 96));
- label->setAlignment(Qt::AlignCenter);
- layout->addWidget(label);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setContentsMargins(0,0,0,0);
+
+ QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ sp.setHorizontalStretch(0);
+ sp.setVerticalStretch(0);
+ setSizePolicy(sp);
+ setMinimumSize(QSize(96, 96));
+ setMaximumSize(QSize(96, 96));
+
+ label = new QLabel(this);
+ label->setWordWrap(true);
+ label->setSizePolicy(sp);
+ label->setMinimumSize(QSize(96, 96));
+ label->setMaximumSize(QSize(96, 96));
+ label->setAlignment(Qt::AlignCenter);
+ layout->addWidget(label);
}
void QtAvatarWidget::setAvatar(const ByteArray& data, const std::string& type) {
- this->data = data;
- this->type = type;
-
- QImage image;
- if (!data.empty()) {
- image.loadFromData(reinterpret_cast<const uchar*>(vecptr(data)), data.size());
- }
-
- if (image.isNull()) {
- image = QImage(":/icons/no-avatar.png");
- QPainter painter(&image);
- painter.setPen(Qt::gray);
- QFont font = painter.font();
- font.setPointSize(14);
- painter.setFont(font);
- painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture"));
- }
-
- if (image.height() > label->height() || image.width() > label->width()) {
- image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- label->setPixmap(QPixmap::fromImage(image));
+ this->data = data;
+ this->type = type;
+
+ QImage image;
+ if (!data.empty()) {
+ image.loadFromData(reinterpret_cast<const uchar*>(vecptr(data)), data.size());
+ }
+
+ if (image.isNull()) {
+ image = QImage(":/icons/no-avatar.png");
+ QPainter painter(&image);
+ painter.setPen(Qt::gray);
+ QFont font = painter.font();
+ font.setPointSize(14);
+ painter.setFont(font);
+ painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture"));
+ }
+
+ if (image.height() > label->height() || image.width() > label->width()) {
+ image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ label->setPixmap(QPixmap::fromImage(image));
}
void QtAvatarWidget::mousePressEvent(QMouseEvent* event) {
- if (!editable) {
- return;
- }
- QMenu menu;
-
- QAction* selectPicture = new QAction(tr("Select picture ..."), this);
- menu.addAction(selectPicture);
-
- QAction* clearPicture = new QAction(tr("Clear picture"), this);
- menu.addAction(clearPicture);
-
- QAction* result = menu.exec(event->globalPos());
- if (result == selectPicture) {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)"));
- if (!fileName.isEmpty()) {
- ByteArray data;
- readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName)));
-
- QBuffer buffer;
- buffer.setData(reinterpret_cast<const char*>(vecptr(data)), data.size());
- buffer.open(QIODevice::ReadOnly);
- QString type = QImageReader::imageFormat(&buffer).toLower();
- if (!type.isEmpty()) {
- type = "image/" + type;
- setAvatar(data, Q2PSTRING(type));
- }
- else {
- QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format"));
- }
- }
- }
- else if (result == clearPicture) {
- setAvatar(ByteArray(), "");
- }
+ if (!editable) {
+ return;
+ }
+ QMenu menu;
+
+ QAction* selectPicture = new QAction(tr("Select picture ..."), this);
+ menu.addAction(selectPicture);
+
+ QAction* clearPicture = new QAction(tr("Clear picture"), this);
+ menu.addAction(clearPicture);
+
+ QAction* result = menu.exec(event->globalPos());
+ if (result == selectPicture) {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)"));
+ if (!fileName.isEmpty()) {
+ ByteArray data;
+ readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName)));
+
+ QBuffer buffer;
+ buffer.setData(reinterpret_cast<const char*>(vecptr(data)), data.size());
+ buffer.open(QIODevice::ReadOnly);
+ QString type = QImageReader::imageFormat(&buffer).toLower();
+ if (!type.isEmpty()) {
+ type = "image/" + type;
+ setAvatar(data, Q2PSTRING(type));
+ }
+ else {
+ QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format"));
+ }
+ }
+ }
+ else if (result == clearPicture) {
+ setAvatar(ByteArray(), "");
+ }
}
diff --git a/Swift/QtUI/QtAvatarWidget.h b/Swift/QtUI/QtAvatarWidget.h
index bcdc7be..612c79b 100644
--- a/Swift/QtUI/QtAvatarWidget.h
+++ b/Swift/QtUI/QtAvatarWidget.h
@@ -14,36 +14,36 @@
class QLabel;
namespace Swift {
- class QtAvatarWidget : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- QtAvatarWidget(QWidget* parent);
-
- void setAvatar(const ByteArray& data, const std::string& type);
-
- const ByteArray& getAvatarData() const {
- return data;
- }
-
- const std::string& getAvatarType() const {
- return type;
- }
-
- void setEditable(bool b) {
- editable = b;
- }
-
- bool isEditable() const {
- return editable;
- }
-
- void mousePressEvent(QMouseEvent* event);
-
- private:
- bool editable;
- ByteArray data;
- std::string type;
- QLabel* label;
- };
+ class QtAvatarWidget : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ public:
+ QtAvatarWidget(QWidget* parent);
+
+ void setAvatar(const ByteArray& data, const std::string& type);
+
+ const ByteArray& getAvatarData() const {
+ return data;
+ }
+
+ const std::string& getAvatarType() const {
+ return type;
+ }
+
+ void setEditable(bool b) {
+ editable = b;
+ }
+
+ bool isEditable() const {
+ return editable;
+ }
+
+ void mousePressEvent(QMouseEvent* event);
+
+ private:
+ bool editable;
+ ByteArray data;
+ std::string type;
+ QLabel* label;
+ };
}
diff --git a/Swift/QtUI/QtBlockListEditorWindow.cpp b/Swift/QtUI/QtBlockListEditorWindow.cpp
index 98c9e98..5b04b49 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.cpp
+++ b/Swift/QtUI/QtBlockListEditorWindow.cpp
@@ -31,197 +31,197 @@
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;
- }
+ 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 {
- QString value = index.model()->data(index, Qt::EditRole).toString();
-
- QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
- lineEdit->setText(value);
- }
-
- void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
- QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
- QString currentValue = lineEdit->text();
- int pos = 0;
- if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) {
- model->setData(index, lineEdit->text(), Qt::EditRole);
- } else {
- model->setData(index, QString(), Qt::EditRole);
- }
- }
-
- void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const {
- editor->setGeometry(option.rect);
- }
+ 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 {
+ QString value = index.model()->data(index, Qt::EditRole).toString();
+
+ QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
+ lineEdit->setText(value);
+ }
+
+ void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
+ QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
+ QString currentValue = lineEdit->text();
+ int pos = 0;
+ if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) {
+ model->setData(index, lineEdit->text(), Qt::EditRole);
+ } else {
+ model->setData(index, QString(), Qt::EditRole);
+ }
+ }
+
+ void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const {
+ editor->setGeometry(option.rect);
+ }
};
QtBlockListEditorWindow::QtBlockListEditorWindow() : QWidget(), ui(new Ui::QtBlockListEditorWindow), removeItemDelegate(0), editItemDelegate(0) {
- ui->setupUi(this);
+ ui->setupUi(this);
- freshBlockListTemplate = tr("Double-click to add contact");
+ freshBlockListTemplate = tr("Double-click to add contact");
- new QShortcut(QKeySequence::Close, this, SLOT(close()));
- ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ new QShortcut(QKeySequence::Close, this, SLOT(close()));
+ ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- removeItemDelegate = new QtRemovableItemDelegate(style());
- editItemDelegate = new QtJIDValidatedItemDelegate(this);
+ removeItemDelegate = new QtRemovableItemDelegate(style());
+ editItemDelegate = new QtJIDValidatedItemDelegate(this);
- connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges()));
+ connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges()));
- ui->blockListTreeWidget->setColumnCount(2);
- ui->blockListTreeWidget->header()->setStretchLastSection(false);
- ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ ui->blockListTreeWidget->setColumnCount(2);
+ ui->blockListTreeWidget->header()->setStretchLastSection(false);
+ ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
#if QT_VERSION >= 0x050000
- ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
+ ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
#endif
- ui->blockListTreeWidget->setHeaderHidden(true);
- ui->blockListTreeWidget->setRootIsDecorated(false);
- ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
- ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate);
- ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate);
- connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
- ui->blockListTreeWidget->installEventFilter(this);
-
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- ui->blockListTreeWidget->addTopLevelItem(item);
+ ui->blockListTreeWidget->setHeaderHidden(true);
+ ui->blockListTreeWidget->setRootIsDecorated(false);
+ ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
+ ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate);
+ ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate);
+ connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int)));
+ ui->blockListTreeWidget->installEventFilter(this);
+
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
}
QtBlockListEditorWindow::~QtBlockListEditorWindow() {
}
void QtBlockListEditorWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtBlockListEditorWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
void QtBlockListEditorWindow::handleItemChanged(QTreeWidgetItem *item, int) {
- // check whether changed item contains a valid JID and make it removable
- if (item && item->text(0) != freshBlockListTemplate) {
- item->setText(1, "");
- }
-
- // 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));
- }
+ // check whether changed item contains a valid JID and make it removable
+ if (item && item->text(0) != freshBlockListTemplate) {
+ item->setText(1, "");
+ }
+
+ // 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());
+ onSetNewBlockList(getCurrentBlockList());
}
void QtBlockListEditorWindow::setCurrentBlockList(const std::vector<JID> &blockedJIDs) {
- ui->blockListTreeWidget->clear();
-
- foreach(const JID& jid, blockedJIDs) {
- QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- ui->blockListTreeWidget->addTopLevelItem(item);
- }
- handleItemChanged(0,0);
+ ui->blockListTreeWidget->clear();
+
+ foreach(const JID& jid, blockedJIDs) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
+ }
+ handleItemChanged(0,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);
- }
+ 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("");
- }
+ if (!error.empty()) {
+ ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
+ }
+ else {
+ ui->errorLabel->setText("");
+ }
}
std::vector<JID> Swift::QtBlockListEditorWindow::getCurrentBlockList() const {
- std::vector<JID> futureBlockedJIDs;
-
- for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) {
- QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
- JID jid = JID(Q2PSTRING(row->text(0)));
- if (!jid.toString().empty() && jid.isValid()) {
- futureBlockedJIDs.push_back(jid);
- }
- }
- return futureBlockedJIDs;
+ std::vector<JID> futureBlockedJIDs;
+
+ for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) {
+ QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i);
+ JID jid = JID(Q2PSTRING(row->text(0)));
+ if (!jid.toString().empty() && jid.isValid()) {
+ futureBlockedJIDs.push_back(jid);
+ }
+ }
+ return futureBlockedJIDs;
}
bool QtBlockListEditorWindow::eventFilter(QObject* target, QEvent* event) {
- if (target == ui->blockListTreeWidget) {
- if (event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
- if (keyEvent->key() == Qt::Key_Backspace) {
- // remove currently selected item
- QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem();
- if (currentItem->text(0) != freshBlockListTemplate) {
- ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem));
- return true;
- }
- }
- else if (keyEvent->key() == Qt::Key_Return) {
- // open editor for return key d
- ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0);
- return true;
- }
- }
- }
- return QWidget::eventFilter(target, event);
+ if (target == ui->blockListTreeWidget) {
+ if (event->type() == QEvent::KeyPress) {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
+ if (keyEvent->key() == Qt::Key_Backspace) {
+ // remove currently selected item
+ QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem();
+ if (currentItem->text(0) != freshBlockListTemplate) {
+ ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem));
+ return true;
+ }
+ }
+ else if (keyEvent->key() == Qt::Key_Return) {
+ // open editor for return key d
+ ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0);
+ return true;
+ }
+ }
+ }
+ return QWidget::eventFilter(target, event);
}
}
diff --git a/Swift/QtUI/QtBlockListEditorWindow.h b/Swift/QtUI/QtBlockListEditorWindow.h
index a594210..dc900ab 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.h
+++ b/Swift/QtUI/QtBlockListEditorWindow.h
@@ -20,7 +20,7 @@
#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
namespace Ui {
- class QtBlockListEditorWindow;
+ class QtBlockListEditorWindow;
}
namespace Swift {
@@ -28,29 +28,29 @@ namespace Swift {
class QtJIDValidatedItemDelegate;
class QtBlockListEditorWindow : public QWidget, public BlockListEditorWidget {
- Q_OBJECT
-
- public:
- QtBlockListEditorWindow();
- virtual ~QtBlockListEditorWindow();
-
- virtual void show();
- virtual void hide();
- virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs);
- virtual void setBusy(bool isBusy);
- virtual void setError(const std::string& error);
- virtual std::vector<JID> getCurrentBlockList() const;
- virtual bool eventFilter(QObject* target, QEvent* event);
-
- private slots:
- void handleItemChanged(QTreeWidgetItem*, int);
- void applyChanges();
-
- private:
- Ui::QtBlockListEditorWindow* ui;
- QtRemovableItemDelegate* removeItemDelegate;
- QtJIDValidatedItemDelegate* editItemDelegate;
- QString freshBlockListTemplate;
+ Q_OBJECT
+
+ public:
+ QtBlockListEditorWindow();
+ virtual ~QtBlockListEditorWindow();
+
+ virtual void show();
+ virtual void hide();
+ virtual void setCurrentBlockList(const std::vector<JID>& blockedJIDs);
+ virtual void setBusy(bool isBusy);
+ virtual void setError(const std::string& error);
+ virtual std::vector<JID> getCurrentBlockList() const;
+ virtual bool eventFilter(QObject* target, QEvent* event);
+
+ private slots:
+ void handleItemChanged(QTreeWidgetItem*, int);
+ void applyChanges();
+
+ private:
+ Ui::QtBlockListEditorWindow* ui;
+ QtRemovableItemDelegate* removeItemDelegate;
+ QtJIDValidatedItemDelegate* editItemDelegate;
+ QString freshBlockListTemplate;
};
}
diff --git a/Swift/QtUI/QtBookmarkDetailWindow.cpp b/Swift/QtUI/QtBookmarkDetailWindow.cpp
index ea5b217..920e94e 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.cpp
+++ b/Swift/QtUI/QtBookmarkDetailWindow.cpp
@@ -13,67 +13,67 @@
namespace Swift {
QtBookmarkDetailWindow::QtBookmarkDetailWindow(QWidget* parent) : QDialog(parent) {
- setupUi(this);
- setAttribute(Qt::WA_DeleteOnClose, true);
- //connect(buttons_, SIGNAL(accepted()), SLOT(accept()));
- //connect(buttons_, SIGNAL(rejected()), SLOT(reject()));
- setFixedHeight(sizeHint().height());
+ setupUi(this);
+ setAttribute(Qt::WA_DeleteOnClose, true);
+ //connect(buttons_, SIGNAL(accepted()), SLOT(accept()));
+ //connect(buttons_, SIGNAL(rejected()), SLOT(reject()));
+ setFixedHeight(sizeHint().height());
}
void QtBookmarkDetailWindow::accept() {
- if (commit()) {
- QDialog::accept();
- }
+ if (commit()) {
+ QDialog::accept();
+ }
}
boost::optional<MUCBookmark> QtBookmarkDetailWindow::createBookmarkFromForm() {
- //check room
- //check bookmarkName
- JID room(Q2PSTRING(room_->text()));
- if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) {
- QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com)."));
- return boost::optional<MUCBookmark>();
- }
- std::string name(Q2PSTRING(name_->text()));
- if (name.empty()) {
- name = room.toString();
- }
+ //check room
+ //check bookmarkName
+ JID room(Q2PSTRING(room_->text()));
+ if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) {
+ QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com)."));
+ return boost::optional<MUCBookmark>();
+ }
+ std::string name(Q2PSTRING(name_->text()));
+ if (name.empty()) {
+ name = room.toString();
+ }
- MUCBookmark bookmark(room, name);
- std::string nick(Q2PSTRING(nick_->text()));
- std::string password(Q2PSTRING(password_->text()));
- bookmark.setAutojoin(autojoin_->isChecked());
- if (!nick.empty()) {
- bookmark.setNick(nick);
- }
- if (!password.empty()) {
- bookmark.setPassword(password);
- }
- return bookmark;
+ MUCBookmark bookmark(room, name);
+ std::string nick(Q2PSTRING(nick_->text()));
+ std::string password(Q2PSTRING(password_->text()));
+ bookmark.setAutojoin(autojoin_->isChecked());
+ if (!nick.empty()) {
+ bookmark.setNick(nick);
+ }
+ if (!password.empty()) {
+ bookmark.setPassword(password);
+ }
+ return bookmark;
}
void QtBookmarkDetailWindow::createFormFromBookmark(const MUCBookmark& bookmark) {
- if (bookmark.getRoom().isValid()) {
- room_->setText(P2QSTRING(bookmark.getRoom().toString()));
- }
+ if (bookmark.getRoom().isValid()) {
+ room_->setText(P2QSTRING(bookmark.getRoom().toString()));
+ }
- if (!bookmark.getName().empty()) {
- name_->setText(P2QSTRING(bookmark.getName()));
- }
+ if (!bookmark.getName().empty()) {
+ name_->setText(P2QSTRING(bookmark.getName()));
+ }
- if (bookmark.getNick()) {
- nick_->setText(P2QSTRING((*bookmark.getNick())));
- }
+ if (bookmark.getNick()) {
+ nick_->setText(P2QSTRING((*bookmark.getNick())));
+ }
- if (bookmark.getPassword()) {
- password_->setText(P2QSTRING((*bookmark.getPassword())));
- }
+ if (bookmark.getPassword()) {
+ password_->setText(P2QSTRING((*bookmark.getPassword())));
+ }
- if (bookmark.getAutojoin()) {
- autojoin_->setCheckState(Qt::Checked);
- } else {
- autojoin_->setCheckState(Qt::Unchecked);
- }
+ if (bookmark.getAutojoin()) {
+ autojoin_->setCheckState(Qt::Checked);
+ } else {
+ autojoin_->setCheckState(Qt::Unchecked);
+ }
}
}
diff --git a/Swift/QtUI/QtBookmarkDetailWindow.h b/Swift/QtUI/QtBookmarkDetailWindow.h
index 427614a..19c6462 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.h
+++ b/Swift/QtUI/QtBookmarkDetailWindow.h
@@ -15,18 +15,18 @@
#include <Swift/QtUI/ui_QtBookmarkDetailWindow.h>
namespace Swift {
- class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtBookmarkDetailWindow(QWidget* parent = NULL);
- virtual bool commit() = 0;
- boost::optional<MUCBookmark> createBookmarkFromForm();
-
- protected:
- void createFormFromBookmark(const MUCBookmark& bookmark);
-
- public slots:
- void accept();
- };
+ class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtBookmarkDetailWindow(QWidget* parent = NULL);
+ virtual bool commit() = 0;
+ boost::optional<MUCBookmark> createBookmarkFromForm();
+
+ protected:
+ void createFormFromBookmark(const MUCBookmark& bookmark);
+
+ public slots:
+ void accept();
+ };
}
diff --git a/Swift/QtUI/QtCachedImageScaler.cpp b/Swift/QtUI/QtCachedImageScaler.cpp
index 0e10062..e1f540b 100644
--- a/Swift/QtUI/QtCachedImageScaler.cpp
+++ b/Swift/QtUI/QtCachedImageScaler.cpp
@@ -20,25 +20,25 @@ QtCachedImageScaler::QtCachedImageScaler() {
}
boost::filesystem::path QtCachedImageScaler::getScaledImage(const boost::filesystem::path& imagePath, int size) {
- boost::filesystem::path scaledImagePath(imagePath);
- std::string suffix = "." + boost::lexical_cast<std::string>(size);
- scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix);
- if (!boost::filesystem::exists(scaledImagePath)) {
- QImage image(P2QSTRING(pathToString(imagePath)));
- if (!image.isNull()) {
- if (image.width() > size || image.height() > size) {
- QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
- }
- else {
- image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
- }
- }
- else {
- return imagePath;
- }
- }
- return scaledImagePath;
+ boost::filesystem::path scaledImagePath(imagePath);
+ std::string suffix = "." + boost::lexical_cast<std::string>(size);
+ scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix);
+ if (!boost::filesystem::exists(scaledImagePath)) {
+ QImage image(P2QSTRING(pathToString(imagePath)));
+ if (!image.isNull()) {
+ if (image.width() > size || image.height() > size) {
+ QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
+ }
+ else {
+ image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG");
+ }
+ }
+ else {
+ return imagePath;
+ }
+ }
+ return scaledImagePath;
}
diff --git a/Swift/QtUI/QtCachedImageScaler.h b/Swift/QtUI/QtCachedImageScaler.h
index fcc2a2d..15d868e 100644
--- a/Swift/QtUI/QtCachedImageScaler.h
+++ b/Swift/QtUI/QtCachedImageScaler.h
@@ -9,11 +9,11 @@
#include <boost/filesystem.hpp>
namespace Swift {
- class QtCachedImageScaler {
- public:
- QtCachedImageScaler();
+ class QtCachedImageScaler {
+ public:
+ QtCachedImageScaler();
- boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size);
- };
+ boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size);
+ };
}
diff --git a/Swift/QtUI/QtCertificateViewerDialog.cpp b/Swift/QtUI/QtCertificateViewerDialog.cpp
index 4b8b0cb..a99c29a 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.cpp
+++ b/Swift/QtUI/QtCertificateViewerDialog.cpp
@@ -25,126 +25,126 @@
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*)));
+ ui->setupUi(this);
+ connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
- setAttribute(Qt::WA_DeleteOnClose);
+ setAttribute(Qt::WA_DeleteOnClose);
}
QtCertificateViewerDialog::~QtCertificateViewerDialog() {
- delete ui;
+ 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) {
- 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);
- }
+ // 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) {
+ 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();
+ QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent);
+ dialog->setCertificateChain(chain);
+ dialog->show();
}
void QtCertificateViewerDialog::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem*) {
- setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt()));
+ setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt()));
}
#define ADD_SECTION( TITLE ) \
- ui->certGridLayout->addWidget(new QLabel("<strong>" + TITLE + "</strong>"), rowCount++, 0, 1, 2);
+ ui->certGridLayout->addWidget(new QLabel("<strong>" + TITLE + "</strong>"), rowCount++, 0, 1, 2);
#define ADD_FIELD( TITLE, VALUE) \
- ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \
- valueLabel = new QLabel(); \
- valueLabel->setText(QStringList(VALUE).join(", ")); \
- valueLabel->setTextFormat(Qt::PlainText); \
- valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \
- ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft);
+ ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \
+ valueLabel = new QLabel(); \
+ valueLabel->setText(QStringList(VALUE).join(", ")); \
+ valueLabel->setTextFormat(Qt::PlainText); \
+ valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \
+ ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft);
void QtCertificateViewerDialog::setCertificateDetails(const QSslCertificate& cert) {
- QLayoutItem* item;
- while ((item = ui->certGridLayout->takeAt(0)) != NULL ) {
- delete item->widget();
- delete item;
- }
+ QLayoutItem* item;
+ while ((item = ui->certGridLayout->takeAt(0)) != NULL ) {
+ delete item->widget();
+ delete item;
+ }
- int rowCount = 0;
+ int rowCount = 0;
- ui->certGridLayout->setColumnStretch(2, 1);
+ ui->certGridLayout->setColumnStretch(2, 1);
- QLabel* valueLabel = 0;
+ 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("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));
+ 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();
+ QMultiMap<QSsl::AlternateNameEntryType, QString> altNames = cert.alternateSubjectNames();
#define SANTYPE QSsl::AlternateNameEntryType
#else
- QMultiMap<QSsl::AlternativeNameEntryType, QString> altNames = cert.subjectAlternativeNames();
+ 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)) {
- 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);
+ if (!altNames.empty()) {
+ ADD_SECTION(tr("Alternate Subject Names"));
+ foreach (const SANTYPE &type, altNames.uniqueKeys()) {
+ foreach (QString 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/QtCertificateViewerDialog.h b/Swift/QtUI/QtCertificateViewerDialog.h
index 9475a83..7b72f1d 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.h
+++ b/Swift/QtUI/QtCertificateViewerDialog.h
@@ -20,25 +20,25 @@ class QtCertificateViewerDialog;
namespace Swift {
class QtCertificateViewerDialog : public QDialog {
- Q_OBJECT
-
- public:
- explicit QtCertificateViewerDialog(QWidget* parent = 0);
- ~QtCertificateViewerDialog();
+ Q_OBJECT
- void setCertificateChain(const std::vector<Certificate::ref>& chain);
+ public:
+ explicit QtCertificateViewerDialog(QWidget* parent = 0);
+ ~QtCertificateViewerDialog();
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ void setCertificateChain(const std::vector<Certificate::ref>& chain);
- private slots:
- void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
- private:
- void setCertificateDetails(const QSslCertificate& cert);
+ private slots:
+ void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*);
- private:
- Ui::QtCertificateViewerDialog *ui;
- QList<QSslCertificate> currentChain;
+ private:
+ void setCertificateDetails(const QSslCertificate& cert);
+
+ private:
+ Ui::QtCertificateViewerDialog *ui;
+ QList<QSslCertificate> currentChain;
};
}
diff --git a/Swift/QtUI/QtChatTabs.cpp b/Swift/QtUI/QtChatTabs.cpp
index f22d869..4a77ffd 100644
--- a/Swift/QtUI/QtChatTabs.cpp
+++ b/Swift/QtUI/QtChatTabs.cpp
@@ -35,389 +35,389 @@
namespace Swift {
QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode) : QWidget(), singleWindow_(singleWindow), settingsProvider_(settingsProvider), trellisMode_(trellisMode), dynamicGrid_(NULL), gridSelectionDialog_(NULL) {
#ifndef Q_OS_MAC
- setWindowIcon(QIcon(":/logo-chat-16.png"));
+ setWindowIcon(QIcon(":/logo-chat-16.png"));
#else
- setAttribute(Qt::WA_ShowWithoutActivating);
+ setAttribute(Qt::WA_ShowWithoutActivating);
#endif
- dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode);
- connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
- connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int)));
-
- QVBoxLayout *layout = new QVBoxLayout;
- layout->setSpacing(0);
- layout->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(dynamicGrid_);
- setLayout(layout);
-
- if (trellisMode) {
- // restore size
- std::string gridSizeString = settingsProvider->getSetting(SettingConstants::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(SettingConstants::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()));
+ dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode);
+ connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
+ connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int)));
+
+ QVBoxLayout *layout = new QVBoxLayout;
+ layout->setSpacing(0);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(dynamicGrid_);
+ setLayout(layout);
+
+ if (trellisMode) {
+ // restore size
+ std::string gridSizeString = settingsProvider->getSetting(SettingConstants::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(SettingConstants::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_) {
- delete shortcut;
- }
-
- if (trellisMode_) {
- storeTabPositions();
- }
- delete gridSelectionDialog_;
+ foreach (QShortcut* 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();
+ //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());
+ return qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget());
}
void QtChatTabs::setViewMenu(QMenu* viewMenu) {
- if (trellisMode_) {
- viewMenu->addSeparator();
- QAction* action = new QAction(tr("Change &layout"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+L")));
- connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab right"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab left"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab to next group"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup()));
- viewMenu->addAction(action);
-
- action = new QAction(tr("Move Tab to previous group"), this);
- action->setShortcutContext(Qt::ApplicationShortcut);
- action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp")));
- connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup()));
- viewMenu->addAction(action);
- }
+ if (trellisMode_) {
+ viewMenu->addSeparator();
+ QAction* action = new QAction(tr("Change &layout"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+L")));
+ connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab right"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab left"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab to next group"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup()));
+ viewMenu->addAction(action);
+
+ action = new QAction(tr("Move Tab to previous group"), this);
+ action->setShortcutContext(Qt::ApplicationShortcut);
+ action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp")));
+ connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup()));
+ viewMenu->addAction(action);
+ }
}
void QtChatTabs::addTab(QtTabbable* tab) {
- QSizePolicy policy = sizePolicy();
- /* Chat windows like to grow - don't let them */
- setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- dynamicGrid_->addTab(tab, tab->windowTitle());
- connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
- connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
- connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection);
- connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection);
- connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection);
- 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(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection);
- setSizePolicy(policy);
+ QSizePolicy policy = sizePolicy();
+ /* Chat windows like to grow - don't let them */
+ setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ dynamicGrid_->addTab(tab, tab->windowTitle());
+ connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection);
+ connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection);
+ 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(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection);
+ setSizePolicy(policy);
}
void QtChatTabs::handleWidgetShown() {
- QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
- if (!widget) {
- return;
- }
- checkForFirstShow();
- if (dynamicGrid_->indexOf(widget) >= 0) {
- handleTabTitleUpdated(widget);
- return;
- }
- widget->blockSignals(true);
- addTab(widget);
- widget->blockSignals(false);
- show();
+ QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
+ if (!widget) {
+ return;
+ }
+ checkForFirstShow();
+ if (dynamicGrid_->indexOf(widget) >= 0) {
+ handleTabTitleUpdated(widget);
+ return;
+ }
+ widget->blockSignals(true);
+ addTab(widget);
+ widget->blockSignals(false);
+ show();
}
void QtChatTabs::handleCurrentTabIndexChanged(int newIndex) {
- handleTabTitleUpdated(dynamicGrid_->widget(newIndex));
+ handleTabTitleUpdated(dynamicGrid_->widget(newIndex));
}
void QtChatTabs::handleWantsToActivate() {
- QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
- Q_ASSERT(widget);
- //Un-minimize and bring to front.
- setWindowState(windowState() & ~Qt::WindowMinimized);
- setWindowState(windowState() | Qt::WindowActive);
- show();
- widget->show();
- dynamicGrid_->setCurrentWidget(widget);
- handleTabTitleUpdated(widget);
- widget->setFocus();
- raise();
- activateWindow();
+ QtTabbable* widget = qobject_cast<QtTabbable*>(sender());
+ Q_ASSERT(widget);
+ //Un-minimize and bring to front.
+ setWindowState(windowState() & ~Qt::WindowMinimized);
+ setWindowState(windowState() | Qt::WindowActive);
+ show();
+ widget->show();
+ dynamicGrid_->setCurrentWidget(widget);
+ handleTabTitleUpdated(widget);
+ widget->setFocus();
+ raise();
+ activateWindow();
}
void QtChatTabs::handleTabClosing() {
- QWidget* widget = qobject_cast<QWidget*>(sender());
- int index;
- if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) {
- dynamicGrid_->removeTab(index);
- if (dynamicGrid_->count() == 0) {
- if (!singleWindow_) {
- hide();
- }
- else {
- setWindowTitle("");
- onTitleChanged("");
- }
- }
- else {
- handleTabTitleUpdated(dynamicGrid_->currentWidget());
- }
- }
+ QWidget* widget = qobject_cast<QWidget*>(sender());
+ int index;
+ if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) {
+ dynamicGrid_->removeTab(index);
+ if (dynamicGrid_->count() == 0) {
+ if (!singleWindow_) {
+ hide();
+ }
+ else {
+ setWindowTitle("");
+ onTitleChanged("");
+ }
+ }
+ else {
+ handleTabTitleUpdated(dynamicGrid_->currentWidget());
+ }
+ }
}
void QtChatTabs::handleRequestedPreviousTab() {
- int newIndex = dynamicGrid_->currentIndex() - 1;
- dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1);
+ int newIndex = dynamicGrid_->currentIndex() - 1;
+ dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1);
}
void QtChatTabs::handleRequestedNextTab() {
- int newIndex = dynamicGrid_->currentIndex() + 1;
- dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0);
+ int newIndex = dynamicGrid_->currentIndex() + 1;
+ dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0);
}
void QtChatTabs::handleRequestedActiveTab() {
- QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
- bool finished = false;
- for (int j = 0; j < 2; j++) {
- bool looped = false;
- for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) {
- if (i >= dynamicGrid_->count()) {
- if (looped) {
- break;
- }
- looped = true;
- i = 0;
- }
- if (qobject_cast<QtTabbable*>(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) {
- dynamicGrid_->setCurrentIndex(i);
- finished = true;
- break;
- }
- }
- }
+ QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
+ bool finished = false;
+ for (int j = 0; j < 2; j++) {
+ bool looped = false;
+ for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) {
+ if (i >= dynamicGrid_->count()) {
+ if (looped) {
+ break;
+ }
+ looped = true;
+ i = 0;
+ }
+ if (qobject_cast<QtTabbable*>(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) {
+ dynamicGrid_->setCurrentIndex(i);
+ finished = true;
+ break;
+ }
+ }
+ }
}
void QtChatTabs::handleCloseTabShortcut() {
- QWidget* currentWidget = dynamicGrid_->currentWidget();
- if (currentWidget) {
- currentWidget->close();
- }
+ QWidget* currentWidget = dynamicGrid_->currentWidget();
+ if (currentWidget) {
+ currentWidget->close();
+ }
}
void QtChatTabs::handleTabCloseRequested(int index) {
- if (trellisMode_) {
- storeTabPositions();
- }
-
- assert(index < dynamicGrid_->count());
- QWidget* widget = dynamicGrid_->widget(index);
- assert(widget);
- widget->close();
+ if (trellisMode_) {
+ storeTabPositions();
+ }
+
+ assert(index < dynamicGrid_->count());
+ QWidget* widget = dynamicGrid_->widget(index);
+ assert(widget);
+ widget->close();
}
void QtChatTabs::handleTabTitleUpdated() {
- QWidget* widget = qobject_cast<QWidget*>(sender());
- handleTabTitleUpdated(widget);
+ QWidget* widget = qobject_cast<QWidget*>(sender());
+ handleTabTitleUpdated(widget);
}
void QtChatTabs::handleTabTitleUpdated(QWidget* widget) {
- if (!widget) {
- return;
- }
- QtTabbable* tabbable = qobject_cast<QtTabbable*>(widget);
- int index = dynamicGrid_->indexOf(widget);
- if (index < 0) {
- return;
- }
-
- QString tabText = tabbable->windowTitle().simplified();
- // look for spectrum-generated and other long JID localparts, and
- // try to abbreviate the resulting long tab texts
- QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$");
- if (hasTrailingGarbage.exactMatch(tabText) &&
- hasTrailingGarbage.cap(1).simplified().length() >= 2 &&
- hasTrailingGarbage.cap(2).length() >= 7) {
- // there may be some trailing garbage, and it's long
- // enough to be worth removing, and we'd leave at
- // least a couple of characters.
- tabText = hasTrailingGarbage.cap(1).simplified();
- }
- // QTabBar interprets &, so escape that
- tabText.replace("&", "&&");
- // see which alt[a-z] keys other tabs use
- bool accelsTaken[26];
- int i = 0;
- while (i < 26) {
- accelsTaken[i] = (i == 0); //A is used for 'switch to active tab'
- i++;
- }
-
- int other = dynamicGrid_->count();
- while (other >= 0) {
- other--;
- if (other != index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex);
- QString t = tabWidget->tabBar()->tabText(tabIndex).toLower();
- int r = t.indexOf('&');
- if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') {
- accelsTaken[t[r+1].unicode()-'a'] = true;
- }
- }
- }
- // then look to see which letters in tabText may be used
- i = 0;
- int accelPos = -1;
- while (i < tabText.length() && accelPos < 0) {
- if (tabText[i] >= 'A' && tabText[i] <= 'Z' &&
- !accelsTaken[tabText[i].unicode()-'A']) {
- accelPos = i;
- }
- if (tabText[i] >= 'a' && tabText[i] <= 'z' &&
- !accelsTaken[tabText[i].unicode()-'a']) {
- accelPos = i;
- }
- ++i;
- }
- if (accelPos >= 0) {
- tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos);
- }
- // this could be improved on some european keyboards, such as
- // the German one (where alt-Sz-Ligature is available) and basically
- // doesn't work on Arabic/Indic keyboards (where Latin letters
- // aren't available), but I don't care to deal with those.
-
- int tabIndex = -1;
- QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex);
- tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText);
- QColor tabTextColor;
- switch (tabbable->getWidgetAlertState()) {
- case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break;
- case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break;
- case QtTabbable::NoActivity : tabTextColor = QColor(); break;
- }
- tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor);
-
- std::vector<std::pair<std::string, int> > unreads;
- for (int i = 0; i < dynamicGrid_->count(); i++) {
- QtTabbable* tab = qobject_cast<QtTabbable*>(dynamicGrid_->widget(i));
- if (tab) {
- unreads.push_back(std::pair<std::string, int>(Q2PSTRING(tab->windowTitle()), tab->getCount()));
- }
- }
-
- std::string current(Q2PSTRING(qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget())->windowTitle()));
- ChatMessageSummarizer summary;
- QString title = summary.getSummary(current, unreads).c_str();
- setWindowTitle(title);
- emit onTitleChanged(title);
+ if (!widget) {
+ return;
+ }
+ QtTabbable* tabbable = qobject_cast<QtTabbable*>(widget);
+ int index = dynamicGrid_->indexOf(widget);
+ if (index < 0) {
+ return;
+ }
+
+ QString tabText = tabbable->windowTitle().simplified();
+ // look for spectrum-generated and other long JID localparts, and
+ // try to abbreviate the resulting long tab texts
+ QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$");
+ if (hasTrailingGarbage.exactMatch(tabText) &&
+ hasTrailingGarbage.cap(1).simplified().length() >= 2 &&
+ hasTrailingGarbage.cap(2).length() >= 7) {
+ // there may be some trailing garbage, and it's long
+ // enough to be worth removing, and we'd leave at
+ // least a couple of characters.
+ tabText = hasTrailingGarbage.cap(1).simplified();
+ }
+ // QTabBar interprets &, so escape that
+ tabText.replace("&", "&&");
+ // see which alt[a-z] keys other tabs use
+ bool accelsTaken[26];
+ int i = 0;
+ while (i < 26) {
+ accelsTaken[i] = (i == 0); //A is used for 'switch to active tab'
+ i++;
+ }
+
+ int other = dynamicGrid_->count();
+ while (other >= 0) {
+ other--;
+ if (other != index) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex);
+ QString t = tabWidget->tabBar()->tabText(tabIndex).toLower();
+ int r = t.indexOf('&');
+ if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') {
+ accelsTaken[t[r+1].unicode()-'a'] = true;
+ }
+ }
+ }
+ // then look to see which letters in tabText may be used
+ i = 0;
+ int accelPos = -1;
+ while (i < tabText.length() && accelPos < 0) {
+ if (tabText[i] >= 'A' && tabText[i] <= 'Z' &&
+ !accelsTaken[tabText[i].unicode()-'A']) {
+ accelPos = i;
+ }
+ if (tabText[i] >= 'a' && tabText[i] <= 'z' &&
+ !accelsTaken[tabText[i].unicode()-'a']) {
+ accelPos = i;
+ }
+ ++i;
+ }
+ if (accelPos >= 0) {
+ tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos);
+ }
+ // this could be improved on some european keyboards, such as
+ // the German one (where alt-Sz-Ligature is available) and basically
+ // doesn't work on Arabic/Indic keyboards (where Latin letters
+ // aren't available), but I don't care to deal with those.
+
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex);
+ tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText);
+ QColor tabTextColor;
+ switch (tabbable->getWidgetAlertState()) {
+ case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break;
+ case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break;
+ case QtTabbable::NoActivity : tabTextColor = QColor(); break;
+ }
+ tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor);
+
+ std::vector<std::pair<std::string, int> > unreads;
+ for (int i = 0; i < dynamicGrid_->count(); i++) {
+ QtTabbable* tab = qobject_cast<QtTabbable*>(dynamicGrid_->widget(i));
+ if (tab) {
+ unreads.push_back(std::pair<std::string, int>(Q2PSTRING(tab->windowTitle()), tab->getCount()));
+ }
+ }
+
+ std::string current(Q2PSTRING(qobject_cast<QtTabbable*>(dynamicGrid_->currentWidget())->windowTitle()));
+ ChatMessageSummarizer summary;
+ QString title = summary.getSummary(current, unreads).c_str();
+ setWindowTitle(title);
+ emit onTitleChanged(title);
}
void QtChatTabs::flash() {
#ifndef SWIFTEN_PLATFORM_MACOSX
- QApplication::alert(this, 0);
+ QApplication::alert(this, 0);
#endif
}
void QtChatTabs::handleOpenLayoutChangeDialog() {
- disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
- gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension());
- gridSelectionDialog_->move(QCursor::pos());
- connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
- gridSelectionDialog_->show();
+ disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
+ gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension());
+ gridSelectionDialog_->move(QCursor::pos());
+ connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize)));
+ gridSelectionDialog_->show();
}
void QtChatTabs::storeTabPositions() {
- // save size
- QByteArray gridSizeData;
- QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
- dataStreamGridSize << dynamicGrid_->getDimension();
- settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64())));
-
- // save positions
- QByteArray tabPositionsData;
- QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite);
- dynamicGrid_->updateTabPositions();
- dataStreamTabPositions << dynamicGrid_->getTabPositions();
- settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64())));
+ // save size
+ QByteArray gridSizeData;
+ QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
+ dataStreamGridSize << dynamicGrid_->getDimension();
+ settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64())));
+
+ // save positions
+ QByteArray tabPositionsData;
+ QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite);
+ dynamicGrid_->updateTabPositions();
+ dataStreamTabPositions << dynamicGrid_->getTabPositions();
+ settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64())));
}
void QtChatTabs::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatTabs::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatTabs::checkForFirstShow() {
- if (!isVisible()) {
+ if (!isVisible()) {
#ifndef Q_OS_MAC
- showMinimized();
+ showMinimized();
#else
- /* https://bugreports.qt-project.org/browse/QTBUG-19194
- * ^ When the above is fixed we can swap the below for just show();
- * WA_ShowWithoutActivating seems to helpfully not work, so... */
-
- QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/
- show();
- QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */
- if (currentWindow) {
- currentWindow->activateWindow(); /* Set focus back */
- }
+ /* https://bugreports.qt-project.org/browse/QTBUG-19194
+ * ^ When the above is fixed we can swap the below for just show();
+ * WA_ShowWithoutActivating seems to helpfully not work, so... */
+
+ QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/
+ show();
+ QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */
+ if (currentWindow) {
+ currentWindow->activateWindow(); /* Set focus back */
+ }
#endif
- }
+ }
}
}
diff --git a/Swift/QtUI/QtChatTabs.h b/Swift/QtUI/QtChatTabs.h
index 8fcbf4a..0c12d96 100644
--- a/Swift/QtUI/QtChatTabs.h
+++ b/Swift/QtUI/QtChatTabs.h
@@ -16,62 +16,62 @@ class QTabWidget;
class QMenu;
namespace Swift {
- class SettingsProvider;
-
- class QtTabbable;
- class QtTabWidget;
- class QtDynamicGridLayout;
- class QtGridSelectionDialog;
-
- class QtChatTabs : public QWidget, public QtChatTabsBase {
- Q_OBJECT
- public:
- QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode);
- virtual ~QtChatTabs();
-
- virtual void addTab(QtTabbable* tab);
- void minimise();
- QtTabbable* getCurrentTab();
- void setViewMenu(QMenu* viewMenu);
-
- signals:
- void geometryChanged();
- void onTitleChanged(const QString& title);
-
- protected slots:
- void closeEvent(QCloseEvent* event);
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
-
- private slots:
- void handleCurrentTabIndexChanged(int newIndex);
- void handleTabClosing();
- void handleTabTitleUpdated();
- void handleTabTitleUpdated(QWidget* widget);
- void handleTabCloseRequested(int index);
- void handleWidgetShown();
- void handleWantsToActivate();
- void handleRequestedPreviousTab();
- void handleRequestedNextTab();
- void handleRequestedActiveTab();
- void flash();
-
- void handleOpenLayoutChangeDialog();
-
- void handleCloseTabShortcut();
-
- private:
- void storeTabPositions();
- void checkForFirstShow();
-
- private:
- bool singleWindow_;
- SettingsProvider* settingsProvider_;
- bool trellisMode_;
- QtDynamicGridLayout* dynamicGrid_;
- QtGridSelectionDialog* gridSelectionDialog_;
-
- QList<QShortcut*> shortcuts_;
- };
+ class SettingsProvider;
+
+ class QtTabbable;
+ class QtTabWidget;
+ class QtDynamicGridLayout;
+ class QtGridSelectionDialog;
+
+ class QtChatTabs : public QWidget, public QtChatTabsBase {
+ Q_OBJECT
+ public:
+ QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode);
+ virtual ~QtChatTabs();
+
+ virtual void addTab(QtTabbable* tab);
+ void minimise();
+ QtTabbable* getCurrentTab();
+ void setViewMenu(QMenu* viewMenu);
+
+ signals:
+ void geometryChanged();
+ void onTitleChanged(const QString& title);
+
+ protected slots:
+ void closeEvent(QCloseEvent* event);
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+
+ private slots:
+ void handleCurrentTabIndexChanged(int newIndex);
+ void handleTabClosing();
+ void handleTabTitleUpdated();
+ void handleTabTitleUpdated(QWidget* widget);
+ void handleTabCloseRequested(int index);
+ void handleWidgetShown();
+ void handleWantsToActivate();
+ void handleRequestedPreviousTab();
+ void handleRequestedNextTab();
+ void handleRequestedActiveTab();
+ void flash();
+
+ void handleOpenLayoutChangeDialog();
+
+ void handleCloseTabShortcut();
+
+ private:
+ void storeTabPositions();
+ void checkForFirstShow();
+
+ private:
+ bool singleWindow_;
+ SettingsProvider* settingsProvider_;
+ bool trellisMode_;
+ QtDynamicGridLayout* dynamicGrid_;
+ QtGridSelectionDialog* gridSelectionDialog_;
+
+ QList<QShortcut*> shortcuts_;
+ };
}
diff --git a/Swift/QtUI/QtChatTabsBase.h b/Swift/QtUI/QtChatTabsBase.h
index 753b706..b49bb10 100644
--- a/Swift/QtUI/QtChatTabsBase.h
+++ b/Swift/QtUI/QtChatTabsBase.h
@@ -11,11 +11,11 @@ namespace Swift {
class QtTabbable;
class QtChatTabsBase {
- public:
- QtChatTabsBase();
- virtual ~QtChatTabsBase();
+ public:
+ QtChatTabsBase();
+ virtual ~QtChatTabsBase();
- virtual void addTab(QtTabbable* tab) = 0;
+ virtual void addTab(QtTabbable* tab) = 0;
};
}
diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
index 7f44177..2c064f8 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
@@ -27,82 +27,82 @@ 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()));
+ 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();
- }
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender()->parent());
+ SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl;
+ if (senderTab) {
+ senderTab->close();
+ }
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedNextTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- int currentIndex = tabs.indexOf(senderTab);
- assert(currentIndex >= 0);
+ int currentIndex = tabs.indexOf(senderTab);
+ assert(currentIndex >= 0);
- QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size());
- nextTab->activateWindow();
+ QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size());
+ nextTab->activateWindow();
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedActiveTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
+ QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity};
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- for (int j = 0; j < 2; j++) {
- int startIndex = tabs.indexOf(senderTab);
- int currentIndex = startIndex;
+ for (int j = 0; j < 2; j++) {
+ int startIndex = tabs.indexOf(senderTab);
+ int currentIndex = startIndex;
- do {
- currentIndex = (currentIndex + 1) % tabs.size();
- QtTabbable* currentTab = tabs.at(currentIndex);
- if (currentTab->getWidgetAlertState() == types[j]) {
- currentTab->activateWindow();
- return;
- }
- } while (startIndex != currentIndex);
- }
+ do {
+ currentIndex = (currentIndex + 1) % tabs.size();
+ QtTabbable* currentTab = tabs.at(currentIndex);
+ if (currentTab->getWidgetAlertState() == types[j]) {
+ currentTab->activateWindow();
+ return;
+ }
+ } while (startIndex != currentIndex);
+ }
}
void QtChatTabsShortcutOnlySubstitute::handleRequestedPreviousTab() {
- QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
+ QtTabbable* senderTab = dynamic_cast<QtTabbable*>(sender());
- QList<QtTabbable*> tabs = tabbableWindows();
+ QList<QtTabbable*> tabs = tabbableWindows();
- int currentIndex = tabs.indexOf(senderTab);
- assert(currentIndex >= 0);
+ int currentIndex = tabs.indexOf(senderTab);
+ assert(currentIndex >= 0);
- QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size());
- previousTab->activateWindow();
+ QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size());
+ previousTab->activateWindow();
}
QList<QtTabbable*> QtChatTabsShortcutOnlySubstitute::tabbableWindows() const {
- QList<QWidget*> windows = qApp->topLevelWidgets();
+ QList<QWidget*> windows = qApp->topLevelWidgets();
- QList<QtTabbable*> tabbables;
- foreach(QWidget* topLevelWidget, windows) {
- QtTabbable* tabbable = dynamic_cast<QtTabbable*>(topLevelWidget);
- if (tabbable) {
- tabbables << tabbable;
- }
- }
+ QList<QtTabbable*> tabbables;
+ foreach(QWidget* topLevelWidget, windows) {
+ QtTabbable* tabbable = dynamic_cast<QtTabbable*>(topLevelWidget);
+ if (tabbable) {
+ tabbables << tabbable;
+ }
+ }
- return tabbables;
+ return tabbables;
}
}
diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
index 80af008..b330fe7 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
@@ -16,25 +16,25 @@ class QShortcut;
namespace Swift {
class QtChatTabsShortcutOnlySubstitute : public QWidget, public QtChatTabsBase {
- Q_OBJECT
+ Q_OBJECT
- public:
- QtChatTabsShortcutOnlySubstitute();
- virtual ~QtChatTabsShortcutOnlySubstitute();
+ public:
+ QtChatTabsShortcutOnlySubstitute();
+ virtual ~QtChatTabsShortcutOnlySubstitute();
- virtual void addTab(QtTabbable* tab);
+ virtual void addTab(QtTabbable* tab);
- private slots:
- void handleCloseTabShortcut();
- void handleRequestedNextTab();
- void handleRequestedActiveTab();
- void handleRequestedPreviousTab();
+ private slots:
+ void handleCloseTabShortcut();
+ void handleRequestedNextTab();
+ void handleRequestedActiveTab();
+ void handleRequestedPreviousTab();
- private:
- QList<QtTabbable*> tabbableWindows() const;
+ private:
+ QList<QtTabbable*> tabbableWindows() const;
- private:
- QList<QShortcut*> shortcuts_;
+ private:
+ QList<QShortcut*> shortcuts_;
};
}
diff --git a/Swift/QtUI/QtChatTheme.cpp b/Swift/QtUI/QtChatTheme.cpp
index a7628d9..e73f8ac 100644
--- a/Swift/QtUI/QtChatTheme.cpp
+++ b/Swift/QtUI/QtChatTheme.cpp
@@ -14,58 +14,58 @@ namespace Swift {
* Load Adium themes, as http://trac.adium.im/wiki/CreatingMessageStyles
*/
QtChatTheme::QtChatTheme(const QString& themePath) : qrc_(themePath[0] == ':'), themePath_(qrc_ ? themePath : themePath + "/Contents/Resources/") {
- QString fileNames[EndMarker];
- fileNames[Header] = "Header.html";
- fileNames[Footer] = "Footer.html";
- fileNames[Content] = "Content.html";
- fileNames[Status] = "Status.html";
- fileNames[Topic] = "Topic.html";
- fileNames[FileTransferRequest] = "FileTransferRequest.html";
- fileNames[IncomingContent] = "Incoming/Content.html";
- fileNames[IncomingNextContent] = "Incoming/NextContent.html";
- fileNames[IncomingContext] = "Incoming/Context.html";
- fileNames[IncomingNextContext] = "Incoming/NextContext.html";
- fileNames[OutgoingContent] = "Outgoing/Content.html";
- fileNames[OutgoingNextContent] = "Outgoing/NextContent.html";
- fileNames[OutgoingContext] = "Outgoing/Context.html";
- fileNames[OutgoingNextContext] = "Outgoing/NextContext.html";
- fileNames[Template] = "Template.html";
- fileNames[MainCSS] = "main.css";
- fileNames[Unread] = "Unread.html";
- fileNames[TemplateDefault] = ":/themes/Template.html";
- for (int i = 0; i < EndMarker; i++) {
- QString source;
- QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]);
- if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) {
- source = sourceFile.readAll();
- sourceFile.close();
- } else {
- //qWarning() << "Couldn't load file " << sourceFile.fileName();
- }
- fileContents_.append(source);
- }
+ QString fileNames[EndMarker];
+ fileNames[Header] = "Header.html";
+ fileNames[Footer] = "Footer.html";
+ fileNames[Content] = "Content.html";
+ fileNames[Status] = "Status.html";
+ fileNames[Topic] = "Topic.html";
+ fileNames[FileTransferRequest] = "FileTransferRequest.html";
+ fileNames[IncomingContent] = "Incoming/Content.html";
+ fileNames[IncomingNextContent] = "Incoming/NextContent.html";
+ fileNames[IncomingContext] = "Incoming/Context.html";
+ fileNames[IncomingNextContext] = "Incoming/NextContext.html";
+ fileNames[OutgoingContent] = "Outgoing/Content.html";
+ fileNames[OutgoingNextContent] = "Outgoing/NextContent.html";
+ fileNames[OutgoingContext] = "Outgoing/Context.html";
+ fileNames[OutgoingNextContext] = "Outgoing/NextContext.html";
+ fileNames[Template] = "Template.html";
+ fileNames[MainCSS] = "main.css";
+ fileNames[Unread] = "Unread.html";
+ fileNames[TemplateDefault] = ":/themes/Template.html";
+ for (int i = 0; i < EndMarker; i++) {
+ QString source;
+ QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]);
+ if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) {
+ source = sourceFile.readAll();
+ sourceFile.close();
+ } else {
+ //qWarning() << "Couldn't load file " << sourceFile.fileName();
+ }
+ fileContents_.append(source);
+ }
- /* Fallbacks */
- if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault];
- if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content];
- if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content];
- if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent];
- if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status];
- if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent];
- if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent];
- if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent];
- if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent];
- if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent];
- if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent];
+ /* Fallbacks */
+ if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault];
+ if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content];
+ if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content];
+ if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent];
+ if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status];
+ if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent];
+ if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent];
+ if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent];
+ if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent];
+ if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent];
+ if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent];
}
QString QtChatTheme::getBase() const {
- return qrc_ ? "qrc" + themePath_ : "file://" + themePath_;
+ return qrc_ ? "qrc" + themePath_ : "file://" + themePath_;
}
QString QtChatTheme::getUnread() const {
- return fileContents_[Unread].isEmpty() ? "<hr/>" : fileContents_[Unread];
+ return fileContents_[Unread].isEmpty() ? "<hr/>" : fileContents_[Unread];
}
}
diff --git a/Swift/QtUI/QtChatTheme.h b/Swift/QtUI/QtChatTheme.h
index 2997de0..8db662f 100644
--- a/Swift/QtUI/QtChatTheme.h
+++ b/Swift/QtUI/QtChatTheme.h
@@ -10,32 +10,32 @@
#include <QString>
namespace Swift {
- class QtChatTheme {
- public:
- QtChatTheme(const QString& themePath);
- QString getHeader() const {return fileContents_[Header];}
- QString getFooter() const {return fileContents_[Footer];}
- QString getContent() const {return fileContents_[Content];}
- QString getStatus() const {return fileContents_[Status];}
- QString getTopic() const {return fileContents_[Topic];}
- QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];}
- QString getIncomingContent() const {return fileContents_[IncomingContent];}
- QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];}
- QString getIncomingContext() const {return fileContents_[IncomingContext];}
- QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];}
- QString getOutgoingContent() const {return fileContents_[OutgoingContent];}
- QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];}
- QString getOutgoingContext() const {return fileContents_[OutgoingContext];}
- QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];}
- QString getTemplate() const {return fileContents_[Template];}
- QString getMainCSS() const {return fileContents_[MainCSS];}
- QString getBase() const;
- QString getUnread() const;
+ class QtChatTheme {
+ public:
+ QtChatTheme(const QString& themePath);
+ QString getHeader() const {return fileContents_[Header];}
+ QString getFooter() const {return fileContents_[Footer];}
+ QString getContent() const {return fileContents_[Content];}
+ QString getStatus() const {return fileContents_[Status];}
+ QString getTopic() const {return fileContents_[Topic];}
+ QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];}
+ QString getIncomingContent() const {return fileContents_[IncomingContent];}
+ QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];}
+ QString getIncomingContext() const {return fileContents_[IncomingContext];}
+ QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];}
+ QString getOutgoingContent() const {return fileContents_[OutgoingContent];}
+ QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];}
+ QString getOutgoingContext() const {return fileContents_[OutgoingContext];}
+ QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];}
+ QString getTemplate() const {return fileContents_[Template];}
+ QString getMainCSS() const {return fileContents_[MainCSS];}
+ QString getBase() const;
+ QString getUnread() const;
- private:
- enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker};
- bool qrc_;
- QList<QString> fileContents_;
- QString themePath_;
- };
+ private:
+ enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker};
+ bool qrc_;
+ QList<QString> fileContents_;
+ QString themePath_;
+ };
}
diff --git a/Swift/QtUI/QtChatView.cpp b/Swift/QtUI/QtChatView.cpp
index 05366c1..6d9a17d 100644
--- a/Swift/QtUI/QtChatView.cpp
+++ b/Swift/QtUI/QtChatView.cpp
@@ -13,7 +13,7 @@ QtChatView::QtChatView(QWidget* parent) : QWidget(parent) {
}
QtChatView::~QtChatView() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatView.h b/Swift/QtUI/QtChatView.h
index 9f0df44..cca3bdf 100644
--- a/Swift/QtUI/QtChatView.h
+++ b/Swift/QtUI/QtChatView.h
@@ -16,49 +16,49 @@
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
namespace Swift {
- class HighlightAction;
- class SecurityLabel;
+ class HighlightAction;
+ class SecurityLabel;
- class QtChatView : public QWidget {
- Q_OBJECT
- public:
- QtChatView(QWidget* parent);
- virtual ~QtChatView();
+ class QtChatView : public QWidget {
+ Q_OBJECT
+ public:
+ QtChatView(QWidget* parent);
+ virtual ~QtChatView();
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0;
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0;
- virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0;
- virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
- virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
- virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0;
-
- virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
- virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0;
- virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0;
- virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0;
- virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0;
- virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0;
+ virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0;
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0;
+ virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0;
- virtual void showEmoticons(bool show) = 0;
- virtual void addLastSeenLine() = 0;
+ virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0;
+ virtual void setFileTransferProgress(std::string, const int percentageDone) = 0;
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0;
+ virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0;
+ virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0;
+ virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0;
+ virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0;
- public slots:
- virtual void resizeFont(int fontSizeSteps) = 0;
- virtual void scrollToBottom() = 0;
- virtual void handleKeyPressEvent(QKeyEvent* event) = 0;
+ virtual void showEmoticons(bool show) = 0;
+ virtual void addLastSeenLine() = 0;
- };
+ public slots:
+ virtual void resizeFont(int fontSizeSteps) = 0;
+ virtual void scrollToBottom() = 0;
+ virtual void handleKeyPressEvent(QKeyEvent* event) = 0;
+
+ };
}
diff --git a/Swift/QtUI/QtChatWindow.cpp b/Swift/QtUI/QtChatWindow.cpp
index 7649256..95d643c 100644
--- a/Swift/QtUI/QtChatWindow.cpp
+++ b/Swift/QtUI/QtChatWindow.cpp
@@ -62,883 +62,883 @@
namespace Swift {
QtChatWindow::QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons) : QtTabbable(), id_(Q2PSTRING(contact)), contact_(contact), nextAlertId_(0), eventStream_(eventStream), blockingState_(BlockingUnsupported), isMUC_(false), supportsImpromptuChat_(false), roomBookmarkState_(RoomNotBookmarked) {
- settings_ = settings;
- unreadCount_ = 0;
- isOnline_ = true;
- completer_ = NULL;
- affiliationEditor_ = NULL;
- theme_ = theme;
- isCorrection_ = false;
- labelModel_ = NULL;
- correctionEnabled_ = Maybe;
- fileTransferEnabled_ = Maybe;
- updateTitleWithUnreadCount();
- assert(settings);
- setAcceptDrops(true);
-
- alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }";
-
- QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(2);
-
- alertLayout_ = new QVBoxLayout();
- layout->addLayout(alertLayout_);
-
- subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight);
- subject_ = new QLineEdit(this);
- subjectLayout_->addWidget(subject_);
- setSubject("");
- subject_->setReadOnly(true);
-
- QPushButton* actionButton_ = new QPushButton(this);
- actionButton_->setIcon(QIcon(":/icons/actions.png"));
- connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked()));
- subject_->hide();
-
- layout->addLayout(subjectLayout_);
-
- logRosterSplitter_ = new QSplitter(this);
- logRosterSplitter_->setAutoFillBackground(true);
- layout->addWidget(logRosterSplitter_);
- if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
- messageLog_ = new QtPlainChatView(this, eventStream_);
- }
- else {
- messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now.
- }
- logRosterSplitter_->addWidget(messageLog_);
-
- treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this);
- treeWidget_->hide();
- logRosterSplitter_->addWidget(treeWidget_);
- logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
-
- midBar_ = new QWidget(this);
- //layout->addWidget(midBar);
- midBar_->setAutoFillBackground(true);
- QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_);
- midBarLayout->setContentsMargins(0,0,0,0);
- midBarLayout->setSpacing(2);
- //midBarLayout->addStretch();
-
- labelsWidget_ = new QComboBox(this);
- labelsWidget_->setFocusPolicy(Qt::NoFocus);
- labelsWidget_->hide();
- labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
- midBarLayout->addWidget(labelsWidget_,0);
- connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int)));
- defaultLabelsPalette_ = labelsWidget_->palette();
-
- QHBoxLayout* inputBarLayout = new QHBoxLayout();
- inputBarLayout->setContentsMargins(0,0,0,0);
- inputBarLayout->setSpacing(2);
- input_ = new QtTextEdit(settings_, this);
- input_->setAcceptRichText(false);
- inputBarLayout->addWidget(midBar_);
- inputBarLayout->addWidget(input_);
- correctingLabel_ = new QLabel(tr("Correcting"), this);
- inputBarLayout->addWidget(correctingLabel_);
- correctingLabel_->hide();
-
- connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus()));
- connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus()));
- QPushButton* emoticonsButton_ = new QPushButton(this);
- emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png"));
- connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked()));
-
- emoticonsMenu_ = new QMenu(this);
- QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_);
- connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString)));
-
- // using an extra layout to work around Qt margin glitches on OS X
- QHBoxLayout* actionLayout = new QHBoxLayout();
- actionLayout->addWidget(emoticonsButton_);
- actionLayout->addWidget(actionButton_);
-
- inputBarLayout->addLayout(actionLayout);
- layout->addLayout(inputBarLayout);
-
- inputClearing_ = false;
- contactIsTyping_ = false;
- tabCompletion_ = false;
-
- connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*)));
- connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
- connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged()));
- connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged()));
- setFocusProxy(input_);
- logRosterSplitter_->setFocusProxy(input_);
- midBar_->setFocusProxy(input_);
- messageLog_->setFocusProxy(input_);
- connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus()));
- resize(400,300);
- connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int)));
- connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared()));
-
- treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1));
- treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2));
-
- settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
- messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- setMinimumSize(100, 100);
+ settings_ = settings;
+ unreadCount_ = 0;
+ isOnline_ = true;
+ completer_ = NULL;
+ affiliationEditor_ = NULL;
+ theme_ = theme;
+ isCorrection_ = false;
+ labelModel_ = NULL;
+ correctionEnabled_ = Maybe;
+ fileTransferEnabled_ = Maybe;
+ updateTitleWithUnreadCount();
+ assert(settings);
+ setAcceptDrops(true);
+
+ alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }";
+
+ QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(2);
+
+ alertLayout_ = new QVBoxLayout();
+ layout->addLayout(alertLayout_);
+
+ subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight);
+ subject_ = new QLineEdit(this);
+ subjectLayout_->addWidget(subject_);
+ setSubject("");
+ subject_->setReadOnly(true);
+
+ QPushButton* actionButton_ = new QPushButton(this);
+ actionButton_->setIcon(QIcon(":/icons/actions.png"));
+ connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked()));
+ subject_->hide();
+
+ layout->addLayout(subjectLayout_);
+
+ logRosterSplitter_ = new QSplitter(this);
+ logRosterSplitter_->setAutoFillBackground(true);
+ layout->addWidget(logRosterSplitter_);
+ if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
+ messageLog_ = new QtPlainChatView(this, eventStream_);
+ }
+ else {
+ messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now.
+ }
+ logRosterSplitter_->addWidget(messageLog_);
+
+ treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this);
+ treeWidget_->hide();
+ logRosterSplitter_->addWidget(treeWidget_);
+ logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int)));
+
+ midBar_ = new QWidget(this);
+ //layout->addWidget(midBar);
+ midBar_->setAutoFillBackground(true);
+ QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_);
+ midBarLayout->setContentsMargins(0,0,0,0);
+ midBarLayout->setSpacing(2);
+ //midBarLayout->addStretch();
+
+ labelsWidget_ = new QComboBox(this);
+ labelsWidget_->setFocusPolicy(Qt::NoFocus);
+ labelsWidget_->hide();
+ labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
+ midBarLayout->addWidget(labelsWidget_,0);
+ connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int)));
+ defaultLabelsPalette_ = labelsWidget_->palette();
+
+ QHBoxLayout* inputBarLayout = new QHBoxLayout();
+ inputBarLayout->setContentsMargins(0,0,0,0);
+ inputBarLayout->setSpacing(2);
+ input_ = new QtTextEdit(settings_, this);
+ input_->setAcceptRichText(false);
+ inputBarLayout->addWidget(midBar_);
+ inputBarLayout->addWidget(input_);
+ correctingLabel_ = new QLabel(tr("Correcting"), this);
+ inputBarLayout->addWidget(correctingLabel_);
+ correctingLabel_->hide();
+
+ connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus()));
+ connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus()));
+ QPushButton* emoticonsButton_ = new QPushButton(this);
+ emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png"));
+ connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked()));
+
+ emoticonsMenu_ = new QMenu(this);
+ QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_);
+ connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString)));
+
+ // using an extra layout to work around Qt margin glitches on OS X
+ QHBoxLayout* actionLayout = new QHBoxLayout();
+ actionLayout->addWidget(emoticonsButton_);
+ actionLayout->addWidget(actionButton_);
+
+ inputBarLayout->addLayout(actionLayout);
+ layout->addLayout(inputBarLayout);
+
+ inputClearing_ = false;
+ contactIsTyping_ = false;
+ tabCompletion_ = false;
+
+ connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*)));
+ connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
+ connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged()));
+ connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged()));
+ setFocusProxy(input_);
+ logRosterSplitter_->setFocusProxy(input_);
+ midBar_->setFocusProxy(input_);
+ messageLog_->setFocusProxy(input_);
+ connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus()));
+ resize(400,300);
+ connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int)));
+ connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared()));
+
+ treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1));
+ treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2));
+
+ settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
+ messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ setMinimumSize(100, 100);
}
QtChatWindow::~QtChatWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
+ settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1));
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
}
void QtChatWindow::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
- bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS);
- messageLog_->showEmoticons(showEmoticons);
- }
+ if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
+ bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS);
+ messageLog_->showEmoticons(showEmoticons);
+ }
}
void QtChatWindow::handleLogCleared() {
- onLogCleared();
+ onLogCleared();
}
void QtChatWindow::handleOccupantSelectionChanged(RosterItem* item) {
- onOccupantSelectionChanged(dynamic_cast<ContactRosterItem*>(item));
+ onOccupantSelectionChanged(dynamic_cast<ContactRosterItem*>(item));
}
void QtChatWindow::handleFontResized(int fontSizeSteps) {
- messageLog_->resizeFont(fontSizeSteps);
+ messageLog_->resizeFont(fontSizeSteps);
}
void QtChatWindow::handleAlertButtonClicked() {
- const QObject* alertWidget = QObject::sender()->parent();
- std::map<AlertID, QWidget*>::const_iterator i = alertWidgets_.begin();
- for ( ; i != alertWidgets_.end(); ++i) {
- if (i->second == alertWidget) {
- removeAlert(i->first);
- break;
- }
- }
+ const QObject* alertWidget = QObject::sender()->parent();
+ std::map<AlertID, QWidget*>::const_iterator i = alertWidgets_.begin();
+ for ( ; i != alertWidgets_.end(); ++i) {
+ if (i->second == alertWidget) {
+ removeAlert(i->first);
+ break;
+ }
+ }
}
QtChatWindow::AlertID QtChatWindow::addAlert(const std::string& alertText) {
- QWidget* alertWidget = new QWidget(this);
- QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget);
- alertLayout_->addWidget(alertWidget);
- QLabel* alertLabel = new QLabel(this);
- alertLabel->setText(alertText.c_str());
- alertLayout->addWidget(alertLabel);
-
- QToolButton* closeButton = new QToolButton(alertWidget);
- closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
- closeButton->setIconSize(QSize(16,16));
- closeButton->setCursor(Qt::ArrowCursor);
- closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
- connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked()));
-
- alertLayout->addWidget(closeButton);
- QPalette palette = alertWidget->palette();
- palette.setColor(QPalette::Window, QColor(Qt::yellow));
- palette.setColor(QPalette::WindowText, QColor(Qt::black));
- alertWidget->setStyleSheet(alertStyleSheet_);
- alertLabel->setStyleSheet(alertStyleSheet_);
-
- AlertID id = nextAlertId_++;
- alertWidgets_[id] = alertWidget;
- return id;
+ QWidget* alertWidget = new QWidget(this);
+ QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget);
+ alertLayout_->addWidget(alertWidget);
+ QLabel* alertLabel = new QLabel(this);
+ alertLabel->setText(alertText.c_str());
+ alertLayout->addWidget(alertLabel);
+
+ QToolButton* closeButton = new QToolButton(alertWidget);
+ closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
+ closeButton->setIconSize(QSize(16,16));
+ closeButton->setCursor(Qt::ArrowCursor);
+ closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
+ connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked()));
+
+ alertLayout->addWidget(closeButton);
+ QPalette palette = alertWidget->palette();
+ palette.setColor(QPalette::Window, QColor(Qt::yellow));
+ palette.setColor(QPalette::WindowText, QColor(Qt::black));
+ alertWidget->setStyleSheet(alertStyleSheet_);
+ alertLabel->setStyleSheet(alertStyleSheet_);
+
+ AlertID id = nextAlertId_++;
+ alertWidgets_[id] = alertWidget;
+ return id;
}
void QtChatWindow::removeAlert(const AlertID id) {
- std::map<AlertID, QWidget*>::iterator i = alertWidgets_.find(id);
- if (i != alertWidgets_.end()) {
- alertLayout_->removeWidget(i->second);
- delete i->second;
- alertWidgets_.erase(i);
- }
+ std::map<AlertID, QWidget*>::iterator i = alertWidgets_.find(id);
+ if (i != alertWidgets_.end()) {
+ alertLayout_->removeWidget(i->second);
+ delete i->second;
+ alertWidgets_.erase(i);
+ }
}
void QtChatWindow::setTabComplete(TabComplete* completer) {
- completer_ = completer;
+ completer_ = completer;
}
void QtChatWindow::handleKeyPressEvent(QKeyEvent* event) {
- event->ignore();
- if (event->isAccepted()) {
- return;
- }
- event->accept();
-
- int key = event->key();
- if (key == Qt::Key_Tab) {
- tabComplete();
- }
- else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) {
- beginCorrection();
- }
- else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) {
- cancelCorrection();
- }
- else if (key == Qt::Key_Down || key == Qt::Key_Up) {
- event->ignore();
- }
- else {
- messageLog_->handleKeyPressEvent(event);
- }
+ event->ignore();
+ if (event->isAccepted()) {
+ return;
+ }
+ event->accept();
+
+ int key = event->key();
+ if (key == Qt::Key_Tab) {
+ tabComplete();
+ }
+ else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) {
+ beginCorrection();
+ }
+ else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) {
+ cancelCorrection();
+ }
+ else if (key == Qt::Key_Down || key == Qt::Key_Up) {
+ event->ignore();
+ }
+ else {
+ messageLog_->handleKeyPressEvent(event);
+ }
}
void QtChatWindow::beginCorrection() {
- boost::optional<AlertID> newCorrectingAlert;
- if (correctionEnabled_ == Maybe) {
- newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message")));
- }
- else if (correctionEnabled_ == No) {
- newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message")));
- }
-
- if (newCorrectingAlert) {
- if (correctingAlert_) {
- removeAlert(*correctingAlert_);
- }
- correctingAlert_ = newCorrectingAlert;
- }
-
- QTextCursor cursor = input_->textCursor();
- cursor.select(QTextCursor::Document);
- cursor.beginEditBlock();
- cursor.insertText(QString(lastSentMessage_));
- cursor.endEditBlock();
- isCorrection_ = true;
- correctingLabel_->show();
- input_->setStyleSheet(alertStyleSheet_);
- labelsWidget_->setEnabled(false);
+ boost::optional<AlertID> newCorrectingAlert;
+ if (correctionEnabled_ == Maybe) {
+ newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message")));
+ }
+ else if (correctionEnabled_ == No) {
+ newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message")));
+ }
+
+ if (newCorrectingAlert) {
+ if (correctingAlert_) {
+ removeAlert(*correctingAlert_);
+ }
+ correctingAlert_ = newCorrectingAlert;
+ }
+
+ QTextCursor cursor = input_->textCursor();
+ cursor.select(QTextCursor::Document);
+ cursor.beginEditBlock();
+ cursor.insertText(QString(lastSentMessage_));
+ cursor.endEditBlock();
+ isCorrection_ = true;
+ correctingLabel_->show();
+ input_->setStyleSheet(alertStyleSheet_);
+ labelsWidget_->setEnabled(false);
}
void QtChatWindow::cancelCorrection() {
- if (correctingAlert_) {
- removeAlert(*correctingAlert_);
- correctingAlert_.reset();
- }
- QTextCursor cursor = input_->textCursor();
- cursor.select(QTextCursor::Document);
- cursor.removeSelectedText();
- isCorrection_ = false;
- correctingLabel_->hide();
- input_->setStyleSheet(qApp->styleSheet());
- labelsWidget_->setEnabled(true);
+ if (correctingAlert_) {
+ removeAlert(*correctingAlert_);
+ correctingAlert_.reset();
+ }
+ QTextCursor cursor = input_->textCursor();
+ cursor.select(QTextCursor::Document);
+ cursor.removeSelectedText();
+ isCorrection_ = false;
+ correctingLabel_->hide();
+ input_->setStyleSheet(qApp->styleSheet());
+ labelsWidget_->setEnabled(true);
}
QByteArray QtChatWindow::getSplitterState() {
- return logRosterSplitter_->saveState();
+ return logRosterSplitter_->saveState();
}
void QtChatWindow::handleChangeSplitterState(QByteArray state) {
- logRosterSplitter_->restoreState(state);
+ logRosterSplitter_->restoreState(state);
}
void QtChatWindow::handleSplitterMoved(int, int) {
- emit splitterMoved();
+ emit splitterMoved();
}
void QtChatWindow::tabComplete() {
- if (!completer_) {
- return;
- }
-
- QTextCursor cursor;
- if (tabCompleteCursor_.hasSelection()) {
- cursor = tabCompleteCursor_;
- }
- else {
- cursor = input_->textCursor();
- while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { }
- }
- QString root = cursor.selectedText();
- if (root.isEmpty()) {
- 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;
+ if (!completer_) {
+ return;
+ }
+
+ QTextCursor cursor;
+ if (tabCompleteCursor_.hasSelection()) {
+ cursor = tabCompleteCursor_;
+ }
+ else {
+ cursor = input_->textCursor();
+ while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { }
+ }
+ QString root = cursor.selectedText();
+ if (root.isEmpty()) {
+ 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);
+ 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) {
- if (label.getIsDefault()) {
- defaultIndex = i;
- break;
- }
- i++;
- }
- labelsWidget_->setCurrentIndex(defaultIndex);
+ delete labelModel_;
+ labelModel_ = new LabelModel();
+ labelModel_->availableLabels_ = labels;
+ int i = 0;
+ int defaultIndex = 0;
+ labelsWidget_->setModel(labelModel_);
+ foreach (SecurityLabelsCatalog::Item 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_);
- }
+ 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_);
+ }
}
void QtChatWindow::setSecurityLabelsError() {
- labelsWidget_->setEnabled(false);
+ labelsWidget_->setEnabled(false);
}
void QtChatWindow::setSecurityLabelsEnabled(bool enabled) {
- if (enabled) {
- labelsWidget_->setEnabled(true);
- labelsWidget_->show();
- }
- else {
- labelsWidget_->hide();
- }
+ if (enabled) {
+ labelsWidget_->setEnabled(true);
+ labelsWidget_->show();
+ }
+ else {
+ labelsWidget_->hide();
+ }
}
void QtChatWindow::setCorrectionEnabled(Tristate enabled) {
- correctionEnabled_ = enabled;
+ correctionEnabled_ = enabled;
}
void QtChatWindow::setFileTransferEnabled(Tristate enabled) {
- fileTransferEnabled_ = enabled;
+ fileTransferEnabled_ = enabled;
}
SecurityLabelsCatalog::Item QtChatWindow::getSelectedSecurityLabel() {
- assert(labelsWidget_->isEnabled());
- assert(labelsWidget_->currentIndex() >= 0 && static_cast<size_t>(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size());
- return labelModel_->availableLabels_[labelsWidget_->currentIndex()];
+ assert(labelsWidget_->isEnabled());
+ assert(labelsWidget_->currentIndex() >= 0 && static_cast<size_t>(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size());
+ return labelModel_->availableLabels_[labelsWidget_->currentIndex()];
}
void QtChatWindow::closeEvent(QCloseEvent* event) {
- event->accept();
- emit windowClosing();
- onClosed();
+ event->accept();
+ emit windowClosing();
+ onClosed();
}
void QtChatWindow::convertToMUC(MUCType mucType) {
- impromptu_ = (mucType == ImpromptuMUC);
- treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID);
- isMUC_ = true;
- treeWidget_->show();
- subject_->setVisible(!impromptu_);
+ impromptu_ = (mucType == ImpromptuMUC);
+ treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID);
+ isMUC_ = true;
+ treeWidget_->show();
+ subject_->setVisible(!impromptu_);
}
void QtChatWindow::setOnline(bool online) {
- isOnline_ = online;
- if (!online) {
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
- if (affiliationEditor_) {
- delete affiliationEditor_.data();
- }
- }
+ isOnline_ = online;
+ if (!online) {
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
+ if (affiliationEditor_) {
+ delete affiliationEditor_.data();
+ }
+ }
}
void QtChatWindow::showEvent(QShowEvent* event) {
- emit windowOpening();
- QWidget::showEvent(event);
+ emit windowOpening();
+ QWidget::showEvent(event);
}
void QtChatWindow::setUnreadMessageCount(int count) {
- if (unreadCount_ != count) {
- unreadCount_ = count;
- updateTitleWithUnreadCount();
- emit countUpdated();
- }
+ if (unreadCount_ != count) {
+ unreadCount_ = count;
+ updateTitleWithUnreadCount();
+ emit countUpdated();
+ }
}
void QtChatWindow::setContactChatState(ChatState::ChatStateType state) {
- contactIsTyping_ = (state == ChatState::Composing);
- emit titleUpdated();
+ contactIsTyping_ = (state == ChatState::Composing);
+ emit titleUpdated();
}
QtTabbable::AlertType QtChatWindow::getWidgetAlertState() {
- if (contactIsTyping_) {
- return ImpendingActivity;
- }
- if (unreadCount_ > 0) {
- return WaitingActivity;
- }
- return NoActivity;
+ if (contactIsTyping_) {
+ return ImpendingActivity;
+ }
+ if (unreadCount_ > 0) {
+ return WaitingActivity;
+ }
+ return NoActivity;
}
void QtChatWindow::setName(const std::string& name) {
- contact_ = P2QSTRING(name);
- updateTitleWithUnreadCount();
+ contact_ = P2QSTRING(name);
+ updateTitleWithUnreadCount();
}
void QtChatWindow::updateTitleWithUnreadCount() {
- if (isWindow()) {
- setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_);
- }
- else {
- setWindowTitle(contact_);
- }
- emit titleUpdated();
+ if (isWindow()) {
+ setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_);
+ }
+ else {
+ setWindowTitle(contact_);
+ }
+ emit titleUpdated();
}
void QtChatWindow::flash() {
- emit requestFlash();
+ emit requestFlash();
}
int QtChatWindow::getCount() {
- return unreadCount_;
+ return unreadCount_;
}
void QtChatWindow::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- messageLog_->replaceSystemMessage(message, id, timestampBehaviour);
+ messageLog_->replaceSystemMessage(message, id, timestampBehaviour);
}
void QtChatWindow::returnPressed() {
- if (!isOnline_ || (blockingState_ == IsBlocked)) {
- return;
- }
- messageLog_->scrollToBottom();
- lastSentMessage_ = QString(input_->toPlainText());
- onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_);
- inputClearing_ = true;
- input_->clear();
- cancelCorrection();
- inputClearing_ = false;
+ if (!isOnline_ || (blockingState_ == IsBlocked)) {
+ return;
+ }
+ messageLog_->scrollToBottom();
+ lastSentMessage_ = QString(input_->toPlainText());
+ onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_);
+ inputClearing_ = true;
+ input_->clear();
+ cancelCorrection();
+ inputClearing_ = false;
}
void QtChatWindow::handleInputChanged() {
- if (inputClearing_) {
- return;
- }
- if (input_->toPlainText().isEmpty()) {
- onUserCancelsTyping();
- }
- else {
- onUserTyping();
- }
+ if (inputClearing_) {
+ return;
+ }
+ if (input_->toPlainText().isEmpty()) {
+ onUserCancelsTyping();
+ }
+ else {
+ onUserTyping();
+ }
}
void QtChatWindow::handleCursorPositionChanged() {
- if (tabCompletion_) {
- return;
- }
- tabCompleteCursor_.clearSelection();
+ if (tabCompletion_) {
+ return;
+ }
+ tabCompleteCursor_.clearSelection();
}
void QtChatWindow::show() {
- if (parentWidget() == NULL) {
- QWidget::show();
- }
- emit windowOpening();
+ if (parentWidget() == NULL) {
+ QWidget::show();
+ }
+ emit windowOpening();
}
bool QtChatWindow::isVisible() const {
- return QWidget::isVisible();
+ return QWidget::isVisible();
}
void QtChatWindow::activate() {
- if (isWindow()) {
- QWidget::show();
- }
- emit wantsToActivate();
- input_->setFocus();
+ if (isWindow()) {
+ QWidget::show();
+ }
+ emit wantsToActivate();
+ input_->setFocus();
}
void QtChatWindow::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatWindow::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtChatWindow::dragEnterEvent(QDragEnterEvent *event) {
- if (isOnline_ && (blockingState_ != IsBlocked)) {
- if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
- if (!isMUC_ && fileTransferEnabled_ == Yes) {
- event->acceptProposedAction();
- }
- }
- else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- if (isMUC_ || supportsImpromptuChat_) {
- // Prevent invitations or impromptu initializations for contacts that you are already chatting to.
- std::vector<JID> droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
- std::set<JID> conversationJIDs;
- if (isMUC_) {
- conversationJIDs = treeWidget_->getRoster()->getJIDs();
- }
-
- for (std::vector<JID>::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) {
- const JID& droppedJID = *i;
- if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) {
- i = droppedJIDs.erase(i);
- }
- else {
- ++i;
- }
- }
-
- if (droppedJIDs.empty()) {
- event->ignore();
- }
- else {
- event->acceptProposedAction();
- }
- }
- }
- }
+ if (isOnline_ && (blockingState_ != IsBlocked)) {
+ if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
+ if (!isMUC_ && fileTransferEnabled_ == Yes) {
+ event->acceptProposedAction();
+ }
+ }
+ else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ if (isMUC_ || supportsImpromptuChat_) {
+ // Prevent invitations or impromptu initializations for contacts that you are already chatting to.
+ std::vector<JID> droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
+ std::set<JID> conversationJIDs;
+ if (isMUC_) {
+ conversationJIDs = treeWidget_->getRoster()->getJIDs();
+ }
+
+ for (std::vector<JID>::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) {
+ const JID& droppedJID = *i;
+ if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) {
+ i = droppedJIDs.erase(i);
+ }
+ else {
+ ++i;
+ }
+ }
+
+ if (droppedJIDs.empty()) {
+ event->ignore();
+ }
+ else {
+ event->acceptProposedAction();
+ }
+ }
+ }
+ }
}
void QtChatWindow::dropEvent(QDropEvent *event) {
- if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) {
- if (event->mimeData()->urls().size() == 1) {
- onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile()));
- }
- else {
- std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time.")));
- ChatMessage message;
- message.append(boost::make_shared<ChatTextMessagePart>(messageText));
- addSystemMessage(message, DefaultDirection);
- }
- }
- else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- std::vector<JID> invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
- onInviteToChat(invites);
- }
+ if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) {
+ if (event->mimeData()->urls().size() == 1) {
+ onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile()));
+ }
+ else {
+ std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time.")));
+ ChatMessage message;
+ message.append(boost::make_shared<ChatTextMessagePart>(messageText));
+ addSystemMessage(message, DefaultDirection);
+ }
+ }
+ else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ std::vector<JID> invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list"));
+ onInviteToChat(invites);
+ }
}
std::vector<JID> QtChatWindow::jidListFromQByteArray(const QByteArray& dataBytes) {
- QDataStream dataStream(dataBytes);
- std::vector<JID> invites;
- while (!dataStream.atEnd()) {
- QString jidString;
- dataStream >> jidString;
- invites.push_back(Q2PSTRING(jidString));
- }
- return invites;
+ QDataStream dataStream(dataBytes);
+ std::vector<JID> invites;
+ while (!dataStream.atEnd()) {
+ QString jidString;
+ dataStream >> jidString;
+ invites.push_back(Q2PSTRING(jidString));
+ }
+ return invites;
}
void QtChatWindow::setAvailableOccupantActions(const std::vector<OccupantAction>& actions) {
- treeWidget_->setAvailableOccupantActions(actions);
+ treeWidget_->setAvailableOccupantActions(actions);
}
void QtChatWindow::setSubject(const std::string& subject) {
- //subject_->setVisible(!subject.empty());
- subject_->setText(P2QSTRING(subject));
- subject_->setToolTip(P2QSTRING(subject));
- subject_->setCursorPosition(0);
+ //subject_->setVisible(!subject.empty());
+ subject_->setText(P2QSTRING(subject));
+ subject_->setToolTip(P2QSTRING(subject));
+ subject_->setCursorPosition(0);
}
void QtChatWindow::handleEmoticonsButtonClicked() {
- emoticonsMenu_->adjustSize();
- QSize menuSize = emoticonsMenu_->size();
- emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height()));
+ emoticonsMenu_->adjustSize();
+ QSize menuSize = emoticonsMenu_->size();
+ emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height()));
}
void QtChatWindow::handleEmoticonClicked(QString emoticonAsText) {
- input_->textCursor().insertText(emoticonAsText);
- input_->setFocus();
+ input_->textCursor().insertText(emoticonAsText);
+ input_->setFocus();
}
void QtChatWindow::handleTextInputReceivedFocus() {
- lastLineTracker_.setHasFocus(true);
- input_->setFocus();
- onAllMessagesRead();
+ lastLineTracker_.setHasFocus(true);
+ input_->setFocus();
+ onAllMessagesRead();
}
void QtChatWindow::handleTextInputLostFocus() {
- lastLineTracker_.setHasFocus(false);
+ lastLineTracker_.setHasFocus(false);
}
void QtChatWindow::handleActionButtonClicked() {
- QMenu contextMenu;
- QAction* changeSubject = NULL;
- QAction* configure = NULL;
- QAction* affiliations = NULL;
- QAction* destroy = NULL;
- QAction* invite = NULL;
-
- QAction* block = NULL;
- QAction* unblock = NULL;
-
- 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_)
- {
- 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_);
- break;
- }
- }
- }
-
- QAction* bookmark = NULL;
- if (isMUC_) {
- if (roomBookmarkState_ == RoomNotBookmarked) {
- bookmark = contextMenu.addAction(tr("Bookmark this room..."));
- }
- else {
- bookmark = contextMenu.addAction(tr("Edit bookmark..."));
- }
- bookmark->setEnabled(isOnline_);
- }
-
- QAction* result = contextMenu.exec(QCursor::pos());
- if (result == NULL) {
- /* Skip processing. Note that otherwise, because the actions could be null they could match */
- }
- else if (result == changeSubject) {
- bool ok;
- QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok);
- if (ok) {
- onChangeSubjectRequest(Q2PSTRING(subject));
- }
- }
- else if (result == configure) {
- onConfigureRequest(Form::ref());
- }
- else if (result == affiliations) {
- if (!affiliationEditor_) {
- onGetAffiliationsRequest();
- affiliationEditor_ = new QtAffiliationEditor(this);
- connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted()));
- }
- affiliationEditor_->show();
- }
- else if (result == destroy) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm room destruction"));
- msgBox.setText(tr("Are you sure you want to destroy the room?"));
- msgBox.setInformativeText(tr("This will destroy the room."));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- if (msgBox.exec() == QMessageBox::Yes) {
- onDestroyRequest();
- }
- }
- else if (result == invite) {
- onInviteToChat(std::vector<JID>());
- }
- else if (result == block) {
- onBlockUserRequest();
- }
- else if (result == unblock) {
- onUnblockUserRequest();
- }
- else if (result == bookmark) {
- onBookmarkRequest();
- }
+ QMenu contextMenu;
+ QAction* changeSubject = NULL;
+ QAction* configure = NULL;
+ QAction* affiliations = NULL;
+ QAction* destroy = NULL;
+ QAction* invite = NULL;
+
+ QAction* block = NULL;
+ QAction* unblock = NULL;
+
+ 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_)
+ {
+ 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_);
+ break;
+ }
+ }
+ }
+
+ QAction* bookmark = NULL;
+ if (isMUC_) {
+ if (roomBookmarkState_ == RoomNotBookmarked) {
+ bookmark = contextMenu.addAction(tr("Bookmark this room..."));
+ }
+ else {
+ bookmark = contextMenu.addAction(tr("Edit bookmark..."));
+ }
+ bookmark->setEnabled(isOnline_);
+ }
+
+ QAction* result = contextMenu.exec(QCursor::pos());
+ if (result == NULL) {
+ /* Skip processing. Note that otherwise, because the actions could be null they could match */
+ }
+ else if (result == changeSubject) {
+ bool ok;
+ QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok);
+ if (ok) {
+ onChangeSubjectRequest(Q2PSTRING(subject));
+ }
+ }
+ else if (result == configure) {
+ onConfigureRequest(Form::ref());
+ }
+ else if (result == affiliations) {
+ if (!affiliationEditor_) {
+ onGetAffiliationsRequest();
+ affiliationEditor_ = new QtAffiliationEditor(this);
+ connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted()));
+ }
+ affiliationEditor_->show();
+ }
+ else if (result == destroy) {
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm room destruction"));
+ msgBox.setText(tr("Are you sure you want to destroy the room?"));
+ msgBox.setInformativeText(tr("This will destroy the room."));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ if (msgBox.exec() == QMessageBox::Yes) {
+ onDestroyRequest();
+ }
+ }
+ else if (result == invite) {
+ onInviteToChat(std::vector<JID>());
+ }
+ else if (result == block) {
+ onBlockUserRequest();
+ }
+ else if (result == unblock) {
+ onUnblockUserRequest();
+ }
+ else if (result == bookmark) {
+ onBookmarkRequest();
+ }
}
void QtChatWindow::handleAffiliationEditorAccepted() {
- onChangeAffiliationsRequest(affiliationEditor_->getChanges());
+ onChangeAffiliationsRequest(affiliationEditor_->getChanges());
}
void QtChatWindow::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
- if (!affiliationEditor_) return;
- affiliationEditor_->setAffiliations(affiliation, jids);
+ if (!affiliationEditor_) return;
+ affiliationEditor_->setAffiliations(affiliation, jids);
}
void QtChatWindow::setAvailableRoomActions(const std::vector<RoomAction>& actions) {
- availableRoomActions_ = actions;
+ availableRoomActions_ = actions;
}
void QtChatWindow::setBlockingState(BlockingState state) {
- blockingState_ = state;
+ blockingState_ = state;
}
void QtChatWindow::setCanInitiateImpromptuChats(bool supportsImpromptu) {
- supportsImpromptuChat_ = supportsImpromptu;
+ supportsImpromptuChat_ = supportsImpromptu;
}
void QtChatWindow::showBookmarkWindow(const MUCBookmark& bookmark) {
- if (roomBookmarkState_ == RoomNotBookmarked) {
- QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark);
- window->show();
- }
- else {
- QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark);
- window->show();
- }
+ if (roomBookmarkState_ == RoomNotBookmarked) {
+ QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark);
+ window->show();
+ }
+ else {
+ QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark);
+ window->show();
+ }
}
std::string QtChatWindow::getID() const {
- return id_;
+ return id_;
}
void QtChatWindow::showRoomConfigurationForm(Form::ref form) {
- if (mucConfigurationWindow_) {
- delete mucConfigurationWindow_.data();
- }
- mucConfigurationWindow_ = new QtMUCConfigurationWindow(form);
- mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1));
- mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled)));
+ if (mucConfigurationWindow_) {
+ delete mucConfigurationWindow_.data();
+ }
+ mucConfigurationWindow_ = new QtMUCConfigurationWindow(form);
+ mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1));
+ mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled)));
}
void QtChatWindow::handleAppendedToLog() {
- if (lastLineTracker_.getShouldMoveLastLine()) {
- /* should this be queued? */
- messageLog_->addLastSeenLine();
- }
- if (isWidgetSelected()) {
- onAllMessagesRead();
- }
+ if (lastLineTracker_.getShouldMoveLastLine()) {
+ /* should this be queued? */
+ messageLog_->addLastSeenLine();
+ }
+ if (isWidgetSelected()) {
+ onAllMessagesRead();
+ }
}
void QtChatWindow::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) {
- handleAppendedToLog();
- messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation);
+ handleAppendedToLog();
+ messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation);
}
std::string QtChatWindow::addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time);
+ handleAppendedToLog();
+ return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time);
}
std::string QtChatWindow::addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time);
+ handleAppendedToLog();
+ return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time);
}
std::string QtChatWindow::addSystemMessage(const ChatMessage& message, Direction direction) {
- handleAppendedToLog();
- return messageLog_->addSystemMessage(message, direction);
+ handleAppendedToLog();
+ return messageLog_->addSystemMessage(message, direction);
}
void QtChatWindow::addPresenceMessage(const ChatMessage& message, Direction direction) {
- handleAppendedToLog();
- messageLog_->addPresenceMessage(message, direction);
+ handleAppendedToLog();
+ messageLog_->addPresenceMessage(message, direction);
}
void QtChatWindow::addErrorMessage(const ChatMessage& message) {
- handleAppendedToLog();
- messageLog_->addErrorMessage(message);
+ handleAppendedToLog();
+ messageLog_->addErrorMessage(message);
}
void QtChatWindow::replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- messageLog_->replaceMessage(message, id, time);
+ handleAppendedToLog();
+ messageLog_->replaceMessage(message, id, time);
}
void QtChatWindow::replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- handleAppendedToLog();
- messageLog_->replaceWithAction(message, id, time);
+ handleAppendedToLog();
+ messageLog_->replaceWithAction(message, id, time);
}
std::string QtChatWindow::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) {
- handleAppendedToLog();
- return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description);
+ handleAppendedToLog();
+ return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description);
}
void QtChatWindow::setFileTransferProgress(std::string id, const int percentageDone) {
- messageLog_->setFileTransferProgress(id, percentageDone);
+ messageLog_->setFileTransferProgress(id, percentageDone);
}
void QtChatWindow::setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg) {
- messageLog_->setFileTransferStatus(id, state, msg);
+ messageLog_->setFileTransferStatus(id, state, msg);
}
std::string QtChatWindow::addWhiteboardRequest(bool senderIsSelf) {
- handleAppendedToLog();
- return messageLog_->addWhiteboardRequest(contact_, senderIsSelf);
+ handleAppendedToLog();
+ return messageLog_->addWhiteboardRequest(contact_, senderIsSelf);
}
void QtChatWindow::setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) {
- messageLog_->setWhiteboardSessionStatus(id, state);
+ messageLog_->setWhiteboardSessionStatus(id, state);
}
void QtChatWindow::replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) {
- messageLog_->replaceLastMessage(message, timestampBehaviour);
+ messageLog_->replaceLastMessage(message, timestampBehaviour);
}
void QtChatWindow::setAckState(const std::string& id, AckState state) {
- messageLog_->setAckState(id, state);
+ messageLog_->setAckState(id, state);
}
void QtChatWindow::setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) {
- messageLog_->setMessageReceiptState(id, state);
+ messageLog_->setMessageReceiptState(id, state);
}
void QtChatWindow::setBookmarkState(RoomBookmarkState bookmarkState) {
- roomBookmarkState_ = bookmarkState;
+ roomBookmarkState_ = bookmarkState;
}
}
diff --git a/Swift/QtUI/QtChatWindow.h b/Swift/QtUI/QtChatWindow.h
index 8acb10c..2a23f5f 100644
--- a/Swift/QtUI/QtChatWindow.h
+++ b/Swift/QtUI/QtChatWindow.h
@@ -32,203 +32,203 @@ class QSplitter;
class QPushButton;
namespace Swift {
- class QtChatView;
- class QtOccupantListWidget;
- class QtChatTheme;
- class TreeWidget;
- class QtTextEdit;
- class UIEventStream;
- class QtChatWindowJSBridge;
- class SettingsProvider;
- class QtEmoticonsGrid;
-
- class LabelModel : public QAbstractListModel {
- Q_OBJECT
- public:
- LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {}
-
- virtual int rowCount(const QModelIndex& /*index*/) const {
- return static_cast<int>(availableLabels_.size());
- }
-
- virtual QVariant data(const QModelIndex& index, int role) const {
- if (!index.isValid()) {
- return QVariant();
- }
- boost::shared_ptr<SecurityLabel> label = availableLabels_[index.row()].getLabel();
- if (label && role == Qt::TextColorRole) {
- return P2QSTRING(label->getForegroundColor());
- }
- if (label && role == Qt::TextColorRole) {
- return P2QSTRING(label->getBackgroundColor());
- }
- if (role == Qt::DisplayRole) {
- std::string selector = availableLabels_[index.row()].getSelector();
- std::string displayMarking = label ? label->getDisplayMarking() : "";
- QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str();
- return labelName;
- }
- return QVariant();
- }
-
- std::vector<SecurityLabelsCatalog::Item> availableLabels_;
- };
-
- class QtChatWindow : public QtTabbable, public ChatWindow {
- Q_OBJECT
-
- public:
- QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons);
- virtual ~QtChatWindow();
- std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
- std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
-
- std::string addSystemMessage(const ChatMessage& message, Direction direction);
- void addPresenceMessage(const ChatMessage& message, Direction direction);
- void addErrorMessage(const ChatMessage& message);
-
- void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
- void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
- // File transfer related stuff
- std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description);
- void setFileTransferProgress(std::string id, const int percentageDone);
- void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg);
-
- std::string addWhiteboardRequest(bool senderIsSelf);
- void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state);
-
- void show();
- bool isVisible() const;
- void activate();
- void setUnreadMessageCount(int count);
- void convertToMUC(MUCType mucType);
-// TreeWidget *getTreeWidget();
- void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels);
- void setSecurityLabelsEnabled(bool enabled);
- void setSecurityLabelsError();
- SecurityLabelsCatalog::Item getSelectedSecurityLabel();
- void setName(const std::string& name);
- void setOnline(bool online);
- QtTabbable::AlertType getWidgetAlertState();
- void setContactChatState(ChatState::ChatStateType state);
- void setRosterModel(Roster* roster);
- void setTabComplete(TabComplete* completer);
- int getCount();
- virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour);
- void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour);
- void setAckState(const std::string& id, AckState state);
-
- // message receipts
- void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state);
-
- void flash();
- QByteArray getSplitterState();
- virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions);
- void setSubject(const std::string& subject);
- void showRoomConfigurationForm(Form::ref);
- void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false);
- void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&);
- void setAvailableRoomActions(const std::vector<RoomAction>& actions);
- void setBlockingState(BlockingState state);
- virtual void setCanInitiateImpromptuChats(bool supportsImpromptu);
- virtual void showBookmarkWindow(const MUCBookmark& bookmark);
- virtual void setBookmarkState(RoomBookmarkState bookmarkState);
- virtual std::string getID() const;
-
- public slots:
- void handleChangeSplitterState(QByteArray state);
- void handleFontResized(int fontSizeSteps);
- AlertID addAlert(const std::string& alertText);
- void removeAlert(const AlertID id);
- void setCorrectionEnabled(Tristate enabled);
- void setFileTransferEnabled(Tristate enabled);
-
- signals:
- void geometryChanged();
- void splitterMoved();
- void fontResized(int);
-
- protected slots:
- void closeEvent(QCloseEvent* event);
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
-
- void dragEnterEvent(QDragEnterEvent *event);
- void dropEvent(QDropEvent *event);
-
- protected:
- void showEvent(QShowEvent* event);
-
- private slots:
- void handleLogCleared();
- void returnPressed();
- void handleInputChanged();
- void handleCursorPositionChanged();
- void handleKeyPressEvent(QKeyEvent* event);
- void handleSplitterMoved(int pos, int index);
- void handleAlertButtonClicked();
- void handleActionButtonClicked();
- void handleAffiliationEditorAccepted();
- void handleCurrentLabelChanged(int);
- void handleEmoticonsButtonClicked();
- void handleEmoticonClicked(QString emoticonAsText);
- void handleTextInputReceivedFocus();
- void handleTextInputLostFocus();
-
- private:
- void updateTitleWithUnreadCount();
- void tabComplete();
- void beginCorrection();
- void cancelCorrection();
- void handleSettingChanged(const std::string& setting);
-
- void handleOccupantSelectionChanged(RosterItem* item);
- void handleAppendedToLog();
-
- static std::vector<JID> jidListFromQByteArray(const QByteArray& dataBytes);
-
- private:
- int unreadCount_;
- bool contactIsTyping_;
- LastLineTracker lastLineTracker_;
- std::string id_;
- QString contact_;
- QString lastSentMessage_;
- QTextCursor tabCompleteCursor_;
- QtChatView* messageLog_;
- QtChatTheme* theme_;
- QtTextEdit* input_;
- QWidget* midBar_;
- QBoxLayout* subjectLayout_;
- QComboBox* labelsWidget_;
- QtOccupantListWidget* treeWidget_;
- QLabel* correctingLabel_;
- boost::optional<AlertID> correctingAlert_;
- QVBoxLayout* alertLayout_;
- std::map<AlertID, QWidget*> alertWidgets_;
- AlertID nextAlertId_;
- TabComplete* completer_;
- QLineEdit* subject_;
- bool isCorrection_;
- bool inputClearing_;
- bool tabCompletion_;
- UIEventStream* eventStream_;
- bool isOnline_;
- QSplitter *logRosterSplitter_;
- Tristate correctionEnabled_;
- Tristate fileTransferEnabled_;
- QString alertStyleSheet_;
- QPointer<QtMUCConfigurationWindow> mucConfigurationWindow_;
- QPointer<QtAffiliationEditor> affiliationEditor_;
- SettingsProvider* settings_;
- std::vector<ChatWindow::RoomAction> availableRoomActions_;
- QPalette defaultLabelsPalette_;
- LabelModel* labelModel_;
- BlockingState blockingState_;
- bool impromptu_;
- bool isMUC_;
- bool supportsImpromptuChat_;
- RoomBookmarkState roomBookmarkState_;
- QMenu* emoticonsMenu_;
- };
+ class QtChatView;
+ class QtOccupantListWidget;
+ class QtChatTheme;
+ class TreeWidget;
+ class QtTextEdit;
+ class UIEventStream;
+ class QtChatWindowJSBridge;
+ class SettingsProvider;
+ class QtEmoticonsGrid;
+
+ class LabelModel : public QAbstractListModel {
+ Q_OBJECT
+ public:
+ LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {}
+
+ virtual int rowCount(const QModelIndex& /*index*/) const {
+ return static_cast<int>(availableLabels_.size());
+ }
+
+ virtual QVariant data(const QModelIndex& index, int role) const {
+ if (!index.isValid()) {
+ return QVariant();
+ }
+ boost::shared_ptr<SecurityLabel> label = availableLabels_[index.row()].getLabel();
+ if (label && role == Qt::TextColorRole) {
+ return P2QSTRING(label->getForegroundColor());
+ }
+ if (label && role == Qt::TextColorRole) {
+ return P2QSTRING(label->getBackgroundColor());
+ }
+ if (role == Qt::DisplayRole) {
+ std::string selector = availableLabels_[index.row()].getSelector();
+ std::string displayMarking = label ? label->getDisplayMarking() : "";
+ QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str();
+ return labelName;
+ }
+ return QVariant();
+ }
+
+ std::vector<SecurityLabelsCatalog::Item> availableLabels_;
+ };
+
+ class QtChatWindow : public QtTabbable, public ChatWindow {
+ Q_OBJECT
+
+ public:
+ QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map<std::string, std::string>& emoticons);
+ virtual ~QtChatWindow();
+ std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
+ std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time);
+
+ std::string addSystemMessage(const ChatMessage& message, Direction direction);
+ void addPresenceMessage(const ChatMessage& message, Direction direction);
+ void addErrorMessage(const ChatMessage& message);
+
+ void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
+ void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time);
+ // File transfer related stuff
+ std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description);
+ void setFileTransferProgress(std::string id, const int percentageDone);
+ void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg);
+
+ std::string addWhiteboardRequest(bool senderIsSelf);
+ void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state);
+
+ void show();
+ bool isVisible() const;
+ void activate();
+ void setUnreadMessageCount(int count);
+ void convertToMUC(MUCType mucType);
+// TreeWidget *getTreeWidget();
+ void setAvailableSecurityLabels(const std::vector<SecurityLabelsCatalog::Item>& labels);
+ void setSecurityLabelsEnabled(bool enabled);
+ void setSecurityLabelsError();
+ SecurityLabelsCatalog::Item getSelectedSecurityLabel();
+ void setName(const std::string& name);
+ void setOnline(bool online);
+ QtTabbable::AlertType getWidgetAlertState();
+ void setContactChatState(ChatState::ChatStateType state);
+ void setRosterModel(Roster* roster);
+ void setTabComplete(TabComplete* completer);
+ int getCount();
+ virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour);
+ void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour);
+ void setAckState(const std::string& id, AckState state);
+
+ // message receipts
+ void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state);
+
+ void flash();
+ QByteArray getSplitterState();
+ virtual void setAvailableOccupantActions(const std::vector<OccupantAction>& actions);
+ void setSubject(const std::string& subject);
+ void showRoomConfigurationForm(Form::ref);
+ void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false);
+ void setAffiliations(MUCOccupant::Affiliation, const std::vector<JID>&);
+ void setAvailableRoomActions(const std::vector<RoomAction>& actions);
+ void setBlockingState(BlockingState state);
+ virtual void setCanInitiateImpromptuChats(bool supportsImpromptu);
+ virtual void showBookmarkWindow(const MUCBookmark& bookmark);
+ virtual void setBookmarkState(RoomBookmarkState bookmarkState);
+ virtual std::string getID() const;
+
+ public slots:
+ void handleChangeSplitterState(QByteArray state);
+ void handleFontResized(int fontSizeSteps);
+ AlertID addAlert(const std::string& alertText);
+ void removeAlert(const AlertID id);
+ void setCorrectionEnabled(Tristate enabled);
+ void setFileTransferEnabled(Tristate enabled);
+
+ signals:
+ void geometryChanged();
+ void splitterMoved();
+ void fontResized(int);
+
+ protected slots:
+ void closeEvent(QCloseEvent* event);
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+
+ void dragEnterEvent(QDragEnterEvent *event);
+ void dropEvent(QDropEvent *event);
+
+ protected:
+ void showEvent(QShowEvent* event);
+
+ private slots:
+ void handleLogCleared();
+ void returnPressed();
+ void handleInputChanged();
+ void handleCursorPositionChanged();
+ void handleKeyPressEvent(QKeyEvent* event);
+ void handleSplitterMoved(int pos, int index);
+ void handleAlertButtonClicked();
+ void handleActionButtonClicked();
+ void handleAffiliationEditorAccepted();
+ void handleCurrentLabelChanged(int);
+ void handleEmoticonsButtonClicked();
+ void handleEmoticonClicked(QString emoticonAsText);
+ void handleTextInputReceivedFocus();
+ void handleTextInputLostFocus();
+
+ private:
+ void updateTitleWithUnreadCount();
+ void tabComplete();
+ void beginCorrection();
+ void cancelCorrection();
+ void handleSettingChanged(const std::string& setting);
+
+ void handleOccupantSelectionChanged(RosterItem* item);
+ void handleAppendedToLog();
+
+ static std::vector<JID> jidListFromQByteArray(const QByteArray& dataBytes);
+
+ private:
+ int unreadCount_;
+ bool contactIsTyping_;
+ LastLineTracker lastLineTracker_;
+ std::string id_;
+ QString contact_;
+ QString lastSentMessage_;
+ QTextCursor tabCompleteCursor_;
+ QtChatView* messageLog_;
+ QtChatTheme* theme_;
+ QtTextEdit* input_;
+ QWidget* midBar_;
+ QBoxLayout* subjectLayout_;
+ QComboBox* labelsWidget_;
+ QtOccupantListWidget* treeWidget_;
+ QLabel* correctingLabel_;
+ boost::optional<AlertID> correctingAlert_;
+ QVBoxLayout* alertLayout_;
+ std::map<AlertID, QWidget*> alertWidgets_;
+ AlertID nextAlertId_;
+ TabComplete* completer_;
+ QLineEdit* subject_;
+ bool isCorrection_;
+ bool inputClearing_;
+ bool tabCompletion_;
+ UIEventStream* eventStream_;
+ bool isOnline_;
+ QSplitter *logRosterSplitter_;
+ Tristate correctionEnabled_;
+ Tristate fileTransferEnabled_;
+ QString alertStyleSheet_;
+ QPointer<QtMUCConfigurationWindow> mucConfigurationWindow_;
+ QPointer<QtAffiliationEditor> affiliationEditor_;
+ SettingsProvider* settings_;
+ std::vector<ChatWindow::RoomAction> availableRoomActions_;
+ QPalette defaultLabelsPalette_;
+ LabelModel* labelModel_;
+ BlockingState blockingState_;
+ bool impromptu_;
+ bool isMUC_;
+ bool supportsImpromptuChat_;
+ RoomBookmarkState roomBookmarkState_;
+ QMenu* emoticonsMenu_;
+ };
}
diff --git a/Swift/QtUI/QtChatWindowFactory.cpp b/Swift/QtUI/QtChatWindowFactory.cpp
index 019eb21..a97fd7c 100644
--- a/Swift/QtUI/QtChatWindowFactory.cpp
+++ b/Swift/QtUI/QtChatWindowFactory.cpp
@@ -23,65 +23,65 @@ static const QString SPLITTER_STATE = "mucSplitterState";
static const QString CHAT_TABS_GEOMETRY = "chatTabsGeometry";
QtChatWindowFactory::QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons) : themePath_(themePath), emoticons_(emoticons) {
- qtOnlySettings_ = qtSettings;
- settings_ = settings;
- tabs_ = tabs;
- theme_ = NULL;
- QtChatTabs* fullTabs = dynamic_cast<QtChatTabs*>(tabs_);
- if (splitter) {
- assert(fullTabs && "Netbook mode and no-tabs interface is not supported!");
- splitter->addWidget(fullTabs);
- } else if (fullTabs) {
- QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
- if (chatTabsGeometryVariant.isValid()) {
- fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray());
- }
- connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
- }
+ qtOnlySettings_ = qtSettings;
+ settings_ = settings;
+ tabs_ = tabs;
+ theme_ = NULL;
+ QtChatTabs* fullTabs = dynamic_cast<QtChatTabs*>(tabs_);
+ if (splitter) {
+ assert(fullTabs && "Netbook mode and no-tabs interface is not supported!");
+ splitter->addWidget(fullTabs);
+ } else if (fullTabs) {
+ QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
+ if (chatTabsGeometryVariant.isValid()) {
+ fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray());
+ }
+ connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
+ }
}
QtChatWindowFactory::~QtChatWindowFactory() {
- delete theme_;
+ delete theme_;
}
ChatWindow* QtChatWindowFactory::createChatWindow(const JID &contact,UIEventStream* eventStream) {
- if (!theme_) {
- theme_ = new QtChatTheme(themePath_);
- if (theme_->getIncomingContent().isEmpty()) {
- delete theme_;
- theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */
- }
- }
+ if (!theme_) {
+ theme_ = new QtChatTheme(themePath_);
+ if (theme_->getIncomingContent().isEmpty()) {
+ delete theme_;
+ theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */
+ }
+ }
- QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_);
- connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved()));
- connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray)));
+ QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_);
+ connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved()));
+ connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray)));
- QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE);
- if(splitterState.isValid()) {
- chatWindow->handleChangeSplitterState(splitterState.toByteArray());
- }
+ QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE);
+ if(splitterState.isValid()) {
+ chatWindow->handleChangeSplitterState(splitterState.toByteArray());
+ }
- if (tabs_) {
- tabs_->addTab(chatWindow);
- } else {
- QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
- if (chatGeometryVariant.isValid()) {
- chatWindow->restoreGeometry(chatGeometryVariant.toByteArray());
- }
- connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
- }
- return chatWindow;
+ if (tabs_) {
+ tabs_->addTab(chatWindow);
+ } else {
+ QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY);
+ if (chatGeometryVariant.isValid()) {
+ chatWindow->restoreGeometry(chatGeometryVariant.toByteArray());
+ }
+ connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged()));
+ }
+ return chatWindow;
}
void QtChatWindowFactory::handleWindowGeometryChanged() {
- qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast<QWidget*>(sender())->saveGeometry());
+ qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast<QWidget*>(sender())->saveGeometry());
}
void QtChatWindowFactory::handleSplitterMoved() {
- QByteArray splitterState = qobject_cast<QtChatWindow*>(sender())->getSplitterState();
- qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState));
- emit changeSplitterState(splitterState);
+ QByteArray splitterState = qobject_cast<QtChatWindow*>(sender())->getSplitterState();
+ qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState));
+ emit changeSplitterState(splitterState);
}
}
diff --git a/Swift/QtUI/QtChatWindowFactory.h b/Swift/QtUI/QtChatWindowFactory.h
index 6b1f0a1..29bc5bc 100644
--- a/Swift/QtUI/QtChatWindowFactory.h
+++ b/Swift/QtUI/QtChatWindowFactory.h
@@ -19,29 +19,29 @@
#include <Swift/QtUI/QtSettingsProvider.h>
namespace Swift {
- class QtChatTabsBase;
- class QtChatTheme;
- class UIEventStream;
- class QtUIPreferences;
- class QtSingleWindow;
- class QtChatWindowFactory : public QObject, public ChatWindowFactory {
- Q_OBJECT
- public:
- QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons);
- ~QtChatWindowFactory();
- ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
- signals:
- void changeSplitterState(QByteArray);
- private slots:
- void handleWindowGeometryChanged();
- void handleSplitterMoved();
- private:
- QString themePath_;
- SettingsProvider* settings_;
- QtSettingsProvider* qtOnlySettings_;
- QtChatTabsBase* tabs_;
- QtChatTheme* theme_;
- std::map<std::string, std::string> emoticons_;
- };
+ class QtChatTabsBase;
+ class QtChatTheme;
+ class UIEventStream;
+ class QtUIPreferences;
+ class QtSingleWindow;
+ class QtChatWindowFactory : public QObject, public ChatWindowFactory {
+ Q_OBJECT
+ public:
+ QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map<std::string, std::string>& emoticons);
+ ~QtChatWindowFactory();
+ ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
+ signals:
+ void changeSplitterState(QByteArray);
+ private slots:
+ void handleWindowGeometryChanged();
+ void handleSplitterMoved();
+ private:
+ QString themePath_;
+ SettingsProvider* settings_;
+ QtSettingsProvider* qtOnlySettings_;
+ QtChatTabsBase* tabs_;
+ QtChatTheme* theme_;
+ std::map<std::string, std::string> emoticons_;
+ };
}
diff --git a/Swift/QtUI/QtChatWindowJSBridge.cpp b/Swift/QtUI/QtChatWindowJSBridge.cpp
index fa6f906..3030689 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.cpp
+++ b/Swift/QtUI/QtChatWindowJSBridge.cpp
@@ -15,11 +15,11 @@
namespace Swift {
QtChatWindowJSBridge::QtChatWindowJSBridge() {
-
+
}
QtChatWindowJSBridge::~QtChatWindowJSBridge() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatWindowJSBridge.h b/Swift/QtUI/QtChatWindowJSBridge.h
index db01abb..bedf6a4 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.h
+++ b/Swift/QtUI/QtChatWindowJSBridge.h
@@ -21,12 +21,12 @@ namespace Swift {
class FileTransferController;
class QtChatWindowJSBridge : public QObject {
- Q_OBJECT
+ Q_OBJECT
public:
- QtChatWindowJSBridge();
- virtual ~QtChatWindowJSBridge();
+ QtChatWindowJSBridge();
+ virtual ~QtChatWindowJSBridge();
signals:
- void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
+ void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
};
}
diff --git a/Swift/QtUI/QtClickableLabel.cpp b/Swift/QtUI/QtClickableLabel.cpp
index 3749cfe..7ce3325 100644
--- a/Swift/QtUI/QtClickableLabel.cpp
+++ b/Swift/QtUI/QtClickableLabel.cpp
@@ -12,7 +12,7 @@ QtClickableLabel::QtClickableLabel(QWidget* parent) : QLabel(parent) {
}
void QtClickableLabel::mousePressEvent(QMouseEvent*) {
- emit clicked();
+ emit clicked();
}
}
diff --git a/Swift/QtUI/QtClickableLabel.h b/Swift/QtUI/QtClickableLabel.h
index deaf646..83ed3f1 100644
--- a/Swift/QtUI/QtClickableLabel.h
+++ b/Swift/QtUI/QtClickableLabel.h
@@ -9,14 +9,14 @@
#include <QLabel>
namespace Swift {
- class QtClickableLabel : public QLabel {
- Q_OBJECT
- public:
- QtClickableLabel(QWidget* parent);
+ class QtClickableLabel : public QLabel {
+ Q_OBJECT
+ public:
+ QtClickableLabel(QWidget* parent);
- void mousePressEvent(QMouseEvent* event);
+ void mousePressEvent(QMouseEvent* event);
- signals:
- void clicked();
- };
+ signals:
+ void clicked();
+ };
}
diff --git a/Swift/QtUI/QtClosableLineEdit.cpp b/Swift/QtUI/QtClosableLineEdit.cpp
index 414463a..033db78 100644
--- a/Swift/QtUI/QtClosableLineEdit.cpp
+++ b/Swift/QtUI/QtClosableLineEdit.cpp
@@ -27,40 +27,40 @@ namespace Swift {
const int QtClosableLineEdit::clearButtonPadding = 2;
QtClosableLineEdit::QtClosableLineEdit(QWidget *parent) : QLineEdit(parent) {
- clearButton = new QToolButton(this);
- clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
- clearButton->setIconSize(QSize(16,16));
- clearButton->setCursor(Qt::ArrowCursor);
- clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
- clearButton->hide();
- connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked()));
- connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
- int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
- QSize minimumSize = minimumSizeHint();
- setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding),
- qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding));
+ clearButton = new QToolButton(this);
+ clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
+ clearButton->setIconSize(QSize(16,16));
+ clearButton->setCursor(Qt::ArrowCursor);
+ clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
+ clearButton->hide();
+ connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked()));
+ connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
+ int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
+ QSize minimumSize = minimumSizeHint();
+ setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding),
+ qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding));
}
void QtClosableLineEdit::resizeEvent(QResizeEvent *) {
- QSize size = clearButton->sizeHint();
- int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- int verticalAdjustment = 1;
+ QSize size = clearButton->sizeHint();
+ int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
+ int verticalAdjustment = 1;
#if defined(Q_OS_WIN32)
- // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit.
- verticalAdjustment += 2;
-#endif
- clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2);
+ // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit.
+ verticalAdjustment += 2;
+#endif
+ clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2);
}
void QtClosableLineEdit::updateCloseButton(const QString& text) {
- clearButton->setVisible(!text.isEmpty());
+ clearButton->setVisible(!text.isEmpty());
}
void QtClosableLineEdit::handleCloseButtonClicked() {
- clear();
- QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier));
- QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier));
+ clear();
+ QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier));
+ QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier));
}
}
diff --git a/Swift/QtUI/QtClosableLineEdit.h b/Swift/QtUI/QtClosableLineEdit.h
index da9f5a8..206851b 100644
--- a/Swift/QtUI/QtClosableLineEdit.h
+++ b/Swift/QtUI/QtClosableLineEdit.h
@@ -24,20 +24,20 @@ namespace Swift {
class QtClosableLineEdit : public QLineEdit
{
- Q_OBJECT
- public:
- QtClosableLineEdit(QWidget *parent = 0);
+ Q_OBJECT
+ public:
+ QtClosableLineEdit(QWidget *parent = 0);
- protected:
- void resizeEvent(QResizeEvent *);
+ protected:
+ void resizeEvent(QResizeEvent *);
- private slots:
- void updateCloseButton(const QString &text);
- void handleCloseButtonClicked();
+ private slots:
+ void updateCloseButton(const QString &text);
+ void handleCloseButtonClicked();
- private:
- static const int clearButtonPadding;
- QToolButton *clearButton;
+ private:
+ static const int clearButtonPadding;
+ QToolButton *clearButton;
};
}
diff --git a/Swift/QtUI/QtColorToolButton.cpp b/Swift/QtUI/QtColorToolButton.cpp
index a91fe0e..b349a47 100644
--- a/Swift/QtUI/QtColorToolButton.cpp
+++ b/Swift/QtUI/QtColorToolButton.cpp
@@ -18,34 +18,34 @@
namespace Swift {
QtColorToolButton::QtColorToolButton(QWidget* parent) :
- QToolButton(parent)
+ QToolButton(parent)
{
- connect(this, SIGNAL(clicked()), SLOT(onClicked()));
- setColorIcon(Qt::transparent);
+ connect(this, SIGNAL(clicked()), SLOT(onClicked()));
+ setColorIcon(Qt::transparent);
}
void QtColorToolButton::setColor(const QColor& color)
{
- if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) {
- color_ = color;
- setColorIcon(color_);
- emit colorChanged(color_);
- }
+ if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) {
+ color_ = color;
+ setColorIcon(color_);
+ emit colorChanged(color_);
+ }
}
void QtColorToolButton::onClicked()
{
- QColor c = QColorDialog::getColor(color_, this);
- if (c.isValid()) {
- setColor(c);
- }
+ QColor c = QColorDialog::getColor(color_, this);
+ if (c.isValid()) {
+ setColor(c);
+ }
}
void QtColorToolButton::setColorIcon(const QColor& color)
{
- QPixmap pix(iconSize());
- pix.fill(color.isValid() ? color : Qt::transparent);
- setIcon(pix);
+ QPixmap pix(iconSize());
+ pix.fill(color.isValid() ? color : Qt::transparent);
+ setIcon(pix);
}
}
diff --git a/Swift/QtUI/QtColorToolButton.h b/Swift/QtUI/QtColorToolButton.h
index 33d195d..5260048 100644
--- a/Swift/QtUI/QtColorToolButton.h
+++ b/Swift/QtUI/QtColorToolButton.h
@@ -10,23 +10,23 @@
namespace Swift {
- class QtColorToolButton : public QToolButton {
- Q_OBJECT
- Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
- public:
- explicit QtColorToolButton(QWidget* parent = NULL);
- void setColor(const QColor& color);
- const QColor& getColor() const { return color_; }
-
- signals:
- void colorChanged(const QColor&);
-
- private slots:
- void onClicked();
-
- private:
- void setColorIcon(const QColor& color);
- QColor color_;
- };
+ class QtColorToolButton : public QToolButton {
+ Q_OBJECT
+ Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
+ public:
+ explicit QtColorToolButton(QWidget* parent = NULL);
+ void setColor(const QColor& color);
+ const QColor& getColor() const { return color_; }
+
+ signals:
+ void colorChanged(const QColor&);
+
+ private slots:
+ void onClicked();
+
+ private:
+ void setColorIcon(const QColor& color);
+ QColor color_;
+ };
}
diff --git a/Swift/QtUI/QtConnectionSettingsWindow.cpp b/Swift/QtUI/QtConnectionSettingsWindow.cpp
index 940625b..a58bc5c 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.cpp
+++ b/Swift/QtUI/QtConnectionSettingsWindow.cpp
@@ -25,147 +25,147 @@
namespace Swift {
QtConnectionSettingsWindow::QtConnectionSettingsWindow(const ClientOptions& options) : QDialog() {
- ui.setupUi(this);
-
- connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int)));
-
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool)));
-
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool)));
- connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool)));
-
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool)));
- connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool)));
-
- connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int)));
-
- connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested()));
-
- QtURLValidator* urlValidator = new QtURLValidator(this);
- ui.bosh_uri->setValidator(urlValidator);
-
- ui.manual_useTLS->setCurrentIndex(2);
-
- ui.manual_proxyType->setCurrentIndex(0);
-
- ClientOptions defaults;
- if (options.boshURL.isEmpty()) {
- bool isDefault = options.useStreamCompression == defaults.useStreamCompression;
- isDefault &= options.useTLS == defaults.useTLS;
- isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS;
- isDefault &= options.useStreamCompression == defaults.useStreamCompression;
- isDefault &= options.useAcks == defaults.useAcks;
- isDefault &= options.manualHostname == defaults.manualHostname;
- isDefault &= options.manualPort == defaults.manualPort;
- isDefault &= options.proxyType == defaults.proxyType;
- isDefault &= options.manualProxyHostname == defaults.manualProxyHostname;
- isDefault &= options.manualProxyPort == defaults.manualProxyPort;
- isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround;
- if (isDefault) {
- ui.connectionMethod->setCurrentIndex(0);
- }
- else {
- ui.connectionMethod->setCurrentIndex(1);
- ui.manual_useTLS->setCurrentIndex(options.useTLS);
- ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS);
- ui.manual_allowCompression->setChecked(options.useStreamCompression);
- if (!options.manualHostname.empty()) {
- ui.manual_manualHost->setChecked(true);
- ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname));
- if (options.manualPort >=0) {
- ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualPort)));
- }
- }
- ui.manual_proxyType->setCurrentIndex(options.proxyType);
- if (!options.manualProxyHostname.empty()) {
- ui.manual_manualProxy->setChecked(true);
- ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname));
- ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualProxyPort)));
- }
- ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround);
- }
- } else {
- ui.connectionMethod->setCurrentIndex(2);
- ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString()));
- if (!options.boshHTTPConnectProxyURL.isEmpty()) {
- ui.bosh_manualProxy->setChecked(true);
- ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost()));
- if (options.boshHTTPConnectProxyURL.getPort()) {
- ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(*options.boshHTTPConnectProxyURL.getPort())));
- }
- }
- }
+ ui.setupUi(this);
+
+ connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int)));
+
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool)));
+
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool)));
+
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool)));
+ connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool)));
+
+ connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int)));
+
+ connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested()));
+
+ QtURLValidator* urlValidator = new QtURLValidator(this);
+ ui.bosh_uri->setValidator(urlValidator);
+
+ ui.manual_useTLS->setCurrentIndex(2);
+
+ ui.manual_proxyType->setCurrentIndex(0);
+
+ ClientOptions defaults;
+ if (options.boshURL.isEmpty()) {
+ bool isDefault = options.useStreamCompression == defaults.useStreamCompression;
+ isDefault &= options.useTLS == defaults.useTLS;
+ isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS;
+ isDefault &= options.useStreamCompression == defaults.useStreamCompression;
+ isDefault &= options.useAcks == defaults.useAcks;
+ isDefault &= options.manualHostname == defaults.manualHostname;
+ isDefault &= options.manualPort == defaults.manualPort;
+ isDefault &= options.proxyType == defaults.proxyType;
+ isDefault &= options.manualProxyHostname == defaults.manualProxyHostname;
+ isDefault &= options.manualProxyPort == defaults.manualProxyPort;
+ isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround;
+ if (isDefault) {
+ ui.connectionMethod->setCurrentIndex(0);
+ }
+ else {
+ ui.connectionMethod->setCurrentIndex(1);
+ ui.manual_useTLS->setCurrentIndex(options.useTLS);
+ ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS);
+ ui.manual_allowCompression->setChecked(options.useStreamCompression);
+ if (!options.manualHostname.empty()) {
+ ui.manual_manualHost->setChecked(true);
+ ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname));
+ if (options.manualPort >=0) {
+ ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualPort)));
+ }
+ }
+ ui.manual_proxyType->setCurrentIndex(options.proxyType);
+ if (!options.manualProxyHostname.empty()) {
+ ui.manual_manualProxy->setChecked(true);
+ ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname));
+ ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(options.manualProxyPort)));
+ }
+ ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround);
+ }
+ } else {
+ ui.connectionMethod->setCurrentIndex(2);
+ ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString()));
+ if (!options.boshHTTPConnectProxyURL.isEmpty()) {
+ ui.bosh_manualProxy->setChecked(true);
+ ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost()));
+ if (options.boshHTTPConnectProxyURL.getPort()) {
+ ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast<std::string>(*options.boshHTTPConnectProxyURL.getPort())));
+ }
+ }
+ }
#ifndef HAVE_SCHANNEL
- ui.manual_forceTLS1_0->hide();
+ ui.manual_forceTLS1_0->hide();
#endif
}
void QtConnectionSettingsWindow::handleProxyTypeChanged(int index) {
- bool proxySettingsVisible = index != NoProxy && index != SystemProxy;
- ui.manual_manualProxy->setVisible(proxySettingsVisible);
- ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible);
- ui.manual_manualProxyHost->setVisible(proxySettingsVisible);
- ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible);
- ui.manual_manualProxyPort->setVisible(proxySettingsVisible);
+ bool proxySettingsVisible = index != NoProxy && index != SystemProxy;
+ ui.manual_manualProxy->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyHost->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible);
+ ui.manual_manualProxyPort->setVisible(proxySettingsVisible);
}
void QtConnectionSettingsWindow::handleAcceptRequested() {
- if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) {
- accept();
- }
- else {
- QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid."));
- }
+ if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) {
+ accept();
+ }
+ else {
+ QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid."));
+ }
}
ClientOptions QtConnectionSettingsWindow::getOptions() {
- ClientOptions options;
- if (ui.connectionMethod->currentIndex() > 0) {
- /* Not automatic */
- if (ui.connectionMethod->currentIndex() == 1) {
- /* Manual */
- options.useTLS = static_cast<ClientOptions::UseTLS>(ui.manual_useTLS->currentIndex());
- options.useStreamCompression = ui.manual_allowCompression->isChecked();
- options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked();
- options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked();
- if (ui.manual_manualHost->isChecked()) {
- options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text());
- try {
- options.manualPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualHostPort->text()));
- } catch (const boost::bad_lexical_cast&) {
- options.manualPort = -1;
- }
- }
- options.proxyType = static_cast<ClientOptions::ProxyType>(ui.manual_proxyType->currentIndex());
- if (ui.manual_manualProxy->isChecked()) {
- options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text());
- try {
- options.manualProxyPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualProxyPort->text()));
- } catch (const boost::bad_lexical_cast&) {}
- }
- }
- else {
- /* BOSH */
- options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text()));
- if (ui.bosh_manualProxy->isChecked()) {
- std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text());
- try {
- int port = boost::lexical_cast<int>(Q2PSTRING(ui.bosh_manualProxyPort->text()));
- options.boshHTTPConnectProxyURL = URL("http", host, port, "");
- } catch (const boost::bad_lexical_cast&) {
- options.boshHTTPConnectProxyURL = URL("http", host, "");
- }
- }
- }
- }
- return options;
+ ClientOptions options;
+ if (ui.connectionMethod->currentIndex() > 0) {
+ /* Not automatic */
+ if (ui.connectionMethod->currentIndex() == 1) {
+ /* Manual */
+ options.useTLS = static_cast<ClientOptions::UseTLS>(ui.manual_useTLS->currentIndex());
+ options.useStreamCompression = ui.manual_allowCompression->isChecked();
+ options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked();
+ options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked();
+ if (ui.manual_manualHost->isChecked()) {
+ options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text());
+ try {
+ options.manualPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualHostPort->text()));
+ } catch (const boost::bad_lexical_cast&) {
+ options.manualPort = -1;
+ }
+ }
+ options.proxyType = static_cast<ClientOptions::ProxyType>(ui.manual_proxyType->currentIndex());
+ if (ui.manual_manualProxy->isChecked()) {
+ options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text());
+ try {
+ options.manualProxyPort = boost::lexical_cast<int>(Q2PSTRING(ui.manual_manualProxyPort->text()));
+ } catch (const boost::bad_lexical_cast&) {}
+ }
+ }
+ else {
+ /* BOSH */
+ options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text()));
+ if (ui.bosh_manualProxy->isChecked()) {
+ std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text());
+ try {
+ int port = boost::lexical_cast<int>(Q2PSTRING(ui.bosh_manualProxyPort->text()));
+ options.boshHTTPConnectProxyURL = URL("http", host, port, "");
+ } catch (const boost::bad_lexical_cast&) {
+ options.boshHTTPConnectProxyURL = URL("http", host, "");
+ }
+ }
+ }
+ }
+ return options;
}
}
diff --git a/Swift/QtUI/QtConnectionSettingsWindow.h b/Swift/QtUI/QtConnectionSettingsWindow.h
index a1d4739..f9fad84 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.h
+++ b/Swift/QtUI/QtConnectionSettingsWindow.h
@@ -13,25 +13,25 @@
#include <Swift/QtUI/ui_QtConnectionSettings.h>
namespace Swift {
- class QtConnectionSettingsWindow : public QDialog {
- Q_OBJECT
-
- public:
- QtConnectionSettingsWindow(const ClientOptions& options);
-
- ClientOptions getOptions();
-
- private slots:
- void handleProxyTypeChanged(int);
- void handleAcceptRequested();
-
- private:
- enum {
- NoProxy = 0,
- SystemProxy = 1,
- SOCKS5Proxy = 2,
- HTTPProxy = 3
- };
- Ui::QtConnectionSettings ui;
- };
+ class QtConnectionSettingsWindow : public QDialog {
+ Q_OBJECT
+
+ public:
+ QtConnectionSettingsWindow(const ClientOptions& options);
+
+ ClientOptions getOptions();
+
+ private slots:
+ void handleProxyTypeChanged(int);
+ void handleAcceptRequested();
+
+ private:
+ enum {
+ NoProxy = 0,
+ SystemProxy = 1,
+ SOCKS5Proxy = 2,
+ HTTPProxy = 3
+ };
+ Ui::QtConnectionSettings ui;
+ };
}
diff --git a/Swift/QtUI/QtContactEditWidget.cpp b/Swift/QtUI/QtContactEditWidget.cpp
index ad02bf9..ced9157 100644
--- a/Swift/QtUI/QtContactEditWidget.cpp
+++ b/Swift/QtUI/QtContactEditWidget.cpp
@@ -21,155 +21,155 @@
namespace Swift {
QtContactEditWidget::QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent) : QWidget(parent), nameRadioButton_(NULL), groups_(NULL) {
- 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) {
- 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));
+ 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) {
+ 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));
+ 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) {
- if (button->isChecked()) {
- if (button == nameRadioButton_) {
- name = Q2PSTRING(name_->text());
- } else {
- name = singleAmpersand(button->text());
- }
- break;
- }
- }
- return name;
+ std::string name = Q2PSTRING(name_->text());
+ QList<QRadioButton*> buttons = findChildren<QRadioButton*>();
+ foreach(const QRadioButton* 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) {
- checkBoxes_[group]->setCheckState(Qt::Checked);
- }
+ foreach (std::string 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_) {
- 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;
+ std::set<std::string> groups;
+ foreach(const CheckBoxMap::value_type& 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 = NULL;
- 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) {
- suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
- }
-
- nameRadioButton_ = new QRadioButton(tr("Name:"), this);
- suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
-
- QRadioButton* suggestedRadioButton = 0;
- QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
- foreach (QRadioButton* candidate, radioButtons) {
- if (candidate->text() == name_->text()) {
- suggestedRadioButton = candidate;
- break;
- }
- }
- if (suggestedRadioButton) {
- suggestedRadioButton->setChecked(true);
- } else {
- nameRadioButton_->setChecked(true);
- }
+ throbberLabel_->movie()->stop();
+ throbberLabel_->hide();
+
+ // remove old suggestions except for the user input text field
+ QLayoutItem* suggestionItem = NULL;
+ 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) {
+ suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
+ }
+
+ nameRadioButton_ = new QRadioButton(tr("Name:"), this);
+ suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
+
+ QRadioButton* suggestedRadioButton = 0;
+ QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
+ foreach (QRadioButton* 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("&", "&&");
+ return P2QSTRING(name).replace("&", "&&");
}
std::string QtContactEditWidget::singleAmpersand(const QString& name) const {
- return Q2PSTRING(QString(name).replace("&&", "&"));
+ 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
- while(suggestionsLayout_->count() != 0) {
- QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0);
- delete layoutItem->widget();
- delete layoutItem;
- }
- nameRadioButton_ = NULL;
+ name_->clear();
+ setSelectedGroups(std::vector<std::string>());
+ newGroup_->setChecked(false);
+ newGroupName_->clear();
+ throbberLabel_->movie()->start();
+ throbberLabel_->show();
+
+ // clear suggestions
+ while(suggestionsLayout_->count() != 0) {
+ QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0);
+ delete layoutItem->widget();
+ delete layoutItem;
+ }
+ nameRadioButton_ = NULL;
}
}
diff --git a/Swift/QtUI/QtContactEditWidget.h b/Swift/QtUI/QtContactEditWidget.h
index a9f1305..5c081e9 100644
--- a/Swift/QtUI/QtContactEditWidget.h
+++ b/Swift/QtUI/QtContactEditWidget.h
@@ -22,37 +22,37 @@ 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_;
- QHBoxLayout* nameLayout_;
- QHBoxLayout* suggestionsLayout_;
- QRadioButton* nameRadioButton_;
- QLineEdit* name_;
- QWidget* groups_;
- QCheckBox* newGroup_;
- QLineEdit* newGroupName_;
- QLabel* throbberLabel_;
- };
+ 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_;
+ QHBoxLayout* nameLayout_;
+ QHBoxLayout* suggestionsLayout_;
+ QRadioButton* nameRadioButton_;
+ QLineEdit* name_;
+ QWidget* groups_;
+ QCheckBox* newGroup_;
+ QLineEdit* newGroupName_;
+ QLabel* throbberLabel_;
+ };
}
diff --git a/Swift/QtUI/QtContactEditWindow.cpp b/Swift/QtUI/QtContactEditWindow.cpp
index abd247a..214f256 100644
--- a/Swift/QtUI/QtContactEditWindow.cpp
+++ b/Swift/QtUI/QtContactEditWindow.cpp
@@ -24,84 +24,84 @@
namespace Swift {
QtContactEditWindow::QtContactEditWindow() : contactEditWidget_(NULL) {
- resize(400,300);
- setWindowTitle(tr("Edit contact"));
- setContentsMargins(0,0,0,0);
-
- QBoxLayout* layout = new QVBoxLayout(this);
-
- jidLabel_ = new QLabel(this);
- jidLabel_->setAlignment(Qt::AlignHCenter);
- layout->addWidget(jidLabel_);
-
- groupsLayout_ = new QVBoxLayout();
- groupsLayout_->setContentsMargins(0,0,0,0);
- layout->addLayout(groupsLayout_);
-
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- layout->addLayout(buttonLayout);
- QPushButton* removeButton = new QPushButton(tr("Remove contact"), this);
- connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact()));
- buttonLayout->addWidget(removeButton);
- QPushButton* okButton = new QPushButton(tr("OK"), this);
- okButton->setDefault( true );
- connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact()));
- buttonLayout->addStretch();
- buttonLayout->addWidget(okButton);
+ resize(400,300);
+ setWindowTitle(tr("Edit contact"));
+ setContentsMargins(0,0,0,0);
+
+ QBoxLayout* layout = new QVBoxLayout(this);
+
+ jidLabel_ = new QLabel(this);
+ jidLabel_->setAlignment(Qt::AlignHCenter);
+ layout->addWidget(jidLabel_);
+
+ groupsLayout_ = new QVBoxLayout();
+ groupsLayout_->setContentsMargins(0,0,0,0);
+ layout->addLayout(groupsLayout_);
+
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ layout->addLayout(buttonLayout);
+ QPushButton* removeButton = new QPushButton(tr("Remove contact"), this);
+ connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact()));
+ buttonLayout->addWidget(removeButton);
+ QPushButton* okButton = new QPushButton(tr("OK"), this);
+ okButton->setDefault( true );
+ connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact()));
+ buttonLayout->addStretch();
+ buttonLayout->addWidget(okButton);
}
QtContactEditWindow::~QtContactEditWindow() {
}
void QtContactEditWindow::setNameSuggestions(const std::vector<std::string>& nameSuggestions) {
- if (contactEditWidget_) {
- contactEditWidget_->setNameSuggestions(nameSuggestions);
- }
+ if (contactEditWidget_) {
+ contactEditWidget_->setNameSuggestions(nameSuggestions);
+ }
}
void QtContactEditWindow::setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups) {
- delete contactEditWidget_;
- jid_ = jid;
- jidLabel_->setText("<b>" + P2QSTRING(jid.toString()) + "</b>");
-
- contactEditWidget_ = new QtContactEditWidget(allGroups, this);
- groupsLayout_->addWidget(contactEditWidget_);
- contactEditWidget_->setName(name);
- contactEditWidget_->setSelectedGroups(groups);
+ delete contactEditWidget_;
+ jid_ = jid;
+ jidLabel_->setText("<b>" + P2QSTRING(jid.toString()) + "</b>");
+
+ contactEditWidget_ = new QtContactEditWidget(allGroups, this);
+ groupsLayout_->addWidget(contactEditWidget_);
+ contactEditWidget_->setName(name);
+ contactEditWidget_->setSelectedGroups(groups);
}
void QtContactEditWindow::setEnabled(bool b) {
- QWidget::setEnabled(b);
+ QWidget::setEnabled(b);
}
void QtContactEditWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtContactEditWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
void QtContactEditWindow::handleRemoveContact() {
- if (confirmContactDeletion(jid_)) {
- onRemoveContactRequest();
- }
+ if (confirmContactDeletion(jid_)) {
+ onRemoveContactRequest();
+ }
}
bool QtContactEditWindow::confirmContactDeletion(const JID& jid) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm contact deletion"));
- msgBox.setText(tr("Are you sure you want to delete this contact?"));
- msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString())));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::Yes);
- return msgBox.exec() == QMessageBox::Yes;
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm contact deletion"));
+ msgBox.setText(tr("Are you sure you want to delete this contact?"));
+ msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString())));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::Yes);
+ return msgBox.exec() == QMessageBox::Yes;
}
void QtContactEditWindow::handleUpdateContact() {
- onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups());
+ onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups());
}
}
diff --git a/Swift/QtUI/QtContactEditWindow.h b/Swift/QtUI/QtContactEditWindow.h
index a6c73b9..655fbb4 100644
--- a/Swift/QtUI/QtContactEditWindow.h
+++ b/Swift/QtUI/QtContactEditWindow.h
@@ -19,33 +19,33 @@ class QLabel;
class QVBoxLayout;
namespace Swift {
- class QtContactEditWidget;
+ class QtContactEditWidget;
- class QtContactEditWindow : public QWidget, public ContactEditWindow {
- Q_OBJECT
+ class QtContactEditWindow : public QWidget, public ContactEditWindow {
+ Q_OBJECT
- public:
- QtContactEditWindow();
- virtual ~QtContactEditWindow();
+ public:
+ QtContactEditWindow();
+ virtual ~QtContactEditWindow();
- virtual void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
- virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups);
+ virtual void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
+ virtual void setContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, const std::set<std::string>& allGroups);
- void setEnabled(bool);
- void show();
- void hide();
+ void setEnabled(bool);
+ void show();
+ void hide();
- static bool confirmContactDeletion(const JID& jid);
+ static bool confirmContactDeletion(const JID& jid);
- private slots:
- void handleRemoveContact();
- void handleUpdateContact();
+ private slots:
+ void handleRemoveContact();
+ void handleUpdateContact();
- private:
- JID jid_;
- QVBoxLayout* groupsLayout_;
- QLabel* jidLabel_;
- QtContactEditWidget* contactEditWidget_;
- };
+ private:
+ JID jid_;
+ QVBoxLayout* groupsLayout_;
+ QLabel* jidLabel_;
+ QtContactEditWidget* contactEditWidget_;
+ };
}
diff --git a/Swift/QtUI/QtDBUSURIHandler.cpp b/Swift/QtUI/QtDBUSURIHandler.cpp
index 71a7016..c873676 100644
--- a/Swift/QtUI/QtDBUSURIHandler.cpp
+++ b/Swift/QtUI/QtDBUSURIHandler.cpp
@@ -14,28 +14,28 @@
using namespace Swift;
namespace {
- class DBUSAdaptor: public QDBusAbstractAdaptor {
- Q_OBJECT
- Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler");
- public:
- DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) {
- }
-
- public slots:
- void openURI(const QString& uri) {
- uriHandler->onURI(Q2PSTRING(uri));
- }
-
- private:
- QtDBUSURIHandler* uriHandler;
- };
+ class DBUSAdaptor: public QDBusAbstractAdaptor {
+ Q_OBJECT
+ Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler");
+ public:
+ DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) {
+ }
+
+ public slots:
+ void openURI(const QString& uri) {
+ uriHandler->onURI(Q2PSTRING(uri));
+ }
+
+ private:
+ QtDBUSURIHandler* uriHandler;
+ };
}
QtDBUSURIHandler::QtDBUSURIHandler() {
- new DBUSAdaptor(this);
- QDBusConnection connection = QDBusConnection::sessionBus();
- connection.registerService("im.swift.Swift.URIHandler");
- connection.registerObject("/", this);
+ new DBUSAdaptor(this);
+ QDBusConnection connection = QDBusConnection::sessionBus();
+ connection.registerService("im.swift.Swift.URIHandler");
+ connection.registerObject("/", this);
}
#include "QtDBUSURIHandler.moc"
diff --git a/Swift/QtUI/QtDBUSURIHandler.h b/Swift/QtUI/QtDBUSURIHandler.h
index cb16892..3cd12f7 100644
--- a/Swift/QtUI/QtDBUSURIHandler.h
+++ b/Swift/QtUI/QtDBUSURIHandler.h
@@ -11,8 +11,8 @@
#include <SwifTools/URIHandler/URIHandler.h>
namespace Swift {
- class QtDBUSURIHandler : public QObject, public URIHandler {
- public:
- QtDBUSURIHandler();
- };
+ class QtDBUSURIHandler : public QObject, public URIHandler {
+ public:
+ QtDBUSURIHandler();
+ };
}
diff --git a/Swift/QtUI/QtEditBookmarkWindow.cpp b/Swift/QtUI/QtEditBookmarkWindow.cpp
index 756e377..a17b1aa 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.cpp
+++ b/Swift/QtUI/QtEditBookmarkWindow.cpp
@@ -10,20 +10,20 @@
namespace Swift {
QtEditBookmarkWindow::QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream), bookmark_(bookmark) {
- name_->setText(P2QSTRING(bookmark.getName()));
- room_->setText(P2QSTRING(bookmark.getRoom().toString()));
- autojoin_->setChecked(bookmark.getAutojoin());
- nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : "");
- password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : "");
+ name_->setText(P2QSTRING(bookmark.getName()));
+ room_->setText(P2QSTRING(bookmark.getRoom().toString()));
+ autojoin_->setChecked(bookmark.getAutojoin());
+ nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : "");
+ password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : "");
}
bool QtEditBookmarkWindow::commit() {
- boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
- if (!bookmark) {
- return false;
- }
- eventStream_->send(boost::shared_ptr<UIEvent>(new EditMUCBookmarkUIEvent(bookmark_, *bookmark)));
- return true;
+ boost::optional<MUCBookmark> bookmark = createBookmarkFromForm();
+ if (!bookmark) {
+ return false;
+ }
+ eventStream_->send(boost::shared_ptr<UIEvent>(new EditMUCBookmarkUIEvent(bookmark_, *bookmark)));
+ return true;
}
}
diff --git a/Swift/QtUI/QtEditBookmarkWindow.h b/Swift/QtUI/QtEditBookmarkWindow.h
index 1d7d08b..337ba1f 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.h
+++ b/Swift/QtUI/QtEditBookmarkWindow.h
@@ -12,14 +12,14 @@
#include <Swift/QtUI/QtBookmarkDetailWindow.h>
namespace Swift {
- class QtEditBookmarkWindow : public QtBookmarkDetailWindow {
- Q_OBJECT
- public:
- QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
- bool commit();
-
- private:
- UIEventStream* eventStream_;
- MUCBookmark bookmark_;
- };
+ class QtEditBookmarkWindow : public QtBookmarkDetailWindow {
+ Q_OBJECT
+ public:
+ QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark);
+ bool commit();
+
+ private:
+ UIEventStream* eventStream_;
+ MUCBookmark bookmark_;
+ };
}
diff --git a/Swift/QtUI/QtElidingLabel.cpp b/Swift/QtUI/QtElidingLabel.cpp
index f5a39f0..4707f9f 100644
--- a/Swift/QtUI/QtElidingLabel.cpp
+++ b/Swift/QtUI/QtElidingLabel.cpp
@@ -8,17 +8,17 @@
namespace Swift {
QtElidingLabel::QtElidingLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f) {
- fullText_ = "";
- dirty_ = true;
- setSizes();
- setTextFormat(Qt::PlainText);
+ fullText_ = "";
+ dirty_ = true;
+ setSizes();
+ setTextFormat(Qt::PlainText);
}
QtElidingLabel::QtElidingLabel(const QString& text, QWidget* parent, Qt::WindowFlags f) : QLabel(text, parent, f) {
- fullText_ = text;
- dirty_ = true;
- setSizes();
- setTextFormat(Qt::PlainText);
+ fullText_ = text;
+ dirty_ = true;
+ setSizes();
+ setTextFormat(Qt::PlainText);
}
QtElidingLabel::~QtElidingLabel() {
@@ -26,35 +26,35 @@ QtElidingLabel::~QtElidingLabel() {
}
QSize QtElidingLabel::sizeHint() const {
- return sizeHint_;
+ return sizeHint_;
}
void QtElidingLabel::setSizes() {
- setMinimumSize(1, minimumHeight());
+ setMinimumSize(1, minimumHeight());
}
void QtElidingLabel::setText(const QString& text) {
- fullText_ = text;
- QLabel::setText(text);
- sizeHint_ = QLabel::sizeHint();
- dirty_ = true;
+ fullText_ = text;
+ QLabel::setText(text);
+ sizeHint_ = QLabel::sizeHint();
+ dirty_ = true;
}
void QtElidingLabel::paintEvent(QPaintEvent* event) {
- QRect rect = contentsRect();
- dirty_ = dirty_ || rect != lastRect_;
- if (dirty_) {
- lastRect_ = rect;
- int fontWidth = fontMetrics().width(fullText_);
- if (fontWidth > rect.width()) {
- QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic));
- QLabel::setText(elidedText);
- } else {
- QLabel::setText(fullText_);
- }
- dirty_ = false;
- }
- QLabel::paintEvent(event);
+ QRect rect = contentsRect();
+ dirty_ = dirty_ || rect != lastRect_;
+ if (dirty_) {
+ lastRect_ = rect;
+ int fontWidth = fontMetrics().width(fullText_);
+ if (fontWidth > rect.width()) {
+ QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic));
+ QLabel::setText(elidedText);
+ } else {
+ QLabel::setText(fullText_);
+ }
+ dirty_ = false;
+ }
+ QLabel::paintEvent(event);
}
}
diff --git a/Swift/QtUI/QtElidingLabel.h b/Swift/QtUI/QtElidingLabel.h
index 84fa00f..9f590a8 100644
--- a/Swift/QtUI/QtElidingLabel.h
+++ b/Swift/QtUI/QtElidingLabel.h
@@ -9,23 +9,23 @@
#include <QLabel>
namespace Swift {
- class QtElidingLabel : public QLabel {
- Q_OBJECT
- public:
- QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0);
- QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0);
- void setText(const QString& text);
- virtual ~QtElidingLabel();
-
- virtual QSize sizeHint() const;
+ class QtElidingLabel : public QLabel {
+ Q_OBJECT
+ public:
+ QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0);
+ QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0);
+ void setText(const QString& text);
+ virtual ~QtElidingLabel();
- virtual void paintEvent(QPaintEvent* event);
+ virtual QSize sizeHint() const;
- private:
- void setSizes();
- bool dirty_;
- QString fullText_;
- QRect lastRect_;
- QSize sizeHint_;
- };
+ virtual void paintEvent(QPaintEvent* event);
+
+ private:
+ void setSizes();
+ bool dirty_;
+ QString fullText_;
+ QRect lastRect_;
+ QSize sizeHint_;
+ };
}
diff --git a/Swift/QtUI/QtEmoticonCell.cpp b/Swift/QtUI/QtEmoticonCell.cpp
index a781876..fe580aa 100644
--- a/Swift/QtUI/QtEmoticonCell.cpp
+++ b/Swift/QtUI/QtEmoticonCell.cpp
@@ -15,11 +15,11 @@
namespace Swift {
QtEmoticonCell::QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent) : QLabel(parent), emoticonAsText_(emoticonAsText) {
- if (filePath.startsWith("qrc:/")) {
- filePath.remove(0, 3);
- }
- setPixmap(QPixmap(filePath));
- setToolTip(emoticonAsText_);
+ if (filePath.startsWith("qrc:/")) {
+ filePath.remove(0, 3);
+ }
+ setPixmap(QPixmap(filePath));
+ setToolTip(emoticonAsText_);
}
QtEmoticonCell::~QtEmoticonCell() {
@@ -27,8 +27,8 @@ QtEmoticonCell::~QtEmoticonCell() {
}
void QtEmoticonCell::mousePressEvent (QMouseEvent* event) {
- emit emoticonClicked(emoticonAsText_);
- QLabel::mousePressEvent(event);
+ emit emoticonClicked(emoticonAsText_);
+ QLabel::mousePressEvent(event);
}
}
diff --git a/Swift/QtUI/QtEmoticonCell.h b/Swift/QtUI/QtEmoticonCell.h
index 379f5d6..e408a83 100644
--- a/Swift/QtUI/QtEmoticonCell.h
+++ b/Swift/QtUI/QtEmoticonCell.h
@@ -18,17 +18,17 @@ class QMouseEvent;
namespace Swift {
- class QtEmoticonCell : public QLabel {
- Q_OBJECT
- public:
- QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0);
- ~QtEmoticonCell();
- virtual void mousePressEvent(QMouseEvent* event);
-
- signals:
- void emoticonClicked(QString emoticonAsText);
-
- private:
- QString emoticonAsText_;
- };
+ class QtEmoticonCell : public QLabel {
+ Q_OBJECT
+ public:
+ QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0);
+ ~QtEmoticonCell();
+ virtual void mousePressEvent(QMouseEvent* event);
+
+ signals:
+ void emoticonClicked(QString emoticonAsText);
+
+ private:
+ QString emoticonAsText_;
+ };
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.cpp b/Swift/QtUI/QtEmoticonsGrid.cpp
index 82fb7e8..a81f516 100644
--- a/Swift/QtUI/QtEmoticonsGrid.cpp
+++ b/Swift/QtUI/QtEmoticonsGrid.cpp
@@ -25,23 +25,23 @@ 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_) {
- 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++;
- }
- }
+ makeUniqueEmoticonsMap(emoticons);
+
+ // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows
+ int row = 0;
+ int column = 0;
+
+ foreach(EmoticonsMap::value_type 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() {
@@ -49,17 +49,17 @@ 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) {
- if (paths.find(emoticon.second) == paths.end()) {
- uniqueEmoticons_.insert(emoticon);
- paths.insert(emoticon.second);
- }
- }
+ std::set<std::string> paths;
+ reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) {
+ if (paths.find(emoticon.second) == paths.end()) {
+ uniqueEmoticons_.insert(emoticon);
+ paths.insert(emoticon.second);
+ }
+ }
}
void QtEmoticonsGrid::emoticonClickedSlot(QString emoticonAsText) {
- emit emoticonClicked(emoticonAsText);
+ emit emoticonClicked(emoticonAsText);
}
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.h b/Swift/QtUI/QtEmoticonsGrid.h
index b045b26..0cae9ab 100644
--- a/Swift/QtUI/QtEmoticonsGrid.h
+++ b/Swift/QtUI/QtEmoticonsGrid.h
@@ -20,21 +20,21 @@ class QWidget;
namespace Swift {
- class QtEmoticonsGrid : public QGridLayout {
- Q_OBJECT
- public:
- explicit QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent = 0);
- virtual ~QtEmoticonsGrid();
+ class QtEmoticonsGrid : public QGridLayout {
+ Q_OBJECT
+ public:
+ explicit QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent = 0);
+ virtual ~QtEmoticonsGrid();
- signals:
- void emoticonClicked(QString emoticonAsText);
+ signals:
+ void emoticonClicked(QString emoticonAsText);
- public slots:
- void emoticonClickedSlot(QString emoticonAsText);
+ public slots:
+ void emoticonClickedSlot(QString emoticonAsText);
- private:
- void makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons);
+ private:
+ void makeUniqueEmoticonsMap(const std::map<std::string, std::string>& emoticons);
- std::map<std::string, std::string> uniqueEmoticons_;
- };
+ std::map<std::string, std::string> uniqueEmoticons_;
+ };
}
diff --git a/Swift/QtUI/QtFileTransferListItemModel.cpp b/Swift/QtUI/QtFileTransferListItemModel.cpp
index ef73f4f..d26733b 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.cpp
+++ b/Swift/QtUI/QtFileTransferListItemModel.cpp
@@ -29,115 +29,115 @@ QtFileTransferListItemModel::QtFileTransferListItemModel(QObject *parent) : QAbs
}
QtFileTransferListItemModel::~QtFileTransferListItemModel() {
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
}
void QtFileTransferListItemModel::setFileTransferOverview(FileTransferOverview *overview) {
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
- fileTransferOverview = overview;
- if (fileTransferOverview) {
- fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
- fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
- }
- emit layoutAboutToBeChanged();
- emit layoutChanged();
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
+ fileTransferOverview = overview;
+ if (fileTransferOverview) {
+ fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1));
+ fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this));
+ }
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
}
void QtFileTransferListItemModel::handleNewFileTransferController(FileTransferController* newController) {
- emit layoutAboutToBeChanged();
- emit layoutChanged();
- dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4));
- newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1));
- newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1));
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
+ dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4));
+ newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1));
+ newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1));
}
void QtFileTransferListItemModel::handleFileTransferListChanged() {
- emit layoutAboutToBeChanged();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ emit layoutChanged();
}
void QtFileTransferListItemModel::handleStateChange(int index) {
- emit dataChanged(createIndex(index, 2), createIndex(index, 2));
+ emit dataChanged(createIndex(index, 2), createIndex(index, 2));
}
void QtFileTransferListItemModel::handleProgressChange(int index) {
- emit dataChanged(createIndex(index, 3), createIndex(index, 3));
+ emit dataChanged(createIndex(index, 3), createIndex(index, 3));
}
QVariant QtFileTransferListItemModel::headerData(int section, Qt::Orientation /* orientation */, int role) const {
- if (role != Qt::DisplayRole) return QVariant();
- if (section == Direction) return QVariant(QObject::tr("Direction"));
- if (section == OtherParty) return QVariant(QObject::tr("Other Party"));
- if (section == State) return QVariant(QObject::tr("State"));
- if (section == Progress) return QVariant(QObject::tr("Progress"));
- if (section == OverallSize) return QVariant(QObject::tr("Size"));
- return QVariant();
+ if (role != Qt::DisplayRole) return QVariant();
+ if (section == Direction) return QVariant(QObject::tr("Direction"));
+ if (section == OtherParty) return QVariant(QObject::tr("Other Party"));
+ if (section == State) return QVariant(QObject::tr("State"));
+ if (section == Progress) return QVariant(QObject::tr("Progress"));
+ if (section == OverallSize) return QVariant(QObject::tr("Size"));
+ return QVariant();
}
int QtFileTransferListItemModel::columnCount(const QModelIndex& /* parent */) const {
- return NoOfColumns;
+ return NoOfColumns;
}
QVariant QtFileTransferListItemModel::data(const QModelIndex &index, int role) const {
- if (role != Qt::DisplayRole || !index.isValid() ||
- !fileTransferOverview || static_cast<size_t>(index.row()) >= fileTransferOverview->getFileTransfers().size()) {
- return QVariant();
- }
- FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row());
- if (index.column() == Direction) {
- return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing"));
- }
- if (index.column() == OtherParty) {
- return QVariant(P2QSTRING(controller->getOtherParty().toString()));
- }
- if (index.column() == State) {
- FileTransfer::State state = controller->getState();
- switch(state.type) {
- case FileTransfer::State::Initial:
- assert(false);
- return QVariant("");
- case FileTransfer::State::WaitingForStart:
- return QVariant(QObject::tr("Waiting for start"));
- case FileTransfer::State::WaitingForAccept:
- return QVariant(QObject::tr("Waiting for other side to accept"));
- case FileTransfer::State::Negotiating:
- return QVariant(QObject::tr("Negotiating"));
- case FileTransfer::State::Transferring:
- return QVariant(QObject::tr("Transferring"));
- case FileTransfer::State::Finished:
- return QVariant(QObject::tr("Finished"));
- case FileTransfer::State::Failed:
- return QVariant(QObject::tr("Failed"));
- case FileTransfer::State::Canceled:
- return QVariant(QObject::tr("Canceled"));
- }
- }
-
- if (index.column() == Progress) {
- return QVariant(QString::number(controller->getProgress()));
- }
- if (index.column() == OverallSize) {
- return QVariant(P2QSTRING(formatSize((controller->getSize()))));
- }
- return QVariant();
+ if (role != Qt::DisplayRole || !index.isValid() ||
+ !fileTransferOverview || static_cast<size_t>(index.row()) >= fileTransferOverview->getFileTransfers().size()) {
+ return QVariant();
+ }
+ FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row());
+ if (index.column() == Direction) {
+ return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing"));
+ }
+ if (index.column() == OtherParty) {
+ return QVariant(P2QSTRING(controller->getOtherParty().toString()));
+ }
+ if (index.column() == State) {
+ FileTransfer::State state = controller->getState();
+ switch(state.type) {
+ case FileTransfer::State::Initial:
+ assert(false);
+ return QVariant("");
+ case FileTransfer::State::WaitingForStart:
+ return QVariant(QObject::tr("Waiting for start"));
+ case FileTransfer::State::WaitingForAccept:
+ return QVariant(QObject::tr("Waiting for other side to accept"));
+ case FileTransfer::State::Negotiating:
+ return QVariant(QObject::tr("Negotiating"));
+ case FileTransfer::State::Transferring:
+ return QVariant(QObject::tr("Transferring"));
+ case FileTransfer::State::Finished:
+ return QVariant(QObject::tr("Finished"));
+ case FileTransfer::State::Failed:
+ return QVariant(QObject::tr("Failed"));
+ case FileTransfer::State::Canceled:
+ return QVariant(QObject::tr("Canceled"));
+ }
+ }
+
+ if (index.column() == Progress) {
+ return QVariant(QString::number(controller->getProgress()));
+ }
+ if (index.column() == OverallSize) {
+ return QVariant(P2QSTRING(formatSize((controller->getSize()))));
+ }
+ return QVariant();
}
QModelIndex QtFileTransferListItemModel::parent(const QModelIndex& /* child */) const {
- return createIndex(0,0);
+ return createIndex(0,0);
}
int QtFileTransferListItemModel::rowCount(const QModelIndex& /* parent */) const {
- return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0;
+ return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0;
}
QModelIndex QtFileTransferListItemModel::index(int row, int column, const QModelIndex& /* parent */) const {
- return createIndex(row, column, static_cast<void*>(0));
+ return createIndex(row, column, static_cast<void*>(0));
}
}
diff --git a/Swift/QtUI/QtFileTransferListItemModel.h b/Swift/QtUI/QtFileTransferListItemModel.h
index 64cdca4..d0e0e42 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.h
+++ b/Swift/QtUI/QtFileTransferListItemModel.h
@@ -20,42 +20,42 @@ class FileTransferController;
class FileTransferOverview;
class QtFileTransferListItemModel : public QAbstractItemModel {
- Q_OBJECT
+ Q_OBJECT
public:
- explicit QtFileTransferListItemModel(QObject *parent = 0);
- virtual ~QtFileTransferListItemModel();
+ explicit QtFileTransferListItemModel(QObject *parent = 0);
+ virtual ~QtFileTransferListItemModel();
- void setFileTransferOverview(FileTransferOverview*);
+ void setFileTransferOverview(FileTransferOverview*);
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- int columnCount(const QModelIndex &parent) const;
- QVariant data(const QModelIndex &index, int role) const;
- QModelIndex parent(const QModelIndex &child) const;
- int rowCount(const QModelIndex &parent) const;
- QModelIndex index(int row, int column, const QModelIndex &parent) const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ int columnCount(const QModelIndex &parent) const;
+ QVariant data(const QModelIndex &index, int role) const;
+ QModelIndex parent(const QModelIndex &child) const;
+ int rowCount(const QModelIndex &parent) const;
+ QModelIndex index(int row, int column, const QModelIndex &parent) const;
private:
- enum Columns {
- Direction = 0,
- OtherParty,
- State,
- Progress,
- OverallSize,
- NoOfColumns
- };
+ enum Columns {
+ Direction = 0,
+ OtherParty,
+ State,
+ Progress,
+ OverallSize,
+ NoOfColumns
+ };
private:
- void handleNewFileTransferController(FileTransferController*);
- void handleFileTransferListChanged();
- void handleStateChange(int index);
- void handleProgressChange(int index);
+ void handleNewFileTransferController(FileTransferController*);
+ void handleFileTransferListChanged();
+ void handleStateChange(int index);
+ void handleProgressChange(int index);
signals:
public slots:
private:
- FileTransferOverview *fileTransferOverview;
+ FileTransferOverview *fileTransferOverview;
};
diff --git a/Swift/QtUI/QtFileTransferListWidget.cpp b/Swift/QtUI/QtFileTransferListWidget.cpp
index d95cd06..f67b510 100644
--- a/Swift/QtUI/QtFileTransferListWidget.cpp
+++ b/Swift/QtUI/QtFileTransferListWidget.cpp
@@ -26,86 +26,86 @@
namespace Swift {
QtFileTransferListWidget::QtFileTransferListWidget() : fileTransferOverview(0) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setSpacing(0);
- layout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setSpacing(0);
+ layout->setContentsMargins(0,0,0,0);
- treeView = new QTreeView(this);
- treeView->setRootIsDecorated(false);
- treeView->setItemsExpandable(false);
- layout->addWidget(treeView);
+ treeView = new QTreeView(this);
+ treeView->setRootIsDecorated(false);
+ treeView->setItemsExpandable(false);
+ layout->addWidget(treeView);
- itemModel = new QtFileTransferListItemModel();
- treeView->setModel(itemModel);
+ itemModel = new QtFileTransferListItemModel();
+ treeView->setModel(itemModel);
- QWidget* bottom = new QWidget(this);
- layout->addWidget(bottom);
- bottom->setAutoFillBackground(true);
+ QWidget* bottom = new QWidget(this);
+ layout->addWidget(bottom);
+ bottom->setAutoFillBackground(true);
- QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
- buttonLayout->setContentsMargins(10,0,20,0);
- buttonLayout->setSpacing(0);
+ QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
+ buttonLayout->setContentsMargins(10,0,20,0);
+ buttonLayout->setSpacing(0);
- clearFinished = new QPushButton(tr("Clear all"), bottom);
- clearFinished->setEnabled(false);
- connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers()));
- buttonLayout->addWidget(clearFinished);
+ clearFinished = new QPushButton(tr("Clear all"), bottom);
+ clearFinished->setEnabled(false);
+ connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers()));
+ buttonLayout->addWidget(clearFinished);
- setWindowTitle(tr("File Transfer List"));
- emit titleUpdated();
+ setWindowTitle(tr("File Transfer List"));
+ emit titleUpdated();
}
QtFileTransferListWidget::~QtFileTransferListWidget() {
- if (fileTransferOverview) {
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- fileTransferOverview = NULL;
- }
- delete itemModel;
+ if (fileTransferOverview) {
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ fileTransferOverview = NULL;
+ }
+ delete itemModel;
}
void QtFileTransferListWidget::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated(); /* This just needs to be somewhere after construction */
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated(); /* This just needs to be somewhere after construction */
+ QWidget::showEvent(event);
}
void QtFileTransferListWidget::handleFileTransferListChanged() {
- clearFinished->setEnabled(fileTransferOverview->isClearable());
+ clearFinished->setEnabled(fileTransferOverview->isClearable());
}
void QtFileTransferListWidget::clearInactiveTransfers() {
- fileTransferOverview->clearFinished();
+ fileTransferOverview->clearFinished();
}
void QtFileTransferListWidget::show() {
- QWidget::show();
- emit windowOpening();
+ QWidget::show();
+ emit windowOpening();
}
void QtFileTransferListWidget::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtFileTransferListWidget::setFileTransferOverview(FileTransferOverview *overview) {
- if (fileTransferOverview) {
- fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- fileTransferOverview = NULL;
- }
- if (overview) {
- fileTransferOverview = overview;
- fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
- clearFinished->setEnabled(fileTransferOverview->isClearable());
- }
- itemModel->setFileTransferOverview(overview);
+ if (fileTransferOverview) {
+ fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ fileTransferOverview = NULL;
+ }
+ if (overview) {
+ fileTransferOverview = overview;
+ fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this));
+ clearFinished->setEnabled(fileTransferOverview->isClearable());
+ }
+ itemModel->setFileTransferOverview(overview);
}
std::string QtFileTransferListWidget::getID() const {
- return "QtFileTransferListWidget";
+ return "QtFileTransferListWidget";
}
void QtFileTransferListWidget::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
}
diff --git a/Swift/QtUI/QtFileTransferListWidget.h b/Swift/QtUI/QtFileTransferListWidget.h
index 740eb15..cfc7dd2 100644
--- a/Swift/QtUI/QtFileTransferListWidget.h
+++ b/Swift/QtUI/QtFileTransferListWidget.h
@@ -27,33 +27,33 @@ class FileTransferOverview;
class QtFileTransferListItemModel;
class QtFileTransferListWidget : public QtTabbable, public FileTransferListWidget {
- Q_OBJECT
+ Q_OBJECT
public:
- QtFileTransferListWidget();
- virtual ~QtFileTransferListWidget();
+ QtFileTransferListWidget();
+ virtual ~QtFileTransferListWidget();
- void show();
- void activate();
+ void show();
+ void activate();
- void setFileTransferOverview(FileTransferOverview *);
+ void setFileTransferOverview(FileTransferOverview *);
- virtual std::string getID() const;
+ virtual std::string getID() const;
private:
- virtual void closeEvent(QCloseEvent* event);
- virtual void showEvent(QShowEvent* event);
- void handleFileTransferListChanged();
+ virtual void closeEvent(QCloseEvent* event);
+ virtual void showEvent(QShowEvent* event);
+ void handleFileTransferListChanged();
private slots:
- void clearInactiveTransfers();
+ void clearInactiveTransfers();
private:
- QTreeView* treeView;
+ QTreeView* treeView;
- QtFileTransferListItemModel* itemModel;
- FileTransferOverview* fileTransferOverview;
- QPushButton* clearFinished;
+ QtFileTransferListItemModel* itemModel;
+ FileTransferOverview* fileTransferOverview;
+ QPushButton* clearFinished;
};
}
diff --git a/Swift/QtUI/QtFormResultItemModel.cpp b/Swift/QtUI/QtFormResultItemModel.cpp
index 6a48bc5..60cf0c0 100644
--- a/Swift/QtUI/QtFormResultItemModel.cpp
+++ b/Swift/QtUI/QtFormResultItemModel.cpp
@@ -29,67 +29,67 @@ QtFormResultItemModel::QtFormResultItemModel(QObject* parent, Form::ref formResu
}
void QtFormResultItemModel::setForm(Form::ref formResult) {
- emit layoutAboutToBeChanged();
- formResult_ = formResult;
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ formResult_ = formResult;
+ emit layoutChanged();
}
const Form::ref QtFormResultItemModel::getForm() const {
- return formResult_;
+ 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()));
+ 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();
+ if (!formResult_) return 0;
+ return formResult_->getItems().size();
}
int QtFormResultItemModel::columnCount(const QModelIndex &/*parent*/) const {
- if (!formResult_) return 0;
- return formResult_->getReportedFields().size();
+ 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 (!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();
+ 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());
+ Form::FormItem item = formResult_->getItems().at(index.row());
- return QVariant(P2QSTRING(getFieldValue(item, index.column())));
+ 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) {
- 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 "";
+ // determine field name
+ std::string name = formResult_->getReportedFields().at(column)->getName();
+
+ foreach(FormField::ref 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/QtFormResultItemModel.h b/Swift/QtUI/QtFormResultItemModel.h
index f383f74..47f3549 100644
--- a/Swift/QtUI/QtFormResultItemModel.h
+++ b/Swift/QtUI/QtFormResultItemModel.h
@@ -13,24 +13,24 @@
namespace Swift {
class QtFormResultItemModel : public QAbstractTableModel {
- Q_OBJECT
- public:
- QtFormResultItemModel(QObject* parent);
- QtFormResultItemModel(QObject* parent, Form::ref formResult);
+ Q_OBJECT
+ public:
+ QtFormResultItemModel(QObject* parent);
+ QtFormResultItemModel(QObject* parent, Form::ref formResult);
- void setForm(Form::ref formResult);
- const Form::ref getForm() const;
+ void setForm(Form::ref formResult);
+ const Form::ref getForm() const;
- virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
- virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
+ virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- private:
- const std::string getFieldValue(const Form::FormItem& item, const int column) const;
+ private:
+ const std::string getFieldValue(const Form::FormItem& item, const int column) const;
- private:
- Form::ref formResult_;
+ private:
+ Form::ref formResult_;
};
}
diff --git a/Swift/QtUI/QtFormWidget.cpp b/Swift/QtUI/QtFormWidget.cpp
index ea452dc..13049ca 100644
--- a/Swift/QtUI/QtFormWidget.cpp
+++ b/Swift/QtUI/QtFormWidget.cpp
@@ -26,46 +26,46 @@
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()) {
- 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);
+ 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()) {
+ 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() {
@@ -73,168 +73,168 @@ 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()) {
- listWidget->addItem(P2QSTRING(value));
- selected.push_back(false);
- }
- } else {
- foreach (FormField::Option 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;
+ 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()) {
+ listWidget->addItem(P2QSTRING(value));
+ selected.push_back(false);
+ }
+ } else {
+ foreach (FormField::Option 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 = NULL;
- 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);
- }
- if (type == FormField::TextMultiType) {
- QString value = field->getTextMultiValue().c_str();
- QTextEdit* textWidget = new QTextEdit(this);
- textWidget->setPlainText(value);
- widget = textWidget;
- }
- if (type == FormField::TextPrivateType) {
- QString value = field->getTextPrivateValue().c_str();
- QLineEdit* lineWidget = new QLineEdit(value, this);
- lineWidget->setEchoMode(QLineEdit::Password);
- 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;
+ QWidget* widget = NULL;
+ 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);
+ }
+ if (type == FormField::TextMultiType) {
+ QString value = field->getTextMultiValue().c_str();
+ QTextEdit* textWidget = new QTextEdit(this);
+ textWidget->setPlainText(value);
+ widget = textWidget;
+ }
+ if (type == FormField::TextPrivateType) {
+ QString value = field->getTextPrivateValue().c_str();
+ QLineEdit* lineWidget = new QLineEdit(value, this);
+ lineWidget->setEchoMode(QLineEdit::Password);
+ 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 (boost::shared_ptr<FormField> field, form_->getFields()) {
- boost::shared_ptr<FormField> resultField = boost::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) {
- resultField->addValue(Q2PSTRING(line));
- }
- }
- }
- if (field->getType() == FormField::ListMultiType) {
- QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
- foreach (QListWidgetItem* item, listWidget->selectedItems()) {
- resultField->addValue(field->getOptions()[listWidget->row(item)].value);
- }
- }
- resultField->setName(field->getName());
- result->addField(resultField);
- }
- return result;
+ Form::ref result(new Form(Form::SubmitType));
+ foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
+ boost::shared_ptr<FormField> resultField = boost::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) {
+ resultField->addValue(Q2PSTRING(line));
+ }
+ }
+ }
+ if (field->getType() == FormField::ListMultiType) {
+ QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
+ foreach (QListWidgetItem* 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);
- }
+ 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);
- }
+ T* widget = qobject_cast<T*>(rawWidget);
+ if (widget) {
+ widget->setReadOnly(!editable);
+ }
}
void QtFormWidget::setEditable(bool editable) {
- if (!form_) {
- return;
- }
- foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
- QWidget* widget = NULL;
- if (field) {
- widget = fields_[field->getName()];
- }
- setEnabled<QCheckBox>(widget, editable);
- setEnabled<QListWidget>(widget, editable);
- setEditable<QTextEdit>(widget, editable);
- setEditable<QLineEdit>(widget, editable);
- }
+ if (!form_) {
+ return;
+ }
+ foreach (boost::shared_ptr<FormField> field, form_->getFields()) {
+ QWidget* widget = NULL;
+ 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/QtFormWidget.h b/Swift/QtUI/QtFormWidget.h
index 4c6311c..1eec115 100644
--- a/Swift/QtUI/QtFormWidget.h
+++ b/Swift/QtUI/QtFormWidget.h
@@ -17,19 +17,19 @@ class QListWidget;
namespace Swift {
class QtFormWidget : public QWidget {
- Q_OBJECT
- public:
- QtFormWidget(Form::ref form, QWidget* parent = NULL);
- virtual ~QtFormWidget();
- Form::ref getCompletedForm();
- void setEditable(bool editable);
- private:
- QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index);
- QListWidget* createList(FormField::ref field);
- template<class T> void setEnabled(QWidget* rawWidget, bool editable);
- template<class T> void setEditable(QWidget* rawWidget, bool editable);
- std::map<std::string, QWidget*> fields_;
- Form::ref form_;
+ Q_OBJECT
+ public:
+ QtFormWidget(Form::ref form, QWidget* parent = NULL);
+ virtual ~QtFormWidget();
+ Form::ref getCompletedForm();
+ void setEditable(bool editable);
+ private:
+ QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index);
+ QListWidget* createList(FormField::ref field);
+ template<class T> void setEnabled(QWidget* rawWidget, bool editable);
+ template<class T> void setEditable(QWidget* rawWidget, bool editable);
+ std::map<std::string, QWidget*> fields_;
+ Form::ref form_;
};
}
diff --git a/Swift/QtUI/QtHighlightEditor.cpp b/Swift/QtUI/QtHighlightEditor.cpp
index 1d47c4e..fdbff9e 100644
--- a/Swift/QtUI/QtHighlightEditor.cpp
+++ b/Swift/QtUI/QtHighlightEditor.cpp
@@ -29,61 +29,61 @@
namespace Swift {
QtHighlightEditor::QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent)
- : QWidget(parent), settings_(settings), previousRow_(-1)
+ : QWidget(parent), settings_(settings), previousRow_(-1)
{
- ui_.setupUi(this);
+ ui_.setupUi(this);
- connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int)));
+ connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int)));
- connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked()));
- connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked()));
+ connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked()));
+ connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick()));
- connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick()));
+ connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked()));
- connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect()));
- connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect()));
+ connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect()));
+ connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect()));
- connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
- connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
- connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect()));
+ connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
+ connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect()));
+ connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect()));
- /* replace the static line-edit control with the roster autocompleter */
- ui_.dummySenderName->setVisible(false);
- jid_ = new QtSuggestingJIDInput(this, settings);
- ui_.senderName->addWidget(jid_);
- jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1));
+ /* replace the static line-edit control with the roster autocompleter */
+ ui_.dummySenderName->setVisible(false);
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ ui_.senderName->addWidget(jid_);
+ jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1));
- /* handle autocomplete */
- connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString)));
+ /* handle autocomplete */
+ connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString)));
- /* we need to be notified if any of the state changes so that we can update our textual rule description */
- connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
- connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
- connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ /* we need to be notified if any of the state changes so that we can update our textual rule description */
+ connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
+ connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick()));
+ connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
+ connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick()));
- /* allow selection of a custom sound file */
- connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile()));
+ /* allow selection of a custom sound file */
+ connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile()));
- /* allowing reordering items */
- connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked()));
- connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked()));
+ /* allowing reordering items */
+ connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked()));
+ connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked()));
- setWindowTitle(tr("Highlight Rules"));
+ setWindowTitle(tr("Highlight Rules"));
}
QtHighlightEditor::~QtHighlightEditor()
@@ -92,477 +92,477 @@ QtHighlightEditor::~QtHighlightEditor()
std::string formatShortDescription(const HighlightRule &rule)
{
- const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room");
+ const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room");
- std::vector<std::string> senders = rule.getSenders();
- std::vector<std::string> keywords = rule.getKeywords();
+ std::vector<std::string> senders = rule.getSenders();
+ std::vector<std::string> keywords = rule.getKeywords();
- if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) {
- return std::string("All ") + chatOrRoom + " messages.";
- }
+ if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) {
+ return std::string("All ") + chatOrRoom + " messages.";
+ }
- if (rule.getNickIsKeyword()) {
- return std::string("All ") + chatOrRoom + " messages that mention my name.";
- }
+ if (rule.getNickIsKeyword()) {
+ return std::string("All ") + chatOrRoom + " messages that mention my name.";
+ }
- if (!senders.empty()) {
- return std::string("All ") + chatOrRoom + " messages from " + senders[0] + ".";
- }
+ if (!senders.empty()) {
+ return std::string("All ") + chatOrRoom + " messages from " + senders[0] + ".";
+ }
- if (!keywords.empty()) {
- return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'.";
- }
+ if (!keywords.empty()) {
+ return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'.";
+ }
- return "Unknown Rule";
+ return "Unknown Rule";
}
void QtHighlightEditor::show()
{
- highlightManager_->loadSettings();
+ highlightManager_->loadSettings();
- populateList();
+ populateList();
- if (ui_.listWidget->count()) {
- selectRow(0);
- }
+ if (ui_.listWidget->count()) {
+ selectRow(0);
+ }
- updateResetToDefaultRulesVisibility();
+ updateResetToDefaultRulesVisibility();
- /* prepare default states */
- widgetClick();
+ /* prepare default states */
+ widgetClick();
- QWidget::show();
- QWidget::activateWindow();
+ QWidget::show();
+ QWidget::activateWindow();
}
void QtHighlightEditor::setHighlightManager(HighlightManager* highlightManager)
{
- highlightManager_ = highlightManager;
+ highlightManager_ = highlightManager;
}
void QtHighlightEditor::setContactSuggestions(const std::vector<Contact::ref>& suggestions)
{
- jid_->setSuggestions(suggestions);
+ jid_->setSuggestions(suggestions);
}
void QtHighlightEditor::colorOtherSelect()
{
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
}
void QtHighlightEditor::colorCustomSelect()
{
- ui_.foregroundColor->setEnabled(true);
- ui_.backgroundColor->setEnabled(true);
+ ui_.foregroundColor->setEnabled(true);
+ ui_.backgroundColor->setEnabled(true);
}
void QtHighlightEditor::soundOtherSelect()
{
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
}
void QtHighlightEditor::soundCustomSelect()
{
- ui_.soundFile->setEnabled(true);
- ui_.soundFileButton->setEnabled(true);
+ ui_.soundFile->setEnabled(true);
+ ui_.soundFileButton->setEnabled(true);
}
void QtHighlightEditor::onNewButtonClicked()
{
- int row = getSelectedRow() + 1;
- populateList();
- HighlightRule newRule;
- newRule.setMatchMUC(true);
- highlightManager_->insertRule(row, newRule);
- QListWidgetItem *item = new QListWidgetItem();
- item->setText(P2QSTRING(formatShortDescription(newRule)));
- QFont font;
- font.setItalic(true);
- item->setFont(font);
- ui_.listWidget->insertItem(row, item);
- selectRow(row);
+ int row = getSelectedRow() + 1;
+ populateList();
+ HighlightRule newRule;
+ newRule.setMatchMUC(true);
+ highlightManager_->insertRule(row, newRule);
+ QListWidgetItem *item = new QListWidgetItem();
+ item->setText(P2QSTRING(formatShortDescription(newRule)));
+ QFont font;
+ font.setItalic(true);
+ item->setFont(font);
+ ui_.listWidget->insertItem(row, item);
+ selectRow(row);
}
void QtHighlightEditor::onDeleteButtonClicked()
{
- int selectedRow = getSelectedRow();
- assert(selectedRow>=0 && selectedRow<ui_.listWidget->count());
- delete ui_.listWidget->takeItem(selectedRow);
- highlightManager_->removeRule(selectedRow);
-
- if (!ui_.listWidget->count()) {
- disableDialog();
- ui_.deleteButton->setEnabled(false);
- } else {
- if (selectedRow == ui_.listWidget->count()) {
- selectRow(ui_.listWidget->count() - 1);
- } else {
- selectRow(selectedRow);
- }
- }
+ int selectedRow = getSelectedRow();
+ assert(selectedRow>=0 && selectedRow<ui_.listWidget->count());
+ delete ui_.listWidget->takeItem(selectedRow);
+ highlightManager_->removeRule(selectedRow);
+
+ if (!ui_.listWidget->count()) {
+ disableDialog();
+ ui_.deleteButton->setEnabled(false);
+ } else {
+ if (selectedRow == ui_.listWidget->count()) {
+ selectRow(ui_.listWidget->count() - 1);
+ } else {
+ selectRow(selectedRow);
+ }
+ }
}
void QtHighlightEditor::moveRowFromTo(int fromRow, int toRow) {
- int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value();
- highlightManager_->swapRules(fromRow, toRow);
- populateList();
- selectRow(toRow);
- ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition);
+ int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value();
+ highlightManager_->swapRules(fromRow, toRow);
+ populateList();
+ selectRow(toRow);
+ ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition);
}
void QtHighlightEditor::onUpButtonClicked() {
- const size_t moveFrom = ui_.listWidget->currentRow();
- const size_t moveTo = moveFrom - 1;
- moveRowFromTo(moveFrom, moveTo);
+ const size_t moveFrom = ui_.listWidget->currentRow();
+ const size_t moveTo = moveFrom - 1;
+ moveRowFromTo(moveFrom, moveTo);
}
void QtHighlightEditor::onDownButtonClicked() {
- const size_t moveFrom = ui_.listWidget->currentRow();
- const size_t moveTo = moveFrom + 1;
- moveRowFromTo(moveFrom, moveTo);
+ const size_t moveFrom = ui_.listWidget->currentRow();
+ const size_t moveTo = moveFrom + 1;
+ moveRowFromTo(moveFrom, moveTo);
}
void QtHighlightEditor::onCurrentRowChanged(int currentRow)
{
- ui_.deleteButton->setEnabled(currentRow != -1);
- ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0);
- ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1));
-
- if (previousRow_ != -1) {
- if (ui_.listWidget->count() > previousRow_) {
- QFont font;
- font.setItalic(false);
- ui_.listWidget->item(previousRow_)->setFont(font);
- highlightManager_->setRule(previousRow_, ruleFromDialog());
- }
- }
-
- if (currentRow != -1) {
- HighlightRule rule = highlightManager_->getRule(currentRow);
- ruleToDialog(rule);
- if (ui_.listWidget->currentItem()) {
- QFont font;
- font.setItalic(true);
- ui_.listWidget->currentItem()->setFont(font);
- ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
- }
- }
-
- /* grey the dialog if we have nothing selected */
- if (currentRow == -1) {
- disableDialog();
- }
-
- previousRow_ = currentRow;
-
- updateResetToDefaultRulesVisibility();
+ ui_.deleteButton->setEnabled(currentRow != -1);
+ ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0);
+ ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1));
+
+ if (previousRow_ != -1) {
+ if (ui_.listWidget->count() > previousRow_) {
+ QFont font;
+ font.setItalic(false);
+ ui_.listWidget->item(previousRow_)->setFont(font);
+ highlightManager_->setRule(previousRow_, ruleFromDialog());
+ }
+ }
+
+ if (currentRow != -1) {
+ HighlightRule rule = highlightManager_->getRule(currentRow);
+ ruleToDialog(rule);
+ if (ui_.listWidget->currentItem()) {
+ QFont font;
+ font.setItalic(true);
+ ui_.listWidget->currentItem()->setFont(font);
+ ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
+ }
+ }
+
+ /* grey the dialog if we have nothing selected */
+ if (currentRow == -1) {
+ disableDialog();
+ }
+
+ previousRow_ = currentRow;
+
+ updateResetToDefaultRulesVisibility();
}
void QtHighlightEditor::onApplyButtonClick()
{
- selectRow(getSelectedRow()); /* force save */
- highlightManager_->storeSettings();
+ selectRow(getSelectedRow()); /* force save */
+ highlightManager_->storeSettings();
}
void QtHighlightEditor::onCancelButtonClick()
{
- close();
+ close();
}
void QtHighlightEditor::onOkButtonClick()
{
- onApplyButtonClick();
- close();
+ onApplyButtonClick();
+ close();
}
void QtHighlightEditor::setChildWidgetStates()
{
- /* disable appropriate radio button child widgets */
-
- if (ui_.chatRadio->isChecked()) {
- if (ui_.nickIsKeyword->isChecked()) {
- /* switch to another choice before we disable this button */
- ui_.allMsgRadio->setChecked(true);
- }
- ui_.nickIsKeyword->setEnabled(false);
- } else if (ui_.roomRadio->isChecked()) {
- ui_.nickIsKeyword->setEnabled(true);
- } else { /* chats and rooms */
- ui_.nickIsKeyword->setEnabled(true);
- }
-
- if (ui_.senderRadio->isChecked()) {
- jid_->setEnabled(true);
- } else {
- jid_->setEnabled(false);
- }
-
- if (ui_.keywordRadio->isChecked()) {
- ui_.keyword->setEnabled(true);
- ui_.matchPartialWords->setEnabled(true);
- ui_.matchCase->setEnabled(true);
- } else {
- ui_.keyword->setEnabled(false);
- ui_.matchPartialWords->setEnabled(false);
- ui_.matchCase->setEnabled(false);
- }
-
- if (ui_.chatRadio->isChecked()) {
- ui_.allMsgRadio->setText(tr("Apply to all chat messages"));
- } else {
- ui_.allMsgRadio->setText(tr("Apply to all room messages"));
- }
+ /* disable appropriate radio button child widgets */
+
+ if (ui_.chatRadio->isChecked()) {
+ if (ui_.nickIsKeyword->isChecked()) {
+ /* switch to another choice before we disable this button */
+ ui_.allMsgRadio->setChecked(true);
+ }
+ ui_.nickIsKeyword->setEnabled(false);
+ } else if (ui_.roomRadio->isChecked()) {
+ ui_.nickIsKeyword->setEnabled(true);
+ } else { /* chats and rooms */
+ ui_.nickIsKeyword->setEnabled(true);
+ }
+
+ if (ui_.senderRadio->isChecked()) {
+ jid_->setEnabled(true);
+ } else {
+ jid_->setEnabled(false);
+ }
+
+ if (ui_.keywordRadio->isChecked()) {
+ ui_.keyword->setEnabled(true);
+ ui_.matchPartialWords->setEnabled(true);
+ ui_.matchCase->setEnabled(true);
+ } else {
+ ui_.keyword->setEnabled(false);
+ ui_.matchPartialWords->setEnabled(false);
+ ui_.matchCase->setEnabled(false);
+ }
+
+ if (ui_.chatRadio->isChecked()) {
+ ui_.allMsgRadio->setText(tr("Apply to all chat messages"));
+ } else {
+ ui_.allMsgRadio->setText(tr("Apply to all room messages"));
+ }
}
void QtHighlightEditor::widgetClick()
{
- setChildWidgetStates();
+ setChildWidgetStates();
- HighlightRule rule = ruleFromDialog();
+ HighlightRule rule = ruleFromDialog();
- if (ui_.listWidget->currentItem()) {
- ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
- }
+ if (ui_.listWidget->currentItem()) {
+ ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule)));
+ }
}
void QtHighlightEditor::disableDialog()
{
- ui_.chatRadio->setEnabled(false);
- ui_.roomRadio->setEnabled(false);
- ui_.allMsgRadio->setEnabled(false);
- ui_.nickIsKeyword->setEnabled(false);
- ui_.senderRadio->setEnabled(false);
- ui_.dummySenderName->setEnabled(false);
- ui_.keywordRadio->setEnabled(false);
- ui_.keyword->setEnabled(false);
- ui_.matchPartialWords->setEnabled(false);
- ui_.matchCase->setEnabled(false);
- ui_.noColorRadio->setEnabled(false);
- ui_.customColorRadio->setEnabled(false);
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
- ui_.noSoundRadio->setEnabled(false);
- ui_.defaultSoundRadio->setEnabled(false);
- ui_.customSoundRadio->setEnabled(false);
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
+ ui_.chatRadio->setEnabled(false);
+ ui_.roomRadio->setEnabled(false);
+ ui_.allMsgRadio->setEnabled(false);
+ ui_.nickIsKeyword->setEnabled(false);
+ ui_.senderRadio->setEnabled(false);
+ ui_.dummySenderName->setEnabled(false);
+ ui_.keywordRadio->setEnabled(false);
+ ui_.keyword->setEnabled(false);
+ ui_.matchPartialWords->setEnabled(false);
+ ui_.matchCase->setEnabled(false);
+ ui_.noColorRadio->setEnabled(false);
+ ui_.customColorRadio->setEnabled(false);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
+ ui_.noSoundRadio->setEnabled(false);
+ ui_.defaultSoundRadio->setEnabled(false);
+ ui_.customSoundRadio->setEnabled(false);
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
}
void QtHighlightEditor::handleContactSuggestionRequested(const QString& text)
{
- std::string stdText = Q2PSTRING(text);
- onContactSuggestionsRequested(stdText);
+ std::string stdText = Q2PSTRING(text);
+ onContactSuggestionsRequested(stdText);
}
void QtHighlightEditor::selectSoundFile()
{
- QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)");
- ui_.soundFile->setText(path);
+ QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)");
+ ui_.soundFile->setText(path);
}
void QtHighlightEditor::onResetToDefaultRulesClicked() {
- highlightManager_->resetToDefaultRulesList();
- populateList();
- updateResetToDefaultRulesVisibility();
+ highlightManager_->resetToDefaultRulesList();
+ populateList();
+ updateResetToDefaultRulesVisibility();
}
void QtHighlightEditor::handleOnUserSelected(const Contact::ref& contact) {
- /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */
- if (contact->jid.isValid()) {
- jid_->setText(P2QSTRING(contact->jid.toString()));
- } else {
- jid_->setText(P2QSTRING(contact->name));
- }
+ /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */
+ if (contact->jid.isValid()) {
+ jid_->setText(P2QSTRING(contact->jid.toString()));
+ } else {
+ jid_->setText(P2QSTRING(contact->name));
+ }
}
void QtHighlightEditor::populateList()
{
- previousRow_ = -1;
- ui_.listWidget->clear();
- HighlightRulesListPtr rules = highlightManager_->getRules();
- for (size_t i = 0; i < rules->getSize(); ++i) {
- const HighlightRule& rule = rules->getRule(i);
- QListWidgetItem *item = new QListWidgetItem();
- item->setText(P2QSTRING(formatShortDescription(rule)));
- ui_.listWidget->addItem(item);
- }
+ previousRow_ = -1;
+ ui_.listWidget->clear();
+ HighlightRulesListPtr rules = highlightManager_->getRules();
+ for (size_t i = 0; i < rules->getSize(); ++i) {
+ const HighlightRule& rule = rules->getRule(i);
+ QListWidgetItem *item = new QListWidgetItem();
+ item->setText(P2QSTRING(formatShortDescription(rule)));
+ ui_.listWidget->addItem(item);
+ }
}
void QtHighlightEditor::selectRow(int row)
{
- for (int i = 0; i < ui_.listWidget->count(); ++i) {
- if (i == row) {
- ui_.listWidget->item(i)->setSelected(true);
- onCurrentRowChanged(i);
- } else {
- ui_.listWidget->item(i)->setSelected(false);
- }
- }
- ui_.listWidget->setCurrentRow(row);
+ for (int i = 0; i < ui_.listWidget->count(); ++i) {
+ if (i == row) {
+ ui_.listWidget->item(i)->setSelected(true);
+ onCurrentRowChanged(i);
+ } else {
+ ui_.listWidget->item(i)->setSelected(false);
+ }
+ }
+ ui_.listWidget->setCurrentRow(row);
}
int QtHighlightEditor::getSelectedRow() const
{
- for (int i = 0; i < ui_.listWidget->count(); ++i) {
- if (ui_.listWidget->item(i)->isSelected()) {
- return i;
- }
- }
- return -1;
+ for (int i = 0; i < ui_.listWidget->count(); ++i) {
+ if (ui_.listWidget->item(i)->isSelected()) {
+ return i;
+ }
+ }
+ return -1;
}
HighlightRule QtHighlightEditor::ruleFromDialog()
{
- HighlightRule rule;
- HighlightAction& action = rule.getAction();
-
- if (ui_.chatRadio->isChecked()) {
- rule.setMatchChat(true);
- rule.setMatchMUC(false);
- } else {
- rule.setMatchChat(false);
- rule.setMatchMUC(true);
- }
-
- if (ui_.allMsgRadio->isChecked()) {
- action.setHighlightWholeMessage(true);
- }
-
- if (ui_.senderRadio->isChecked()) {
- QString senderName = jid_->text();
- if (!senderName.isEmpty()) {
- std::vector<std::string> senders;
- senders.push_back(Q2PSTRING(senderName));
- rule.setSenders(senders);
- action.setHighlightWholeMessage(true);
- }
- }
-
- if (ui_.keywordRadio->isChecked()) {
- QString keywordString = ui_.keyword->text();
- if (!keywordString.isEmpty()) {
- std::vector<std::string> keywords;
- keywords.push_back(Q2PSTRING(keywordString));
- rule.setKeywords(keywords);
- }
- }
-
- if (ui_.nickIsKeyword->isChecked()) {
- rule.setNickIsKeyword(true);
- rule.setMatchWholeWords(true);
- rule.setMatchCase(true);
- } else {
- rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked());
- rule.setMatchCase(ui_.matchCase->isChecked());
- }
-
- if (ui_.noColorRadio->isChecked()) {
- action.setTextColor("");
- action.setTextBackground("");
- } else {
- action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name()));
- action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name()));
- }
-
- if (ui_.noSoundRadio->isChecked()) {
- action.setPlaySound(false);
- } else if (ui_.defaultSoundRadio->isChecked()) {
- action.setPlaySound(true);
- action.setSoundFile("");
- } else {
- action.setPlaySound(true);
- action.setSoundFile(Q2PSTRING(ui_.soundFile->text()));
- }
-
- return rule;
+ HighlightRule rule;
+ HighlightAction& action = rule.getAction();
+
+ if (ui_.chatRadio->isChecked()) {
+ rule.setMatchChat(true);
+ rule.setMatchMUC(false);
+ } else {
+ rule.setMatchChat(false);
+ rule.setMatchMUC(true);
+ }
+
+ if (ui_.allMsgRadio->isChecked()) {
+ action.setHighlightWholeMessage(true);
+ }
+
+ if (ui_.senderRadio->isChecked()) {
+ QString senderName = jid_->text();
+ if (!senderName.isEmpty()) {
+ std::vector<std::string> senders;
+ senders.push_back(Q2PSTRING(senderName));
+ rule.setSenders(senders);
+ action.setHighlightWholeMessage(true);
+ }
+ }
+
+ if (ui_.keywordRadio->isChecked()) {
+ QString keywordString = ui_.keyword->text();
+ if (!keywordString.isEmpty()) {
+ std::vector<std::string> keywords;
+ keywords.push_back(Q2PSTRING(keywordString));
+ rule.setKeywords(keywords);
+ }
+ }
+
+ if (ui_.nickIsKeyword->isChecked()) {
+ rule.setNickIsKeyword(true);
+ rule.setMatchWholeWords(true);
+ rule.setMatchCase(true);
+ } else {
+ rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked());
+ rule.setMatchCase(ui_.matchCase->isChecked());
+ }
+
+ if (ui_.noColorRadio->isChecked()) {
+ action.setTextColor("");
+ action.setTextBackground("");
+ } else {
+ action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name()));
+ action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name()));
+ }
+
+ if (ui_.noSoundRadio->isChecked()) {
+ action.setPlaySound(false);
+ } else if (ui_.defaultSoundRadio->isChecked()) {
+ action.setPlaySound(true);
+ action.setSoundFile("");
+ } else {
+ action.setPlaySound(true);
+ action.setSoundFile(Q2PSTRING(ui_.soundFile->text()));
+ }
+
+ return rule;
}
void QtHighlightEditor::ruleToDialog(const HighlightRule& rule)
{
- ui_.chatRadio->setEnabled(true);
- ui_.roomRadio->setEnabled(true);
-
- if (rule.getMatchMUC()) {
- ui_.chatRadio->setChecked(false);
- ui_.roomRadio->setChecked(true);
- } else {
- ui_.chatRadio->setChecked(true);
- ui_.roomRadio->setChecked(false);
- }
-
- ui_.allMsgRadio->setEnabled(true);
- ui_.allMsgRadio->setChecked(true); /* this is the default radio button */
- jid_->setText("");
- ui_.keyword->setText("");
- ui_.matchPartialWords->setChecked(false);
- ui_.matchCase->setChecked(false);
-
- ui_.nickIsKeyword->setEnabled(true);
- if (rule.getNickIsKeyword()) {
- ui_.nickIsKeyword->setChecked(true);
- }
-
- ui_.senderRadio->setEnabled(true);
- std::vector<std::string> senders = rule.getSenders();
- if (!senders.empty()) {
- ui_.senderRadio->setChecked(true);
- jid_->setText(P2QSTRING(senders[0]));
- }
-
- ui_.keywordRadio->setEnabled(true);
- std::vector<std::string> keywords = rule.getKeywords();
- if (!keywords.empty()) {
- ui_.keywordRadio->setChecked(true);
- ui_.keyword->setText(P2QSTRING(keywords[0]));
- ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords());
- ui_.matchCase->setChecked(rule.getMatchCase());
- }
-
- const HighlightAction& action = rule.getAction();
-
- ui_.noColorRadio->setEnabled(true);
- ui_.customColorRadio->setEnabled(true);
- if (action.getTextColor().empty() && action.getTextBackground().empty()) {
- ui_.noColorRadio->setChecked(true);
- ui_.foregroundColor->setEnabled(false);
- ui_.backgroundColor->setEnabled(false);
- } else {
- ui_.foregroundColor->setEnabled(true);
- ui_.backgroundColor->setEnabled(true);
- QColor foregroundColor(P2QSTRING(action.getTextColor()));
- ui_.foregroundColor->setColor(foregroundColor);
- QColor backgroundColor(P2QSTRING(action.getTextBackground()));
- ui_.backgroundColor->setColor(backgroundColor);
- ui_.customColorRadio->setChecked(true);
- }
-
- ui_.noSoundRadio->setEnabled(true);
- ui_.defaultSoundRadio->setEnabled(true);
- ui_.customSoundRadio->setEnabled(true);
- ui_.soundFile->setText("");
- ui_.soundFile->setEnabled(false);
- ui_.soundFileButton->setEnabled(false);
- if (action.playSound()) {
- if (action.getSoundFile().empty()) {
- ui_.defaultSoundRadio->setChecked(true);
- } else {
- ui_.customSoundRadio->setChecked(true);
- ui_.soundFile->setText(P2QSTRING(action.getSoundFile()));
- ui_.soundFile->setEnabled(true);
- ui_.soundFileButton->setEnabled(true);
- }
- } else {
- ui_.noSoundRadio->setChecked(true);
- }
-
- /* set radio button child option states */
- setChildWidgetStates();
+ ui_.chatRadio->setEnabled(true);
+ ui_.roomRadio->setEnabled(true);
+
+ if (rule.getMatchMUC()) {
+ ui_.chatRadio->setChecked(false);
+ ui_.roomRadio->setChecked(true);
+ } else {
+ ui_.chatRadio->setChecked(true);
+ ui_.roomRadio->setChecked(false);
+ }
+
+ ui_.allMsgRadio->setEnabled(true);
+ ui_.allMsgRadio->setChecked(true); /* this is the default radio button */
+ jid_->setText("");
+ ui_.keyword->setText("");
+ ui_.matchPartialWords->setChecked(false);
+ ui_.matchCase->setChecked(false);
+
+ ui_.nickIsKeyword->setEnabled(true);
+ if (rule.getNickIsKeyword()) {
+ ui_.nickIsKeyword->setChecked(true);
+ }
+
+ ui_.senderRadio->setEnabled(true);
+ std::vector<std::string> senders = rule.getSenders();
+ if (!senders.empty()) {
+ ui_.senderRadio->setChecked(true);
+ jid_->setText(P2QSTRING(senders[0]));
+ }
+
+ ui_.keywordRadio->setEnabled(true);
+ std::vector<std::string> keywords = rule.getKeywords();
+ if (!keywords.empty()) {
+ ui_.keywordRadio->setChecked(true);
+ ui_.keyword->setText(P2QSTRING(keywords[0]));
+ ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords());
+ ui_.matchCase->setChecked(rule.getMatchCase());
+ }
+
+ const HighlightAction& action = rule.getAction();
+
+ ui_.noColorRadio->setEnabled(true);
+ ui_.customColorRadio->setEnabled(true);
+ if (action.getTextColor().empty() && action.getTextBackground().empty()) {
+ ui_.noColorRadio->setChecked(true);
+ ui_.foregroundColor->setEnabled(false);
+ ui_.backgroundColor->setEnabled(false);
+ } else {
+ ui_.foregroundColor->setEnabled(true);
+ ui_.backgroundColor->setEnabled(true);
+ QColor foregroundColor(P2QSTRING(action.getTextColor()));
+ ui_.foregroundColor->setColor(foregroundColor);
+ QColor backgroundColor(P2QSTRING(action.getTextBackground()));
+ ui_.backgroundColor->setColor(backgroundColor);
+ ui_.customColorRadio->setChecked(true);
+ }
+
+ ui_.noSoundRadio->setEnabled(true);
+ ui_.defaultSoundRadio->setEnabled(true);
+ ui_.customSoundRadio->setEnabled(true);
+ ui_.soundFile->setText("");
+ ui_.soundFile->setEnabled(false);
+ ui_.soundFileButton->setEnabled(false);
+ if (action.playSound()) {
+ if (action.getSoundFile().empty()) {
+ ui_.defaultSoundRadio->setChecked(true);
+ } else {
+ ui_.customSoundRadio->setChecked(true);
+ ui_.soundFile->setText(P2QSTRING(action.getSoundFile()));
+ ui_.soundFile->setEnabled(true);
+ ui_.soundFileButton->setEnabled(true);
+ }
+ } else {
+ ui_.noSoundRadio->setChecked(true);
+ }
+
+ /* set radio button child option states */
+ setChildWidgetStates();
}
void QtHighlightEditor::updateResetToDefaultRulesVisibility() {
- ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList());
+ ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList());
}
}
diff --git a/Swift/QtUI/QtHighlightEditor.h b/Swift/QtUI/QtHighlightEditor.h
index e45963c..2a9f06b 100644
--- a/Swift/QtUI/QtHighlightEditor.h
+++ b/Swift/QtUI/QtHighlightEditor.h
@@ -19,56 +19,56 @@
namespace Swift {
- class QtSettingsProvider;
- class QtSuggestingJIDInput;
- class QtWebKitChatView;
+ class QtSettingsProvider;
+ class QtSuggestingJIDInput;
+ class QtWebKitChatView;
- class QtHighlightEditor : public QWidget, public HighlightEditorWindow {
- Q_OBJECT
+ class QtHighlightEditor : public QWidget, public HighlightEditorWindow {
+ Q_OBJECT
- public:
- QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL);
- virtual ~QtHighlightEditor();
+ public:
+ QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL);
+ virtual ~QtHighlightEditor();
- virtual void show();
- virtual void setHighlightManager(HighlightManager* highlightManager);
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
+ virtual void show();
+ virtual void setHighlightManager(HighlightManager* highlightManager);
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
- private slots:
- void colorOtherSelect();
- void colorCustomSelect();
- void soundOtherSelect();
- void soundCustomSelect();
- void onNewButtonClicked();
- void onDeleteButtonClicked();
- void onUpButtonClicked();
- void onDownButtonClicked();
- void onCurrentRowChanged(int currentRow);
- void onApplyButtonClick();
- void onCancelButtonClick();
- void onOkButtonClick();
- void setChildWidgetStates();
- void widgetClick();
- void disableDialog();
- void handleContactSuggestionRequested(const QString& text);
- void selectSoundFile();
- void onResetToDefaultRulesClicked();
+ private slots:
+ void colorOtherSelect();
+ void colorCustomSelect();
+ void soundOtherSelect();
+ void soundCustomSelect();
+ void onNewButtonClicked();
+ void onDeleteButtonClicked();
+ void onUpButtonClicked();
+ void onDownButtonClicked();
+ void onCurrentRowChanged(int currentRow);
+ void onApplyButtonClick();
+ void onCancelButtonClick();
+ void onOkButtonClick();
+ void setChildWidgetStates();
+ void widgetClick();
+ void disableDialog();
+ void handleContactSuggestionRequested(const QString& text);
+ void selectSoundFile();
+ void onResetToDefaultRulesClicked();
- private:
- void handleOnUserSelected(const Contact::ref& contact);
- void populateList();
- void selectRow(int row);
- int getSelectedRow() const;
- HighlightRule ruleFromDialog();
- void ruleToDialog(const HighlightRule& rule);
- void updateResetToDefaultRulesVisibility();
- void moveRowFromTo(int fromRow, int toRow);
+ private:
+ void handleOnUserSelected(const Contact::ref& contact);
+ void populateList();
+ void selectRow(int row);
+ int getSelectedRow() const;
+ HighlightRule ruleFromDialog();
+ void ruleToDialog(const HighlightRule& rule);
+ void updateResetToDefaultRulesVisibility();
+ void moveRowFromTo(int fromRow, int toRow);
- Ui::QtHighlightEditor ui_;
- QtSettingsProvider* settings_;
- HighlightManager* highlightManager_;
- QtSuggestingJIDInput* jid_;
- int previousRow_;
- };
+ Ui::QtHighlightEditor ui_;
+ QtSettingsProvider* settings_;
+ HighlightManager* highlightManager_;
+ QtSuggestingJIDInput* jid_;
+ int previousRow_;
+ };
}
diff --git a/Swift/QtUI/QtHistoryWindow.cpp b/Swift/QtUI/QtHistoryWindow.cpp
index 0a1f07a..5ed8114 100644
--- a/Swift/QtUI/QtHistoryWindow.cpp
+++ b/Swift/QtUI/QtHistoryWindow.cpp
@@ -42,227 +42,227 @@
namespace Swift {
QtHistoryWindow::QtHistoryWindow(SettingsProvider* settings, UIEventStream* eventStream) :
- previousTopMessageWasSelf_(false),
- previousBottomMessageWasSelf_(false) {
- ui_.setupUi(this);
-
- theme_ = new QtChatTheme("");
- idCounter_ = 0;
-
- delete ui_.conversation_;
- conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME
- QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
- sizePolicy.setHorizontalStretch(80);
- sizePolicy.setVerticalStretch(0);
- conversation_->setSizePolicy(sizePolicy);
-
- ui_.conversation_ = conversation_;
- ui_.bottomLayout_->addWidget(conversation_);
-
- delete ui_.conversationRoster_;
- conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this);
- QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding);
- sizePolicy2.setVerticalStretch(80);
- conversationRoster_->setSizePolicy(sizePolicy2);
- ui_.conversationRoster_ = conversationRoster_;
- ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop);
- ui_.bottomLeftLayout_->addWidget(conversationRoster_);
-
- setWindowTitle(tr("History"));
-
- conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1));
- connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
- connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
- connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
- connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
- connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
- connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
- connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
+ previousTopMessageWasSelf_(false),
+ previousBottomMessageWasSelf_(false) {
+ ui_.setupUi(this);
+
+ theme_ = new QtChatTheme("");
+ idCounter_ = 0;
+
+ delete ui_.conversation_;
+ conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME
+ QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
+ sizePolicy.setHorizontalStretch(80);
+ sizePolicy.setVerticalStretch(0);
+ conversation_->setSizePolicy(sizePolicy);
+
+ ui_.conversation_ = conversation_;
+ ui_.bottomLayout_->addWidget(conversation_);
+
+ delete ui_.conversationRoster_;
+ conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this);
+ QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding);
+ sizePolicy2.setVerticalStretch(80);
+ conversationRoster_->setSizePolicy(sizePolicy2);
+ ui_.conversationRoster_ = conversationRoster_;
+ ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop);
+ ui_.bottomLeftLayout_->addWidget(conversationRoster_);
+
+ setWindowTitle(tr("History"));
+
+ conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1));
+ connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
+ connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
+ connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
+ connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
+ connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
+ connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
+ connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
}
QtHistoryWindow::~QtHistoryWindow() {
- disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
- disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
- disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
- disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
- disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
- disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
- disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
- disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
-
- delete theme_;
- delete conversation_;
- // TODO: delete ui_
+ disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int)));
+ disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop()));
+ disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom()));
+ disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int)));
+ disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed()));
+ disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&)));
+ disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked()));
+ disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked()));
+
+ delete theme_;
+ delete conversation_;
+ // TODO: delete ui_
}
void QtHistoryWindow::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtHistoryWindow::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated();
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated();
+ QWidget::showEvent(event);
}
void QtHistoryWindow::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
void QtHistoryWindow::setRosterModel(Roster* model) {
- conversationRoster_->setRosterModel(model);
+ conversationRoster_->setRosterModel(model);
}
void QtHistoryWindow::addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) {
- QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
-
- QString messageHTML(P2QSTRING(message));
- messageHTML = QtUtilities::htmlEscape(messageHTML);
- QString searchTerm = ui_.searchBox_->lineEdit()->text();
- if (searchTerm.length()) {
- messageHTML.replace(searchTerm, "<span style='background-color: yellow'>" + searchTerm + "</span>");
- }
-
- // note: time uses localtime
- QDate date = QDate(time.date().year(), time.date().month(), time.date().day());
- QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds());
- QDateTime qTime = QDateTime(date, dayTime);
-
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
-
- QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
-
- if (addAtTheTop) {
- bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName)));
- conversation_->addMessageTop(boost::shared_ptr<ChatSnippet>(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))));
-
- previousTopMessageWasSelf_ = senderIsSelf;
- previousTopSenderName_ = P2QSTRING(senderName);
- }
- else {
- bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName)));
- conversation_->addMessageBottom(boost::make_shared<MessageSnippet>(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)));
- previousBottomMessageWasSelf_ = senderIsSelf;
- previousBottomSenderName_ = P2QSTRING(senderName);
- }
-
- // keep track of the days viewable in the chatView
- if (!dates_.count(date)) {
- dates_.insert(date);
- }
+ QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
+
+ QString messageHTML(P2QSTRING(message));
+ messageHTML = QtUtilities::htmlEscape(messageHTML);
+ QString searchTerm = ui_.searchBox_->lineEdit()->text();
+ if (searchTerm.length()) {
+ messageHTML.replace(searchTerm, "<span style='background-color: yellow'>" + searchTerm + "</span>");
+ }
+
+ // note: time uses localtime
+ QDate date = QDate(time.date().year(), time.date().month(), time.date().day());
+ QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds());
+ QDateTime qTime = QDateTime(date, dayTime);
+
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+
+ QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
+
+ if (addAtTheTop) {
+ bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName)));
+ conversation_->addMessageTop(boost::shared_ptr<ChatSnippet>(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))));
+
+ previousTopMessageWasSelf_ = senderIsSelf;
+ previousTopSenderName_ = P2QSTRING(senderName);
+ }
+ else {
+ bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName)));
+ conversation_->addMessageBottom(boost::make_shared<MessageSnippet>(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)));
+ previousBottomMessageWasSelf_ = senderIsSelf;
+ 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);
+ onSelectedContactChanged(item);
}
void QtHistoryWindow::resetConversationView() {
- previousTopMessageWasSelf_ = false;
- previousBottomMessageWasSelf_ = false;
- previousTopSenderName_.clear();
- previousBottomSenderName_.clear();
+ previousTopMessageWasSelf_ = false;
+ previousBottomMessageWasSelf_ = false;
+ previousTopSenderName_.clear();
+ previousBottomSenderName_.clear();
- dates_.clear();
- conversation_->resetView();
+ 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_) {
- int snippetPosition = conversation_->getSnippetPositionByDate(date);
- if (snippetPosition <= pos) {
- currentDate = date;
- }
- }
-
- if (ui_.calendarWidget_->selectedDate() != currentDate) {
- ui_.calendarWidget_->setSelectedDate(currentDate);
- }
+ // first message starts with offset 5
+ if (pos < 5) {
+ pos = 5;
+ }
+
+ QDate currentDate;
+ foreach (const QDate& 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)));
+ 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);
- onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ if (dates_.empty()) {
+ return;
+ }
+
+ int year, month, day;
+ QDate lastDate = *dates_.rbegin();
+ lastDate.getDate(&year, &month, &day);
+ onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::handleReturnPressed() {
- onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString());
+ onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString());
}
void QtHistoryWindow::handleCalendarClicked(const QDate& date) {
- int year, month, day;
- QDate tempDate = date; // getDate discards const qualifier
- tempDate.getDate(&year, &month, &day);
- onCalendarClicked(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ int year, month, day;
+ QDate tempDate = date; // getDate discards const qualifier
+ tempDate.getDate(&year, &month, &day);
+ onCalendarClicked(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
}
void QtHistoryWindow::setDate(const boost::gregorian::date& date) {
- ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day()));
+ ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day()));
}
void QtHistoryWindow::handleNextButtonClicked() {
- onNextButtonClicked();
+ onNextButtonClicked();
}
void QtHistoryWindow::handlePreviousButtonClicked() {
- onPreviousButtonClicked();
+ onPreviousButtonClicked();
}
void QtHistoryWindow::handleFontResized(int fontSizeSteps) {
- conversation_->resizeFont(fontSizeSteps);
+ conversation_->resizeFont(fontSizeSteps);
- emit fontResized(fontSizeSteps);
+ emit fontResized(fontSizeSteps);
}
void QtHistoryWindow::resetConversationViewTopInsertPoint() {
- previousTopMessageWasSelf_ = false;
- previousTopSenderName_ = QString();
- conversation_->resetTopInsertPoint();
+ previousTopMessageWasSelf_ = false;
+ previousTopSenderName_ = QString();
+ conversation_->resetTopInsertPoint();
}
std::string QtHistoryWindow::getSearchBoxText() {
- return ui_.searchBox_->lineEdit()->text().toStdString();
+ return ui_.searchBox_->lineEdit()->text().toStdString();
}
boost::gregorian::date QtHistoryWindow::getLastVisibleDate() {
- if (!dates_.empty()) {
- QDate lastDate = *dates_.rbegin();
- int year, month, day;
- lastDate.getDate(&year, &month, &day);
-
- return boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day));
- }
- return boost::gregorian::date(boost::gregorian::not_a_date_time);
+ if (!dates_.empty()) {
+ QDate lastDate = *dates_.rbegin();
+ int year, month, day;
+ lastDate.getDate(&year, &month, &day);
+
+ return boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day));
+ }
+ return boost::gregorian::date(boost::gregorian::not_a_date_time);
}
std::string QtHistoryWindow::getID() const {
- return "QtHistoryWindow";
+ return "QtHistoryWindow";
}
}
diff --git a/Swift/QtUI/QtHistoryWindow.h b/Swift/QtUI/QtHistoryWindow.h
index 2008079..02d7fb8 100644
--- a/Swift/QtUI/QtHistoryWindow.h
+++ b/Swift/QtUI/QtHistoryWindow.h
@@ -22,61 +22,61 @@
#include <Swift/QtUI/ui_QtHistoryWindow.h>
namespace Swift {
- class QtTabbable;
- class QtTreeWidget;
- class QtWebKitChatView;
- class QtChatTheme;
- class SettingsProvider;
- class UIEventStream;
-
- class QtHistoryWindow : public QtTabbable, public HistoryWindow {
- Q_OBJECT
-
- public:
- QtHistoryWindow(SettingsProvider*, UIEventStream*);
- ~QtHistoryWindow();
- void activate();
- void setRosterModel(Roster*);
- void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop);
- void resetConversationView();
- void resetConversationViewTopInsertPoint();
- void setDate(const boost::gregorian::date& date);
-
- void closeEvent(QCloseEvent* event);
- void showEvent(QShowEvent* event);
-
- std::string getSearchBoxText();
- boost::gregorian::date getLastVisibleDate();
-
- virtual std::string getID() const;
-
- signals:
- void fontResized(int);
-
- public slots:
- void handleFontResized(int fontSizeSteps);
-
- protected slots:
- void handleScrollRequested(int pos);
- void handleScrollReachedTop();
- void handleScrollReachedBottom();
- void handleReturnPressed();
- void handleCalendarClicked(const QDate& date);
- void handlePreviousButtonClicked();
- void handleNextButtonClicked();
-
- private:
- void handleSomethingSelectedChanged(RosterItem* item);
-
- Ui::QtHistoryWindow ui_;
- QtChatTheme* theme_;
- QtWebKitChatView* conversation_;
- QtTreeWidget* conversationRoster_;
- std::set<QDate> dates_;
- int idCounter_;
- bool previousTopMessageWasSelf_;
- QString previousTopSenderName_;
- bool previousBottomMessageWasSelf_;
- QString previousBottomSenderName_;
- };
+ class QtTabbable;
+ class QtTreeWidget;
+ class QtWebKitChatView;
+ class QtChatTheme;
+ class SettingsProvider;
+ class UIEventStream;
+
+ class QtHistoryWindow : public QtTabbable, public HistoryWindow {
+ Q_OBJECT
+
+ public:
+ QtHistoryWindow(SettingsProvider*, UIEventStream*);
+ ~QtHistoryWindow();
+ void activate();
+ void setRosterModel(Roster*);
+ void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop);
+ void resetConversationView();
+ void resetConversationViewTopInsertPoint();
+ void setDate(const boost::gregorian::date& date);
+
+ void closeEvent(QCloseEvent* event);
+ void showEvent(QShowEvent* event);
+
+ std::string getSearchBoxText();
+ boost::gregorian::date getLastVisibleDate();
+
+ virtual std::string getID() const;
+
+ signals:
+ void fontResized(int);
+
+ public slots:
+ void handleFontResized(int fontSizeSteps);
+
+ protected slots:
+ void handleScrollRequested(int pos);
+ void handleScrollReachedTop();
+ void handleScrollReachedBottom();
+ void handleReturnPressed();
+ void handleCalendarClicked(const QDate& date);
+ void handlePreviousButtonClicked();
+ void handleNextButtonClicked();
+
+ private:
+ void handleSomethingSelectedChanged(RosterItem* item);
+
+ Ui::QtHistoryWindow ui_;
+ QtChatTheme* theme_;
+ QtWebKitChatView* conversation_;
+ QtTreeWidget* conversationRoster_;
+ std::set<QDate> dates_;
+ int idCounter_;
+ bool previousTopMessageWasSelf_;
+ QString previousTopSenderName_;
+ bool previousBottomMessageWasSelf_;
+ QString previousBottomSenderName_;
+ };
}
diff --git a/Swift/QtUI/QtJoinMUCWindow.cpp b/Swift/QtUI/QtJoinMUCWindow.cpp
index 53944da..7225b06 100644
--- a/Swift/QtUI/QtJoinMUCWindow.cpp
+++ b/Swift/QtUI/QtJoinMUCWindow.cpp
@@ -17,59 +17,59 @@ namespace Swift {
QtJoinMUCWindow::QtJoinMUCWindow(UIEventStream* uiEventStream) : uiEventStream(uiEventStream) {
- ui.setupUi(this);
+ ui.setupUi(this);
#if QT_VERSION >= 0x040700
- ui.room->setPlaceholderText(tr("someroom@rooms.example.com"));
+ ui.room->setPlaceholderText(tr("someroom@rooms.example.com"));
#endif
- connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin()));
- connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
- connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin()));
+ connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin()));
+ connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch()));
+ connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin()));
#if QT_VERSION < 0x050200
- // FIXME: Temporarily set focus on the nickName field first, so that the
- // placeholder for the room is visible. This is just because Qt hides
- // the placeholder when a widget is focused for some reason.
- // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0.
- ui.nickName->setFocus();
+ // FIXME: Temporarily set focus on the nickName field first, so that the
+ // placeholder for the room is visible. This is just because Qt hides
+ // the placeholder when a widget is focused for some reason.
+ // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0.
+ ui.nickName->setFocus();
#endif
- ui.instantRoom->setChecked(true);
- ui.nickName->setValidator(new NickValidator(this));
- ui.room->setValidator(new RoomJIDValidator(this));
+ ui.instantRoom->setChecked(true);
+ ui.nickName->setValidator(new NickValidator(this));
+ ui.room->setValidator(new RoomJIDValidator(this));
}
void QtJoinMUCWindow::handleJoin() {
- if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) {
- QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room);
- return;
- }
- if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) {
- QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName);
- return;
- }
+ if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) {
+ QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room);
+ return;
+ }
+ if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) {
+ QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName);
+ return;
+ }
- lastSetNick = Q2PSTRING(ui.nickName->text());
- std::string password = Q2PSTRING(ui.password->text());
- JID room(Q2PSTRING(ui.room->text()));
- uiEventStream->send(boost::make_shared<JoinMUCUIEvent>(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked()));
- hide();
+ lastSetNick = Q2PSTRING(ui.nickName->text());
+ std::string password = Q2PSTRING(ui.password->text());
+ JID room(Q2PSTRING(ui.room->text()));
+ uiEventStream->send(boost::make_shared<JoinMUCUIEvent>(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked()));
+ hide();
}
void QtJoinMUCWindow::handleSearch() {
- onSearchMUC();
+ onSearchMUC();
}
void QtJoinMUCWindow::setNick(const std::string& nick) {
- ui.nickName->setText(P2QSTRING(nick));
- lastSetNick = nick;
+ ui.nickName->setText(P2QSTRING(nick));
+ lastSetNick = nick;
}
void QtJoinMUCWindow::setMUC(const std::string& nick) {
- ui.room->setText(P2QSTRING(nick));
+ ui.room->setText(P2QSTRING(nick));
}
void QtJoinMUCWindow::show() {
- QWidget::show();
- QWidget::activateWindow();
- ui.password->setText("");
+ QWidget::show();
+ QWidget::activateWindow();
+ ui.password->setText("");
}
}
diff --git a/Swift/QtUI/QtJoinMUCWindow.h b/Swift/QtUI/QtJoinMUCWindow.h
index 618f2e9..c2e8068 100644
--- a/Swift/QtUI/QtJoinMUCWindow.h
+++ b/Swift/QtUI/QtJoinMUCWindow.h
@@ -16,60 +16,60 @@
#include <Swift/QtUI/ui_QtJoinMUCWindow.h>
namespace Swift {
- class UIEventStream;
- class NickValidator : public QValidator {
- Q_OBJECT
- public:
- NickValidator(QObject* parent) : QValidator(parent) {
- }
-
- virtual QValidator::State validate(QString& input, int& /*pos*/) const {
- if (input.isEmpty()) {
- return QValidator::Intermediate;
- }
- JID test("alice", "wonderland.lit", Q2PSTRING(input));
-
- return test.isValid() ? QValidator::Acceptable : QValidator::Invalid;
- }
- };
-
- class RoomJIDValidator : public QValidator {
- Q_OBJECT
- public:
- RoomJIDValidator(QObject* parent) : QValidator(parent) {
- }
-
- virtual QValidator::State validate(QString& input, int& /*pos*/) const {
- if (input.isEmpty()) {
- return QValidator::Intermediate;
- }
- JID roomJID(Q2PSTRING(input));
-
- if (roomJID.getNode().empty() || roomJID.getDomain().empty()) {
- return QValidator::Intermediate;
- }
-
- return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid;
- }
- };
-
- class QtJoinMUCWindow : public QWidget, public JoinMUCWindow {
- Q_OBJECT
- public:
- QtJoinMUCWindow(UIEventStream* uiEventStream);
-
- virtual void setNick(const std::string& nick);
- virtual void setMUC(const std::string& nick);
-
- virtual void show();
-
- private slots:
- void handleJoin();
- void handleSearch();
-
- private:
- Ui::QtJoinMUCWindow ui;
- std::string lastSetNick;
- UIEventStream* uiEventStream;
- };
+ class UIEventStream;
+ class NickValidator : public QValidator {
+ Q_OBJECT
+ public:
+ NickValidator(QObject* parent) : QValidator(parent) {
+ }
+
+ virtual QValidator::State validate(QString& input, int& /*pos*/) const {
+ if (input.isEmpty()) {
+ return QValidator::Intermediate;
+ }
+ JID test("alice", "wonderland.lit", Q2PSTRING(input));
+
+ return test.isValid() ? QValidator::Acceptable : QValidator::Invalid;
+ }
+ };
+
+ class RoomJIDValidator : public QValidator {
+ Q_OBJECT
+ public:
+ RoomJIDValidator(QObject* parent) : QValidator(parent) {
+ }
+
+ virtual QValidator::State validate(QString& input, int& /*pos*/) const {
+ if (input.isEmpty()) {
+ return QValidator::Intermediate;
+ }
+ JID roomJID(Q2PSTRING(input));
+
+ if (roomJID.getNode().empty() || roomJID.getDomain().empty()) {
+ return QValidator::Intermediate;
+ }
+
+ return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid;
+ }
+ };
+
+ class QtJoinMUCWindow : public QWidget, public JoinMUCWindow {
+ Q_OBJECT
+ public:
+ QtJoinMUCWindow(UIEventStream* uiEventStream);
+
+ virtual void setNick(const std::string& nick);
+ virtual void setMUC(const std::string& nick);
+
+ virtual void show();
+
+ private slots:
+ void handleJoin();
+ void handleSearch();
+
+ private:
+ Ui::QtJoinMUCWindow ui;
+ std::string lastSetNick;
+ UIEventStream* uiEventStream;
+ };
}
diff --git a/Swift/QtUI/QtLineEdit.cpp b/Swift/QtUI/QtLineEdit.cpp
index a98663c..d3ec4c4 100644
--- a/Swift/QtUI/QtLineEdit.cpp
+++ b/Swift/QtUI/QtLineEdit.cpp
@@ -14,10 +14,10 @@ QtLineEdit::QtLineEdit(QWidget* parent) : QLineEdit(parent) {
}
void QtLineEdit::keyPressEvent(QKeyEvent* event) {
- if (event->key() == Qt::Key_Escape) {
- emit escapePressed();
- }
- QLineEdit::keyPressEvent(event);
+ if (event->key() == Qt::Key_Escape) {
+ emit escapePressed();
+ }
+ QLineEdit::keyPressEvent(event);
}
}
diff --git a/Swift/QtUI/QtLineEdit.h b/Swift/QtUI/QtLineEdit.h
index 1c7240a..557f025 100644
--- a/Swift/QtUI/QtLineEdit.h
+++ b/Swift/QtUI/QtLineEdit.h
@@ -9,13 +9,13 @@
#include <QLineEdit>
namespace Swift {
- class QtLineEdit : public QLineEdit {
- Q_OBJECT
- public:
- QtLineEdit(QWidget* parent = NULL);
- signals:
- void escapePressed();
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- };
+ class QtLineEdit : public QLineEdit {
+ Q_OBJECT
+ public:
+ QtLineEdit(QWidget* parent = NULL);
+ signals:
+ void escapePressed();
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp
index 229df7f..5f15f4c 100644
--- a/Swift/QtUI/QtLoginWindow.cpp
+++ b/Swift/QtUI/QtLoginWindow.cpp
@@ -54,524 +54,524 @@
namespace Swift{
QtLoginWindow::QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory) : QMainWindow(), settings_(settings), timerFactory_(timerFactory) {
- uiEventStream_ = uiEventStream;
+ uiEventStream_ = uiEventStream;
- setWindowTitle("Swift");
+ setWindowTitle("Swift");
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- QtUtilities::setX11Resource(this, "Main");
- setAccessibleName(tr("Swift Login Window"));
- //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service"));
-
- resize(200, 500);
- setContentsMargins(0,0,0,0);
- QWidget *centralWidget = new QWidget(this);
- setCentralWidget(centralWidget);
- QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
- stack_ = new QStackedWidget(centralWidget);
- topLayout->addWidget(stack_);
- topLayout->setMargin(0);
- loginWidgetWrapper_ = new QWidget(this);
- loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_);
- layout->addStretch(2);
-
- QLabel* logo = new QLabel(this);
- logo->setPixmap(QPixmap(":/logo-shaded-text.256.png"));
- logo->setScaledContents(true);
- logo->setFixedSize(192,192);
-
- QWidget *logoWidget = new QWidget(this);
- QHBoxLayout *logoLayout = new QHBoxLayout();
- logoLayout->setMargin(0);
- logoLayout->addStretch(0);
- logoLayout->addWidget(logo);
- logoLayout->addStretch(0);
- logoWidget->setLayout(logoLayout);
- layout->addWidget(logoWidget);
-
- layout->addStretch(2);
-
- QLabel* jidLabel = new QLabel(this);
- jidLabel->setText("<font size='-1'>" + tr("User address:") + "</font>");
- layout->addWidget(jidLabel);
-
-
- username_ = new QComboBox(this);
- username_->setEditable(true);
- username_->setWhatsThis(tr("User address - looks like someuser@someserver.com"));
- username_->setToolTip(tr("User address - looks like someuser@someserver.com"));
- username_->view()->installEventFilter(this);
- username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)"));
- username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with"));
- layout->addWidget(username_);
- QLabel* jidHintLabel = new QLabel(this);
- jidHintLabel->setText("<font size='-1' color='grey' >" + tr("Example: alice@wonderland.lit") + "</font>");
- jidHintLabel->setAlignment(Qt::AlignRight);
- layout->addWidget(jidHintLabel);
-
-
- QLabel* passwordLabel = new QLabel();
- passwordLabel->setText("<font size='-1'>" + tr("Password:") + "</font>");
- passwordLabel->setAccessibleName(tr("User password"));
- passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service"));
- layout->addWidget(passwordLabel);
-
-
- QWidget* w = new QWidget(this);
- w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- layout->addWidget(w);
-
- QHBoxLayout* credentialsLayout = new QHBoxLayout(w);
- credentialsLayout->setMargin(0);
- credentialsLayout->setSpacing(3);
- password_ = new QLineEdit(this);
- password_->setEchoMode(QLineEdit::Password);
- connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked()));
- connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus()));
- connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged()));
- credentialsLayout->addWidget(password_);
-
- certificateButton_ = new QToolButton(this);
- certificateButton_->setCheckable(true);
- certificateButton_->setIcon(QIcon(":/icons/certificate.png"));
- certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service."));
- certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service."));
- certificateButton_->setAccessibleName(tr("Login with certificate"));
- certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service."));
-
- credentialsLayout->addWidget(certificateButton_);
- connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool)));
-
- loginButton_ = new QPushButton(this);
- loginButton_->setText(tr("Connect"));
- loginButton_->setAutoDefault(true);
- loginButton_->setDefault(true);
- loginButton_->setAccessibleName(tr("Connect now"));
- layout->addWidget(loginButton_);
-
- QLabel* connectionOptionsLabel = new QLabel(this);
- connectionOptionsLabel->setText("<a href=\"#\"><font size='-1'>" + QObject::tr("Connection Options") + "</font></a>");
- connectionOptionsLabel->setTextFormat(Qt::RichText);
- connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
- layout->addWidget(connectionOptionsLabel);
- connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions()));
-
- message_ = new QLabel(this);
- message_->setTextFormat(Qt::RichText);
- message_->setWordWrap(true);
- layout->addWidget(message_);
-
- layout->addStretch(2);
- remember_ = new QCheckBox(tr("Remember Password?"), this);
- layout->addWidget(remember_);
- loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this);
- layout->addWidget(loginAutomatically_);
-
- connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked()));
- stack_->addWidget(loginWidgetWrapper_);
+ QtUtilities::setX11Resource(this, "Main");
+ setAccessibleName(tr("Swift Login Window"));
+ //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service"));
+
+ resize(200, 500);
+ setContentsMargins(0,0,0,0);
+ QWidget *centralWidget = new QWidget(this);
+ setCentralWidget(centralWidget);
+ QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
+ stack_ = new QStackedWidget(centralWidget);
+ topLayout->addWidget(stack_);
+ topLayout->setMargin(0);
+ loginWidgetWrapper_ = new QWidget(this);
+ loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_);
+ layout->addStretch(2);
+
+ QLabel* logo = new QLabel(this);
+ logo->setPixmap(QPixmap(":/logo-shaded-text.256.png"));
+ logo->setScaledContents(true);
+ logo->setFixedSize(192,192);
+
+ QWidget *logoWidget = new QWidget(this);
+ QHBoxLayout *logoLayout = new QHBoxLayout();
+ logoLayout->setMargin(0);
+ logoLayout->addStretch(0);
+ logoLayout->addWidget(logo);
+ logoLayout->addStretch(0);
+ logoWidget->setLayout(logoLayout);
+ layout->addWidget(logoWidget);
+
+ layout->addStretch(2);
+
+ QLabel* jidLabel = new QLabel(this);
+ jidLabel->setText("<font size='-1'>" + tr("User address:") + "</font>");
+ layout->addWidget(jidLabel);
+
+
+ username_ = new QComboBox(this);
+ username_->setEditable(true);
+ username_->setWhatsThis(tr("User address - looks like someuser@someserver.com"));
+ username_->setToolTip(tr("User address - looks like someuser@someserver.com"));
+ username_->view()->installEventFilter(this);
+ username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)"));
+ username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with"));
+ layout->addWidget(username_);
+ QLabel* jidHintLabel = new QLabel(this);
+ jidHintLabel->setText("<font size='-1' color='grey' >" + tr("Example: alice@wonderland.lit") + "</font>");
+ jidHintLabel->setAlignment(Qt::AlignRight);
+ layout->addWidget(jidHintLabel);
+
+
+ QLabel* passwordLabel = new QLabel();
+ passwordLabel->setText("<font size='-1'>" + tr("Password:") + "</font>");
+ passwordLabel->setAccessibleName(tr("User password"));
+ passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service"));
+ layout->addWidget(passwordLabel);
+
+
+ QWidget* w = new QWidget(this);
+ w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ layout->addWidget(w);
+
+ QHBoxLayout* credentialsLayout = new QHBoxLayout(w);
+ credentialsLayout->setMargin(0);
+ credentialsLayout->setSpacing(3);
+ password_ = new QLineEdit(this);
+ password_->setEchoMode(QLineEdit::Password);
+ connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked()));
+ connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus()));
+ connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged()));
+ credentialsLayout->addWidget(password_);
+
+ certificateButton_ = new QToolButton(this);
+ certificateButton_->setCheckable(true);
+ certificateButton_->setIcon(QIcon(":/icons/certificate.png"));
+ certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service."));
+ certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service."));
+ certificateButton_->setAccessibleName(tr("Login with certificate"));
+ certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service."));
+
+ credentialsLayout->addWidget(certificateButton_);
+ connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool)));
+
+ loginButton_ = new QPushButton(this);
+ loginButton_->setText(tr("Connect"));
+ loginButton_->setAutoDefault(true);
+ loginButton_->setDefault(true);
+ loginButton_->setAccessibleName(tr("Connect now"));
+ layout->addWidget(loginButton_);
+
+ QLabel* connectionOptionsLabel = new QLabel(this);
+ connectionOptionsLabel->setText("<a href=\"#\"><font size='-1'>" + QObject::tr("Connection Options") + "</font></a>");
+ connectionOptionsLabel->setTextFormat(Qt::RichText);
+ connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
+ layout->addWidget(connectionOptionsLabel);
+ connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions()));
+
+ message_ = new QLabel(this);
+ message_->setTextFormat(Qt::RichText);
+ message_->setWordWrap(true);
+ layout->addWidget(message_);
+
+ layout->addStretch(2);
+ remember_ = new QCheckBox(tr("Remember Password?"), this);
+ layout->addWidget(remember_);
+ loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this);
+ layout->addWidget(loginAutomatically_);
+
+ connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked()));
+ stack_->addWidget(loginWidgetWrapper_);
#ifdef SWIFTEN_PLATFORM_MACOSX
- menuBar_ = new QMenuBar(NULL);
+ menuBar_ = new QMenuBar(NULL);
#else
- menuBar_ = menuBar();
+ menuBar_ = menuBar();
#endif
- QApplication::setQuitOnLastWindowClosed(false);
+ QApplication::setQuitOnLastWindowClosed(false);
- swiftMenu_ = new QMenu(tr("&Swift"), this);
+ swiftMenu_ = new QMenu(tr("&Swift"), this);
#ifdef SWIFTEN_PLATFORM_MACOSX
- generalMenu_ = new QMenu(tr("&General"), this);
+ generalMenu_ = new QMenu(tr("&General"), this);
#else
- generalMenu_ = swiftMenu_;
+ generalMenu_ = swiftMenu_;
#endif
#ifdef SWIFTEN_PLATFORM_MACOSX
- QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this);
+ QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this);
#else
- QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this);
+ QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this);
#endif
- connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout()));
- swiftMenu_->addAction(aboutAction);
+ connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout()));
+ swiftMenu_->addAction(aboutAction);
- xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this);
- connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole()));
- generalMenu_->addAction(xmlConsoleAction_);
+ xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this);
+ connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole()));
+ generalMenu_->addAction(xmlConsoleAction_);
#ifdef SWIFT_EXPERIMENTAL_FT
- fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this);
- connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview()));
- generalMenu_->addAction(fileTransferOverviewAction_);
+ fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this);
+ connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview()));
+ generalMenu_->addAction(fileTransferOverviewAction_);
#endif
- highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this);
- connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor()));
- generalMenu_->addAction(highlightEditorAction_);
+ highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this);
+ connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor()));
+ generalMenu_->addAction(highlightEditorAction_);
- toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this);
- toggleSoundsAction_->setCheckable(true);
- toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
- connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool)));
- generalMenu_->addAction(toggleSoundsAction_);
+ toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this);
+ toggleSoundsAction_->setCheckable(true);
+ toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
+ connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool)));
+ generalMenu_->addAction(toggleSoundsAction_);
- toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this);
- toggleNotificationsAction_->setCheckable(true);
- toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool)));
+ toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this);
+ toggleNotificationsAction_->setCheckable(true);
+ toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool)));
#ifndef SWIFTEN_PLATFORM_MACOSX
- swiftMenu_->addSeparator();
+ swiftMenu_->addSeparator();
#endif
#ifdef SWIFTEN_PLATFORM_MACOSX
- QAction* quitAction = new QAction("&Quit", this);
+ QAction* quitAction = new QAction("&Quit", this);
#else
- QAction* quitAction = new QAction(tr("&Quit"), this);
+ QAction* quitAction = new QAction(tr("&Quit"), this);
#endif
- connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit()));
- swiftMenu_->addAction(quitAction);
+ connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit()));
+ swiftMenu_->addAction(quitAction);
- setInitialMenus();
- settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1));
+ setInitialMenus();
+ settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1));
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- remember_->setEnabled(!eagle);
- loginAutomatically_->setEnabled(!eagle);
- xmlConsoleAction_->setEnabled(!eagle);
- if (eagle) {
- remember_->setChecked(false);
- loginAutomatically_->setChecked(false);
- }
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ remember_->setEnabled(!eagle);
+ loginAutomatically_->setEnabled(!eagle);
+ xmlConsoleAction_->setEnabled(!eagle);
+ if (eagle) {
+ remember_->setChecked(false);
+ loginAutomatically_->setChecked(false);
+ }
#ifdef SWIFTEN_PLATFORM_MACOSX
- // Temporary workaround for case 501. Could be that this code is still
- // needed when Qt provides a proper fix
- qApp->installEventFilter(this);
+ // Temporary workaround for case 501. Could be that this code is still
+ // needed when Qt provides a proper fix
+ qApp->installEventFilter(this);
#endif
- this->show();
+ this->show();
}
void QtLoginWindow::setShowNotificationToggle(bool toggle) {
- if (toggle) {
- QList< QAction* > generalMenuActions = generalMenu_->actions();
- generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_);
- }
- else {
- generalMenu_->removeAction(toggleNotificationsAction_);
- }
+ if (toggle) {
+ QList< QAction* > generalMenuActions = generalMenu_->actions();
+ generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_);
+ }
+ else {
+ generalMenu_->removeAction(toggleNotificationsAction_);
+ }
}
bool QtLoginWindow::eventFilter(QObject *obj, QEvent *event) {
- if (obj == username_->view() && event->type() == QEvent::KeyPress) {
- QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
- if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) {
- QString jid(username_->view()->currentIndex().data().toString());
- int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No);
- if (result == QMessageBox::Yes) {
- onPurgeSavedLoginRequest(Q2PSTRING(jid));
- }
- return true;
- }
- }
+ if (obj == username_->view() && event->type() == QEvent::KeyPress) {
+ QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
+ if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) {
+ QString jid(username_->view()->currentIndex().data().toString());
+ int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No);
+ if (result == QMessageBox::Yes) {
+ onPurgeSavedLoginRequest(Q2PSTRING(jid));
+ }
+ return true;
+ }
+ }
#ifdef SWIFTEN_PLATFORM_MACOSX
- // Dock clicked
- // Temporary workaround for case 501. Could be that this code is still
- // needed when Qt provides a proper fix
- if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) {
- bringToFront();
- }
+ // Dock clicked
+ // Temporary workaround for case 501. Could be that this code is still
+ // needed when Qt provides a proper fix
+ if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) {
+ bringToFront();
+ }
#endif
- return QObject::eventFilter(obj, event);
+ return QObject::eventFilter(obj, event);
}
void QtLoginWindow::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) {
- toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
- }
- if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
- toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
- }
+ if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) {
+ toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS));
+ }
+ if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) {
+ toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS));
+ }
}
void QtLoginWindow::selectUser(const std::string& username) {
- for (int i = 0; i < usernames_.count(); i++) {
- if (P2QSTRING(username) == usernames_[i]) {
- username_->setCurrentIndex(i);
- password_->setFocus();
- break;
- }
- }
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (P2QSTRING(username) == usernames_[i]) {
+ username_->setCurrentIndex(i);
+ password_->setFocus();
+ break;
+ }
+ }
}
void QtLoginWindow::removeAvailableAccount(const std::string& jid) {
- QString username = P2QSTRING(jid);
- int index = -1;
- for (int i = 0; i < usernames_.count(); i++) {
- if (username == usernames_[i]) {
- index = i;
- }
- }
- if (index >= 0) {
- usernames_.removeAt(index);
- passwords_.removeAt(index);
- certificateFiles_.removeAt(index);
- username_->removeItem(index);
- }
+ QString username = P2QSTRING(jid);
+ int index = -1;
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username == usernames_[i]) {
+ index = i;
+ }
+ }
+ if (index >= 0) {
+ usernames_.removeAt(index);
+ passwords_.removeAt(index);
+ certificateFiles_.removeAt(index);
+ username_->removeItem(index);
+ }
}
void QtLoginWindow::addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) {
- QString username = P2QSTRING(defaultJID);
- int index = -1;
- for (int i = 0; i < usernames_.count(); i++) {
- if (username == usernames_[i]) {
- index = i;
- }
- }
- if (index == -1) {
- usernames_.append(username);
- passwords_.append(P2QSTRING(defaultPassword));
- certificateFiles_.append(P2QSTRING(defaultCertificate));
- options_.push_back(options);
- username_->addItem(username);
- } else {
- usernames_[index] = username;
- passwords_[index] = P2QSTRING(defaultPassword);
- certificateFiles_[index] = P2QSTRING(defaultCertificate);
- options_[index] = options;
- }
+ QString username = P2QSTRING(defaultJID);
+ int index = -1;
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username == usernames_[i]) {
+ index = i;
+ }
+ }
+ if (index == -1) {
+ usernames_.append(username);
+ passwords_.append(P2QSTRING(defaultPassword));
+ certificateFiles_.append(P2QSTRING(defaultCertificate));
+ options_.push_back(options);
+ username_->addItem(username);
+ } else {
+ usernames_[index] = username;
+ passwords_[index] = P2QSTRING(defaultPassword);
+ certificateFiles_[index] = P2QSTRING(defaultCertificate);
+ options_[index] = options;
+ }
}
void QtLoginWindow::handleUsernameTextChanged() {
- QString username = username_->currentText();
- for (int i = 0; i < usernames_.count(); i++) {
- if (username_->currentText() == usernames_[i]) {
- certificateFile_ = certificateFiles_[i];
- password_->setText(passwords_[i]);
- remember_->setChecked(password_->text() != "");
- currentOptions_ = options_[i];
- }
- }
- certificateButton_->setChecked(!certificateFile_.isEmpty());
+ QString username = username_->currentText();
+ for (int i = 0; i < usernames_.count(); i++) {
+ if (username_->currentText() == usernames_[i]) {
+ certificateFile_ = certificateFiles_[i];
+ password_->setText(passwords_[i]);
+ remember_->setChecked(password_->text() != "");
+ currentOptions_ = options_[i];
+ }
+ }
+ certificateButton_->setChecked(!certificateFile_.isEmpty());
}
void QtLoginWindow::loggedOut() {
- stack_->removeWidget(stack_->currentWidget());
- stack_->addWidget(loginWidgetWrapper_);
- stack_->setCurrentWidget(loginWidgetWrapper_);
- setInitialMenus();
- setIsLoggingIn(false);
+ stack_->removeWidget(stack_->currentWidget());
+ stack_->addWidget(loginWidgetWrapper_);
+ stack_->setCurrentWidget(loginWidgetWrapper_);
+ setInitialMenus();
+ setIsLoggingIn(false);
}
void QtLoginWindow::setIsLoggingIn(bool loggingIn) {
- /* Change the for loop as well if you add to this.*/
- QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_};
- loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect"));
- for (int i = 0; i < 5; i++) {
- widgets[i]->setEnabled(!loggingIn);
- }
- bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
- remember_->setEnabled(!eagle);
- loginAutomatically_->setEnabled(!eagle);
+ /* Change the for loop as well if you add to this.*/
+ QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_};
+ loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect"));
+ for (int i = 0; i < 5; i++) {
+ widgets[i]->setEnabled(!loggingIn);
+ }
+ bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
+ remember_->setEnabled(!eagle);
+ loginAutomatically_->setEnabled(!eagle);
}
void QtLoginWindow::loginClicked() {
- if (username_->isEnabled()) {
- std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER);
- if (!banner.empty()) {
- QMessageBox msgBox;
- msgBox.setWindowTitle(tr("Confirm terms of use"));
- msgBox.setText("");
- msgBox.setInformativeText(P2QSTRING(banner));
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- if (msgBox.exec() != QMessageBox::Yes) {
- return;
- }
- }
- CertificateWithKey::ref certificate;
- std::string certificateString = Q2PSTRING(certificateFile_);
- if (!certificateString.empty()) {
+ if (username_->isEnabled()) {
+ std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER);
+ if (!banner.empty()) {
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Confirm terms of use"));
+ msgBox.setText("");
+ msgBox.setInformativeText(P2QSTRING(banner));
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ if (msgBox.exec() != QMessageBox::Yes) {
+ return;
+ }
+ }
+ CertificateWithKey::ref certificate;
+ std::string certificateString = Q2PSTRING(certificateFile_);
+ if (!certificateString.empty()) {
#if defined(HAVE_SCHANNEL)
- if (isCAPIURI(certificateString)) {
- certificate = boost::make_shared<CAPICertificate>(certificateString, timerFactory_);
- } else {
- certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
- }
+ if (isCAPIURI(certificateString)) {
+ certificate = boost::make_shared<CAPICertificate>(certificateString, timerFactory_);
+ } else {
+ certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ }
#else
- certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
#endif
- }
+ }
- onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked());
- if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */
- username_->clearEditText();
- password_->setText("");
- }
- } else {
- onCancelLoginRequest();
- }
+ onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked());
+ if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */
+ username_->clearEditText();
+ password_->setText("");
+ }
+ } else {
+ onCancelLoginRequest();
+ }
}
void QtLoginWindow::setLoginAutomatically(bool loginAutomatically) {
- loginAutomatically_->setChecked(loginAutomatically);
+ loginAutomatically_->setChecked(loginAutomatically);
}
void QtLoginWindow::handleCertficateChecked(bool checked) {
- if (checked) {
+ if (checked) {
#ifdef HAVE_SCHANNEL
- certificateFile_ = P2QSTRING(selectCAPICertificate());
- if (certificateFile_.isEmpty()) {
- certificateButton_->setChecked(false);
- }
+ certificateFile_ = P2QSTRING(selectCAPICertificate());
+ if (certificateFile_.isEmpty()) {
+ certificateButton_->setChecked(false);
+ }
#else
- certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)"));
- if (certificateFile_.isEmpty()) {
- certificateButton_->setChecked(false);
- }
+ certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)"));
+ if (certificateFile_.isEmpty()) {
+ certificateButton_->setChecked(false);
+ }
#endif
- }
- else {
- certificateFile_ = "";
- }
+ }
+ else {
+ certificateFile_ = "";
+ }
}
void QtLoginWindow::handleAbout() {
- if (!aboutDialog_) {
- aboutDialog_ = new QtAboutWidget();
- aboutDialog_->show();
- }
- else {
- aboutDialog_->show();
- aboutDialog_->raise();
- aboutDialog_->activateWindow();
- }
+ if (!aboutDialog_) {
+ aboutDialog_ = new QtAboutWidget();
+ aboutDialog_->show();
+ }
+ else {
+ aboutDialog_->show();
+ aboutDialog_->raise();
+ aboutDialog_->activateWindow();
+ }
}
void QtLoginWindow::handleShowXMLConsole() {
- uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
}
void QtLoginWindow::handleShowFileTransferOverview() {
- uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
}
void QtLoginWindow::handleShowHighlightEditor() {
- uiEventStream_->send(boost::make_shared<RequestHighlightEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestHighlightEditorUIEvent>());
}
void QtLoginWindow::handleToggleSounds(bool enabled) {
- settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled);
+ settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled);
}
void QtLoginWindow::handleToggleNotifications(bool enabled) {
- settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
+ settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
}
void QtLoginWindow::handleQuit() {
- onQuitRequest();
+ onQuitRequest();
}
void QtLoginWindow::quit() {
- QApplication::quit();
+ QApplication::quit();
}
void QtLoginWindow::setInitialMenus() {
- menuBar_->clear();
- menuBar_->addMenu(swiftMenu_);
+ menuBar_->clear();
+ menuBar_->addMenu(swiftMenu_);
#ifdef SWIFTEN_PLATFORM_MACOSX
- menuBar_->addMenu(generalMenu_);
+ 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) {
- menuBar_->addMenu(menu);
- }
- setFocus();
+ 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) {
+ 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("");
- }
+ 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();
- }
+ if (!isVisible()) {
+ bringToFront();
+ }
+ else {
+ window()->hide();
+ }
}
void QtLoginWindow::bringToFront() {
- window()->showNormal();
- window()->raise();
- window()->activateWindow();
+ window()->showNormal();
+ window()->raise();
+ window()->activateWindow();
}
void QtLoginWindow::hide() {
- window()->hide();
+ window()->hide();
}
QtLoginWindow::QtMenus QtLoginWindow::getMenus() const {
- return QtMenus(swiftMenu_, generalMenu_);
+ return QtMenus(swiftMenu_, generalMenu_);
}
void QtLoginWindow::resizeEvent(QResizeEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
void QtLoginWindow::moveEvent(QMoveEvent*) {
- emit geometryChanged();
+ emit geometryChanged();
}
bool QtLoginWindow::askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificates) {
- QMessageBox dialog(this);
-
- dialog.setText(tr("The certificate presented by the server is not valid."));
- dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct."));
-
- dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole);
- dialog.addButton(QMessageBox::Yes);
- dialog.addButton(QMessageBox::No);
- dialog.setDefaultButton(QMessageBox::No);
- while (true) {
- int result = dialog.exec();
- if (result == QMessageBox::Yes || result == QMessageBox::No) {
- return result == QMessageBox::Yes;
- }
- // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real
- // dialog with a custom button.
- QtMainWindow::openCertificateDialog(certificates, &dialog);
- }
+ QMessageBox dialog(this);
+
+ dialog.setText(tr("The certificate presented by the server is not valid."));
+ dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct."));
+
+ dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole);
+ dialog.addButton(QMessageBox::Yes);
+ dialog.addButton(QMessageBox::No);
+ dialog.setDefaultButton(QMessageBox::No);
+ while (true) {
+ int result = dialog.exec();
+ if (result == QMessageBox::Yes || result == QMessageBox::No) {
+ return result == QMessageBox::Yes;
+ }
+ // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real
+ // dialog with a custom button.
+ QtMainWindow::openCertificateDialog(certificates, &dialog);
+ }
}
void QtLoginWindow::handleOpenConnectionOptions() {
- QtConnectionSettingsWindow connectionSettings(currentOptions_);
- if (connectionSettings.exec() == QDialog::Accepted) {
- currentOptions_ = connectionSettings.getOptions();
- }
+ QtConnectionSettingsWindow connectionSettings(currentOptions_);
+ if (connectionSettings.exec() == QDialog::Accepted) {
+ currentOptions_ = connectionSettings.getOptions();
+ }
}
}
diff --git a/Swift/QtUI/QtLoginWindow.h b/Swift/QtUI/QtLoginWindow.h
index e8e2e20..91b21f6 100644
--- a/Swift/QtUI/QtLoginWindow.h
+++ b/Swift/QtUI/QtLoginWindow.h
@@ -25,89 +25,89 @@ class QToolButton;
class QComboBox;
namespace Swift {
- class SettingsProvider;
- class TimerFactory;
+ class SettingsProvider;
+ class TimerFactory;
- class QtLoginWindow : public QMainWindow, public LoginWindow {
- Q_OBJECT
- public:
- struct QtMenus {
- QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {}
- QMenu* swiftMenu;
- QMenu* generalMenu;
- };
+ class QtLoginWindow : public QMainWindow, public LoginWindow {
+ Q_OBJECT
+ public:
+ struct QtMenus {
+ QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {}
+ QMenu* swiftMenu;
+ QMenu* generalMenu;
+ };
- public:
- QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory);
+ public:
+ QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory);
- void morphInto(MainWindow *mainWindow);
- virtual void loggedOut();
- virtual void setShowNotificationToggle(bool);
- virtual void setMessage(const std::string& message);
- virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options);
- virtual void removeAvailableAccount(const std::string& jid);
- virtual void setLoginAutomatically(bool loginAutomatically);
- virtual void setIsLoggingIn(bool loggingIn);
- void selectUser(const std::string& user);
- bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificate);
- void hide();
- QtMenus getMenus() const;
- virtual void quit();
+ void morphInto(MainWindow *mainWindow);
+ virtual void loggedOut();
+ virtual void setShowNotificationToggle(bool);
+ virtual void setMessage(const std::string& message);
+ virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options);
+ virtual void removeAvailableAccount(const std::string& jid);
+ virtual void setLoginAutomatically(bool loginAutomatically);
+ virtual void setIsLoggingIn(bool loggingIn);
+ void selectUser(const std::string& user);
+ bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector<Certificate::ref>& certificate);
+ void hide();
+ QtMenus getMenus() const;
+ virtual void quit();
- signals:
- void geometryChanged();
+ signals:
+ void geometryChanged();
- private slots:
- void loginClicked();
- void handleCertficateChecked(bool);
- void handleQuit();
- void handleShowXMLConsole();
- void handleShowFileTransferOverview();
- void handleShowHighlightEditor();
- void handleToggleSounds(bool enabled);
- void handleToggleNotifications(bool enabled);
- void handleAbout();
- void bringToFront();
- void toggleBringToFront();
- void handleUsernameTextChanged();
- void resizeEvent(QResizeEvent* event);
- void moveEvent(QMoveEvent* event);
- void handleSettingChanged(const std::string& settingPath);
- void handleOpenConnectionOptions();
+ private slots:
+ void loginClicked();
+ void handleCertficateChecked(bool);
+ void handleQuit();
+ void handleShowXMLConsole();
+ void handleShowFileTransferOverview();
+ void handleShowHighlightEditor();
+ void handleToggleSounds(bool enabled);
+ void handleToggleNotifications(bool enabled);
+ void handleAbout();
+ void bringToFront();
+ void toggleBringToFront();
+ void handleUsernameTextChanged();
+ void resizeEvent(QResizeEvent* event);
+ void moveEvent(QMoveEvent* event);
+ void handleSettingChanged(const std::string& settingPath);
+ void handleOpenConnectionOptions();
- protected:
- bool eventFilter(QObject *obj, QEvent *event);
+ protected:
+ bool eventFilter(QObject *obj, QEvent *event);
- private:
- void setInitialMenus();
- QWidget* loginWidgetWrapper_;
- QStringList usernames_;
- QStringList passwords_;
- QStringList certificateFiles_;
- std::vector<ClientOptions> options_;
- QComboBox* username_;
- QLineEdit* password_;
- QPushButton* loginButton_;
- /* If you add a widget here, change setLoggingIn as well.*/
- QCheckBox* remember_;
- QCheckBox* loginAutomatically_;
- QStackedWidget* stack_;
- QLabel* message_;
- QString certificateFile_;
- QToolButton* certificateButton_;
- QMenuBar* menuBar_;
- QMenu* swiftMenu_;
- QMenu* generalMenu_;
- QMenu* viewMenu_;
- QAction* toggleSoundsAction_;
- QAction* toggleNotificationsAction_;
- UIEventStream* uiEventStream_;
- QPointer<QtAboutWidget> aboutDialog_;
- SettingsProvider* settings_;
- QAction* xmlConsoleAction_;
- QAction* fileTransferOverviewAction_;
- QAction* highlightEditorAction_;
- TimerFactory* timerFactory_;
- ClientOptions currentOptions_;
- };
+ private:
+ void setInitialMenus();
+ QWidget* loginWidgetWrapper_;
+ QStringList usernames_;
+ QStringList passwords_;
+ QStringList certificateFiles_;
+ std::vector<ClientOptions> options_;
+ QComboBox* username_;
+ QLineEdit* password_;
+ QPushButton* loginButton_;
+ /* If you add a widget here, change setLoggingIn as well.*/
+ QCheckBox* remember_;
+ QCheckBox* loginAutomatically_;
+ QStackedWidget* stack_;
+ QLabel* message_;
+ QString certificateFile_;
+ QToolButton* certificateButton_;
+ QMenuBar* menuBar_;
+ QMenu* swiftMenu_;
+ QMenu* generalMenu_;
+ QMenu* viewMenu_;
+ QAction* toggleSoundsAction_;
+ QAction* toggleNotificationsAction_;
+ UIEventStream* uiEventStream_;
+ QPointer<QtAboutWidget> aboutDialog_;
+ SettingsProvider* settings_;
+ QAction* xmlConsoleAction_;
+ QAction* fileTransferOverviewAction_;
+ QAction* highlightEditorAction_;
+ TimerFactory* timerFactory_;
+ ClientOptions currentOptions_;
+ };
}
diff --git a/Swift/QtUI/QtMUCConfigurationWindow.cpp b/Swift/QtUI/QtMUCConfigurationWindow.cpp
index a4ef9e3..629e94f 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.cpp
+++ b/Swift/QtUI/QtMUCConfigurationWindow.cpp
@@ -16,30 +16,30 @@
namespace Swift {
QtMUCConfigurationWindow::QtMUCConfigurationWindow(Form::ref form) : closed_(false) {
- setAttribute(Qt::WA_DeleteOnClose);
-
- QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- layout->setContentsMargins(0,0,0,0);
- layout->setSpacing(2);
- //QLabel* label = new QLabel(this);
- //label->setText(tr("Room configuration"));
- //layout->addWidget(label);
-
- formWidget_ = NULL;
- formWidget_ = new QtFormWidget(form, this);
- layout->addWidget(formWidget_);
-
- QWidget* buttonsWidget = new QWidget(this);
- layout->addWidget(buttonsWidget);
-
- QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget);
- cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget);
- buttonsLayout->addWidget(cancelButton_);
- connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
- okButton_ = new QPushButton(tr("OK"), buttonsWidget);
- buttonsLayout->addWidget(okButton_);
- connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked()));
- show();
+ setAttribute(Qt::WA_DeleteOnClose);
+
+ QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ layout->setContentsMargins(0,0,0,0);
+ layout->setSpacing(2);
+ //QLabel* label = new QLabel(this);
+ //label->setText(tr("Room configuration"));
+ //layout->addWidget(label);
+
+ formWidget_ = NULL;
+ formWidget_ = new QtFormWidget(form, this);
+ layout->addWidget(formWidget_);
+
+ QWidget* buttonsWidget = new QWidget(this);
+ layout->addWidget(buttonsWidget);
+
+ QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget);
+ cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget);
+ buttonsLayout->addWidget(cancelButton_);
+ connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked()));
+ okButton_ = new QPushButton(tr("OK"), buttonsWidget);
+ buttonsLayout->addWidget(okButton_);
+ connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked()));
+ show();
}
QtMUCConfigurationWindow::~QtMUCConfigurationWindow() {
@@ -47,19 +47,19 @@ QtMUCConfigurationWindow::~QtMUCConfigurationWindow() {
}
void QtMUCConfigurationWindow::closeEvent(QCloseEvent* /*event*/) {
- if (!closed_) {
- onFormCancelled();
- }
+ if (!closed_) {
+ onFormCancelled();
+ }
}
void QtMUCConfigurationWindow::handleCancelClicked() {
- close();
+ close();
}
void QtMUCConfigurationWindow::handleOKClicked() {
- onFormComplete(formWidget_->getCompletedForm());
- closed_ = true;
- close();
+ onFormComplete(formWidget_->getCompletedForm());
+ closed_ = true;
+ close();
}
diff --git a/Swift/QtUI/QtMUCConfigurationWindow.h b/Swift/QtUI/QtMUCConfigurationWindow.h
index bae7556..c8835e4 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.h
+++ b/Swift/QtUI/QtMUCConfigurationWindow.h
@@ -17,23 +17,23 @@ class QBoxLayout;
class QCloseEvent;
namespace Swift {
- class QtFormWidget;
- class QtMUCConfigurationWindow : public QWidget {
- Q_OBJECT
- public:
- QtMUCConfigurationWindow(Form::ref form);
- virtual ~QtMUCConfigurationWindow();
- boost::signal<void (Form::ref)> onFormComplete;
- boost::signal<void ()> onFormCancelled;
- private slots:
- void handleCancelClicked();
- void handleOKClicked();
- protected:
- virtual void closeEvent(QCloseEvent* event);
- private:
- QtFormWidget* formWidget_;
- QPushButton* okButton_;
- QPushButton* cancelButton_;
- bool closed_;
- };
+ class QtFormWidget;
+ class QtMUCConfigurationWindow : public QWidget {
+ Q_OBJECT
+ public:
+ QtMUCConfigurationWindow(Form::ref form);
+ virtual ~QtMUCConfigurationWindow();
+ boost::signal<void (Form::ref)> onFormComplete;
+ boost::signal<void ()> onFormCancelled;
+ private slots:
+ void handleCancelClicked();
+ void handleOKClicked();
+ protected:
+ virtual void closeEvent(QCloseEvent* event);
+ private:
+ QtFormWidget* formWidget_;
+ QPushButton* okButton_;
+ QPushButton* cancelButton_;
+ bool closed_;
+ };
}
diff --git a/Swift/QtUI/QtMainWindow.cpp b/Swift/QtUI/QtMainWindow.cpp
index e2092f6..d61026a 100644
--- a/Swift/QtUI/QtMainWindow.cpp
+++ b/Swift/QtUI/QtMainWindow.cpp
@@ -52,373 +52,373 @@
namespace Swift {
QtMainWindow::QtMainWindow(SettingsProvider* settings, UIEventStream* uiEventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID) : QWidget(), MainWindow(false), loginMenus_(loginMenus) {
- uiEventStream_ = uiEventStream;
- settings_ = settings;
- setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
- QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
- mainLayout->setContentsMargins(0,0,0,0);
- mainLayout->setSpacing(0);
- meView_ = new QtRosterHeader(settings, statusCache, this);
- mainLayout->addWidget(meView_);
- connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&)));
- connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest()));
- connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo()));
-
- tabs_ = new QtTabWidget(this);
+ uiEventStream_ = uiEventStream;
+ settings_ = settings;
+ setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+ QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this);
+ mainLayout->setContentsMargins(0,0,0,0);
+ mainLayout->setSpacing(0);
+ meView_ = new QtRosterHeader(settings, statusCache, this);
+ mainLayout->addWidget(meView_);
+ connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&)));
+ connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest()));
+ connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo()));
+
+ tabs_ = new QtTabWidget(this);
#if QT_VERSION >= 0x040500
- tabs_->setDocumentMode(true);
+ tabs_->setDocumentMode(true);
#endif
- tabs_->setTabPosition(QTabWidget::South);
- mainLayout->addWidget(tabs_);
- contactsTabWidget_ = new QWidget(this);
- contactsTabWidget_->setContentsMargins(0, 0, 0, 0);
- QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_);
- contactsTabWidget_->setLayout(contactTabLayout);
- contactTabLayout->setSpacing(0);
- contactTabLayout->setContentsMargins(0, 0, 0, 0);
-
- treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this);
-
- contactTabLayout->addWidget(treeWidget_);
- new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout);
-
- tabs_->addTab(contactsTabWidget_, tr("&Contacts"));
-
- eventWindow_ = new QtEventWindow(uiEventStream_);
- connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int)));
-
- chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_);
- connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int)));
-
- tabs_->addTab(chatListWindow_, tr("C&hats"));
- tabs_->addTab(eventWindow_, tr("&Notices"));
-
- tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB));
-
- connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int)));
-
- tabBarCombo_ = NULL;
- if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
- tabs_->tabBar()->hide();
- tabBarCombo_ = new QComboBox(this);
- tabBarCombo_->setAccessibleName("Current View");
- tabBarCombo_->addItem(tr("Contacts"));
- tabBarCombo_->addItem(tr("Chats"));
- tabBarCombo_->addItem(tr("Notices"));
- tabBarCombo_->setCurrentIndex(tabs_->currentIndex());
- mainLayout->addWidget(tabBarCombo_);
- connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int)));
- }
-
-
- this->setLayout(mainLayout);
-
- QMenu* viewMenu = new QMenu(tr("&View"), this);
- menus_.push_back(viewMenu);
-
- compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
- compactRosterAction_->setCheckable(true);
- compactRosterAction_->setChecked(false);
- connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool)));
- viewMenu->addAction(compactRosterAction_);
- handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
-
- showOfflineAction_ = new QAction(tr("&Show offline contacts"), this);
- showOfflineAction_->setCheckable(true);
- showOfflineAction_->setChecked(false);
- connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool)));
- viewMenu->addAction(showOfflineAction_);
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
-
- if (emoticonsExist) {
- showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this);
- showEmoticonsAction_->setCheckable(true);
- showEmoticonsAction_->setChecked(false);
- connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool)));
- viewMenu->addAction(showEmoticonsAction_);
- handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- }
-
- QMenu* actionsMenu = new QMenu(tr("&Actions"), this);
- menus_.push_back(actionsMenu);
- QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this);
- connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction()));
- actionsMenu->addAction(editProfileAction);
- onlineOnlyActions_ << editProfileAction;
- QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this);
- connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction()));
- actionsMenu->addAction(joinMUCAction);
- onlineOnlyActions_ << joinMUCAction;
+ tabs_->setTabPosition(QTabWidget::South);
+ mainLayout->addWidget(tabs_);
+ contactsTabWidget_ = new QWidget(this);
+ contactsTabWidget_->setContentsMargins(0, 0, 0, 0);
+ QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_);
+ contactsTabWidget_->setLayout(contactTabLayout);
+ contactTabLayout->setSpacing(0);
+ contactTabLayout->setContentsMargins(0, 0, 0, 0);
+
+ treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this);
+
+ contactTabLayout->addWidget(treeWidget_);
+ new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout);
+
+ tabs_->addTab(contactsTabWidget_, tr("&Contacts"));
+
+ eventWindow_ = new QtEventWindow(uiEventStream_);
+ connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int)));
+
+ chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_);
+ connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int)));
+
+ tabs_->addTab(chatListWindow_, tr("C&hats"));
+ tabs_->addTab(eventWindow_, tr("&Notices"));
+
+ tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB));
+
+ connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int)));
+
+ tabBarCombo_ = NULL;
+ if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) {
+ tabs_->tabBar()->hide();
+ tabBarCombo_ = new QComboBox(this);
+ tabBarCombo_->setAccessibleName("Current View");
+ tabBarCombo_->addItem(tr("Contacts"));
+ tabBarCombo_->addItem(tr("Chats"));
+ tabBarCombo_->addItem(tr("Notices"));
+ tabBarCombo_->setCurrentIndex(tabs_->currentIndex());
+ mainLayout->addWidget(tabBarCombo_);
+ connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int)));
+ }
+
+
+ this->setLayout(mainLayout);
+
+ QMenu* viewMenu = new QMenu(tr("&View"), this);
+ menus_.push_back(viewMenu);
+
+ compactRosterAction_ = new QAction(tr("&Compact Roster"), this);
+ compactRosterAction_->setCheckable(true);
+ compactRosterAction_->setChecked(false);
+ connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool)));
+ viewMenu->addAction(compactRosterAction_);
+ handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+
+ showOfflineAction_ = new QAction(tr("&Show offline contacts"), this);
+ showOfflineAction_->setCheckable(true);
+ showOfflineAction_->setChecked(false);
+ connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool)));
+ viewMenu->addAction(showOfflineAction_);
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+
+ if (emoticonsExist) {
+ showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this);
+ showEmoticonsAction_->setCheckable(true);
+ showEmoticonsAction_->setChecked(false);
+ connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool)));
+ viewMenu->addAction(showEmoticonsAction_);
+ handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ }
+
+ QMenu* actionsMenu = new QMenu(tr("&Actions"), this);
+ menus_.push_back(actionsMenu);
+ QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this);
+ connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction()));
+ actionsMenu->addAction(editProfileAction);
+ onlineOnlyActions_ << editProfileAction;
+ QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this);
+ connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction()));
+ actionsMenu->addAction(joinMUCAction);
+ onlineOnlyActions_ << joinMUCAction;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- QAction* viewLogsAction = new QAction(tr("&View History…"), this);
- connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction()));
- actionsMenu->addAction(viewLogsAction);
+ QAction* viewLogsAction = new QAction(tr("&View History…"), this);
+ connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction()));
+ actionsMenu->addAction(viewLogsAction);
#endif
- openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this);
- connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList()));
- actionsMenu->addAction(openBlockingListEditor_);
- onlineOnlyActions_ << openBlockingListEditor_;
- openBlockingListEditor_->setVisible(false);
- addUserAction_ = new QAction(tr("&Add Contact…"), this);
- addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
- addUserAction_->setShortcutContext(Qt::ApplicationShortcut);
- connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool)));
- actionsMenu->addAction(addUserAction_);
- onlineOnlyActions_ << addUserAction_;
- editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this);
- connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool)));
- actionsMenu->addAction(editUserAction_);
- onlineOnlyActions_ << editUserAction_;
- editUserAction_->setEnabled(false);
- chatUserAction_ = new QAction(tr("Start &Chat…"), this);
- chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
- chatUserAction_->setShortcutContext(Qt::ApplicationShortcut);
- connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool)));
- actionsMenu->addAction(chatUserAction_);
- onlineOnlyActions_ << chatUserAction_;
- if (enableAdHocCommandOnJID) {
- otherAdHocAction_ = new QAction(tr("Run Other Command"), this);
- connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered()));
- actionsMenu->addAction(otherAdHocAction_);
- onlineOnlyActions_ << otherAdHocAction_;
- }
- serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this);
- actionsMenu->addMenu(serverAdHocMenu_);
- actionsMenu->addSeparator();
- QAction* signOutAction = new QAction(tr("&Sign Out"), this);
- connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction()));
- actionsMenu->addAction(signOutAction);
-
- toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this);
- toggleRequestDeliveryReceipts_->setCheckable(true);
- toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
- connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool)));
-
- QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions();
- loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_);
-
- treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1));
-
- setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
- QAction* adHocAction = new QAction(tr("Collecting commands..."), this);
- adHocAction->setEnabled(false);
- serverAdHocMenu_->addAction(adHocAction);
- serverAdHocCommandActions_.append(adHocAction);
-
- settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
+ openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this);
+ connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList()));
+ actionsMenu->addAction(openBlockingListEditor_);
+ onlineOnlyActions_ << openBlockingListEditor_;
+ openBlockingListEditor_->setVisible(false);
+ addUserAction_ = new QAction(tr("&Add Contact…"), this);
+ addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
+ addUserAction_->setShortcutContext(Qt::ApplicationShortcut);
+ connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool)));
+ actionsMenu->addAction(addUserAction_);
+ onlineOnlyActions_ << addUserAction_;
+ editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this);
+ connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool)));
+ actionsMenu->addAction(editUserAction_);
+ onlineOnlyActions_ << editUserAction_;
+ editUserAction_->setEnabled(false);
+ chatUserAction_ = new QAction(tr("Start &Chat…"), this);
+ chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
+ chatUserAction_->setShortcutContext(Qt::ApplicationShortcut);
+ connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool)));
+ actionsMenu->addAction(chatUserAction_);
+ onlineOnlyActions_ << chatUserAction_;
+ if (enableAdHocCommandOnJID) {
+ otherAdHocAction_ = new QAction(tr("Run Other Command"), this);
+ connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered()));
+ actionsMenu->addAction(otherAdHocAction_);
+ onlineOnlyActions_ << otherAdHocAction_;
+ }
+ serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this);
+ actionsMenu->addMenu(serverAdHocMenu_);
+ actionsMenu->addSeparator();
+ QAction* signOutAction = new QAction(tr("&Sign Out"), this);
+ connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction()));
+ actionsMenu->addAction(signOutAction);
+
+ toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this);
+ toggleRequestDeliveryReceipts_->setCheckable(true);
+ toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
+ connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool)));
+
+ QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions();
+ loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_);
+
+ treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1));
+
+ setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
+ QAction* adHocAction = new QAction(tr("Collecting commands..."), this);
+ adHocAction->setEnabled(false);
+ serverAdHocMenu_->addAction(adHocAction);
+ serverAdHocCommandActions_.append(adHocAction);
+
+ settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
QtMainWindow::~QtMainWindow() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
+ settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1));
}
void QtMainWindow::handleTabChanged(int index) {
- settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index);
+ settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index);
}
void QtMainWindow::handleToggleRequestDeliveryReceipts(bool enabled) {
- settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled);
}
void QtMainWindow::handleShowCertificateInfo() {
- onShowCertificateRequest();
+ onShowCertificateRequest();
}
void QtMainWindow::handleEditBlockingList() {
- uiEventStream_->send(boost::make_shared<RequestBlockListDialogUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestBlockListDialogUIEvent>());
}
void QtMainWindow::handleSomethingSelectedChanged(bool itemSelected) {
- bool isOnline = addUserAction_->isEnabled();
- editUserAction_->setEnabled(isOnline && itemSelected);
+ bool isOnline = addUserAction_->isEnabled();
+ editUserAction_->setEnabled(isOnline && itemSelected);
}
QtEventWindow* QtMainWindow::getEventWindow() {
- return eventWindow_;
+ return eventWindow_;
}
QtChatListWindow* QtMainWindow::getChatListWindow() {
- return chatListWindow_;
+ return chatListWindow_;
}
void QtMainWindow::setRosterModel(Roster* roster) {
- treeWidget_->setRosterModel(roster);
+ treeWidget_->setRosterModel(roster);
}
void QtMainWindow::handleEditProfileRequest() {
- uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleEventCountUpdated(int count) {
- QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
- int eventIndex = 2;
- tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor);
- QString text = tr("&Notices");
- if (count > 0) {
- text += QString(" (%1)").arg(count);
- }
- tabs_->setTabText(eventIndex, text);
+ QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
+ int eventIndex = 2;
+ tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor);
+ QString text = tr("&Notices");
+ if (count > 0) {
+ text += QString(" (%1)").arg(count);
+ }
+ tabs_->setTabText(eventIndex, text);
}
void QtMainWindow::handleChatCountUpdated(int count) {
- QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
- int chatIndex = 1;
- tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor);
- QString text = tr("C&hats");
- if (count > 0) {
- text += QString(" (%1)").arg(count);
- }
- tabs_->setTabText(chatIndex, text);
+ QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default
+ int chatIndex = 1;
+ tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor);
+ QString text = tr("C&hats");
+ if (count > 0) {
+ text += QString(" (%1)").arg(count);
+ }
+ tabs_->setTabText(chatIndex, text);
}
void QtMainWindow::handleAddUserActionTriggered(bool /*checked*/) {
- boost::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
- uiEventStream_->send(event);
+ boost::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
+ uiEventStream_->send(event);
}
void QtMainWindow::handleChatUserActionTriggered(bool /*checked*/) {
- boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
- uiEventStream_->send(event);
+ boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
+ uiEventStream_->send(event);
}
void QtMainWindow::handleOtherAdHocActionTriggered() {
- new QtAdHocCommandWithJIDWindow(uiEventStream_);
+ new QtAdHocCommandWithJIDWindow(uiEventStream_);
}
void QtMainWindow::handleSignOutAction() {
- loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_);
- onSignOutRequest();
+ loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_);
+ onSignOutRequest();
}
void QtMainWindow::handleEditProfileAction() {
- uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleJoinMUCAction() {
- uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
}
void QtMainWindow::handleViewLogsAction() {
- uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
+ uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
}
void QtMainWindow::handleStatusChanged(StatusShow::Type showType, const QString &statusMessage) {
- onChangeStatusRequest(showType, Q2PSTRING(statusMessage));
+ onChangeStatusRequest(showType, Q2PSTRING(statusMessage));
}
void QtMainWindow::handleSettingChanged(const std::string& settingPath) {
- if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
- handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
- }
- if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
- handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
- }
- if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
- toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
- }
- if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- }
+ if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) {
+ handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+ }
+ if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) {
+ handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ }
+ if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) {
+ toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS));
+ }
+ if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ }
}
void QtMainWindow::handleCompactRosterToggled(bool state) {
- settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state);
- compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state);
+ compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
void QtMainWindow::handleShowOfflineToggled(bool state) {
- settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state);
- showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
+ settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state);
+ showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE));
}
void QtMainWindow::handleShowEmoticonsToggled(bool state) {
- settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state);
- showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
+ settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state);
+ showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS));
}
void QtMainWindow::setMyNick(const std::string& nick) {
- meView_->setNick(P2QSTRING(nick));
+ meView_->setNick(P2QSTRING(nick));
}
void QtMainWindow::setMyJID(const JID& jid) {
- meView_->setJID(P2QSTRING(jid.toBare().toString()));
+ meView_->setJID(P2QSTRING(jid.toBare().toString()));
}
void QtMainWindow::setMyAvatarPath(const std::string& path) {
- meView_->setAvatar(P2QSTRING(path));
+ meView_->setAvatar(P2QSTRING(path));
}
void QtMainWindow::setMyStatusText(const std::string& status) {
- meView_->setStatusText(P2QSTRING(status));
+ meView_->setStatusText(P2QSTRING(status));
}
void QtMainWindow::setMyStatusType(StatusShow::Type type) {
- meView_->setStatusType(type);
- const bool online = (type != StatusShow::None);
- treeWidget_->setOnline(online);
- chatListWindow_->setOnline(online);
- foreach (QAction *action, onlineOnlyActions_) {
- action->setEnabled(online);
- }
- serverAdHocMenu_->setEnabled(online);
+ meView_->setStatusType(type);
+ const bool online = (type != StatusShow::None);
+ treeWidget_->setOnline(online);
+ chatListWindow_->setOnline(online);
+ foreach (QAction *action, onlineOnlyActions_) {
+ action->setEnabled(online);
+ }
+ serverAdHocMenu_->setEnabled(online);
}
void QtMainWindow::setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
- meView_->setContactRosterItem(contact);
+ meView_->setContactRosterItem(contact);
}
void QtMainWindow::setConnecting() {
- meView_->setConnecting();
+ meView_->setConnecting();
}
void QtMainWindow::setStreamEncryptionStatus(bool tlsInPlaceAndValid) {
- meView_->setStreamEncryptionStatus(tlsInPlaceAndValid);
+ meView_->setStreamEncryptionStatus(tlsInPlaceAndValid);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain) {
- openCertificateDialog(chain, this);
+ openCertificateDialog(chain, this);
}
void QtMainWindow::openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent) {
#if defined(SWIFTEN_PLATFORM_MACOSX)
- CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain);
+ CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain);
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- WinUIHelpers::displayCertificateChainAsSheet(parent, chain);
+ WinUIHelpers::displayCertificateChainAsSheet(parent, chain);
#else
- QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain);
+ QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain);
#endif
}
void QtMainWindow::handleAdHocActionTriggered(bool /*checked*/) {
- QAction* action = qobject_cast<QAction*>(sender());
- assert(action);
- DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
- uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestAdHocUIEvent(command)));
+ QAction* action = qobject_cast<QAction*>(sender());
+ assert(action);
+ DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
+ uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestAdHocUIEvent(command)));
}
void QtMainWindow::setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands) {
- serverAdHocCommands_ = commands;
- foreach (QAction* action, serverAdHocCommandActions_) {
- delete action;
- }
- serverAdHocMenu_->clear();
- serverAdHocCommandActions_.clear();
- foreach (DiscoItems::Item command, commands) {
- QAction* action = new QAction(P2QSTRING(command.getName()), this);
- connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool)));
- serverAdHocMenu_->addAction(action);
- serverAdHocCommandActions_.append(action);
- }
- if (serverAdHocCommandActions_.isEmpty()) {
- QAction* action = new QAction(tr("No Available Commands"), this);
- action->setEnabled(false);
- serverAdHocMenu_->addAction(action);
- serverAdHocCommandActions_.append(action);
- }
+ serverAdHocCommands_ = commands;
+ foreach (QAction* action, serverAdHocCommandActions_) {
+ delete action;
+ }
+ serverAdHocMenu_->clear();
+ serverAdHocCommandActions_.clear();
+ foreach (DiscoItems::Item command, commands) {
+ QAction* action = new QAction(P2QSTRING(command.getName()), this);
+ connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool)));
+ serverAdHocMenu_->addAction(action);
+ serverAdHocCommandActions_.append(action);
+ }
+ if (serverAdHocCommandActions_.isEmpty()) {
+ QAction* action = new QAction(tr("No Available Commands"), this);
+ action->setEnabled(false);
+ serverAdHocMenu_->addAction(action);
+ serverAdHocCommandActions_.append(action);
+ }
}
void QtMainWindow::setBlockingCommandAvailable(bool isAvailable) {
- openBlockingListEditor_->setVisible(isAvailable);
+ openBlockingListEditor_->setVisible(isAvailable);
}
}
diff --git a/Swift/QtUI/QtMainWindow.h b/Swift/QtUI/QtMainWindow.h
index 71a5783..d90dade 100644
--- a/Swift/QtUI/QtMainWindow.h
+++ b/Swift/QtUI/QtMainWindow.h
@@ -28,83 +28,83 @@ class QMenu;
class QTabWidget;
namespace Swift {
- class QtRosterWidget;
- class TreeWidget;
- class UIEventStream;
- class QtTabWidget;
- class SettingsProvider;
- class QtUIPreferences;
- class StatusCache;
+ class QtRosterWidget;
+ class TreeWidget;
+ class UIEventStream;
+ class QtTabWidget;
+ class SettingsProvider;
+ class QtUIPreferences;
+ class StatusCache;
- class QtMainWindow : public QWidget, public MainWindow {
- Q_OBJECT
- public:
- QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID);
- virtual ~QtMainWindow();
- std::vector<QMenu*> getMenus() {return menus_;}
- void setMyNick(const std::string& name);
- void setMyJID(const JID& jid);
- void setMyAvatarPath(const std::string& path);
- void setMyStatusText(const std::string& status);
- void setMyStatusType(StatusShow::Type type);
- void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
- void setConnecting();
- void setStreamEncryptionStatus(bool tlsInPlaceAndValid);
- void openCertificateDialog(const std::vector<Certificate::ref>& chain);
- static void openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent);
- QtEventWindow* getEventWindow();
- QtChatListWindow* getChatListWindow();
- void setRosterModel(Roster* roster);
- void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands);
- void setBlockingCommandAvailable(bool isAvailable);
- private slots:
- void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage);
- void handleSettingChanged(const std::string& settingPath);
- void handleCompactRosterToggled(bool);
- void handleShowOfflineToggled(bool);
- void handleShowEmoticonsToggled(bool);
- void handleJoinMUCAction();
- void handleViewLogsAction();
- void handleSignOutAction();
- void handleEditProfileAction();
- void handleAddUserActionTriggered(bool checked);
- void handleChatUserActionTriggered(bool checked);
- void handleOtherAdHocActionTriggered();
- void handleAdHocActionTriggered(bool checked);
- void handleEventCountUpdated(int count);
- void handleChatCountUpdated(int count);
- void handleEditProfileRequest();
- void handleTabChanged(int index);
- void handleToggleRequestDeliveryReceipts(bool enabled);
- void handleShowCertificateInfo();
- void handleEditBlockingList();
- void handleSomethingSelectedChanged(bool itemSelected);
+ class QtMainWindow : public QWidget, public MainWindow {
+ Q_OBJECT
+ public:
+ QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID);
+ virtual ~QtMainWindow();
+ std::vector<QMenu*> getMenus() {return menus_;}
+ void setMyNick(const std::string& name);
+ void setMyJID(const JID& jid);
+ void setMyAvatarPath(const std::string& path);
+ void setMyStatusText(const std::string& status);
+ void setMyStatusType(StatusShow::Type type);
+ void setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
+ void setConnecting();
+ void setStreamEncryptionStatus(bool tlsInPlaceAndValid);
+ void openCertificateDialog(const std::vector<Certificate::ref>& chain);
+ static void openCertificateDialog(const std::vector<Certificate::ref>& chain, QWidget* parent);
+ QtEventWindow* getEventWindow();
+ QtChatListWindow* getChatListWindow();
+ void setRosterModel(Roster* roster);
+ void setAvailableAdHocCommands(const std::vector<DiscoItems::Item>& commands);
+ void setBlockingCommandAvailable(bool isAvailable);
+ private slots:
+ void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage);
+ void handleSettingChanged(const std::string& settingPath);
+ void handleCompactRosterToggled(bool);
+ void handleShowOfflineToggled(bool);
+ void handleShowEmoticonsToggled(bool);
+ void handleJoinMUCAction();
+ void handleViewLogsAction();
+ void handleSignOutAction();
+ void handleEditProfileAction();
+ void handleAddUserActionTriggered(bool checked);
+ void handleChatUserActionTriggered(bool checked);
+ void handleOtherAdHocActionTriggered();
+ void handleAdHocActionTriggered(bool checked);
+ void handleEventCountUpdated(int count);
+ void handleChatCountUpdated(int count);
+ void handleEditProfileRequest();
+ void handleTabChanged(int index);
+ void handleToggleRequestDeliveryReceipts(bool enabled);
+ void handleShowCertificateInfo();
+ void handleEditBlockingList();
+ void handleSomethingSelectedChanged(bool itemSelected);
- private:
- SettingsProvider* settings_;
- QtLoginWindow::QtMenus loginMenus_;
- std::vector<QMenu*> menus_;
- QtRosterWidget* treeWidget_;
- QtRosterHeader* meView_;
- QAction* addUserAction_;
- QAction* editUserAction_;
- QAction* chatUserAction_;
- QAction* otherAdHocAction_;
- QAction* showOfflineAction_;
- QAction* compactRosterAction_;
- QAction* showEmoticonsAction_;
- QAction* openBlockingListEditor_;
- QAction* toggleRequestDeliveryReceipts_;
- QMenu* serverAdHocMenu_;
- QtTabWidget* tabs_;
- QComboBox* tabBarCombo_;
- QWidget* contactsTabWidget_;
- QWidget* eventsTabWidget_;
- QtEventWindow* eventWindow_;
- QtChatListWindow* chatListWindow_;
- UIEventStream* uiEventStream_;
- std::vector<DiscoItems::Item> serverAdHocCommands_;
- QList<QAction*> serverAdHocCommandActions_;
- QList<QAction*> onlineOnlyActions_;
- };
+ private:
+ SettingsProvider* settings_;
+ QtLoginWindow::QtMenus loginMenus_;
+ std::vector<QMenu*> menus_;
+ QtRosterWidget* treeWidget_;
+ QtRosterHeader* meView_;
+ QAction* addUserAction_;
+ QAction* editUserAction_;
+ QAction* chatUserAction_;
+ QAction* otherAdHocAction_;
+ QAction* showOfflineAction_;
+ QAction* compactRosterAction_;
+ QAction* showEmoticonsAction_;
+ QAction* openBlockingListEditor_;
+ QAction* toggleRequestDeliveryReceipts_;
+ QMenu* serverAdHocMenu_;
+ QtTabWidget* tabs_;
+ QComboBox* tabBarCombo_;
+ QWidget* contactsTabWidget_;
+ QWidget* eventsTabWidget_;
+ QtEventWindow* eventWindow_;
+ QtChatListWindow* chatListWindow_;
+ UIEventStream* uiEventStream_;
+ std::vector<DiscoItems::Item> serverAdHocCommands_;
+ QList<QAction*> serverAdHocCommandActions_;
+ QList<QAction*> onlineOnlyActions_;
+ };
}
diff --git a/Swift/QtUI/QtNameWidget.cpp b/Swift/QtUI/QtNameWidget.cpp
index cf668c8..0610a00 100644
--- a/Swift/QtUI/QtNameWidget.cpp
+++ b/Swift/QtUI/QtNameWidget.cpp
@@ -18,80 +18,80 @@
namespace Swift {
QtNameWidget::QtNameWidget(SettingsProvider* settings, QWidget *parent) : QWidget(parent), settings(settings), isOnline_(false) {
- QHBoxLayout* mainLayout = new QHBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
+ QHBoxLayout* mainLayout = new QHBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
- mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID;
+ mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID;
- textLabel = new QtElidingLabel(this);
- QFont font = textLabel->font();
- font.setBold(true);
- textLabel->setFont(font);
- mainLayout->addWidget(textLabel);
+ textLabel = new QtElidingLabel(this);
+ QFont font = textLabel->font();
+ font.setBold(true);
+ textLabel->setFont(font);
+ mainLayout->addWidget(textLabel);
}
void QtNameWidget::setNick(const QString& nick) {
- this->nick = nick;
- updateText();
+ this->nick = nick;
+ updateText();
}
void QtNameWidget::setJID(const QString& jid) {
- this->jid = jid;
- updateText();
+ this->jid = jid;
+ updateText();
}
void QtNameWidget::setOnline(const bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
void QtNameWidget::mousePressEvent(QMouseEvent* event) {
- QMenu menu;
- bool hasNick = !nick.isEmpty();
-
- QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this);
- showAsNick->setCheckable(true);
- showAsNick->setEnabled(hasNick);
- if (mode == ShowNick && hasNick) {
- showAsNick->setChecked(true);
- }
- menu.addAction(showAsNick);
-
- QAction* showAsJID = new QAction(tr("Show Address"), this);
- showAsJID->setCheckable(true);
- if (mode == ShowJID || !hasNick) {
- showAsJID->setChecked(true);
- }
- menu.addAction(showAsJID);
-
- QAction* editProfile = new QAction(tr("Edit Profile"), this);
- menu.addAction(editProfile);
- editProfile->setEnabled(isOnline_);
-
- QAction* result = menu.exec(event->globalPos());
- if (result == showAsJID) {
- mode = ShowJID;
- }
- else if (result == showAsNick) {
- mode = ShowNick;
- }
- else if (result == editProfile) {
- emit onChangeNickRequest();
- }
- settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick);
- updateText();
+ QMenu menu;
+ bool hasNick = !nick.isEmpty();
+
+ QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this);
+ showAsNick->setCheckable(true);
+ showAsNick->setEnabled(hasNick);
+ if (mode == ShowNick && hasNick) {
+ showAsNick->setChecked(true);
+ }
+ menu.addAction(showAsNick);
+
+ QAction* showAsJID = new QAction(tr("Show Address"), this);
+ showAsJID->setCheckable(true);
+ if (mode == ShowJID || !hasNick) {
+ showAsJID->setChecked(true);
+ }
+ menu.addAction(showAsJID);
+
+ QAction* editProfile = new QAction(tr("Edit Profile"), this);
+ menu.addAction(editProfile);
+ editProfile->setEnabled(isOnline_);
+
+ QAction* result = menu.exec(event->globalPos());
+ if (result == showAsJID) {
+ mode = ShowJID;
+ }
+ else if (result == showAsNick) {
+ mode = ShowNick;
+ }
+ else if (result == editProfile) {
+ emit onChangeNickRequest();
+ }
+ settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick);
+ updateText();
}
void QtNameWidget::updateText() {
- QString text;
- if (mode == ShowNick && !nick.isEmpty()) {
- text = nick;
- }
- else {
- text = jid;
- }
- text.replace("<","&lt;");
- textLabel->setText(text);
+ QString text;
+ if (mode == ShowNick && !nick.isEmpty()) {
+ text = nick;
+ }
+ else {
+ text = jid;
+ }
+ text.replace("<","&lt;");
+ textLabel->setText(text);
}
}
diff --git a/Swift/QtUI/QtNameWidget.h b/Swift/QtUI/QtNameWidget.h
index 5f9962b..0da0ff6 100644
--- a/Swift/QtUI/QtNameWidget.h
+++ b/Swift/QtUI/QtNameWidget.h
@@ -9,38 +9,38 @@
#include <QWidget>
namespace Swift {
- class QtElidingLabel;
- class SettingsProvider;
-
- class QtNameWidget : public QWidget {
- Q_OBJECT
-
- public:
- QtNameWidget(SettingsProvider* settings, QWidget *parent);
-
- void setNick(const QString& text);
- void setJID(const QString& jid);
- void setOnline(const bool isOnline);
-
- signals:
- void onChangeNickRequest();
-
- private:
- void updateText();
- virtual void mousePressEvent(QMouseEvent* event);
-
- private:
- enum Mode {
- ShowNick,
- ShowJID
- };
-
- SettingsProvider* settings;
- Mode mode;
- QtElidingLabel* textLabel;
- QString jid;
- QString nick;
- bool isOnline_;
- };
+ class QtElidingLabel;
+ class SettingsProvider;
+
+ class QtNameWidget : public QWidget {
+ Q_OBJECT
+
+ public:
+ QtNameWidget(SettingsProvider* settings, QWidget *parent);
+
+ void setNick(const QString& text);
+ void setJID(const QString& jid);
+ void setOnline(const bool isOnline);
+
+ signals:
+ void onChangeNickRequest();
+
+ private:
+ void updateText();
+ virtual void mousePressEvent(QMouseEvent* event);
+
+ private:
+ enum Mode {
+ ShowNick,
+ ShowJID
+ };
+
+ SettingsProvider* settings;
+ Mode mode;
+ QtElidingLabel* textLabel;
+ QString jid;
+ QString nick;
+ bool isOnline_;
+ };
}
diff --git a/Swift/QtUI/QtPlainChatView.cpp b/Swift/QtUI/QtPlainChatView.cpp
index 3144080..9dc815a 100644
--- a/Swift/QtUI/QtPlainChatView.cpp
+++ b/Swift/QtUI/QtPlainChatView.cpp
@@ -31,402 +31,402 @@ 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_);
+ 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 (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
-
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
- text.replace("\n","<br/>");
- result += text;
- continue;
- }
- if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
- QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
- result += "<a href='" + uri + "' >" + uri + "</a>";
- continue;
- }
- if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
- result += P2QSTRING(emoticonPart->alternativeText);
- continue;
- }
- if ((highlightPart = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
- //FIXME: Maybe do something here. Anything, really.
- continue;
- }
- }
- return result;
+ QString result;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = boost::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
+ result += P2QSTRING(emoticonPart->alternativeText);
+ continue;
+ }
+ if ((highlightPart = boost::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, boost::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
- QString text = "<p>";
- if (label) {
- text += P2QSTRING(label->getLabel()) + "<br/>";
- }
- QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
- text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
- const std::string idx = senderIsSelf ? "" : senderName;
- lastMessageLabel_[idx] = label;
- return idx;
+ QString text = "<p>";
+ if (label) {
+ text += P2QSTRING(label->getLabel()) + "<br/>";
+ }
+ QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
+ text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
+ const std::string idx = senderIsSelf ? "" : senderName;
+ lastMessageLabel_[idx] = label;
+ return idx;
}
std::string QtPlainChatView::addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
- QString text = "<p>";
- if (label) {
- text += P2QSTRING(label->getLabel()) + "<br/>";
- }
- QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
- text += QString(tr("At %1 <i>%2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
- const std::string idx = senderIsSelf ? "" : senderName;
- lastMessageLabel_[idx] = label;
- return idx;
+ QString text = "<p>";
+ if (label) {
+ text += P2QSTRING(label->getLabel()) + "<br/>";
+ }
+ QString name = senderIsSelf ? "you" : P2QSTRING(senderName);
+ text += QString(tr("At %1 <i>%2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
+ const std::string idx = senderIsSelf ? "" : senderName;
+ lastMessageLabel_[idx] = label;
+ return idx;
}
std::string QtPlainChatView::addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
- return "";
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
+ return "";
}
void QtPlainChatView::addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::addErrorMessage(const ChatWindow::ChatMessage& message)
{
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time)
{
- QString text = "<p>";
- if (lastMessageLabel_[id]) {
- text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
- }
- QString name = id.empty() ? "you" : P2QSTRING(id);
- text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
+ QString text = "<p>";
+ if (lastMessageLabel_[id]) {
+ text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
+ }
+ QString name = id.empty() ? "you" : P2QSTRING(id);
+ text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
}
void QtPlainChatView::replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time)
{
- QString text = "<p>";
- if (lastMessageLabel_[id]) {
- text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
- }
- QString name = id.empty() ? "you" : P2QSTRING(id);
- text += QString(tr("At %1 %2 corrected the last action to: <i>")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p>";
+ if (lastMessageLabel_[id]) {
+ text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "<br/>";
+ }
+ QString name = id.empty() ? "you" : P2QSTRING(id);
+ text += QString(tr("At %1 %2 corrected the last action to: <i>")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name);
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/)
{
- QString text = "<p>The last message was corrected to:<br/>";
- text += chatMessageToString(message);
- text += "</p>";
- log_->append(text);
+ QString text = "<p>The last message was corrected to:<br/>";
+ text += chatMessageToString(message);
+ text += "</p>";
+ log_->append(text);
}
void QtPlainChatView::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& /*id*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) {
- QString text = "<p><i>";
- text += chatMessageToString(message);
- text += "</i></p>";
- log_->append(text);
+ QString text = "<p><i>";
+ text += chatMessageToString(message);
+ text += "</i></p>";
+ log_->append(text);
}
void QtPlainChatView::setAckState(const std::string& /*id*/, ChatWindow::AckState state)
{
- if (state == ChatWindow::Failed) {
- addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection);
- }
+ if (state == ChatWindow::Failed) {
+ addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection);
+ }
}
std::string QtPlainChatView::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description)
{
- const std::string ftId = "ft" + boost::lexical_cast<std::string>(idGenerator_++);
- const std::string sizeString = formatSize(sizeInBytes);
-
- FileTransfer* transfer;
- if (senderIsSelf) {
- QString description = QInputDialog::getText(this, tr("File transfer description"),
- tr("Description:"), QLineEdit::Normal, "");
- /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */
- const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\"");
- const std::string message = std::string() + "Confirm file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
- transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true);
- addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection);
- } else { /* incoming transfer */
- const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\"");
- const std::string message = std::string() + "Incoming file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
- transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true);
- addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection);
- }
-
- fileTransfers_[ftId] = transfer;
- layout()->addWidget(transfer->dialog_);
-
- return ftId;
+ const std::string ftId = "ft" + boost::lexical_cast<std::string>(idGenerator_++);
+ const std::string sizeString = formatSize(sizeInBytes);
+
+ FileTransfer* transfer;
+ if (senderIsSelf) {
+ QString description = QInputDialog::getText(this, tr("File transfer description"),
+ tr("Description:"), QLineEdit::Normal, "");
+ /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */
+ const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\"");
+ const std::string message = std::string() + "Confirm file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
+ transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true);
+ addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection);
+ } else { /* incoming transfer */
+ const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\"");
+ const std::string message = std::string() + "Incoming file transfer: <i>" + filename + " (" + sizeString + " bytes)</i>" + descriptionMessage;
+ transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true);
+ addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection);
+ }
+
+ fileTransfers_[ftId] = transfer;
+ layout()->addWidget(transfer->dialog_);
+
+ return ftId;
}
void QtPlainChatView::setFileTransferProgress(std::string id, const int percentageDone)
{
- FileTransferMap::iterator transfer = fileTransfers_.find(id);
- if (transfer != fileTransfers_.end()) {
- transfer->second->bar_->setValue(percentageDone);
- }
+ FileTransferMap::iterator transfer = fileTransfers_.find(id);
+ if (transfer != fileTransfers_.end()) {
+ transfer->second->bar_->setValue(percentageDone);
+ }
}
void QtPlainChatView::setFileTransferStatus(std::string id, const ChatWindow::FileTransferState state, const std::string& msg)
{
- FileTransferMap::iterator transferIter = fileTransfers_.find(id);
- if (transferIter == fileTransfers_.end()) {
- return;
- }
-
- /* store the layout index so we can restore it to the same location */
- FileTransfer* oldTransfer = transferIter->second;
- const int layoutIndex = layout()->indexOf(oldTransfer->dialog_);
- layout()->removeWidget(oldTransfer->dialog_);
- const std::string &label = (!msg.empty() ? msg : oldTransfer->message_);
- FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false);
- fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */
- delete oldTransfer;
-
- /* insert the new dialog at the old position in the layout list */
- QBoxLayout* parentLayout = dynamic_cast<QBoxLayout*>(layout());
- assert(parentLayout);
- parentLayout->insertWidget(layoutIndex, transfer->dialog_);
-
- /* log the transfer end result as a system message */
- if (state == ChatWindow::Finished) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection);
- } else if (state == ChatWindow::Canceled) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection);
- } else if (state == ChatWindow::FTFailed) {
- addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection);
- }
+ FileTransferMap::iterator transferIter = fileTransfers_.find(id);
+ if (transferIter == fileTransfers_.end()) {
+ return;
+ }
+
+ /* store the layout index so we can restore it to the same location */
+ FileTransfer* oldTransfer = transferIter->second;
+ const int layoutIndex = layout()->indexOf(oldTransfer->dialog_);
+ layout()->removeWidget(oldTransfer->dialog_);
+ const std::string &label = (!msg.empty() ? msg : oldTransfer->message_);
+ FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false);
+ fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */
+ delete oldTransfer;
+
+ /* insert the new dialog at the old position in the layout list */
+ QBoxLayout* parentLayout = dynamic_cast<QBoxLayout*>(layout());
+ assert(parentLayout);
+ parentLayout->insertWidget(layoutIndex, transfer->dialog_);
+
+ /* log the transfer end result as a system message */
+ if (state == ChatWindow::Finished) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection);
+ } else if (state == ChatWindow::Canceled) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection);
+ } else if (state == ChatWindow::FTFailed) {
+ addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection);
+ }
}
void QtPlainChatView::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& /*reason*/, const std::string& password, bool /*direct*/, bool isImpromptu, bool isContinuation)
{
- PopupDialog *invite = new PopupDialog(this);
+ PopupDialog *invite = new PopupDialog(this);
- QLabel* statusLabel = new QLabel;
- std::string msg = senderName + " has invited you to join " + jid.toString() + "...";
- statusLabel->setText(P2QSTRING(msg));
- invite->layout_->addWidget(statusLabel);
- invite->layout_->addWidget(new QLabel); /* padding */
+ QLabel* statusLabel = new QLabel;
+ std::string msg = senderName + " has invited you to join " + jid.toString() + "...";
+ statusLabel->setText(P2QSTRING(msg));
+ invite->layout_->addWidget(statusLabel);
+ invite->layout_->addWidget(new QLabel); /* padding */
- AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation);
- connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite()));
- invite->layout_->addWidget(accept);
+ AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation);
+ connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite()));
+ invite->layout_->addWidget(accept);
- AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation);
- connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite()));
- invite->layout_->addWidget(reject);
- statusLabel->setText(P2QSTRING(msg));
+ AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation);
+ connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite()));
+ invite->layout_->addWidget(reject);
+ statusLabel->setText(P2QSTRING(msg));
- layout()->addWidget(invite->dialog_);
+ layout()->addWidget(invite->dialog_);
- addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection);
+ addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection);
}
void QtPlainChatView::scrollToBottom()
{
- log_->ensureCursorVisible();
- log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
+ log_->ensureCursorVisible();
+ log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum());
}
void QtPlainChatView::fileTransferAccept()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (!action) {
- return;
- }
-
- FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
- if (transferIter == fileTransfers_.end()) {
- return;
- }
-
- FileTransfer* transfer = transferIter->second;
-
- const std::string message = transfer->message_;
-
- if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */
- window_->onFileTransferStart(transfer->ftId_, transfer->description_);
- } else { /* ask the user where to save the file first */
- QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_));
- if (path.isEmpty()) {
- fileTransferReject(); /* because the user did not select a desintation path */
- return;
- }
- window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path));
- }
-
- setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message);
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (!action) {
+ return;
+ }
+
+ FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
+ if (transferIter == fileTransfers_.end()) {
+ return;
+ }
+
+ FileTransfer* transfer = transferIter->second;
+
+ const std::string message = transfer->message_;
+
+ if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */
+ window_->onFileTransferStart(transfer->ftId_, transfer->description_);
+ } else { /* ask the user where to save the file first */
+ QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_));
+ if (path.isEmpty()) {
+ fileTransferReject(); /* because the user did not select a desintation path */
+ return;
+ }
+ window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path));
+ }
+
+ setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message);
}
void QtPlainChatView::fileTransferReject()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (action) {
- window_->onFileTransferCancel(action->id_);
- fileTransferFinish();
- }
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (action) {
+ window_->onFileTransferCancel(action->id_);
+ fileTransferFinish();
+ }
}
void QtPlainChatView::fileTransferFinish()
{
- FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
- if (action) {
- FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
- if (transferIter != fileTransfers_.end()) {
- delete transferIter->second; /* cause the dialog to close */
- fileTransfers_.erase(transferIter);
- }
- }
+ FileTransfer::Action* action = dynamic_cast<FileTransfer::Action*>(sender());
+ if (action) {
+ FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_);
+ if (transferIter != fileTransfers_.end()) {
+ delete transferIter->second; /* cause the dialog to close */
+ fileTransfers_.erase(transferIter);
+ }
+ }
}
void QtPlainChatView::acceptMUCInvite()
{
- AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
- if (action) {
- eventStream_->send(boost::make_shared<JoinMUCUIEvent>(action->jid_.toString(), action->password_, boost::optional<std::string>(), false, false, action->isImpromptu_, action->isContinuation_));
- delete action->parent_;
- }
+ AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
+ if (action) {
+ eventStream_->send(boost::make_shared<JoinMUCUIEvent>(action->jid_.toString(), action->password_, boost::optional<std::string>(), false, false, action->isImpromptu_, action->isContinuation_));
+ delete action->parent_;
+ }
}
void QtPlainChatView::rejectMUCInvite()
{
- AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
- if (action) {
- /* NOTE: no action required to reject an invite? */
- delete action->parent_;
- }
+ AcceptMUCInviteAction *action = dynamic_cast<AcceptMUCInviteAction*>(sender());
+ if (action) {
+ /* NOTE: no action required to reject an invite? */
+ delete action->parent_;
+ }
}
QtPlainChatView::FileTransfer::FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string &desc, const std::string& msg, bool initializing)
: PopupDialog(parent), bar_(0), senderIsSelf_(senderIsSelf), ftId_(ftId), filename_(filename), description_(desc), message_(msg), initializing_(initializing)
{
- QHBoxLayout* layout = new QHBoxLayout;
- QLabel* statusLabel = new QLabel;
- layout_->addWidget(statusLabel);
- layout_->addWidget(new QLabel); /* padding */
-
- if (initializing_) {
- FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId);
- parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept()));
- layout_->addWidget(accept);
- FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId);
- parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(reject);
- statusLabel->setText(P2QSTRING(msg));
- return;
- }
-
- std::string status = msg;
-
- switch (state) {
- case ChatWindow::Initialisation: {
- status = "Preparing to send <i>"+ filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::WaitingForAccept: {
- status = "Waiting for user to accept <i>" + filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Negotiating: {
- status = "Preparing to transfer <i>" + filename + "</i>...";
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Transferring: {
- status = "Transferring <i>" + filename + "</i>...";
- bar_ = new QProgressBar;
- bar_->setRange(0, 100);
- bar_->setValue(0);
- layout->addWidget(bar_);
- FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
- parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
- layout_->addWidget(cancel);
- break;
- }
- case ChatWindow::Canceled: {
- status = "File <i>" + filename + "</i> was canceled.";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- case ChatWindow::Finished: {
- status = "File <i>" + filename + "</i> was transfered successfully.";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- case ChatWindow::FTFailed: {
- status = "File transfer failed: <i>" + filename + "</i>";
- FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
- parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
- layout_->addWidget(finish);
- break;
- }
- }
-
- statusLabel->setText(P2QSTRING(status));
+ QHBoxLayout* layout = new QHBoxLayout;
+ QLabel* statusLabel = new QLabel;
+ layout_->addWidget(statusLabel);
+ layout_->addWidget(new QLabel); /* padding */
+
+ if (initializing_) {
+ FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId);
+ parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept()));
+ layout_->addWidget(accept);
+ FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId);
+ parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(reject);
+ statusLabel->setText(P2QSTRING(msg));
+ return;
+ }
+
+ std::string status = msg;
+
+ switch (state) {
+ case ChatWindow::Initialisation: {
+ status = "Preparing to send <i>"+ filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::WaitingForAccept: {
+ status = "Waiting for user to accept <i>" + filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Negotiating: {
+ status = "Preparing to transfer <i>" + filename + "</i>...";
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Transferring: {
+ status = "Transferring <i>" + filename + "</i>...";
+ bar_ = new QProgressBar;
+ bar_->setRange(0, 100);
+ bar_->setValue(0);
+ layout->addWidget(bar_);
+ FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId);
+ parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject()));
+ layout_->addWidget(cancel);
+ break;
+ }
+ case ChatWindow::Canceled: {
+ status = "File <i>" + filename + "</i> was canceled.";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ case ChatWindow::Finished: {
+ status = "File <i>" + filename + "</i> was transfered successfully.";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ case ChatWindow::FTFailed: {
+ status = "File transfer failed: <i>" + filename + "</i>";
+ FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId);
+ parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish()));
+ layout_->addWidget(finish);
+ break;
+ }
+ }
+
+ statusLabel->setText(P2QSTRING(status));
}
void QtPlainChatView::LogTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
- QMenu *menu = createStandardContextMenu();
- menu->exec(event->globalPos());
- delete menu;
+ QMenu *menu = createStandardContextMenu();
+ menu->exec(event->globalPos());
+ delete menu;
}
}
diff --git a/Swift/QtUI/QtPlainChatView.h b/Swift/QtUI/QtPlainChatView.h
index fc293ff..cd6ab7e 100644
--- a/Swift/QtUI/QtPlainChatView.h
+++ b/Swift/QtUI/QtPlainChatView.h
@@ -23,112 +23,112 @@ class QTextEdit;
class QProgressBar;
namespace Swift {
- class HighlightAction;
- class SecurityLabel;
-
- class QtPlainChatView : public QtChatView {
- Q_OBJECT
- public:
- QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream);
- virtual ~QtPlainChatView();
-
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
-
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
- virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/);
-
- virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
- virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
- virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/);
-
- virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/);
- virtual void setFileTransferProgress(std::string, const int /*percentageDone*/);
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = "");
- virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/);
- virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";};
- virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {};
- virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {};
-
- virtual void showEmoticons(bool /*show*/) {};
- virtual void addLastSeenLine() {};
-
- public slots:
- virtual void resizeFont(int /*fontSizeSteps*/) {};
- virtual void scrollToBottom();
- virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {};
- virtual void fileTransferAccept();
- virtual void fileTransferReject();
- virtual void fileTransferFinish();
- virtual void acceptMUCInvite();
- virtual void rejectMUCInvite();
-
- private:
- struct PopupDialog {
- PopupDialog(QtPlainChatView* parent) {
- dialog_ = new QFrame(parent);
- dialog_->setFrameShape(QFrame::Panel);
- dialog_->setFrameShadow(QFrame::Raised);
- layout_ = new QHBoxLayout;
- dialog_->setLayout(layout_);
- }
- virtual ~PopupDialog() {
- delete dialog_;
- }
- QFrame* dialog_;
- QHBoxLayout* layout_;
- };
-
- struct AcceptMUCInviteAction : public QPushButton {
- AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation)
- : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {}
- PopupDialog *parent_;
- JID jid_;
- std::string senderName_;
- std::string password_;
- bool isImpromptu_;
- bool isContinuation_;
- };
-
- struct FileTransfer : public PopupDialog {
- struct Action : QPushButton {
- Action(const std::string& text, const std::string& id)
- : QPushButton(P2QSTRING(text)), id_(id) {}
- std::string id_;
- };
- FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing);
- QProgressBar* bar_;
- bool senderIsSelf_;
- std::string ftId_;
- std::string filename_;
- std::string description_;
- std::string message_;
- bool initializing_;
- };
-
- class LogTextEdit : public QTextEdit {
- public:
- LogTextEdit(QWidget* parent) : QTextEdit(parent) {}
- virtual ~LogTextEdit() {}
- virtual void contextMenuEvent(QContextMenuEvent *event);
- };
-
- typedef std::map<std::string, FileTransfer*> FileTransferMap;
- QtChatWindow* window_;
- UIEventStream* eventStream_;
- LogTextEdit* log_;
- FileTransferMap fileTransfers_;
- std::map<std::string, boost::shared_ptr<SecurityLabel> > lastMessageLabel_;
- int idGenerator_;
-
- };
+ class HighlightAction;
+ class SecurityLabel;
+
+ class QtPlainChatView : public QtChatView {
+ Q_OBJECT
+ public:
+ QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream);
+ virtual ~QtPlainChatView();
+
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/);
+
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/);
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/);
+
+ virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/);
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/);
+ virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/);
+
+ virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/);
+ virtual void setFileTransferProgress(std::string, const int /*percentageDone*/);
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = "");
+ virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/);
+ virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";};
+ virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {};
+ virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {};
+
+ virtual void showEmoticons(bool /*show*/) {};
+ virtual void addLastSeenLine() {};
+
+ public slots:
+ virtual void resizeFont(int /*fontSizeSteps*/) {};
+ virtual void scrollToBottom();
+ virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {};
+ virtual void fileTransferAccept();
+ virtual void fileTransferReject();
+ virtual void fileTransferFinish();
+ virtual void acceptMUCInvite();
+ virtual void rejectMUCInvite();
+
+ private:
+ struct PopupDialog {
+ PopupDialog(QtPlainChatView* parent) {
+ dialog_ = new QFrame(parent);
+ dialog_->setFrameShape(QFrame::Panel);
+ dialog_->setFrameShadow(QFrame::Raised);
+ layout_ = new QHBoxLayout;
+ dialog_->setLayout(layout_);
+ }
+ virtual ~PopupDialog() {
+ delete dialog_;
+ }
+ QFrame* dialog_;
+ QHBoxLayout* layout_;
+ };
+
+ struct AcceptMUCInviteAction : public QPushButton {
+ AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation)
+ : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {}
+ PopupDialog *parent_;
+ JID jid_;
+ std::string senderName_;
+ std::string password_;
+ bool isImpromptu_;
+ bool isContinuation_;
+ };
+
+ struct FileTransfer : public PopupDialog {
+ struct Action : QPushButton {
+ Action(const std::string& text, const std::string& id)
+ : QPushButton(P2QSTRING(text)), id_(id) {}
+ std::string id_;
+ };
+ FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing);
+ QProgressBar* bar_;
+ bool senderIsSelf_;
+ std::string ftId_;
+ std::string filename_;
+ std::string description_;
+ std::string message_;
+ bool initializing_;
+ };
+
+ class LogTextEdit : public QTextEdit {
+ public:
+ LogTextEdit(QWidget* parent) : QTextEdit(parent) {}
+ virtual ~LogTextEdit() {}
+ virtual void contextMenuEvent(QContextMenuEvent *event);
+ };
+
+ typedef std::map<std::string, FileTransfer*> FileTransferMap;
+ QtChatWindow* window_;
+ UIEventStream* eventStream_;
+ LogTextEdit* log_;
+ FileTransferMap fileTransfers_;
+ std::map<std::string, boost::shared_ptr<SecurityLabel> > lastMessageLabel_;
+ int idGenerator_;
+
+ };
}
diff --git a/Swift/QtUI/QtProfileWindow.cpp b/Swift/QtUI/QtProfileWindow.cpp
index 8b4b044..461ea38 100644
--- a/Swift/QtUI/QtProfileWindow.cpp
+++ b/Swift/QtUI/QtProfileWindow.cpp
@@ -25,143 +25,143 @@
namespace Swift {
QtProfileWindow::QtProfileWindow() :
- QWidget(),
- ui(new Ui::QtProfileWindow) {
- ui->setupUi(this);
+ QWidget(),
+ ui(new Ui::QtProfileWindow) {
+ ui->setupUi(this);
- ui->statusLabel->setText(tr("Retrieving profile information for this user."));
- ui->statusLabel->setVisible(false);
+ ui->statusLabel->setText(tr("Retrieving profile information for this user."));
+ ui->statusLabel->setVisible(false);
- ui->emptyLabel->setText(tr("No profile information is available for this user."));
- ui->emptyLabel->setVisible(false);
+ ui->emptyLabel->setText(tr("No profile information is available for this user."));
+ ui->emptyLabel->setVisible(false);
- new QShortcut(QKeySequence::Close, this, SLOT(close()));
- ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave()));
- setEditable(false);
- setAttribute(Qt::WA_DeleteOnClose);
- setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
+ new QShortcut(QKeySequence::Close, this, SLOT(close()));
+ ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave()));
+ setEditable(false);
+ setAttribute(Qt::WA_DeleteOnClose);
+ setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
- adjustSizeTimer.setSingleShot(true);
- connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout()));
+ adjustSizeTimer.setSingleShot(true);
+ connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout()));
}
QtProfileWindow::~QtProfileWindow() {
- delete ui;
+ delete ui;
}
void QtProfileWindow::setJID(const JID& jid) {
- this->jid = jid;
- updateTitle();
+ this->jid = jid;
+ updateTitle();
}
void QtProfileWindow::setVCard(VCard::ref vcard) {
- ui->vcard->setVCard(vcard);
- if (vcard->isEmpty()) {
- ui->vcard->setVisible(false);
- ui->emptyLabel->setVisible(true);
- } else {
- ui->vcard->setVisible(true);
- ui->emptyLabel->setVisible(false);
- }
- updateWindowSize();
+ ui->vcard->setVCard(vcard);
+ if (vcard->isEmpty()) {
+ ui->vcard->setVisible(false);
+ ui->emptyLabel->setVisible(true);
+ } else {
+ ui->vcard->setVisible(true);
+ ui->emptyLabel->setVisible(false);
+ }
+ updateWindowSize();
}
void QtProfileWindow::setEnabled(bool b) {
- ui->vcard->setEnabled(b);
- ui->savePushButton->setEnabled(b);
+ ui->vcard->setEnabled(b);
+ ui->savePushButton->setEnabled(b);
}
void QtProfileWindow::setEditable(bool b) {
- ui->throbberLabel->setVisible(b);
- ui->errorLabel->setVisible(b);
- ui->savePushButton->setVisible(b);
- ui->vcard->setEditable(b);
- updateTitle();
- updateWindowSize();
+ ui->throbberLabel->setVisible(b);
+ ui->errorLabel->setVisible(b);
+ ui->savePushButton->setVisible(b);
+ ui->vcard->setEditable(b);
+ updateTitle();
+ updateWindowSize();
}
void QtProfileWindow::setProcessing(bool processing) {
- if (processing) {
- ui->throbberLabel->movie()->start();
- ui->throbberLabel->show();
- ui->statusLabel->setVisible(true);
- ui->vcard->setVisible(false);
- }
- else {
- ui->throbberLabel->hide();
- ui->throbberLabel->movie()->stop();
- ui->statusLabel->setVisible(false);
- ui->vcard->setVisible(true);
- }
+ if (processing) {
+ ui->throbberLabel->movie()->start();
+ ui->throbberLabel->show();
+ ui->statusLabel->setVisible(true);
+ ui->vcard->setVisible(false);
+ }
+ else {
+ ui->throbberLabel->hide();
+ ui->throbberLabel->movie()->stop();
+ ui->statusLabel->setVisible(false);
+ ui->vcard->setVisible(true);
+ }
}
void QtProfileWindow::setError(const std::string& error) {
- if (!error.empty()) {
- ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
- }
- else {
- ui->errorLabel->setText("");
- }
+ if (!error.empty()) {
+ ui->errorLabel->setText("<font color='red'>" + QtUtilities::htmlEscape(P2QSTRING(error)) + "</font>");
+ }
+ else {
+ ui->errorLabel->setText("");
+ }
}
void QtProfileWindow::show() {
- QWidget::showNormal();
- QWidget::activateWindow();
- QWidget::raise();
+ QWidget::showNormal();
+ QWidget::activateWindow();
+ QWidget::raise();
}
void QtProfileWindow::hide() {
- QWidget::hide();
+ QWidget::hide();
}
QSize QtProfileWindow::sizeHint() const {
- return QWidget::sizeHint();
+ return QWidget::sizeHint();
}
void QtProfileWindow::updateTitle() {
- QString jidString;
- if (jid.isValid()) {
- jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString()));
- }
+ QString jidString;
+ if (jid.isValid()) {
+ jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString()));
+ }
- if (ui->vcard->isEditable()) {
- setWindowTitle(tr("Edit Profile") + jidString);
- } else {
- setWindowTitle(tr("Show Profile") + jidString);
- }
+ if (ui->vcard->isEditable()) {
+ 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);
- }
+ // 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);
+ event->accept();
+ onWindowAboutToBeClosed(jid);
}
void QtProfileWindow::handleSave() {
- onVCardChangeRequest(ui->vcard->getVCard());
+ 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) {
- child->updateGeometry();
- }
-
- updateGeometry();
- adjustSize();
+ // 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) {
+ child->updateGeometry();
+ }
+
+ updateGeometry();
+ adjustSize();
}
}
diff --git a/Swift/QtUI/QtProfileWindow.h b/Swift/QtUI/QtProfileWindow.h
index 0821444..7315807 100644
--- a/Swift/QtUI/QtProfileWindow.h
+++ b/Swift/QtUI/QtProfileWindow.h
@@ -20,44 +20,44 @@
#include <Swift/Controllers/UIInterfaces/ProfileWindow.h>
namespace Ui {
- class QtProfileWindow;
+ class QtProfileWindow;
}
namespace Swift {
class QtProfileWindow : public QWidget, public ProfileWindow {
- Q_OBJECT
+ Q_OBJECT
- public:
- QtProfileWindow();
- virtual ~QtProfileWindow();
+ public:
+ QtProfileWindow();
+ virtual ~QtProfileWindow();
- virtual void setJID(const JID& jid);
- virtual void setVCard(VCard::ref vcard);
+ virtual void setJID(const JID& jid);
+ virtual void setVCard(VCard::ref vcard);
- virtual void setEnabled(bool b);
- virtual void setProcessing(bool processing);
- virtual void setError(const std::string& error);
- virtual void setEditable(bool b);
+ virtual void setEnabled(bool b);
+ virtual void setProcessing(bool processing);
+ virtual void setError(const std::string& error);
+ virtual void setEditable(bool b);
- virtual void show();
- virtual void hide();
+ virtual void show();
+ virtual void hide();
- virtual QSize sizeHint() const;
+ virtual QSize sizeHint() const;
- private:
- void updateTitle();
- void updateWindowSize();
- virtual void closeEvent(QCloseEvent* event);
+ private:
+ void updateTitle();
+ void updateWindowSize();
+ virtual void closeEvent(QCloseEvent* event);
- private slots:
- void handleSave();
- void handleAdjustSizeTimeout();
+ private slots:
+ void handleSave();
+ void handleAdjustSizeTimeout();
- private:
- Ui::QtProfileWindow* ui;
- JID jid;
- QTimer adjustSizeTimer;
+ private:
+ Ui::QtProfileWindow* ui;
+ JID jid;
+ QTimer adjustSizeTimer;
};
}
diff --git a/Swift/QtUI/QtResourceHelper.cpp b/Swift/QtUI/QtResourceHelper.cpp
index f76c438..a802b19 100644
--- a/Swift/QtUI/QtResourceHelper.cpp
+++ b/Swift/QtUI/QtResourceHelper.cpp
@@ -9,16 +9,16 @@
namespace Swift {
QString statusShowTypeToIconPath(StatusShow::Type type) {
- QString iconString;
- switch (type) {
- case StatusShow::Online: iconString = "online";break;
- case StatusShow::Away: iconString = "away";break;
- case StatusShow::XA: iconString = "away";break;
- case StatusShow::FFC: iconString = "online";break;
- case StatusShow::DND: iconString = "dnd";break;
- case StatusShow::None: iconString = "offline";break;
- }
- return QString(":/icons/%1.png").arg(iconString);
+ QString iconString;
+ switch (type) {
+ case StatusShow::Online: iconString = "online";break;
+ case StatusShow::Away: iconString = "away";break;
+ case StatusShow::XA: iconString = "away";break;
+ case StatusShow::FFC: iconString = "online";break;
+ case StatusShow::DND: iconString = "dnd";break;
+ case StatusShow::None: iconString = "offline";break;
+ }
+ return QString(":/icons/%1.png").arg(iconString);
}
}
diff --git a/Swift/QtUI/QtRosterHeader.cpp b/Swift/QtUI/QtRosterHeader.cpp
index 4783a64..f8a4cdb 100644
--- a/Swift/QtUI/QtRosterHeader.cpp
+++ b/Swift/QtUI/QtRosterHeader.cpp
@@ -28,112 +28,112 @@
namespace Swift {
QtRosterHeader::QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent) : QWidget(parent), statusEdit_(NULL) {
- QHBoxLayout* topLayout = new QHBoxLayout();
- topLayout->setSpacing(3);
- topLayout->setContentsMargins(4,4,4,4);
- setLayout(topLayout);
- setMinimumHeight(50);
- setMaximumHeight(50);
-
- avatarLabel_ = new QtClickableLabel(this);
- avatarLabel_->setMinimumSize(avatarSize_, avatarSize_);
- avatarLabel_->setMaximumSize(avatarSize_, avatarSize_);
- avatarLabel_->setAlignment(Qt::AlignCenter);
- setAvatar(":/icons/avatar.png");
- avatarLabel_->setScaledContents(false);
- topLayout->addWidget(avatarLabel_);
- connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
-
- QVBoxLayout* rightLayout = new QVBoxLayout();
- rightLayout->setSpacing(4);
- rightLayout->setContentsMargins(4,0,0,0);
- topLayout->addLayout(rightLayout);
-
- QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout();
- nameAndSecurityLayout->setContentsMargins(4,0,0,0);
-
- nameWidget_ = new QtNameWidget(settings, this);
- connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest()));
- nameAndSecurityLayout->addWidget(nameWidget_);
-
- securityInfoButton_ = new QToolButton(this);
- securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}");
- //securityInfoButton_->setAutoRaise(true);
- securityInfoButton_->setIcon(QIcon(":/icons/lock.png"));
- securityInfoButton_->setToolTip(tr("Connection is secured"));
- connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo()));
- nameAndSecurityLayout->addWidget(securityInfoButton_);
-
- rightLayout->addLayout(nameAndSecurityLayout);
-
- statusWidget_ = new QtStatusWidget(statusCache, this);
- connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&)));
- rightLayout->addWidget(statusWidget_);
-
- show();
+ QHBoxLayout* topLayout = new QHBoxLayout();
+ topLayout->setSpacing(3);
+ topLayout->setContentsMargins(4,4,4,4);
+ setLayout(topLayout);
+ setMinimumHeight(50);
+ setMaximumHeight(50);
+
+ avatarLabel_ = new QtClickableLabel(this);
+ avatarLabel_->setMinimumSize(avatarSize_, avatarSize_);
+ avatarLabel_->setMaximumSize(avatarSize_, avatarSize_);
+ avatarLabel_->setAlignment(Qt::AlignCenter);
+ setAvatar(":/icons/avatar.png");
+ avatarLabel_->setScaledContents(false);
+ topLayout->addWidget(avatarLabel_);
+ connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
+
+ QVBoxLayout* rightLayout = new QVBoxLayout();
+ rightLayout->setSpacing(4);
+ rightLayout->setContentsMargins(4,0,0,0);
+ topLayout->addLayout(rightLayout);
+
+ QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout();
+ nameAndSecurityLayout->setContentsMargins(4,0,0,0);
+
+ nameWidget_ = new QtNameWidget(settings, this);
+ connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest()));
+ nameAndSecurityLayout->addWidget(nameWidget_);
+
+ securityInfoButton_ = new QToolButton(this);
+ securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}");
+ //securityInfoButton_->setAutoRaise(true);
+ securityInfoButton_->setIcon(QIcon(":/icons/lock.png"));
+ securityInfoButton_->setToolTip(tr("Connection is secured"));
+ connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo()));
+ nameAndSecurityLayout->addWidget(securityInfoButton_);
+
+ rightLayout->addLayout(nameAndSecurityLayout);
+
+ statusWidget_ = new QtStatusWidget(statusCache, this);
+ connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&)));
+ rightLayout->addWidget(statusWidget_);
+
+ show();
}
void QtRosterHeader::handleChangeStatusRequest(StatusShow::Type type, const QString& text) {
- emit onChangeStatusRequest(type, text);
+ emit onChangeStatusRequest(type, text);
}
void QtRosterHeader::setStatusText(const QString& statusMessage) {
- statusWidget_->setStatusText(statusMessage);
+ statusWidget_->setStatusText(statusMessage);
}
void QtRosterHeader::setStatusType(StatusShow::Type type) {
- statusWidget_->setStatusType(type);
- if (type == StatusShow::None) {
- nameWidget_->setOnline(false);
- disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
- }
- else {
- nameWidget_->setOnline(true);
- connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection);
- }
+ statusWidget_->setStatusType(type);
+ if (type == StatusShow::None) {
+ nameWidget_->setOnline(false);
+ disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()));
+ }
+ else {
+ nameWidget_->setOnline(true);
+ connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection);
+ }
}
void QtRosterHeader::setConnecting() {
- statusWidget_->setConnecting();
+ statusWidget_->setConnecting();
}
void QtRosterHeader::setStreamEncryptionStatus(bool tlsInPlace) {
- securityInfoButton_->setVisible(tlsInPlace);
+ securityInfoButton_->setVisible(tlsInPlace);
}
bool QtRosterHeader::event(QEvent* event) {
- if (event->type() == QEvent::ToolTip) {
- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
- QtScaledAvatarCache scaledAvatarCache(avatarSize_);
- QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache);
- QToolTip::showText(helpEvent->globalPos(), text);
- return true;
- }
- return QWidget::event(event);
+ if (event->type() == QEvent::ToolTip) {
+ QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
+ QtScaledAvatarCache scaledAvatarCache(avatarSize_);
+ QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache);
+ QToolTip::showText(helpEvent->globalPos(), text);
+ return true;
+ }
+ return QWidget::event(event);
}
void QtRosterHeader::setAvatar(const QString& path) {
- QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path);
- QPixmap avatar;
- if (QFileInfo(scaledAvatarPath).exists()) {
- avatar.load(scaledAvatarPath);
- }
- else {
- avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- avatarLabel_->setPixmap(avatar);
+ QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path);
+ QPixmap avatar;
+ if (QFileInfo(scaledAvatarPath).exists()) {
+ avatar.load(scaledAvatarPath);
+ }
+ else {
+ avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ avatarLabel_->setPixmap(avatar);
}
void QtRosterHeader::setNick(const QString& nick) {
- nameWidget_->setNick(nick);
+ nameWidget_->setNick(nick);
}
void QtRosterHeader::setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
- contact_ = contact;
+ contact_ = contact;
}
void QtRosterHeader::setJID(const QString& jid) {
- nameWidget_->setJID(jid);
+ nameWidget_->setJID(jid);
}
diff --git a/Swift/QtUI/QtRosterHeader.h b/Swift/QtUI/QtRosterHeader.h
index 49c3338..b556504 100644
--- a/Swift/QtUI/QtRosterHeader.h
+++ b/Swift/QtUI/QtRosterHeader.h
@@ -24,43 +24,43 @@
class QHBoxLayout;
namespace Swift {
- class QtClickableLabel;
- class QtStatusWidget;
- class QtNameWidget;
- class SettingsProvider;
- class StatusCache;
-
- class QtRosterHeader : public QWidget {
- Q_OBJECT
- public:
- QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL);
- void setAvatar(const QString& path);
+ class QtClickableLabel;
+ class QtStatusWidget;
+ class QtNameWidget;
+ class SettingsProvider;
+ class StatusCache;
- void setJID(const QString& jid);
- void setNick(const QString& nick);
- void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
+ class QtRosterHeader : public QWidget {
+ Q_OBJECT
+ public:
+ QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL);
+ void setAvatar(const QString& path);
- void setStatusText(const QString& statusMessage);
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- void setStreamEncryptionStatus(bool tlsInPlace);
- private:
- bool event(QEvent* event);
- signals:
- void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage);
- void onEditProfileRequest();
- void onShowCertificateInfo();
+ void setJID(const QString& jid);
+ void setNick(const QString& nick);
+ void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
- private slots:
- void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage);
- private:
- QString name_;
- QtClickableLabel* avatarLabel_;
- QtNameWidget* nameWidget_;
- QtTextEdit* statusEdit_;
- QtStatusWidget* statusWidget_;
- QToolButton* securityInfoButton_;
- static const int avatarSize_;
- boost::shared_ptr<ContactRosterItem> contact_;
- };
+ void setStatusText(const QString& statusMessage);
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ void setStreamEncryptionStatus(bool tlsInPlace);
+ private:
+ bool event(QEvent* event);
+ signals:
+ void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage);
+ void onEditProfileRequest();
+ void onShowCertificateInfo();
+
+ private slots:
+ void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage);
+ private:
+ QString name_;
+ QtClickableLabel* avatarLabel_;
+ QtNameWidget* nameWidget_;
+ QtTextEdit* statusEdit_;
+ QtStatusWidget* statusWidget_;
+ QToolButton* securityInfoButton_;
+ static const int avatarSize_;
+ boost::shared_ptr<ContactRosterItem> contact_;
+ };
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.cpp b/Swift/QtUI/QtScaledAvatarCache.cpp
index 9668336..6d683bd 100644
--- a/Swift/QtUI/QtScaledAvatarCache.cpp
+++ b/Swift/QtUI/QtScaledAvatarCache.cpp
@@ -24,39 +24,39 @@ QtScaledAvatarCache::QtScaledAvatarCache(int size) : size(size) {
}
QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) {
- QFileInfo avatarFile(path);
- if (avatarFile.exists()) {
- if (!avatarFile.dir().exists(QString::number(size))) {
- if (!avatarFile.dir().mkdir(QString::number(size))) {
- return path;
- }
- }
- QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size)));
- QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
- if (!QFileInfo(targetFile).exists()) {
- QPixmap avatarPixmap;
- if (avatarPixmap.load(path)) {
- QPixmap maskedAvatar(avatarPixmap.size());
- maskedAvatar.fill(QColor(0, 0, 0, 0));
- QPainter maskPainter(&maskedAvatar);
- maskPainter.setBrush(Qt::black);
- maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize);
- maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
- maskPainter.drawPixmap(0, 0, avatarPixmap);
- maskPainter.end();
-
- if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
- return path;
- }
- } else {
- SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl;
- }
- }
- return targetFile;
- }
- else {
- return path;
- }
+ QFileInfo avatarFile(path);
+ if (avatarFile.exists()) {
+ if (!avatarFile.dir().exists(QString::number(size))) {
+ if (!avatarFile.dir().mkdir(QString::number(size))) {
+ return path;
+ }
+ }
+ QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size)));
+ QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
+ if (!QFileInfo(targetFile).exists()) {
+ QPixmap avatarPixmap;
+ if (avatarPixmap.load(path)) {
+ QPixmap maskedAvatar(avatarPixmap.size());
+ maskedAvatar.fill(QColor(0, 0, 0, 0));
+ QPainter maskPainter(&maskedAvatar);
+ maskPainter.setBrush(Qt::black);
+ maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize);
+ maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
+ maskPainter.drawPixmap(0, 0, avatarPixmap);
+ maskPainter.end();
+
+ if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
+ return path;
+ }
+ } else {
+ SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl;
+ }
+ }
+ return targetFile;
+ }
+ else {
+ return path;
+ }
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.h b/Swift/QtUI/QtScaledAvatarCache.h
index 4ee583d..748fb40 100644
--- a/Swift/QtUI/QtScaledAvatarCache.h
+++ b/Swift/QtUI/QtScaledAvatarCache.h
@@ -11,13 +11,13 @@
#include <QString>
namespace Swift {
- class QtScaledAvatarCache {
- public:
- QtScaledAvatarCache(int size);
+ class QtScaledAvatarCache {
+ public:
+ QtScaledAvatarCache(int size);
- QString getScaledAvatarPath(const QString& path);
+ QString getScaledAvatarPath(const QString& path);
- private:
- int size;
- };
+ private:
+ int size;
+ };
}
diff --git a/Swift/QtUI/QtSettingsProvider.cpp b/Swift/QtUI/QtSettingsProvider.cpp
index d60fa2b..3c32dc8 100644
--- a/Swift/QtUI/QtSettingsProvider.cpp
+++ b/Swift/QtUI/QtSettingsProvider.cpp
@@ -19,105 +19,105 @@ QtSettingsProvider::~QtSettingsProvider() {
}
bool QtSettingsProvider::hasSetting(const std::string& key) {
- return !settings_.value(key.c_str()).isNull();
+ return !settings_.value(key.c_str()).isNull();
}
std::string QtSettingsProvider::getSetting(const Setting<std::string>& setting) {
- QVariant variant = settings_.value(setting.getKey().c_str());
- return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8());
+ QVariant variant = settings_.value(setting.getKey().c_str());
+ return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8());
}
void QtSettingsProvider::storeSetting(const Setting<std::string>& setting, const std::string& settingValue) {
- bool changed = false;
- if (getSetting(setting) != settingValue) {
- changed = true;
- }
- settings_.setValue(setting.getKey().c_str(), settingValue.c_str());
- if (changed) {
- onSettingChanged(setting.getKey());
- }
- updatePermissions();
+ bool changed = false;
+ if (getSetting(setting) != settingValue) {
+ changed = true;
+ }
+ settings_.setValue(setting.getKey().c_str(), settingValue.c_str());
+ if (changed) {
+ onSettingChanged(setting.getKey());
+ }
+ updatePermissions();
}
bool QtSettingsProvider::getSetting(const Setting<bool>& setting) {
- QVariant variant = settings_.value(setting.getKey().c_str());
- return variant.isNull() ? setting.getDefaultValue() : variant.toBool();
+ QVariant variant = settings_.value(setting.getKey().c_str());
+ return variant.isNull() ? setting.getDefaultValue() : variant.toBool();
}
void QtSettingsProvider::storeSetting(const Setting<bool>& setting, const bool& settingValue) {
- bool changed = false;
- if (getSetting(setting) != settingValue) {
- changed = true;
- }
- settings_.setValue(setting.getKey().c_str(), settingValue);
- if (changed) {
- onSettingChanged(setting.getKey());
- }
- updatePermissions();
+ bool changed = false;
+ 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();
+ 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();
+ 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()) {
- profiles.push_back(std::string(profileQString.toUtf8()));
- }
- return profiles;
+ std::vector<std::string> profiles;
+ QVariant profilesVariant = settings_.value("profileList");
+ foreach(QString 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();
+ 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()) {
- if (key.startsWith(profileStart)) {
- settings_.remove(key);
- }
- }
- QStringList stringList = settings_.value("profileList").toStringList();
- stringList.removeAll(profile.c_str());
- settings_.setValue("profileList", stringList);
- updatePermissions();
+ QString profileStart(QString(profile.c_str()) + ":");
+ foreach (QString 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_;
+ 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);
- }
+ QFile file(settings_.fileName());
+ if (file.exists()) {
+ file.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
+ }
#endif
}
bool QtSettingsProvider::getIsSettingFinal(const std::string& /*settingPath*/) {
- return false;
+ return false;
}
}
diff --git a/Swift/QtUI/QtSettingsProvider.h b/Swift/QtUI/QtSettingsProvider.h
index 06984f5..21e9211 100644
--- a/Swift/QtUI/QtSettingsProvider.h
+++ b/Swift/QtUI/QtSettingsProvider.h
@@ -13,28 +13,28 @@
namespace Swift {
class QtSettingsProvider : public SettingsProvider {
- public:
- QtSettingsProvider();
- virtual ~QtSettingsProvider();
- virtual std::string getSetting(const Setting<std::string>& setting);
- virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
- virtual bool getSetting(const Setting<bool>& setting);
- virtual void storeSetting(const Setting<bool>& setting, const bool& value);
- virtual int getSetting(const Setting<int>& setting);
- virtual void storeSetting(const Setting<int>& setting, const int& value);
- virtual std::vector<std::string> getAvailableProfiles();
- virtual void createProfile(const std::string& profile);
- virtual void removeProfile(const std::string& profile);
- virtual bool hasSetting(const std::string& key);
- QSettings* getQSettings();
- protected:
- virtual bool getIsSettingFinal(const std::string& settingPath);
-
- private:
- void updatePermissions();
-
- private:
- QSettings settings_;
+ public:
+ QtSettingsProvider();
+ virtual ~QtSettingsProvider();
+ virtual std::string getSetting(const Setting<std::string>& setting);
+ virtual void storeSetting(const Setting<std::string>& setting, const std::string& value);
+ virtual bool getSetting(const Setting<bool>& setting);
+ virtual void storeSetting(const Setting<bool>& setting, const bool& value);
+ virtual int getSetting(const Setting<int>& setting);
+ virtual void storeSetting(const Setting<int>& setting, const int& value);
+ virtual std::vector<std::string> getAvailableProfiles();
+ virtual void createProfile(const std::string& profile);
+ virtual void removeProfile(const std::string& profile);
+ virtual bool hasSetting(const std::string& key);
+ QSettings* getQSettings();
+ protected:
+ virtual bool getIsSettingFinal(const std::string& settingPath);
+
+ private:
+ void updatePermissions();
+
+ private:
+ QSettings settings_;
};
}
diff --git a/Swift/QtUI/QtSingleWindow.cpp b/Swift/QtUI/QtSingleWindow.cpp
index 8613d62..db7f7dc 100644
--- a/Swift/QtUI/QtSingleWindow.cpp
+++ b/Swift/QtUI/QtSingleWindow.cpp
@@ -17,13 +17,13 @@ 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();
+ 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() {
@@ -31,51 +31,51 @@ 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);
+ 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);
+ setWindowTitle(title);
}
void QtSingleWindow::handleSplitterMoved(int, int) {
- QList<QVariant> variantValues;
- QList<int> intValues = sizes();
- foreach (int value, intValues) {
- variantValues.append(QVariant(value));
- }
- settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues));
+ QList<QVariant> variantValues;
+ QList<int> intValues = sizes();
+ foreach (int 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) {
- intValues.append(value.toInt());
- }
- setSizes(intValues);
+ QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
+ QList<int> intValues;
+ foreach (QVariant value, variantValues) {
+ intValues.append(value.toInt());
+ }
+ setSizes(intValues);
}
void QtSingleWindow::insertAtFront(QWidget* widget) {
- insertWidget(0, widget);
- restoreSplitters();
+ insertWidget(0, widget);
+ restoreSplitters();
}
void QtSingleWindow::handleGeometryChanged() {
- settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry());
+ settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry());
}
void QtSingleWindow::resizeEvent(QResizeEvent*) {
- handleGeometryChanged();
+ handleGeometryChanged();
}
void QtSingleWindow::moveEvent(QMoveEvent*) {
- handleGeometryChanged();
+ handleGeometryChanged();
}
}
diff --git a/Swift/QtUI/QtSingleWindow.h b/Swift/QtUI/QtSingleWindow.h
index e430c56..804be65 100644
--- a/Swift/QtUI/QtSingleWindow.h
+++ b/Swift/QtUI/QtSingleWindow.h
@@ -9,29 +9,29 @@
#include <QSplitter>
namespace Swift {
- class QtSettingsProvider;
-
- class QtSingleWindow : public QSplitter {
- Q_OBJECT
- public:
- QtSingleWindow(QtSettingsProvider* settings);
- virtual ~QtSingleWindow();
- void insertAtFront(QWidget* widget);
- void addWidget(QWidget* widget);
- protected:
- void resizeEvent(QResizeEvent*);
- void moveEvent(QMoveEvent*);
- private slots:
- void handleSplitterMoved(int, int);
- void handleTabsTitleChanged(const QString& title);
- private:
- void handleGeometryChanged();
- void restoreSplitters();
-
- private:
-
- QtSettingsProvider* settings_;
- };
+ class QtSettingsProvider;
+
+ class QtSingleWindow : public QSplitter {
+ Q_OBJECT
+ public:
+ QtSingleWindow(QtSettingsProvider* settings);
+ virtual ~QtSingleWindow();
+ void insertAtFront(QWidget* widget);
+ void addWidget(QWidget* widget);
+ protected:
+ void resizeEvent(QResizeEvent*);
+ void moveEvent(QMoveEvent*);
+ private slots:
+ void handleSplitterMoved(int, int);
+ void handleTabsTitleChanged(const QString& title);
+ private:
+ void handleGeometryChanged();
+ void restoreSplitters();
+
+ private:
+
+ QtSettingsProvider* settings_;
+ };
}
diff --git a/Swift/QtUI/QtSoundPlayer.cpp b/Swift/QtUI/QtSoundPlayer.cpp
index f047427..22f544d 100644
--- a/Swift/QtUI/QtSoundPlayer.cpp
+++ b/Swift/QtUI/QtSoundPlayer.cpp
@@ -17,30 +17,30 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
-
+
QtSoundPlayer::QtSoundPlayer(ApplicationPathProvider* applicationPathProvider) : applicationPathProvider(applicationPathProvider) {
}
void QtSoundPlayer::playSound(SoundEffect sound, const std::string& soundResource) {
- switch (sound) {
- case MessageReceived:
- playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource);
- break;
- }
+ switch (sound) {
+ case MessageReceived:
+ playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource);
+ break;
+ }
}
void QtSoundPlayer::playSound(const std::string& soundResource) {
- boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource);
- if (boost::filesystem::exists(resourcePath)) {
- QSound::play(P2QSTRING(pathToString(resourcePath)));
- }
- else if (boost::filesystem::exists(soundResource)) {
- QSound::play(P2QSTRING(soundResource));
- }
- else {
- std::cerr << "Unable to find sound: " << soundResource << std::endl;
- }
+ boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource);
+ if (boost::filesystem::exists(resourcePath)) {
+ QSound::play(P2QSTRING(pathToString(resourcePath)));
+ }
+ else if (boost::filesystem::exists(soundResource)) {
+ QSound::play(P2QSTRING(soundResource));
+ }
+ else {
+ std::cerr << "Unable to find sound: " << soundResource << std::endl;
+ }
}
}
diff --git a/Swift/QtUI/QtSoundPlayer.h b/Swift/QtUI/QtSoundPlayer.h
index e34529e..8a0b8fe 100644
--- a/Swift/QtUI/QtSoundPlayer.h
+++ b/Swift/QtUI/QtSoundPlayer.h
@@ -11,20 +11,20 @@
#include <Swift/Controllers/SoundPlayer.h>
namespace Swift {
- class ApplicationPathProvider;
-
+ class ApplicationPathProvider;
- class QtSoundPlayer : public QObject, public SoundPlayer {
- Q_OBJECT
- public:
- QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
- void playSound(SoundEffect sound, const std::string& soundResource);
+ class QtSoundPlayer : public QObject, public SoundPlayer {
+ Q_OBJECT
+ public:
+ QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
- private:
- void playSound(const std::string& soundResource);
+ void playSound(SoundEffect sound, const std::string& soundResource);
- private:
- ApplicationPathProvider* applicationPathProvider;
- };
+ private:
+ void playSound(const std::string& soundResource);
+
+ private:
+ ApplicationPathProvider* applicationPathProvider;
+ };
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.cpp b/Swift/QtUI/QtSpellCheckHighlighter.cpp
index 0112d7a..6565b06 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.cpp
+++ b/Swift/QtUI/QtSpellCheckHighlighter.cpp
@@ -21,21 +21,21 @@ QtSpellCheckHighlighter::~QtSpellCheckHighlighter() {
}
void QtSpellCheckHighlighter::highlightBlock(const QString& text) {
- misspelledPositions_.clear();
- std::string fragment = Q2PSTRING(text);
- checker_->checkFragment(fragment, misspelledPositions_);
+ misspelledPositions_.clear();
+ std::string fragment = Q2PSTRING(text);
+ checker_->checkFragment(fragment, misspelledPositions_);
- QTextCharFormat spellingErrorFormat;
- spellingErrorFormat.setUnderlineColor(QColor(Qt::red));
- spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
+ QTextCharFormat spellingErrorFormat;
+ spellingErrorFormat.setUnderlineColor(QColor(Qt::red));
+ spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline);
- foreach (PositionPair position, misspelledPositions_) {
- setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat);
- };
+ foreach (PositionPair position, misspelledPositions_) {
+ setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat);
+ };
}
PositionPairList QtSpellCheckHighlighter::getMisspelledPositions() const {
- return misspelledPositions_;
+ return misspelledPositions_;
}
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.h b/Swift/QtUI/QtSpellCheckHighlighter.h
index 7fa48de..5519a1d 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.h
+++ b/Swift/QtUI/QtSpellCheckHighlighter.h
@@ -18,20 +18,20 @@ namespace Swift {
class SpellChecker;
class QtSpellCheckHighlighter : public QSyntaxHighlighter {
- Q_OBJECT
+ Q_OBJECT
public:
- QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker);
- virtual ~QtSpellCheckHighlighter();
+ QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker);
+ virtual ~QtSpellCheckHighlighter();
- PositionPairList getMisspelledPositions() const;
+ PositionPairList getMisspelledPositions() const;
protected:
- virtual void highlightBlock(const QString& text);
+ virtual void highlightBlock(const QString& text);
private:
- SpellChecker* checker_;
- PositionPairList misspelledPositions_;
+ SpellChecker* checker_;
+ PositionPairList misspelledPositions_;
};
diff --git a/Swift/QtUI/QtSpellCheckerWindow.cpp b/Swift/QtUI/QtSpellCheckerWindow.cpp
index ba4dbd3..9232b19 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.cpp
+++ b/Swift/QtUI/QtSpellCheckerWindow.cpp
@@ -27,96 +27,96 @@
namespace Swift {
QtSpellCheckerWindow::QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent) : QDialog(parent) {
- settings_ = settings;
- ui_.setupUi(this);
+ settings_ = settings;
+ ui_.setupUi(this);
#ifdef HAVE_HUNSPELL
- ui_.hunspellOptions->show();
+ ui_.hunspellOptions->show();
#else
- ui_.hunspellOptions->hide();
- QTimer::singleShot(0, this, SLOT(shrinkWindow()));
+ ui_.hunspellOptions->hide();
+ QTimer::singleShot(0, this, SLOT(shrinkWindow()));
#endif
- connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool)));
- connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel()));
- connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply()));
- connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton()));
- setFromSettings();
+ connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool)));
+ connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel()));
+ connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply()));
+ connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton()));
+ setFromSettings();
}
void QtSpellCheckerWindow::shrinkWindow() {
- resize(0,0);
+ resize(0,0);
}
void QtSpellCheckerWindow::setFromSettings() {
- ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER));
- ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH)));
- ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE)));
- std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
- QString filename = "*.dic";
- QDir dictDirectory = QDir(P2QSTRING(currentPath));
- QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
- showFiles(files);
- setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER));
+ ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER));
+ ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH)));
+ ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE)));
+ std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ QString filename = "*.dic";
+ QDir dictDirectory = QDir(P2QSTRING(currentPath));
+ QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
+ showFiles(files);
+ setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER));
}
void QtSpellCheckerWindow::handleChecker(bool state) {
- setEnabled(state);
+ setEnabled(state);
}
void QtSpellCheckerWindow::setEnabled(bool state) {
- ui_.pathContent->setEnabled(state);
- ui_.languageView->setEnabled(state);
- ui_.pathButton->setEnabled(state);
- ui_.pathLabel->setEnabled(state);
- ui_.currentLanguage->setEnabled(state);
- ui_.currentLanguageValue->setEnabled(state);
- ui_.language->setEnabled(state);
+ ui_.pathContent->setEnabled(state);
+ ui_.languageView->setEnabled(state);
+ ui_.pathButton->setEnabled(state);
+ ui_.pathLabel->setEnabled(state);
+ ui_.currentLanguage->setEnabled(state);
+ ui_.currentLanguageValue->setEnabled(state);
+ ui_.language->setEnabled(state);
}
void QtSpellCheckerWindow::handleApply() {
- settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked());
- QList<QListWidgetItem* > selectedLanguage = ui_.languageView->selectedItems();
- if (!selectedLanguage.empty()) {
- settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text()));
- }
- this->done(0);
+ settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked());
+ QList<QListWidgetItem* > selectedLanguage = ui_.languageView->selectedItems();
+ if (!selectedLanguage.empty()) {
+ settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text()));
+ }
+ this->done(0);
}
void QtSpellCheckerWindow::handleCancel() {
- this->done(0);
+ this->done(0);
}
void QtSpellCheckerWindow::handlePathButton() {
- std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
- QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath));
- if (dirpath != P2QSTRING(currentPath)) {
- ui_.languageView->clear();
- settings_->storeSetting(SettingConstants::DICT_FILE, "");
- ui_.currentLanguageValue->setText(" ");
- }
- if (!dirpath.isEmpty()) {
- if (!dirpath.endsWith("/")) {
- dirpath.append("/");
- }
- settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath));
- QDir dictDirectory = QDir(dirpath);
- ui_.pathContent->setText(dirpath);
- QString filename = "*.dic";
- QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
- showFiles(files);
- }
+ std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath));
+ if (dirpath != P2QSTRING(currentPath)) {
+ ui_.languageView->clear();
+ settings_->storeSetting(SettingConstants::DICT_FILE, "");
+ ui_.currentLanguageValue->setText(" ");
+ }
+ if (!dirpath.isEmpty()) {
+ if (!dirpath.endsWith("/")) {
+ dirpath.append("/");
+ }
+ settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath));
+ QDir dictDirectory = QDir(dirpath);
+ ui_.pathContent->setText(dirpath);
+ QString filename = "*.dic";
+ QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files);
+ showFiles(files);
+ }
}
void QtSpellCheckerWindow::handlePersonalPathButton() {
- std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH);
- QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic"));
- settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename));
+ std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH);
+ QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic"));
+ settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename));
}
void QtSpellCheckerWindow::showFiles(const QStringList& files) {
- ui_.languageView->clear();
- for (int i = 0; i < files.size(); ++i) {
- ui_.languageView->insertItem(i, files[i]);
- }
+ ui_.languageView->clear();
+ for (int i = 0; i < files.size(); ++i) {
+ ui_.languageView->insertItem(i, files[i]);
+ }
}
}
diff --git a/Swift/QtUI/QtSpellCheckerWindow.h b/Swift/QtUI/QtSpellCheckerWindow.h
index 0e43ddd..95e0725 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.h
+++ b/Swift/QtUI/QtSpellCheckerWindow.h
@@ -17,24 +17,24 @@
#include <Swift/QtUI/ui_QtSpellCheckerWindow.h>
namespace Swift {
- class SettingsProvider;
- class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow {
- Q_OBJECT
- public:
- QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL);
- public slots:
- void handleChecker(bool state);
- void handleCancel();
- void handlePathButton();
- void handlePersonalPathButton();
- void handleApply();
- private slots:
- void shrinkWindow();
- private:
- void setEnabled(bool state);
- void setFromSettings();
- void showFiles(const QStringList& files);
- SettingsProvider* settings_;
- Ui::QtSpellCheckerWindow ui_;
- };
+ class SettingsProvider;
+ class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow {
+ Q_OBJECT
+ public:
+ QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL);
+ public slots:
+ void handleChecker(bool state);
+ void handleCancel();
+ void handlePathButton();
+ void handlePersonalPathButton();
+ void handleApply();
+ private slots:
+ void shrinkWindow();
+ private:
+ void setEnabled(bool state);
+ void setFromSettings();
+ void showFiles(const QStringList& files);
+ SettingsProvider* settings_;
+ Ui::QtSpellCheckerWindow ui_;
+ };
}
diff --git a/Swift/QtUI/QtStatusWidget.cpp b/Swift/QtUI/QtStatusWidget.cpp
index 78b2c5a..2e9e4cc 100644
--- a/Swift/QtUI/QtStatusWidget.cpp
+++ b/Swift/QtUI/QtStatusWidget.cpp
@@ -37,266 +37,266 @@ namespace lambda = boost::lambda;
namespace Swift {
QtStatusWidget::QtStatusWidget(StatusCache* statusCache, QWidget *parent) : QWidget(parent), statusCache_(statusCache), editCursor_(Qt::IBeamCursor), viewCursor_(Qt::PointingHandCursor) {
- allTypes_.push_back(StatusShow::Online);
- allTypes_.push_back(StatusShow::FFC);
- allTypes_.push_back(StatusShow::Away);
- allTypes_.push_back(StatusShow::XA);
- allTypes_.push_back(StatusShow::DND);
- allTypes_.push_back(StatusShow::None);
-
- isClicking_ = false;
- connecting_ = false;
- setMaximumHeight(24);
-
- connectingMovie_ = new QMovie(":/icons/connecting.mng");
-
- QHBoxLayout* mainLayout = new QHBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
-
- stack_ = new QStackedWidget(this);
- stack_->setLineWidth(2);
- stack_->setFrameShape(QFrame::StyledPanel);
- mainLayout->addWidget(stack_);
-
- QWidget* page1 = new QWidget(this);
- stack_->addWidget(page1);
- QHBoxLayout* page1Layout = new QHBoxLayout(page1);
- page1Layout->setSpacing(0);
- page1Layout->setContentsMargins(0,0,0,0);
- page1->setCursor(viewCursor_);
-
- statusIcon_ = new QLabel(this);
- statusIcon_->setMinimumSize(16, 16);
- statusIcon_->setMaximumSize(16, 16);
- page1Layout->addWidget(statusIcon_);
-
- statusTextLabel_ = new QtElidingLabel(this);
- QFont font = statusTextLabel_->font();
- font.setItalic(true);
- statusTextLabel_->setFont(font);
- page1Layout->addWidget(statusTextLabel_);
-
- icons_[StatusShow::Online] = QIcon(":/icons/online.png");
- icons_[StatusShow::Away] = QIcon(":/icons/away.png");
- icons_[StatusShow::DND] = QIcon(":/icons/dnd.png");
- icons_[StatusShow::None] = QIcon(":/icons/offline.png");
-
- setStatusType(StatusShow::None);
-
- QWidget* page2 = new QWidget(this);
- QHBoxLayout* page2Layout = new QHBoxLayout(page2);
- page2Layout->setSpacing(0);
- page2Layout->setContentsMargins(0,0,0,0);
- stack_->addWidget(page2);
-
- statusEdit_ = new QtLineEdit(this);
- page2Layout->addWidget(statusEdit_);
- connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete()));
- connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled()));
- connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList()));
-
- setStatusText("");
-
-
- menu_ = new QListWidget();
- menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint );
- menu_->setAlternatingRowColors(true);
- menu_->setFocusProxy(statusEdit_);
- menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- QSizePolicy policy(menu_->sizePolicy());
- policy.setVerticalPolicy(QSizePolicy::Expanding);
- menu_->setSizePolicy(policy);
-
-
- connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*)));
-
- viewMode();
+ allTypes_.push_back(StatusShow::Online);
+ allTypes_.push_back(StatusShow::FFC);
+ allTypes_.push_back(StatusShow::Away);
+ allTypes_.push_back(StatusShow::XA);
+ allTypes_.push_back(StatusShow::DND);
+ allTypes_.push_back(StatusShow::None);
+
+ isClicking_ = false;
+ connecting_ = false;
+ setMaximumHeight(24);
+
+ connectingMovie_ = new QMovie(":/icons/connecting.mng");
+
+ QHBoxLayout* mainLayout = new QHBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+
+ stack_ = new QStackedWidget(this);
+ stack_->setLineWidth(2);
+ stack_->setFrameShape(QFrame::StyledPanel);
+ mainLayout->addWidget(stack_);
+
+ QWidget* page1 = new QWidget(this);
+ stack_->addWidget(page1);
+ QHBoxLayout* page1Layout = new QHBoxLayout(page1);
+ page1Layout->setSpacing(0);
+ page1Layout->setContentsMargins(0,0,0,0);
+ page1->setCursor(viewCursor_);
+
+ statusIcon_ = new QLabel(this);
+ statusIcon_->setMinimumSize(16, 16);
+ statusIcon_->setMaximumSize(16, 16);
+ page1Layout->addWidget(statusIcon_);
+
+ statusTextLabel_ = new QtElidingLabel(this);
+ QFont font = statusTextLabel_->font();
+ font.setItalic(true);
+ statusTextLabel_->setFont(font);
+ page1Layout->addWidget(statusTextLabel_);
+
+ icons_[StatusShow::Online] = QIcon(":/icons/online.png");
+ icons_[StatusShow::Away] = QIcon(":/icons/away.png");
+ icons_[StatusShow::DND] = QIcon(":/icons/dnd.png");
+ icons_[StatusShow::None] = QIcon(":/icons/offline.png");
+
+ setStatusType(StatusShow::None);
+
+ QWidget* page2 = new QWidget(this);
+ QHBoxLayout* page2Layout = new QHBoxLayout(page2);
+ page2Layout->setSpacing(0);
+ page2Layout->setContentsMargins(0,0,0,0);
+ stack_->addWidget(page2);
+
+ statusEdit_ = new QtLineEdit(this);
+ page2Layout->addWidget(statusEdit_);
+ connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete()));
+ connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled()));
+ connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList()));
+
+ setStatusText("");
+
+
+ menu_ = new QListWidget();
+ menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint );
+ menu_->setAlternatingRowColors(true);
+ menu_->setFocusProxy(statusEdit_);
+ menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ QSizePolicy policy(menu_->sizePolicy());
+ policy.setVerticalPolicy(QSizePolicy::Expanding);
+ menu_->setSizePolicy(policy);
+
+
+ connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*)));
+
+ viewMode();
}
QtStatusWidget::~QtStatusWidget() {
- delete menu_;
- delete connectingMovie_;
+ 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();
- }
-
+ 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();
- }
+ 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()) {
- 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) {
- 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()) {
- 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();
+ if (!editing_) {
+ return;
+ }
+ QString text = statusEdit_->text();
+ newStatusText_ = text;
+ menu_->clear();
+ foreach (StatusShow::Type 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) {
+ 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()) {
+ 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);
+ 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_) {
- // 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);
+ 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_) {
+ // 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();
- stack_->setCurrentIndex(0);
+ disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
+ editing_ = false;
+ menu_->hide();
+ stack_->setCurrentIndex(0);
}
void QtStatusWidget::handleEditComplete() {
- editing_ = false;
- statusText_ = newStatusText_;
- viewMode();
- emit onChangeStatusRequest(selectedStatusType_, statusText_);
- statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_);
+ editing_ = false;
+ statusText_ = newStatusText_;
+ viewMode();
+ emit onChangeStatusRequest(selectedStatusType_, statusText_);
+ statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_);
}
void QtStatusWidget::handleEditCancelled() {
- editing_ = false;
- setStatusText(statusText_);
- viewMode();
+ editing_ = false;
+ setStatusText(statusText_);
+ viewMode();
}
StatusShow::Type QtStatusWidget::getSelectedStatusShow() {
- return selectedStatusType_;
+ return selectedStatusType_;
}
void QtStatusWidget::handleItemClicked(QListWidgetItem* item) {
- editing_ = false;
- selectedStatusType_ = static_cast<StatusShow::Type>(item->data(Qt::UserRole).toInt());
- QString message = item->data(Qt::DisplayRole).toString();
- newStatusText_ = message == getNoMessage() ? "" : message;
- statusEdit_->setText(newStatusText_);
- handleEditComplete();
+ editing_ = false;
+ selectedStatusType_ = static_cast<StatusShow::Type>(item->data(Qt::UserRole).toInt());
+ QString message = item->data(Qt::DisplayRole).toString();
+ newStatusText_ = message == getNoMessage() ? "" : message;
+ statusEdit_->setText(newStatusText_);
+ handleEditComplete();
}
void QtStatusWidget::setNewToolTip() {
- if (connecting_) {
- statusTextLabel_->setToolTip(tr("Connecting"));
- } else {
- statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text());
- }
+ if (connecting_) {
+ statusTextLabel_->setToolTip(tr("Connecting"));
+ } else {
+ statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text());
+ }
}
void QtStatusWidget::setStatusText(const QString& text) {
- connectingMovie_->stop();
- statusText_ = text;
- statusEdit_->setText(text);
- QString escapedText(text.isEmpty() ? getNoMessage() : text);
- statusTextLabel_->setText(escapedText);
- setNewToolTip();
+ connectingMovie_->stop();
+ statusText_ = text;
+ statusEdit_->setText(text);
+ QString escapedText(text.isEmpty() ? getNoMessage() : text);
+ statusTextLabel_->setText(escapedText);
+ setNewToolTip();
}
void QtStatusWidget::setConnecting() {
- connecting_ = true;
- statusIcon_->setMovie(connectingMovie_);
- connectingMovie_->start();
- setNewToolTip();
+ connecting_ = true;
+ statusIcon_->setMovie(connectingMovie_);
+ connectingMovie_->start();
+ setNewToolTip();
}
void QtStatusWidget::setStatusType(StatusShow::Type type) {
- connecting_ = false;
- selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online;
- statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16));
- setNewToolTip();
+ connecting_ = false;
+ selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online;
+ statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16));
+ setNewToolTip();
}
QString QtStatusWidget::getNoMessage() {
- return QString(tr("(No message)"));
+ return QString(tr("(No message)"));
}
}
diff --git a/Swift/QtUI/QtStatusWidget.h b/Swift/QtUI/QtStatusWidget.h
index b835490..f346868 100644
--- a/Swift/QtUI/QtStatusWidget.h
+++ b/Swift/QtUI/QtStatusWidget.h
@@ -20,55 +20,55 @@ class QListWidgetItem;
class QMovie;
namespace Swift {
- class QtLineEdit;
- class QtElidingLabel;
- class StatusCache;
+ class QtLineEdit;
+ class QtElidingLabel;
+ class StatusCache;
- class QtStatusWidget : public QWidget {
- Q_OBJECT
- public:
- QtStatusWidget(StatusCache* statusCache, QWidget *parent);
- ~QtStatusWidget();
- StatusShow::Type getSelectedStatusShow();
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- signals:
- void onChangeStatusRequest(StatusShow::Type showType, const QString& text);
- public slots:
- void setStatusText(const QString& text);
- private slots:
- void generateList();
- void handleClicked();
- void handleEditComplete();
- void handleEditCancelled();
- void handleApplicationFocusChanged(QWidget* old, QWidget* now);
- protected slots:
- virtual void mousePressEvent(QMouseEvent* event);
- void handleItemClicked(QListWidgetItem* item);
- static QString getNoMessage();
- private:
- void resizeMenu();
- void viewMode();
- void setNewToolTip();
- //QComboBox *types_;
- StatusCache* statusCache_;
- QStackedWidget* stack_;
- QLabel* statusIcon_;
- QtElidingLabel* statusTextLabel_;
- QtLineEdit* statusEdit_;
- QString statusText_;
- QString newStatusText_;
- QMap<StatusShow::Type, QIcon> icons_;
- StatusShow::Type selectedStatusType_;
- bool isClicking_;
- QListWidget* menu_;
- QCursor editCursor_;
- QCursor viewCursor_;
- bool editing_;
- QMovie* connectingMovie_;
- bool connecting_;
- static const QString NO_MESSAGE;
- std::vector<StatusShow::Type> allTypes_;
- };
+ class QtStatusWidget : public QWidget {
+ Q_OBJECT
+ public:
+ QtStatusWidget(StatusCache* statusCache, QWidget *parent);
+ ~QtStatusWidget();
+ StatusShow::Type getSelectedStatusShow();
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ signals:
+ void onChangeStatusRequest(StatusShow::Type showType, const QString& text);
+ public slots:
+ void setStatusText(const QString& text);
+ private slots:
+ void generateList();
+ void handleClicked();
+ void handleEditComplete();
+ void handleEditCancelled();
+ void handleApplicationFocusChanged(QWidget* old, QWidget* now);
+ protected slots:
+ virtual void mousePressEvent(QMouseEvent* event);
+ void handleItemClicked(QListWidgetItem* item);
+ static QString getNoMessage();
+ private:
+ void resizeMenu();
+ void viewMode();
+ void setNewToolTip();
+ //QComboBox *types_;
+ StatusCache* statusCache_;
+ QStackedWidget* stack_;
+ QLabel* statusIcon_;
+ QtElidingLabel* statusTextLabel_;
+ QtLineEdit* statusEdit_;
+ QString statusText_;
+ QString newStatusText_;
+ QMap<StatusShow::Type, QIcon> icons_;
+ StatusShow::Type selectedStatusType_;
+ bool isClicking_;
+ QListWidget* menu_;
+ QCursor editCursor_;
+ QCursor viewCursor_;
+ bool editing_;
+ QMovie* connectingMovie_;
+ bool connecting_;
+ static const QString NO_MESSAGE;
+ std::vector<StatusShow::Type> allTypes_;
+ };
}
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.cpp b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
index 43cdb50..9e1fc37 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.cpp
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
@@ -15,76 +15,76 @@
namespace Swift {
QtSubscriptionRequestWindow::QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) : QDialog(parent), event_(event) {
- QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString()));
- QVBoxLayout* layout = new QVBoxLayout();
- QLabel* label = new QLabel(text, this);
- layout->addWidget(label);
- label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?"));
- //layout->addWidget(new QLabel);
- layout->addWidget(label);
+ QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString()));
+ QVBoxLayout* layout = new QVBoxLayout();
+ QLabel* label = new QLabel(text, this);
+ layout->addWidget(label);
+ label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?"));
+ //layout->addWidget(new QLabel);
+ layout->addWidget(label);
- if (event_->getConcluded()) {
- QLabel* doneLabel = new QLabel(tr("You have already replied to this request"));
- QPushButton* okButton = new QPushButton(tr("OK"), this);
- connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
- layout->addWidget(doneLabel);
- layout->addWidget(okButton);
- } else {
- QPushButton* yesButton = new QPushButton(tr("Accept"), this);
- yesButton->setDefault(true);
- connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes()));
- QPushButton* noButton = new QPushButton(tr("Reject"), this);
- connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo()));
- QPushButton* deferButton = new QPushButton(tr("Defer"), this);
- deferButton->setShortcut(QKeySequence(Qt::Key_Escape));
- connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
+ if (event_->getConcluded()) {
+ QLabel* doneLabel = new QLabel(tr("You have already replied to this request"));
+ QPushButton* okButton = new QPushButton(tr("OK"), this);
+ connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
+ layout->addWidget(doneLabel);
+ layout->addWidget(okButton);
+ } else {
+ QPushButton* yesButton = new QPushButton(tr("Accept"), this);
+ yesButton->setDefault(true);
+ connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes()));
+ QPushButton* noButton = new QPushButton(tr("Reject"), this);
+ connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo()));
+ QPushButton* deferButton = new QPushButton(tr("Defer"), this);
+ deferButton->setShortcut(QKeySequence(Qt::Key_Escape));
+ connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer()));
- QHBoxLayout* buttonLayout = new QHBoxLayout();
- buttonLayout->addWidget(yesButton);
- buttonLayout->addWidget(noButton);
- buttonLayout->addWidget(deferButton);
- 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);
- }
+ QHBoxLayout* buttonLayout = new QHBoxLayout();
+ buttonLayout->addWidget(yesButton);
+ buttonLayout->addWidget(noButton);
+ buttonLayout->addWidget(deferButton);
+ 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);
+ setLayout(layout);
}
void QtSubscriptionRequestWindow::handleYes() {
- event_->accept();
- delete this;
+ event_->accept();
+ delete this;
}
void QtSubscriptionRequestWindow::handleNo() {
- event_->decline();
- delete this;
+ event_->decline();
+ delete this;
}
void QtSubscriptionRequestWindow::handleDefer() {
- event_->defer();
- delete this;
+ event_->defer();
+ delete this;
}
QtSubscriptionRequestWindow::~QtSubscriptionRequestWindow() {
- windows_.removeOne(this);
+ windows_.removeOne(this);
}
QtSubscriptionRequestWindow* QtSubscriptionRequestWindow::getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) {
- foreach (QtSubscriptionRequestWindow* window, windows_) {
- if (window->getEvent() == event) {
- return window;
- }
- }
- QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent);
- windows_.append(window);
- return window;
+ foreach (QtSubscriptionRequestWindow* window, windows_) {
+ if (window->getEvent() == event) {
+ return window;
+ }
+ }
+ QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent);
+ windows_.append(window);
+ return window;
}
boost::shared_ptr<SubscriptionRequestEvent> QtSubscriptionRequestWindow::getEvent() {
- return event_;
+ return event_;
}
QList<QtSubscriptionRequestWindow*> QtSubscriptionRequestWindow::windows_;
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.h b/Swift/QtUI/QtSubscriptionRequestWindow.h
index 02932af..1a36e19 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.h
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.h
@@ -13,22 +13,22 @@
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
namespace Swift {
- class QtSubscriptionRequestWindow : public QDialog {
- Q_OBJECT
- public:
- static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
- ~QtSubscriptionRequestWindow();
- boost::shared_ptr<SubscriptionRequestEvent> getEvent();
- private slots:
- void handleYes();
- void handleNo();
- void handleDefer();
- private:
- QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
- static QList<QtSubscriptionRequestWindow*> windows_;
- boost::shared_ptr<SubscriptionRequestEvent> event_;
- /*QPushButton* yesButton_;
- QPushButton* noButton_;
- QPushButton* deferButton_;*/
- };
+ class QtSubscriptionRequestWindow : public QDialog {
+ Q_OBJECT
+ public:
+ static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
+ ~QtSubscriptionRequestWindow();
+ boost::shared_ptr<SubscriptionRequestEvent> getEvent();
+ private slots:
+ void handleYes();
+ void handleNo();
+ void handleDefer();
+ private:
+ QtSubscriptionRequestWindow(boost::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = 0);
+ static QList<QtSubscriptionRequestWindow*> windows_;
+ boost::shared_ptr<SubscriptionRequestEvent> event_;
+ /*QPushButton* yesButton_;
+ QPushButton* noButton_;
+ QPushButton* deferButton_;*/
+ };
}
diff --git a/Swift/QtUI/QtSwift.cpp b/Swift/QtUI/QtSwift.cpp
index 6444e0c..5e8d61c 100644
--- a/Swift/QtUI/QtSwift.cpp
+++ b/Swift/QtUI/QtSwift.cpp
@@ -85,203 +85,203 @@ namespace Swift{
#endif
po::options_description QtSwift::getOptionsDescription() {
- po::options_description result("Options");
- result.add_options()
- ("debug", "Turn on debug logging")
- ("help", "Show this help message")
- ("version", "Show version information")
- ("netbook-mode", "Use netbook mode display (unsupported)")
- ("no-tabs", "Don't manage chat windows in tabs (unsupported)")
- ("latency-debug", "Use latency debugging (unsupported)")
- ("multi-account", po::value<int>()->default_value(1), "Number of accounts to open windows for (unsupported)")
- ("start-minimized", "Don't show the login/roster window at startup")
- ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.")
- ("trellis", "Enable support for trellis layout")
+ po::options_description result("Options");
+ result.add_options()
+ ("debug", "Turn on debug logging")
+ ("help", "Show this help message")
+ ("version", "Show version information")
+ ("netbook-mode", "Use netbook mode display (unsupported)")
+ ("no-tabs", "Don't manage chat windows in tabs (unsupported)")
+ ("latency-debug", "Use latency debugging (unsupported)")
+ ("multi-account", po::value<int>()->default_value(1), "Number of accounts to open windows for (unsupported)")
+ ("start-minimized", "Don't show the login/roster window at startup")
+ ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.")
+ ("trellis", "Enable support for trellis layout")
#if QT_VERSION >= 0x040800
- ("language", po::value<std::string>(), "Use a specific language, instead of the system-wide one")
+ ("language", po::value<std::string>(), "Use a specific language, instead of the system-wide one")
#endif
- ;
- return result;
+ ;
+ return result;
}
XMLSettingsProvider* QtSwift::loadSettingsFile(const QString& fileName) {
- QFile configFile(fileName);
- if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) {
- QString xmlString;
- while (!configFile.atEnd()) {
- QByteArray line = configFile.readLine();
- xmlString += line + "\n";
- }
- return new XMLSettingsProvider(Q2PSTRING(xmlString));
- }
- return new XMLSettingsProvider("");
+ QFile configFile(fileName);
+ if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) {
+ QString xmlString;
+ while (!configFile.atEnd()) {
+ QByteArray line = configFile.readLine();
+ xmlString += line + "\n";
+ }
+ return new XMLSettingsProvider(Q2PSTRING(xmlString));
+ }
+ return new XMLSettingsProvider("");
}
void QtSwift::loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons) {
- QFile file(fileName);
- if (file.exists() && file.open(QIODevice::ReadOnly)) {
- while (!file.atEnd()) {
- QString line = file.readLine();
- line.replace("\n", "");
- line.replace("\r", "");
- QStringList tokens = line.split(" ");
- if (tokens.size() == 2) {
- QString emoticonFile = tokens[1];
- if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) {
- emoticonFile = "file://" + emoticonFile;
- }
- emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile);
- }
- }
- }
+ QFile file(fileName);
+ if (file.exists() && file.open(QIODevice::ReadOnly)) {
+ while (!file.atEnd()) {
+ QString line = file.readLine();
+ line.replace("\n", "");
+ line.replace("\r", "");
+ QStringList tokens = line.split(" ");
+ if (tokens.size() == 2) {
+ QString emoticonFile = tokens[1];
+ if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) {
+ emoticonFile = "file://" + emoticonFile;
+ }
+ emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile);
+ }
+ }
+ }
}
QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMainThreadCaller_), autoUpdater_(NULL), idleDetector_(&idleQuerier_, networkFactories_.getTimerFactory(), 1000) {
- QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME);
- QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME);
- QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN);
- QCoreApplication::setApplicationVersion(buildVersion);
-
- qtSettings_ = new QtSettingsProvider();
- xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml")));
- settingsHierachy_ = new SettingsProviderHierachy();
- settingsHierachy_->addProviderToTopOfStack(xmlSettings_);
- settingsHierachy_->addProviderToTopOfStack(qtSettings_);
-
- networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL));
-
- std::map<std::string, std::string> emoticons;
- loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons);
- loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons);
-
- if (options.count("netbook-mode")) {
- splitter_ = new QtSingleWindow(qtSettings_);
- } else {
- splitter_ = NULL;
- }
-
- int numberOfAccounts = 1;
- try {
- numberOfAccounts = options["multi-account"].as<int>();
- } catch (...) {
- /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/
- numberOfAccounts = 1;
- }
-
- if (options.count("debug")) {
- Log::setLogLevel(Swift::Log::debug);
- }
-
- bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0;
- tabs_ = NULL;
- if (options.count("no-tabs") && !splitter_) {
- tabs_ = new QtChatTabsShortcutOnlySubstitute();
- }
- else {
- tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis"));
- }
- bool startMinimized = options.count("start-minimized") > 0;
- applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME);
- storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider());
- certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider());
- chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons);
- soundPlayer_ = new QtSoundPlayer(applicationPathProvider_);
-
- // Ugly, because the dock depends on the tray, but the temporary
- // multi-account hack creates one tray per account.
- QtSystemTray* systemTray = new QtSystemTray();
- systemTrays_.push_back(systemTray);
+ QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME);
+ QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME);
+ QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN);
+ QCoreApplication::setApplicationVersion(buildVersion);
+
+ qtSettings_ = new QtSettingsProvider();
+ xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml")));
+ settingsHierachy_ = new SettingsProviderHierachy();
+ settingsHierachy_->addProviderToTopOfStack(xmlSettings_);
+ settingsHierachy_->addProviderToTopOfStack(qtSettings_);
+
+ networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL));
+
+ std::map<std::string, std::string> emoticons;
+ loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons);
+ loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons);
+
+ if (options.count("netbook-mode")) {
+ splitter_ = new QtSingleWindow(qtSettings_);
+ } else {
+ splitter_ = NULL;
+ }
+
+ int numberOfAccounts = 1;
+ try {
+ numberOfAccounts = options["multi-account"].as<int>();
+ } catch (...) {
+ /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/
+ numberOfAccounts = 1;
+ }
+
+ if (options.count("debug")) {
+ Log::setLogLevel(Swift::Log::debug);
+ }
+
+ bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0;
+ tabs_ = NULL;
+ if (options.count("no-tabs") && !splitter_) {
+ tabs_ = new QtChatTabsShortcutOnlySubstitute();
+ }
+ else {
+ tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis"));
+ }
+ bool startMinimized = options.count("start-minimized") > 0;
+ applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME);
+ storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider());
+ certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider());
+ chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons);
+ soundPlayer_ = new QtSoundPlayer(applicationPathProvider_);
+
+ // Ugly, because the dock depends on the tray, but the temporary
+ // multi-account hack creates one tray per account.
+ QtSystemTray* systemTray = new QtSystemTray();
+ systemTrays_.push_back(systemTray);
#if defined(HAVE_GROWL)
- notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME);
+ notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME);
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon());
+ notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon());
#elif defined(SWIFTEN_PLATFORM_LINUX)
- notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME);
+ notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME);
#elif defined(SWIFTEN_PLATFORM_MACOSX)
- notifier_ = new NotificationCenterNotifier();
+ notifier_ = new NotificationCenterNotifier();
#else
- notifier_ = new NullNotifier();
+ notifier_ = new NullNotifier();
#endif
#if defined(SWIFTEN_PLATFORM_MACOSX)
- dock_ = new MacOSXDock(&cocoaApplication_);
+ dock_ = new MacOSXDock(&cocoaApplication_);
#else
- dock_ = new NullDock();
+ dock_ = new NullDock();
#endif
#if defined(SWIFTEN_PLATFORM_MACOSX)
- uriHandler_ = new QtURIHandler();
+ uriHandler_ = new QtURIHandler();
#elif defined(SWIFTEN_PLATFORM_WIN32)
- uriHandler_ = new NullURIHandler();
+ uriHandler_ = new NullURIHandler();
#else
- uriHandler_ = new QtDBUSURIHandler();
+ uriHandler_ = new QtDBUSURIHandler();
#endif
- statusCache_ = new StatusCache(applicationPathProvider_);
-
- if (splitter_) {
- splitter_->show();
- }
-
- for (int i = 0; i < numberOfAccounts; i++) {
- if (i > 0) {
- // Don't add the first tray (see note above)
- systemTrays_.push_back(new QtSystemTray());
- }
- QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID);
- uiFactories_.push_back(uiFactory);
- MainController* mainController = new MainController(
- &clientMainThreadCaller_,
- &networkFactories_,
- uiFactory,
- settingsHierachy_,
- systemTrays_[i],
- soundPlayer_,
- storagesFactory_,
- certificateStorageFactory_,
- dock_,
- notifier_,
- uriHandler_,
- &idleDetector_,
- emoticons,
- options.count("latency-debug") > 0);
- mainControllers_.push_back(mainController);
- }
-
-
- // PlatformAutoUpdaterFactory autoUpdaterFactory;
- // if (autoUpdaterFactory.isSupported()) {
- // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL);
- // autoUpdater_->checkForUpdates();
- // }
+ statusCache_ = new StatusCache(applicationPathProvider_);
+
+ if (splitter_) {
+ splitter_->show();
+ }
+
+ for (int i = 0; i < numberOfAccounts; i++) {
+ if (i > 0) {
+ // Don't add the first tray (see note above)
+ systemTrays_.push_back(new QtSystemTray());
+ }
+ QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID);
+ uiFactories_.push_back(uiFactory);
+ MainController* mainController = new MainController(
+ &clientMainThreadCaller_,
+ &networkFactories_,
+ uiFactory,
+ settingsHierachy_,
+ systemTrays_[i],
+ soundPlayer_,
+ storagesFactory_,
+ certificateStorageFactory_,
+ dock_,
+ notifier_,
+ uriHandler_,
+ &idleDetector_,
+ emoticons,
+ options.count("latency-debug") > 0);
+ mainControllers_.push_back(mainController);
+ }
+
+
+ // PlatformAutoUpdaterFactory autoUpdaterFactory;
+ // if (autoUpdaterFactory.isSupported()) {
+ // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL);
+ // autoUpdater_->checkForUpdates();
+ // }
}
QtSwift::~QtSwift() {
- delete autoUpdater_;
- foreach (QtUIFactory* factory, uiFactories_) {
- delete factory;
- }
- foreach (MainController* controller, mainControllers_) {
- delete controller;
- }
- delete notifier_;
- foreach (QtSystemTray* tray, systemTrays_) {
- delete tray;
- }
- delete tabs_;
- delete splitter_;
- delete settingsHierachy_;
- delete qtSettings_;
- delete xmlSettings_;
- delete statusCache_;
- delete uriHandler_;
- delete dock_;
- delete soundPlayer_;
- delete chatWindowFactory_;
- delete certificateStorageFactory_;
- delete storagesFactory_;
- delete applicationPathProvider_;
+ delete autoUpdater_;
+ foreach (QtUIFactory* factory, uiFactories_) {
+ delete factory;
+ }
+ foreach (MainController* controller, mainControllers_) {
+ delete controller;
+ }
+ delete notifier_;
+ foreach (QtSystemTray* tray, systemTrays_) {
+ delete tray;
+ }
+ delete tabs_;
+ delete splitter_;
+ delete settingsHierachy_;
+ delete qtSettings_;
+ delete xmlSettings_;
+ delete statusCache_;
+ delete uriHandler_;
+ delete dock_;
+ delete soundPlayer_;
+ delete chatWindowFactory_;
+ delete certificateStorageFactory_;
+ delete storagesFactory_;
+ delete applicationPathProvider_;
}
}
diff --git a/Swift/QtUI/QtSwift.h b/Swift/QtUI/QtSwift.h
index a971324..9932545 100644
--- a/Swift/QtUI/QtSwift.h
+++ b/Swift/QtUI/QtSwift.h
@@ -30,65 +30,65 @@ namespace po = boost::program_options;
class QSplitter;
namespace Swift {
- class QtUIFactory;
- class CertificateStorageFactory;
- class Dock;
- class Notifier;
- class StoragesFactory;
- class AutoUpdater;
- class ApplicationPathProvider;
- class AvatarStorage;
- class CapsStorage;
- class MainController;
- class QtSystemTray;
- class QtChatTabsBase;
- class QtChatWindowFactory;
- class QtSoundPlayer;
- class QtMUCSearchWindowFactory;
- class QtUserSearchWindowFactory;
- class EventLoop;
- class URIHandler;
- class SettingsProviderHierachy;
- class XMLSettingsProvider;
- class StatusCache;
- class QtSingleWindow;
-
- class QtSwift : public QObject {
- Q_OBJECT
- public:
- QtSwift(const po::variables_map& options);
- static po::options_description getOptionsDescription();
- ~QtSwift();
- private:
- XMLSettingsProvider* loadSettingsFile(const QString& fileName);
- void loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons);
- private:
- QtEventLoop clientMainThreadCaller_;
- PlatformTLSFactories tlsFactories_;
- BoostNetworkFactories networkFactories_;
- QtChatWindowFactory* chatWindowFactory_;
- std::vector<MainController*> mainControllers_;
- std::vector<QtSystemTray*> systemTrays_;
- std::vector<QtUIFactory*> uiFactories_;
- QtSettingsProvider* qtSettings_;
- XMLSettingsProvider* xmlSettings_;
- SettingsProviderHierachy* settingsHierachy_;
- QtSingleWindow* splitter_;
- QtSoundPlayer* soundPlayer_;
- Dock* dock_;
- URIHandler* uriHandler_;
- QtChatTabsBase* tabs_;
- ApplicationPathProvider* applicationPathProvider_;
- StoragesFactory* storagesFactory_;
- CertificateStorageFactory* certificateStorageFactory_;
- AutoUpdater* autoUpdater_;
- Notifier* notifier_;
- StatusCache* statusCache_;
- PlatformIdleQuerier idleQuerier_;
- ActualIdleDetector idleDetector_;
+ class QtUIFactory;
+ class CertificateStorageFactory;
+ class Dock;
+ class Notifier;
+ class StoragesFactory;
+ class AutoUpdater;
+ class ApplicationPathProvider;
+ class AvatarStorage;
+ class CapsStorage;
+ class MainController;
+ class QtSystemTray;
+ class QtChatTabsBase;
+ class QtChatWindowFactory;
+ class QtSoundPlayer;
+ class QtMUCSearchWindowFactory;
+ class QtUserSearchWindowFactory;
+ class EventLoop;
+ class URIHandler;
+ class SettingsProviderHierachy;
+ class XMLSettingsProvider;
+ class StatusCache;
+ class QtSingleWindow;
+
+ class QtSwift : public QObject {
+ Q_OBJECT
+ public:
+ QtSwift(const po::variables_map& options);
+ static po::options_description getOptionsDescription();
+ ~QtSwift();
+ private:
+ XMLSettingsProvider* loadSettingsFile(const QString& fileName);
+ void loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons);
+ private:
+ QtEventLoop clientMainThreadCaller_;
+ PlatformTLSFactories tlsFactories_;
+ BoostNetworkFactories networkFactories_;
+ QtChatWindowFactory* chatWindowFactory_;
+ std::vector<MainController*> mainControllers_;
+ std::vector<QtSystemTray*> systemTrays_;
+ std::vector<QtUIFactory*> uiFactories_;
+ QtSettingsProvider* qtSettings_;
+ XMLSettingsProvider* xmlSettings_;
+ SettingsProviderHierachy* settingsHierachy_;
+ QtSingleWindow* splitter_;
+ QtSoundPlayer* soundPlayer_;
+ Dock* dock_;
+ URIHandler* uriHandler_;
+ QtChatTabsBase* tabs_;
+ ApplicationPathProvider* applicationPathProvider_;
+ StoragesFactory* storagesFactory_;
+ CertificateStorageFactory* certificateStorageFactory_;
+ AutoUpdater* autoUpdater_;
+ Notifier* notifier_;
+ StatusCache* statusCache_;
+ PlatformIdleQuerier idleQuerier_;
+ ActualIdleDetector idleDetector_;
#if defined(SWIFTEN_PLATFORM_MACOSX)
- CocoaApplication cocoaApplication_;
- CocoaApplicationActivateHelper cocoaApplicationActivateHelper_;
+ CocoaApplication cocoaApplication_;
+ CocoaApplicationActivateHelper cocoaApplicationActivateHelper_;
#endif
- };
+ };
}
diff --git a/Swift/QtUI/QtSystemTray.cpp b/Swift/QtUI/QtSystemTray.cpp
index d268d16..55a7d43 100644
--- a/Swift/QtUI/QtSystemTray.cpp
+++ b/Swift/QtUI/QtSystemTray.cpp
@@ -20,71 +20,71 @@
namespace Swift {
QtSystemTray::QtSystemTray() : QObject(), statusType_(StatusShow::None), trayMenu_(0), onlineIcon_(":icons/online.png"), awayIcon_(":icons/away.png"), dndIcon_(":icons/dnd.png"), offlineIcon_(":icons/offline.png"), newMessageIcon_(":icons/new-chat.png"), throbberMovie_(":/icons/connecting.mng"), unreadMessages_(false), connecting_(false) {
- trayIcon_ = new QSystemTrayIcon(offlineIcon_);
- trayIcon_->setToolTip("Swift");
- connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason)));
- connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int)));
+ trayIcon_ = new QSystemTrayIcon(offlineIcon_);
+ trayIcon_->setToolTip("Swift");
+ connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason)));
+ connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int)));
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC)
- bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid();
- if (isUnity) {
- // Add an activation menu, because this is the only way to get the application to the
- // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity)
- trayMenu_ = new QMenu();
- QAction* showAction = new QAction(QString("Show/Hide"), this);
- connect(showAction, SIGNAL(triggered()), SIGNAL(clicked()));
- trayMenu_->addAction(showAction);
- trayIcon_->setContextMenu(trayMenu_);
- }
+ bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid();
+ if (isUnity) {
+ // Add an activation menu, because this is the only way to get the application to the
+ // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity)
+ trayMenu_ = new QMenu();
+ QAction* showAction = new QAction(QString("Show/Hide"), this);
+ connect(showAction, SIGNAL(triggered()), SIGNAL(clicked()));
+ trayMenu_->addAction(showAction);
+ trayIcon_->setContextMenu(trayMenu_);
+ }
#endif
- trayIcon_->show();
+ trayIcon_->show();
}
QtSystemTray::~QtSystemTray() {
- delete trayMenu_;
- delete trayIcon_;
+ delete trayMenu_;
+ delete trayIcon_;
}
void QtSystemTray::setUnreadMessages(bool some) {
- unreadMessages_ = some;
- updateStatusIcon();
+ unreadMessages_ = some;
+ updateStatusIcon();
}
void QtSystemTray::handleThrobberFrameChanged(int /*frameNumber*/) {
- trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap()));
+ trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap()));
}
void QtSystemTray::setConnecting() {
- connecting_ = true;
- updateStatusIcon();
+ connecting_ = true;
+ updateStatusIcon();
}
void QtSystemTray::handleIconActivated(QSystemTrayIcon::ActivationReason reason) {
- if (reason == QSystemTrayIcon::Trigger) {
- emit clicked();
- }
+ if (reason == QSystemTrayIcon::Trigger) {
+ emit clicked();
+ }
}
void QtSystemTray::setStatusType(StatusShow::Type type) {
- connecting_ = false;
- statusType_ = type;
- updateStatusIcon();
+ connecting_ = false;
+ statusType_ = type;
+ updateStatusIcon();
}
void QtSystemTray::updateStatusIcon() {
- throbberMovie_.stop();
- if (unreadMessages_) {
- trayIcon_->setIcon(newMessageIcon_);
- } else if (connecting_) {
- throbberMovie_.start();
- } else {
- switch (statusType_) {
- case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break;
- case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break;
- case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break;
- case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break;
- case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break;
- case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break;
- }
- }
+ throbberMovie_.stop();
+ if (unreadMessages_) {
+ trayIcon_->setIcon(newMessageIcon_);
+ } else if (connecting_) {
+ throbberMovie_.start();
+ } else {
+ switch (statusType_) {
+ case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break;
+ case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break;
+ case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break;
+ case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break;
+ case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break;
+ case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break;
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtSystemTray.h b/Swift/QtUI/QtSystemTray.h
index b1dffd0..ba2c5cb 100644
--- a/Swift/QtUI/QtSystemTray.h
+++ b/Swift/QtUI/QtSystemTray.h
@@ -16,35 +16,35 @@ class QMenu;
namespace Swift {
- class QtSystemTray : public QObject, public SystemTray {
- Q_OBJECT
- public:
- QtSystemTray();
- ~QtSystemTray();
- void setUnreadMessages(bool some);
- void setStatusType(StatusShow::Type type);
- void setConnecting();
- QSystemTrayIcon* getQSystemTrayIcon() {
- return trayIcon_;
- }
+ class QtSystemTray : public QObject, public SystemTray {
+ Q_OBJECT
+ public:
+ QtSystemTray();
+ ~QtSystemTray();
+ void setUnreadMessages(bool some);
+ void setStatusType(StatusShow::Type type);
+ void setConnecting();
+ QSystemTrayIcon* getQSystemTrayIcon() {
+ return trayIcon_;
+ }
- signals:
- void clicked();
- private slots:
- void handleIconActivated(QSystemTrayIcon::ActivationReason reason);
- void handleThrobberFrameChanged(int);
- private:
- void updateStatusIcon();
- StatusShow::Type statusType_;
- QSystemTrayIcon* trayIcon_;
- QMenu* trayMenu_;
- QIcon onlineIcon_;
- QIcon awayIcon_;
- QIcon dndIcon_;
- QIcon offlineIcon_;
- QIcon newMessageIcon_;
- QMovie throbberMovie_;
- bool unreadMessages_;
- bool connecting_;
- };
+ signals:
+ void clicked();
+ private slots:
+ void handleIconActivated(QSystemTrayIcon::ActivationReason reason);
+ void handleThrobberFrameChanged(int);
+ private:
+ void updateStatusIcon();
+ StatusShow::Type statusType_;
+ QSystemTrayIcon* trayIcon_;
+ QMenu* trayMenu_;
+ QIcon onlineIcon_;
+ QIcon awayIcon_;
+ QIcon dndIcon_;
+ QIcon offlineIcon_;
+ QIcon newMessageIcon_;
+ QMovie throbberMovie_;
+ bool unreadMessages_;
+ bool connecting_;
+ };
}
diff --git a/Swift/QtUI/QtTabWidget.cpp b/Swift/QtUI/QtTabWidget.cpp
index ca9ea5d..9f353d7 100644
--- a/Swift/QtUI/QtTabWidget.cpp
+++ b/Swift/QtUI/QtTabWidget.cpp
@@ -17,10 +17,10 @@ QtTabWidget::~QtTabWidget() {
}
QTabBar* QtTabWidget::tabBar() {
- return QTabWidget::tabBar();
+ return QTabWidget::tabBar();
}
void QtTabWidget::setTabBar(QTabBar* tabBar) {
- QTabWidget::setTabBar(tabBar);
+ QTabWidget::setTabBar(tabBar);
}
}
diff --git a/Swift/QtUI/QtTabWidget.h b/Swift/QtUI/QtTabWidget.h
index 0a723e2..de1a846 100644
--- a/Swift/QtUI/QtTabWidget.h
+++ b/Swift/QtUI/QtTabWidget.h
@@ -9,13 +9,13 @@
#include <QTabWidget>
namespace Swift {
- class QtTabWidget : public QTabWidget {
- Q_OBJECT
- public:
- QtTabWidget(QWidget* parent);
- virtual ~QtTabWidget();
+ class QtTabWidget : public QTabWidget {
+ Q_OBJECT
+ public:
+ QtTabWidget(QWidget* parent);
+ virtual ~QtTabWidget();
- QTabBar* tabBar();
- void setTabBar(QTabBar* tabBar);
- };
+ QTabBar* tabBar();
+ void setTabBar(QTabBar* tabBar);
+ };
}
diff --git a/Swift/QtUI/QtTabbable.cpp b/Swift/QtUI/QtTabbable.cpp
index 0e08343..bad6315 100644
--- a/Swift/QtUI/QtTabbable.cpp
+++ b/Swift/QtUI/QtTabbable.cpp
@@ -23,47 +23,47 @@ QtTabbable::QtTabbable() : QWidget() {
}
QtTabbable::~QtTabbable() {
- emit windowClosing();
+ 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());
+ /*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.
- if (keyEvent->type() == QEvent::KeyRelease) {
- emit requestNextTab();
- }
- return true;
- }
+ 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.
+ if (keyEvent->type() == QEvent::KeyRelease) {
+ emit requestNextTab();
+ }
+ return true;
+ }
#ifdef SWIFTEN_PLATFORM_LINUX
- else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) {
+ else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) {
#else
- else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) {
+ else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) {
#endif
#ifdef SWIFTEN_PLATFORM_WINDOWS
- // Windows emits both the KeyPress and KeyRelease events.
- if (keyEvent->type() == QEvent::KeyPress) {
+ // Windows emits both the KeyPress and KeyRelease events.
+ if (keyEvent->type() == QEvent::KeyPress) {
#else
- if (keyEvent->type() != QEvent::ShortcutOverride) {
+ if (keyEvent->type() != QEvent::ShortcutOverride) {
#endif
- emit requestPreviousTab();
- }
- return true;
- }
- }
- return QWidget::event(event);
+ emit requestPreviousTab();
+ }
+ return true;
+ }
+ }
+ return QWidget::event(event);
}
}
diff --git a/Swift/QtUI/QtTabbable.h b/Swift/QtUI/QtTabbable.h
index db83ba9..c2d0961 100644
--- a/Swift/QtUI/QtTabbable.h
+++ b/Swift/QtUI/QtTabbable.h
@@ -11,29 +11,29 @@
#include <QWidget>
namespace Swift {
- class QtTabbable : public QWidget {
- Q_OBJECT
- public:
- enum AlertType {NoActivity, WaitingActivity, ImpendingActivity};
- virtual ~QtTabbable();
- bool isWidgetSelected();
- virtual AlertType getWidgetAlertState() {return NoActivity;}
- virtual int getCount() {return 0;}
- virtual std::string getID() const = 0;
+ class QtTabbable : public QWidget {
+ Q_OBJECT
+ public:
+ enum AlertType {NoActivity, WaitingActivity, ImpendingActivity};
+ virtual ~QtTabbable();
+ bool isWidgetSelected();
+ virtual AlertType getWidgetAlertState() {return NoActivity;}
+ virtual int getCount() {return 0;}
+ virtual std::string getID() const = 0;
- protected:
- QtTabbable();
- bool event(QEvent* event);
+ protected:
+ QtTabbable();
+ bool event(QEvent* event);
- signals:
- void titleUpdated();
- void countUpdated();
- void windowClosing();
- void windowOpening();
- void wantsToActivate();
- void requestPreviousTab();
- void requestNextTab();
- void requestActiveTab();
- void requestFlash();
- };
+ signals:
+ void titleUpdated();
+ void countUpdated();
+ void windowClosing();
+ void windowOpening();
+ void wantsToActivate();
+ void requestPreviousTab();
+ void requestNextTab();
+ void requestActiveTab();
+ void requestFlash();
+ };
}
diff --git a/Swift/QtUI/QtTextEdit.cpp b/Swift/QtUI/QtTextEdit.cpp
index adf3878..d3ba914 100644
--- a/Swift/QtUI/QtTextEdit.cpp
+++ b/Swift/QtUI/QtTextEdit.cpp
@@ -30,202 +30,202 @@
namespace Swift {
QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(NULL), highlighter_(NULL) {
- connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
- settings_ = settings;
+ connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
+ settings_ = settings;
#ifdef HAVE_SPELLCHECKER
- setUpSpellChecker();
+ setUpSpellChecker();
#endif
- handleTextChanged();
- QTextOption textOption = document()->defaultTextOption();
- textOption.setWrapMode(QTextOption::WordWrap);
- document()->setDefaultTextOption(textOption);
+ handleTextChanged();
+ QTextOption textOption = document()->defaultTextOption();
+ textOption.setWrapMode(QTextOption::WordWrap);
+ document()->setDefaultTextOption(textOption);
}
QtTextEdit::~QtTextEdit() {
- delete checker_;
+ delete checker_;
}
void QtTextEdit::keyPressEvent(QKeyEvent* event) {
- int key = event->key();
- Qt::KeyboardModifiers modifiers = event->modifiers();
- if ((key == Qt::Key_Enter || key == Qt::Key_Return)
- && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) {
- emit returnPressed();
- }
- else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier)
- || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty())
- || (key == Qt::Key_W && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier)
- || (key == Qt::Key_A && modifiers == Qt::AltModifier)
- || (key == Qt::Key_Tab)
- ) {
- emit unhandledKeyPressEvent(event);
- }
- else if ((key == Qt::Key_Up)
- || (key == Qt::Key_Down)) {
- emit unhandledKeyPressEvent(event);
- QTextEdit::keyPressEvent(event);
- }
- else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) {
- QTextCursor cursor = textCursor();
- cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor);
- cursor.removeSelectedText();
- }
- else {
- QTextEdit::keyPressEvent(event);
- }
+ int key = event->key();
+ Qt::KeyboardModifiers modifiers = event->modifiers();
+ if ((key == Qt::Key_Enter || key == Qt::Key_Return)
+ && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) {
+ emit returnPressed();
+ }
+ else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier)
+ || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty())
+ || (key == Qt::Key_W && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier)
+ || (key == Qt::Key_A && modifiers == Qt::AltModifier)
+ || (key == Qt::Key_Tab)
+ ) {
+ emit unhandledKeyPressEvent(event);
+ }
+ else if ((key == Qt::Key_Up)
+ || (key == Qt::Key_Down)) {
+ emit unhandledKeyPressEvent(event);
+ QTextEdit::keyPressEvent(event);
+ }
+ else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) {
+ QTextCursor cursor = textCursor();
+ cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor);
+ cursor.removeSelectedText();
+ }
+ else {
+ QTextEdit::keyPressEvent(event);
+ }
}
void QtTextEdit::focusInEvent(QFocusEvent* event) {
- receivedFocus();
- QTextEdit::focusInEvent(event);
+ receivedFocus();
+ QTextEdit::focusInEvent(event);
}
void QtTextEdit::focusOutEvent(QFocusEvent* event) {
- lostFocus();
- QTextEdit::focusOutEvent(event);
+ lostFocus();
+ QTextEdit::focusOutEvent(event);
}
void QtTextEdit::handleTextChanged() {
- QSize previous(maximumSize());
- setMaximumSize(QSize(maximumWidth(), sizeHint().height()));
- if (previous != maximumSize()) {
- updateGeometry();
- }
+ QSize previous(maximumSize());
+ setMaximumSize(QSize(maximumWidth(), sizeHint().height()));
+ if (previous != maximumSize()) {
+ updateGeometry();
+ }
}
void QtTextEdit::replaceMisspelledWord(const QString& word, int cursorPosition) {
- QTextCursor cursor = textCursor();
- PositionPair wordPosition = getWordFromCursor(cursorPosition);
- cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
- cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
- QTextCharFormat normalFormat;
- cursor.insertText(word, normalFormat);
+ QTextCursor cursor = textCursor();
+ PositionPair wordPosition = getWordFromCursor(cursorPosition);
+ cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
+ cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
+ QTextCharFormat normalFormat;
+ cursor.insertText(word, normalFormat);
}
PositionPair QtTextEdit::getWordFromCursor(int cursorPosition) {
- PositionPairList misspelledPositions = highlighter_->getMisspelledPositions();
- for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) {
- if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) {
- return *it;
- }
- }
- return boost::make_tuple(-1,-1);
+ PositionPairList misspelledPositions = highlighter_->getMisspelledPositions();
+ for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) {
+ if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) {
+ return *it;
+ }
+ }
+ return boost::make_tuple(-1,-1);
}
QSize QtTextEdit::sizeHint() const {
- QSize hint = document()->size().toSize();
- QMargins margins = contentsMargins();
- return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
+ QSize hint = document()->size().toSize();
+ QMargins margins = contentsMargins();
+ return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
}
void QtTextEdit::contextMenuEvent(QContextMenuEvent* event) {
- QMenu* menu = createStandardContextMenu();
- QTextCursor cursor = cursorForPosition(event->pos());
+ QMenu* menu = createStandardContextMenu();
+ QTextCursor cursor = cursorForPosition(event->pos());
#ifdef HAVE_SPELLCHECKER
- QAction* insertPoint = menu->actions().first();
- QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu);
- menu->insertAction(insertPoint, settingsAction);
- menu->insertAction(insertPoint, menu->addSeparator());
- addSuggestions(menu, event);
- QAction* result = menu->exec(event->globalPos());
- if (result == settingsAction) {
- spellCheckerSettingsWindow();
- }
- for (std::vector<QAction*>::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) {
- if (*it == result) {
- replaceMisspelledWord((*it)->text(), cursor.position());
- }
- }
+ QAction* insertPoint = menu->actions().first();
+ QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu);
+ menu->insertAction(insertPoint, settingsAction);
+ menu->insertAction(insertPoint, menu->addSeparator());
+ addSuggestions(menu, event);
+ QAction* result = menu->exec(event->globalPos());
+ if (result == settingsAction) {
+ spellCheckerSettingsWindow();
+ }
+ for (std::vector<QAction*>::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) {
+ if (*it == result) {
+ replaceMisspelledWord((*it)->text(), cursor.position());
+ }
+ }
#else
- menu->exec(event->globalPos());
+ menu->exec(event->globalPos());
#endif
- delete menu;
+ delete menu;
}
void QtTextEdit::addSuggestions(QMenu* menu, QContextMenuEvent* event)
{
- replaceWordActions_.clear();
- if (checker_ && highlighter_) {
- QAction* insertPoint = menu->actions().first();
- QTextCursor cursor = cursorForPosition(event->pos());
- PositionPair wordPosition = getWordFromCursor(cursor.position());
- if (boost::get<0>(wordPosition) < 0) {
- // The click was executed outside a spellable word so no
- // suggestions are necessary
- return;
- }
- cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
- cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
- std::vector<std::string> wordList;
- checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList);
- if (wordList.size() == 0) {
- QAction* noSuggestions = new QAction(tr("No Suggestions"), menu);
- noSuggestions->setDisabled(true);
- menu->insertAction(insertPoint, noSuggestions);
- }
- else {
- for (std::vector<std::string>::iterator it = wordList.begin(); it != wordList.end(); ++it) {
- QAction* wordAction = new QAction(it->c_str(), menu);
- menu->insertAction(insertPoint, wordAction);
- replaceWordActions_.push_back(wordAction);
- }
- }
- menu->insertAction(insertPoint, menu->addSeparator());
- }
+ replaceWordActions_.clear();
+ if (checker_ && highlighter_) {
+ QAction* insertPoint = menu->actions().first();
+ QTextCursor cursor = cursorForPosition(event->pos());
+ PositionPair wordPosition = getWordFromCursor(cursor.position());
+ if (boost::get<0>(wordPosition) < 0) {
+ // The click was executed outside a spellable word so no
+ // suggestions are necessary
+ return;
+ }
+ cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor);
+ cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor);
+ std::vector<std::string> wordList;
+ checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList);
+ if (wordList.size() == 0) {
+ QAction* noSuggestions = new QAction(tr("No Suggestions"), menu);
+ noSuggestions->setDisabled(true);
+ menu->insertAction(insertPoint, noSuggestions);
+ }
+ else {
+ for (std::vector<std::string>::iterator it = wordList.begin(); it != wordList.end(); ++it) {
+ QAction* wordAction = new QAction(it->c_str(), menu);
+ menu->insertAction(insertPoint, wordAction);
+ replaceWordActions_.push_back(wordAction);
+ }
+ }
+ menu->insertAction(insertPoint, menu->addSeparator());
+ }
}
#ifdef HAVE_SPELLCHECKER
void QtTextEdit::setUpSpellChecker()
{
- delete highlighter_;
- highlighter_ = NULL;
- delete checker_;
- checker_ = NULL;
- if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) {
- std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH);
- std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE);
- checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile);
- if (checker_) {
- highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
- }
- else {
- // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
- SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
- settings_->storeSetting(SettingConstants::SPELL_CHECKER, false);
- }
-
- }
+ delete highlighter_;
+ highlighter_ = NULL;
+ delete checker_;
+ checker_ = NULL;
+ if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) {
+ std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH);
+ std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE);
+ checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile);
+ if (checker_) {
+ highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
+ }
+ else {
+ // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
+ SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
+ settings_->storeSetting(SettingConstants::SPELL_CHECKER, false);
+ }
+
+ }
}
#endif
void QtTextEdit::spellCheckerSettingsWindow() {
- if (!spellCheckerWindow_) {
- spellCheckerWindow_ = new QtSpellCheckerWindow(settings_);
- settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1));
- spellCheckerWindow_->show();
- }
- else {
- spellCheckerWindow_->show();
- spellCheckerWindow_->raise();
- spellCheckerWindow_->activateWindow();
- }
+ if (!spellCheckerWindow_) {
+ spellCheckerWindow_ = new QtSpellCheckerWindow(settings_);
+ settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1));
+ spellCheckerWindow_->show();
+ }
+ else {
+ spellCheckerWindow_->show();
+ spellCheckerWindow_->raise();
+ spellCheckerWindow_->activateWindow();
+ }
}
void QtTextEdit::handleSettingChanged(const std::string& settings) {
- if (settings == SettingConstants::SPELL_CHECKER.getKey()
- || settings == SettingConstants::DICT_PATH.getKey()
- || settings == SettingConstants::DICT_FILE.getKey()) {
+ if (settings == SettingConstants::SPELL_CHECKER.getKey()
+ || settings == SettingConstants::DICT_PATH.getKey()
+ || settings == SettingConstants::DICT_FILE.getKey()) {
#ifdef HAVE_SPELLCHECKER
- setUpSpellChecker();
- if (highlighter_) {
- highlighter_->rehighlight();
- }
+ setUpSpellChecker();
+ if (highlighter_) {
+ highlighter_->rehighlight();
+ }
#endif
- }
+ }
}
}
diff --git a/Swift/QtUI/QtTextEdit.h b/Swift/QtUI/QtTextEdit.h
index 67826ba..f03699b 100644
--- a/Swift/QtUI/QtTextEdit.h
+++ b/Swift/QtUI/QtTextEdit.h
@@ -17,47 +17,47 @@
#include <Swift/QtUI/QtSpellCheckHighlighter.h>
namespace Swift {
- class SpellChecker;
- class QtSpellCheckerWindow;
-
- class QtTextEdit : public QTextEdit {
- Q_OBJECT
- public:
- QtTextEdit(SettingsProvider* settings, QWidget* parent = 0);
- virtual ~QtTextEdit();
- virtual QSize sizeHint() const;
-
- signals:
- void wordCorrected(QString& word);
- void returnPressed();
- void unhandledKeyPressEvent(QKeyEvent* event);
- void receivedFocus();
- void lostFocus();
-
- public slots:
- void handleSettingChanged(const std::string& settings);
-
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- virtual void focusInEvent(QFocusEvent* event);
- virtual void focusOutEvent(QFocusEvent* event);
- virtual void contextMenuEvent(QContextMenuEvent* event);
-
- private slots:
- void handleTextChanged();
-
- private:
- void addSuggestions(QMenu* menu, QContextMenuEvent* event);
- void replaceMisspelledWord(const QString& word, int cursorPosition);
- void setUpSpellChecker();
- void spellCheckerSettingsWindow();
- PositionPair getWordFromCursor(int cursorPosition);
-
- private:
- SpellChecker* checker_;
- QtSpellCheckHighlighter* highlighter_;
- std::vector<QAction*> replaceWordActions_;
- SettingsProvider* settings_;
- QPointer<QtSpellCheckerWindow> spellCheckerWindow_;
- };
+ class SpellChecker;
+ class QtSpellCheckerWindow;
+
+ class QtTextEdit : public QTextEdit {
+ Q_OBJECT
+ public:
+ QtTextEdit(SettingsProvider* settings, QWidget* parent = 0);
+ virtual ~QtTextEdit();
+ virtual QSize sizeHint() const;
+
+ signals:
+ void wordCorrected(QString& word);
+ void returnPressed();
+ void unhandledKeyPressEvent(QKeyEvent* event);
+ void receivedFocus();
+ void lostFocus();
+
+ public slots:
+ void handleSettingChanged(const std::string& settings);
+
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ virtual void focusInEvent(QFocusEvent* event);
+ virtual void focusOutEvent(QFocusEvent* event);
+ virtual void contextMenuEvent(QContextMenuEvent* event);
+
+ private slots:
+ void handleTextChanged();
+
+ private:
+ void addSuggestions(QMenu* menu, QContextMenuEvent* event);
+ void replaceMisspelledWord(const QString& word, int cursorPosition);
+ void setUpSpellChecker();
+ void spellCheckerSettingsWindow();
+ PositionPair getWordFromCursor(int cursorPosition);
+
+ private:
+ SpellChecker* checker_;
+ QtSpellCheckHighlighter* highlighter_;
+ std::vector<QAction*> replaceWordActions_;
+ SettingsProvider* settings_;
+ QPointer<QtSpellCheckerWindow> spellCheckerWindow_;
+ };
}
diff --git a/Swift/QtUI/QtTranslator.h b/Swift/QtUI/QtTranslator.h
index b74ea3e..4254324 100644
--- a/Swift/QtUI/QtTranslator.h
+++ b/Swift/QtUI/QtTranslator.h
@@ -11,15 +11,15 @@
#include <Swift/Controllers/Translator.h>
class QtTranslator : public Swift::Translator {
- public:
- QtTranslator() {
- }
+ public:
+ QtTranslator() {
+ }
- virtual std::string translate(const std::string& text, const std::string& context) {
+ virtual std::string translate(const std::string& text, const std::string& context) {
#if QT_VERSION >= 0x050000
- return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8());
+ return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8());
#else
- return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8());
+ return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8());
#endif
- }
+ }
};
diff --git a/Swift/QtUI/QtUIFactory.cpp b/Swift/QtUI/QtUIFactory.cpp
index 0cde4e1..a1321bd 100644
--- a/Swift/QtUI/QtUIFactory.cpp
+++ b/Swift/QtUI/QtUIFactory.cpp
@@ -39,148 +39,148 @@
namespace Swift {
QtUIFactory::QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID) : settings(settings), qtOnlySettings(qtOnlySettings), tabsBase(tabs), netbookSplitter(netbookSplitter), systemTray(systemTray), chatWindowFactory(chatWindowFactory), timerFactory_(timerFactory), lastMainWindow(NULL), loginWindow(NULL), statusCache(statusCache), startMinimized(startMinimized), emoticonsExist_(emoticonsExist), enableAdHocCommandOnJID_(enableAdHocCommandOnJID) {
- chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE);
- historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE);
- this->tabs = dynamic_cast<QtChatTabs*>(tabsBase);
+ chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE);
+ historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE);
+ this->tabs = dynamic_cast<QtChatTabs*>(tabsBase);
}
XMLConsoleWidget* QtUIFactory::createXMLConsoleWidget() {
- QtXMLConsoleWidget* widget = new QtXMLConsoleWidget();
- tabsBase->addTab(widget);
- showTabs();
- widget->show();
- return widget;
+ QtXMLConsoleWidget* widget = new QtXMLConsoleWidget();
+ tabsBase->addTab(widget);
+ showTabs();
+ widget->show();
+ return widget;
}
HistoryWindow* QtUIFactory::createHistoryWindow(UIEventStream* uiEventStream) {
- QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream);
- tabsBase->addTab(window);
- showTabs();
- connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int)));
+ QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream);
+ tabsBase->addTab(window);
+ showTabs();
+ connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int)));
- window->handleFontResized(historyFontSize_);
- window->show();
- return window;
+ window->handleFontResized(historyFontSize_);
+ window->show();
+ return window;
}
void QtUIFactory::handleHistoryWindowFontResized(int size) {
- historyFontSize_ = size;
- settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size);
+ historyFontSize_ = size;
+ settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size);
}
FileTransferListWidget* QtUIFactory::createFileTransferListWidget() {
- QtFileTransferListWidget* widget = new QtFileTransferListWidget();
- tabsBase->addTab(widget);
- showTabs();
- widget->show();
- return widget;
+ QtFileTransferListWidget* widget = new QtFileTransferListWidget();
+ tabsBase->addTab(widget);
+ showTabs();
+ widget->show();
+ return widget;
}
MainWindow* QtUIFactory::createMainWindow(UIEventStream* eventStream) {
- lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_);
- if (tabs) {
- tabs->setViewMenu(lastMainWindow->getMenus()[0]);
- }
- return lastMainWindow;
+ lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_);
+ if (tabs) {
+ tabs->setViewMenu(lastMainWindow->getMenus()[0]);
+ }
+ return lastMainWindow;
}
LoginWindow* QtUIFactory::createLoginWindow(UIEventStream* eventStream) {
- loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_);
- if (netbookSplitter) {
- netbookSplitter->insertAtFront(loginWindow);
- }
- connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront()));
+ loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_);
+ if (netbookSplitter) {
+ netbookSplitter->insertAtFront(loginWindow);
+ }
+ connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront()));
#ifndef SWIFT_MOBILE
- QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry");
- if (loginWindowGeometryVariant.isValid()) {
- loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray());
- }
- connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged()));
- if (startMinimized) loginWindow->hide();
+ QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry");
+ if (loginWindowGeometryVariant.isValid()) {
+ loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray());
+ }
+ connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged()));
+ if (startMinimized) loginWindow->hide();
#endif
- return loginWindow;
+ return loginWindow;
}
void QtUIFactory::handleLoginWindowGeometryChanged() {
- qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry());
+ qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry());
}
EventWindow* QtUIFactory::createEventWindow() {
- return lastMainWindow->getEventWindow();
+ return lastMainWindow->getEventWindow();
}
ChatListWindow* QtUIFactory::createChatListWindow(UIEventStream*) {
- return lastMainWindow->getChatListWindow();
+ return lastMainWindow->getChatListWindow();
}
MUCSearchWindow* QtUIFactory::createMUCSearchWindow() {
- return new QtMUCSearchWindow();
+ return new QtMUCSearchWindow();
}
ChatWindow* QtUIFactory::createChatWindow(const JID& contact, UIEventStream* eventStream) {
- QtChatWindow* window = dynamic_cast<QtChatWindow*>(chatWindowFactory->createChatWindow(contact, eventStream));
- chatWindows.push_back(window);
- std::vector<QPointer<QtChatWindow> > deletions;
- foreach (QPointer<QtChatWindow> existingWindow, chatWindows) {
- if (existingWindow.isNull()) {
- deletions.push_back(existingWindow);
- } else {
- connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int)));
- connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int)));
- }
- }
- foreach (QPointer<QtChatWindow> deletedWindow, deletions) {
- chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end());
- }
- connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int)));
- window->handleFontResized(chatFontSize);
- return window;
+ QtChatWindow* window = dynamic_cast<QtChatWindow*>(chatWindowFactory->createChatWindow(contact, eventStream));
+ chatWindows.push_back(window);
+ std::vector<QPointer<QtChatWindow> > deletions;
+ foreach (QPointer<QtChatWindow> existingWindow, chatWindows) {
+ if (existingWindow.isNull()) {
+ deletions.push_back(existingWindow);
+ } else {
+ connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int)));
+ connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int)));
+ }
+ }
+ foreach (QPointer<QtChatWindow> deletedWindow, deletions) {
+ chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end());
+ }
+ connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int)));
+ window->handleFontResized(chatFontSize);
+ return window;
}
void QtUIFactory::handleChatWindowFontResized(int size) {
- chatFontSize = size;
- settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size);
+ chatFontSize = size;
+ settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size);
}
UserSearchWindow* QtUIFactory::createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups) {
- return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings);
+ return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings);
}
JoinMUCWindow* QtUIFactory::createJoinMUCWindow(UIEventStream* uiEventStream) {
- return new QtJoinMUCWindow(uiEventStream);
+ return new QtJoinMUCWindow(uiEventStream);
}
ProfileWindow* QtUIFactory::createProfileWindow() {
- return new QtProfileWindow();
+ return new QtProfileWindow();
}
ContactEditWindow* QtUIFactory::createContactEditWindow() {
- return new QtContactEditWindow();
+ return new QtContactEditWindow();
}
WhiteboardWindow* QtUIFactory::createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession) {
- return new QtWhiteboardWindow(whiteboardSession);
+ return new QtWhiteboardWindow(whiteboardSession);
}
HighlightEditorWindow* QtUIFactory::createHighlightEditorWindow() {
- return new QtHighlightEditor(qtOnlySettings);
+ return new QtHighlightEditor(qtOnlySettings);
}
BlockListEditorWidget *QtUIFactory::createBlockListEditorWidget() {
- return new QtBlockListEditorWindow();
+ return new QtBlockListEditorWindow();
}
AdHocCommandWindow* QtUIFactory::createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command) {
- return new QtAdHocCommandWindow(command);
+ return new QtAdHocCommandWindow(command);
}
void QtUIFactory::showTabs() {
- if (tabs) {
- if (!tabs->isVisible()) {
- tabs->show();
- }
- }
+ if (tabs) {
+ if (!tabs->isVisible()) {
+ tabs->show();
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtUIFactory.h b/Swift/QtUI/QtUIFactory.h
index 1d935bc..c72bf63 100644
--- a/Swift/QtUI/QtUIFactory.h
+++ b/Swift/QtUI/QtUIFactory.h
@@ -14,70 +14,70 @@
class QSplitter;
namespace Swift {
- class QtSettingsProvider;
- class SettingsProviderHierachy;
- class QtChatTabsBase;
- class QtChatTabs;
- class QtSystemTray;
- class QtLoginWindow;
- class QtMainWindow;
- class QtChatTheme;
- class QtChatWindowFactory;
- class QtChatWindow;
- class TimerFactory;
- class historyWindow_;
- class WhiteboardSession;
- class StatusCache;
- class QtSingleWindow;
+ class QtSettingsProvider;
+ class SettingsProviderHierachy;
+ class QtChatTabsBase;
+ class QtChatTabs;
+ class QtSystemTray;
+ class QtLoginWindow;
+ class QtMainWindow;
+ class QtChatTheme;
+ class QtChatWindowFactory;
+ class QtChatWindow;
+ class TimerFactory;
+ class historyWindow_;
+ class WhiteboardSession;
+ class StatusCache;
+ class QtSingleWindow;
- class QtUIFactory : public QObject, public UIFactory {
- Q_OBJECT
- public:
- QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID);
+ class QtUIFactory : public QObject, public UIFactory {
+ Q_OBJECT
+ public:
+ QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID);
- virtual XMLConsoleWidget* createXMLConsoleWidget();
- virtual HistoryWindow* createHistoryWindow(UIEventStream*);
- virtual MainWindow* createMainWindow(UIEventStream* eventStream);
- virtual LoginWindow* createLoginWindow(UIEventStream* eventStream);
- virtual EventWindow* createEventWindow();
- virtual ChatListWindow* createChatListWindow(UIEventStream*);
- virtual MUCSearchWindow* createMUCSearchWindow();
- virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
- virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups);
- virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream);
- virtual ProfileWindow* createProfileWindow();
- virtual ContactEditWindow* createContactEditWindow();
- virtual FileTransferListWidget* createFileTransferListWidget();
- virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession);
- virtual HighlightEditorWindow* createHighlightEditorWindow();
- virtual BlockListEditorWidget* createBlockListEditorWidget();
- virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
+ virtual XMLConsoleWidget* createXMLConsoleWidget();
+ virtual HistoryWindow* createHistoryWindow(UIEventStream*);
+ virtual MainWindow* createMainWindow(UIEventStream* eventStream);
+ virtual LoginWindow* createLoginWindow(UIEventStream* eventStream);
+ virtual EventWindow* createEventWindow();
+ virtual ChatListWindow* createChatListWindow(UIEventStream*);
+ virtual MUCSearchWindow* createMUCSearchWindow();
+ virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream);
+ virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set<std::string>& groups);
+ virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream);
+ virtual ProfileWindow* createProfileWindow();
+ virtual ContactEditWindow* createContactEditWindow();
+ virtual FileTransferListWidget* createFileTransferListWidget();
+ virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr<WhiteboardSession> whiteboardSession);
+ virtual HighlightEditorWindow* createHighlightEditorWindow();
+ virtual BlockListEditorWidget* createBlockListEditorWidget();
+ virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr<OutgoingAdHocCommandSession> command);
- private slots:
- void handleLoginWindowGeometryChanged();
- void handleChatWindowFontResized(int);
- void handleHistoryWindowFontResized(int);
+ private slots:
+ void handleLoginWindowGeometryChanged();
+ void handleChatWindowFontResized(int);
+ void handleHistoryWindowFontResized(int);
- private:
- void showTabs();
+ private:
+ void showTabs();
- private:
- SettingsProviderHierachy* settings;
- QtSettingsProvider* qtOnlySettings;
- QtChatTabsBase* tabsBase;
- QtChatTabs* tabs;
- QtSingleWindow* netbookSplitter;
- QtSystemTray* systemTray;
- QtChatWindowFactory* chatWindowFactory;
- TimerFactory* timerFactory_;
- QtMainWindow* lastMainWindow;
- QtLoginWindow* loginWindow;
- StatusCache* statusCache;
- std::vector<QPointer<QtChatWindow> > chatWindows;
- bool startMinimized;
- int chatFontSize;
- int historyFontSize_;
- bool emoticonsExist_;
- bool enableAdHocCommandOnJID_;
- };
+ private:
+ SettingsProviderHierachy* settings;
+ QtSettingsProvider* qtOnlySettings;
+ QtChatTabsBase* tabsBase;
+ QtChatTabs* tabs;
+ QtSingleWindow* netbookSplitter;
+ QtSystemTray* systemTray;
+ QtChatWindowFactory* chatWindowFactory;
+ TimerFactory* timerFactory_;
+ QtMainWindow* lastMainWindow;
+ QtLoginWindow* loginWindow;
+ StatusCache* statusCache;
+ std::vector<QPointer<QtChatWindow> > chatWindows;
+ bool startMinimized;
+ int chatFontSize;
+ int historyFontSize_;
+ bool emoticonsExist_;
+ bool enableAdHocCommandOnJID_;
+ };
}
diff --git a/Swift/QtUI/QtUISettingConstants.h b/Swift/QtUI/QtUISettingConstants.h
index 4c17c0d..3e7291f 100644
--- a/Swift/QtUI/QtUISettingConstants.h
+++ b/Swift/QtUI/QtUISettingConstants.h
@@ -9,16 +9,16 @@
#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
- class QtUISettingConstants {
- public:
- static const SettingsProvider::Setting<bool> COMPACT_ROSTER;
- static const SettingsProvider::Setting<std::string> CLICKTHROUGH_BANNER;
- static const SettingsProvider::Setting<int> CURRENT_ROSTER_TAB;
- static const SettingsProvider::Setting<bool> SHOW_NICK_IN_ROSTER_HEADER;
- static const SettingsProvider::Setting<int> CHATWINDOW_FONT_SIZE;
- static const SettingsProvider::Setting<int> HISTORYWINDOW_FONT_SIZE;
- static const SettingsProvider::Setting<bool> SHOW_EMOTICONS;
- static const SettingsProvider::Setting<bool> USE_PLAIN_CHATS;
- static const SettingsProvider::Setting<bool> USE_SCREENREADER;
- };
+ class QtUISettingConstants {
+ public:
+ static const SettingsProvider::Setting<bool> COMPACT_ROSTER;
+ static const SettingsProvider::Setting<std::string> CLICKTHROUGH_BANNER;
+ static const SettingsProvider::Setting<int> CURRENT_ROSTER_TAB;
+ static const SettingsProvider::Setting<bool> SHOW_NICK_IN_ROSTER_HEADER;
+ static const SettingsProvider::Setting<int> CHATWINDOW_FONT_SIZE;
+ static const SettingsProvider::Setting<int> HISTORYWINDOW_FONT_SIZE;
+ static const SettingsProvider::Setting<bool> SHOW_EMOTICONS;
+ static const SettingsProvider::Setting<bool> USE_PLAIN_CHATS;
+ static const SettingsProvider::Setting<bool> USE_SCREENREADER;
+ };
}
diff --git a/Swift/QtUI/QtURIHandler.cpp b/Swift/QtUI/QtURIHandler.cpp
index e3b9a53..24bd328 100644
--- a/Swift/QtUI/QtURIHandler.cpp
+++ b/Swift/QtUI/QtURIHandler.cpp
@@ -15,16 +15,16 @@
using namespace Swift;
QtURIHandler::QtURIHandler() {
- qApp->installEventFilter(this);
+ qApp->installEventFilter(this);
}
bool QtURIHandler::eventFilter(QObject*, QEvent* event) {
- if (event->type() == QEvent::FileOpen) {
- QFileOpenEvent* fileOpenEvent = static_cast<QFileOpenEvent*>(event);
- if (fileOpenEvent->url().scheme() == "xmpp") {
- onURI(Q2PSTRING(fileOpenEvent->url().toString()));
- return true;
- }
- }
- return false;
+ if (event->type() == QEvent::FileOpen) {
+ QFileOpenEvent* fileOpenEvent = static_cast<QFileOpenEvent*>(event);
+ if (fileOpenEvent->url().scheme() == "xmpp") {
+ onURI(Q2PSTRING(fileOpenEvent->url().toString()));
+ return true;
+ }
+ }
+ return false;
}
diff --git a/Swift/QtUI/QtURIHandler.h b/Swift/QtUI/QtURIHandler.h
index 1abcac6..309e55b 100644
--- a/Swift/QtUI/QtURIHandler.h
+++ b/Swift/QtUI/QtURIHandler.h
@@ -13,11 +13,11 @@
class QUrl;
namespace Swift {
- class QtURIHandler : public QObject, public URIHandler {
- public:
- QtURIHandler();
+ class QtURIHandler : public QObject, public URIHandler {
+ public:
+ QtURIHandler();
- private:
- bool eventFilter(QObject* obj, QEvent* event);
- };
+ private:
+ bool eventFilter(QObject* obj, QEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtURLValidator.cpp b/Swift/QtUI/QtURLValidator.cpp
index 45bf528..8017710 100644
--- a/Swift/QtUI/QtURLValidator.cpp
+++ b/Swift/QtUI/QtURLValidator.cpp
@@ -16,10 +16,10 @@ QtURLValidator::QtURLValidator(QObject* parent) : QValidator(parent) {
}
QValidator::State QtURLValidator::validate(QString& input, int&) const {
- URL url = URL::fromString(Q2PSTRING(input));
- bool valid = !url.isEmpty();
- valid &= (url.getScheme() == "http" || url.getScheme() == "https");
- return valid ? Acceptable : Intermediate;
+ URL url = URL::fromString(Q2PSTRING(input));
+ bool valid = !url.isEmpty();
+ valid &= (url.getScheme() == "http" || url.getScheme() == "https");
+ return valid ? Acceptable : Intermediate;
}
}
diff --git a/Swift/QtUI/QtURLValidator.h b/Swift/QtUI/QtURLValidator.h
index b374ef4..887828a 100644
--- a/Swift/QtUI/QtURLValidator.h
+++ b/Swift/QtUI/QtURLValidator.h
@@ -7,11 +7,11 @@
#include <QValidator>
namespace Swift {
- class QtURLValidator : public QValidator {
- Q_OBJECT
- public:
- QtURLValidator(QObject* parent);
- virtual QValidator::State validate(QString& input, int& pos) const;
- };
+ class QtURLValidator : public QValidator {
+ Q_OBJECT
+ public:
+ QtURLValidator(QObject* parent);
+ virtual QValidator::State validate(QString& input, int& pos) const;
+ };
}
diff --git a/Swift/QtUI/QtUtilities.cpp b/Swift/QtUI/QtUtilities.cpp
index b4b1b09..401af17 100644
--- a/Swift/QtUI/QtUtilities.cpp
+++ b/Swift/QtUI/QtUtilities.cpp
@@ -22,23 +22,23 @@ namespace QtUtilities {
void setX11Resource(QWidget* widget, const QString& c) {
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC) && QT_VERSION < 0x050000
- char res_class[] = SWIFT_APPLICATION_NAME;
- XClassHint hint;
- QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8();
- hint.res_name = resName.data();
- hint.res_class = res_class;
- XSetClassHint(widget->x11Info().display(), widget->winId(), &hint);
+ char res_class[] = SWIFT_APPLICATION_NAME;
+ XClassHint hint;
+ QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8();
+ hint.res_name = resName.data();
+ hint.res_class = res_class;
+ XSetClassHint(widget->x11Info().display(), widget->winId(), &hint);
#else
- (void) widget;
- (void) c;
+ (void) widget;
+ (void) c;
#endif
}
QString htmlEscape(const QString& s) {
#if QT_VERSION >= 0x050000
- return s.toHtmlEscaped();
+ return s.toHtmlEscaped();
#else
- return Qt::escape(s);
+ return Qt::escape(s);
#endif
}
diff --git a/Swift/QtUI/QtUtilities.h b/Swift/QtUI/QtUtilities.h
index 4d71d7c..ad58499 100644
--- a/Swift/QtUI/QtUtilities.h
+++ b/Swift/QtUI/QtUtilities.h
@@ -12,11 +12,11 @@ class QString;
#include <QKeyEvent>
namespace QtUtilities {
- void setX11Resource(QWidget* widget, const QString& c);
- QString htmlEscape(const QString& s);
- #ifdef SWIFTEN_PLATFORM_MACOSX
- const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier;
- #else
- const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier;
- #endif
+ void setX11Resource(QWidget* widget, const QString& c);
+ QString htmlEscape(const QString& s);
+ #ifdef SWIFTEN_PLATFORM_MACOSX
+ const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier;
+ #else
+ const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier;
+ #endif
}
diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
index 9d79859..ec7941c 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
@@ -24,28 +24,28 @@ QtCloseButton::QtCloseButton(QWidget *parent) : QAbstractButton(parent) {
}
QSize QtCloseButton::sizeHint() const {
- return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0));
+ return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0));
}
bool QtCloseButton::event(QEvent *e) {
- if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) {
- update();
- }
- return QAbstractButton::event(e);
+ if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) {
+ update();
+ }
+ return QAbstractButton::event(e);
}
void QtCloseButton::paintEvent(QPaintEvent *) {
- QPainter painter(this);
- painter.setRenderHint(QPainter::HighQualityAntialiasing);
- QStyleOption opt;
- opt.init(this);
- opt.state |= QStyle::State_AutoRaise;
- if (underMouse() && !isDown()) {
- opt.state |= QStyle::State_Raised;
- } else if (isDown()) {
- opt.state |= QStyle::State_Sunken;
- }
- style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this);
+ QPainter painter(this);
+ painter.setRenderHint(QPainter::HighQualityAntialiasing);
+ QStyleOption opt;
+ opt.init(this);
+ opt.state |= QStyle::State_AutoRaise;
+ if (underMouse() && !isDown()) {
+ opt.state |= QStyle::State_Raised;
+ } else if (isDown()) {
+ opt.state |= QStyle::State_Sunken;
+ }
+ style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.h b/Swift/QtUI/QtVCardWidget/QtCloseButton.h
index cb92e12..1ba31a0 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.h
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.h
@@ -10,15 +10,15 @@
namespace Swift {
- class QtCloseButton : public QAbstractButton {
- Q_OBJECT
- public:
- explicit QtCloseButton(QWidget *parent = 0);
- virtual QSize sizeHint() const;
+ class QtCloseButton : public QAbstractButton {
+ Q_OBJECT
+ public:
+ explicit QtCloseButton(QWidget *parent = 0);
+ virtual QSize sizeHint() const;
- protected:
- virtual bool event(QEvent *e);
- virtual void paintEvent(QPaintEvent* );
- };
+ protected:
+ virtual bool event(QEvent *e);
+ virtual void paintEvent(QPaintEvent* );
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
index 73575f6..67c79a9 100644
--- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
@@ -24,42 +24,42 @@ QtRemovableItemDelegate::QtRemovableItemDelegate(const QStyle* style) : style(st
}
void QtRemovableItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QStyleOption opt;
- opt.state = option.state;
- opt.state |= QStyle::State_AutoRaise;
- if (option.state.testFlag(QStyle::State_MouseOver)) {
- opt.state |= QStyle::State_Raised;
- }
- opt.rect = option.rect;
- painter->save();
- painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base());
- if (index.data().toString().isEmpty()) {
+ QStyleOption opt;
+ opt.state = option.state;
+ opt.state |= QStyle::State_AutoRaise;
+ if (option.state.testFlag(QStyle::State_MouseOver)) {
+ opt.state |= QStyle::State_Raised;
+ }
+ opt.rect = option.rect;
+ painter->save();
+ painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base());
+ if (index.data().toString().isEmpty()) {
#ifdef SWIFTEN_PLATFORM_MACOSX
- // workaround for Qt not painting relative to the cell we're in, on OS X
- int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0);
- painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2);
+ // workaround for Qt not painting relative to the cell we're in, on OS X
+ int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0);
+ painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2);
#endif
- style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter);
- }
- painter->restore();
+ style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter);
+ }
+ painter->restore();
}
QWidget* QtRemovableItemDelegate::createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const {
- return NULL;
+ return NULL;
}
bool QtRemovableItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) {
- if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) {
- model->removeRow(index.row());
- return true;
- } else {
- return QItemDelegate::editorEvent(event, model, option, index);
- }
+ if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) {
+ model->removeRow(index.row());
+ return true;
+ } else {
+ return QItemDelegate::editorEvent(event, model, option, index);
+ }
}
QSize QtRemovableItemDelegate::sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const {
- QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2);
- return size;
+ QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2);
+ return size;
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
index 75137e1..ea9e0b2 100644
--- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
+++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h
@@ -11,18 +11,18 @@
namespace Swift {
class QtRemovableItemDelegate : public QItemDelegate {
- public:
- QtRemovableItemDelegate(const QStyle* style);
+ public:
+ QtRemovableItemDelegate(const QStyle* style);
- virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const;
- virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const;
- virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const;
+ virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const;
+ virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const;
+ virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const;
- protected:
- virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index);
+ protected:
+ virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index);
- private:
- const QStyle* style;
+ private:
+ const QStyle* style;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
index 3492cb9..9eef970 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
@@ -16,43 +16,43 @@
namespace Swift {
QtResizableLineEdit::QtResizableLineEdit(QWidget* parent) :
- QLineEdit(parent), editable(false) {
- connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString)));
- setMinimumWidth(30);
+ QLineEdit(parent), editable(false) {
+ connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString)));
+ setMinimumWidth(30);
}
QtResizableLineEdit::~QtResizableLineEdit() {
}
bool QtResizableLineEdit::isEditable() const {
- return editable;
+ return editable;
}
void QtResizableLineEdit::setEditable(const bool editable) {
- this->editable = editable;
- if (editable) {
- setReadOnly(false);
- } else {
- setReadOnly(true);
- }
+ this->editable = editable;
+ if (editable) {
+ setReadOnly(false);
+ } else {
+ setReadOnly(true);
+ }
}
QSize QtResizableLineEdit::sizeHint() const {
- int horizontalMargin = 10;
- int verticalMargin = 6;
- QSize textDimensions;
+ int horizontalMargin = 10;
+ int verticalMargin = 6;
+ QSize textDimensions;
#if QT_VERSION >= 0x040700
- textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size();
+ textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size();
#else
- textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size();
+ textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size();
#endif
- textDimensions.setWidth(textDimensions.width() + horizontalMargin);
- textDimensions.setHeight(textDimensions.height() + verticalMargin);
- return textDimensions;
+ textDimensions.setWidth(textDimensions.width() + horizontalMargin);
+ textDimensions.setHeight(textDimensions.height() + verticalMargin);
+ return textDimensions;
}
void QtResizableLineEdit::textChanged(QString) {
- updateGeometry();
+ updateGeometry();
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
index 9022d38..47c6f3e 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
@@ -10,24 +10,24 @@
namespace Swift {
- class QtResizableLineEdit : public QLineEdit {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ class QtResizableLineEdit : public QLineEdit {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtResizableLineEdit(QWidget* parent = 0);
- ~QtResizableLineEdit();
+ public:
+ explicit QtResizableLineEdit(QWidget* parent = 0);
+ ~QtResizableLineEdit();
- bool isEditable() const;
- void setEditable(const bool);
+ bool isEditable() const;
+ void setEditable(const bool);
- virtual QSize sizeHint() const;
+ virtual QSize sizeHint() const;
- private slots:
- void textChanged(QString);
+ private slots:
+ void textChanged(QString);
- private:
- bool editable;
- };
+ private:
+ bool editable;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
index 7036f84..ed36580 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
@@ -18,14 +18,14 @@
namespace Swift {
QtTagComboBox::QtTagComboBox(QWidget* parent) : QComboBox(parent) {
- setEditable(false);
- displayModel = new QStandardItemModel(this);
- displayItem = new QStandardItem();
- displayItem->setText("");
- displayModel->insertRow(0, displayItem);
- editMenu = new QMenu(this);
- this->setModel(displayModel);
- editable = true;
+ setEditable(false);
+ displayModel = new QStandardItemModel(this);
+ displayItem = new QStandardItem();
+ displayItem->setText("");
+ displayModel->insertRow(0, displayItem);
+ editMenu = new QMenu(this);
+ this->setModel(displayModel);
+ editable = true;
}
QtTagComboBox::~QtTagComboBox() {
@@ -33,40 +33,40 @@ QtTagComboBox::~QtTagComboBox() {
}
bool QtTagComboBox::isEditable() const {
- return editable;
+ return editable;
}
void QtTagComboBox::setEditable(const bool editable) {
- this->editable = 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);
+ 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) {
- if (action->data() == id) {
- action->setChecked(value);
- updateDisplayItem();
- return;
- }
- }
+ QList<QAction*> tagActions = editMenu->actions();
+ foreach(QAction* 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) {
- if (action->data() == id) {
- return action->isChecked();
- }
- }
- return false;
+ QList<QAction*> tagActions = editMenu->actions();
+ foreach(QAction* action, tagActions) {
+ if (action->data() == id) {
+ return action->isChecked();
+ }
+ }
+ return false;
}
void QtTagComboBox::showPopup() {
@@ -78,31 +78,31 @@ 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);
+ 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) {
- if (action->isChecked()) {
- if (text != "") {
- text += ", ";
- }
- text += action->text();
- }
- }
- setItemText(0, text);
+ QList<QAction*> tagActions = editMenu->actions();
+ QString text = "";
+ foreach(QAction* action, tagActions) {
+ if (action->isChecked()) {
+ if (text != "") {
+ text += ", ";
+ }
+ text += action->text();
+ }
+ }
+ setItemText(0, text);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
index 37a60af..f08f136 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
@@ -14,33 +14,33 @@
namespace Swift {
class QtTagComboBox : public QComboBox {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtTagComboBox(QWidget* parent = 0);
- ~QtTagComboBox();
+ public:
+ explicit QtTagComboBox(QWidget* parent = 0);
+ ~QtTagComboBox();
- bool isEditable() const;
- void setEditable(const bool);
+ bool isEditable() const;
+ void setEditable(const bool);
- void addTag(const QString& id, const QString& label);
- void setTag(const QString& id, bool value);
- bool isTagSet(const QString& id) const;
+ void addTag(const QString& id, const QString& label);
+ void setTag(const QString& id, bool value);
+ bool isTagSet(const QString& id) const;
- virtual void showPopup();
- virtual void hidePopup();
+ virtual void showPopup();
+ virtual void hidePopup();
- virtual bool event(QEvent* event);
+ virtual bool event(QEvent* event);
- private:
- void updateDisplayItem();
+ private:
+ void updateDisplayItem();
- private:
- bool editable;
- QStandardItemModel* displayModel;
- QStandardItem* displayItem;
- QMenu* editMenu;
+ private:
+ bool editable;
+ QStandardItemModel* displayModel;
+ QStandardItem* displayItem;
+ QMenu* editMenu;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
index 5f9fddf..57bb2cd 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
@@ -20,163 +20,163 @@
namespace Swift {
QtVCardAddressField::QtVCardAddressField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardAddressField::~QtVCardAddressField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardAddressField::setupContentWidgets() {
- textFieldGridLayout = new QGridLayout();
+ textFieldGridLayout = new QGridLayout();
- streetLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter);
+ streetLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter);
- poboxLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter);
+ poboxLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter);
- addressextLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter);
+ addressextLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter);
- cityLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter);
+ cityLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter);
- pocodeLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter);
+ pocodeLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter);
- regionLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter);
+ regionLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter);
- countryLineEdit = new QtResizableLineEdit(this);
- textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter);
- textFieldGridLayout->setVerticalSpacing(2);
- getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter);
- textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2);
+ countryLineEdit = new QtResizableLineEdit(this);
+ textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter);
+ textFieldGridLayout->setVerticalSpacing(2);
+ getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter);
+ textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2);
#if QT_VERSION >= 0x040700
- streetLineEdit->setPlaceholderText(tr("Street"));
- poboxLineEdit->setPlaceholderText(tr("PO Box"));
- addressextLineEdit->setPlaceholderText(tr("Address Extension"));
- cityLineEdit->setPlaceholderText(tr("City"));
- pocodeLineEdit->setPlaceholderText(tr("Postal Code"));
- regionLineEdit->setPlaceholderText(tr("Region"));
- countryLineEdit->setPlaceholderText(tr("Country"));
+ streetLineEdit->setPlaceholderText(tr("Street"));
+ poboxLineEdit->setPlaceholderText(tr("PO Box"));
+ addressextLineEdit->setPlaceholderText(tr("Address Extension"));
+ cityLineEdit->setPlaceholderText(tr("City"));
+ 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);
+ 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);
+ 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);
+ 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);
+ buttonGroup = new QButtonGroup(this);
+ buttonGroup->addButton(domesticRadioButton);
+ buttonGroup->addButton(internationalRadioButton);
- setTabOrder(internationalRadioButton, getTagComboBox());
- getTagComboBox()->addTag("postal", tr("Postal"));
- getTagComboBox()->addTag("parcel", tr("Parcel"));
+ setTabOrder(internationalRadioButton, getTagComboBox());
+ getTagComboBox()->addTag("postal", tr("Postal"));
+ getTagComboBox()->addTag("parcel", tr("Parcel"));
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
- textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit;
- childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
+ textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit;
+ childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
}
void QtVCardAddressField::customCleanup() {
- foreach(QWidget* widget, textFields) {
- widget->hide();
- textFieldGridLayout->removeWidget(widget);
- }
- getGridLayout()->removeItem(textFieldGridLayoutItem);
+ foreach(QWidget* 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();
+ 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));
- pocodeLineEdit->setText(P2QSTRING(address.postalCode));
- regionLineEdit->setText(P2QSTRING(address.region));
- countryLineEdit->setText(P2QSTRING(address.country));
+ 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));
+ pocodeLineEdit->setText(P2QSTRING(address.postalCode));
+ regionLineEdit->setText(P2QSTRING(address.region));
+ countryLineEdit->setText(P2QSTRING(address.country));
}
VCard::Address QtVCardAddressField::getAddress() const {
- VCard::Address address;
- address.isPreferred = getPreferred();
- address.isHome = getHome();
- address.isWork = getWork();
- address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
- address.isPostal = getTagComboBox()->isTagSet("postal");
- address.isParcel = getTagComboBox()->isTagSet("parcel");
- address.street = Q2PSTRING(streetLineEdit->text());
- address.poBox = Q2PSTRING(poboxLineEdit->text());
- address.addressExtension = Q2PSTRING(addressextLineEdit->text());
- address.locality = Q2PSTRING(cityLineEdit->text());
- address.postalCode = Q2PSTRING(pocodeLineEdit->text());
- address.region = Q2PSTRING(regionLineEdit->text());
- address.country = Q2PSTRING(countryLineEdit->text());
- return address;
+ VCard::Address address;
+ address.isPreferred = getPreferred();
+ address.isHome = getHome();
+ address.isWork = getWork();
+ address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
+ address.isPostal = getTagComboBox()->isTagSet("postal");
+ address.isParcel = getTagComboBox()->isTagSet("parcel");
+ address.street = Q2PSTRING(streetLineEdit->text());
+ address.poBox = Q2PSTRING(poboxLineEdit->text());
+ address.addressExtension = Q2PSTRING(addressextLineEdit->text());
+ address.locality = Q2PSTRING(cityLineEdit->text());
+ address.postalCode = Q2PSTRING(pocodeLineEdit->text());
+ address.region = Q2PSTRING(regionLineEdit->text());
+ 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() == 0 ? "" : buttonGroup->checkedButton()->text());
- deliveryTypeLabel->setVisible(!isEditable);
-
- domesticRadioButton->setVisible(isEditable);
- internationalRadioButton->setVisible(isEditable);
-
- foreach (QWidget* 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; }");
- }
- }
+ 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() == 0 ? "" : buttonGroup->checkedButton()->text());
+ deliveryTypeLabel->setVisible(!isEditable);
+
+ domesticRadioButton->setVisible(isEditable);
+ internationalRadioButton->setVisible(isEditable);
+
+ foreach (QWidget* 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/QtVCardAddressField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
index 51bc323..c90628a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
@@ -27,42 +27,42 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
-
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField)
-
- QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardAddressField();
-
- virtual bool isEmpty() const;
-
- void setAddress(const VCard::Address& address);
- VCard::Address getAddress() const;
-
- protected:
- virtual void setupContentWidgets();
- virtual void customCleanup();
-
- public slots:
- void handleEditibleChanged(bool isEditable);
-
- private:
- QList<QWidget*> textFields;
- QtResizableLineEdit* streetLineEdit;
- QtResizableLineEdit* poboxLineEdit;
- QtResizableLineEdit* addressextLineEdit;
- QtResizableLineEdit* cityLineEdit;
- QtResizableLineEdit* pocodeLineEdit;
- QtResizableLineEdit* regionLineEdit;
- QtResizableLineEdit* countryLineEdit;
- QGridLayout* textFieldGridLayout;
- QLayoutItem* textFieldGridLayoutItem;
-
- QtElidingLabel* deliveryTypeLabel;
- QRadioButton* domesticRadioButton;
- QRadioButton* internationalRadioButton;
- QButtonGroup* buttonGroup;
+ Q_OBJECT
+
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField)
+
+ QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardAddressField();
+
+ virtual bool isEmpty() const;
+
+ void setAddress(const VCard::Address& address);
+ VCard::Address getAddress() const;
+
+ protected:
+ virtual void setupContentWidgets();
+ virtual void customCleanup();
+
+ public slots:
+ void handleEditibleChanged(bool isEditable);
+
+ private:
+ QList<QWidget*> textFields;
+ QtResizableLineEdit* streetLineEdit;
+ QtResizableLineEdit* poboxLineEdit;
+ QtResizableLineEdit* addressextLineEdit;
+ QtResizableLineEdit* cityLineEdit;
+ QtResizableLineEdit* pocodeLineEdit;
+ QtResizableLineEdit* regionLineEdit;
+ QtResizableLineEdit* countryLineEdit;
+ QGridLayout* textFieldGridLayout;
+ QLayoutItem* textFieldGridLayoutItem;
+
+ QtElidingLabel* deliveryTypeLabel;
+ QRadioButton* domesticRadioButton;
+ QRadioButton* internationalRadioButton;
+ QButtonGroup* buttonGroup;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
index 64d2533..7f270c5 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
@@ -22,86 +22,86 @@
namespace Swift {
QtVCardAddressLabelField::QtVCardAddressLabelField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardAddressLabelField::~QtVCardAddressLabelField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardAddressLabelField::setupContentWidgets() {
- addressLabelPlainTextEdit = new QPlainTextEdit(this);
- addressLabelPlainTextEdit->setTabChangesFocus(true);
- getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter);
+ addressLabelPlainTextEdit = new QPlainTextEdit(this);
+ addressLabelPlainTextEdit->setTabChangesFocus(true);
+ getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter);
- deliveryTypeLabel = new QtElidingLabel(this);
- deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
+ deliveryTypeLabel = new QtElidingLabel(this);
+ deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter);
- domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this);
- getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 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);
+ 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);
+ buttonGroup = new QButtonGroup(this);
+ buttonGroup->addButton(domesticRadioButton);
+ buttonGroup->addButton(internationalRadioButton);
- setTabOrder(internationalRadioButton, getTagComboBox());
- getTagComboBox()->addTag("postal", tr("Postal"));
- getTagComboBox()->addTag("parcel", tr("Parcel"));
+ setTabOrder(internationalRadioButton, getTagComboBox());
+ getTagComboBox()->addTag("postal", tr("Postal"));
+ getTagComboBox()->addTag("parcel", tr("Parcel"));
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
- deliveryTypeLabel->hide();
- childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ deliveryTypeLabel->hide();
+ childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton;
}
bool QtVCardAddressLabelField::isEmpty() const {
- return addressLabelPlainTextEdit->toPlainText().isEmpty();
+ return addressLabelPlainTextEdit->toPlainText().isEmpty();
}
void QtVCardAddressLabelField::setAddressLabel(const VCard::AddressLabel& addressLabel) {
- setPreferred(addressLabel.isPreferred);
- setHome(addressLabel.isHome);
- setWork(addressLabel.isWork);
- getTagComboBox()->setTag("postal", addressLabel.isPostal);
- getTagComboBox()->setTag("parcel", addressLabel.isParcel);
- domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery);
- internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery);
- std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n");
- addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines));
+ setPreferred(addressLabel.isPreferred);
+ setHome(addressLabel.isHome);
+ setWork(addressLabel.isWork);
+ getTagComboBox()->setTag("postal", addressLabel.isPostal);
+ getTagComboBox()->setTag("parcel", addressLabel.isParcel);
+ domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery);
+ internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery);
+ std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n");
+ addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines));
}
VCard::AddressLabel QtVCardAddressLabelField::getAddressLabel() const {
- VCard::AddressLabel addressLabel;
- addressLabel.isPreferred = getPreferred();
- addressLabel.isHome = getHome();
- addressLabel.isWork = getWork();
- addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
- addressLabel.isPostal = getTagComboBox()->isTagSet("postal");
- addressLabel.isParcel = getTagComboBox()->isTagSet("parcel");
-
- std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText());
- boost::split(addressLabel.lines, lines, boost::is_any_of("\n"));
- return addressLabel;
+ VCard::AddressLabel addressLabel;
+ addressLabel.isPreferred = getPreferred();
+ addressLabel.isHome = getHome();
+ addressLabel.isWork = getWork();
+ addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None);
+ addressLabel.isPostal = getTagComboBox()->isTagSet("postal");
+ addressLabel.isParcel = getTagComboBox()->isTagSet("parcel");
+
+ std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText());
+ boost::split(addressLabel.lines, lines, boost::is_any_of("\n"));
+ return addressLabel;
}
void QtVCardAddressLabelField::handleEditibleChanged(bool isEditable) {
- assert(addressLabelPlainTextEdit);
- assert(deliveryTypeLabel);
- assert(domesticRadioButton);
- assert(internationalRadioButton);
+ assert(addressLabelPlainTextEdit);
+ assert(deliveryTypeLabel);
+ assert(domesticRadioButton);
+ assert(internationalRadioButton);
- addressLabelPlainTextEdit->setReadOnly(!isEditable);
- addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
+ addressLabelPlainTextEdit->setReadOnly(!isEditable);
+ addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
- deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
- deliveryTypeLabel->setVisible(!isEditable);
+ deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text());
+ deliveryTypeLabel->setVisible(!isEditable);
- domesticRadioButton->setVisible(isEditable);
- internationalRadioButton->setVisible(isEditable);
+ domesticRadioButton->setVisible(isEditable);
+ internationalRadioButton->setVisible(isEditable);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
index f59e482..16910b3 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
@@ -27,32 +27,32 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressLabelField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField)
- QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardAddressLabelField();
+ QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardAddressLabelField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setAddressLabel(const VCard::AddressLabel& addressLabel);
- VCard::AddressLabel getAddressLabel() const;
+ void setAddressLabel(const VCard::AddressLabel& addressLabel);
+ VCard::AddressLabel getAddressLabel() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QPlainTextEdit* addressLabelPlainTextEdit;
+ private:
+ QPlainTextEdit* addressLabelPlainTextEdit;
- QtElidingLabel* deliveryTypeLabel;
- QRadioButton* domesticRadioButton;
- QRadioButton* internationalRadioButton;
- QButtonGroup* buttonGroup;
+ QtElidingLabel* deliveryTypeLabel;
+ QRadioButton* domesticRadioButton;
+ QRadioButton* internationalRadioButton;
+ QButtonGroup* buttonGroup;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
index 603b8be..53dfc7f 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
@@ -22,47 +22,47 @@
namespace Swift {
QtVCardBirthdayField::QtVCardBirthdayField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardBirthdayField::~QtVCardBirthdayField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardBirthdayField::setupContentWidgets() {
- birthdayLabel = new QLabel(this);
- birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- birthdayDateEdit = new QDateEdit(this);
- birthdayDateEdit->setCalendarPopup(true);
+ birthdayLabel = new QLabel(this);
+ birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ birthdayDateEdit = new QDateEdit(this);
+ birthdayDateEdit->setCalendarPopup(true);
- QHBoxLayout* birthdayLayout = new QHBoxLayout();
- birthdayLayout->addWidget(birthdayLabel);
- birthdayLayout->addWidget(birthdayDateEdit);
+ QHBoxLayout* birthdayLayout = new QHBoxLayout();
+ birthdayLayout->addWidget(birthdayLabel);
+ birthdayLayout->addWidget(birthdayDateEdit);
- getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter);
+ getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- birthdayLabel->hide();
- childWidgets << birthdayLabel << birthdayDateEdit;
+ getTagComboBox()->hide();
+ birthdayLabel->hide();
+ childWidgets << birthdayLabel << birthdayDateEdit;
}
bool QtVCardBirthdayField::isEmpty() const {
- return false;
+ return false;
}
void QtVCardBirthdayField::setBirthday(const boost::posix_time::ptime& birthday) {
- birthdayDateEdit->setDate(B2QDATE(birthday).date());
+ birthdayDateEdit->setDate(B2QDATE(birthday).date());
}
boost::posix_time::ptime QtVCardBirthdayField::getBirthday() const {
- return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t());
+ return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t());
}
void QtVCardBirthdayField::handleEditibleChanged(bool isEditable) {
- birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate));
- birthdayDateEdit->setVisible(isEditable);
- birthdayLabel->setVisible(!isEditable);
+ birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate));
+ birthdayDateEdit->setVisible(isEditable);
+ birthdayLabel->setVisible(!isEditable);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
index bf15a75..431751e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
@@ -23,28 +23,28 @@
namespace Swift {
class QtVCardBirthdayField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField)
- QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardBirthdayField();
+ QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardBirthdayField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setBirthday(const boost::posix_time::ptime& addressLabel);
- boost::posix_time::ptime getBirthday() const;
+ void setBirthday(const boost::posix_time::ptime& addressLabel);
+ boost::posix_time::ptime getBirthday() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* birthdayLabel;
- QDateEdit* birthdayDateEdit;
+ private:
+ QLabel* birthdayLabel;
+ QDateEdit* birthdayDateEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
index f3c4dbf..9926262 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
@@ -22,50 +22,50 @@
namespace Swift {
QtVCardDescriptionField::QtVCardDescriptionField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardDescriptionField::~QtVCardDescriptionField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardDescriptionField::setupContentWidgets() {
- descriptionPlainTextEdit = new QPlainTextEdit(this);
- descriptionPlainTextEdit->setMinimumHeight(70);
- getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << descriptionPlainTextEdit;
+ descriptionPlainTextEdit = new QPlainTextEdit(this);
+ descriptionPlainTextEdit->setMinimumHeight(70);
+ getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << descriptionPlainTextEdit;
}
bool QtVCardDescriptionField::isEmpty() const {
- return descriptionPlainTextEdit->toPlainText().isEmpty();
+ return descriptionPlainTextEdit->toPlainText().isEmpty();
}
void QtVCardDescriptionField::setDescription(const std::string& description) {
- descriptionPlainTextEdit->setPlainText(P2QSTRING(description));
+ descriptionPlainTextEdit->setPlainText(P2QSTRING(description));
}
std::string QtVCardDescriptionField::getDescription() const {
- return Q2PSTRING(descriptionPlainTextEdit->toPlainText());
+ return Q2PSTRING(descriptionPlainTextEdit->toPlainText());
}
void QtVCardDescriptionField::handleEditibleChanged(bool isEditable) {
- assert(descriptionPlainTextEdit);
+ assert(descriptionPlainTextEdit);
- if (isEditable) {
- descriptionPlainTextEdit->setMinimumHeight(70);
- } else {
- QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont());
- QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999);
- QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A");
- int left, top, right, bottom;
- getContentsMargins(&left, &top, &right, &bottom);
- int height = boundingRect.height() + top + bottom + inputMetrics.height();
- descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height);
- }
- descriptionPlainTextEdit->setReadOnly(!isEditable);
- descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
+ if (isEditable) {
+ descriptionPlainTextEdit->setMinimumHeight(70);
+ } else {
+ QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont());
+ QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999);
+ QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A");
+ int left, top, right, bottom;
+ getContentsMargins(&left, &top, &right, &bottom);
+ int height = boundingRect.height() + top + bottom + inputMetrics.height();
+ descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height);
+ }
+ descriptionPlainTextEdit->setReadOnly(!isEditable);
+ descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
index 8fb6344..489797a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
@@ -22,27 +22,27 @@
namespace Swift {
class QtVCardDescriptionField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField)
- QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardDescriptionField();
+ QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardDescriptionField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setDescription(const std::string& description);
- std::string getDescription() const;
+ void setDescription(const std::string& description);
+ std::string getDescription() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QPlainTextEdit* descriptionPlainTextEdit;
+ private:
+ QPlainTextEdit* descriptionPlainTextEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
index 12f990a..093357a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
@@ -18,41 +18,41 @@
#include <QObject>
#include <QString>
#define GENERIC_QT_VCARD_FIELD_INFO(MENU_NAME, ALLOWED_INSTANCES, FIELD_CLASS) \
- class FieldInfo : public QtVCardFieldInfo { \
- public: \
- virtual ~FieldInfo() { \
- } \
- \
- virtual QString getMenuName() const { \
- return MENU_NAME; \
- } \
- \
- virtual int getAllowedInstances() const { \
- return ALLOWED_INSTANCES; \
- } \
- \
- virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \
- return new FIELD_CLASS(parent, layout, editable); \
- } \
- \
- virtual bool testInstance(QWidget* widget) const { \
- return dynamic_cast<FIELD_CLASS*>(widget) != 0; \
- } \
- };
+ class FieldInfo : public QtVCardFieldInfo { \
+ public: \
+ virtual ~FieldInfo() { \
+ } \
+ \
+ virtual QString getMenuName() const { \
+ return MENU_NAME; \
+ } \
+ \
+ virtual int getAllowedInstances() const { \
+ return ALLOWED_INSTANCES; \
+ } \
+ \
+ virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \
+ return new FIELD_CLASS(parent, layout, editable); \
+ } \
+ \
+ virtual bool testInstance(QWidget* widget) const { \
+ return dynamic_cast<FIELD_CLASS*>(widget) != 0; \
+ } \
+ };
class QWidget;
namespace Swift {
- class QtVCardFieldInfo {
- public:
- static const int UNLIMITED_INSTANCES = -1;
-
- virtual ~QtVCardFieldInfo() {
- }
- virtual QString getMenuName() const = 0;
- virtual int getAllowedInstances() const = 0;
- virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0;
- virtual bool testInstance(QWidget*) const = 0;
- };
+ class QtVCardFieldInfo {
+ public:
+ static const int UNLIMITED_INSTANCES = -1;
+
+ virtual ~QtVCardFieldInfo() {
+ }
+ virtual QString getMenuName() const = 0;
+ virtual int getAllowedInstances() const = 0;
+ virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0;
+ virtual bool testInstance(QWidget*) const = 0;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
index ed30ae1..44d94d7 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp
@@ -22,8 +22,8 @@
namespace Swift {
QtVCardGeneralField::QtVCardGeneralField(QWidget* parent, QGridLayout* layout, bool editable, int row, QString label, bool preferrable, bool taggable) :
- QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label),
- tagComboBox(0), tagLabel(NULL), closeButton(0) {
+ QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label),
+ tagComboBox(0), tagLabel(NULL), closeButton(0) {
}
QtVCardGeneralField::~QtVCardGeneralField() {
@@ -31,126 +31,126 @@ QtVCardGeneralField::~QtVCardGeneralField() {
}
void QtVCardGeneralField::initialize() {
- if (preferrable) {
- preferredCheckBox = new QCheckBox(this);
- preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details."));
- preferredCheckBox->setStyleSheet(
- "QCheckBox::indicator { width: 18px; height: 18px; }"
- "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }"
- "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }"
- );
- layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter);
- childWidgets << preferredCheckBox;
- connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int)));
- }
- label = new QLabel(this);
- label->setText(labelText);
- layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight);
-
- tagLabel = new QtElidingLabel(this);
- tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
-
- tagComboBox = new QtTagComboBox(this);
- closeButton = new QtCloseButton(this);
- connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked()));
-
- QHBoxLayout* tagLayout = new QHBoxLayout();
- tagLayout->addWidget(tagLabel);
- tagLayout->addWidget(tagComboBox);
-
- setupContentWidgets();
- layout->addLayout(tagLayout, row, 4, Qt::AlignTop);
- layout->addWidget(closeButton, row, 5, Qt::AlignCenter);
- closeButton->resize(12, 12);
- tagLabel->hide();
-
- childWidgets << label << tagComboBox << tagLabel << closeButton;
- setEditable(editable);
+ if (preferrable) {
+ preferredCheckBox = new QCheckBox(this);
+ preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details."));
+ preferredCheckBox->setStyleSheet(
+ "QCheckBox::indicator { width: 18px; height: 18px; }"
+ "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }"
+ "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }"
+ );
+ layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter);
+ childWidgets << preferredCheckBox;
+ connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int)));
+ }
+ label = new QLabel(this);
+ label->setText(labelText);
+ layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight);
+
+ tagLabel = new QtElidingLabel(this);
+ tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+
+ tagComboBox = new QtTagComboBox(this);
+ closeButton = new QtCloseButton(this);
+ connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked()));
+
+ QHBoxLayout* tagLayout = new QHBoxLayout();
+ tagLayout->addWidget(tagLabel);
+ tagLayout->addWidget(tagComboBox);
+
+ setupContentWidgets();
+ layout->addLayout(tagLayout, row, 4, Qt::AlignTop);
+ layout->addWidget(closeButton, row, 5, Qt::AlignCenter);
+ closeButton->resize(12, 12);
+ tagLabel->hide();
+
+ childWidgets << label << tagComboBox << tagLabel << closeButton;
+ setEditable(editable);
}
bool QtVCardGeneralField::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardGeneralField::setEditable(bool editable) {
- assert(tagComboBox);
- assert(closeButton);
-
- this->editable = editable;
- if (taggable) {
- tagLabel->setText(tagComboBox->itemText(0));
- tagComboBox->setVisible(editable);
- tagLabel->setVisible(!editable);
- } else {
- tagLabel->hide();
- tagComboBox->hide();
- }
- closeButton->setVisible(editable);
- updatePreferredStarVisibility();
- editableChanged(this->editable);
+ assert(tagComboBox);
+ assert(closeButton);
+
+ this->editable = editable;
+ if (taggable) {
+ tagLabel->setText(tagComboBox->itemText(0));
+ tagComboBox->setVisible(editable);
+ tagLabel->setVisible(!editable);
+ } else {
+ tagLabel->hide();
+ tagComboBox->hide();
+ }
+ closeButton->setVisible(editable);
+ updatePreferredStarVisibility();
+ editableChanged(this->editable);
}
void QtVCardGeneralField::setStarVisible(const bool isVisible) {
- starVisible = isVisible;
- updatePreferredStarVisibility();
+ starVisible = isVisible;
+ updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getStarVisible() const {
- return starVisible;
+ return starVisible;
}
void QtVCardGeneralField::setPreferred(const bool preferred) {
- if (preferredCheckBox) preferredCheckBox->setChecked(preferred);
- updatePreferredStarVisibility();
+ if (preferredCheckBox) preferredCheckBox->setChecked(preferred);
+ updatePreferredStarVisibility();
}
bool QtVCardGeneralField::getPreferred() const {
- return preferredCheckBox ? preferredCheckBox->isChecked() : false;
+ return preferredCheckBox ? preferredCheckBox->isChecked() : false;
}
void QtVCardGeneralField::customCleanup() {
}
QtTagComboBox* QtVCardGeneralField::getTagComboBox() const {
- return tagComboBox;
+ return tagComboBox;
}
QGridLayout* QtVCardGeneralField::getGridLayout() const {
- return layout;
+ return layout;
}
void QtVCardGeneralField::handleCloseButtonClicked() {
- customCleanup();
- foreach(QWidget* widget, childWidgets) {
- widget->hide();
- layout->removeWidget(widget);
- }
- deleteField(this);
+ customCleanup();
+ foreach(QWidget* 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));
- }
+ 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);
- }
+ 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/QtVCardGeneralField.h b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
index 6583d12..d907196 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
@@ -25,69 +25,69 @@ namespace Swift {
class QtElidingLabel;
/*
- * covers features like:
- * - preffered (star ceckbox)
- * - combo check box
- * - label
- * - remove button
+ * covers features like:
+ * - preffered (star ceckbox)
+ * - combo check box
+ * - label
+ * - remove button
*/
class QtVCardGeneralField : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged)
- Q_PROPERTY(bool empty READ isEmpty)
-
- public:
- explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(),
- bool preferrable = true, bool taggable = true);
- virtual ~QtVCardGeneralField();
-
- void initialize();
-
- virtual bool isEditable() const;
- virtual void setEditable(bool);
-
- virtual bool isEmpty() const = 0;
-
- void setStarVisible(const bool isVisible);
- bool getStarVisible() const;
-
- void setPreferred(const bool preferred);
- bool getPreferred() const;
-
- protected:
- virtual void setupContentWidgets() = 0;
- virtual void customCleanup();
-
- QtTagComboBox* getTagComboBox() const;
- QGridLayout* getGridLayout() const;
-
- signals:
- void editableChanged(bool);
- void deleteField(QtVCardGeneralField*);
-
- public slots:
- void handleCloseButtonClicked();
- void handlePreferredStarStateChanged(int statte);
-
- protected:
- QList<QWidget*> childWidgets;
-
- private:
- void updatePreferredStarVisibility();
-
- private:
- bool editable;
- bool preferrable;
- bool starVisible;
- bool taggable;
- QGridLayout* layout;
- int row;
- QCheckBox* preferredCheckBox;
- QLabel* label;
- QString labelText;
- QtTagComboBox* tagComboBox;
- QtElidingLabel* tagLabel;
- QtCloseButton* closeButton;
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged)
+ Q_PROPERTY(bool empty READ isEmpty)
+
+ public:
+ explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(),
+ bool preferrable = true, bool taggable = true);
+ virtual ~QtVCardGeneralField();
+
+ void initialize();
+
+ virtual bool isEditable() const;
+ virtual void setEditable(bool);
+
+ virtual bool isEmpty() const = 0;
+
+ void setStarVisible(const bool isVisible);
+ bool getStarVisible() const;
+
+ void setPreferred(const bool preferred);
+ bool getPreferred() const;
+
+ protected:
+ virtual void setupContentWidgets() = 0;
+ virtual void customCleanup();
+
+ QtTagComboBox* getTagComboBox() const;
+ QGridLayout* getGridLayout() const;
+
+ signals:
+ void editableChanged(bool);
+ void deleteField(QtVCardGeneralField*);
+
+ public slots:
+ void handleCloseButtonClicked();
+ void handlePreferredStarStateChanged(int statte);
+
+ protected:
+ QList<QWidget*> childWidgets;
+
+ private:
+ void updatePreferredStarVisibility();
+
+ private:
+ bool editable;
+ bool preferrable;
+ bool starVisible;
+ bool taggable;
+ QGridLayout* layout;
+ int row;
+ QCheckBox* preferredCheckBox;
+ QLabel* label;
+ QString labelText;
+ QtTagComboBox* tagComboBox;
+ QtElidingLabel* tagLabel;
+ QtCloseButton* closeButton;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
index 3be6901..c147c68 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
@@ -21,25 +21,25 @@ QtVCardHomeWork::~QtVCardHomeWork() {
}
void QtVCardHomeWork::setTagComboBox(QtTagComboBox* tagBox) {
- tagComboBox = tagBox;
- tagComboBox->addTag("home", QObject::tr("Home"));
- tagComboBox->addTag("work", QObject::tr("Work"));
+ tagComboBox = tagBox;
+ tagComboBox->addTag("home", QObject::tr("Home"));
+ tagComboBox->addTag("work", QObject::tr("Work"));
}
void QtVCardHomeWork::setHome(const bool home) {
- tagComboBox->setTag("home", home);
+ tagComboBox->setTag("home", home);
}
bool QtVCardHomeWork::getHome() const {
- return tagComboBox->isTagSet("home");
+ return tagComboBox->isTagSet("home");
}
void QtVCardHomeWork::setWork(const bool work) {
- tagComboBox->setTag("work", work);
+ tagComboBox->setTag("work", work);
}
bool QtVCardHomeWork::getWork() const {
- return tagComboBox->isTagSet("work");
+ return tagComboBox->isTagSet("work");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
index aea2ff2..dd1452a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
@@ -19,19 +19,19 @@
namespace Swift {
class QtVCardHomeWork {
- public:
- QtVCardHomeWork();
- virtual ~QtVCardHomeWork();
+ public:
+ QtVCardHomeWork();
+ virtual ~QtVCardHomeWork();
- void setTagComboBox(QtTagComboBox* tagBox);
+ void setTagComboBox(QtTagComboBox* tagBox);
- void setHome(const bool home);
- bool getHome() const;
- void setWork(const bool work);
- bool getWork() const;
+ void setHome(const bool home);
+ bool getHome() const;
+ void setWork(const bool work);
+ bool getWork() const;
- private:
- QtTagComboBox* tagComboBox;
+ private:
+ QtTagComboBox* tagComboBox;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
index 9be9737..e563ca2 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
@@ -24,66 +24,66 @@
namespace Swift {
QtVCardInternetEMailField::QtVCardInternetEMailField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardInternetEMailField::~QtVCardInternetEMailField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardInternetEMailField::setupContentWidgets() {
- emailLabel = new QLabel(this);
- emailLabel->setOpenExternalLinks(true);
- emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- emailLineEdit = new QtResizableLineEdit(this);
+ emailLabel = new QLabel(this);
+ emailLabel->setOpenExternalLinks(true);
+ emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ emailLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
+ emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- QHBoxLayout* emailLayout = new QHBoxLayout();
- emailLayout->addWidget(emailLabel);
- emailLayout->addWidget(emailLineEdit);
- getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- setTabOrder(emailLineEdit, getTagComboBox());
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
- emailLabel->hide();
- childWidgets << emailLabel << emailLineEdit;
+ QHBoxLayout* emailLayout = new QHBoxLayout();
+ emailLayout->addWidget(emailLabel);
+ emailLayout->addWidget(emailLineEdit);
+ getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ setTabOrder(emailLineEdit, getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+ emailLabel->hide();
+ childWidgets << emailLabel << emailLineEdit;
}
bool QtVCardInternetEMailField::isEmpty() const {
- return emailLineEdit->text().isEmpty();
+ return emailLineEdit->text().isEmpty();
}
void QtVCardInternetEMailField::setInternetEMailAddress(const VCard::EMailAddress& address) {
- assert(address.isInternet);
- setPreferred(address.isPreferred);
- setHome(address.isHome);
- setWork(address.isWork);
- emailLineEdit->setText(P2QSTRING(address.address));
+ assert(address.isInternet);
+ setPreferred(address.isPreferred);
+ setHome(address.isHome);
+ setWork(address.isWork);
+ emailLineEdit->setText(P2QSTRING(address.address));
}
VCard::EMailAddress QtVCardInternetEMailField::getInternetEMailAddress() const {
- VCard::EMailAddress address;
- address.isInternet = true;
- address.isPreferred = getPreferred();
- address.isHome = getHome();
- address.isWork = getWork();
- address.address = Q2PSTRING(emailLineEdit->text());
- return address;
+ VCard::EMailAddress address;
+ address.isInternet = true;
+ address.isPreferred = getPreferred();
+ address.isHome = getHome();
+ address.isWork = getWork();
+ address.address = Q2PSTRING(emailLineEdit->text());
+ return address;
}
void QtVCardInternetEMailField::handleEditibleChanged(bool isEditable) {
- assert(emailLineEdit);
- assert(emailLabel);
+ assert(emailLineEdit);
+ assert(emailLabel);
- if (isEditable) {
- emailLineEdit->show();
- emailLabel->hide();
- } else {
- emailLineEdit->hide();
- emailLabel->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(QtUtilities::htmlEscape(emailLineEdit->text())));
- emailLabel->show();
- }
+ if (isEditable) {
+ emailLineEdit->show();
+ emailLabel->hide();
+ } else {
+ emailLineEdit->hide();
+ emailLabel->setText(QString("<a href=\"mailto:%1\">%1</a>").arg(QtUtilities::htmlEscape(emailLineEdit->text())));
+ emailLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
index e3a5d79..63a83e2 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
@@ -22,28 +22,28 @@
namespace Swift {
class QtVCardInternetEMailField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField)
- QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardInternetEMailField();
+ QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardInternetEMailField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setInternetEMailAddress(const VCard::EMailAddress& address);
- VCard::EMailAddress getInternetEMailAddress() const;
+ void setInternetEMailAddress(const VCard::EMailAddress& address);
+ VCard::EMailAddress getInternetEMailAddress() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* emailLineEdit;
- QLabel* emailLabel;
+ private:
+ QtResizableLineEdit* emailLineEdit;
+ QLabel* emailLabel;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
index 4c23036..705ad6b 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
@@ -23,58 +23,58 @@
namespace Swift {
QtVCardJIDField::QtVCardJIDField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardJIDField::~QtVCardJIDField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardJIDField::setupContentWidgets() {
- jidLabel = new QLabel(this);
- jidLabel->setOpenExternalLinks(true);
- jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- jidLineEdit = new QtResizableLineEdit(this);
+ jidLabel = new QLabel(this);
+ jidLabel->setOpenExternalLinks(true);
+ jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ jidLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
+ jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- QHBoxLayout* jidLayout = new QHBoxLayout();
- jidLayout->addWidget(jidLabel);
- jidLayout->addWidget(jidLineEdit);
- getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ QHBoxLayout* jidLayout = new QHBoxLayout();
+ jidLayout->addWidget(jidLabel);
+ jidLayout->addWidget(jidLineEdit);
+ getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- jidLabel->hide();
- getTagComboBox()->hide();
+ jidLabel->hide();
+ getTagComboBox()->hide();
- childWidgets << jidLabel << jidLineEdit;
+ childWidgets << jidLabel << jidLineEdit;
}
bool QtVCardJIDField::isEmpty() const {
- return jidLineEdit->text().isEmpty();
+ return jidLineEdit->text().isEmpty();
}
void QtVCardJIDField::setJID(const JID& jid) {
- std::string jidStr = jid.toBare().toString();
- jidLineEdit->setText(P2QSTRING(jidStr));
+ std::string jidStr = jid.toBare().toString();
+ jidLineEdit->setText(P2QSTRING(jidStr));
}
JID QtVCardJIDField::getJID() const {
- return JID(Q2PSTRING(jidLineEdit->text()));
+ return JID(Q2PSTRING(jidLineEdit->text()));
}
void QtVCardJIDField::handleEditibleChanged(bool isEditable) {
- assert(jidLineEdit);
- assert(jidLabel);
-
- if (isEditable) {
- jidLineEdit->show();
- jidLabel->hide();
- } else {
- jidLineEdit->hide();
- jidLabel->setText(QString("<a href=\"xmpp:%1\">%1</a>").arg(QtUtilities::htmlEscape(jidLineEdit->text())));
- jidLabel->show();
- }
+ assert(jidLineEdit);
+ assert(jidLabel);
+
+ if (isEditable) {
+ jidLineEdit->show();
+ jidLabel->hide();
+ } else {
+ jidLineEdit->hide();
+ jidLabel->setText(QString("<a href=\"xmpp:%1\">%1</a>").arg(QtUtilities::htmlEscape(jidLineEdit->text())));
+ jidLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
index 4e75885..2e9b4ef 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
@@ -21,28 +21,28 @@
namespace Swift {
class QtVCardJIDField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField)
- QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardJIDField();
+ QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardJIDField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setJID(const JID& jid);
- JID getJID() const;
+ void setJID(const JID& jid);
+ JID getJID() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* jidLabel;
- QtResizableLineEdit* jidLineEdit;
+ private:
+ QLabel* jidLabel;
+ QtResizableLineEdit* jidLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
index ba51078..8b94c42 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
@@ -17,129 +17,129 @@
namespace Swift {
QtVCardOrganizationField::QtVCardOrganizationField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardOrganizationField::~QtVCardOrganizationField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardOrganizationField::setupContentWidgets() {
- organizationLabel = new QLabel(this);
- organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
- organizationLineEdit = new QtResizableLineEdit(this);
- QHBoxLayout* organizationLayout = new QHBoxLayout();
- organizationLayout->addWidget(organizationLabel);
- organizationLayout->addWidget(organizationLineEdit);
+ organizationLabel = new QLabel(this);
+ organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
+ organizationLineEdit = new QtResizableLineEdit(this);
+ QHBoxLayout* organizationLayout = new QHBoxLayout();
+ organizationLayout->addWidget(organizationLabel);
+ organizationLayout->addWidget(organizationLineEdit);
- getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- itemDelegate = new QtRemovableItemDelegate(style());
+ itemDelegate = new QtRemovableItemDelegate(style());
- unitsTreeWidget = new QTreeWidget(this);
- connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int)));
- unitsTreeWidget->setColumnCount(2);
- unitsTreeWidget->header()->setStretchLastSection(false);
- unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ unitsTreeWidget = new QTreeWidget(this);
+ connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int)));
+ unitsTreeWidget->setColumnCount(2);
+ unitsTreeWidget->header()->setStretchLastSection(false);
+ unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
#if QT_VERSION >= 0x050000
- unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch);
+ 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);
+ 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);
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
- getTagComboBox()->hide();
- organizationLabel->hide();
- childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget;
+ getTagComboBox()->hide();
+ organizationLabel->hide();
+ childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget;
}
bool QtVCardOrganizationField::isEmpty() const {
- return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0;
+ 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) {
- 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);
+ organizationLineEdit->setText(P2QSTRING(organization.name));
+ unitsTreeWidget->clear();
+ foreach(std::string 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;
+ 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);
+ 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();
+ guaranteeEmptyRow();
}
void QtVCardOrganizationField::handleRowsRemoved(const QModelIndex&, int, int) {
- guaranteeEmptyRow();
+ guaranteeEmptyRow();
}
void QtVCardOrganizationField::guaranteeEmptyRow() {
- bool hasEmptyRow = false;
- QList<QTreeWidgetItem*> rows = unitsTreeWidget->findItems("", Qt::MatchFixedString);
- foreach(QTreeWidgetItem* 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);
- }
+ bool hasEmptyRow = false;
+ QList<QTreeWidgetItem*> rows = unitsTreeWidget->findItems("", Qt::MatchFixedString);
+ foreach(QTreeWidgetItem* 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/QtVCardWidget/QtVCardOrganizationField.h b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
index f567e92..6de3167 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
@@ -24,37 +24,37 @@
namespace Swift {
class QtVCardOrganizationField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField)
- QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardOrganizationField();
+ QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardOrganizationField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setOrganization(const VCard::Organization& organization);
- VCard::Organization getOrganization() const;
+ void setOrganization(const VCard::Organization& organization);
+ VCard::Organization getOrganization() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private slots:
- void handleItemChanged(QTreeWidgetItem*, int);
- void handleRowsRemoved(const QModelIndex&, int, int);
+ private slots:
+ void handleItemChanged(QTreeWidgetItem*, int);
+ void handleRowsRemoved(const QModelIndex&, int, int);
- private:
- void guaranteeEmptyRow();
+ private:
+ void guaranteeEmptyRow();
- private:
- QLabel* organizationLabel;
- QtResizableLineEdit* organizationLineEdit;
- QTreeWidget* unitsTreeWidget;
- QtRemovableItemDelegate* itemDelegate;
+ private:
+ QLabel* organizationLabel;
+ QtResizableLineEdit* organizationLineEdit;
+ QTreeWidget* unitsTreeWidget;
+ QtRemovableItemDelegate* itemDelegate;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
index 680fdb5..90d6e5e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
@@ -19,134 +19,134 @@
namespace Swift {
QtVCardPhotoAndNameFields::QtVCardPhotoAndNameFields(QWidget* parent) :
- QWidget(parent),
- ui(new Ui::QtVCardPhotoAndNameFields) {
- ui->setupUi(this);
- ui->lineEditPREFIX->hide();
- ui->lineEditMIDDLE->hide();
- ui->lineEditSUFFIX->hide();
- ui->lineEditFN->hide();
- ui->lineEditNICKNAME->hide();
- ui->labelFN->hide();
- ui->labelNICKNAME->hide();
- ui->labelFULLNAME->hide();
+ QWidget(parent),
+ ui(new Ui::QtVCardPhotoAndNameFields) {
+ ui->setupUi(this);
+ ui->lineEditPREFIX->hide();
+ ui->lineEditMIDDLE->hide();
+ ui->lineEditSUFFIX->hide();
+ ui->lineEditFN->hide();
+ ui->lineEditNICKNAME->hide();
+ ui->labelFN->hide();
+ ui->labelNICKNAME->hide();
+ ui->labelFULLNAME->hide();
#if QT_VERSION >= 0x040700
- ui->lineEditFN->setPlaceholderText(tr("Formatted Name"));
- ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname"));
- ui->lineEditPREFIX->setPlaceholderText(tr("Prefix"));
- ui->lineEditGIVEN->setPlaceholderText(tr("Given Name"));
- ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name"));
- ui->lineEditFAMILY->setPlaceholderText(tr("Last Name"));
- ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix"));
+ ui->lineEditFN->setPlaceholderText(tr("Formatted Name"));
+ ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname"));
+ ui->lineEditPREFIX->setPlaceholderText(tr("Prefix"));
+ ui->lineEditGIVEN->setPlaceholderText(tr("Given Name"));
+ ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name"));
+ ui->lineEditFAMILY->setPlaceholderText(tr("Last Name"));
+ ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix"));
#endif
- setEditable(false);
+ setEditable(false);
}
QtVCardPhotoAndNameFields::~QtVCardPhotoAndNameFields() {
- delete ui;
+ delete ui;
}
bool QtVCardPhotoAndNameFields::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardPhotoAndNameFields::setEditable(bool editable) {
- this->editable = editable;
+ this->editable = editable;
- ui->avatarWidget->setEditable(editable);
- ui->lineEditFN->setVisible(editable);
- ui->labelFN->setVisible(!editable);
+ ui->avatarWidget->setEditable(editable);
+ ui->lineEditFN->setVisible(editable);
+ ui->labelFN->setVisible(!editable);
- ui->lineEditNICKNAME->setVisible(editable);
- ui->labelNICKNAME->setVisible(!editable);
+ ui->lineEditNICKNAME->setVisible(editable);
+ ui->labelNICKNAME->setVisible(!editable);
- // prefix given middle last suffix
- ui->lineEditPREFIX->setVisible(editable);
- ui->lineEditGIVEN->setVisible(editable);
- ui->lineEditMIDDLE->setVisible(editable);
- ui->lineEditFAMILY->setVisible(editable);
- ui->lineEditSUFFIX->setVisible(editable);
- ui->labelFULLNAME->setVisible(!editable);
+ // prefix given middle last suffix
+ ui->lineEditPREFIX->setVisible(editable);
+ ui->lineEditGIVEN->setVisible(editable);
+ ui->lineEditMIDDLE->setVisible(editable);
+ ui->lineEditFAMILY->setVisible(editable);
+ ui->lineEditSUFFIX->setVisible(editable);
+ ui->labelFULLNAME->setVisible(!editable);
- QStringList fullname;
- fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text();
- fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text();
- for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) {
- *i = i->trimmed();
- }
- ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" "));
+ QStringList fullname;
+ fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text();
+ fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text();
+ for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) {
+ *i = i->trimmed();
+ }
+ ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" "));
}
void QtVCardPhotoAndNameFields::setAvatar(const ByteArray &data, const std::string &type) {
- ui->avatarWidget->setAvatar(data, type);
+ ui->avatarWidget->setAvatar(data, type);
}
ByteArray QtVCardPhotoAndNameFields::getAvatarData() const {
- return ui->avatarWidget->getAvatarData();
+ return ui->avatarWidget->getAvatarData();
}
std::string QtVCardPhotoAndNameFields::getAvatarType() const {
- return ui->avatarWidget->getAvatarType();
+ return ui->avatarWidget->getAvatarType();
}
void QtVCardPhotoAndNameFields::setFormattedName(const QString& formattedName) {
- ui->lineEditFN->setText(formattedName);
- ui->labelFN->setText(formattedName);
+ ui->lineEditFN->setText(formattedName);
+ ui->labelFN->setText(formattedName);
}
QString QtVCardPhotoAndNameFields::getFormattedName() const {
- return ui->lineEditFN->text();
+ return ui->lineEditFN->text();
}
void QtVCardPhotoAndNameFields::setNickname(const QString& nickname) {
- ui->lineEditNICKNAME->setText(nickname);
- ui->labelNICKNAME->setText(nickname);
+ ui->lineEditNICKNAME->setText(nickname);
+ ui->labelNICKNAME->setText(nickname);
}
QString QtVCardPhotoAndNameFields::getNickname() const {
- return ui->lineEditNICKNAME->text();
+ return ui->lineEditNICKNAME->text();
}
void QtVCardPhotoAndNameFields::setPrefix(const QString& prefix) {
- ui->lineEditPREFIX->setText(prefix);
+ ui->lineEditPREFIX->setText(prefix);
}
QString QtVCardPhotoAndNameFields::getPrefix() const {
- return ui->lineEditPREFIX->text();
+ return ui->lineEditPREFIX->text();
}
void QtVCardPhotoAndNameFields::setGivenName(const QString& givenName) {
- ui->lineEditGIVEN->setText(givenName);
+ ui->lineEditGIVEN->setText(givenName);
}
QString QtVCardPhotoAndNameFields::getGivenName() const {
- return ui->lineEditGIVEN->text();
+ return ui->lineEditGIVEN->text();
}
void QtVCardPhotoAndNameFields::setMiddleName(const QString& middleName) {
- ui->lineEditMIDDLE->setText(middleName);
+ ui->lineEditMIDDLE->setText(middleName);
}
QString QtVCardPhotoAndNameFields::getMiddleName() const {
- return ui->lineEditMIDDLE->text();
+ return ui->lineEditMIDDLE->text();
}
void QtVCardPhotoAndNameFields::setFamilyName(const QString& familyName) {
- ui->lineEditFAMILY->setText(familyName);
+ ui->lineEditFAMILY->setText(familyName);
}
QString QtVCardPhotoAndNameFields::getFamilyName() const {
- return ui->lineEditFAMILY->text();
+ return ui->lineEditFAMILY->text();
}
void QtVCardPhotoAndNameFields::setSuffix(const QString& suffix) {
- ui->lineEditSUFFIX->setText(suffix);
+ ui->lineEditSUFFIX->setText(suffix);
}
QString QtVCardPhotoAndNameFields::getSuffix() const {
- return ui->lineEditSUFFIX->text();
+ return ui->lineEditSUFFIX->text();
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
index ac35109..a0bbb24 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
@@ -12,51 +12,51 @@
#include <Swiften/Base/ByteArray.h>
namespace Ui {
- class QtVCardPhotoAndNameFields;
+ class QtVCardPhotoAndNameFields;
}
namespace Swift {
- class QtVCardPhotoAndNameFields : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+ class QtVCardPhotoAndNameFields : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
- public:
- explicit QtVCardPhotoAndNameFields(QWidget* parent = 0);
- ~QtVCardPhotoAndNameFields();
+ public:
+ explicit QtVCardPhotoAndNameFields(QWidget* parent = 0);
+ ~QtVCardPhotoAndNameFields();
- bool isEditable() const;
- void setEditable(bool);
+ bool isEditable() const;
+ void setEditable(bool);
- void setAvatar(const ByteArray& data, const std::string& type);
- ByteArray getAvatarData() const;
- std::string getAvatarType() const;
+ void setAvatar(const ByteArray& data, const std::string& type);
+ ByteArray getAvatarData() const;
+ std::string getAvatarType() const;
- void setFormattedName(const QString& formattedName);
- QString getFormattedName() const;
+ void setFormattedName(const QString& formattedName);
+ QString getFormattedName() const;
- void setNickname(const QString& nickname);
- QString getNickname() const;
+ void setNickname(const QString& nickname);
+ QString getNickname() const;
- void setPrefix(const QString& prefix);
- QString getPrefix() const;
+ void setPrefix(const QString& prefix);
+ QString getPrefix() const;
- void setGivenName(const QString& givenName);
- QString getGivenName() const;
+ void setGivenName(const QString& givenName);
+ QString getGivenName() const;
- void setMiddleName(const QString& middleName);
- QString getMiddleName() const;
+ void setMiddleName(const QString& middleName);
+ QString getMiddleName() const;
- void setFamilyName(const QString& familyName);
- QString getFamilyName() const;
+ void setFamilyName(const QString& familyName);
+ QString getFamilyName() const;
- void setSuffix(const QString& suffix);
- QString getSuffix() const;
+ void setSuffix(const QString& suffix);
+ QString getSuffix() const;
- private:
- Ui::QtVCardPhotoAndNameFields* ui;
- bool editable;
- };
+ private:
+ Ui::QtVCardPhotoAndNameFields* ui;
+ bool editable;
+ };
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
index ce3cc2f..2881932 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
@@ -21,37 +21,37 @@
namespace Swift {
QtVCardRoleField::QtVCardRoleField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardRoleField::~QtVCardRoleField() {
}
void QtVCardRoleField::setupContentWidgets() {
- roleLineEdit = new QtResizableLineEdit(this);
- getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << roleLineEdit;
+ roleLineEdit = new QtResizableLineEdit(this);
+ getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << roleLineEdit;
}
bool QtVCardRoleField::isEmpty() const {
- return roleLineEdit->text().isEmpty();
+ return roleLineEdit->text().isEmpty();
}
void QtVCardRoleField::setRole(const std::string& role) {
- roleLineEdit->setText(P2QSTRING(role));
+ roleLineEdit->setText(P2QSTRING(role));
}
std::string QtVCardRoleField::getRole() const {
- return Q2PSTRING(roleLineEdit->text());
+ return Q2PSTRING(roleLineEdit->text());
}
void QtVCardRoleField::handleEditibleChanged(bool isEditable) {
- assert(roleLineEdit);
+ assert(roleLineEdit);
- roleLineEdit->setEditable(isEditable);
- roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ roleLineEdit->setEditable(isEditable);
+ roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
index f2d5e75..40b5d0b 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
@@ -21,27 +21,27 @@
namespace Swift {
class QtVCardRoleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField)
- QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardRoleField();
+ QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardRoleField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setRole(const std::string& role);
- std::string getRole() const;
+ void setRole(const std::string& role);
+ std::string getRole() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* roleLineEdit;
+ private:
+ QtResizableLineEdit* roleLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
index 57e2b27..4af2fa3 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
@@ -19,88 +19,88 @@
namespace Swift {
QtVCardTelephoneField::QtVCardTelephoneField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardTelephoneField::~QtVCardTelephoneField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardTelephoneField::setupContentWidgets() {
- telephoneLineEdit = new QtResizableLineEdit(this);
+ telephoneLineEdit = new QtResizableLineEdit(this);
#if QT_VERSION >= 0x040700
- telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253"));
+ telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253"));
#endif
- getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- setTabOrder(telephoneLineEdit, getTagComboBox());
- QtVCardHomeWork::setTagComboBox(getTagComboBox());
-
- getTagComboBox()->addTag("voice", QObject::tr("Voice"));
- getTagComboBox()->addTag("fax", QObject::tr("Fax"));
- getTagComboBox()->addTag("pager", QObject::tr("Pager"));
- getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging"));
- getTagComboBox()->addTag("cell", QObject::tr("Cell"));
- getTagComboBox()->addTag("video", QObject::tr("Video"));
- getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System"));
- getTagComboBox()->addTag("modem", QObject::tr("Modem"));
- getTagComboBox()->addTag("isdn", QObject::tr("ISDN"));
- getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services"));
-
- childWidgets << telephoneLineEdit;
+ getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ setTabOrder(telephoneLineEdit, getTagComboBox());
+ QtVCardHomeWork::setTagComboBox(getTagComboBox());
+
+ getTagComboBox()->addTag("voice", QObject::tr("Voice"));
+ getTagComboBox()->addTag("fax", QObject::tr("Fax"));
+ getTagComboBox()->addTag("pager", QObject::tr("Pager"));
+ getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging"));
+ getTagComboBox()->addTag("cell", QObject::tr("Cell"));
+ getTagComboBox()->addTag("video", QObject::tr("Video"));
+ getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System"));
+ getTagComboBox()->addTag("modem", QObject::tr("Modem"));
+ getTagComboBox()->addTag("isdn", QObject::tr("ISDN"));
+ getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services"));
+
+ childWidgets << telephoneLineEdit;
}
bool QtVCardTelephoneField::isEmpty() const {
- return telephoneLineEdit->text().isEmpty();
+ return telephoneLineEdit->text().isEmpty();
}
void QtVCardTelephoneField::setTelephone(const VCard::Telephone& telephone) {
- setPreferred(telephone.isPreferred);
- setHome(telephone.isHome);
- setWork(telephone.isWork);
-
- telephoneLineEdit->setText(P2QSTRING(telephone.number));
-
- getTagComboBox()->setTag("voice", telephone.isVoice);
- getTagComboBox()->setTag("fax", telephone.isFax);
- getTagComboBox()->setTag("pager", telephone.isPager);
- getTagComboBox()->setTag("msg", telephone.isMSG);
- getTagComboBox()->setTag("cell", telephone.isCell);
- getTagComboBox()->setTag("video", telephone.isVideo);
- getTagComboBox()->setTag("bbs", telephone.isBBS);
- getTagComboBox()->setTag("modem", telephone.isModem);
- getTagComboBox()->setTag("isdn", telephone.isISDN);
- getTagComboBox()->setTag("pcs", telephone.isPCS);
+ setPreferred(telephone.isPreferred);
+ setHome(telephone.isHome);
+ setWork(telephone.isWork);
+
+ telephoneLineEdit->setText(P2QSTRING(telephone.number));
+
+ getTagComboBox()->setTag("voice", telephone.isVoice);
+ getTagComboBox()->setTag("fax", telephone.isFax);
+ getTagComboBox()->setTag("pager", telephone.isPager);
+ getTagComboBox()->setTag("msg", telephone.isMSG);
+ getTagComboBox()->setTag("cell", telephone.isCell);
+ getTagComboBox()->setTag("video", telephone.isVideo);
+ getTagComboBox()->setTag("bbs", telephone.isBBS);
+ getTagComboBox()->setTag("modem", telephone.isModem);
+ getTagComboBox()->setTag("isdn", telephone.isISDN);
+ getTagComboBox()->setTag("pcs", telephone.isPCS);
}
VCard::Telephone QtVCardTelephoneField::getTelephone() const {
- VCard::Telephone telephone;
-
- telephone.number = Q2PSTRING(telephoneLineEdit->text());
-
- telephone.isPreferred = getPreferred();
- telephone.isHome = getHome();
- telephone.isWork = getWork();
-
- telephone.isVoice = getTagComboBox()->isTagSet("voice");
- telephone.isFax = getTagComboBox()->isTagSet("fax");
- telephone.isPager = getTagComboBox()->isTagSet("pager");
- telephone.isMSG = getTagComboBox()->isTagSet("msg");
- telephone.isCell = getTagComboBox()->isTagSet("cell");
- telephone.isVideo = getTagComboBox()->isTagSet("video");
- telephone.isBBS = getTagComboBox()->isTagSet("bbs");
- telephone.isModem = getTagComboBox()->isTagSet("modem");
- telephone.isISDN = getTagComboBox()->isTagSet("isdn");
- telephone.isPCS = getTagComboBox()->isTagSet("pcs");
-
- return telephone;
+ VCard::Telephone telephone;
+
+ telephone.number = Q2PSTRING(telephoneLineEdit->text());
+
+ telephone.isPreferred = getPreferred();
+ telephone.isHome = getHome();
+ telephone.isWork = getWork();
+
+ telephone.isVoice = getTagComboBox()->isTagSet("voice");
+ telephone.isFax = getTagComboBox()->isTagSet("fax");
+ telephone.isPager = getTagComboBox()->isTagSet("pager");
+ telephone.isMSG = getTagComboBox()->isTagSet("msg");
+ telephone.isCell = getTagComboBox()->isTagSet("cell");
+ telephone.isVideo = getTagComboBox()->isTagSet("video");
+ telephone.isBBS = getTagComboBox()->isTagSet("bbs");
+ telephone.isModem = getTagComboBox()->isTagSet("modem");
+ telephone.isISDN = getTagComboBox()->isTagSet("isdn");
+ telephone.isPCS = getTagComboBox()->isTagSet("pcs");
+
+ return telephone;
}
void QtVCardTelephoneField::handleEditibleChanged(bool isEditable) {
- assert(telephoneLineEdit);
+ assert(telephoneLineEdit);
- telephoneLineEdit->setEditable(isEditable);
- telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ telephoneLineEdit->setEditable(isEditable);
+ telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
index a06eb32..1a08a5a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
@@ -22,27 +22,27 @@
namespace Swift {
class QtVCardTelephoneField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField)
- QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardTelephoneField();
+ QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardTelephoneField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setTelephone(const VCard::Telephone& telephone);
- VCard::Telephone getTelephone() const;
+ void setTelephone(const VCard::Telephone& telephone);
+ VCard::Telephone getTelephone() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* telephoneLineEdit;
+ private:
+ QtResizableLineEdit* telephoneLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
index aab7fac..5da5763 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
@@ -21,38 +21,38 @@
namespace Swift {
QtVCardTitleField::QtVCardTitleField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardTitleField::~QtVCardTitleField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardTitleField::setupContentWidgets() {
- titleLineEdit = new QtResizableLineEdit(this);
- getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- childWidgets << titleLineEdit;
+ titleLineEdit = new QtResizableLineEdit(this);
+ getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ childWidgets << titleLineEdit;
}
bool QtVCardTitleField::isEmpty() const {
- return titleLineEdit->text().isEmpty();
+ return titleLineEdit->text().isEmpty();
}
void QtVCardTitleField::setTitle(const std::string& title) {
- titleLineEdit->setText(P2QSTRING(title));
+ titleLineEdit->setText(P2QSTRING(title));
}
std::string QtVCardTitleField::getTitle() const {
- return Q2PSTRING(titleLineEdit->text());
+ return Q2PSTRING(titleLineEdit->text());
}
void QtVCardTitleField::handleEditibleChanged(bool isEditable) {
- assert(titleLineEdit);
+ assert(titleLineEdit);
- titleLineEdit->setEditable(isEditable);
- titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ titleLineEdit->setEditable(isEditable);
+ titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
index a7feb81..ff2a04e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
@@ -21,27 +21,27 @@
namespace Swift {
class QtVCardTitleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField)
- QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardTitleField();
+ QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardTitleField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setTitle(const std::string& title);
- std::string getTitle() const;
+ void setTitle(const std::string& title);
+ std::string getTitle() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QtResizableLineEdit* titleLineEdit;
+ private:
+ QtResizableLineEdit* titleLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
index 262a0e2..8abc46e 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
@@ -24,54 +24,54 @@
namespace Swift {
QtVCardURLField::QtVCardURLField(QWidget* parent, QGridLayout *layout, bool editable) :
- QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) {
- connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
+ QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) {
+ connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool)));
}
QtVCardURLField::~QtVCardURLField() {
- disconnect(this, SLOT(handleEditibleChanged(bool)));
+ disconnect(this, SLOT(handleEditibleChanged(bool)));
}
void QtVCardURLField::setupContentWidgets() {
- urlLabel = new QLabel(this);
- urlLabel->setOpenExternalLinks(true);
- urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
- urlLineEdit = new QtResizableLineEdit(this);
-
- QHBoxLayout* urlLayout = new QHBoxLayout();
- urlLayout->addWidget(urlLabel);
- urlLayout->addWidget(urlLineEdit);
-
- getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
- getTagComboBox()->hide();
- urlLabel->hide();
- childWidgets << urlLabel << urlLineEdit;
+ urlLabel = new QLabel(this);
+ urlLabel->setOpenExternalLinks(true);
+ urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
+ urlLineEdit = new QtResizableLineEdit(this);
+
+ QHBoxLayout* urlLayout = new QHBoxLayout();
+ urlLayout->addWidget(urlLabel);
+ urlLayout->addWidget(urlLineEdit);
+
+ getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter);
+ getTagComboBox()->hide();
+ urlLabel->hide();
+ childWidgets << urlLabel << urlLineEdit;
}
bool QtVCardURLField::isEmpty() const {
- return urlLineEdit->text().isEmpty();
+ return urlLineEdit->text().isEmpty();
}
void QtVCardURLField::setURL(const std::string& url) {
- urlLineEdit->setText(P2QSTRING(url));
+ urlLineEdit->setText(P2QSTRING(url));
}
std::string QtVCardURLField::getURL() const {
- return Q2PSTRING(urlLineEdit->text());
+ return Q2PSTRING(urlLineEdit->text());
}
void QtVCardURLField::handleEditibleChanged(bool isEditable) {
- assert(urlLineEdit);
- assert(urlLabel);
-
- if (isEditable) {
- urlLineEdit->show();
- urlLabel->hide();
- } else {
- urlLineEdit->hide();
- urlLabel->setText(QString("<a href=\"%1\">%1</a>").arg(QtUtilities::htmlEscape(urlLineEdit->text())));
- urlLabel->show();
- }
+ assert(urlLineEdit);
+ assert(urlLabel);
+
+ if (isEditable) {
+ urlLineEdit->show();
+ urlLabel->hide();
+ } else {
+ urlLineEdit->hide();
+ urlLabel->setText(QString("<a href=\"%1\">%1</a>").arg(QtUtilities::htmlEscape(urlLineEdit->text())));
+ urlLabel->show();
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
index 824879a..a1ffacd 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
@@ -21,28 +21,28 @@
namespace Swift {
class QtVCardURLField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField)
+ public:
+ GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField)
- QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
- virtual ~QtVCardURLField();
+ QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false);
+ virtual ~QtVCardURLField();
- virtual bool isEmpty() const;
+ virtual bool isEmpty() const;
- void setURL(const std::string& url);
- std::string getURL() const;
+ void setURL(const std::string& url);
+ std::string getURL() const;
- protected:
- virtual void setupContentWidgets();
+ protected:
+ virtual void setupContentWidgets();
- public slots:
- void handleEditibleChanged(bool isEditable);
+ public slots:
+ void handleEditibleChanged(bool isEditable);
- private:
- QLabel* urlLabel;
- QtResizableLineEdit* urlLineEdit;
+ private:
+ QLabel* urlLabel;
+ QtResizableLineEdit* urlLineEdit;
};
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
index f390d30..712cedf 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
@@ -33,394 +33,394 @@
namespace Swift {
QtVCardWidget::QtVCardWidget(QWidget* parent) :
- QWidget(parent),
- ui(new ::Ui::QtVCardWidget) {
- ui->setupUi(this);
-
- ui->cardFields->setColumnStretch(0,0);
- ui->cardFields->setColumnStretch(1,0);
- ui->cardFields->setColumnStretch(2,2);
- ui->cardFields->setColumnStretch(3,1);
- ui->cardFields->setColumnStretch(4,2);
- menu = new QMenu(this);
-
- toolButton = new QToolButton(this);
- toolButton->setText(tr("Add Field"));
- toolButton->setArrowType(Qt::NoArrow);
- toolButton->setAutoRaise(false);
- toolButton->setPopupMode(QToolButton::InstantPopup);
- toolButton->hide();
- toolButton->setMenu(menu);
-
- addFieldType(menu, boost::make_shared<QtVCardInternetEMailField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardTelephoneField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardAddressField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardAddressLabelField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardBirthdayField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardJIDField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardDescriptionField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardRoleField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardTitleField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardOrganizationField::FieldInfo>());
- addFieldType(menu, boost::make_shared<QtVCardURLField::FieldInfo>());
-
- setEditable(false);
- setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
+ QWidget(parent),
+ ui(new ::Ui::QtVCardWidget) {
+ ui->setupUi(this);
+
+ ui->cardFields->setColumnStretch(0,0);
+ ui->cardFields->setColumnStretch(1,0);
+ ui->cardFields->setColumnStretch(2,2);
+ ui->cardFields->setColumnStretch(3,1);
+ ui->cardFields->setColumnStretch(4,2);
+ menu = new QMenu(this);
+
+ toolButton = new QToolButton(this);
+ toolButton->setText(tr("Add Field"));
+ toolButton->setArrowType(Qt::NoArrow);
+ toolButton->setAutoRaise(false);
+ toolButton->setPopupMode(QToolButton::InstantPopup);
+ toolButton->hide();
+ toolButton->setMenu(menu);
+
+ addFieldType(menu, boost::make_shared<QtVCardInternetEMailField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardTelephoneField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardAddressField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardAddressLabelField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardBirthdayField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardJIDField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardDescriptionField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardRoleField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardTitleField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardOrganizationField::FieldInfo>());
+ addFieldType(menu, boost::make_shared<QtVCardURLField::FieldInfo>());
+
+ setEditable(false);
+ setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
QtVCardWidget::~QtVCardWidget() {
- delete ui;
+ delete ui;
}
QSize QtVCardWidget::sizeHint() const {
- QSize newSizeHint = ui->photoAndName->sizeHint();
+ QSize newSizeHint = ui->photoAndName->sizeHint();
- // use mininmal size that does not require scrolling
- QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize();
- fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width());
+ // use mininmal size that does not require scrolling
+ QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize();
+ fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width());
- newSizeHint += QSize(0, ui->line->height());
+ newSizeHint += QSize(0, ui->line->height());
- newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height());
+ newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height());
- // add layout margin
- newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom());
+ // add layout margin
+ newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom());
- // the spaceing before and after the line between the profile header and its fields
- newSizeHint += QSize(0, layout()->spacing() * 2);
+ // the spaceing before and after the line between the profile header and its fields
+ newSizeHint += QSize(0, layout()->spacing() * 2);
- return newSizeHint;
+ return newSizeHint;
}
bool QtVCardWidget::isEditable() const {
- return editable;
+ return editable;
}
void QtVCardWidget::setEditable(bool editable) {
- this->editable = editable;
+ this->editable = editable;
- ui->photoAndName->setProperty("editable", QVariant(editable));
+ ui->photoAndName->setProperty("editable", QVariant(editable));
- foreach(QtVCardGeneralField* field, fields) {
- field->setEditable(editable);
- }
- toolButton->setVisible(editable);
+ foreach(QtVCardGeneralField* field, fields) {
+ field->setEditable(editable);
+ }
+ toolButton->setVisible(editable);
- editableChanged(editable);
+ editableChanged(editable);
}
void QtVCardWidget::setVCard(VCard::ref vcard) {
- clearFields();
- this->vcard = boost::make_shared<VCard>(*vcard);
- ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName()));
- ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname()));
- ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix()));
- ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName()));
- ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName()));
- ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName()));
- ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix()));
- ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType());
-
- foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) {
- if (address.isInternet) {
- QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields);
- internetEmailField->initialize();
- internetEmailField->setInternetEMailAddress(address);
- appendField(internetEmailField);
- }
- }
-
- foreach (const VCard::Telephone& telephone, vcard->getTelephones()) {
- QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields);
- telField->initialize();
- telField->setTelephone(telephone);
- appendField(telField);
- }
-
- foreach (const VCard::Address& address, vcard->getAddresses()) {
- QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields);
- addressField->initialize();
- addressField->setAddress(address);
- appendField(addressField);
- }
-
- foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) {
- QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields);
- addressLabelField->initialize();
- addressLabelField->setAddressLabel(label);
- appendField(addressLabelField);
- }
-
- if (!vcard->getBirthday().is_not_a_date_time()) {
- QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields);
- bdayField->initialize();
- bdayField->setBirthday(vcard->getBirthday());
- appendField(bdayField);
- }
-
- foreach (const JID& jid, vcard->getJIDs()) {
- QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields);
- jidField->initialize();
- jidField->setJID(jid);
- appendField(jidField);
- }
-
- if (!vcard->getDescription().empty()) {
- QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields);
- descField->initialize();
- descField->setDescription(vcard->getDescription());
- appendField(descField);
- }
-
- foreach (const VCard::Organization& org, vcard->getOrganizations()) {
- QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields);
- orgField->initialize();
- orgField->setOrganization(org);
- appendField(orgField);
- }
-
- foreach (const std::string& role, vcard->getRoles()) {
- QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields);
- roleField->initialize();
- roleField->setRole(role);
- appendField(roleField);
- }
-
- foreach (const std::string& title, vcard->getTitles()) {
- QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields);
- titleField->initialize();
- titleField->setTitle(title);
- appendField(titleField);
- }
-
- foreach (const std::string& url, vcard->getURLs()) {
- QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields);
- urlField->initialize();
- urlField->setURL(url);
- appendField(urlField);
- }
-
- relayoutToolButton();
- setEditable(editable);
+ clearFields();
+ this->vcard = boost::make_shared<VCard>(*vcard);
+ ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName()));
+ ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname()));
+ ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix()));
+ ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName()));
+ ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName()));
+ ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName()));
+ ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix()));
+ ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType());
+
+ foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) {
+ if (address.isInternet) {
+ QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields);
+ internetEmailField->initialize();
+ internetEmailField->setInternetEMailAddress(address);
+ appendField(internetEmailField);
+ }
+ }
+
+ foreach (const VCard::Telephone& telephone, vcard->getTelephones()) {
+ QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields);
+ telField->initialize();
+ telField->setTelephone(telephone);
+ appendField(telField);
+ }
+
+ foreach (const VCard::Address& address, vcard->getAddresses()) {
+ QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields);
+ addressField->initialize();
+ addressField->setAddress(address);
+ appendField(addressField);
+ }
+
+ foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) {
+ QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields);
+ addressLabelField->initialize();
+ addressLabelField->setAddressLabel(label);
+ appendField(addressLabelField);
+ }
+
+ if (!vcard->getBirthday().is_not_a_date_time()) {
+ QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields);
+ bdayField->initialize();
+ bdayField->setBirthday(vcard->getBirthday());
+ appendField(bdayField);
+ }
+
+ foreach (const JID& jid, vcard->getJIDs()) {
+ QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields);
+ jidField->initialize();
+ jidField->setJID(jid);
+ appendField(jidField);
+ }
+
+ if (!vcard->getDescription().empty()) {
+ QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields);
+ descField->initialize();
+ descField->setDescription(vcard->getDescription());
+ appendField(descField);
+ }
+
+ foreach (const VCard::Organization& org, vcard->getOrganizations()) {
+ QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields);
+ orgField->initialize();
+ orgField->setOrganization(org);
+ appendField(orgField);
+ }
+
+ foreach (const std::string& role, vcard->getRoles()) {
+ QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields);
+ roleField->initialize();
+ roleField->setRole(role);
+ appendField(roleField);
+ }
+
+ foreach (const std::string& title, vcard->getTitles()) {
+ QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields);
+ titleField->initialize();
+ titleField->setTitle(title);
+ appendField(titleField);
+ }
+
+ foreach (const std::string& url, vcard->getURLs()) {
+ QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields);
+ urlField->initialize();
+ urlField->setURL(url);
+ appendField(urlField);
+ }
+
+ relayoutToolButton();
+ setEditable(editable);
}
VCard::ref QtVCardWidget::getVCard() {
- clearEmptyFields();
- vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName()));
- vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname()));
- vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix()));
- vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName()));
- vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName()));
- vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName()));
- vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix()));
- vcard->setPhoto(ui->photoAndName->getAvatarData());
- vcard->setPhotoType(ui->photoAndName->getAvatarType());
-
- vcard->clearEMailAddresses();
- vcard->clearJIDs();
- vcard->clearURLs();
- vcard->clearTelephones();
- vcard->clearRoles();
- vcard->clearTitles();
- vcard->clearOrganizations();
- vcard->clearAddresses();
- vcard->clearAddressLabels();
-
-
- QtVCardBirthdayField* bdayField = NULL;
- QtVCardDescriptionField* descriptionField = NULL;
-
- foreach(QtVCardGeneralField* field, fields) {
- QtVCardInternetEMailField* emailField;
- if ((emailField = dynamic_cast<QtVCardInternetEMailField*>(field))) {
- vcard->addEMailAddress(emailField->getInternetEMailAddress());
- continue;
- }
-
- QtVCardTelephoneField* telephoneField;
- if ((telephoneField = dynamic_cast<QtVCardTelephoneField*>(field))) {
- vcard->addTelephone(telephoneField->getTelephone());
- continue;
- }
-
- QtVCardAddressField* addressField;
- if ((addressField = dynamic_cast<QtVCardAddressField*>(field))) {
- vcard->addAddress(addressField->getAddress());
- continue;
- }
-
- QtVCardAddressLabelField* addressLabelField;
- if ((addressLabelField = dynamic_cast<QtVCardAddressLabelField*>(field))) {
- vcard->addAddressLabel(addressLabelField->getAddressLabel());
- continue;
- }
-
- if ((bdayField = dynamic_cast<QtVCardBirthdayField*>(field))) {
- continue;
- }
-
- QtVCardJIDField* jidField;
- if ((jidField = dynamic_cast<QtVCardJIDField*>(field))) {
- vcard->addJID(jidField->getJID());
- continue;
- }
-
- if ((descriptionField = dynamic_cast<QtVCardDescriptionField*>(field))) {
- continue;
- }
-
- QtVCardOrganizationField* orgField;
- if ((orgField = dynamic_cast<QtVCardOrganizationField*>(field))) {
- vcard->addOrganization(orgField->getOrganization());
- continue;
- }
-
- QtVCardRoleField* roleField;
- if ((roleField = dynamic_cast<QtVCardRoleField*>(field))) {
- vcard->addRole(roleField->getRole());
- continue;
- }
-
- QtVCardTitleField* titleField;
- if ((titleField = dynamic_cast<QtVCardTitleField*>(field))) {
- vcard->addTitle(titleField->getTitle());
- continue;
- }
-
- QtVCardURLField* urlField;
- if ((urlField = dynamic_cast<QtVCardURLField*>(field))) {
- vcard->addURL(urlField->getURL());
- continue;
- }
- }
-
- if (bdayField) {
- vcard->setBirthday(bdayField->getBirthday());
- } else {
- vcard->setBirthday(boost::posix_time::ptime());
- }
-
- if (descriptionField) {
- vcard->setDescription(descriptionField->getDescription());
- } else {
- vcard->setDescription("");
- }
-
- return vcard;
+ clearEmptyFields();
+ vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName()));
+ vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname()));
+ vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix()));
+ vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName()));
+ vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName()));
+ vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName()));
+ vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix()));
+ vcard->setPhoto(ui->photoAndName->getAvatarData());
+ vcard->setPhotoType(ui->photoAndName->getAvatarType());
+
+ vcard->clearEMailAddresses();
+ vcard->clearJIDs();
+ vcard->clearURLs();
+ vcard->clearTelephones();
+ vcard->clearRoles();
+ vcard->clearTitles();
+ vcard->clearOrganizations();
+ vcard->clearAddresses();
+ vcard->clearAddressLabels();
+
+
+ QtVCardBirthdayField* bdayField = NULL;
+ QtVCardDescriptionField* descriptionField = NULL;
+
+ foreach(QtVCardGeneralField* field, fields) {
+ QtVCardInternetEMailField* emailField;
+ if ((emailField = dynamic_cast<QtVCardInternetEMailField*>(field))) {
+ vcard->addEMailAddress(emailField->getInternetEMailAddress());
+ continue;
+ }
+
+ QtVCardTelephoneField* telephoneField;
+ if ((telephoneField = dynamic_cast<QtVCardTelephoneField*>(field))) {
+ vcard->addTelephone(telephoneField->getTelephone());
+ continue;
+ }
+
+ QtVCardAddressField* addressField;
+ if ((addressField = dynamic_cast<QtVCardAddressField*>(field))) {
+ vcard->addAddress(addressField->getAddress());
+ continue;
+ }
+
+ QtVCardAddressLabelField* addressLabelField;
+ if ((addressLabelField = dynamic_cast<QtVCardAddressLabelField*>(field))) {
+ vcard->addAddressLabel(addressLabelField->getAddressLabel());
+ continue;
+ }
+
+ if ((bdayField = dynamic_cast<QtVCardBirthdayField*>(field))) {
+ continue;
+ }
+
+ QtVCardJIDField* jidField;
+ if ((jidField = dynamic_cast<QtVCardJIDField*>(field))) {
+ vcard->addJID(jidField->getJID());
+ continue;
+ }
+
+ if ((descriptionField = dynamic_cast<QtVCardDescriptionField*>(field))) {
+ continue;
+ }
+
+ QtVCardOrganizationField* orgField;
+ if ((orgField = dynamic_cast<QtVCardOrganizationField*>(field))) {
+ vcard->addOrganization(orgField->getOrganization());
+ continue;
+ }
+
+ QtVCardRoleField* roleField;
+ if ((roleField = dynamic_cast<QtVCardRoleField*>(field))) {
+ vcard->addRole(roleField->getRole());
+ continue;
+ }
+
+ QtVCardTitleField* titleField;
+ if ((titleField = dynamic_cast<QtVCardTitleField*>(field))) {
+ vcard->addTitle(titleField->getTitle());
+ continue;
+ }
+
+ QtVCardURLField* urlField;
+ if ((urlField = dynamic_cast<QtVCardURLField*>(field))) {
+ vcard->addURL(urlField->getURL());
+ continue;
+ }
+ }
+
+ if (bdayField) {
+ vcard->setBirthday(bdayField->getBirthday());
+ } else {
+ vcard->setBirthday(boost::posix_time::ptime());
+ }
+
+ if (descriptionField) {
+ vcard->setDescription(descriptionField->getDescription());
+ } else {
+ vcard->setDescription("");
+ }
+
+ return vcard;
}
void QtVCardWidget::addField() {
- QAction* action = NULL;
- if ((action = dynamic_cast<QAction*>(sender()))) {
- boost::shared_ptr<QtVCardFieldInfo> fieldInfo = actionFieldInfo[action];
- QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true);
- QtVCardGeneralField* newGeneralField = dynamic_cast<QtVCardGeneralField*>(newField);
- if (newGeneralField) {
- newGeneralField->initialize();
- }
- appendField(newGeneralField);
- relayoutToolButton();
- }
+ QAction* action = NULL;
+ if ((action = dynamic_cast<QAction*>(sender()))) {
+ boost::shared_ptr<QtVCardFieldInfo> fieldInfo = actionFieldInfo[action];
+ QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true);
+ QtVCardGeneralField* newGeneralField = dynamic_cast<QtVCardGeneralField*>(newField);
+ if (newGeneralField) {
+ newGeneralField->initialize();
+ }
+ appendField(newGeneralField);
+ relayoutToolButton();
+ }
}
void QtVCardWidget::removeField(QtVCardGeneralField *field) {
- int sameFields = 0;
- QtVCardGeneralField* fieldToChange = NULL;
- foreach (QtVCardGeneralField* vcardField, fields) {
- if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) {
- sameFields++;
- fieldToChange = vcardField;
- }
- }
-
- if ((sameFields == 1) && fieldToChange) {
- fieldToChange->setStarVisible(false);
- }
-
- fields.remove(field);
- delete field;
+ int sameFields = 0;
+ QtVCardGeneralField* fieldToChange = NULL;
+ foreach (QtVCardGeneralField* vcardField, fields) {
+ if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) {
+ sameFields++;
+ fieldToChange = vcardField;
+ }
+ }
+
+ if ((sameFields == 1) && fieldToChange) {
+ fieldToChange->setStarVisible(false);
+ }
+
+ fields.remove(field);
+ delete field;
}
void QtVCardWidget::addFieldType(QMenu* menu, boost::shared_ptr<QtVCardFieldInfo> fieldType) {
- if (!fieldType->getMenuName().isEmpty()) {
- QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this);
- actionFieldInfo[action] = fieldType;
- connect(action, SIGNAL(triggered()), this, SLOT(addField()));
- menu->addAction(action);
- }
+ if (!fieldType->getMenuName().isEmpty()) {
+ QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this);
+ actionFieldInfo[action] = fieldType;
+ connect(action, SIGNAL(triggered()), this, SLOT(addField()));
+ menu->addAction(action);
+ }
}
int QtVCardWidget::fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo> fieldType) {
- int instances = 0;
- for (int n = 0; n < ui->cardFields->count(); n++) {
- if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++;
- }
- return instances;
+ int instances = 0;
+ for (int n = 0; n < ui->cardFields->count(); n++) {
+ if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++;
+ }
+ return instances;
}
void layoutDeleteChildren(QLayout *layout) {
- while(layout->count() > 0) {
- QLayoutItem* child;
- if ((child = layout->takeAt(0)) != 0) {
- if (child->layout()) {
- layoutDeleteChildren(child->layout());
- }
- if (dynamic_cast<QToolButton*>(child->widget())) {
- delete child;
- break;
- }
- delete child->widget();
- delete child;
- }
- }
+ while(layout->count() > 0) {
+ QLayoutItem* child;
+ if ((child = layout->takeAt(0)) != 0) {
+ if (child->layout()) {
+ layoutDeleteChildren(child->layout());
+ }
+ if (dynamic_cast<QToolButton*>(child->widget())) {
+ delete child;
+ break;
+ }
+ delete child->widget();
+ delete child;
+ }
+ }
}
void QtVCardWidget::clearFields() {
- foreach(QtVCardGeneralField* field, fields) {
- delete field;
- }
- fields.clear();
+ foreach(QtVCardGeneralField* field, fields) {
+ delete field;
+ }
+ fields.clear();
- assert(ui->cardFields->count() >= 0);
- layoutDeleteChildren(ui->cardFields);
+ assert(ui->cardFields->count() >= 0);
+ layoutDeleteChildren(ui->cardFields);
}
void QtVCardWidget::clearEmptyFields() {
- std::vector<QtVCardGeneralField*> items_to_remove;
- foreach (QtVCardGeneralField* field, fields) {
- if (field->property("empty").isValid() && field->property("empty").toBool()) {
- ui->cardFields->removeWidget(field);
- items_to_remove.push_back(field);
- delete field;
- }
- }
-
- foreach(QtVCardGeneralField* field, items_to_remove) {
- fields.remove(field);
- }
+ std::vector<QtVCardGeneralField*> items_to_remove;
+ foreach (QtVCardGeneralField* field, fields) {
+ if (field->property("empty").isValid() && field->property("empty").toBool()) {
+ ui->cardFields->removeWidget(field);
+ items_to_remove.push_back(field);
+ delete field;
+ }
+ }
+
+ foreach(QtVCardGeneralField* field, items_to_remove) {
+ fields.remove(field);
+ }
}
void QtVCardWidget::appendField(QtVCardGeneralField *field) {
- connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*)));
-
- QtVCardGeneralField* fieldToChange = NULL;
- foreach (QtVCardGeneralField* vcardField, fields) {
- if (typeid(*vcardField) == typeid(*field)) {
- fieldToChange = vcardField;
- break;
- }
- }
-
- if (fieldToChange) {
- fieldToChange->setStarVisible(true);
- field->setStarVisible(true);
- }
-
- fields.push_back(field);
+ connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*)));
+
+ QtVCardGeneralField* fieldToChange = NULL;
+ foreach (QtVCardGeneralField* vcardField, fields) {
+ if (typeid(*vcardField) == typeid(*field)) {
+ fieldToChange = vcardField;
+ break;
+ }
+ }
+
+ if (fieldToChange) {
+ fieldToChange->setStarVisible(true);
+ field->setStarVisible(true);
+ }
+
+ fields.push_back(field);
}
void QtVCardWidget::relayoutToolButton() {
- ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight);
+ ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight);
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
index 8c0ff31..95283c5 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
@@ -24,50 +24,50 @@
#include <Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h>
namespace Ui {
- class QtVCardWidget;
+ class QtVCardWidget;
}
namespace Swift {
- class QtVCardWidget : public QWidget {
- Q_OBJECT
- Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
-
- public :
- explicit QtVCardWidget(QWidget* parent = 0);
- ~QtVCardWidget();
-
- bool isEditable() const;
- void setEditable(bool);
-
- void setVCard(VCard::ref vcard);
- VCard::ref getVCard();
-
- virtual QSize sizeHint() const;
-
- signals:
- void editableChanged(bool editable);
-
- private slots:
- void addField();
- void removeField(QtVCardGeneralField* field);
-
- private:
- void addFieldType(QMenu*, boost::shared_ptr<QtVCardFieldInfo>);
- int fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo>);
- void clearFields();
- void clearEmptyFields();
- void appendField(QtVCardGeneralField* field);
- void relayoutToolButton();
-
- private:
- VCard::ref vcard;
- Ui::QtVCardWidget* ui;
- QToolButton* toolButton;
- bool editable;
- QMenu* menu;
- std::list<QtVCardGeneralField*> fields;
- std::map<QAction*, boost::shared_ptr<QtVCardFieldInfo> > actionFieldInfo;
- };
+ class QtVCardWidget : public QWidget {
+ Q_OBJECT
+ Q_PROPERTY(bool editable READ isEditable WRITE setEditable)
+
+ public :
+ explicit QtVCardWidget(QWidget* parent = 0);
+ ~QtVCardWidget();
+
+ bool isEditable() const;
+ void setEditable(bool);
+
+ void setVCard(VCard::ref vcard);
+ VCard::ref getVCard();
+
+ virtual QSize sizeHint() const;
+
+ signals:
+ void editableChanged(bool editable);
+
+ private slots:
+ void addField();
+ void removeField(QtVCardGeneralField* field);
+
+ private:
+ void addFieldType(QMenu*, boost::shared_ptr<QtVCardFieldInfo>);
+ int fieldTypeInstances(boost::shared_ptr<QtVCardFieldInfo>);
+ void clearFields();
+ void clearEmptyFields();
+ void appendField(QtVCardGeneralField* field);
+ void relayoutToolButton();
+
+ private:
+ VCard::ref vcard;
+ Ui::QtVCardWidget* ui;
+ QToolButton* toolButton;
+ bool editable;
+ QMenu* menu;
+ std::list<QtVCardGeneralField*> fields;
+ std::map<QAction*, boost::shared_ptr<QtVCardFieldInfo> > actionFieldInfo;
+ };
}
diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp
index a0c65ef..4193921 100644
--- a/Swift/QtUI/QtWebKitChatView.cpp
+++ b/Swift/QtUI/QtWebKitChatView.cpp
@@ -50,926 +50,926 @@ const QString QtWebKitChatView::ButtonFileTransferOpenFile = QString("filetransf
const QString QtWebKitChatView::ButtonMUCInvite = QString("mucinvite");
QtWebKitChatView::QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll) : QtChatView(parent), window_(window), eventStream_(eventStream), fontSizeSteps_(0), disableAutoScroll_(disableAutoScroll), previousMessageKind_(PreviosuMessageWasNone), previousMessageWasSelf_(false), showEmoticons_(false), insertingLastLine_(false), idCounter_(0) {
- theme_ = theme;
-
- QVBoxLayout* mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->setContentsMargins(0,0,0,0);
- webView_ = new QtWebView(this);
- connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&)));
- connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool)));
- connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus()));
- connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested()));
- connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize()));
- connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize()));
+ theme_ = theme;
+
+ QVBoxLayout* mainLayout = new QVBoxLayout(this);
+ mainLayout->setSpacing(0);
+ mainLayout->setContentsMargins(0,0,0,0);
+ webView_ = new QtWebView(this);
+ connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&)));
+ connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool)));
+ connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus()));
+ connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested()));
+ connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize()));
+ connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize()));
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC)
- /* To give a border on Linux, where it looks bad without */
- QStackedWidget* stack = new QStackedWidget(this);
- stack->addWidget(webView_);
- stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
- stack->setLineWidth(2);
- mainLayout->addWidget(stack);
+ /* To give a border on Linux, where it looks bad without */
+ QStackedWidget* stack = new QStackedWidget(this);
+ stack->addWidget(webView_);
+ stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
+ stack->setLineWidth(2);
+ mainLayout->addWidget(stack);
#else
- mainLayout->addWidget(webView_);
+ mainLayout->addWidget(webView_);
#endif
#ifdef SWIFT_EXPERIMENTAL_FT
- setAcceptDrops(true);
+ setAcceptDrops(true);
#endif
- webPage_ = new QWebPage(this);
- webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
- if (Log::getLogLevel() == Log::debug) {
- webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
- }
- webView_->setPage(webPage_);
- connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
- connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&)));
+ webPage_ = new QWebPage(this);
+ webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
+ if (Log::getLogLevel() == Log::debug) {
+ webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
+ }
+ webView_->setPage(webPage_);
+ connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard()));
+ connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&)));
- viewReady_ = false;
- isAtBottom_ = true;
- resetView();
+ viewReady_ = false;
+ isAtBottom_ = true;
+ resetView();
- jsBridge = new QtChatWindowJSBridge();
- addToJSEnvironment("chatwindow", jsBridge);
- connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString)));
+ jsBridge = new QtChatWindowJSBridge();
+ addToJSEnvironment("chatwindow", jsBridge);
+ connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString)));
}
QtWebKitChatView::~QtWebKitChatView() {
- delete jsBridge;
+ delete jsBridge;
}
void QtWebKitChatView::handleClearRequested() {
- QMessageBox messageBox(this);
- messageBox.setWindowTitle(tr("Clear log"));
- messageBox.setText(tr("You are about to clear the contents of your chat log."));
- messageBox.setInformativeText(tr("Are you sure?"));
- messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- messageBox.setDefaultButton(QMessageBox::Yes);
- int button = messageBox.exec();
- if (button == QMessageBox::Yes) {
- logCleared();
- resetView();
- }
+ QMessageBox messageBox(this);
+ messageBox.setWindowTitle(tr("Clear log"));
+ messageBox.setText(tr("You are about to clear the contents of your chat log."));
+ messageBox.setInformativeText(tr("Are you sure?"));
+ messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ messageBox.setDefaultButton(QMessageBox::Yes);
+ int button = messageBox.exec();
+ if (button == QMessageBox::Yes) {
+ logCleared();
+ resetView();
+ }
}
void QtWebKitChatView::handleKeyPressEvent(QKeyEvent* event) {
- webView_->keyPressEvent(event);
+ webView_->keyPressEvent(event);
}
void QtWebKitChatView::addMessageBottom(boost::shared_ptr<ChatSnippet> snippet) {
- if (viewReady_) {
- addToDOM(snippet);
- } else {
- /* If this asserts, the previous queuing code was necessary and should be reinstated */
- assert(false);
- }
+ if (viewReady_) {
+ addToDOM(snippet);
+ } else {
+ /* If this asserts, the previous queuing code was necessary and should be reinstated */
+ assert(false);
+ }
}
void QtWebKitChatView::addMessageTop(boost::shared_ptr<ChatSnippet> /* snippet */) {
- // TODO: Implement this in a sensible manner later.
- assert(false);
+ // TODO: Implement this in a sensible manner later.
+ assert(false);
}
void QtWebKitChatView::addToDOM(boost::shared_ptr<ChatSnippet> snippet) {
- //qDebug() << snippet->getContent();
- rememberScrolledToBottom();
+ //qDebug() << snippet->getContent();
+ rememberScrolledToBottom();
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- assert(!insertElement.isNull());
- insertElement.prependOutside(snippet->getContent());
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ assert(!insertElement.isNull());
+ insertElement.prependOutside(snippet->getContent());
- //qDebug() << "-----------------";
- //qDebug() << webPage_->mainFrame()->toHtml();
+ //qDebug() << "-----------------";
+ //qDebug() << webPage_->mainFrame()->toHtml();
}
void QtWebKitChatView::addLastSeenLine() {
- // Remove a potentially existing unread bar.
- QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread");
- if (!existingUnreadBar.isNull()) {
- existingUnreadBar.removeFromDocument();
- }
+ // Remove a potentially existing unread bar.
+ QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread");
+ if (!existingUnreadBar.isNull()) {
+ existingUnreadBar.removeFromDocument();
+ }
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- insertElement.prependOutside(theme_->getUnread());
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ insertElement.prependOutside(theme_->getUnread());
}
void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- rememberScrolledToBottom();
- QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
- assert(!insertElement.isNull());
+ rememberScrolledToBottom();
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ assert(!insertElement.isNull());
- QWebElement lastMessageElement = insertElement.previousSibling();
- QWebElement messageChild = lastMessageElement.findFirst("span.swift_message");
- assert(!messageChild.isNull());
- messageChild.setInnerXml(ChatSnippet::escape(newMessage));
- if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
- QWebElement timeChild = lastMessageElement.findFirst("span.swift_time");
- assert(!timeChild.isNull());
- timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
- }
+ QWebElement lastMessageElement = insertElement.previousSibling();
+ QWebElement messageChild = lastMessageElement.findFirst("span.swift_message");
+ assert(!messageChild.isNull());
+ messageChild.setInnerXml(ChatSnippet::escape(newMessage));
+ if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
+ QWebElement timeChild = lastMessageElement.findFirst("span.swift_time");
+ assert(!timeChild.isNull());
+ timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
+ }
}
void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const QString& note) {
- rememberScrolledToBottom();
- replaceLastMessage(newMessage, ChatWindow::KeepTimestamp);
- QWebElement replace = lastElement_.findFirst("span.swift_time");
- assert(!replace.isNull());
- replace.setInnerXml(ChatSnippet::escape(note));
+ rememberScrolledToBottom();
+ replaceLastMessage(newMessage, ChatWindow::KeepTimestamp);
+ QWebElement replace = lastElement_.findFirst("span.swift_time");
+ assert(!replace.isNull());
+ replace.setInnerXml(ChatSnippet::escape(note));
}
QString QtWebKitChatView::getLastSentMessage() {
- return lastElement_.toPlainText();
+ return lastElement_.toPlainText();
}
void QtWebKitChatView::addToJSEnvironment(const QString& name, QObject* obj) {
- webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj);
+ webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj);
}
void QtWebKitChatView::replaceMessage(const QString& newMessage, const QString& id, const QDateTime& editTime) {
- rememberScrolledToBottom();
- QWebElement message = document_.findFirst("#" + id);
- if (!message.isNull()) {
- QWebElement replaceContent = message.findFirst("span.swift_inner_message");
- assert(!replaceContent.isNull());
- QString old = replaceContent.toOuterXml();
- replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
- QWebElement replaceTime = message.findFirst("span.swift_time");
- assert(!replaceTime.isNull());
- old = replaceTime.toOuterXml();
- replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime))));
- }
- else {
- qWarning() << "Trying to replace element with id " << id << " but it's not there.";
- }
+ rememberScrolledToBottom();
+ QWebElement message = document_.findFirst("#" + id);
+ if (!message.isNull()) {
+ QWebElement replaceContent = message.findFirst("span.swift_inner_message");
+ assert(!replaceContent.isNull());
+ QString old = replaceContent.toOuterXml();
+ replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
+ QWebElement replaceTime = message.findFirst("span.swift_time");
+ assert(!replaceTime.isNull());
+ old = replaceTime.toOuterXml();
+ replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime))));
+ }
+ else {
+ qWarning() << "Trying to replace element with id " << id << " but it's not there.";
+ }
}
void QtWebKitChatView::showEmoticons(bool show) {
- showEmoticons_ = show;
- {
- const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("display", show ? "inline" : "none");
- }
- }
- {
- const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("display", show ? "none" : "inline");
- }
- }
+ showEmoticons_ = show;
+ {
+ const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image");
+ Q_FOREACH (QWebElement span, spans) {
+ span.setStyleProperty("display", show ? "inline" : "none");
+ }
+ }
+ {
+ const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text");
+ Q_FOREACH (QWebElement span, spans) {
+ span.setStyleProperty("display", show ? "none" : "inline");
+ }
+ }
}
void QtWebKitChatView::copySelectionToClipboard() {
- if (!webPage_->selectedText().isEmpty()) {
- webPage_->triggerAction(QWebPage::Copy);
- }
+ if (!webPage_->selectedText().isEmpty()) {
+ webPage_->triggerAction(QWebPage::Copy);
+ }
}
void QtWebKitChatView::setAckXML(const QString& id, const QString& xml) {
- QWebElement message = document_.findFirst("#" + id);
- /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */
- if (message.isNull()) return;
- QWebElement ackElement = message.findFirst("span.swift_ack");
- assert(!ackElement.isNull());
- ackElement.setInnerXml(xml);
+ QWebElement message = document_.findFirst("#" + id);
+ /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */
+ if (message.isNull()) return;
+ QWebElement ackElement = message.findFirst("span.swift_ack");
+ assert(!ackElement.isNull());
+ ackElement.setInnerXml(xml);
}
void QtWebKitChatView::setReceiptXML(const QString& id, const QString& xml) {
- QWebElement message = document_.findFirst("#" + id);
- if (message.isNull()) return;
- QWebElement receiptElement = message.findFirst("span.swift_receipt");
- assert(!receiptElement.isNull());
- receiptElement.setInnerXml(xml);
+ QWebElement message = document_.findFirst("#" + id);
+ if (message.isNull()) return;
+ QWebElement receiptElement = message.findFirst("span.swift_receipt");
+ assert(!receiptElement.isNull());
+ receiptElement.setInnerXml(xml);
}
void QtWebKitChatView::displayReceiptInfo(const QString& id, bool showIt) {
- QWebElement message = document_.findFirst("#" + id);
- if (message.isNull()) return;
- QWebElement receiptElement = message.findFirst("span.swift_receipt");
- assert(!receiptElement.isNull());
- receiptElement.setStyleProperty("display", showIt ? "inline" : "none");
+ QWebElement message = document_.findFirst("#" + id);
+ if (message.isNull()) return;
+ QWebElement receiptElement = message.findFirst("span.swift_receipt");
+ assert(!receiptElement.isNull());
+ receiptElement.setStyleProperty("display", showIt ? "inline" : "none");
}
void QtWebKitChatView::rememberScrolledToBottom() {
- isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1);
+ isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1);
}
void QtWebKitChatView::scrollToBottom() {
- isAtBottom_ = true;
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
- webView_->update(); /* Work around redraw bug in some versions of Qt. */
+ isAtBottom_ = true;
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical));
+ webView_->update(); /* Work around redraw bug in some versions of Qt. */
}
void QtWebKitChatView::handleFrameSizeChanged() {
- if (topMessageAdded_) {
- // adjust new scrollbar position
- int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical);
- webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_);
- topMessageAdded_ = false;
- }
+ if (topMessageAdded_) {
+ // adjust new scrollbar position
+ int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical);
+ webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_);
+ topMessageAdded_ = false;
+ }
- if (isAtBottom_ && !disableAutoScroll_) {
- scrollToBottom();
- }
+ if (isAtBottom_ && !disableAutoScroll_) {
+ scrollToBottom();
+ }
}
void QtWebKitChatView::handleLinkClicked(const QUrl& url) {
- QDesktopServices::openUrl(url);
+ QDesktopServices::openUrl(url);
}
void QtWebKitChatView::handleViewLoadFinished(bool ok) {
- Q_ASSERT(ok);
- viewReady_ = true;
+ Q_ASSERT(ok);
+ viewReady_ = true;
}
void QtWebKitChatView::increaseFontSize(int numSteps) {
- //qDebug() << "Increasing";
- fontSizeSteps_ += numSteps;
- emit fontResized(fontSizeSteps_);
+ //qDebug() << "Increasing";
+ fontSizeSteps_ += numSteps;
+ emit fontResized(fontSizeSteps_);
}
void QtWebKitChatView::decreaseFontSize() {
- fontSizeSteps_--;
- if (fontSizeSteps_ < 0) {
- fontSizeSteps_ = 0;
- }
- emit fontResized(fontSizeSteps_);
+ fontSizeSteps_--;
+ if (fontSizeSteps_ < 0) {
+ fontSizeSteps_ = 0;
+ }
+ emit fontResized(fontSizeSteps_);
}
void QtWebKitChatView::resizeFont(int fontSizeSteps) {
- fontSizeSteps_ = fontSizeSteps;
- double size = 1.0 + 0.2 * fontSizeSteps_;
- QString sizeString(QString().setNum(size, 'g', 3) + "em");
+ fontSizeSteps_ = fontSizeSteps;
+ double size = 1.0 + 0.2 * fontSizeSteps_;
+ QString sizeString(QString().setNum(size, 'g', 3) + "em");
- // Set the font size in the <style id="text-resize-style"> element in the theme <head> element.
- QWebElement resizableTextStyle = document_.findFirst("style#text-resize-style");
- assert(!resizableTextStyle.isNull());
- resizableTextStyle.setInnerXml(QString("span.swift_resizable { font-size: %1;}").arg(sizeString));
- webView_->setFontSizeIsMinimal(size == 1.0);
+ // Set the font size in the <style id="text-resize-style"> element in the theme <head> element.
+ QWebElement resizableTextStyle = document_.findFirst("style#text-resize-style");
+ assert(!resizableTextStyle.isNull());
+ resizableTextStyle.setInnerXml(QString("span.swift_resizable { font-size: %1;}").arg(sizeString));
+ webView_->setFontSizeIsMinimal(size == 1.0);
}
void QtWebKitChatView::resetView() {
- lastElement_ = QWebElement();
- firstElement_ = lastElement_;
- topMessageAdded_ = false;
- scrollBarMaximum_ = 0;
- QString pageHTML = theme_->getTemplate();
- pageHTML.replace("==bodyBackground==", "background-color:#e3e3e3");
- pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getBase());
- if (pageHTML.count("%@") > 3) {
- pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getMainCSS());
- }
- pageHTML.replace(pageHTML.indexOf("%@"), 2, "Variants/Blue on Green.css");
- pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*headerSnippet.getContent()*/);
- pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*footerSnippet.getContent()*/);
- QEventLoop syncLoop;
- connect(webView_, SIGNAL(loadFinished(bool)), &syncLoop, SLOT(quit()));
- webPage_->mainFrame()->setHtml(pageHTML);
- while (!viewReady_) {
- QTimer t;
- t.setSingleShot(true);
- connect(&t, SIGNAL(timeout()), &syncLoop, SLOT(quit()));
- t.start(50);
- syncLoop.exec();
- }
- document_ = webPage_->mainFrame()->documentElement();
-
- scrollToBottom();
-
- connect(webPage_->mainFrame(), SIGNAL(contentsSizeChanged(const QSize&)), this, SLOT(handleFrameSizeChanged()), Qt::UniqueConnection);
+ lastElement_ = QWebElement();
+ firstElement_ = lastElement_;
+ topMessageAdded_ = false;
+ scrollBarMaximum_ = 0;
+ QString pageHTML = theme_->getTemplate();
+ pageHTML.replace("==bodyBackground==", "background-color:#e3e3e3");
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getBase());
+ if (pageHTML.count("%@") > 3) {
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, theme_->getMainCSS());
+ }
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, "Variants/Blue on Green.css");
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*headerSnippet.getContent()*/);
+ pageHTML.replace(pageHTML.indexOf("%@"), 2, ""/*footerSnippet.getContent()*/);
+ QEventLoop syncLoop;
+ connect(webView_, SIGNAL(loadFinished(bool)), &syncLoop, SLOT(quit()));
+ webPage_->mainFrame()->setHtml(pageHTML);
+ while (!viewReady_) {
+ QTimer t;
+ t.setSingleShot(true);
+ connect(&t, SIGNAL(timeout()), &syncLoop, SLOT(quit()));
+ t.start(50);
+ syncLoop.exec();
+ }
+ document_ = webPage_->mainFrame()->documentElement();
+
+ scrollToBottom();
+
+ connect(webPage_->mainFrame(), SIGNAL(contentsSizeChanged(const QSize&)), this, SLOT(handleFrameSizeChanged()), Qt::UniqueConnection);
}
static QWebElement findElementWithID(QWebElement document, QString elementName, QString id) {
- QWebElementCollection elements = document.findAll(elementName);
- Q_FOREACH(QWebElement element, elements) {
- if (element.attribute("id") == id) {
- return element;
- }
- }
- return QWebElement();
+ QWebElementCollection elements = document.findAll(elementName);
+ Q_FOREACH(QWebElement element, elements) {
+ if (element.attribute("id") == id) {
+ return element;
+ }
+ }
+ return QWebElement();
}
void QtWebKitChatView::setFileTransferProgress(QString id, const int percentageDone) {
- rememberScrolledToBottom();
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!" << std::endl;
- return;
- }
- QWebElement progressBar = ftElement.findFirst("div.progressbar");
- progressBar.setStyleProperty("width", QString::number(percentageDone) + "%");
+ rememberScrolledToBottom();
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!" << std::endl;
+ return;
+ }
+ QWebElement progressBar = ftElement.findFirst("div.progressbar");
+ progressBar.setStyleProperty("width", QString::number(percentageDone) + "%");
- QWebElement progressBarValue = ftElement.findFirst("div.progressbar-value");
- progressBarValue.setInnerXml(QString::number(percentageDone) + " %");
+ QWebElement progressBarValue = ftElement.findFirst("div.progressbar-value");
+ progressBarValue.setInnerXml(QString::number(percentageDone) + " %");
}
void QtWebKitChatView::setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& /* msg */) {
- rememberScrolledToBottom();
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
-
- QString newInnerHTML = "";
- if (state == ChatWindow::Initialisation) {
- QWebElement filenameSizeDescriptionElement = ftElement.parent().firstChild();
- QString description = QtUtilities::htmlEscape(descriptions_[id]);
- if (!description.isEmpty()) {
- filenameSizeDescriptionElement.prependOutside(QString(" \"%1\"").arg(description));
- }
- newInnerHTML = tr("Preparing to transfer.") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::WaitingForAccept) {
- newInnerHTML = tr("Waiting for other side to accept the transfer.") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Negotiating) {
- // replace with text "Negotiaging" + Cancel button
- newInnerHTML = tr("Negotiating...") + "<br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Transferring) {
- // progress bar + Cancel Button
- newInnerHTML = "<div style=\"position: relative; width: 90%; height: 20px; border: 2px solid grey; -webkit-border-radius: 10px;\">"
- "<div class=\"progressbar\" style=\"width: 0%; height: 100%; background: #AAA; -webkit-border-radius: 6px;\">"
- "<div class=\"progressbar-value\" style=\"position: absolute; top: 0px; left: 0px; width: 100%; text-align: center; padding-top: 2px;\">"
- "0%"
- "</div>"
- "</div>"
- "</div>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
- }
- else if (state == ChatWindow::Canceled) {
- newInnerHTML = tr("Transfer has been canceled!");
- }
- else if (state == ChatWindow::Finished) {
- // text "Successful transfer"
- newInnerHTML = tr("Transfer completed successfully." ) + " " + buildChatWindowButton(tr("Open file"), ButtonFileTransferOpenFile, id, filePaths_[id]);
- filePaths_.erase(id);
- }
- else if (state == ChatWindow::FTFailed) {
- newInnerHTML = tr("Transfer failed.");
- }
-
- ftElement.setInnerXml(newInnerHTML);
+ rememberScrolledToBottom();
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
+
+ QString newInnerHTML = "";
+ if (state == ChatWindow::Initialisation) {
+ QWebElement filenameSizeDescriptionElement = ftElement.parent().firstChild();
+ QString description = QtUtilities::htmlEscape(descriptions_[id]);
+ if (!description.isEmpty()) {
+ filenameSizeDescriptionElement.prependOutside(QString(" \"%1\"").arg(description));
+ }
+ newInnerHTML = tr("Preparing to transfer.") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::WaitingForAccept) {
+ newInnerHTML = tr("Waiting for other side to accept the transfer.") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Negotiating) {
+ // replace with text "Negotiaging" + Cancel button
+ newInnerHTML = tr("Negotiating...") + "<br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Transferring) {
+ // progress bar + Cancel Button
+ newInnerHTML = "<div style=\"position: relative; width: 90%; height: 20px; border: 2px solid grey; -webkit-border-radius: 10px;\">"
+ "<div class=\"progressbar\" style=\"width: 0%; height: 100%; background: #AAA; -webkit-border-radius: 6px;\">"
+ "<div class=\"progressbar-value\" style=\"position: absolute; top: 0px; left: 0px; width: 100%; text-align: center; padding-top: 2px;\">"
+ "0%"
+ "</div>"
+ "</div>"
+ "</div>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, id);
+ }
+ else if (state == ChatWindow::Canceled) {
+ newInnerHTML = tr("Transfer has been canceled!");
+ }
+ else if (state == ChatWindow::Finished) {
+ // text "Successful transfer"
+ newInnerHTML = tr("Transfer completed successfully." ) + " " + buildChatWindowButton(tr("Open file"), ButtonFileTransferOpenFile, id, filePaths_[id]);
+ filePaths_.erase(id);
+ }
+ else if (state == ChatWindow::FTFailed) {
+ newInnerHTML = tr("Transfer failed.");
+ }
+
+ ftElement.setInnerXml(newInnerHTML);
}
void QtWebKitChatView::setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state) {
- QWebElement divElement = findElementWithID(document_, "div", id);
- QString newInnerHTML;
- if (state == ChatWindow::WhiteboardAccepted) {
- newInnerHTML = tr("Started whiteboard chat") + "<br/>" + buildChatWindowButton(tr("Show whiteboard"), ButtonWhiteboardShowWindow, id);
- } else if (state == ChatWindow::WhiteboardTerminated) {
- newInnerHTML = tr("Whiteboard chat has been canceled");
- } else if (state == ChatWindow::WhiteboardRejected) {
- newInnerHTML = tr("Whiteboard chat request has been rejected");
- }
- divElement.setInnerXml(newInnerHTML);
+ QWebElement divElement = findElementWithID(document_, "div", id);
+ QString newInnerHTML;
+ if (state == ChatWindow::WhiteboardAccepted) {
+ newInnerHTML = tr("Started whiteboard chat") + "<br/>" + buildChatWindowButton(tr("Show whiteboard"), ButtonWhiteboardShowWindow, id);
+ } else if (state == ChatWindow::WhiteboardTerminated) {
+ newInnerHTML = tr("Whiteboard chat has been canceled");
+ } else if (state == ChatWindow::WhiteboardRejected) {
+ newInnerHTML = tr("Whiteboard chat request has been rejected");
+ }
+ divElement.setInnerXml(newInnerHTML);
}
void QtWebKitChatView::setMUCInvitationJoined(QString id) {
- QWebElement divElement = findElementWithID(document_, "div", id);
- QWebElement buttonElement = findElementWithID(divElement, "input", "mucinvite");
- if (!buttonElement.isNull()) {
- buttonElement.setAttribute("value", tr("Return to room"));
- }
+ QWebElement divElement = findElementWithID(document_, "div", id);
+ QWebElement buttonElement = findElementWithID(divElement, "input", "mucinvite");
+ if (!buttonElement.isNull()) {
+ buttonElement.setAttribute("value", tr("Return to room"));
+ }
}
void QtWebKitChatView::askDesktopToOpenFile(const QString& filename) {
- QFileInfo fileInfo(filename);
- if (fileInfo.exists() && fileInfo.isFile()) {
- QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
- }
+ QFileInfo fileInfo(filename);
+ if (fileInfo.exists() && fileInfo.isFile()) {
+ QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
+ }
}
void QtWebKitChatView::handleScrollRequested(int, int dy, const QRect&) {
- rememberScrolledToBottom();
+ rememberScrolledToBottom();
- int pos = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) - dy;
- emit scrollRequested(pos);
+ int pos = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) - dy;
+ emit scrollRequested(pos);
- if (pos == 0) {
- emit scrollReachedTop();
- }
- else if (pos == webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)) {
- emit scrollReachedBottom();
- }
+ if (pos == 0) {
+ emit scrollReachedTop();
+ }
+ else if (pos == webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)) {
+ emit scrollReachedBottom();
+ }
}
int QtWebKitChatView::getSnippetPositionByDate(const QDate& date) {
- QWebElement message = webPage_->mainFrame()->documentElement().findFirst(".date" + date.toString(Qt::ISODate));
+ QWebElement message = webPage_->mainFrame()->documentElement().findFirst(".date" + date.toString(Qt::ISODate));
- return message.geometry().top();
+ return message.geometry().top();
}
void QtWebKitChatView::resetTopInsertPoint() {
- // TODO: Implement or refactor later.
- assert(false);
+ // TODO: Implement or refactor later.
+ assert(false);
}
std::string QtWebKitChatView::addMessage(
- const ChatWindow::ChatMessage& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::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));
+ const ChatWindow::ChatMessage& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::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 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());
+ return getHighlightSpanStart(highlight.getTextColor(), highlight.getTextBackground());
}
QString QtWebKitChatView::chatMessageToHTML(const ChatWindow::ChatMessage& message) {
- QString result;
- foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
- boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
- boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
- boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
-
- if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
- QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
- text.replace("\n","<br/>");
- result += text;
- continue;
- }
- if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
- QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
- result += "<a href='" + uri + "' >" + uri + "</a>";
- continue;
- }
- if ((emoticonPart = boost::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 = boost::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;
+ QString result;
+ foreach (boost::shared_ptr<ChatWindow::ChatMessagePart> part, message.getParts()) {
+ boost::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ boost::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ boost::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = boost::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = boost::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = boost::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 = boost::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;
}
std::string QtWebKitChatView::addMessage(
- const QString& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::shared_ptr<SecurityLabel> label,
- const std::string& avatarPath,
- const QString& style,
- const boost::posix_time::ptime& time,
- const HighlightAction& highlight,
- ChatSnippet::Direction direction) {
+ const QString& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const QString& style,
+ const boost::posix_time::ptime& time,
+ const HighlightAction& highlight,
+ ChatSnippet::Direction direction) {
- QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
+ QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str());
- QString htmlString;
- if (label) {
- htmlString = QString("<span style=\"border: thin dashed grey; padding-left: .5em; padding-right: .5em; color: %1; background-color: %2; font-size: 90%; margin-right: .5em; \" class='swift_label'>").arg(QtUtilities::htmlEscape(P2QSTRING(label->getForegroundColor()))).arg(QtUtilities::htmlEscape(P2QSTRING(label->getBackgroundColor())));
- htmlString += QString("%1</span> ").arg(QtUtilities::htmlEscape(P2QSTRING(label->getDisplayMarking())));
- }
+ QString htmlString;
+ if (label) {
+ htmlString = QString("<span style=\"border: thin dashed grey; padding-left: .5em; padding-right: .5em; color: %1; background-color: %2; font-size: 90%; margin-right: .5em; \" class='swift_label'>").arg(QtUtilities::htmlEscape(P2QSTRING(label->getForegroundColor()))).arg(QtUtilities::htmlEscape(P2QSTRING(label->getBackgroundColor())));
+ htmlString += QString("%1</span> ").arg(QtUtilities::htmlEscape(P2QSTRING(label->getDisplayMarking())));
+ }
- QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
- QString styleSpanEnd = style == "" ? "" : "</span>";
+ QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
+ QString styleSpanEnd = style == "" ? "" : "</span>";
- bool highlightWholeMessage = highlight.highlightWholeMessage() && highlight.getTextBackground() != "" && highlight.getTextColor() != "";
- QString highlightSpanStart = highlightWholeMessage ? getHighlightSpanStart(highlight) : "";
- QString highlightSpanEnd = highlightWholeMessage ? "</span>" : "";
- htmlString += "<span class='swift_inner_message'>" + styleSpanStart + highlightSpanStart + message + highlightSpanEnd + styleSpanEnd + "</span>" ;
+ bool highlightWholeMessage = highlight.highlightWholeMessage() && highlight.getTextBackground() != "" && highlight.getTextColor() != "";
+ QString highlightSpanStart = highlightWholeMessage ? getHighlightSpanStart(highlight) : "";
+ QString highlightSpanEnd = highlightWholeMessage ? "</span>" : "";
+ htmlString += "<span class='swift_inner_message'>" + styleSpanStart + highlightSpanStart + message + highlightSpanEnd + styleSpanEnd + "</span>" ;
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMessage, senderName, senderIsSelf);
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMessage, senderName, senderIsSelf);
- QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(time), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), direction));
+ QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(time), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), direction));
- previousMessageWasSelf_ = senderIsSelf;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasMessage;
- return id;
+ previousMessageWasSelf_ = senderIsSelf;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasMessage;
+ return id;
}
std::string QtWebKitChatView::addAction(const ChatWindow::ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
- return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "font-style:italic ", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
+ return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "font-style:italic ", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
}
static QString encodeButtonArgument(const QString& str) {
- return QtUtilities::htmlEscape(P2QSTRING(Base64::encode(createByteArray(Q2PSTRING(str)))));
+ return QtUtilities::htmlEscape(P2QSTRING(Base64::encode(createByteArray(Q2PSTRING(str)))));
}
static QString decodeButtonArgument(const QString& str) {
- return P2QSTRING(byteArrayToString(Base64::decode(Q2PSTRING(str))));
+ return P2QSTRING(byteArrayToString(Base64::decode(Q2PSTRING(str))));
}
QString QtWebKitChatView::buildChatWindowButton(const QString& name, const QString& id, const QString& arg1, const QString& arg2, const QString& arg3, const QString& arg4, const QString& arg5) {
- QRegExp regex("[A-Za-z][A-Za-z0-9\\-\\_]+");
- Q_ASSERT(regex.exactMatch(id));
- QString html = QString("<input id='%2' type='submit' value='%1' onclick='chatwindow.buttonClicked(\"%2\", \"%3\", \"%4\", \"%5\", \"%6\", \"%7\");' />").arg(name).arg(id).arg(encodeButtonArgument(arg1)).arg(encodeButtonArgument(arg2)).arg(encodeButtonArgument(arg3)).arg(encodeButtonArgument(arg4)).arg(encodeButtonArgument(arg5));
- return html;
+ QRegExp regex("[A-Za-z][A-Za-z0-9\\-\\_]+");
+ Q_ASSERT(regex.exactMatch(id));
+ QString html = QString("<input id='%2' type='submit' value='%1' onclick='chatwindow.buttonClicked(\"%2\", \"%3\", \"%4\", \"%5\", \"%6\", \"%7\");' />").arg(name).arg(id).arg(encodeButtonArgument(arg1)).arg(encodeButtonArgument(arg2)).arg(encodeButtonArgument(arg3)).arg(encodeButtonArgument(arg4)).arg(encodeButtonArgument(arg5));
+ return html;
}
std::string QtWebKitChatView::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) {
- SWIFT_LOG(debug) << "addFileTransfer" << std::endl;
- QString ft_id = QString("ft%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
-
- QString actionText;
- QString htmlString;
- QString formattedFileSize = P2QSTRING(formatSize(sizeInBytes));
- QString sanitizedFileName = QtUtilities::htmlEscape(P2QSTRING(filename));
- QString sanitizedDescription = QtUtilities::htmlEscape(P2QSTRING(description));
- if (senderIsSelf) {
- // outgoing
- filePaths_[ft_id] = sanitizedFileName;
- actionText = tr("Send file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
- htmlString = actionText + " <br/>" +
- "<div id='" + ft_id + "'>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
- buildChatWindowButton(tr("Set Description"), ButtonFileTransferSetDescription, ft_id) +
- buildChatWindowButton(tr("Send"), ButtonFileTransferSendRequest, ft_id) +
- "</div>";
- } else {
- // incoming
- actionText = tr("Receiving file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
- if (!sanitizedDescription.isEmpty()) {
- actionText += QString(" \"%1\"").arg(sanitizedDescription);
- }
- htmlString = actionText + " <br/>" +
- "<div id='" + ft_id + "'>" +
- buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
- buildChatWindowButton(tr("Accept"), ButtonFileTransferAcceptRequest, ft_id, P2QSTRING(filename)) +
- "</div>";
- }
-
- //addMessage(message, senderName, senderIsSelf, boost::shared_ptr<SecurityLabel>(), "", boost::posix_time::second_clock::local_time());
-
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasFileTransfer, senderName, senderIsSelf);
-
- QString qAvatarPath = "qrc:/icons/avatar.png";
- std::string id = "ftmessage" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
-
- previousMessageWasSelf_ = senderIsSelf;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasFileTransfer;
- return Q2PSTRING(ft_id);
+ SWIFT_LOG(debug) << "addFileTransfer" << std::endl;
+ QString ft_id = QString("ft%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+
+ QString actionText;
+ QString htmlString;
+ QString formattedFileSize = P2QSTRING(formatSize(sizeInBytes));
+ QString sanitizedFileName = QtUtilities::htmlEscape(P2QSTRING(filename));
+ QString sanitizedDescription = QtUtilities::htmlEscape(P2QSTRING(description));
+ if (senderIsSelf) {
+ // outgoing
+ filePaths_[ft_id] = sanitizedFileName;
+ actionText = tr("Send file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
+ htmlString = actionText + " <br/>" +
+ "<div id='" + ft_id + "'>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
+ buildChatWindowButton(tr("Set Description"), ButtonFileTransferSetDescription, ft_id) +
+ buildChatWindowButton(tr("Send"), ButtonFileTransferSendRequest, ft_id) +
+ "</div>";
+ } else {
+ // incoming
+ actionText = tr("Receiving file: %1 (%2)").arg(sanitizedFileName).arg(formattedFileSize);
+ if (!sanitizedDescription.isEmpty()) {
+ actionText += QString(" \"%1\"").arg(sanitizedDescription);
+ }
+ htmlString = actionText + " <br/>" +
+ "<div id='" + ft_id + "'>" +
+ buildChatWindowButton(tr("Cancel"), ButtonFileTransferCancel, ft_id) +
+ buildChatWindowButton(tr("Accept"), ButtonFileTransferAcceptRequest, ft_id, P2QSTRING(filename)) +
+ "</div>";
+ }
+
+ //addMessage(message, senderName, senderIsSelf, boost::shared_ptr<SecurityLabel>(), "", boost::posix_time::second_clock::local_time());
+
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasFileTransfer, senderName, senderIsSelf);
+
+ QString qAvatarPath = "qrc:/icons/avatar.png";
+ std::string id = "ftmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
+
+ previousMessageWasSelf_ = senderIsSelf;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasFileTransfer;
+ return Q2PSTRING(ft_id);
}
void QtWebKitChatView::setFileTransferProgress(std::string id, const int percentageDone) {
- setFileTransferProgress(P2QSTRING(id), percentageDone);
+ setFileTransferProgress(P2QSTRING(id), percentageDone);
}
void QtWebKitChatView::setFileTransferStatus(std::string id, const ChatWindow::FileTransferState state, const std::string& msg) {
- setFileTransferStatus(P2QSTRING(id), state, P2QSTRING(msg));
+ setFileTransferStatus(P2QSTRING(id), state, P2QSTRING(msg));
}
std::string QtWebKitChatView::addWhiteboardRequest(const QString& contact, bool senderIsSelf) {
- QString wb_id = QString("wb%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
- QString htmlString;
- QString actionText;
- if (senderIsSelf) {
- actionText = tr("Starting whiteboard chat");
- htmlString = "<div id='" + wb_id + "'>" + actionText + "<br />"+
- buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
- "</div>";
- } else {
- actionText = tr("%1 would like to start a whiteboard chat");
- htmlString = "<div id='" + wb_id + "'>" + actionText.arg(QtUtilities::htmlEscape(contact)) + ": <br/>" +
- buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
- buildChatWindowButton(tr("Accept"), ButtonWhiteboardSessionAcceptRequest, wb_id) +
- "</div>";
- }
- QString qAvatarPath = "qrc:/icons/avatar.png";
- std::string id = "wbmessage" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(contact), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, false, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
- previousMessageWasSelf_ = false;
- previousSenderName_ = contact;
- return Q2PSTRING(wb_id);
+ QString wb_id = QString("wb%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+ QString htmlString;
+ QString actionText;
+ if (senderIsSelf) {
+ actionText = tr("Starting whiteboard chat");
+ htmlString = "<div id='" + wb_id + "'>" + actionText + "<br />"+
+ buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
+ "</div>";
+ } else {
+ actionText = tr("%1 would like to start a whiteboard chat");
+ htmlString = "<div id='" + wb_id + "'>" + actionText.arg(QtUtilities::htmlEscape(contact)) + ": <br/>" +
+ buildChatWindowButton(tr("Cancel"), ButtonWhiteboardSessionCancel, wb_id) +
+ buildChatWindowButton(tr("Accept"), ButtonWhiteboardSessionAcceptRequest, wb_id) +
+ "</div>";
+ }
+ QString qAvatarPath = "qrc:/icons/avatar.png";
+ std::string id = "wbmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(contact), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, false, theme_, P2QSTRING(id), ChatSnippet::getDirection(actionText)));
+ previousMessageWasSelf_ = false;
+ previousSenderName_ = contact;
+ return Q2PSTRING(wb_id);
}
void QtWebKitChatView::setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) {
- setWhiteboardSessionStatus(P2QSTRING(id), state);
+ setWhiteboardSessionStatus(P2QSTRING(id), state);
}
static bool isFilePathWritable(const QString& path) {
- QFileInfo fileInfo = QFileInfo(path);
- if (fileInfo.exists()) {
- return fileInfo.isWritable();
- }
- else {
- bool writable = false;
- QFile writeTestFile(path);
- if (writeTestFile.open(QIODevice::ReadWrite)) {
- writeTestFile.write("test");
- if (writeTestFile.error() == QFileDevice::NoError) {
- writable = true;
- }
- }
- writeTestFile.close();
- writeTestFile.remove();
- return writable;
- }
+ QFileInfo fileInfo = QFileInfo(path);
+ if (fileInfo.exists()) {
+ return fileInfo.isWritable();
+ }
+ else {
+ bool writable = false;
+ QFile writeTestFile(path);
+ if (writeTestFile.open(QIODevice::ReadWrite)) {
+ writeTestFile.write("test");
+ if (writeTestFile.error() == QFileDevice::NoError) {
+ writable = true;
+ }
+ }
+ writeTestFile.close();
+ writeTestFile.remove();
+ return writable;
+ }
}
void QtWebKitChatView::setFileTransferWarning(QString id, QString warningText) {
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
- removeFileTransferWarning(id);
- ftElement.appendInside(QString("<div class='ft_warning' style='color: red;'><br/>%1</div>").arg(QtUtilities::htmlEscape(warningText)));
+ removeFileTransferWarning(id);
+ ftElement.appendInside(QString("<div class='ft_warning' style='color: red;'><br/>%1</div>").arg(QtUtilities::htmlEscape(warningText)));
}
void QtWebKitChatView::removeFileTransferWarning(QString id) {
- QWebElement ftElement = findElementWithID(document_, "div", id);
- if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
- return;
- }
+ QWebElement ftElement = findElementWithID(document_, "div", id);
+ if (ftElement.isNull()) {
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ return;
+ }
- QWebElement warningElement = ftElement.findFirst(".ft_warning");
- if (!warningElement.isNull()) {
- warningElement.removeFromDocument();
- }
+ QWebElement warningElement = ftElement.findFirst(".ft_warning");
+ if (!warningElement.isNull()) {
+ warningElement.removeFromDocument();
+ }
}
void QtWebKitChatView::handleHTMLButtonClicked(QString id, QString encodedArgument1, QString encodedArgument2, QString encodedArgument3, QString encodedArgument4, QString encodedArgument5) {
- QString arg1 = decodeButtonArgument(encodedArgument1);
- QString arg2 = decodeButtonArgument(encodedArgument2);
- QString arg3 = decodeButtonArgument(encodedArgument3);
- QString arg4 = decodeButtonArgument(encodedArgument4);
- QString arg5 = decodeButtonArgument(encodedArgument5);
-
- if (id.startsWith(ButtonFileTransferCancel)) {
- QString ft_id = arg1;
- window_->onFileTransferCancel(Q2PSTRING(ft_id));
- }
- else if (id.startsWith(ButtonFileTransferSetDescription)) {
- QString ft_id = arg1;
- bool ok = false;
- QString text = QInputDialog::getText(this, tr("File transfer description"),
- tr("Description:"), QLineEdit::Normal, "", &ok);
- if (ok) {
- descriptions_[ft_id] = text;
- }
- }
- else if (id.startsWith(ButtonFileTransferSendRequest)) {
- QString ft_id = arg1;
- QString text = descriptions_.find(ft_id) == descriptions_.end() ? QString() : descriptions_[ft_id];
- window_->onFileTransferStart(Q2PSTRING(ft_id), Q2PSTRING(text));
- }
- else if (id.startsWith(ButtonFileTransferAcceptRequest)) {
- QString ft_id = arg1;
- QString filename = arg2;
-
- QString path = QFileDialog::getSaveFileName(this, tr("Save File"), filename);
- if (!path.isEmpty() && isFilePathWritable(path)) {
- filePaths_[ft_id] = path;
- window_->onFileTransferAccept(Q2PSTRING(ft_id), Q2PSTRING(path));
- removeFileTransferWarning(ft_id);
- }
- else {
- setFileTransferWarning(ft_id, tr("The chosen save location is not writable! Click the 'Accept' button to select a different save location."));
- }
- }
- else if (id.startsWith(ButtonFileTransferOpenFile)) {
- QString ft_id = arg1;
- QString filename = arg2;
- askDesktopToOpenFile(filename);
- }
- else if (id.startsWith(ButtonWhiteboardSessionAcceptRequest)) {
- QString id = arg1;
- setWhiteboardSessionStatus(id, ChatWindow::WhiteboardAccepted);
- window_->onWhiteboardSessionAccept();
- }
- else if (id.startsWith(ButtonWhiteboardSessionCancel)) {
- QString id = arg1;
- setWhiteboardSessionStatus(id, ChatWindow::WhiteboardTerminated);
- window_->onWhiteboardSessionCancel();
- }
- else if (id.startsWith(ButtonWhiteboardShowWindow)) {
- QString id = arg1;
- window_->onWhiteboardWindowShow();
- }
- else if (id.startsWith(ButtonMUCInvite)) {
- QString roomJID = arg1;
- QString password = arg2;
- QString elementID = arg3;
- QString isImpromptu = arg4;
- QString isContinuation = arg5;
- eventStream_->send(boost::make_shared<JoinMUCUIEvent>(Q2PSTRING(roomJID), Q2PSTRING(password), boost::optional<std::string>(), false, false, isImpromptu.contains("true"), isContinuation.contains("true")));
- setMUCInvitationJoined(elementID);
- }
- else {
- SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )" << std::endl;
- }
+ QString arg1 = decodeButtonArgument(encodedArgument1);
+ QString arg2 = decodeButtonArgument(encodedArgument2);
+ QString arg3 = decodeButtonArgument(encodedArgument3);
+ QString arg4 = decodeButtonArgument(encodedArgument4);
+ QString arg5 = decodeButtonArgument(encodedArgument5);
+
+ if (id.startsWith(ButtonFileTransferCancel)) {
+ QString ft_id = arg1;
+ window_->onFileTransferCancel(Q2PSTRING(ft_id));
+ }
+ else if (id.startsWith(ButtonFileTransferSetDescription)) {
+ QString ft_id = arg1;
+ bool ok = false;
+ QString text = QInputDialog::getText(this, tr("File transfer description"),
+ tr("Description:"), QLineEdit::Normal, "", &ok);
+ if (ok) {
+ descriptions_[ft_id] = text;
+ }
+ }
+ else if (id.startsWith(ButtonFileTransferSendRequest)) {
+ QString ft_id = arg1;
+ QString text = descriptions_.find(ft_id) == descriptions_.end() ? QString() : descriptions_[ft_id];
+ window_->onFileTransferStart(Q2PSTRING(ft_id), Q2PSTRING(text));
+ }
+ else if (id.startsWith(ButtonFileTransferAcceptRequest)) {
+ QString ft_id = arg1;
+ QString filename = arg2;
+
+ QString path = QFileDialog::getSaveFileName(this, tr("Save File"), filename);
+ if (!path.isEmpty() && isFilePathWritable(path)) {
+ filePaths_[ft_id] = path;
+ window_->onFileTransferAccept(Q2PSTRING(ft_id), Q2PSTRING(path));
+ removeFileTransferWarning(ft_id);
+ }
+ else {
+ setFileTransferWarning(ft_id, tr("The chosen save location is not writable! Click the 'Accept' button to select a different save location."));
+ }
+ }
+ else if (id.startsWith(ButtonFileTransferOpenFile)) {
+ QString ft_id = arg1;
+ QString filename = arg2;
+ askDesktopToOpenFile(filename);
+ }
+ else if (id.startsWith(ButtonWhiteboardSessionAcceptRequest)) {
+ QString id = arg1;
+ setWhiteboardSessionStatus(id, ChatWindow::WhiteboardAccepted);
+ window_->onWhiteboardSessionAccept();
+ }
+ else if (id.startsWith(ButtonWhiteboardSessionCancel)) {
+ QString id = arg1;
+ setWhiteboardSessionStatus(id, ChatWindow::WhiteboardTerminated);
+ window_->onWhiteboardSessionCancel();
+ }
+ else if (id.startsWith(ButtonWhiteboardShowWindow)) {
+ QString id = arg1;
+ window_->onWhiteboardWindowShow();
+ }
+ else if (id.startsWith(ButtonMUCInvite)) {
+ QString roomJID = arg1;
+ QString password = arg2;
+ QString elementID = arg3;
+ QString isImpromptu = arg4;
+ QString isContinuation = arg5;
+ eventStream_->send(boost::make_shared<JoinMUCUIEvent>(Q2PSTRING(roomJID), Q2PSTRING(password), boost::optional<std::string>(), false, false, isImpromptu.contains("true"), isContinuation.contains("true")));
+ setMUCInvitationJoined(elementID);
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )" << std::endl;
+ }
}
void QtWebKitChatView::addErrorMessage(const ChatWindow::ChatMessage& errorMessage) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString errorMessageHTML(chatMessageToHTML(errorMessage));
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>("<span class=\"error\">" + errorMessageHTML + "</span>", QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), ChatSnippet::getDirection(errorMessage)));
+ QString errorMessageHTML(chatMessageToHTML(errorMessage));
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>("<span class=\"error\">" + errorMessageHTML + "</span>", QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), ChatSnippet::getDirection(errorMessage)));
- previousMessageWasSelf_ = false;
- previousMessageKind_ = PreviousMessageWasSystem;
+ previousMessageWasSelf_ = false;
+ previousMessageKind_ = PreviousMessageWasSystem;
}
std::string QtWebKitChatView::addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML = chatMessageToHTML(message);
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
+ QString messageHTML = chatMessageToHTML(message);
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
- previousMessageKind_ = PreviousMessageWasSystem;
- return id;
+ previousMessageKind_ = PreviousMessageWasSystem;
+ return id;
}
void QtWebKitChatView::replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- replaceMessage(" *" + chatMessageToHTML(message) + "*", id, time, "font-style:italic ", message.getFullMessageHighlightAction());
+ replaceMessage(" *" + chatMessageToHTML(message) + "*", id, time, "font-style:italic ", message.getFullMessageHighlightAction());
}
void QtWebKitChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
- replaceMessage(chatMessageToHTML(message), id, time, "", message.getFullMessageHighlightAction());
+ replaceMessage(chatMessageToHTML(message), id, time, "", message.getFullMessageHighlightAction());
}
void QtWebKitChatView::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehavior) {
- replaceSystemMessage(chatMessageToHTML(message), P2QSTRING(id), timestampBehavior);
+ replaceSystemMessage(chatMessageToHTML(message), P2QSTRING(id), timestampBehavior);
}
void QtWebKitChatView::replaceSystemMessage(const QString& newMessage, const QString& id, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- rememberScrolledToBottom();
- QWebElement message = document_.findFirst("#" + id);
- if (!message.isNull()) {
- QWebElement replaceContent = message.findFirst("span.swift_message");
- assert(!replaceContent.isNull());
- QString old = replaceContent.toOuterXml();
- replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
-
- if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
- QWebElement replace = message.findFirst("span.swift_time");
- assert(!replace.isNull());
- replace.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
- }
- }
- else {
- qWarning() << "Trying to replace element with id " << id << " but it's not there.";
- }
+ rememberScrolledToBottom();
+ QWebElement message = document_.findFirst("#" + id);
+ if (!message.isNull()) {
+ QWebElement replaceContent = message.findFirst("span.swift_message");
+ assert(!replaceContent.isNull());
+ QString old = replaceContent.toOuterXml();
+ replaceContent.setInnerXml(ChatSnippet::escape(newMessage));
+
+ if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
+ QWebElement replace = message.findFirst("span.swift_time");
+ assert(!replace.isNull());
+ replace.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
+ }
+ }
+ else {
+ qWarning() << "Trying to replace element with id " << id << " but it's not there.";
+ }
}
void QtWebKitChatView::replaceMessage(const QString& message, const std::string& id, const boost::posix_time::ptime& time, const QString& style, const HighlightAction& highlight) {
- if (!id.empty()) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (!id.empty()) {
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML(message);
+ QString messageHTML(message);
- QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
- QString styleSpanEnd = style == "" ? "" : "</span>";
- QString highlightSpanStart = highlight.highlightWholeMessage() ? getHighlightSpanStart(highlight) : "";
- QString highlightSpanEnd = highlight.highlightWholeMessage() ? "</span>" : "";
- messageHTML = styleSpanStart + highlightSpanStart + messageHTML + highlightSpanEnd + styleSpanEnd;
+ QString styleSpanStart = style == "" ? "" : "<span style=\"" + style + "\">";
+ QString styleSpanEnd = style == "" ? "" : "</span>";
+ QString highlightSpanStart = highlight.highlightWholeMessage() ? getHighlightSpanStart(highlight) : "";
+ QString highlightSpanEnd = highlight.highlightWholeMessage() ? "</span>" : "";
+ messageHTML = styleSpanStart + highlightSpanStart + messageHTML + highlightSpanEnd + styleSpanEnd;
- replaceMessage(messageHTML, P2QSTRING(id), B2QDATE(time));
- }
- else {
- std::cerr << "Trying to replace a message with no id";
- }
+ replaceMessage(messageHTML, P2QSTRING(id), B2QDATE(time));
+ }
+ else {
+ std::cerr << "Trying to replace a message with no id";
+ }
}
void QtWebKitChatView::addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString messageHTML = chatMessageToHTML(message);
- std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
- addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
+ QString messageHTML = chatMessageToHTML(message);
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(boost::make_shared<SystemMessageSnippet>(messageHTML, QDateTime::currentDateTime(), false, theme_, P2QSTRING(id), getActualDirection(message, direction)));
- previousMessageKind_ = PreviousMessageWasPresence;
+ previousMessageKind_ = PreviousMessageWasPresence;
}
void QtWebKitChatView::replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- replaceLastMessage(chatMessageToHTML(message), timestampBehaviour);
+ replaceLastMessage(chatMessageToHTML(message), timestampBehaviour);
}
void QtWebKitChatView::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) {
- if (window_->isWidgetSelected()) {
- window_->onAllMessagesRead();
- }
+ if (window_->isWidgetSelected()) {
+ window_->onAllMessagesRead();
+ }
- QString message;
- if (isImpromptu) {
- message = QObject::tr("You've been invited to join a chat.") + "\n";
- } else {
- message = QObject::tr("You've been invited to enter the %1 room.").arg(P2QSTRING(jid.toString())) + "\n";
- }
- QString htmlString = message;
- if (!reason.empty()) {
- htmlString += QObject::tr("Reason: %1").arg(P2QSTRING(reason)) + "\n";
- }
- if (!direct) {
- htmlString += QObject::tr("This person may not have really sent this invitation!") + "\n";
- }
- htmlString = chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING(htmlString)));
+ QString message;
+ if (isImpromptu) {
+ message = QObject::tr("You've been invited to join a chat.") + "\n";
+ } else {
+ message = QObject::tr("You've been invited to enter the %1 room.").arg(P2QSTRING(jid.toString())) + "\n";
+ }
+ QString htmlString = message;
+ if (!reason.empty()) {
+ htmlString += QObject::tr("Reason: %1").arg(P2QSTRING(reason)) + "\n";
+ }
+ if (!direct) {
+ htmlString += QObject::tr("This person may not have really sent this invitation!") + "\n";
+ }
+ htmlString = chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING(htmlString)));
- QString id = QString(ButtonMUCInvite + "%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
- htmlString += "<div id='" + id + "'>" +
- buildChatWindowButton(chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING((tr("Accept Invite"))))), ButtonMUCInvite, QtUtilities::htmlEscape(P2QSTRING(jid.toString())), QtUtilities::htmlEscape(P2QSTRING(password)), id, QtUtilities::htmlEscape(isImpromptu ? "true" : "false"), QtUtilities::htmlEscape(isContinuation ? "true" : "false")) +
- "</div>";
+ QString id = QString(ButtonMUCInvite + "%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
+ htmlString += "<div id='" + id + "'>" +
+ buildChatWindowButton(chatMessageToHTML(ChatWindow::ChatMessage(Q2PSTRING((tr("Accept Invite"))))), ButtonMUCInvite, QtUtilities::htmlEscape(P2QSTRING(jid.toString())), QtUtilities::htmlEscape(P2QSTRING(password)), id, QtUtilities::htmlEscape(isImpromptu ? "true" : "false"), QtUtilities::htmlEscape(isContinuation ? "true" : "false")) +
+ "</div>";
- bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMUCInvite, senderName, false);
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasMUCInvite, senderName, false);
- QString qAvatarPath = "qrc:/icons/avatar.png";
+ QString qAvatarPath = "qrc:/icons/avatar.png";
- addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, appendToPrevious, theme_, id, ChatSnippet::getDirection(message)));
- previousMessageWasSelf_ = false;
- previousSenderName_ = P2QSTRING(senderName);
- previousMessageKind_ = PreviousMessageWasMUCInvite;
+ addMessageBottom(boost::make_shared<MessageSnippet>(htmlString, QtUtilities::htmlEscape(P2QSTRING(senderName)), B2QDATE(boost::posix_time::second_clock::universal_time()), qAvatarPath, false, appendToPrevious, theme_, id, ChatSnippet::getDirection(message)));
+ previousMessageWasSelf_ = false;
+ previousSenderName_ = P2QSTRING(senderName);
+ previousMessageKind_ = PreviousMessageWasMUCInvite;
}
void QtWebKitChatView::setAckState(std::string const& id, ChatWindow::AckState state) {
- QString xml;
- switch (state) {
- case ChatWindow::Pending:
- xml = "<img src='qrc:/icons/throbber.gif' title='" + tr("This message has not been received by your server yet.") + "'/>";
- displayReceiptInfo(P2QSTRING(id), false);
- break;
- case ChatWindow::Received:
- xml = "";
- displayReceiptInfo(P2QSTRING(id), true);
- break;
- case ChatWindow::Failed: xml = "<img src='qrc:/icons/error.png' title='" + tr("This message may not have been transmitted.") + "'/>"; break;
- }
- setAckXML(P2QSTRING(id), xml);
+ QString xml;
+ switch (state) {
+ case ChatWindow::Pending:
+ xml = "<img src='qrc:/icons/throbber.gif' title='" + tr("This message has not been received by your server yet.") + "'/>";
+ displayReceiptInfo(P2QSTRING(id), false);
+ break;
+ case ChatWindow::Received:
+ xml = "";
+ displayReceiptInfo(P2QSTRING(id), true);
+ break;
+ case ChatWindow::Failed: xml = "<img src='qrc:/icons/error.png' title='" + tr("This message may not have been transmitted.") + "'/>"; break;
+ }
+ setAckXML(P2QSTRING(id), xml);
}
void QtWebKitChatView::setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) {
- QString xml;
- switch (state) {
- case ChatWindow::ReceiptReceived:
- xml = "<img src='qrc:/icons/delivery-successful.png' title='" + tr("The receipt for this message has been received.") + "'/>";
- break;
- case ChatWindow::ReceiptRequested:
- xml = "<img src='qrc:/icons/warn.png' title='" + tr("The receipt for this message has not yet been received. The recipient(s) might not have received this message.") + "'/>";
- break;
- case ChatWindow::ReceiptFailed:
- xml = "<img src='qrc:/icons/delivery-failure.png' title='" + tr("Failed to transmit message to the receipient(s).") + "'/>";
- }
- setReceiptXML(P2QSTRING(id), xml);
+ QString xml;
+ switch (state) {
+ case ChatWindow::ReceiptReceived:
+ xml = "<img src='qrc:/icons/delivery-successful.png' title='" + tr("The receipt for this message has been received.") + "'/>";
+ break;
+ case ChatWindow::ReceiptRequested:
+ xml = "<img src='qrc:/icons/warn.png' title='" + tr("The receipt for this message has not yet been received. The recipient(s) might not have received this message.") + "'/>";
+ break;
+ case ChatWindow::ReceiptFailed:
+ xml = "<img src='qrc:/icons/delivery-failure.png' title='" + tr("Failed to transmit message to the receipient(s).") + "'/>";
+ }
+ setReceiptXML(P2QSTRING(id), xml);
}
bool QtWebKitChatView::appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf) {
- bool result = previousMessageKind_ == messageKind && ((senderIsSelf && previousMessageWasSelf_) || (!senderIsSelf && !previousMessageWasSelf_&& previousSenderName_ == P2QSTRING(senderName)));
- if (insertingLastLine_) {
- insertingLastLine_ = false;
- return false;
- }
- return result;
+ bool result = previousMessageKind_ == messageKind && ((senderIsSelf && previousMessageWasSelf_) || (!senderIsSelf && !previousMessageWasSelf_&& previousSenderName_ == P2QSTRING(senderName)));
+ if (insertingLastLine_) {
+ insertingLastLine_ = false;
+ return false;
+ }
+ return result;
}
ChatSnippet::Direction QtWebKitChatView::getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) {
- if (direction == ChatWindow::DefaultDirection) {
- return QCoreApplication::translate("QApplication", "QT_LAYOUT_DIRECTION") == "RTL" ? ChatSnippet::RTL : ChatSnippet::LTR;
- }
- else {
- return ChatSnippet::getDirection(message);
- }
+ if (direction == ChatWindow::DefaultDirection) {
+ return QCoreApplication::translate("QApplication", "QT_LAYOUT_DIRECTION") == "RTL" ? ChatSnippet::RTL : ChatSnippet::LTR;
+ }
+ else {
+ return ChatSnippet::getDirection(message);
+ }
}
// void QtWebKitChatView::setShowEmoticons(bool value) {
-// showEmoticons_ = value;
+// showEmoticons_ = value;
// }
diff --git a/Swift/QtUI/QtWebKitChatView.h b/Swift/QtUI/QtWebKitChatView.h
index aeed53b..e3fb967 100644
--- a/Swift/QtUI/QtWebKitChatView.h
+++ b/Swift/QtUI/QtWebKitChatView.h
@@ -25,168 +25,168 @@ class QUrl;
class QDate;
namespace Swift {
- class QtWebView;
- class QtChatTheme;
- class QtChatWindowJSBridge;
- class UIEventStream;
- class QtChatWindow;
- class QtWebKitChatView : public QtChatView {
- Q_OBJECT
-
- public:
- static const QString ButtonWhiteboardSessionCancel;
- static const QString ButtonWhiteboardSessionAcceptRequest;
- static const QString ButtonWhiteboardShowWindow;
- static const QString ButtonFileTransferCancel;
- static const QString ButtonFileTransferSetDescription;
- static const QString ButtonFileTransferSendRequest;
- static const QString ButtonFileTransferAcceptRequest;
- static const QString ButtonFileTransferOpenFile;
- static const QString ButtonMUCInvite;
- public:
- QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll = false);
- ~QtWebKitChatView();
-
- /** Add message to window.
- * @return id of added message (for acks).
- */
- virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- /** Adds action to window.
- * @return id of added message (for acks);
- */
- virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
-
- virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
- virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
-
- virtual void addErrorMessage(const ChatWindow::ChatMessage& message) SWIFTEN_OVERRIDE;
- virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
- virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
- virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
- virtual void setAckState(const std::string& id, ChatWindow::AckState state) SWIFTEN_OVERRIDE;
-
- virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) SWIFTEN_OVERRIDE;
- virtual void setFileTransferProgress(std::string, const int percentageDone) SWIFTEN_OVERRIDE;
- virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") SWIFTEN_OVERRIDE;
- virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) SWIFTEN_OVERRIDE;
- virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) SWIFTEN_OVERRIDE;
- virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) SWIFTEN_OVERRIDE;
- virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) SWIFTEN_OVERRIDE;
-
- virtual void showEmoticons(bool show) SWIFTEN_OVERRIDE;
- void addMessageTop(boost::shared_ptr<ChatSnippet> snippet);
- void addMessageBottom(boost::shared_ptr<ChatSnippet> snippet);
-
- int getSnippetPositionByDate(const QDate& date); // FIXME : This probably shouldn't have been public
- virtual void addLastSeenLine() SWIFTEN_OVERRIDE;
-
- private: // previously public, now private
- void replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour);
- void replaceLastMessage(const QString& newMessage, const QString& note);
- void replaceMessage(const QString& newMessage, const QString& id, const QDateTime& time);
- void replaceSystemMessage(const QString& newMessage, const QString&id, const ChatWindow::TimestampBehaviour timestampBehaviour);
- void rememberScrolledToBottom();
- void setAckXML(const QString& id, const QString& xml);
- void setReceiptXML(const QString& id, const QString& xml);
- void displayReceiptInfo(const QString& id, bool showIt);
-
- QString getLastSentMessage();
- void addToJSEnvironment(const QString&, QObject*);
- void setFileTransferProgress(QString id, const int percentageDone);
- void setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& msg);
- void setFileTransferWarning(QString id, QString warningText);
- void removeFileTransferWarning(QString id);
- void setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state);
- void setMUCInvitationJoined(QString id);
- void askDesktopToOpenFile(const QString& filename);
-
- signals:
- void gotFocus();
- void fontResized(int);
- void logCleared();
- void scrollRequested(int pos);
- void scrollReachedTop();
- void scrollReachedBottom();
-
- public slots:
- void copySelectionToClipboard();
- void handleLinkClicked(const QUrl&);
- void resetView();
- void resetTopInsertPoint();
- void increaseFontSize(int numSteps = 1);
- void decreaseFontSize();
- virtual void resizeFont(int fontSizeSteps) SWIFTEN_OVERRIDE;
- virtual void scrollToBottom() SWIFTEN_OVERRIDE;
- virtual void handleKeyPressEvent(QKeyEvent* event) SWIFTEN_OVERRIDE;
-
- private slots:
- void handleViewLoadFinished(bool);
- void handleFrameSizeChanged();
- void handleClearRequested();
- void handleScrollRequested(int dx, int dy, const QRect& rectToScroll);
- void handleHTMLButtonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
-
- private:
- enum PreviousMessageKind {
- PreviosuMessageWasNone,
- PreviousMessageWasMessage,
- PreviousMessageWasSystem,
- PreviousMessageWasPresence,
- PreviousMessageWasFileTransfer,
- PreviousMessageWasMUCInvite
- };
- std::string addMessage(
- const QString& message,
- const std::string& senderName,
- bool senderIsSelf,
- boost::shared_ptr<SecurityLabel> label,
- const std::string& avatarPath,
- const QString& style,
- const boost::posix_time::ptime& time,
- const HighlightAction& highlight,
- ChatSnippet::Direction direction);
- void replaceMessage(
- const QString& message,
- const std::string& id,
- const boost::posix_time::ptime& time,
- const QString& style,
- const HighlightAction& highlight);
- bool appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf);
- static ChatSnippet::Direction getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction);
- QString getHighlightSpanStart(const std::string& text, const std::string& background);
- QString getHighlightSpanStart(const HighlightAction& highlight);
- QString chatMessageToHTML(const ChatWindow::ChatMessage& message);
- static QString buildChatWindowButton(const QString& name, const QString& id, const QString& arg1 = QString(), const QString& arg2 = QString(), const QString& arg3 = QString(), const QString& arg4 = QString(), const QString& arg5 = QString());
-
- private:
- void headerEncode();
- void messageEncode();
- void addToDOM(boost::shared_ptr<ChatSnippet> snippet);
-
- QtChatWindow* window_;
- UIEventStream* eventStream_;
- bool viewReady_;
- bool isAtBottom_;
- bool topMessageAdded_;
- int scrollBarMaximum_;
- QtWebView* webView_;
- QWebPage* webPage_;
- int fontSizeSteps_;
- QtChatTheme* theme_;
- QWebElement lineSeparator_;
- QWebElement lastElement_;
- QWebElement firstElement_;
- QWebElement document_;
- bool disableAutoScroll_;
- QtChatWindowJSBridge* jsBridge;
- PreviousMessageKind previousMessageKind_;
- bool previousMessageWasSelf_;
- bool showEmoticons_;
- bool insertingLastLine_;
- int idCounter_;
- QString previousSenderName_;
- std::map<QString, QString> descriptions_;
- std::map<QString, QString> filePaths_;
- };
+ class QtWebView;
+ class QtChatTheme;
+ class QtChatWindowJSBridge;
+ class UIEventStream;
+ class QtChatWindow;
+ class QtWebKitChatView : public QtChatView {
+ Q_OBJECT
+
+ public:
+ static const QString ButtonWhiteboardSessionCancel;
+ static const QString ButtonWhiteboardSessionAcceptRequest;
+ static const QString ButtonWhiteboardShowWindow;
+ static const QString ButtonFileTransferCancel;
+ static const QString ButtonFileTransferSetDescription;
+ static const QString ButtonFileTransferSendRequest;
+ static const QString ButtonFileTransferAcceptRequest;
+ static const QString ButtonFileTransferOpenFile;
+ static const QString ButtonMUCInvite;
+ public:
+ QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll = false);
+ ~QtWebKitChatView();
+
+ /** Add message to window.
+ * @return id of added message (for acks).
+ */
+ virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ /** Adds action to window.
+ * @return id of added message (for acks);
+ */
+ virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+
+ virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
+ virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) SWIFTEN_OVERRIDE;
+
+ virtual void addErrorMessage(const ChatWindow::ChatMessage& message) SWIFTEN_OVERRIDE;
+ virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
+ virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour timestampBehaviour) SWIFTEN_OVERRIDE;
+ virtual void setAckState(const std::string& id, ChatWindow::AckState state) SWIFTEN_OVERRIDE;
+
+ virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) SWIFTEN_OVERRIDE;
+ virtual void setFileTransferProgress(std::string, const int percentageDone) SWIFTEN_OVERRIDE;
+ virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") SWIFTEN_OVERRIDE;
+ virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) SWIFTEN_OVERRIDE;
+ virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) SWIFTEN_OVERRIDE;
+ virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) SWIFTEN_OVERRIDE;
+ virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) SWIFTEN_OVERRIDE;
+
+ virtual void showEmoticons(bool show) SWIFTEN_OVERRIDE;
+ void addMessageTop(boost::shared_ptr<ChatSnippet> snippet);
+ void addMessageBottom(boost::shared_ptr<ChatSnippet> snippet);
+
+ int getSnippetPositionByDate(const QDate& date); // FIXME : This probably shouldn't have been public
+ virtual void addLastSeenLine() SWIFTEN_OVERRIDE;
+
+ private: // previously public, now private
+ void replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour);
+ void replaceLastMessage(const QString& newMessage, const QString& note);
+ void replaceMessage(const QString& newMessage, const QString& id, const QDateTime& time);
+ void replaceSystemMessage(const QString& newMessage, const QString&id, const ChatWindow::TimestampBehaviour timestampBehaviour);
+ void rememberScrolledToBottom();
+ void setAckXML(const QString& id, const QString& xml);
+ void setReceiptXML(const QString& id, const QString& xml);
+ void displayReceiptInfo(const QString& id, bool showIt);
+
+ QString getLastSentMessage();
+ void addToJSEnvironment(const QString&, QObject*);
+ void setFileTransferProgress(QString id, const int percentageDone);
+ void setFileTransferStatus(QString id, const ChatWindow::FileTransferState state, const QString& msg);
+ void setFileTransferWarning(QString id, QString warningText);
+ void removeFileTransferWarning(QString id);
+ void setWhiteboardSessionStatus(QString id, const ChatWindow::WhiteboardSessionState state);
+ void setMUCInvitationJoined(QString id);
+ void askDesktopToOpenFile(const QString& filename);
+
+ signals:
+ void gotFocus();
+ void fontResized(int);
+ void logCleared();
+ void scrollRequested(int pos);
+ void scrollReachedTop();
+ void scrollReachedBottom();
+
+ public slots:
+ void copySelectionToClipboard();
+ void handleLinkClicked(const QUrl&);
+ void resetView();
+ void resetTopInsertPoint();
+ void increaseFontSize(int numSteps = 1);
+ void decreaseFontSize();
+ virtual void resizeFont(int fontSizeSteps) SWIFTEN_OVERRIDE;
+ virtual void scrollToBottom() SWIFTEN_OVERRIDE;
+ virtual void handleKeyPressEvent(QKeyEvent* event) SWIFTEN_OVERRIDE;
+
+ private slots:
+ void handleViewLoadFinished(bool);
+ void handleFrameSizeChanged();
+ void handleClearRequested();
+ void handleScrollRequested(int dx, int dy, const QRect& rectToScroll);
+ void handleHTMLButtonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
+
+ private:
+ enum PreviousMessageKind {
+ PreviosuMessageWasNone,
+ PreviousMessageWasMessage,
+ PreviousMessageWasSystem,
+ PreviousMessageWasPresence,
+ PreviousMessageWasFileTransfer,
+ PreviousMessageWasMUCInvite
+ };
+ std::string addMessage(
+ const QString& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ boost::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const QString& style,
+ const boost::posix_time::ptime& time,
+ const HighlightAction& highlight,
+ ChatSnippet::Direction direction);
+ void replaceMessage(
+ const QString& message,
+ const std::string& id,
+ const boost::posix_time::ptime& time,
+ const QString& style,
+ const HighlightAction& highlight);
+ bool appendToPreviousCheck(PreviousMessageKind messageKind, const std::string& senderName, bool senderIsSelf);
+ static ChatSnippet::Direction getActualDirection(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction);
+ QString getHighlightSpanStart(const std::string& text, const std::string& background);
+ QString getHighlightSpanStart(const HighlightAction& highlight);
+ QString chatMessageToHTML(const ChatWindow::ChatMessage& message);
+ static QString buildChatWindowButton(const QString& name, const QString& id, const QString& arg1 = QString(), const QString& arg2 = QString(), const QString& arg3 = QString(), const QString& arg4 = QString(), const QString& arg5 = QString());
+
+ private:
+ void headerEncode();
+ void messageEncode();
+ void addToDOM(boost::shared_ptr<ChatSnippet> snippet);
+
+ QtChatWindow* window_;
+ UIEventStream* eventStream_;
+ bool viewReady_;
+ bool isAtBottom_;
+ bool topMessageAdded_;
+ int scrollBarMaximum_;
+ QtWebView* webView_;
+ QWebPage* webPage_;
+ int fontSizeSteps_;
+ QtChatTheme* theme_;
+ QWebElement lineSeparator_;
+ QWebElement lastElement_;
+ QWebElement firstElement_;
+ QWebElement document_;
+ bool disableAutoScroll_;
+ QtChatWindowJSBridge* jsBridge;
+ PreviousMessageKind previousMessageKind_;
+ bool previousMessageWasSelf_;
+ bool showEmoticons_;
+ bool insertingLastLine_;
+ int idCounter_;
+ QString previousSenderName_;
+ std::map<QString, QString> descriptions_;
+ std::map<QString, QString> filePaths_;
+ };
}
diff --git a/Swift/QtUI/QtWebView.cpp b/Swift/QtUI/QtWebView.cpp
index 4950d27..717310b 100644
--- a/Swift/QtUI/QtWebView.cpp
+++ b/Swift/QtUI/QtWebView.cpp
@@ -17,29 +17,29 @@
namespace Swift {
QtWebView::QtWebView(QWidget* parent) : QWebView(parent), fontSizeIsMinimal(false) {
- setRenderHint(QPainter::SmoothPixmapTransform);
- filteredActions.push_back(QWebPage::CopyLinkToClipboard);
- filteredActions.push_back(QWebPage::CopyImageToClipboard);
- filteredActions.push_back(QWebPage::Copy);
- if (Log::getLogLevel() == Log::debug) {
- filteredActions.push_back(QWebPage::InspectElement);
- }
+ setRenderHint(QPainter::SmoothPixmapTransform);
+ filteredActions.push_back(QWebPage::CopyLinkToClipboard);
+ filteredActions.push_back(QWebPage::CopyImageToClipboard);
+ filteredActions.push_back(QWebPage::Copy);
+ if (Log::getLogLevel() == Log::debug) {
+ filteredActions.push_back(QWebPage::InspectElement);
+ }
}
void QtWebView::keyPressEvent(QKeyEvent* event) {
- Qt::KeyboardModifiers modifiers = event->modifiers();
- int key = event->key();
- if (modifiers == Qt::ShiftModifier && (key == Qt::Key_PageUp || key == Qt::Key_PageDown)) {
- modifiers = Qt::NoModifier;
- }
- QKeyEvent* translatedEvent = new QKeyEvent(QEvent::KeyPress,
- key,
- modifiers,
- event->text(),
- event->isAutoRepeat(),
- boost::numeric_cast<unsigned short>(event->count()));
- QWebView::keyPressEvent(translatedEvent);
- delete translatedEvent;
+ Qt::KeyboardModifiers modifiers = event->modifiers();
+ int key = event->key();
+ if (modifiers == Qt::ShiftModifier && (key == Qt::Key_PageUp || key == Qt::Key_PageDown)) {
+ modifiers = Qt::NoModifier;
+ }
+ QKeyEvent* translatedEvent = new QKeyEvent(QEvent::KeyPress,
+ key,
+ modifiers,
+ event->text(),
+ event->isAutoRepeat(),
+ boost::numeric_cast<unsigned short>(event->count()));
+ QWebView::keyPressEvent(translatedEvent);
+ delete translatedEvent;
}
void QtWebView::dragEnterEvent(QDragEnterEvent*) {
@@ -47,43 +47,43 @@ void QtWebView::dragEnterEvent(QDragEnterEvent*) {
}
void QtWebView::setFontSizeIsMinimal(bool minimum) {
- fontSizeIsMinimal = minimum;
+ fontSizeIsMinimal = minimum;
}
void QtWebView::contextMenuEvent(QContextMenuEvent* ev) {
- // Filter out the relevant actions from the standard actions
-
- QMenu* menu = page()->createStandardContextMenu();
- QList<QAction*> actions(menu->actions());
- for (int i = 0; i < actions.size(); ++i) {
- QAction* action = actions.at(i);
- bool removeAction = true;
- for(size_t j = 0; j < filteredActions.size(); ++j) {
- if (action == pageAction(filteredActions[j])) {
- removeAction = false;
- break;
- }
- }
- if (removeAction) {
- menu->removeAction(action);
- }
- }
-
- // Add our own custom actions
- menu->addAction(tr("Clear"), this, SIGNAL(clearRequested()));
- menu->addAction(tr("Increase font size"), this, SIGNAL(fontGrowRequested()));
- QAction* shrink = new QAction(tr("Decrease font size"), this);
- shrink->setEnabled(!fontSizeIsMinimal);
- connect(shrink, SIGNAL(triggered()), this, SIGNAL(fontShrinkRequested()));
- menu->addAction(shrink);
-
- menu->exec(ev->globalPos());
- delete menu;
+ // Filter out the relevant actions from the standard actions
+
+ QMenu* menu = page()->createStandardContextMenu();
+ QList<QAction*> actions(menu->actions());
+ for (int i = 0; i < actions.size(); ++i) {
+ QAction* action = actions.at(i);
+ bool removeAction = true;
+ for(size_t j = 0; j < filteredActions.size(); ++j) {
+ if (action == pageAction(filteredActions[j])) {
+ removeAction = false;
+ break;
+ }
+ }
+ if (removeAction) {
+ menu->removeAction(action);
+ }
+ }
+
+ // Add our own custom actions
+ menu->addAction(tr("Clear"), this, SIGNAL(clearRequested()));
+ menu->addAction(tr("Increase font size"), this, SIGNAL(fontGrowRequested()));
+ QAction* shrink = new QAction(tr("Decrease font size"), this);
+ shrink->setEnabled(!fontSizeIsMinimal);
+ connect(shrink, SIGNAL(triggered()), this, SIGNAL(fontShrinkRequested()));
+ menu->addAction(shrink);
+
+ menu->exec(ev->globalPos());
+ delete menu;
}
void QtWebView::focusInEvent(QFocusEvent* event) {
- QWebView::focusInEvent(event);
- emit gotFocus();
+ QWebView::focusInEvent(event);
+ emit gotFocus();
}
}
diff --git a/Swift/QtUI/QtWebView.h b/Swift/QtUI/QtWebView.h
index 134f578..985a0db 100644
--- a/Swift/QtUI/QtWebView.h
+++ b/Swift/QtUI/QtWebView.h
@@ -12,26 +12,26 @@
#include <QWebView>
namespace Swift {
- class QtWebView : public QWebView {
- Q_OBJECT
- public:
- QtWebView(QWidget* parent);
- void keyPressEvent(QKeyEvent* event);
- void dragEnterEvent(QDragEnterEvent *event);
- void contextMenuEvent(QContextMenuEvent* ev);
- void setFontSizeIsMinimal(bool minimum);
-
- signals:
- void gotFocus();
- void clearRequested();
- void fontGrowRequested();
- void fontShrinkRequested();
-
- protected:
- void focusInEvent(QFocusEvent* event);
-
- private:
- std::vector<QWebPage::WebAction> filteredActions;
- bool fontSizeIsMinimal;
- };
+ class QtWebView : public QWebView {
+ Q_OBJECT
+ public:
+ QtWebView(QWidget* parent);
+ void keyPressEvent(QKeyEvent* event);
+ void dragEnterEvent(QDragEnterEvent *event);
+ void contextMenuEvent(QContextMenuEvent* ev);
+ void setFontSizeIsMinimal(bool minimum);
+
+ signals:
+ void gotFocus();
+ void clearRequested();
+ void fontGrowRequested();
+ void fontShrinkRequested();
+
+ protected:
+ void focusInEvent(QFocusEvent* event);
+
+ private:
+ std::vector<QWebPage::WebAction> filteredActions;
+ bool fontSizeIsMinimal;
+ };
}
diff --git a/Swift/QtUI/QtWin32NotifierWindow.h b/Swift/QtUI/QtWin32NotifierWindow.h
index 54369cf..bf55706 100644
--- a/Swift/QtUI/QtWin32NotifierWindow.h
+++ b/Swift/QtUI/QtWin32NotifierWindow.h
@@ -11,19 +11,19 @@
#include <SwifTools/Notifier/Win32NotifierWindow.h>
namespace Swift {
- class QtWin32NotifierWindow : public QWidget, public Win32NotifierWindow {
- public:
- QtWin32NotifierWindow(QWidget* parent = NULL) {
- setVisible(false);
- }
+ class QtWin32NotifierWindow : public QWidget, public Win32NotifierWindow {
+ public:
+ QtWin32NotifierWindow(QWidget* parent = NULL) {
+ setVisible(false);
+ }
- bool winEvent (MSG* message, long* result ) {
- onMessageReceived(message);
- return false;
- }
+ bool winEvent (MSG* message, long* result ) {
+ onMessageReceived(message);
+ return false;
+ }
- virtual HWND getID() const {
- return (HWND) winId();
- }
- };
+ virtual HWND getID() const {
+ return (HWND) winId();
+ }
+ };
}
diff --git a/Swift/QtUI/QtXMLConsoleWidget.cpp b/Swift/QtUI/QtXMLConsoleWidget.cpp
index 1fbad8f..a7f9702 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.cpp
+++ b/Swift/QtUI/QtXMLConsoleWidget.cpp
@@ -22,99 +22,99 @@
namespace Swift {
QtXMLConsoleWidget::QtXMLConsoleWidget() {
- setWindowTitle(tr("Console"));
+ setWindowTitle(tr("Console"));
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setSpacing(0);
- layout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->setSpacing(0);
+ layout->setContentsMargins(0,0,0,0);
- textEdit = new QTextEdit(this);
- textEdit->setReadOnly(true);
- layout->addWidget(textEdit);
+ textEdit = new QTextEdit(this);
+ textEdit->setReadOnly(true);
+ layout->addWidget(textEdit);
- QWidget* bottom = new QWidget(this);
- layout->addWidget(bottom);
- bottom->setAutoFillBackground(true);
+ QWidget* bottom = new QWidget(this);
+ layout->addWidget(bottom);
+ bottom->setAutoFillBackground(true);
- QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
- buttonLayout->setContentsMargins(10,0,20,0);
- buttonLayout->setSpacing(0);
+ QHBoxLayout* buttonLayout = new QHBoxLayout(bottom);
+ buttonLayout->setContentsMargins(10,0,20,0);
+ buttonLayout->setSpacing(0);
- enabled = new QCheckBox(tr("Trace input/output"), bottom);
- enabled->setChecked(true);
- buttonLayout->addWidget(enabled);
+ enabled = new QCheckBox(tr("Trace input/output"), bottom);
+ enabled->setChecked(true);
+ buttonLayout->addWidget(enabled);
- buttonLayout->addStretch();
+ buttonLayout->addStretch();
- QPushButton* clearButton = new QPushButton(tr("Clear"), bottom);
- connect(clearButton, SIGNAL(clicked()), textEdit, SLOT(clear()));
- buttonLayout->addWidget(clearButton);
+ QPushButton* clearButton = new QPushButton(tr("Clear"), bottom);
+ connect(clearButton, SIGNAL(clicked()), textEdit, SLOT(clear()));
+ buttonLayout->addWidget(clearButton);
- setWindowTitle(tr("Debug Console"));
- emit titleUpdated();
+ setWindowTitle(tr("Debug Console"));
+ emit titleUpdated();
}
QtXMLConsoleWidget::~QtXMLConsoleWidget() {
}
void QtXMLConsoleWidget::showEvent(QShowEvent* event) {
- emit windowOpening();
- emit titleUpdated(); /* This just needs to be somewhere after construction */
- QWidget::showEvent(event);
+ emit windowOpening();
+ emit titleUpdated(); /* This just needs to be somewhere after construction */
+ QWidget::showEvent(event);
}
void QtXMLConsoleWidget::show() {
- QWidget::show();
- emit windowOpening();
+ QWidget::show();
+ emit windowOpening();
}
void QtXMLConsoleWidget::activate() {
- emit wantsToActivate();
+ emit wantsToActivate();
}
void QtXMLConsoleWidget::closeEvent(QCloseEvent* event) {
- emit windowClosing();
- event->accept();
+ emit windowClosing();
+ event->accept();
}
void QtXMLConsoleWidget::handleDataRead(const SafeByteArray& data) {
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- std::string tag = Q2PSTRING(tr("<!-- IN %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
- appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(33,98,33));
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ std::string tag = Q2PSTRING(tr("<!-- IN %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
+ appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(33,98,33));
}
void QtXMLConsoleWidget::handleDataWritten(const SafeByteArray& data) {
- boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
- std::string tag = Q2PSTRING(tr("<!-- OUT %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
- appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(155,1,0));
+ boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
+ std::string tag = Q2PSTRING(tr("<!-- OUT %1 -->").arg(P2QSTRING(boost::posix_time::to_iso_extended_string(now))));
+ appendTextIfEnabled(tag + "\n" + safeByteArrayToString(data) + "\n", QColor(155,1,0));
}
std::string QtXMLConsoleWidget::getID() const {
- return "QtXMLConsoleWidget";
+ return "QtXMLConsoleWidget";
}
void QtXMLConsoleWidget::appendTextIfEnabled(const std::string& data, const QColor& color) {
- if (enabled->isChecked()) {
- QScrollBar* scrollBar = textEdit->verticalScrollBar();
- bool scrollToBottom = (!scrollBar || scrollBar->value() == scrollBar->maximum());
-
- QTextCursor cursor(textEdit->document());
- cursor.beginEditBlock();
- cursor.movePosition(QTextCursor::End);
- QTextCharFormat format;
- format.setForeground(QBrush(color));
- cursor.mergeCharFormat(format);
- cursor.insertText(P2QSTRING(data));
- cursor.endEditBlock();
-
- // Checking for the scrollbar again, because it could have appeared after inserting text.
- // In practice, I suspect that the scrollbar is always there, but hidden, but since we were
- // explicitly testing for this already above, I'm leaving the code in.
- scrollBar = textEdit->verticalScrollBar();
- if (scrollToBottom && scrollBar) {
- scrollBar->setValue(scrollBar->maximum());
- }
- }
+ if (enabled->isChecked()) {
+ QScrollBar* scrollBar = textEdit->verticalScrollBar();
+ bool scrollToBottom = (!scrollBar || scrollBar->value() == scrollBar->maximum());
+
+ QTextCursor cursor(textEdit->document());
+ cursor.beginEditBlock();
+ cursor.movePosition(QTextCursor::End);
+ QTextCharFormat format;
+ format.setForeground(QBrush(color));
+ cursor.mergeCharFormat(format);
+ cursor.insertText(P2QSTRING(data));
+ cursor.endEditBlock();
+
+ // Checking for the scrollbar again, because it could have appeared after inserting text.
+ // In practice, I suspect that the scrollbar is always there, but hidden, but since we were
+ // explicitly testing for this already above, I'm leaving the code in.
+ scrollBar = textEdit->verticalScrollBar();
+ if (scrollToBottom && scrollBar) {
+ scrollBar->setValue(scrollBar->maximum());
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtXMLConsoleWidget.h b/Swift/QtUI/QtXMLConsoleWidget.h
index ddcfe20..ef10e63 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.h
+++ b/Swift/QtUI/QtXMLConsoleWidget.h
@@ -15,29 +15,29 @@ class QCheckBox;
class QColor;
namespace Swift {
- class QtXMLConsoleWidget : public QtTabbable, public XMLConsoleWidget {
- Q_OBJECT
+ class QtXMLConsoleWidget : public QtTabbable, public XMLConsoleWidget {
+ Q_OBJECT
- public:
- QtXMLConsoleWidget();
- ~QtXMLConsoleWidget();
+ public:
+ QtXMLConsoleWidget();
+ ~QtXMLConsoleWidget();
- void show();
- void activate();
+ void show();
+ void activate();
- virtual void handleDataRead(const SafeByteArray& data);
- virtual void handleDataWritten(const SafeByteArray& data);
+ virtual void handleDataRead(const SafeByteArray& data);
+ virtual void handleDataWritten(const SafeByteArray& data);
- virtual std::string getID() const;
+ virtual std::string getID() const;
- private:
- virtual void closeEvent(QCloseEvent* event);
- virtual void showEvent(QShowEvent* event);
+ private:
+ virtual void closeEvent(QCloseEvent* event);
+ virtual void showEvent(QShowEvent* event);
- void appendTextIfEnabled(const std::string& data, const QColor& color);
+ void appendTextIfEnabled(const std::string& data, const QColor& color);
- private:
- QTextEdit* textEdit;
- QCheckBox* enabled;
- };
+ private:
+ QTextEdit* textEdit;
+ QCheckBox* enabled;
+ };
}
diff --git a/Swift/QtUI/Roster/DelegateCommons.cpp b/Swift/QtUI/Roster/DelegateCommons.cpp
index f9d732c..517683b 100644
--- a/Swift/QtUI/Roster/DelegateCommons.cpp
+++ b/Swift/QtUI/Roster/DelegateCommons.cpp
@@ -14,96 +14,96 @@ namespace Swift {
void DelegateCommons::drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags) {
- QString adjustedText(painter->fontMetrics().elidedText(text, Qt::ElideRight, region.width(), Qt::TextShowMnemonic));
- painter->setClipRect(region);
- painter->drawText(region, flags, adjustedText.simplified());
- painter->setClipping(false);
+ QString adjustedText(painter->fontMetrics().elidedText(text, Qt::ElideRight, region.width(), Qt::TextShowMnemonic));
+ painter->setClipRect(region);
+ painter->drawText(region, flags, adjustedText.simplified());
+ painter->setClipping(false);
}
void DelegateCommons::paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const {
- painter->save();
- QRect fullRegion(option.rect);
- if ( option.state & QStyle::State_Selected ) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- } else {
- painter->setPen(QPen(nameColor));
- }
-
- QRect presenceIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth, fullRegion.height() - verticalMargin));
-
- QRect idleIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth*2, fullRegion.height() - verticalMargin));
- int calculatedAvatarSize = presenceIconRegion.height();
- //This overlaps the presenceIcon, so must be painted first
- QRect avatarRegion(QPoint(presenceIconRegion.right() - presenceIconWidth / 2, presenceIconRegion.top()), QSize(calculatedAvatarSize, calculatedAvatarSize));
-
- QPixmap avatarPixmap;
- if (!compact && !avatarPath.isEmpty()) {
- QString scaledAvatarPath = QtScaledAvatarCache(avatarRegion.height()).getScaledAvatarPath(avatarPath);
- if (QFileInfo(scaledAvatarPath).exists()) {
- avatarPixmap.load(scaledAvatarPath);
- }
- }
- if (!compact && avatarPixmap.isNull()) {
- avatarPixmap = QPixmap(":/icons/avatar.png").scaled(avatarRegion.height(), avatarRegion.width(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
-
- if (!compact) {
- painter->drawPixmap(avatarRegion.topLeft() + QPoint(((avatarRegion.width() - avatarPixmap.width()) / 2), (avatarRegion.height() - avatarPixmap.height()) / 2), avatarPixmap);
- }
-
- //Paint the presence icon over the top of the avatar
- presenceIcon.paint(painter, presenceIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
-
- if (isIdle) {
- idleIcon.paint(painter, idleIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
- }
-
- QFontMetrics nameMetrics(nameFont);
- painter->setFont(nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = (compact ? presenceIconRegion : avatarRegion).right() + horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0/*-leftOffset*/, 0));
-
- int nameHeight = nameMetrics.height() + verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, verticalMargin, 0, 0));
-
- DelegateCommons::drawElidedText(painter, nameRegion, name);
-
- if (!compact) {
- painter->setFont(detailFont);
- painter->setPen(QPen(QColor(160,160,160)));
-
- QRect statusTextRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- DelegateCommons::drawElidedText(painter, statusTextRegion, statusText);
- }
-
- if (unreadCount > 0) {
- QRect unreadRect(fullRegion.right() - unreadCountSize - horizontalMargin, fullRegion.top() + (fullRegion.height() - unreadCountSize) / 2, unreadCountSize, unreadCountSize);
- QPen pen(QColor("black"));
- pen.setWidth(1);
- painter->setRenderHint(QPainter::Antialiasing, true);
- painter->setPen(pen);
- painter->setBrush(QBrush(QColor("red"), Qt::SolidPattern));
- //painter->setBackgroundMode(Qt::OpaqueMode);
- painter->drawEllipse(unreadRect);
- painter->setBackgroundMode(Qt::TransparentMode);
- painter->setPen(QColor("white"));
- drawElidedText(painter, unreadRect, QString("%1").arg(unreadCount), Qt::AlignCenter);
- }
-
- painter->restore();
+ painter->save();
+ QRect fullRegion(option.rect);
+ if ( option.state & QStyle::State_Selected ) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ } else {
+ painter->setPen(QPen(nameColor));
+ }
+
+ QRect presenceIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth, fullRegion.height() - verticalMargin));
+
+ QRect idleIconRegion(QPoint(farLeftMargin, fullRegion.top()), QSize(presenceIconWidth*2, fullRegion.height() - verticalMargin));
+ int calculatedAvatarSize = presenceIconRegion.height();
+ //This overlaps the presenceIcon, so must be painted first
+ QRect avatarRegion(QPoint(presenceIconRegion.right() - presenceIconWidth / 2, presenceIconRegion.top()), QSize(calculatedAvatarSize, calculatedAvatarSize));
+
+ QPixmap avatarPixmap;
+ if (!compact && !avatarPath.isEmpty()) {
+ QString scaledAvatarPath = QtScaledAvatarCache(avatarRegion.height()).getScaledAvatarPath(avatarPath);
+ if (QFileInfo(scaledAvatarPath).exists()) {
+ avatarPixmap.load(scaledAvatarPath);
+ }
+ }
+ if (!compact && avatarPixmap.isNull()) {
+ avatarPixmap = QPixmap(":/icons/avatar.png").scaled(avatarRegion.height(), avatarRegion.width(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+
+ if (!compact) {
+ painter->drawPixmap(avatarRegion.topLeft() + QPoint(((avatarRegion.width() - avatarPixmap.width()) / 2), (avatarRegion.height() - avatarPixmap.height()) / 2), avatarPixmap);
+ }
+
+ //Paint the presence icon over the top of the avatar
+ presenceIcon.paint(painter, presenceIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
+
+ if (isIdle) {
+ idleIcon.paint(painter, idleIconRegion, Qt::AlignBottom | Qt::AlignHCenter);
+ }
+
+ QFontMetrics nameMetrics(nameFont);
+ painter->setFont(nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = (compact ? presenceIconRegion : avatarRegion).right() + horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0/*-leftOffset*/, 0));
+
+ int nameHeight = nameMetrics.height() + verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, verticalMargin, 0, 0));
+
+ DelegateCommons::drawElidedText(painter, nameRegion, name);
+
+ if (!compact) {
+ painter->setFont(detailFont);
+ painter->setPen(QPen(QColor(160,160,160)));
+
+ QRect statusTextRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ DelegateCommons::drawElidedText(painter, statusTextRegion, statusText);
+ }
+
+ if (unreadCount > 0) {
+ QRect unreadRect(fullRegion.right() - unreadCountSize - horizontalMargin, fullRegion.top() + (fullRegion.height() - unreadCountSize) / 2, unreadCountSize, unreadCountSize);
+ QPen pen(QColor("black"));
+ pen.setWidth(1);
+ painter->setRenderHint(QPainter::Antialiasing, true);
+ painter->setPen(pen);
+ painter->setBrush(QBrush(QColor("red"), Qt::SolidPattern));
+ //painter->setBackgroundMode(Qt::OpaqueMode);
+ painter->drawEllipse(unreadRect);
+ painter->setBackgroundMode(Qt::TransparentMode);
+ painter->setPen(QColor("white"));
+ drawElidedText(painter, unreadRect, QString("%1").arg(unreadCount), Qt::AlignCenter);
+ }
+
+ painter->restore();
}
QSize DelegateCommons::contactSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/, bool compact ) const {
- int heightByAvatar = (compact ? presenceIconHeight : avatarSize) + verticalMargin * 2;
- QFontMetrics nameMetrics(nameFont);
- QFontMetrics statusMetrics(detailFont);
- int sizeByText = 2 * verticalMargin + nameMetrics.height() + (compact ? 0 : statusMetrics.height());
- //Doesn't work, yay! FIXME: why?
- //QSize size = (option.state & QStyle::State_Selected) ? QSize(150, 80) : QSize(150, avatarSize_ + margin_ * 2);
- //qDebug() << "Returning size" << size;
- return QSize(150, sizeByText > heightByAvatar ? sizeByText : heightByAvatar);
+ int heightByAvatar = (compact ? presenceIconHeight : avatarSize) + verticalMargin * 2;
+ QFontMetrics nameMetrics(nameFont);
+ QFontMetrics statusMetrics(detailFont);
+ int sizeByText = 2 * verticalMargin + nameMetrics.height() + (compact ? 0 : statusMetrics.height());
+ //Doesn't work, yay! FIXME: why?
+ //QSize size = (option.state & QStyle::State_Selected) ? QSize(150, 80) : QSize(150, avatarSize_ + margin_ * 2);
+ //qDebug() << "Returning size" << size;
+ return QSize(150, sizeByText > heightByAvatar ? sizeByText : heightByAvatar);
}
const int DelegateCommons::horizontalMargin = 2;
diff --git a/Swift/QtUI/Roster/DelegateCommons.h b/Swift/QtUI/Roster/DelegateCommons.h
index 5e28ac1..74b08f2 100644
--- a/Swift/QtUI/Roster/DelegateCommons.h
+++ b/Swift/QtUI/Roster/DelegateCommons.h
@@ -15,29 +15,29 @@
#include <QStyleOptionViewItem>
namespace Swift {
- class DelegateCommons {
- public:
- DelegateCommons() : nameFont(QApplication::font()), detailFont(QApplication::font()), idleIcon(QIcon(":/icons/zzz.png")) {
- detailFontSizeDrop = nameFont.pointSize() >= 10 ? 2 : 0;
- detailFont.setStyle(QFont::StyleItalic);
- detailFont.setPointSize(nameFont.pointSize() - detailFontSizeDrop);
- }
+ class DelegateCommons {
+ public:
+ DelegateCommons() : nameFont(QApplication::font()), detailFont(QApplication::font()), idleIcon(QIcon(":/icons/zzz.png")) {
+ detailFontSizeDrop = nameFont.pointSize() >= 10 ? 2 : 0;
+ detailFont.setStyle(QFont::StyleItalic);
+ detailFont.setPointSize(nameFont.pointSize() - detailFontSizeDrop);
+ }
- static void drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags = Qt::AlignTop);
+ static void drawElidedText(QPainter* painter, const QRect& region, const QString& text, int flags = Qt::AlignTop);
- QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index, bool compact) const;
- void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const;
+ QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index, bool compact) const;
+ void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QColor& nameColor, const QString& avatarPath, const QIcon& presenceIcon, const QString& name, const QString& statusText, bool isIdle, int unreadCount, bool compact) const;
- int detailFontSizeDrop;
- QFont nameFont;
- QFont detailFont;
- static const int horizontalMargin;
- static const int verticalMargin;
- static const int farLeftMargin;
- static const int avatarSize;
- static const int presenceIconHeight;
- static const int presenceIconWidth;
- static const int unreadCountSize;
- QIcon idleIcon;
- };
+ int detailFontSizeDrop;
+ QFont nameFont;
+ QFont detailFont;
+ static const int horizontalMargin;
+ static const int verticalMargin;
+ static const int farLeftMargin;
+ static const int avatarSize;
+ static const int presenceIconHeight;
+ static const int presenceIconWidth;
+ static const int unreadCountSize;
+ QIcon idleIcon;
+ };
}
diff --git a/Swift/QtUI/Roster/GroupItemDelegate.cpp b/Swift/QtUI/Roster/GroupItemDelegate.cpp
index d91d4ba..0356aa0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.cpp
+++ b/Swift/QtUI/Roster/GroupItemDelegate.cpp
@@ -13,100 +13,100 @@
namespace Swift {
GroupItemDelegate::GroupItemDelegate() : groupFont_(QApplication::font()) {
- groupFont_.setPointSize(common_.nameFont.pointSize() - common_.detailFontSizeDrop);
- groupFont_.setWeight(QFont::Bold);
+ groupFont_.setPointSize(common_.nameFont.pointSize() - common_.detailFontSizeDrop);
+ groupFont_.setWeight(QFont::Bold);
}
QSize GroupItemDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/) const {
- QFontMetrics groupMetrics(groupFont_);
- return QSize(150, groupMetrics.height() + common_.verticalMargin + 2);
+ QFontMetrics groupMetrics(groupFont_);
+ return QSize(150, groupMetrics.height() + common_.verticalMargin + 2);
}
void GroupItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const {
- painter->save();
- painter->setPen(QPen(QColor(189, 189, 189)));
- //FIXME: It looks like Qt is passing us a rectangle that's too small
- //This deliberately draws outside the lines, and we need to find a better solution.
- int correctionAmount = groupCornerRadius_ > 0 ? 0 : 1;
- QRect region(QPoint(option.rect.left() - correctionAmount, option.rect.top()), QSize(option.rect.width() + correctionAmount, option.rect.height() - common_.verticalMargin));
- QLinearGradient fillGradient(region.topLeft(), region.bottomLeft());
- fillGradient.setColorAt(0, QColor(244, 244, 244));
- fillGradient.setColorAt(0.1, QColor(231, 231, 231));
- fillGradient.setColorAt(1, QColor(209, 209, 209));
-
- QBrush backgroundBrush = QBrush(fillGradient);
- QPainterPath fillPath;
- fillPath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
- QPainterPath linePath;
- linePath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
- painter->fillPath(fillPath, backgroundBrush);
- painter->drawPath(linePath);
-
- int triangleHorizontalOffset = 1;
- int triangleWidth = 9;
- int triangleHeight = 5;
- paintExpansionTriangle(painter, region.adjusted(common_.horizontalMargin + triangleHorizontalOffset + 1, 0, 0, 0), triangleWidth, triangleHeight, expanded);
-
- int textLeftOffset = 3 * common_.horizontalMargin + 1 + triangleWidth + triangleHorizontalOffset;
- QFontMetrics fontMetrics(groupFont_);
- int textTopOffset = (region.height() - fontMetrics.height()) / 2;
- painter->setFont(groupFont_);
- int contactCountWidth = 0;
- QRect textRect = region.adjusted(textLeftOffset, textTopOffset, -1 * textLeftOffset, -1 * textTopOffset);
-
- if (!expanded) {
- QFontMetrics groupMetrics(groupFont_);
- int contactCount = rowCount;
- QString countString = QString("%1").arg(contactCount);
- contactCountWidth = groupMetrics.width(countString) + 2 * common_.horizontalMargin;
- int offsetAmount = textRect.width() - contactCountWidth + common_.horizontalMargin;
- QRect countRect = textRect.adjusted(offsetAmount, 0, 0/*-1 * offsetAmount*/, 0);
- paintShadowText(painter, countRect, countString);
- }
- QRect nameTextRect = expanded ? textRect : textRect.adjusted(0, 0, -contactCountWidth, 0);
- QString elidedName = fontMetrics.elidedText(name, Qt::ElideRight, nameTextRect.width(), Qt::TextShowMnemonic);
- paintShadowText(painter, nameTextRect, elidedName);
- painter->restore();
+ painter->save();
+ painter->setPen(QPen(QColor(189, 189, 189)));
+ //FIXME: It looks like Qt is passing us a rectangle that's too small
+ //This deliberately draws outside the lines, and we need to find a better solution.
+ int correctionAmount = groupCornerRadius_ > 0 ? 0 : 1;
+ QRect region(QPoint(option.rect.left() - correctionAmount, option.rect.top()), QSize(option.rect.width() + correctionAmount, option.rect.height() - common_.verticalMargin));
+ QLinearGradient fillGradient(region.topLeft(), region.bottomLeft());
+ fillGradient.setColorAt(0, QColor(244, 244, 244));
+ fillGradient.setColorAt(0.1, QColor(231, 231, 231));
+ fillGradient.setColorAt(1, QColor(209, 209, 209));
+
+ QBrush backgroundBrush = QBrush(fillGradient);
+ QPainterPath fillPath;
+ fillPath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
+ QPainterPath linePath;
+ linePath.addRoundedRect(region, groupCornerRadius_, groupCornerRadius_);
+ painter->fillPath(fillPath, backgroundBrush);
+ painter->drawPath(linePath);
+
+ int triangleHorizontalOffset = 1;
+ int triangleWidth = 9;
+ int triangleHeight = 5;
+ paintExpansionTriangle(painter, region.adjusted(common_.horizontalMargin + triangleHorizontalOffset + 1, 0, 0, 0), triangleWidth, triangleHeight, expanded);
+
+ int textLeftOffset = 3 * common_.horizontalMargin + 1 + triangleWidth + triangleHorizontalOffset;
+ QFontMetrics fontMetrics(groupFont_);
+ int textTopOffset = (region.height() - fontMetrics.height()) / 2;
+ painter->setFont(groupFont_);
+ int contactCountWidth = 0;
+ QRect textRect = region.adjusted(textLeftOffset, textTopOffset, -1 * textLeftOffset, -1 * textTopOffset);
+
+ if (!expanded) {
+ QFontMetrics groupMetrics(groupFont_);
+ int contactCount = rowCount;
+ QString countString = QString("%1").arg(contactCount);
+ contactCountWidth = groupMetrics.width(countString) + 2 * common_.horizontalMargin;
+ int offsetAmount = textRect.width() - contactCountWidth + common_.horizontalMargin;
+ QRect countRect = textRect.adjusted(offsetAmount, 0, 0/*-1 * offsetAmount*/, 0);
+ paintShadowText(painter, countRect, countString);
+ }
+ QRect nameTextRect = expanded ? textRect : textRect.adjusted(0, 0, -contactCountWidth, 0);
+ QString elidedName = fontMetrics.elidedText(name, Qt::ElideRight, nameTextRect.width(), Qt::TextShowMnemonic);
+ paintShadowText(painter, nameTextRect, elidedName);
+ painter->restore();
}
void GroupItemDelegate::paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const {
- // height is the height of the downward pointing triangle
- QPolygonF triangle;
- if (expanded) {
- QPointF triangleTopLeft(region.left(), region.top() + region.height() / 2 - height / 2);
- triangle << triangleTopLeft;
- triangle << triangleTopLeft + QPointF(width, 0);
- triangle << triangleTopLeft + QPointF(width / 2, height);
- // The expanded triangle should be a little lower, because its pointy shape makes it feel
- // as if it's too high.
- triangle.translate(QPointF(0,1));
- }
- else {
- QPointF triangleTopLeft(region.left() + ((width - height) / 2), region.top() + region.height() / 2 - width / 2);
- triangle << triangleTopLeft;
- triangle << triangleTopLeft + QPointF(height, width / 2);
- triangle << triangleTopLeft + QPointF(0, width);
- }
- //qDebug() << "Painting triangle: " << triangle;
-
- QPolygonF triangleShadow(triangle);
- triangleShadow.translate(QPointF(0, -1));
-
- QPainterPath trianglePath;
- QPainterPath triangleShadowPath;
- QBrush triangleBrush(QColor(110, 110, 110));
- QBrush triangleShadowBrush(QColor(47, 47, 47));
- trianglePath.addPolygon(triangle);
- triangleShadowPath.addPolygon(triangleShadow);
- painter->fillPath(triangleShadowPath, triangleShadowBrush);
- painter->fillPath(trianglePath, triangleBrush);
+ // height is the height of the downward pointing triangle
+ QPolygonF triangle;
+ if (expanded) {
+ QPointF triangleTopLeft(region.left(), region.top() + region.height() / 2 - height / 2);
+ triangle << triangleTopLeft;
+ triangle << triangleTopLeft + QPointF(width, 0);
+ triangle << triangleTopLeft + QPointF(width / 2, height);
+ // The expanded triangle should be a little lower, because its pointy shape makes it feel
+ // as if it's too high.
+ triangle.translate(QPointF(0,1));
+ }
+ else {
+ QPointF triangleTopLeft(region.left() + ((width - height) / 2), region.top() + region.height() / 2 - width / 2);
+ triangle << triangleTopLeft;
+ triangle << triangleTopLeft + QPointF(height, width / 2);
+ triangle << triangleTopLeft + QPointF(0, width);
+ }
+ //qDebug() << "Painting triangle: " << triangle;
+
+ QPolygonF triangleShadow(triangle);
+ triangleShadow.translate(QPointF(0, -1));
+
+ QPainterPath trianglePath;
+ QPainterPath triangleShadowPath;
+ QBrush triangleBrush(QColor(110, 110, 110));
+ QBrush triangleShadowBrush(QColor(47, 47, 47));
+ trianglePath.addPolygon(triangle);
+ triangleShadowPath.addPolygon(triangleShadow);
+ painter->fillPath(triangleShadowPath, triangleShadowBrush);
+ painter->fillPath(trianglePath, triangleBrush);
}
void GroupItemDelegate::paintShadowText(QPainter* painter, const QRect& region, const QString& text) const {
- painter->setPen(QPen(QColor(254, 254, 254)));
- painter->drawText(region.adjusted(0, 1, 0, 0), Qt::AlignTop, text);
- painter->setPen(QPen(QColor(115, 115, 115)));
- painter->drawText(region, Qt::AlignTop, text);
+ painter->setPen(QPen(QColor(254, 254, 254)));
+ painter->drawText(region.adjusted(0, 1, 0, 0), Qt::AlignTop, text);
+ painter->setPen(QPen(QColor(115, 115, 115)));
+ painter->drawText(region, Qt::AlignTop, text);
}
const int GroupItemDelegate::groupCornerRadius_ = 0;
diff --git a/Swift/QtUI/Roster/GroupItemDelegate.h b/Swift/QtUI/Roster/GroupItemDelegate.h
index c279c79..f989ed0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.h
+++ b/Swift/QtUI/Roster/GroupItemDelegate.h
@@ -13,17 +13,17 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class QtTreeWidgetItem;
- class GroupItemDelegate {
- public:
- GroupItemDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const;
- private:
- void paintShadowText(QPainter* painter, const QRect& region, const QString& text) const;
- void paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const;
- QFont groupFont_;
- static const int groupCornerRadius_;
- DelegateCommons common_;
- };
+ class QtTreeWidgetItem;
+ class GroupItemDelegate {
+ public:
+ GroupItemDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QString& name, int rowCount, bool expanded) const;
+ private:
+ void paintShadowText(QPainter* painter, const QRect& region, const QString& text) const;
+ void paintExpansionTriangle(QPainter* painter, const QRect& region, int width, int height, bool expanded) const;
+ QFont groupFont_;
+ static const int groupCornerRadius_;
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/Roster/QtFilterWidget.cpp b/Swift/QtUI/Roster/QtFilterWidget.cpp
index 24be214..60b87df 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.cpp
+++ b/Swift/QtUI/Roster/QtFilterWidget.cpp
@@ -27,24 +27,24 @@
namespace Swift {
QtFilterWidget::QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout) : QWidget(parent), treeView_(treeView), eventStream_(eventStream), fuzzyRosterFilter_(0), isModifierSinglePressed_(false) {
- int targetIndex = layout->indexOf(treeView);
+ int targetIndex = layout->indexOf(treeView);
- QVBoxLayout* vboxLayout = new QVBoxLayout(this);
- vboxLayout->setSpacing(0);
- vboxLayout->setContentsMargins(0,0,0,0);
+ QVBoxLayout* vboxLayout = new QVBoxLayout(this);
+ vboxLayout->setSpacing(0);
+ vboxLayout->setContentsMargins(0,0,0,0);
- filterLineEdit_ = new QtClosableLineEdit(this);
- filterLineEdit_->hide();
- vboxLayout->addWidget(filterLineEdit_);
+ filterLineEdit_ = new QtClosableLineEdit(this);
+ filterLineEdit_->hide();
+ vboxLayout->addWidget(filterLineEdit_);
- vboxLayout->addWidget(treeView);
- setLayout(vboxLayout);
- layout->insertWidget(targetIndex, this);
+ vboxLayout->addWidget(treeView);
+ setLayout(vboxLayout);
+ layout->insertWidget(targetIndex, this);
- filterLineEdit_->installEventFilter(this);
- treeView->installEventFilter(this);
+ filterLineEdit_->installEventFilter(this);
+ treeView->installEventFilter(this);
- sourceModel_ = treeView_->model();
+ sourceModel_ = treeView_->model();
}
QtFilterWidget::~QtFilterWidget() {
@@ -52,118 +52,118 @@ QtFilterWidget::~QtFilterWidget() {
}
bool QtFilterWidget::eventFilter(QObject*, QEvent* event) {
- if (event->type() == QEvent::KeyPress ||
- event->type() == QEvent::KeyRelease ||
- // InputMethodQuery got introduced in Qt 5.
+ if (event->type() == QEvent::KeyPress ||
+ event->type() == QEvent::KeyRelease ||
+ // InputMethodQuery got introduced in Qt 5.
#if QT_VERSION >= 0x050000
- event->type() == QEvent::InputMethodQuery ||
+ event->type() == QEvent::InputMethodQuery ||
#endif
- event->type() == QEvent::InputMethod) {
- event->ignore();
- QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
- if (keyEvent) {
- if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) {
- return false;
- } else if ((keyEvent->key() == Qt::Key_Left || keyEvent->key() == Qt::Key_Right) && filterLineEdit_->text().isEmpty()) {
- return false;
- } else if (keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyPress) {
- isModifierSinglePressed_ = true;
- } else if ((keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyRelease && isModifierSinglePressed_)
- || (keyEvent->key() == Qt::Key_Menu)) {
- 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(boost::shared_ptr<UIEvent>(new 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;
+ event->type() == QEvent::InputMethod) {
+ event->ignore();
+ QKeyEvent* keyEvent = dynamic_cast<QKeyEvent*>(event);
+ if (keyEvent) {
+ if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) {
+ return false;
+ } else if ((keyEvent->key() == Qt::Key_Left || keyEvent->key() == Qt::Key_Right) && filterLineEdit_->text().isEmpty()) {
+ return false;
+ } else if (keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyPress) {
+ isModifierSinglePressed_ = true;
+ } else if ((keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyRelease && isModifierSinglePressed_)
+ || (keyEvent->key() == Qt::Key_Menu)) {
+ 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(boost::shared_ptr<UIEvent>(new 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) {
- 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));
+ std::vector<RosterFilter*> filters = treeView_->getRoster()->getFilters();
+ foreach(RosterFilter* 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_) {
- treeView_->getRoster()->addFilter(filter);
- }
- filters_.clear();
+ treeView_->getRoster()->onFilterAdded.disconnect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
+ treeView_->getRoster()->onFilterRemoved.disconnect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
+ foreach(RosterFilter* 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_ = NULL;
- 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());
+ if (fuzzyRosterFilter_) {
+ if (filterLineEdit_->text().isEmpty()) {
+ // remove currently installed search filter and put old filters back
+ treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
+ delete fuzzyRosterFilter_;
+ fuzzyRosterFilter_ = NULL;
+ 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_);
- delete fuzzyRosterFilter_;
- fuzzyRosterFilter_ = NULL;
- }
- fuzzyRosterFilter_ = new FuzzyRosterFilter(Q2PSTRING(filterLineEdit_->text()));
- treeView_->getRoster()->addFilter(fuzzyRosterFilter_);
- treeView_->setCurrentIndex(sourceModel_->index(0, 0, sourceModel_->index(0,0)));
+ if (fuzzyRosterFilter_) {
+ treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
+ delete fuzzyRosterFilter_;
+ fuzzyRosterFilter_ = NULL;
+ }
+ fuzzyRosterFilter_ = new FuzzyRosterFilter(Q2PSTRING(filterLineEdit_->text()));
+ treeView_->getRoster()->addFilter(fuzzyRosterFilter_);
+ treeView_->setCurrentIndex(sourceModel_->index(0, 0, sourceModel_->index(0,0)));
}
void QtFilterWidget::handleFilterAdded(RosterFilter* filter) {
- if (filter != fuzzyRosterFilter_) {
- filterLineEdit_->setText("");
- updateRosterFilters();
- }
+ if (filter != fuzzyRosterFilter_) {
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ }
}
void QtFilterWidget::handleFilterRemoved(RosterFilter* filter) {
- /* make sure we don't end up adding this one back in later */
- filters_.erase(std::remove(filters_.begin(), filters_.end(), filter), filters_.end());
- if (filter != fuzzyRosterFilter_) {
- filterLineEdit_->setText("");
- updateRosterFilters();
- }
+ /* make sure we don't end up adding this one back in later */
+ filters_.erase(std::remove(filters_.begin(), filters_.end(), filter), filters_.end());
+ if (filter != fuzzyRosterFilter_) {
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtFilterWidget.h b/Swift/QtUI/Roster/QtFilterWidget.h
index 314aec2..5edcc5b 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.h
+++ b/Swift/QtUI/Roster/QtFilterWidget.h
@@ -26,32 +26,32 @@ namespace Swift {
class UIEventStream;
class QtClosableLineEdit;
class QtFilterWidget : public QWidget {
- Q_OBJECT
- public:
- QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout = 0);
- virtual ~QtFilterWidget();
-
- protected:
- bool eventFilter(QObject*, QEvent* event);
-
- private:
- void popAllFilters();
- void pushAllFilters();
-
- void updateRosterFilters();
- void updateSearchFilter();
-
- void handleFilterAdded(RosterFilter* filter);
- void handleFilterRemoved(RosterFilter* filter);
-
- private:
- QtClosableLineEdit* filterLineEdit_;
- QtTreeWidget* treeView_;
- UIEventStream* eventStream_;
- std::vector<RosterFilter*> filters_;
- QAbstractItemModel* sourceModel_;
- FuzzyRosterFilter* fuzzyRosterFilter_;
- bool isModifierSinglePressed_;
+ Q_OBJECT
+ public:
+ QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout = 0);
+ virtual ~QtFilterWidget();
+
+ protected:
+ bool eventFilter(QObject*, QEvent* event);
+
+ private:
+ void popAllFilters();
+ void pushAllFilters();
+
+ void updateRosterFilters();
+ void updateSearchFilter();
+
+ void handleFilterAdded(RosterFilter* filter);
+ void handleFilterRemoved(RosterFilter* filter);
+
+ private:
+ QtClosableLineEdit* filterLineEdit_;
+ QtTreeWidget* treeView_;
+ UIEventStream* eventStream_;
+ std::vector<RosterFilter*> filters_;
+ QAbstractItemModel* sourceModel_;
+ FuzzyRosterFilter* fuzzyRosterFilter_;
+ bool isModifierSinglePressed_;
};
}
diff --git a/Swift/QtUI/Roster/QtOccupantListWidget.cpp b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
index 1eefd56..03c14fd 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.cpp
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
@@ -29,47 +29,47 @@ QtOccupantListWidget::~QtOccupantListWidget() {
}
void QtOccupantListWidget::setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions) {
- availableOccupantActions_ = actions;
+ availableOccupantActions_ = actions;
}
void QtOccupantListWidget::contextMenuEvent(QContextMenuEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (!index.isValid()) {
- return;
- }
+ 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_) {
- 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);
- }
- }
- }
+ 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_) {
+ 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/QtOccupantListWidget.h b/Swift/QtUI/Roster/QtOccupantListWidget.h
index d433d07..4cff50f 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.h
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.h
@@ -16,16 +16,16 @@ namespace Swift {
class SettingsProvider;
class QtOccupantListWidget : public QtTreeWidget {
- Q_OBJECT
- public:
- QtOccupantListWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget privateMessageTarget, QWidget* parent = NULL);
- virtual ~QtOccupantListWidget();
- void setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions);
- boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
- protected:
- void contextMenuEvent(QContextMenuEvent* event);
- private:
- std::vector<ChatWindow::OccupantAction> availableOccupantActions_;
+ Q_OBJECT
+ public:
+ QtOccupantListWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget privateMessageTarget, QWidget* parent = NULL);
+ virtual ~QtOccupantListWidget();
+ void setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions);
+ boost::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
+ protected:
+ void contextMenuEvent(QContextMenuEvent* event);
+ private:
+ std::vector<ChatWindow::OccupantAction> availableOccupantActions_;
};
}
diff --git a/Swift/QtUI/Roster/QtRosterWidget.cpp b/Swift/QtUI/Roster/QtRosterWidget.cpp
index 469fa83..027ff00 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.cpp
+++ b/Swift/QtUI/Roster/QtRosterWidget.cpp
@@ -38,125 +38,125 @@ QtRosterWidget::~QtRosterWidget() {
}
void QtRosterWidget::handleEditUserActionTriggered(bool /*checked*/) {
- QModelIndexList selectedIndexList = getSelectedIndexes();
- if (selectedIndexList.empty()) {
- return;
- }
- QModelIndex index = selectedIndexList[0];
- if (!index.isValid()) {
- return;
- }
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
- }
+ QModelIndexList selectedIndexList = getSelectedIndexes();
+ if (selectedIndexList.empty()) {
+ return;
+ }
+ QModelIndex index = selectedIndexList[0];
+ if (!index.isValid()) {
+ return;
+ }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
+ }
}
void QtRosterWidget::contextMenuEvent(QContextMenuEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (!index.isValid()) {
- return;
- }
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- QMenu contextMenu;
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- QAction* editContact = contextMenu.addAction(tr("Edit…"));
- editContact->setEnabled(isOnline());
- QAction* removeContact = contextMenu.addAction(tr("Remove"));
- removeContact->setEnabled(isOnline());
- QAction* showProfileForContact = contextMenu.addAction(tr("Show Profile"));
-
- QAction* unblockContact = NULL;
- if (contact->blockState() == ContactRosterItem::IsBlocked ||
- contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- unblockContact = contextMenu.addAction(tr("Unblock"));
- unblockContact->setEnabled(isOnline());
- }
-
- QAction* blockContact = NULL;
- if (contact->blockState() == ContactRosterItem::IsUnblocked) {
- blockContact = contextMenu.addAction(tr("Block"));
- blockContact->setEnabled(isOnline());
- }
+ QModelIndex index = indexAt(event->pos());
+ if (!index.isValid()) {
+ return;
+ }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ QMenu contextMenu;
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ QAction* editContact = contextMenu.addAction(tr("Edit…"));
+ editContact->setEnabled(isOnline());
+ QAction* removeContact = contextMenu.addAction(tr("Remove"));
+ removeContact->setEnabled(isOnline());
+ QAction* showProfileForContact = contextMenu.addAction(tr("Show Profile"));
+
+ QAction* unblockContact = NULL;
+ if (contact->blockState() == ContactRosterItem::IsBlocked ||
+ contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ unblockContact = contextMenu.addAction(tr("Unblock"));
+ unblockContact->setEnabled(isOnline());
+ }
+
+ QAction* blockContact = NULL;
+ if (contact->blockState() == ContactRosterItem::IsUnblocked) {
+ blockContact = contextMenu.addAction(tr("Block"));
+ blockContact->setEnabled(isOnline());
+ }
#ifdef SWIFT_EXPERIMENTAL_FT
- QAction* sendFile = NULL;
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- sendFile = contextMenu.addAction(tr("Send File"));
- sendFile->setEnabled(isOnline());
- }
+ QAction* sendFile = NULL;
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ sendFile = contextMenu.addAction(tr("Send File"));
+ sendFile->setEnabled(isOnline());
+ }
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
- QAction* startWhiteboardChat = NULL;
- if (contact->supportsFeature(ContactRosterItem::WhiteboardFeature)) {
- startWhiteboardChat = contextMenu.addAction(tr("Start Whiteboard Chat"));
- startWhiteboardChat->setEnabled(isOnline());
- }
+ QAction* startWhiteboardChat = NULL;
+ if (contact->supportsFeature(ContactRosterItem::WhiteboardFeature)) {
+ startWhiteboardChat = contextMenu.addAction(tr("Start Whiteboard Chat"));
+ startWhiteboardChat->setEnabled(isOnline());
+ }
#endif
- QAction* result = contextMenu.exec(event->globalPos());
- if (result == editContact) {
- eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
- }
- else if (result == removeContact) {
- if (QtContactEditWindow::confirmContactDeletion(contact->getJID())) {
- eventStream_->send(boost::make_shared<RemoveRosterItemUIEvent>(contact->getJID()));
- }
- }
- else if (result == showProfileForContact) {
- eventStream_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(contact->getJID()));
- }
- else if (unblockContact && result == unblockContact) {
- if (contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- QMessageBox messageBox(QMessageBox::Question, tr("Swift"), tr("%2 is currently blocked because of a block on all users of the %1 service.\n %2 cannot be unblocked individually; do you want to unblock all %1 users?").arg(P2QSTRING(contact->getJID().getDomain()), P2QSTRING(contact->getJID().toString())), QMessageBox::NoButton, this);
- QPushButton* unblockDomainButton = messageBox.addButton(tr("Unblock %1 domain").arg(P2QSTRING(contact->getJID().getDomain())), QMessageBox::AcceptRole);
- messageBox.addButton(QMessageBox::Abort);
-
- messageBox.exec();
- if (messageBox.clickedButton() == unblockDomainButton) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID().getDomain()));
- }
- } else {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID()));
- }
- }
- else if (blockContact && result == blockContact) {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, contact->getJID()));
- }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result == editContact) {
+ eventStream_->send(boost::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
+ }
+ else if (result == removeContact) {
+ if (QtContactEditWindow::confirmContactDeletion(contact->getJID())) {
+ eventStream_->send(boost::make_shared<RemoveRosterItemUIEvent>(contact->getJID()));
+ }
+ }
+ else if (result == showProfileForContact) {
+ eventStream_->send(boost::make_shared<ShowProfileForRosterItemUIEvent>(contact->getJID()));
+ }
+ else if (unblockContact && result == unblockContact) {
+ if (contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ QMessageBox messageBox(QMessageBox::Question, tr("Swift"), tr("%2 is currently blocked because of a block on all users of the %1 service.\n %2 cannot be unblocked individually; do you want to unblock all %1 users?").arg(P2QSTRING(contact->getJID().getDomain()), P2QSTRING(contact->getJID().toString())), QMessageBox::NoButton, this);
+ QPushButton* unblockDomainButton = messageBox.addButton(tr("Unblock %1 domain").arg(P2QSTRING(contact->getJID().getDomain())), QMessageBox::AcceptRole);
+ messageBox.addButton(QMessageBox::Abort);
+
+ messageBox.exec();
+ if (messageBox.clickedButton() == unblockDomainButton) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID().getDomain()));
+ }
+ } else {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID()));
+ }
+ }
+ else if (blockContact && result == blockContact) {
+ eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, contact->getJID()));
+ }
#ifdef SWIFT_EXPERIMENTAL_FT
- else if (sendFile && result == sendFile) {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Send File"), "", tr("All Files (*);;"));
- if (!fileName.isEmpty()) {
- eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(fileName)));
- }
- }
+ else if (sendFile && result == sendFile) {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Send File"), "", tr("All Files (*);;"));
+ if (!fileName.isEmpty()) {
+ eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(fileName)));
+ }
+ }
#endif
#ifdef SWIFT_EXPERIMENTAL_WB
- else if (startWhiteboardChat && result == startWhiteboardChat) {
- eventStream_->send(boost::make_shared<RequestWhiteboardUIEvent>(contact->getJID()));
- }
+ else if (startWhiteboardChat && result == startWhiteboardChat) {
+ eventStream_->send(boost::make_shared<RequestWhiteboardUIEvent>(contact->getJID()));
+ }
#endif
- }
- else if (GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item)) {
- QAction* renameGroupAction = contextMenu.addAction(tr("Rename"));
- if (P2QSTRING(group->getDisplayName()) == tr("Contacts")) {
- renameGroupAction->setEnabled(false);
- }
- else {
- renameGroupAction->setEnabled(isOnline());
- }
- QAction* result = contextMenu.exec(event->globalPos());
- if (result == renameGroupAction) {
- renameGroup(group);
- }
- }
+ }
+ else if (GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item)) {
+ QAction* renameGroupAction = contextMenu.addAction(tr("Rename"));
+ if (P2QSTRING(group->getDisplayName()) == tr("Contacts")) {
+ renameGroupAction->setEnabled(false);
+ }
+ else {
+ renameGroupAction->setEnabled(isOnline());
+ }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result == renameGroupAction) {
+ renameGroup(group);
+ }
+ }
}
void QtRosterWidget::renameGroup(GroupRosterItem* group) {
- bool ok;
- QString newName = QInputDialog::getText(NULL, tr("Rename group"), tr("Enter a new name for group '%1':").arg(P2QSTRING(group->getDisplayName())), QLineEdit::Normal, P2QSTRING(group->getDisplayName()), &ok);
- if (ok) {
- eventStream_->send(boost::make_shared<RenameGroupUIEvent>(group->getDisplayName(), Q2PSTRING(newName)));
- }
+ bool ok;
+ QString newName = QInputDialog::getText(NULL, tr("Rename group"), tr("Enter a new name for group '%1':").arg(P2QSTRING(group->getDisplayName())), QLineEdit::Normal, P2QSTRING(group->getDisplayName()), &ok);
+ if (ok) {
+ eventStream_->send(boost::make_shared<RenameGroupUIEvent>(group->getDisplayName(), Q2PSTRING(newName)));
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtRosterWidget.h b/Swift/QtUI/Roster/QtRosterWidget.h
index de5ee9b..25f7f9d 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.h
+++ b/Swift/QtUI/Roster/QtRosterWidget.h
@@ -12,16 +12,16 @@ namespace Swift {
class QtUIPreferences;
class QtRosterWidget : public QtTreeWidget {
- Q_OBJECT
- public:
- QtRosterWidget(UIEventStream* eventStream, SettingsProvider* settings, QWidget* parent = 0);
- virtual ~QtRosterWidget();
- public slots:
- void handleEditUserActionTriggered(bool checked);
- protected:
- void contextMenuEvent(QContextMenuEvent* event);
- private:
- void renameGroup(GroupRosterItem* group);
+ Q_OBJECT
+ public:
+ QtRosterWidget(UIEventStream* eventStream, SettingsProvider* settings, QWidget* parent = 0);
+ virtual ~QtRosterWidget();
+ public slots:
+ void handleEditUserActionTriggered(bool checked);
+ protected:
+ void contextMenuEvent(QContextMenuEvent* event);
+ private:
+ void renameGroup(GroupRosterItem* group);
};
}
diff --git a/Swift/QtUI/Roster/QtTreeWidget.cpp b/Swift/QtUI/Roster/QtTreeWidget.cpp
index 277effb..a0b6e92 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.cpp
+++ b/Swift/QtUI/Roster/QtTreeWidget.cpp
@@ -32,232 +32,232 @@
namespace Swift {
QtTreeWidget::QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent) : QTreeView(parent), tooltipShown_(false), messageTarget_(messageTarget) {
- eventStream_ = eventStream;
- settings_ = settings;
- model_ = new RosterModel(this, settings_->getSetting(QtUISettingConstants::USE_SCREENREADER));
- setModel(model_);
- delegate_ = new RosterDelegate(this, settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- setItemDelegate(delegate_);
- setHeaderHidden(true);
+ eventStream_ = eventStream;
+ settings_ = settings;
+ model_ = new RosterModel(this, settings_->getSetting(QtUISettingConstants::USE_SCREENREADER));
+ setModel(model_);
+ delegate_ = new RosterDelegate(this, settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ setItemDelegate(delegate_);
+ setHeaderHidden(true);
#ifdef SWIFT_PLATFORM_MACOSX
- setAlternatingRowColors(true);
+ setAlternatingRowColors(true);
#endif
- setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
- expandAll();
- setAnimated(true);
- setIndentation(0);
+ setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
+ expandAll();
+ setAnimated(true);
+ setIndentation(0);
#ifdef SWIFT_EXPERIMENTAL_FT
- setAcceptDrops(true);
+ setAcceptDrops(true);
#endif
- setDragEnabled(true);
- setRootIsDecorated(true);
- connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
- connect(model_, SIGNAL(itemExpanded(const QModelIndex&, bool)), this, SLOT(handleModelItemExpanded(const QModelIndex&, bool)));
- connect(this, SIGNAL(expanded(const QModelIndex&)), this, SLOT(handleExpanded(const QModelIndex&)));
- connect(this, SIGNAL(collapsed(const QModelIndex&)), this, SLOT(handleCollapsed(const QModelIndex&)));
- connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
-
- settings_->onSettingChanged.connect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
+ setDragEnabled(true);
+ setRootIsDecorated(true);
+ connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&)));
+ connect(model_, SIGNAL(itemExpanded(const QModelIndex&, bool)), this, SLOT(handleModelItemExpanded(const QModelIndex&, bool)));
+ connect(this, SIGNAL(expanded(const QModelIndex&)), this, SLOT(handleExpanded(const QModelIndex&)));
+ connect(this, SIGNAL(collapsed(const QModelIndex&)), this, SLOT(handleCollapsed(const QModelIndex&)));
+ connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&)));
+
+ settings_->onSettingChanged.connect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
}
QtTreeWidget::~QtTreeWidget() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
- delete model_;
- delete delegate_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtTreeWidget::handleSettingChanged, this, _1));
+ delete model_;
+ delete delegate_;
}
void QtTreeWidget::handleSettingChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- repaint();
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ repaint();
+ }
}
void QtTreeWidget::handleRefreshTooltip() {
- if (tooltipShown_) {
- QPoint position = QCursor::pos();
- QModelIndex index = indexAt(mapFromGlobal(position));
- QToolTip::showText(position, model_->data(index, Qt::ToolTipRole).toString());
- }
+ if (tooltipShown_) {
+ QPoint position = QCursor::pos();
+ QModelIndex index = indexAt(mapFromGlobal(position));
+ QToolTip::showText(position, model_->data(index, Qt::ToolTipRole).toString());
+ }
}
void QtTreeWidget::setRosterModel(Roster* roster) {
- roster_ = roster;
- model_->setRoster(roster);
- expandAll();
+ roster_ = roster;
+ model_->setRoster(roster);
+ expandAll();
}
void QtTreeWidget::refreshTooltip() {
- // Qt needs some time to emit the events we need to detect tooltip's visibility correctly; 20 ms should be enough
- QTimer::singleShot(20, this, SLOT(handleRefreshTooltip()));
+ // Qt needs some time to emit the events we need to detect tooltip's visibility correctly; 20 ms should be enough
+ QTimer::singleShot(20, this, SLOT(handleRefreshTooltip()));
}
QtTreeWidgetItem* QtTreeWidget::getRoot() {
- return treeRoot_;
+ return treeRoot_;
}
void QtTreeWidget::handleClicked(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- setExpanded(index, !isExpanded(index));
- }
- currentChanged(index, QModelIndex());
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ setExpanded(index, !isExpanded(index));
+ }
+ currentChanged(index, QModelIndex());
}
QModelIndexList QtTreeWidget::getSelectedIndexes() const {
- // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
- // QModelIndexList destructor.
- // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
- // was resolved by linking against the debug libs, ours isn't, and we're not alone)
- QItemSelection ranges = selectionModel()->selection();
- QModelIndexList selectedIndexList;
- for (int i = 0; i < ranges.count(); ++i) {
- QModelIndex parent = ranges.at(i).parent();
- int right = ranges.at(i).model()->columnCount(parent) - 1;
- if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
- for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
- selectedIndexList.append(ranges.at(i).model()->index(r, 0, parent));
- }
- }
- }
- return selectedIndexList;
+ // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the
+ // QModelIndexList destructor.
+ // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case
+ // was resolved by linking against the debug libs, ours isn't, and we're not alone)
+ QItemSelection ranges = selectionModel()->selection();
+ QModelIndexList selectedIndexList;
+ for (int i = 0; i < ranges.count(); ++i) {
+ QModelIndex parent = ranges.at(i).parent();
+ int right = ranges.at(i).model()->columnCount(parent) - 1;
+ if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) {
+ for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) {
+ selectedIndexList.append(ranges.at(i).model()->index(r, 0, parent));
+ }
+ }
+ }
+ return selectedIndexList;
}
void QtTreeWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous) {
- RosterItem* item = NULL;
- QModelIndexList selectedIndexList = getSelectedIndexes();
- if (selectedIndexList.empty() || !selectedIndexList[0].isValid()) {
- /* I didn't quite understand why using current didn't seem to work here.*/
- }
- else if (current.isValid()) {
- item = static_cast<RosterItem*>(current.internalPointer());
- item = dynamic_cast<ContactRosterItem*>(item);
- }
- onSomethingSelectedChanged(item);
- QTreeView::currentChanged(current, previous);
+ RosterItem* item = NULL;
+ QModelIndexList selectedIndexList = getSelectedIndexes();
+ if (selectedIndexList.empty() || !selectedIndexList[0].isValid()) {
+ /* I didn't quite understand why using current didn't seem to work here.*/
+ }
+ else if (current.isValid()) {
+ item = static_cast<RosterItem*>(current.internalPointer());
+ item = dynamic_cast<ContactRosterItem*>(item);
+ }
+ onSomethingSelectedChanged(item);
+ QTreeView::currentChanged(current, previous);
}
void QtTreeWidget::handleItemActivated(const QModelIndex& index) {
- JID target = jidFromIndex(index);
- if (target.isValid()) {
- eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
- }
+ JID target = jidFromIndex(index);
+ if (target.isValid()) {
+ eventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(target)));
+ }
}
void QtTreeWidget::dragEnterEvent(QDragEnterEvent *event) {
- if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
- event->acceptProposedAction();
- }
+ if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
+ event->acceptProposedAction();
+ }
}
void QtTreeWidget::dropEvent(QDropEvent *event) {
- QModelIndex index = indexAt(event->pos());
- if (index.isValid()) {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- QString filename = event->mimeData()->urls().at(0).toLocalFile();
- if (!filename.isEmpty()) {
- eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(filename)));
- }
- }
- }
- }
+ QModelIndex index = indexAt(event->pos());
+ if (index.isValid()) {
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ QString filename = event->mimeData()->urls().at(0).toLocalFile();
+ if (!filename.isEmpty()) {
+ eventStream_->send(boost::make_shared<SendFileUIEvent>(contact->getJID(), Q2PSTRING(filename)));
+ }
+ }
+ }
+ }
}
void QtTreeWidget::dragMoveEvent(QDragMoveEvent* event) {
- QModelIndex index = indexAt(event->pos());
- if (index.isValid()) {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
- if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
- event->accept();
- return;
- }
- }
- }
- QTreeView::dragMoveEvent(event);
+ QModelIndex index = indexAt(event->pos());
+ if (index.isValid()) {
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item)) {
+ if (contact->supportsFeature(ContactRosterItem::FileTransferFeature)) {
+ event->accept();
+ return;
+ }
+ }
+ }
+ QTreeView::dragMoveEvent(event);
}
bool QtTreeWidget::event(QEvent* event) {
- QChildEvent* childEvent = NULL;
- if ((childEvent = dynamic_cast<QChildEvent*>(event))) {
- if (childEvent->polished()) {
- if (dynamic_cast<QLabel*>(childEvent->child())) {
- tooltipShown_ = true;
- }
- }
- else if (childEvent->removed()) {
- if (childEvent->child()->objectName() == "qtooltip_label") {
- tooltipShown_ = false;
- }
- }
- }
- return QAbstractItemView::event(event);
+ QChildEvent* childEvent = NULL;
+ if ((childEvent = dynamic_cast<QChildEvent*>(event))) {
+ if (childEvent->polished()) {
+ if (dynamic_cast<QLabel*>(childEvent->child())) {
+ tooltipShown_ = true;
+ }
+ }
+ else if (childEvent->removed()) {
+ if (childEvent->child()->objectName() == "qtooltip_label") {
+ tooltipShown_ = false;
+ }
+ }
+ }
+ return QAbstractItemView::event(event);
}
void QtTreeWidget::handleExpanded(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- item->setExpanded(true);
- }
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ item->setExpanded(true);
+ }
}
void QtTreeWidget::handleCollapsed(const QModelIndex& index) {
- GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
- if (item) {
- item->setExpanded(false);
- }
+ GroupRosterItem* item = dynamic_cast<GroupRosterItem*>(static_cast<RosterItem*>(index.internalPointer()));
+ if (item) {
+ item->setExpanded(false);
+ }
}
void QtTreeWidget::handleModelItemExpanded(const QModelIndex& index, bool shouldExpand) {
- if (!index.isValid()) {
- return;
- }
- bool alreadyRight = this->isExpanded(index) == shouldExpand;
- if (alreadyRight) {
- return;
- }
- setExpanded(index, shouldExpand);
+ if (!index.isValid()) {
+ return;
+ }
+ bool alreadyRight = this->isExpanded(index) == shouldExpand;
+ if (alreadyRight) {
+ return;
+ }
+ setExpanded(index, shouldExpand);
}
void QtTreeWidget::drawBranches(QPainter*, const QRect&, const QModelIndex&) const {
}
void QtTreeWidget::show() {
- QWidget::show();
+ QWidget::show();
}
void QtTreeWidget::setMessageTarget(MessageTarget messageTarget) {
- messageTarget_ = messageTarget;
+ messageTarget_ = messageTarget;
}
JID QtTreeWidget::jidFromIndex(const QModelIndex& index) const {
- JID target;
- if (messageTarget_ == MessageDisplayJID) {
- target = JID(Q2PSTRING(index.data(DisplayJIDRole).toString()));
- target = target.toBare();
- }
- if (!target.isValid()) {
- target = JID(Q2PSTRING(index.data(JIDRole).toString()));
- }
- return target;
+ JID target;
+ if (messageTarget_ == MessageDisplayJID) {
+ target = JID(Q2PSTRING(index.data(DisplayJIDRole).toString()));
+ target = target.toBare();
+ }
+ if (!target.isValid()) {
+ target = JID(Q2PSTRING(index.data(JIDRole).toString()));
+ }
+ return target;
}
JID QtTreeWidget::selectedJID() const {
- QModelIndexList list = selectedIndexes();
- if (list.size() != 1) {
- return JID();
- }
- return jidFromIndex(list[0]);
+ QModelIndexList list = selectedIndexes();
+ if (list.size() != 1) {
+ return JID();
+ }
+ return jidFromIndex(list[0]);
}
void QtTreeWidget::setOnline(bool isOnline) {
- isOnline_ = isOnline;
+ isOnline_ = isOnline;
}
bool QtTreeWidget::isOnline() const {
- return isOnline_;
+ return isOnline_;
}
}
diff --git a/Swift/QtUI/Roster/QtTreeWidget.h b/Swift/QtUI/Roster/QtTreeWidget.h
index 205bc70..9a94e8f 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.h
+++ b/Swift/QtUI/Roster/QtTreeWidget.h
@@ -22,59 +22,59 @@ class UIEventStream;
class SettingsProvider;
class QtTreeWidget : public QTreeView {
- Q_OBJECT
- public:
- enum MessageTarget {MessageDefaultJID, MessageDisplayJID};
+ Q_OBJECT
+ public:
+ enum MessageTarget {MessageDefaultJID, MessageDisplayJID};
- QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent = 0);
- ~QtTreeWidget();
- void show();
- QtTreeWidgetItem* getRoot();
- void setRosterModel(Roster* roster);
- Roster* getRoster() {return roster_;}
- void refreshTooltip();
- void setMessageTarget(MessageTarget messageTarget);
- JID jidFromIndex(const QModelIndex& index) const;
- JID selectedJID() const;
- void setOnline(bool isOnline);
+ QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent = 0);
+ ~QtTreeWidget();
+ void show();
+ QtTreeWidgetItem* getRoot();
+ void setRosterModel(Roster* roster);
+ Roster* getRoster() {return roster_;}
+ void refreshTooltip();
+ void setMessageTarget(MessageTarget messageTarget);
+ JID jidFromIndex(const QModelIndex& index) const;
+ JID selectedJID() const;
+ void setOnline(bool isOnline);
- public:
- boost::signal<void (RosterItem*)> onSomethingSelectedChanged;
+ public:
+ boost::signal<void (RosterItem*)> onSomethingSelectedChanged;
- private slots:
- void handleItemActivated(const QModelIndex&);
- void handleModelItemExpanded(const QModelIndex&, bool expanded);
- void handleExpanded(const QModelIndex&);
- void handleCollapsed(const QModelIndex&);
- void handleClicked(const QModelIndex&);
- void handleSettingChanged(const std::string& setting);
- void handleRefreshTooltip();
+ private slots:
+ void handleItemActivated(const QModelIndex&);
+ void handleModelItemExpanded(const QModelIndex&, bool expanded);
+ void handleExpanded(const QModelIndex&);
+ void handleCollapsed(const QModelIndex&);
+ void handleClicked(const QModelIndex&);
+ void handleSettingChanged(const std::string& setting);
+ void handleRefreshTooltip();
- protected:
- void dragEnterEvent(QDragEnterEvent* event);
- void dropEvent(QDropEvent* event);
- void dragMoveEvent(QDragMoveEvent* event);
- bool event(QEvent* event);
- QModelIndexList getSelectedIndexes() const;
- bool isOnline() const;
+ protected:
+ void dragEnterEvent(QDragEnterEvent* event);
+ void dropEvent(QDropEvent* event);
+ void dragMoveEvent(QDragMoveEvent* event);
+ bool event(QEvent* event);
+ QModelIndexList getSelectedIndexes() const;
+ bool isOnline() const;
- private:
- void drawBranches(QPainter*, const QRect&, const QModelIndex&) const;
+ private:
+ void drawBranches(QPainter*, const QRect&, const QModelIndex&) const;
- protected slots:
- virtual void currentChanged(const QModelIndex& current, const QModelIndex& previous);
- protected:
- UIEventStream* eventStream_;
+ protected slots:
+ virtual void currentChanged(const QModelIndex& current, const QModelIndex& previous);
+ protected:
+ UIEventStream* eventStream_;
- private:
- RosterModel* model_;
- Roster* roster_;
- RosterDelegate* delegate_;
- QtTreeWidgetItem* treeRoot_;
- SettingsProvider* settings_;
- bool tooltipShown_;
- MessageTarget messageTarget_;
- bool isOnline_;
+ private:
+ RosterModel* model_;
+ Roster* roster_;
+ RosterDelegate* delegate_;
+ QtTreeWidgetItem* treeRoot_;
+ SettingsProvider* settings_;
+ bool tooltipShown_;
+ MessageTarget messageTarget_;
+ bool isOnline_;
};
}
diff --git a/Swift/QtUI/Roster/RosterDelegate.cpp b/Swift/QtUI/Roster/RosterDelegate.cpp
index ff950e5..061982e 100644
--- a/Swift/QtUI/Roster/RosterDelegate.cpp
+++ b/Swift/QtUI/Roster/RosterDelegate.cpp
@@ -25,59 +25,59 @@
namespace Swift {
RosterDelegate::RosterDelegate(QtTreeWidget* tree, bool compact) : compact_(compact) {
- tree_ = tree;
- groupDelegate_ = new GroupItemDelegate();
+ tree_ = tree;
+ groupDelegate_ = new GroupItemDelegate();
}
RosterDelegate::~RosterDelegate() {
- delete groupDelegate_;
+ delete groupDelegate_;
}
void RosterDelegate::setCompact(bool compact) {
- compact_ = compact;
- emit sizeHintChanged(QModelIndex());
+ compact_ = compact;
+ emit sizeHintChanged(QModelIndex());
}
-
+
QSize RosterDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (dynamic_cast<GroupRosterItem*>(item)) {
- return groupDelegate_->sizeHint(option, index);
- }
- return contactSizeHint(option, index);
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (dynamic_cast<GroupRosterItem*>(item)) {
+ return groupDelegate_->sizeHint(option, index);
+ }
+ return contactSizeHint(option, index);
}
QSize RosterDelegate::contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const {
- return common_.contactSizeHint(option, index, compact_);
+ return common_.contactSizeHint(option, index, compact_);
}
void RosterDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
- if (dynamic_cast<GroupRosterItem*>(item)) {
- paintGroup(painter, option, index);
- } else {
- paintContact(painter, option, index);
- }
+ RosterItem* item = static_cast<RosterItem*>(index.internalPointer());
+ if (dynamic_cast<GroupRosterItem*>(item)) {
+ paintGroup(painter, option, index);
+ } else {
+ paintContact(painter, option, index);
+ }
}
void RosterDelegate::paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- if (index.isValid()) {
- groupDelegate_->paint(painter, option, index.data(Qt::DisplayRole).toString(), index.data(ChildCountRole).toInt(), tree_->isExpanded(index));
- }
+ if (index.isValid()) {
+ groupDelegate_->paint(painter, option, index.data(Qt::DisplayRole).toString(), index.data(ChildCountRole).toInt(), tree_->isExpanded(index));
+ }
}
void RosterDelegate::paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
- QString avatarPath;
- if (index.data(AvatarRole).isValid() && !index.data(AvatarRole).value<QString>().isNull()) {
- avatarPath = index.data(AvatarRole).value<QString>();
- }
- QIcon presenceIcon = index.data(PresenceIconRole).isValid() && !index.data(PresenceIconRole).value<QIcon>().isNull()
- ? index.data(PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- bool isIdle = index.data(IdleRole).isValid() ? index.data(IdleRole).toBool() : false;
- QString name = index.data(Qt::DisplayRole).toString();
- QString statusText = index.data(StatusTextRole).toString();
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, isIdle, 0, compact_);
+ QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath;
+ if (index.data(AvatarRole).isValid() && !index.data(AvatarRole).value<QString>().isNull()) {
+ avatarPath = index.data(AvatarRole).value<QString>();
+ }
+ QIcon presenceIcon = index.data(PresenceIconRole).isValid() && !index.data(PresenceIconRole).value<QIcon>().isNull()
+ ? index.data(PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ bool isIdle = index.data(IdleRole).isValid() ? index.data(IdleRole).toBool() : false;
+ QString name = index.data(Qt::DisplayRole).toString();
+ QString statusText = index.data(StatusTextRole).toString();
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, isIdle, 0, compact_);
}
}
diff --git a/Swift/QtUI/Roster/RosterDelegate.h b/Swift/QtUI/Roster/RosterDelegate.h
index f17f9b8..34c1569 100644
--- a/Swift/QtUI/Roster/RosterDelegate.h
+++ b/Swift/QtUI/Roster/RosterDelegate.h
@@ -14,22 +14,22 @@
#include <Swift/QtUI/Roster/GroupItemDelegate.h>
namespace Swift {
- class QtTreeWidget;
- class RosterDelegate : public QStyledItemDelegate {
- public:
- RosterDelegate(QtTreeWidget* tree, bool compact);
- ~RosterDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
- private:
- QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- bool compact_;
- DelegateCommons common_;
- GroupItemDelegate* groupDelegate_;
- QtTreeWidget* tree_;
- };
+ class QtTreeWidget;
+ class RosterDelegate : public QStyledItemDelegate {
+ public:
+ RosterDelegate(QtTreeWidget* tree, bool compact);
+ ~RosterDelegate();
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ public slots:
+ void setCompact(bool compact);
+ private:
+ QSize contactSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paintGroup(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paintContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ bool compact_;
+ DelegateCommons common_;
+ GroupItemDelegate* groupDelegate_;
+ QtTreeWidget* tree_;
+ };
}
diff --git a/Swift/QtUI/Roster/RosterModel.cpp b/Swift/QtUI/Roster/RosterModel.cpp
index 60e4aca..2b3759d 100644
--- a/Swift/QtUI/Roster/RosterModel.cpp
+++ b/Swift/QtUI/Roster/RosterModel.cpp
@@ -29,251 +29,251 @@
namespace Swift {
RosterModel::RosterModel(QtTreeWidget* view, bool screenReaderMode) : roster_(NULL), view_(view), screenReader_(screenReaderMode) {
- const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
- cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
+ const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
+ cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
}
RosterModel::~RosterModel() {
- delete cachedImageScaler_;
+ 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();
+ 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()) {
- GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(item);
- if (!child) continue;
- emit itemExpanded(index(child), child->isExpanded());
- }
+ //emit layoutChanged();
+ beginResetModel();
+ endResetModel(); // TODO: Not sure if this isn't too early?
+ if (!roster_) {
+ return;
+ }
+ foreach (RosterItem* 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();
+ reLayout();
}
void RosterModel::handleDataChanged(RosterItem* item) {
- Q_ASSERT(item);
- QModelIndex modelIndex = index(item);
- if (modelIndex.isValid()) {
- emit dataChanged(modelIndex, modelIndex);
- view_->refreshTooltip();
- }
+ 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)) == NULL) {
- flags |= Qt::ItemIsDragEnabled;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (dynamic_cast<GroupRosterItem*>(getItem(index)) == NULL) {
+ flags |= Qt::ItemIsDragEnabled;
+ }
+ return flags;
}
int RosterModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
RosterItem* RosterModel::getItem(const QModelIndex& index) const {
- return index.isValid() ? static_cast<RosterItem*>(index.internalPointer()) : NULL;
+ return index.isValid() ? static_cast<RosterItem*>(index.internalPointer()) : NULL;
}
QVariant RosterModel::data(const QModelIndex& index, int role) const {
- RosterItem* item = getItem(index);
- if (!item) return QVariant();
-
- switch (role) {
- case Qt::DisplayRole: return getScreenReaderTextOr(item, P2QSTRING(item->getDisplayName()));
- case Qt::TextColorRole: return getTextColor(item);
- case Qt::BackgroundColorRole: return getBackgroundColor(item);
- case Qt::ToolTipRole: return getToolTip(item);
- case StatusTextRole: return getStatusText(item);
- case AvatarRole: return getAvatar(item);
- case PresenceIconRole: return getPresenceIcon(item);
- case ChildCountRole: return getChildCount(item);
- case IdleRole: return getIsIdle(item);
- case JIDRole: return getJID(item);
- case DisplayJIDRole: return getDisplayJID(item);
- default: return QVariant();
- }
+ RosterItem* item = getItem(index);
+ if (!item) return QVariant();
+
+ switch (role) {
+ case Qt::DisplayRole: return getScreenReaderTextOr(item, P2QSTRING(item->getDisplayName()));
+ case Qt::TextColorRole: return getTextColor(item);
+ case Qt::BackgroundColorRole: return getBackgroundColor(item);
+ case Qt::ToolTipRole: return getToolTip(item);
+ case StatusTextRole: return getStatusText(item);
+ case AvatarRole: return getAvatar(item);
+ case PresenceIconRole: return getPresenceIcon(item);
+ case ChildCountRole: return getChildCount(item);
+ case IdleRole: return getIsIdle(item);
+ case JIDRole: return getJID(item);
+ case DisplayJIDRole: return getDisplayJID(item);
+ default: return QVariant();
+ }
}
QString RosterModel::getScreenReaderTextOr(RosterItem* item, const QString& alternative) const {
- QString name = P2QSTRING(item->getDisplayName());
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact && screenReader_) {
- name += ": " + P2QSTRING(statusShowTypeToFriendlyName(contact->getStatusShow()));
- if (!contact->getStatusText().empty()) {
- name += " (" + P2QSTRING(contact->getStatusText()) + ")";
- }
- return name;
- }
- else {
- return alternative;
- }
+ QString name = P2QSTRING(item->getDisplayName());
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact && screenReader_) {
+ name += ": " + P2QSTRING(statusShowTypeToFriendlyName(contact->getStatusShow()));
+ if (!contact->getStatusText().empty()) {
+ name += " (" + P2QSTRING(contact->getStatusText()) + ")";
+ }
+ return name;
+ }
+ else {
+ return alternative;
+ }
}
int RosterModel::getChildCount(RosterItem* item) const {
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- return group ? group->getDisplayedChildren().size() : 0;
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ return group ? group->getDisplayedChildren().size() : 0;
}
bool RosterModel::getIsIdle(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- return contact ? !contact->getIdleText().empty() : false;
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ return contact ? !contact->getIdleText().empty() : false;
}
QColor RosterModel::intToColor(int color) const {
- return QColor(
- ((color & 0xFF0000)>>16),
- ((color & 0xFF00)>>8),
- (color & 0xFF));
+ return QColor(
+ ((color & 0xFF0000)>>16),
+ ((color & 0xFF00)>>8),
+ (color & 0xFF));
}
QColor RosterModel::getTextColor(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- int color = 0;
- if (contact) {
- switch (contact->getStatusShow()) {
- case StatusShow::Online: color = 0x000000; break;
- case StatusShow::Away: color = 0x336699; break;
- case StatusShow::XA: color = 0x336699; break;
- case StatusShow::FFC: color = 0x000000; break;
- case StatusShow::DND: color = 0x990000; break;
- case StatusShow::None: color = 0x7F7F7F;break;
- }
- }
- return intToColor(color);
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ int color = 0;
+ if (contact) {
+ switch (contact->getStatusShow()) {
+ case StatusShow::Online: color = 0x000000; break;
+ case StatusShow::Away: color = 0x336699; break;
+ case StatusShow::XA: color = 0x336699; break;
+ case StatusShow::FFC: color = 0x000000; break;
+ case StatusShow::DND: color = 0x990000; break;
+ case StatusShow::None: color = 0x7F7F7F;break;
+ }
+ }
+ return intToColor(color);
}
QColor RosterModel::getBackgroundColor(RosterItem* item) const {
- return dynamic_cast<ContactRosterItem*>(item) ? intToColor(0xFFFFFF) : intToColor(0x969696);
+ return dynamic_cast<ContactRosterItem*>(item) ? intToColor(0xFFFFFF) : intToColor(0x969696);
}
QString RosterModel::getToolTip(RosterItem* item) const {
- QString tip(P2QSTRING(item->getDisplayName()));
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (contact) {
- return RosterTooltip::buildDetailedTooltip(contact, cachedImageScaler_);
- }
- return tip;
+ QString tip(P2QSTRING(item->getDisplayName()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (contact) {
+ return RosterTooltip::buildDetailedTooltip(contact, cachedImageScaler_);
+ }
+ return tip;
}
QString RosterModel::getAvatar(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) {
- return "";
- }
- return P2QSTRING(pathToString(contact->getAvatarPath()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) {
+ return "";
+ }
+ return P2QSTRING(pathToString(contact->getAvatarPath()));
}
QString RosterModel::getStatusText(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) return "";
- return P2QSTRING(contact->getStatusText());
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) return "";
+ return P2QSTRING(contact->getStatusText());
}
QString RosterModel::getJID(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- return contact ? P2QSTRING(contact->getJID().toString()) : QString();
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ return contact ? P2QSTRING(contact->getJID().toString()) : QString();
}
QString RosterModel::getDisplayJID(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- QString result = contact ? P2QSTRING(contact->getDisplayJID().toString()) : QString();
- if (result.isEmpty()) {
- result = getJID(item);
- }
- return result;
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ QString result = contact ? P2QSTRING(contact->getDisplayJID().toString()) : QString();
+ if (result.isEmpty()) {
+ result = getJID(item);
+ }
+ return result;
}
QIcon RosterModel::getPresenceIcon(RosterItem* item) const {
- ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
- if (!contact) return QIcon();
- if (contact->blockState() == ContactRosterItem::IsBlocked ||
- contact->blockState() == ContactRosterItem::IsDomainBlocked) {
- return QIcon(":/icons/stop.png");
- }
-
- return QIcon(statusShowTypeToIconPath(contact->getStatusShow()));
+ ContactRosterItem* contact = dynamic_cast<ContactRosterItem*>(item);
+ if (!contact) return QIcon();
+ if (contact->blockState() == ContactRosterItem::IsBlocked ||
+ contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ return QIcon(":/icons/stop.png");
+ }
+
+ return QIcon(statusShowTypeToIconPath(contact->getStatusShow()));
}
QModelIndex RosterModel::index(int row, int column, const QModelIndex& parent) const {
- if (!roster_) {
- return QModelIndex();
- }
- GroupRosterItem* parentItem;
- if (!parent.isValid()) {
- //top level
- parentItem = roster_->getRoot();
- } else {
- parentItem = dynamic_cast<GroupRosterItem*>(getItem(parent));
- if (!parentItem) return QModelIndex();
- }
- return static_cast<size_t>(row) < parentItem->getDisplayedChildren().size() ? createIndex(row, column, parentItem->getDisplayedChildren()[row]) : QModelIndex();
+ if (!roster_) {
+ return QModelIndex();
+ }
+ GroupRosterItem* parentItem;
+ if (!parent.isValid()) {
+ //top level
+ parentItem = roster_->getRoot();
+ } else {
+ parentItem = dynamic_cast<GroupRosterItem*>(getItem(parent));
+ if (!parentItem) return QModelIndex();
+ }
+ return static_cast<size_t>(row) < parentItem->getDisplayedChildren().size() ? createIndex(row, column, parentItem->getDisplayedChildren()[row]) : QModelIndex();
}
QModelIndex RosterModel::index(RosterItem* item) const {
- GroupRosterItem* parent = item->getParent();
- /* Recursive check that it's ok to create such an item
- Assuming there are more contacts in a group than groups in a
- group, this could save a decent chunk of search time at startup.*/
- if (parent == NULL || roster_ == NULL || (parent != roster_->getRoot() && !index(parent).isValid())) {
- return QModelIndex();
- }
- for (size_t i = 0; i < parent->getDisplayedChildren().size(); i++) {
- if (parent->getDisplayedChildren()[i] == item) {
- return createIndex(i, 0, item);
- }
- }
- return QModelIndex();
+ GroupRosterItem* parent = item->getParent();
+ /* Recursive check that it's ok to create such an item
+ Assuming there are more contacts in a group than groups in a
+ group, this could save a decent chunk of search time at startup.*/
+ if (parent == NULL || roster_ == NULL || (parent != roster_->getRoot() && !index(parent).isValid())) {
+ return QModelIndex();
+ }
+ for (size_t i = 0; i < parent->getDisplayedChildren().size(); i++) {
+ if (parent->getDisplayedChildren()[i] == item) {
+ return createIndex(i, 0, item);
+ }
+ }
+ return QModelIndex();
}
QModelIndex RosterModel::parent(const QModelIndex& child) const {
- if (!roster_ || !child.isValid()) {
- return QModelIndex();
- }
-
- GroupRosterItem* parent = getItem(child)->getParent();
- return (parent != roster_->getRoot()) ? index(parent) : QModelIndex();
+ if (!roster_ || !child.isValid()) {
+ return QModelIndex();
+ }
+
+ GroupRosterItem* parent = getItem(child)->getParent();
+ return (parent != roster_->getRoot()) ? index(parent) : QModelIndex();
}
int RosterModel::rowCount(const QModelIndex& parent) const {
- if (!roster_) return 0;
- RosterItem* item = parent.isValid() ? static_cast<RosterItem*>(parent.internalPointer()) : roster_->getRoot();
- Q_ASSERT(item);
- GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
- int count = group ? group->getDisplayedChildren().size() : 0;
-// qDebug() << "rowCount = " << count << " where parent.isValid() == " << parent.isValid() << ", group == " << (group ? P2QSTRING(group->getDisplayName()) : "*contact*");
- return count;
+ if (!roster_) return 0;
+ RosterItem* item = parent.isValid() ? static_cast<RosterItem*>(parent.internalPointer()) : roster_->getRoot();
+ Q_ASSERT(item);
+ GroupRosterItem* group = dynamic_cast<GroupRosterItem*>(item);
+ int count = group ? group->getDisplayedChildren().size() : 0;
+// qDebug() << "rowCount = " << count << " where parent.isValid() == " << parent.isValid() << ", group == " << (group ? P2QSTRING(group->getDisplayName()) : "*contact*");
+ return count;
}
QMimeData* RosterModel::mimeData(const QModelIndexList& indexes) const {
- QMimeData* data = QAbstractItemModel::mimeData(indexes);
-
- ContactRosterItem *item = dynamic_cast<ContactRosterItem*>(getItem(indexes.first()));
- if (item == NULL) {
- return data;
- }
-
- /* only a single JID in this list */
- QByteArray itemData;
- QDataStream dataStream(&itemData, QIODevice::WriteOnly);
- dataStream << P2QSTRING(item->getJID().toString());
- data->setData("application/vnd.swift.contact-jid-list", itemData);
- return data;
+ QMimeData* data = QAbstractItemModel::mimeData(indexes);
+
+ ContactRosterItem *item = dynamic_cast<ContactRosterItem*>(getItem(indexes.first()));
+ if (item == NULL) {
+ return data;
+ }
+
+ /* only a single JID in this list */
+ QByteArray itemData;
+ QDataStream dataStream(&itemData, QIODevice::WriteOnly);
+ dataStream << P2QSTRING(item->getJID().toString());
+ data->setData("application/vnd.swift.contact-jid-list", itemData);
+ return data;
}
}
diff --git a/Swift/QtUI/Roster/RosterModel.h b/Swift/QtUI/Roster/RosterModel.h
index 47ed614..af0d43a 100644
--- a/Swift/QtUI/Roster/RosterModel.h
+++ b/Swift/QtUI/Roster/RosterModel.h
@@ -14,58 +14,58 @@
#include <Swift/QtUI/QtScaledAvatarCache.h>
namespace Swift {
- enum RosterRoles {
- StatusTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3,
- ChildCountRole = Qt::UserRole + 4,
- IdleRole = Qt::UserRole + 5,
- JIDRole = Qt::UserRole + 6,
- DisplayJIDRole = Qt::UserRole + 7
- };
+ enum RosterRoles {
+ StatusTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3,
+ ChildCountRole = Qt::UserRole + 4,
+ IdleRole = Qt::UserRole + 5,
+ JIDRole = Qt::UserRole + 6,
+ DisplayJIDRole = Qt::UserRole + 7
+ };
- class QtTreeWidget;
+ class QtTreeWidget;
- class RosterModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- RosterModel(QtTreeWidget* view, bool screenReaderMode);
- ~RosterModel();
- void setRoster(Roster* swiftRoster);
- Qt::ItemFlags flags(const QModelIndex& index) const;
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex index(RosterItem* item) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- QMimeData* mimeData(const QModelIndexList& indexes) const;
+ class RosterModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ RosterModel(QtTreeWidget* view, bool screenReaderMode);
+ ~RosterModel();
+ void setRoster(Roster* swiftRoster);
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex index(RosterItem* item) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ QMimeData* mimeData(const QModelIndexList& indexes) const;
- signals:
- void itemExpanded(const QModelIndex& item, bool expanded);
- private:
- void handleDataChanged(RosterItem* item);
- void handleChildrenChanged(GroupRosterItem* item);
- RosterItem* getItem(const QModelIndex& index) const;
- QColor intToColor(int color) const;
- QColor getTextColor(RosterItem* item) const;
- QColor getBackgroundColor(RosterItem* item) const;
- QString getToolTip(RosterItem* item) const;
- QString getAvatar(RosterItem* item) const;
- QString getStatusText(RosterItem* item) const;
- QString getJID(RosterItem* item) const;
- QString getDisplayJID(RosterItem* item) const;
- QIcon getPresenceIcon(RosterItem* item) const;
- int getChildCount(RosterItem* item) const;
- bool getIsIdle(RosterItem* item) const;
- void reLayout();
- /** calculates screenreader-friendly text if in screenreader mode, otherwise uses alternative text */
- QString getScreenReaderTextOr(RosterItem* item, const QString& alternative) const;
- private:
- Roster* roster_;
- QtTreeWidget* view_;
- QtScaledAvatarCache* cachedImageScaler_;
- bool screenReader_;
- };
+ signals:
+ void itemExpanded(const QModelIndex& item, bool expanded);
+ private:
+ void handleDataChanged(RosterItem* item);
+ void handleChildrenChanged(GroupRosterItem* item);
+ RosterItem* getItem(const QModelIndex& index) const;
+ QColor intToColor(int color) const;
+ QColor getTextColor(RosterItem* item) const;
+ QColor getBackgroundColor(RosterItem* item) const;
+ QString getToolTip(RosterItem* item) const;
+ QString getAvatar(RosterItem* item) const;
+ QString getStatusText(RosterItem* item) const;
+ QString getJID(RosterItem* item) const;
+ QString getDisplayJID(RosterItem* item) const;
+ QIcon getPresenceIcon(RosterItem* item) const;
+ int getChildCount(RosterItem* item) const;
+ bool getIsIdle(RosterItem* item) const;
+ void reLayout();
+ /** calculates screenreader-friendly text if in screenreader mode, otherwise uses alternative text */
+ QString getScreenReaderTextOr(RosterItem* item, const QString& alternative) const;
+ private:
+ Roster* roster_;
+ QtTreeWidget* view_;
+ QtScaledAvatarCache* cachedImageScaler_;
+ bool screenReader_;
+ };
}
diff --git a/Swift/QtUI/Roster/RosterTooltip.cpp b/Swift/QtUI/Roster/RosterTooltip.cpp
index e4a5626..d151628 100644
--- a/Swift/QtUI/Roster/RosterTooltip.cpp
+++ b/Swift/QtUI/Roster/RosterTooltip.cpp
@@ -31,142 +31,142 @@ using namespace QtUtilities;
namespace Swift {
QString RosterTooltip::buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler) {
- QString tooltipTemplate;
- if (QApplication::layoutDirection() == Qt::RightToLeft) {
- tooltipTemplate = QString(
- "<table style='white-space:pre'>"
- "<tr>"
- "<td>"
- "<img src=\"%1\" />"
- "</td>"
- "<td>"
- "<p style='font-size: 14px'>%3 %2</p>"
- "<table><tr><td valign='middle'>%5</td><td valign='middle'>%4</td></tr></table>"
- "%6"
- "%7"
- "%8"
- "%9"
- "</td>"
- "</tr>"
- "</table>");
- } else {
- tooltipTemplate = QString(
- "<table style='white-space:pre'>"
- "<tr>"
- "<td>"
- "<img src=\"%1\" />"
- "</td>"
- "<td>"
- "<p style='font-size: 14px'>%2 %3</p>"
- "<table><tr><td valign='middle'>%4</td><td valign='middle'>%5</td></tr></table>"
- "%6"
- "%7"
- "%8"
- "%9"
- "</td>"
- "</tr>"
- "</table>");
- }
- // prepare tooltip
- QString fullName = P2QSTRING(contact->getDisplayName());
-
- QString vCardSummary;
- VCard::ref vCard = contact->getVCard();
- if (vCard) {
- fullName = P2QSTRING(vCard->getFullName()).trimmed();
- if (fullName.isEmpty()) {
- fullName = (P2QSTRING(vCard->getGivenName()) + " " + P2QSTRING(vCard->getFamilyName())).trimmed();
- }
- if (fullName.isEmpty()) {
- fullName = P2QSTRING(contact->getDisplayName());
- }
- vCardSummary = buildVCardSummary(vCard);
- } else {
- contact->onVCardRequested();
- }
-
- QString scaledAvatarPath = cachedImageScaler->getScaledAvatarPath(P2QSTRING(contact->getAvatarPath().empty() ? ":/icons/avatar.png" : pathToString(contact->getAvatarPath())));
-
- QString bareJID = contact->getDisplayJID().toString().empty() ? "" : "( " + P2QSTRING(contact->getDisplayJID().toString()) + " )";
-
- QString presenceIconTag = QString("<img src='%1' />").arg(statusShowTypeToIconPath(contact->getStatusShow()));
-
- QString statusMessage = contact->getStatusText().empty() ? QObject::tr("(No message)") : P2QSTRING(contact->getStatusText());
-
- QString idleString = P2QSTRING(contact->getIdleText());
- if (!idleString.isEmpty()) {
- idleString = QObject::tr("Idle since %1").arg(idleString);
- idleString = htmlEscape(idleString) + "<br/>";
- }
-
- QString lastSeen = P2QSTRING(contact->getOfflineSinceText());
- if (!lastSeen.isEmpty()) {
- lastSeen = QObject::tr("Last seen %1").arg(lastSeen);
- 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 tooltipTemplate;
+ if (QApplication::layoutDirection() == Qt::RightToLeft) {
+ tooltipTemplate = QString(
+ "<table style='white-space:pre'>"
+ "<tr>"
+ "<td>"
+ "<img src=\"%1\" />"
+ "</td>"
+ "<td>"
+ "<p style='font-size: 14px'>%3 %2</p>"
+ "<table><tr><td valign='middle'>%5</td><td valign='middle'>%4</td></tr></table>"
+ "%6"
+ "%7"
+ "%8"
+ "%9"
+ "</td>"
+ "</tr>"
+ "</table>");
+ } else {
+ tooltipTemplate = QString(
+ "<table style='white-space:pre'>"
+ "<tr>"
+ "<td>"
+ "<img src=\"%1\" />"
+ "</td>"
+ "<td>"
+ "<p style='font-size: 14px'>%2 %3</p>"
+ "<table><tr><td valign='middle'>%4</td><td valign='middle'>%5</td></tr></table>"
+ "%6"
+ "%7"
+ "%8"
+ "%9"
+ "</td>"
+ "</tr>"
+ "</table>");
+ }
+ // prepare tooltip
+ QString fullName = P2QSTRING(contact->getDisplayName());
+
+ QString vCardSummary;
+ VCard::ref vCard = contact->getVCard();
+ if (vCard) {
+ fullName = P2QSTRING(vCard->getFullName()).trimmed();
+ if (fullName.isEmpty()) {
+ fullName = (P2QSTRING(vCard->getGivenName()) + " " + P2QSTRING(vCard->getFamilyName())).trimmed();
+ }
+ if (fullName.isEmpty()) {
+ fullName = P2QSTRING(contact->getDisplayName());
+ }
+ vCardSummary = buildVCardSummary(vCard);
+ } else {
+ contact->onVCardRequested();
+ }
+
+ QString scaledAvatarPath = cachedImageScaler->getScaledAvatarPath(P2QSTRING(contact->getAvatarPath().empty() ? ":/icons/avatar.png" : pathToString(contact->getAvatarPath())));
+
+ QString bareJID = contact->getDisplayJID().toString().empty() ? "" : "( " + P2QSTRING(contact->getDisplayJID().toString()) + " )";
+
+ QString presenceIconTag = QString("<img src='%1' />").arg(statusShowTypeToIconPath(contact->getStatusShow()));
+
+ QString statusMessage = contact->getStatusText().empty() ? QObject::tr("(No message)") : P2QSTRING(contact->getStatusText());
+
+ QString idleString = P2QSTRING(contact->getIdleText());
+ if (!idleString.isEmpty()) {
+ idleString = QObject::tr("Idle since %1").arg(idleString);
+ idleString = htmlEscape(idleString) + "<br/>";
+ }
+
+ QString lastSeen = P2QSTRING(contact->getOfflineSinceText());
+ if (!lastSeen.isEmpty()) {
+ lastSeen = QObject::tr("Last seen %1").arg(lastSeen);
+ 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()) {
- 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()) {
- 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()) {
- QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
- currentBlock += field;
- }
- summary += currentBlock;
-
- currentBlock = "";
- foreach(const std::string& title, vcard->getTitles()) {
- QString field = buildVCardField(false, QObject::tr("Title"), htmlEscape(P2QSTRING(title)));
- currentBlock += field;
- }
- summary += currentBlock;
-
- summary += "</table>";
- return summary;
+ QString summary;
+ summary = "<table>";
+
+ // star | name | content
+ QString currentBlock;
+ foreach (const VCard::Telephone& 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()) {
+ 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()) {
+ QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ foreach(const std::string& 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);
+ 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/Roster/RosterTooltip.h b/Swift/QtUI/Roster/RosterTooltip.h
index 37f5da2..642809f 100644
--- a/Swift/QtUI/Roster/RosterTooltip.h
+++ b/Swift/QtUI/Roster/RosterTooltip.h
@@ -16,12 +16,12 @@ class ContactRosterItem;
class QtScaledAvatarCache;
class RosterTooltip {
- public:
- static QString buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler);
+ public:
+ static QString buildDetailedTooltip(ContactRosterItem* contact, QtScaledAvatarCache* cachedImageScaler);
- private:
- static QString buildVCardSummary(VCard::ref vcard);
- static QString buildVCardField(bool preferred, const QString& name, const QString& content);
+ private:
+ static QString buildVCardSummary(VCard::ref vcard);
+ static QString buildVCardField(bool preferred, const QString& name, const QString& content);
};
}
diff --git a/Swift/QtUI/Roster/main.cpp b/Swift/QtUI/Roster/main.cpp
index 078fcaf..c0402e8 100644
--- a/Swift/QtUI/Roster/main.cpp
+++ b/Swift/QtUI/Roster/main.cpp
@@ -13,55 +13,55 @@
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
- //Swift::RosterModel model;
+ //Swift::RosterModel model;
- //QTreeView view;
- //view.setModel(&model);
- //view.setWindowTitle("A roster");
- //view.show();
+ //QTreeView view;
+ //view.setModel(&model);
+ //view.setWindowTitle("A roster");
+ //view.show();
- Swift::QtTreeWidgetFactory treeWidgetFactory;
- Swift::QtTreeWidget* tree = dynamic_cast<Swift::QtTreeWidget*>(treeWidgetFactory.createTreeWidget());
- tree->show();
- QList<Swift::QtTreeWidgetItem*> item3s;
- for (int i = 0; i < 500; i++) {
- Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
- group->setText("People");
- group->setBackgroundColor(0xBBBBBB);
- Swift::QtTreeWidgetItem* item1 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item2 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item3 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- Swift::QtTreeWidgetItem* item4 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- item1->setText("Remko");
- item2->setText("Kevin");
- item3->setText("Cath");
- item4->setText("KimTypo");
- item4->setText("Kim");
- item3s.push_back(item3);
- }
-
- Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
- group->setText("Many People");
-
- Swift::QtTreeWidgetItem* person350;
- Swift::QtTreeWidgetItem* person1200;
+ Swift::QtTreeWidgetFactory treeWidgetFactory;
+ Swift::QtTreeWidget* tree = dynamic_cast<Swift::QtTreeWidget*>(treeWidgetFactory.createTreeWidget());
+ tree->show();
+ QList<Swift::QtTreeWidgetItem*> item3s;
+ for (int i = 0; i < 500; i++) {
+ Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
+ group->setText("People");
+ group->setBackgroundColor(0xBBBBBB);
+ Swift::QtTreeWidgetItem* item1 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item2 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item3 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ Swift::QtTreeWidgetItem* item4 = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ item1->setText("Remko");
+ item2->setText("Kevin");
+ item3->setText("Cath");
+ item4->setText("KimTypo");
+ item4->setText("Kim");
+ item3s.push_back(item3);
+ }
- for (int i = 0; i < 1500; i++) {
- Swift::QtTreeWidgetItem* item = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
- item->setText(Q2PSTRING(QString("Some person %1").arg(i)));
- item->setStatusShow(Swift::StatusShow::Away);
- if (i == 350) person350 = item;
- if (i == 1200) person1200 = item;
- }
+ Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
+ group->setText("Many People");
- for (int i = 0; i < item3s.size(); i++) {
- item3s[i]->setStatusShow(Swift::StatusShow::XA);
- }
+ Swift::QtTreeWidgetItem* person350;
+ Swift::QtTreeWidgetItem* person1200;
- person350->setStatusShow(Swift::StatusShow::DND);
- person1200->setStatusShow(Swift::StatusShow::Online);
+ for (int i = 0; i < 1500; i++) {
+ Swift::QtTreeWidgetItem* item = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(group));
+ item->setText(Q2PSTRING(QString("Some person %1").arg(i)));
+ item->setStatusShow(Swift::StatusShow::Away);
+ if (i == 350) person350 = item;
+ if (i == 1200) person1200 = item;
+ }
- return app.exec();
+ for (int i = 0; i < item3s.size(); i++) {
+ item3s[i]->setStatusShow(Swift::StatusShow::XA);
+ }
+
+ person350->setStatusShow(Swift::StatusShow::DND);
+ person1200->setStatusShow(Swift::StatusShow::Online);
+
+ return app.exec();
}
diff --git a/Swift/QtUI/SystemMessageSnippet.cpp b/Swift/QtUI/SystemMessageSnippet.cpp
index 87c17b1..fbf8810 100644
--- a/Swift/QtUI/SystemMessageSnippet.cpp
+++ b/Swift/QtUI/SystemMessageSnippet.cpp
@@ -11,16 +11,16 @@
namespace Swift {
SystemMessageSnippet::SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction) : ChatSnippet(appendToPrevious) {
- if (appendToPrevious) {
- setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new SystemMessageSnippet(message, time, false, theme, id, direction)));
- }
- content_ = theme->getStatus();
-
- content_.replace("%direction%", directionToCSS(direction));
- content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
- content_.replace("%shortTime%", wrapResizable(escape(time.toString("h:mm"))));
- content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
- content_.replace("%id%", id);
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(boost::shared_ptr<ChatSnippet>(new SystemMessageSnippet(message, time, false, theme, id, direction)));
+ }
+ content_ = theme->getStatus();
+
+ content_.replace("%direction%", directionToCSS(direction));
+ content_.replace("%message%", wrapResizable("<span class='swift_message'>" + escape(message) + "</span>"));
+ content_.replace("%shortTime%", wrapResizable(escape(time.toString("h:mm"))));
+ content_.replace("%time%", wrapResizable("<span class='swift_time'>" + timeToEscapedString(time) + "</span>"));
+ content_.replace("%id%", id);
}
SystemMessageSnippet::~SystemMessageSnippet() {
diff --git a/Swift/QtUI/SystemMessageSnippet.h b/Swift/QtUI/SystemMessageSnippet.h
index a1f2682..c0d4d2f 100644
--- a/Swift/QtUI/SystemMessageSnippet.h
+++ b/Swift/QtUI/SystemMessageSnippet.h
@@ -13,18 +13,18 @@
class QDateTime;
namespace Swift {
- class SystemMessageSnippet : public ChatSnippet {
- public:
- SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
- virtual ~SystemMessageSnippet();
+ class SystemMessageSnippet : public ChatSnippet {
+ public:
+ SystemMessageSnippet(const QString& message, const QDateTime& time, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction);
+ virtual ~SystemMessageSnippet();
- const QString& getContent() const {return content_;}
+ const QString& getContent() const {return content_;}
- /*QString getContinuationElementID() const {
- return "insert";
- };*/
+ /*QString getContinuationElementID() const {
+ return "insert";
+ };*/
- private:
- QString content_;
- };
+ private:
+ QString content_;
+ };
}
diff --git a/Swift/QtUI/Trellis/QtDNDTabBar.cpp b/Swift/QtUI/Trellis/QtDNDTabBar.cpp
index dbe397b..fac2233 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.cpp
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.cpp
@@ -18,12 +18,12 @@
namespace Swift {
QtDNDTabBar::QtDNDTabBar(QWidget* parent) : QTabBar(parent) {
- setAcceptDrops(true);
+ setAcceptDrops(true);
- // detect the default tab bar height;
- insertTab(0, "");
- defaultTabHeight = QTabBar::sizeHint().height();
- removeTab(0);
+ // detect the default tab bar height;
+ insertTab(0, "");
+ defaultTabHeight = QTabBar::sizeHint().height();
+ removeTab(0);
}
QtDNDTabBar::~QtDNDTabBar() {
@@ -31,136 +31,136 @@ QtDNDTabBar::~QtDNDTabBar() {
}
int QtDNDTabBar::getDragIndex() const {
- return dragIndex;
+ return dragIndex;
}
QString QtDNDTabBar::getDragText() const {
- return dragText;
+ return dragText;
}
QWidget* QtDNDTabBar::getDragWidget() const {
- return dragWidget;
+ return dragWidget;
}
QSize QtDNDTabBar::sizeHint() const {
- QSize hint = QTabBar::sizeHint();
- if (hint.isEmpty()) {
- hint = QSize(parentWidget()->width(), defaultTabHeight);
- }
- return hint;
+ QSize hint = QTabBar::sizeHint();
+ if (hint.isEmpty()) {
+ hint = QSize(parentWidget()->width(), defaultTabHeight);
+ }
+ return hint;
}
QSize QtDNDTabBar::tabSizeHint(int index) const {
- QSize tabSize = QTabBar::tabSizeHint(index);
+ QSize tabSize = QTabBar::tabSizeHint(index);
#if defined(Q_OS_MAC)
- // With multiple tabs having the same label in a QTabBar, the size hint computed by
- // Qt on OS X is too small and it is elided even though there is enough horizontal
- // space available. We work around this issue by adding the width of a letter to the
- // size hint.
- tabSize += QSize(QFontMetrics(font()).width("I"), 0);
+ // With multiple tabs having the same label in a QTabBar, the size hint computed by
+ // Qt on OS X is too small and it is elided even though there is enough horizontal
+ // space available. We work around this issue by adding the width of a letter to the
+ // size hint.
+ tabSize += QSize(QFontMetrics(font()).width("I"), 0);
#endif
- return tabSize;
+ return tabSize;
}
void QtDNDTabBar::dragEnterEvent(QDragEnterEvent* dragEnterEvent) {
- QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dragEnterEvent->source());
- if (sourceTabBar) {
- dragEnterEvent->acceptProposedAction();
- }
+ QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dragEnterEvent->source());
+ if (sourceTabBar) {
+ dragEnterEvent->acceptProposedAction();
+ }
}
void QtDNDTabBar::dropEvent(QDropEvent* dropEvent) {
- QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
- if (sourceTabBar && dropEvent->mimeData() && dropEvent->mimeData()->data("action") == QByteArray("application/tab-detach")) {
- QtDNDTabBar* source = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
-
- int targetTabIndex = tabAt(dropEvent->pos());
- QRect rect = tabRect(targetTabIndex);
- if (targetTabIndex >= 0 && (dropEvent->pos().x() - rect.left() - rect.width()/2 > 0)) {
- targetTabIndex++;
- }
-
- QWidget* tab = source->getDragWidget();
- assert(tab);
- QTabWidget* targetTabWidget = dynamic_cast<QTabWidget*>(parentWidget());
-
- QString tabText = source->getDragText();
-
- /*
- * When you add a widget to an empty QTabWidget, it's automatically made the current widget.
- * Making the widget the current widget, widget->show() is called for the widget. Directly reacting
- * to that event, and adding the widget again to the QTabWidget results in undefined behavior. For
- * example the tab label is shown but the widget is neither has the old nor in the new QTabWidget as
- * parent. Blocking signals on the QWidget to be added to a QTabWidget prevents this behavior.
- */
- targetTabWidget->setUpdatesEnabled(false);
- tab->blockSignals(true);
- targetTabWidget->insertTab(targetTabIndex, tab, tabText);
- dropEvent->acceptProposedAction();
- tab->blockSignals(false);
- targetTabWidget->setUpdatesEnabled(true);
- onDropSucceeded();
- }
+ QtDNDTabBar* sourceTabBar = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
+ if (sourceTabBar && dropEvent->mimeData() && dropEvent->mimeData()->data("action") == QByteArray("application/tab-detach")) {
+ QtDNDTabBar* source = dynamic_cast<QtDNDTabBar*>(dropEvent->source());
+
+ int targetTabIndex = tabAt(dropEvent->pos());
+ QRect rect = tabRect(targetTabIndex);
+ if (targetTabIndex >= 0 && (dropEvent->pos().x() - rect.left() - rect.width()/2 > 0)) {
+ targetTabIndex++;
+ }
+
+ QWidget* tab = source->getDragWidget();
+ assert(tab);
+ QTabWidget* targetTabWidget = dynamic_cast<QTabWidget*>(parentWidget());
+
+ QString tabText = source->getDragText();
+
+ /*
+ * When you add a widget to an empty QTabWidget, it's automatically made the current widget.
+ * Making the widget the current widget, widget->show() is called for the widget. Directly reacting
+ * to that event, and adding the widget again to the QTabWidget results in undefined behavior. For
+ * example the tab label is shown but the widget is neither has the old nor in the new QTabWidget as
+ * parent. Blocking signals on the QWidget to be added to a QTabWidget prevents this behavior.
+ */
+ targetTabWidget->setUpdatesEnabled(false);
+ tab->blockSignals(true);
+ targetTabWidget->insertTab(targetTabIndex, tab, tabText);
+ dropEvent->acceptProposedAction();
+ tab->blockSignals(false);
+ targetTabWidget->setUpdatesEnabled(true);
+ onDropSucceeded();
+ }
}
bool QtDNDTabBar::event(QEvent* event) {
- QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(event);
- if (mouseEvent) {
- QWidget* childAtPoint = window()->childAt(mapTo(window(), mouseEvent->pos()));
- QtDNDTabBar* underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint);
- if (!underMouse && childAtPoint) {
- underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint->parent());
- }
- if (!underMouse && currentIndex() >= 0) {
- // detach and drag
-
- // stop move event
- QMouseEvent* finishMoveEvent = new QMouseEvent (QEvent::MouseMove, mouseEvent->pos (), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
- QTabBar::event(finishMoveEvent);
- delete finishMoveEvent;
- finishMoveEvent = NULL;
-
- // start drag
- QDrag* drag = new QDrag(this);
- QMimeData* mimeData = new QMimeData;
-
- // distinguish tab-reordering drops from other ones
- mimeData->setData("action", "application/tab-detach") ;
- drag->setMimeData(mimeData);
-
- // set drag image
- QRect rect = tabRect( currentIndex() );
+ QMouseEvent* mouseEvent = dynamic_cast<QMouseEvent*>(event);
+ if (mouseEvent) {
+ QWidget* childAtPoint = window()->childAt(mapTo(window(), mouseEvent->pos()));
+ QtDNDTabBar* underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint);
+ if (!underMouse && childAtPoint) {
+ underMouse = dynamic_cast<QtDNDTabBar*>(childAtPoint->parent());
+ }
+ if (!underMouse && currentIndex() >= 0) {
+ // detach and drag
+
+ // stop move event
+ QMouseEvent* finishMoveEvent = new QMouseEvent (QEvent::MouseMove, mouseEvent->pos (), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
+ QTabBar::event(finishMoveEvent);
+ delete finishMoveEvent;
+ finishMoveEvent = NULL;
+
+ // start drag
+ QDrag* drag = new QDrag(this);
+ QMimeData* mimeData = new QMimeData;
+
+ // distinguish tab-reordering drops from other ones
+ mimeData->setData("action", "application/tab-detach") ;
+ drag->setMimeData(mimeData);
+
+ // set drag image
+ QRect rect = tabRect( currentIndex() );
#if QT_VERSION >= 0x050000
- QPixmap pixmap = grab(rect);
+ QPixmap pixmap = grab(rect);
#else
- QPixmap pixmap = QPixmap::grabWidget(this, rect);
+ QPixmap pixmap = QPixmap::grabWidget(this, rect);
#endif
- QPixmap targetPixmap (pixmap.size ());
- QPainter painter (&targetPixmap);
- painter.setOpacity(0.9);
- painter.drawPixmap(0,0, pixmap);
- painter.end ();
- drag->setPixmap (targetPixmap);
-
- drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()));
-
- dragIndex = currentIndex();
- dragText = tabText(dragIndex);
- dragWidget = dynamic_cast<QTabWidget*>(parent())->widget(dragIndex);
- assert(dragWidget);
- dynamic_cast<QTabWidget*>(parent())->removeTab(currentIndex());
- Qt::DropAction dropAction = drag->exec();
- if (dropAction == Qt::IgnoreAction) {
- // aborted drag, put tab back in place
- // disable event handling during the insert for the tab to prevent infinite recursion (stack overflow)
- dragWidget->blockSignals(true);
- dynamic_cast<QTabWidget*>(parent())->insertTab(dragIndex, dragWidget, dragText);
- dragWidget->blockSignals(false);
- }
- return true;
- }
- }
- return QTabBar::event(event);
+ QPixmap targetPixmap (pixmap.size ());
+ QPainter painter (&targetPixmap);
+ painter.setOpacity(0.9);
+ painter.drawPixmap(0,0, pixmap);
+ painter.end ();
+ drag->setPixmap (targetPixmap);
+
+ drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()));
+
+ dragIndex = currentIndex();
+ dragText = tabText(dragIndex);
+ dragWidget = dynamic_cast<QTabWidget*>(parent())->widget(dragIndex);
+ assert(dragWidget);
+ dynamic_cast<QTabWidget*>(parent())->removeTab(currentIndex());
+ Qt::DropAction dropAction = drag->exec();
+ if (dropAction == Qt::IgnoreAction) {
+ // aborted drag, put tab back in place
+ // disable event handling during the insert for the tab to prevent infinite recursion (stack overflow)
+ dragWidget->blockSignals(true);
+ dynamic_cast<QTabWidget*>(parent())->insertTab(dragIndex, dragWidget, dragText);
+ dragWidget->blockSignals(false);
+ }
+ return true;
+ }
+ }
+ return QTabBar::event(event);
}
}
diff --git a/Swift/QtUI/Trellis/QtDNDTabBar.h b/Swift/QtUI/Trellis/QtDNDTabBar.h
index 71ca94b..3677b73 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.h
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.h
@@ -11,31 +11,31 @@
namespace Swift {
class QtDNDTabBar : public QTabBar {
- Q_OBJECT
- public:
- explicit QtDNDTabBar(QWidget* parent = 0);
- virtual ~QtDNDTabBar();
-
- int getDragIndex() const;
- QString getDragText() const;
- QWidget* getDragWidget() const;
-
- virtual QSize sizeHint() const;
-
- signals:
- void onDropSucceeded();
-
- protected:
- virtual void dragEnterEvent(QDragEnterEvent* dragEnterEvent);
- virtual void dropEvent(QDropEvent* dropEvent);
- virtual bool event(QEvent* event);
- virtual QSize tabSizeHint(int index) const;
-
- private:
- int defaultTabHeight;
- int dragIndex;
- QString dragText;
- QWidget* dragWidget;
+ Q_OBJECT
+ public:
+ explicit QtDNDTabBar(QWidget* parent = 0);
+ virtual ~QtDNDTabBar();
+
+ int getDragIndex() const;
+ QString getDragText() const;
+ QWidget* getDragWidget() const;
+
+ virtual QSize sizeHint() const;
+
+ signals:
+ void onDropSucceeded();
+
+ protected:
+ virtual void dragEnterEvent(QDragEnterEvent* dragEnterEvent);
+ virtual void dropEvent(QDropEvent* dropEvent);
+ virtual bool event(QEvent* event);
+ virtual QSize tabSizeHint(int index) const;
+
+ private:
+ int defaultTabHeight;
+ int dragIndex;
+ QString dragText;
+ QWidget* dragWidget;
};
}
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
index 3b8adf8..7de2791 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
@@ -24,127 +24,127 @@
namespace Swift {
QtDynamicGridLayout::QtDynamicGridLayout(QWidget* parent, bool enableDND) : QWidget(parent), dndEnabled_(enableDND), movingTab_(NULL) {
- gridLayout_ = new QGridLayout(this);
- setContentsMargins(0,0,0,0);
- setDimensions(QSize(1,1));
- connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*,QWidget*)));
+ gridLayout_ = new QGridLayout(this);
+ setContentsMargins(0,0,0,0);
+ setDimensions(QSize(1,1));
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*,QWidget*)));
}
QtDynamicGridLayout::~QtDynamicGridLayout() {
}
int QtDynamicGridLayout::addTab(QtTabbable* tab, const QString& title) {
- assert(gridLayout_->rowCount() > 0 && gridLayout_->columnCount() > 0);
+ assert(gridLayout_->rowCount() > 0 && gridLayout_->columnCount() > 0);
- QPoint lastPos(0,0);
- if (tabPositions_.contains(P2QSTRING(tab->getID()))) {
- lastPos = tabPositions_[P2QSTRING(tab->getID())];
- }
+ QPoint lastPos(0,0);
+ if (tabPositions_.contains(P2QSTRING(tab->getID()))) {
+ lastPos = tabPositions_[P2QSTRING(tab->getID())];
+ }
- lastPos = QPoint(qMin(lastPos.x(), gridLayout_->columnCount() - 1), qMin(lastPos.y(), gridLayout_->rowCount() - 1));
+ lastPos = QPoint(qMin(lastPos.x(), gridLayout_->columnCount() - 1), qMin(lastPos.y(), gridLayout_->rowCount() - 1));
- QLayoutItem* item = gridLayout_->itemAtPosition(lastPos.y(), lastPos.x());
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(item ? item->widget() : 0);
- if (tabWidget) {
- tabWidget->addTab(tab, title);
- }
- return tabWidget ? indexOf(tab) : -1;
+ QLayoutItem* item = gridLayout_->itemAtPosition(lastPos.y(), lastPos.x());
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(item ? item->widget() : 0);
+ if (tabWidget) {
+ tabWidget->addTab(tab, title);
+ }
+ return tabWidget ? indexOf(tab) : -1;
}
int QtDynamicGridLayout::count() const {
- int count = 0;
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- count += tabWidget->count();
- }
- }
- }
- return count;
+ int count = 0;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ count += tabWidget->count();
+ }
+ }
+ }
+ return count;
}
QWidget* QtDynamicGridLayout::widget(int index) const {
- QWidget* widgetAtIndex = NULL;
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- if (index < tabWidget->count()) {
- widgetAtIndex = tabWidget->widget(index);
- return widgetAtIndex;
- }
- else {
- index -= tabWidget->count();
- }
- }
- }
- }
- return widgetAtIndex;
+ QWidget* widgetAtIndex = NULL;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ if (index < tabWidget->count()) {
+ widgetAtIndex = tabWidget->widget(index);
+ return widgetAtIndex;
+ }
+ else {
+ index -= tabWidget->count();
+ }
+ }
+ }
+ }
+ return widgetAtIndex;
}
int QtDynamicGridLayout::indexOf(const QWidget* widget) const {
- int index = 0;
- if (widget) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- for (int n = 0; n < tabWidget->count(); n++) {
- QWidget* nthWidget = tabWidget->widget(n);
- if (nthWidget == widget) {
- return index;
- }
- index++;
- }
- }
- }
- }
- }
- return -1;
+ int index = 0;
+ if (widget) {
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ for (int n = 0; n < tabWidget->count(); n++) {
+ QWidget* nthWidget = tabWidget->widget(n);
+ if (nthWidget == widget) {
+ return index;
+ }
+ index++;
+ }
+ }
+ }
+ }
+ }
+ return -1;
}
void QtDynamicGridLayout::handleApplicationFocusChanged(QWidget*, QWidget* newFocus) {
- if (movingTab_) {
- return;
- }
-
- if (newFocus) {
- if (isAncestorOf(newFocus)) {
- QtTabbable *newTab = dynamic_cast<QtTabbable*>(newFocus->parentWidget());
- if (newTab) {
- onCurrentIndexChanged(currentIndex());
- }
- }
- }
+ if (movingTab_) {
+ return;
+ }
+
+ if (newFocus) {
+ if (isAncestorOf(newFocus)) {
+ QtTabbable *newTab = dynamic_cast<QtTabbable*>(newFocus->parentWidget());
+ if (newTab) {
+ onCurrentIndexChanged(currentIndex());
+ }
+ }
+ }
}
int QtDynamicGridLayout::currentIndex() const {
- return indexOf(currentWidget());
+ return indexOf(currentWidget());
}
void QtDynamicGridLayout::setCurrentIndex(int index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- if (tabIndex >= 0) {
- tabWidget->setCurrentIndex(tabIndex);
- if (!tabWidget->hasFocus()) {
- tabWidget->widget(tabIndex)->setFocus(Qt::TabFocusReason);
- }
- } else {
- assert(false);
- }
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ if (tabIndex >= 0) {
+ tabWidget->setCurrentIndex(tabIndex);
+ if (!tabWidget->hasFocus()) {
+ tabWidget->widget(tabIndex)->setFocus(Qt::TabFocusReason);
+ }
+ } else {
+ assert(false);
+ }
}
void QtDynamicGridLayout::removeTab(int index) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- if (tabWidget) {
- tabWidget->removeTab(tabIndex);
- }
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ if (tabWidget) {
+ tabWidget->removeTab(tabIndex);
+ }
}
/**
@@ -158,348 +158,348 @@ void QtDynamicGridLayout::removeTab(int index) {
* being out of sync in an inconsistent state.
*/
bool QtDynamicGridLayout::eventFilter(QObject* object, QEvent* event) {
- QtTabbable* tab = qobject_cast<QtTabbable*>(object);
- if (!tab) {
- return false;
- }
- if (tab && (tab != movingTab_)) {
- if (event->type() == QEvent::Show) {
- return true;
- }
- }
- return false;
+ QtTabbable* tab = qobject_cast<QtTabbable*>(object);
+ if (!tab) {
+ return false;
+ }
+ if (tab && (tab != movingTab_)) {
+ if (event->type() == QEvent::Show) {
+ return true;
+ }
+ }
+ return false;
}
QWidget* QtDynamicGridLayout::currentWidget() const {
- QWidget* current = NULL;
- current = focusWidget();
- while (current && !dynamic_cast<QtTabbable*>(current)) {
- if (current->parentWidget()) {
- current = current->parentWidget();
- } else {
- current = NULL;
- break;
- }
- }
- if (!current) {
- current = widget(0);
- }
- return current;
+ QWidget* current = NULL;
+ current = focusWidget();
+ while (current && !dynamic_cast<QtTabbable*>(current)) {
+ if (current->parentWidget()) {
+ current = current->parentWidget();
+ } else {
+ current = NULL;
+ break;
+ }
+ }
+ if (!current) {
+ current = widget(0);
+ }
+ return current;
}
void QtDynamicGridLayout::setCurrentWidget(QWidget* widget) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- for (int n = 0; n < tabWidget->count(); n++) {
- if (tabWidget->widget(n) == widget) {
- tabWidget->setCurrentWidget(widget);
- }
- }
- }
- }
- }
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ for (int n = 0; n < tabWidget->count(); n++) {
+ if (tabWidget->widget(n) == widget) {
+ tabWidget->setCurrentWidget(widget);
+ }
+ }
+ }
+ }
+ }
}
QtTabWidget* QtDynamicGridLayout::indexToTabWidget(int index, int& tabIndex) {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget) {
- if (index < tabWidget->count()) {
- tabIndex = index;
- return tabWidget;
- }
- else {
- index -= tabWidget->count();
- if (index < 0) {
- qWarning() << "Called QtDynamicGridLayout::setCurrentIndex with index out of bounds: index = " << index;
- tabIndex = -1;
- return NULL;
- }
- }
- }
- }
- }
- tabIndex = -1;
- return NULL;
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget) {
+ if (index < tabWidget->count()) {
+ tabIndex = index;
+ return tabWidget;
+ }
+ else {
+ index -= tabWidget->count();
+ if (index < 0) {
+ qWarning() << "Called QtDynamicGridLayout::setCurrentIndex with index out of bounds: index = " << index;
+ tabIndex = -1;
+ return NULL;
+ }
+ }
+ }
+ }
+ }
+ tabIndex = -1;
+ return NULL;
}
bool QtDynamicGridLayout::isDNDEnabled() const {
- return dndEnabled_;
+ return dndEnabled_;
}
QHash<QString, QPoint> QtDynamicGridLayout::getTabPositions() const {
- return tabPositions_;
+ return tabPositions_;
}
void QtDynamicGridLayout::setTabPositions(const QHash<QString, QPoint> positions) {
- tabPositions_ = positions;
+ tabPositions_ = positions;
}
QSize QtDynamicGridLayout::getDimension() const {
- return QSize(gridLayout_->columnCount(), gridLayout_->rowCount());
+ return QSize(gridLayout_->columnCount(), gridLayout_->rowCount());
}
void QtDynamicGridLayout::setDimensions(const QSize& dim) {
- assert(dim.width() > 0 && dim.height() > 0);
- setUpdatesEnabled(false);
-
- QGridLayout* oldLayout = dynamic_cast<QGridLayout*>(layout());
- QGridLayout* newLayout = new QGridLayout;
- newLayout->setSpacing(4);
- newLayout->setContentsMargins(0,0,0,0);
-
- int oldWidth = oldLayout->columnCount();
- int oldHeight = oldLayout->rowCount();
- int maxCol = qMax(oldWidth, dim.width());
- int minCol = qMin(oldWidth, dim.width());
- int maxRow = qMax(oldHeight, dim.height());
- int minRow = qMin(oldHeight, dim.height());
-
- for (int row = 0; row < maxRow; row++) {
- for (int col = 0; col < maxCol; col++) {
- QLayoutItem* oldItem = oldLayout->itemAtPosition(row, col);
- QLayoutItem* newItem = newLayout->itemAtPosition(row, col);
- bool removeRow = !(row < dim.height());
- bool removeCol = !(col < dim.width());
-
- if (removeCol || removeRow) {
- if (oldItem) {
- int squeezeRow = removeRow ? (minRow - 1) : row;
- int squeezeCol = removeCol ? (minCol - 1) : col;
- newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
- if (!newItem) {
- newLayout->addWidget(createDNDTabWidget(this), squeezeRow, squeezeCol);
- newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
- }
- QtTabWidget* oldTabWidget = dynamic_cast<QtTabWidget*>(oldItem->widget());
- QtTabWidget* newTabWidget = dynamic_cast<QtTabWidget*>(newItem->widget());
- assert(oldTabWidget && newTabWidget);
-
- oldTabWidget->hide();
- while(oldTabWidget->count()) {
- QIcon icon = oldTabWidget->tabIcon(0);
- QString text = oldTabWidget->tabText(0);
- newTabWidget->addTab(oldTabWidget->widget(0), icon, text);
- }
- delete oldTabWidget;
- }
- } else {
- if (oldItem) {
- newLayout->addWidget(oldItem->widget(), row, col);
- newItem = newLayout->itemAtPosition(row, col);
- } else {
- newLayout->addWidget(createDNDTabWidget(this), row, col);
- }
- }
- }
- }
-
- for (int col = 0; col < dim.width(); col++) {
- newLayout->setColumnStretch(col, 1);
- }
- for (int row = 0; row < dim.height(); row++) {
- newLayout->setRowStretch(row, 1);
- }
-
- setUpdatesEnabled(true);
- delete layout();
- setLayout(newLayout);
- gridLayout_ = newLayout;
+ assert(dim.width() > 0 && dim.height() > 0);
+ setUpdatesEnabled(false);
+
+ QGridLayout* oldLayout = dynamic_cast<QGridLayout*>(layout());
+ QGridLayout* newLayout = new QGridLayout;
+ newLayout->setSpacing(4);
+ newLayout->setContentsMargins(0,0,0,0);
+
+ int oldWidth = oldLayout->columnCount();
+ int oldHeight = oldLayout->rowCount();
+ int maxCol = qMax(oldWidth, dim.width());
+ int minCol = qMin(oldWidth, dim.width());
+ int maxRow = qMax(oldHeight, dim.height());
+ int minRow = qMin(oldHeight, dim.height());
+
+ for (int row = 0; row < maxRow; row++) {
+ for (int col = 0; col < maxCol; col++) {
+ QLayoutItem* oldItem = oldLayout->itemAtPosition(row, col);
+ QLayoutItem* newItem = newLayout->itemAtPosition(row, col);
+ bool removeRow = !(row < dim.height());
+ bool removeCol = !(col < dim.width());
+
+ if (removeCol || removeRow) {
+ if (oldItem) {
+ int squeezeRow = removeRow ? (minRow - 1) : row;
+ int squeezeCol = removeCol ? (minCol - 1) : col;
+ newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
+ if (!newItem) {
+ newLayout->addWidget(createDNDTabWidget(this), squeezeRow, squeezeCol);
+ newItem = newLayout->itemAtPosition(squeezeRow, squeezeCol);
+ }
+ QtTabWidget* oldTabWidget = dynamic_cast<QtTabWidget*>(oldItem->widget());
+ QtTabWidget* newTabWidget = dynamic_cast<QtTabWidget*>(newItem->widget());
+ assert(oldTabWidget && newTabWidget);
+
+ oldTabWidget->hide();
+ while(oldTabWidget->count()) {
+ QIcon icon = oldTabWidget->tabIcon(0);
+ QString text = oldTabWidget->tabText(0);
+ newTabWidget->addTab(oldTabWidget->widget(0), icon, text);
+ }
+ delete oldTabWidget;
+ }
+ } else {
+ if (oldItem) {
+ newLayout->addWidget(oldItem->widget(), row, col);
+ newItem = newLayout->itemAtPosition(row, col);
+ } else {
+ newLayout->addWidget(createDNDTabWidget(this), row, col);
+ }
+ }
+ }
+ }
+
+ for (int col = 0; col < dim.width(); col++) {
+ newLayout->setColumnStretch(col, 1);
+ }
+ for (int row = 0; row < dim.height(); row++) {
+ newLayout->setRowStretch(row, 1);
+ }
+
+ setUpdatesEnabled(true);
+ delete layout();
+ setLayout(newLayout);
+ gridLayout_ = newLayout;
}
void QtDynamicGridLayout::moveCurrentTabRight() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- assert(tabWidget);
- int newTabIndex = (tabIndex + 1) % tabWidget->count();
- moveTab(tabWidget, tabIndex, newTabIndex);
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ assert(tabWidget);
+ int newTabIndex = (tabIndex + 1) % tabWidget->count();
+ moveTab(tabWidget, tabIndex, newTabIndex);
+ }
}
void QtDynamicGridLayout::moveCurrentTabLeft() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
- assert(tabWidget);
- int newTabIndex = (tabWidget->count() + tabIndex - 1) % tabWidget->count();
- moveTab(tabWidget, tabIndex, newTabIndex);
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+ assert(tabWidget);
+ int newTabIndex = (tabWidget->count() + tabIndex - 1) % tabWidget->count();
+ moveTab(tabWidget, tabIndex, newTabIndex);
+ }
}
void QtDynamicGridLayout::moveCurrentTabToNextGroup() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
-
- int row = -1;
- int col = -1;
- int tmp;
- gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
-
- // calculate next cell
- col++;
- if (!(col < gridLayout_->columnCount())) {
- col = 0;
- row++;
- if (!(row < gridLayout_->rowCount())) {
- row = 0;
- }
- }
-
- QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
- assert(tabWidget);
- assert(targetTabWidget);
-
- // fetch tab information
- QWidget* tab = tabWidget->widget(tabIndex);
- QString tabText = tabWidget->tabText(tabIndex);
-
- // move tab
- tab->blockSignals(true);
- targetTabWidget->addTab(tab, tabText);
- tab->blockSignals(false);
- tab->setFocus(Qt::TabFocusReason);
-
- updateTabPositions();
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+
+ int row = -1;
+ int col = -1;
+ int tmp;
+ gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
+
+ // calculate next cell
+ col++;
+ if (!(col < gridLayout_->columnCount())) {
+ col = 0;
+ row++;
+ if (!(row < gridLayout_->rowCount())) {
+ row = 0;
+ }
+ }
+
+ QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
+ assert(tabWidget);
+ assert(targetTabWidget);
+
+ // fetch tab information
+ QWidget* tab = tabWidget->widget(tabIndex);
+ QString tabText = tabWidget->tabText(tabIndex);
+
+ // move tab
+ tab->blockSignals(true);
+ targetTabWidget->addTab(tab, tabText);
+ tab->blockSignals(false);
+ tab->setFocus(Qt::TabFocusReason);
+
+ updateTabPositions();
+ }
}
void QtDynamicGridLayout::moveCurrentTabToPreviousGroup() {
- int index = currentIndex();
- if (index >= 0) {
- int tabIndex = -1;
- QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
-
- int row = -1;
- int col = -1;
- int tmp;
- gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
-
- // calculate next cell
- col--;
- if (col < 0) {
- col = gridLayout_->columnCount() - 1;
- row--;
- if (row < 0) {
- row = gridLayout_->rowCount() - 1;
- }
- }
-
- QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
- assert(tabWidget);
- assert(targetTabWidget);
-
- // fetch tab information
- QWidget* tab = tabWidget->widget(tabIndex);
- QString tabText = tabWidget->tabText(tabIndex);
-
- // move tab
- tab->blockSignals(true);
- targetTabWidget->addTab(tab, tabText);
- tab->blockSignals(false);
- tab->setFocus(Qt::TabFocusReason);
-
- updateTabPositions();
- }
+ int index = currentIndex();
+ if (index >= 0) {
+ int tabIndex = -1;
+ QtTabWidget* tabWidget = indexToTabWidget(index, tabIndex);
+
+ int row = -1;
+ int col = -1;
+ int tmp;
+ gridLayout_->getItemPosition(gridLayout_->indexOf(tabWidget), &row, &col, &tmp, &tmp);
+
+ // calculate next cell
+ col--;
+ if (col < 0) {
+ col = gridLayout_->columnCount() - 1;
+ row--;
+ if (row < 0) {
+ row = gridLayout_->rowCount() - 1;
+ }
+ }
+
+ QtTabWidget* targetTabWidget = dynamic_cast<QtTabWidget*>(gridLayout_->itemAtPosition(row, col)->widget());
+ assert(tabWidget);
+ assert(targetTabWidget);
+
+ // fetch tab information
+ QWidget* tab = tabWidget->widget(tabIndex);
+ QString tabText = tabWidget->tabText(tabIndex);
+
+ // move tab
+ tab->blockSignals(true);
+ targetTabWidget->addTab(tab, tabText);
+ tab->blockSignals(false);
+ tab->setFocus(Qt::TabFocusReason);
+
+ updateTabPositions();
+ }
}
void QtDynamicGridLayout::handleTabCloseRequested(int index) {
- updateTabPositions();
- QtTabWidget* tabWidgetSender = dynamic_cast<QtTabWidget*>(sender());
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- if (tabWidget == tabWidgetSender) {
- tabCloseRequested(index);
- }
- else {
- index += tabWidget->count();
- }
- }
- }
+ updateTabPositions();
+ QtTabWidget* tabWidgetSender = dynamic_cast<QtTabWidget*>(sender());
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ if (tabWidget == tabWidgetSender) {
+ tabCloseRequested(index);
+ }
+ else {
+ index += tabWidget->count();
+ }
+ }
+ }
}
void QtDynamicGridLayout::handleTabCurrentChanged(int index) {
- if (movingTab_) {
- return;
- }
-
- if (index >= 0) {
- QTabWidget* sendingTabWidget = dynamic_cast<QTabWidget*>(sender());
- assert(sendingTabWidget);
- sendingTabWidget->widget(index)->setFocus();
- }
+ if (movingTab_) {
+ return;
+ }
+
+ if (index >= 0) {
+ QTabWidget* sendingTabWidget = dynamic_cast<QTabWidget*>(sender());
+ assert(sendingTabWidget);
+ sendingTabWidget->widget(index)->setFocus();
+ }
}
void QtDynamicGridLayout::updateTabPositions() {
- for (int y = 0; y < gridLayout_->rowCount(); y++) {
- for (int x = 0; x < gridLayout_->columnCount(); x++) {
- QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
- QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
- assert(tabWidget);
- for (int index = 0; index < tabWidget->count(); index++) {
- QtTabbable* tab = dynamic_cast<QtTabbable*>(tabWidget->widget(index));
- assert(tab);
- tabPositions_.insert(P2QSTRING(tab->getID()), QPoint(x, y));
- }
- }
- }
+ for (int y = 0; y < gridLayout_->rowCount(); y++) {
+ for (int x = 0; x < gridLayout_->columnCount(); x++) {
+ QLayoutItem* layoutItem = gridLayout_->itemAtPosition(y, x);
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(layoutItem->widget());
+ assert(tabWidget);
+ for (int index = 0; index < tabWidget->count(); index++) {
+ QtTabbable* tab = dynamic_cast<QtTabbable*>(tabWidget->widget(index));
+ assert(tab);
+ tabPositions_.insert(P2QSTRING(tab->getID()), QPoint(x, y));
+ }
+ }
+ }
}
void QtDynamicGridLayout::moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex) {
#if QT_VERSION >= 0x040500
- SWIFT_LOG_ASSERT(movingTab_ == NULL, error) << std::endl;
- movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
- SWIFT_LOG_ASSERT(movingTab_ != NULL, error) << std::endl;
-
- if (movingTab_) {
- // Install event filter that filters out events issued during the internal movement of the
- // tab but not targeted at the moving tab.
- qApp->installEventFilter(this);
-
- tabWidget->tabBar()->moveTab(oldIndex, newIndex);
-
- qApp->removeEventFilter(this);
- SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error) << std::endl;
- }
- movingTab_ = NULL;
- tabWidget->widget(newIndex)->setFocus();
+ SWIFT_LOG_ASSERT(movingTab_ == NULL, error) << std::endl;
+ movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
+ SWIFT_LOG_ASSERT(movingTab_ != NULL, error) << std::endl;
+
+ if (movingTab_) {
+ // Install event filter that filters out events issued during the internal movement of the
+ // tab but not targeted at the moving tab.
+ qApp->installEventFilter(this);
+
+ tabWidget->tabBar()->moveTab(oldIndex, newIndex);
+
+ qApp->removeEventFilter(this);
+ SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error) << std::endl;
+ }
+ movingTab_ = NULL;
+ tabWidget->widget(newIndex)->setFocus();
#else
#warning Qt 4.5 or later is needed. Trying anyway, some things will be disabled.
#endif
}
QtTabWidget* QtDynamicGridLayout::createDNDTabWidget(QWidget* parent) {
- QtTabWidget* tab = new QtTabWidget(parent);
- if (dndEnabled_) {
- QtDNDTabBar* tabBar = new QtDNDTabBar(tab);
- connect(tabBar, SIGNAL(onDropSucceeded()), this, SLOT(updateTabPositions()));
- tab->setTabBar(tabBar);
- }
- tab->setUsesScrollButtons(true);
- tab->setElideMode(Qt::ElideRight);
+ QtTabWidget* tab = new QtTabWidget(parent);
+ if (dndEnabled_) {
+ QtDNDTabBar* tabBar = new QtDNDTabBar(tab);
+ connect(tabBar, SIGNAL(onDropSucceeded()), this, SLOT(updateTabPositions()));
+ tab->setTabBar(tabBar);
+ }
+ tab->setUsesScrollButtons(true);
+ tab->setElideMode(Qt::ElideRight);
#if QT_VERSION >= 0x040500
- /*For Macs, change the tab rendering.*/
- tab->setDocumentMode(true);
- /*Closable tabs are only in Qt4.5 and later*/
- tab->setTabsClosable(true);
- tab->setMovable(true);
- connect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
- connect(tab, SIGNAL(currentChanged(int)), this, SLOT(handleTabCurrentChanged(int)));
+ /*For Macs, change the tab rendering.*/
+ tab->setDocumentMode(true);
+ /*Closable tabs are only in Qt4.5 and later*/
+ tab->setTabsClosable(true);
+ tab->setMovable(true);
+ connect(tab, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int)));
+ connect(tab, SIGNAL(currentChanged(int)), this, SLOT(handleTabCurrentChanged(int)));
#else
#warning Qt 4.5 or later is needed. Trying anyway, some things will be disabled.
#endif
- return tab;
+ return tab;
}
}
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.h b/Swift/QtUI/Trellis/QtDynamicGridLayout.h
index ed8a9fc..2a6029c 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.h
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.h
@@ -14,67 +14,67 @@
#include <QWidget>
namespace Swift {
- class QtTabbable;
- class QtTabWidget;
+ class QtTabbable;
+ class QtTabWidget;
- class QtDynamicGridLayout : public QWidget {
- Q_OBJECT
- public:
- explicit QtDynamicGridLayout(QWidget* parent = 0, bool enableDND = false);
- virtual ~QtDynamicGridLayout();
+ class QtDynamicGridLayout : public QWidget {
+ Q_OBJECT
+ public:
+ explicit QtDynamicGridLayout(QWidget* parent = 0, bool enableDND = false);
+ virtual ~QtDynamicGridLayout();
- QSize getDimension() const;
+ QSize getDimension() const;
- // emulate QtTabWidget API
- int addTab(QtTabbable* tab, const QString& title);
- void removeTab(int index);
- int count() const;
+ // emulate QtTabWidget API
+ int addTab(QtTabbable* tab, const QString& title);
+ void removeTab(int index);
+ int count() const;
- QWidget* widget(int index) const;
- QWidget* currentWidget() const;
- void setCurrentWidget(QWidget* widget);
+ QWidget* widget(int index) const;
+ QWidget* currentWidget() const;
+ void setCurrentWidget(QWidget* widget);
- QtTabWidget* indexToTabWidget(int index, int& tabIndex);
+ QtTabWidget* indexToTabWidget(int index, int& tabIndex);
- int indexOf(const QWidget* widget) const;
- int currentIndex() const;
- void setCurrentIndex(int index);
+ int indexOf(const QWidget* widget) const;
+ int currentIndex() const;
+ void setCurrentIndex(int index);
- bool isDNDEnabled() const;
+ bool isDNDEnabled() const;
- QHash<QString, QPoint> getTabPositions() const;
- void setTabPositions(const QHash<QString, QPoint> positions);
+ QHash<QString, QPoint> getTabPositions() const;
+ void setTabPositions(const QHash<QString, QPoint> positions);
- bool eventFilter(QObject* object, QEvent* event);
+ bool eventFilter(QObject* object, QEvent* event);
- signals:
- void tabCloseRequested(int index);
- void onCurrentIndexChanged(int newIndex);
+ signals:
+ void tabCloseRequested(int index);
+ void onCurrentIndexChanged(int newIndex);
- public slots:
- void setDimensions(const QSize& dim);
+ public slots:
+ void setDimensions(const QSize& dim);
- // Tab Management
- void moveCurrentTabRight();
- void moveCurrentTabLeft();
- void moveCurrentTabToNextGroup();
- void moveCurrentTabToPreviousGroup();
+ // Tab Management
+ void moveCurrentTabRight();
+ void moveCurrentTabLeft();
+ void moveCurrentTabToNextGroup();
+ void moveCurrentTabToPreviousGroup();
- void updateTabPositions();
+ void updateTabPositions();
- private slots:
- void handleTabCloseRequested(int index);
- void handleTabCurrentChanged(int index);
- void handleApplicationFocusChanged(QWidget* oldFocus, QWidget* newFocus);
+ private slots:
+ void handleTabCloseRequested(int index);
+ void handleTabCurrentChanged(int index);
+ void handleApplicationFocusChanged(QWidget* oldFocus, QWidget* newFocus);
- private:
- void moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex);
- QtTabWidget* createDNDTabWidget(QWidget* parent);
+ private:
+ void moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex);
+ QtTabWidget* createDNDTabWidget(QWidget* parent);
- private:
- QGridLayout *gridLayout_;
- bool dndEnabled_;
- QHash<QString, QPoint> tabPositions_;
- QtTabbable* movingTab_;
- };
+ private:
+ QGridLayout *gridLayout_;
+ bool dndEnabled_;
+ QHash<QString, QPoint> tabPositions_;
+ QtTabbable* movingTab_;
+ };
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
index a3a1bf8..c7b7edb 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
@@ -16,142 +16,142 @@
namespace Swift {
QtGridSelectionDialog::QtGridSelectionDialog(QWidget* parent) : QWidget(parent) {
- frameSize = QSize(23,23) * 2;
- maxGridSize = QSize(7,7);
- minGridSize = QSize(1,1);
- currentGridSize = QSize(1,1);
- padding = 4;
- setWindowFlags(Qt::FramelessWindowHint);
- setCursor(Qt::SizeAllCursor);
- horizontalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
- verticalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
+ frameSize = QSize(23,23) * 2;
+ maxGridSize = QSize(7,7);
+ minGridSize = QSize(1,1);
+ currentGridSize = QSize(1,1);
+ padding = 4;
+ setWindowFlags(Qt::FramelessWindowHint);
+ setCursor(Qt::SizeAllCursor);
+ horizontalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
+ verticalMargin = style()->pixelMetric(QStyle::PM_MenuVMargin) * 2;
}
QSize QtGridSelectionDialog::sizeHint() const {
- // PM_MenuVMargin | frameSize | ( padding | frameSize ) * | PM_MenuVMargin
- int width = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) + horizontalMargin;
- int height = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) + verticalMargin;
- return QSize(width, height);
+ // PM_MenuVMargin | frameSize | ( padding | frameSize ) * | PM_MenuVMargin
+ int width = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) + horizontalMargin;
+ int height = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) + verticalMargin;
+ return QSize(width, height);
}
void QtGridSelectionDialog::setCurrentGridSize(const QSize& size) {
- currentGridSize = size;
- emit currentGridSizeChanged(size);
+ currentGridSize = size;
+ emit currentGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getCurrentGridSize() const {
- return currentGridSize;
+ return currentGridSize;
}
void QtGridSelectionDialog::setMinGridSize(const QSize& size) {
- minGridSize = size;
- emit minGridSizeChanged(size);
+ minGridSize = size;
+ emit minGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getMinGridSize() const {
- return minGridSize;
+ return minGridSize;
}
void QtGridSelectionDialog::setMaxGridSize(const QSize& size) {
- maxGridSize = size;
- emit maxGridSizeChanged(size);
+ maxGridSize = size;
+ emit maxGridSizeChanged(size);
}
QSize QtGridSelectionDialog::getMaxGridSize() const {
- return maxGridSize;
+ return maxGridSize;
}
void QtGridSelectionDialog::keyReleaseEvent(QKeyEvent* event) {
- if (event) {
- QSize newGridSize = currentGridSize;
- if (event->key() == Qt::Key_Up) {
- newGridSize += QSize(0, -1);
- }
- else if (event->key() == Qt::Key_Down) {
- newGridSize += QSize(0, 1);
- }
- else if (event->key() == Qt::Key_Left) {
- newGridSize += QSize(-1, 0);
- }
- else if (event->key() == Qt::Key_Right) {
- newGridSize += QSize(1, 0);
- }
- else if (event->key() == Qt::Key_Return) {
- hide();
- setCurrentGridSize(currentGridSize);
- }
- if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
- resize(sizeHint());
- }
- }
+ if (event) {
+ QSize newGridSize = currentGridSize;
+ if (event->key() == Qt::Key_Up) {
+ newGridSize += QSize(0, -1);
+ }
+ else if (event->key() == Qt::Key_Down) {
+ newGridSize += QSize(0, 1);
+ }
+ else if (event->key() == Qt::Key_Left) {
+ newGridSize += QSize(-1, 0);
+ }
+ else if (event->key() == Qt::Key_Right) {
+ newGridSize += QSize(1, 0);
+ }
+ else if (event->key() == Qt::Key_Return) {
+ hide();
+ setCurrentGridSize(currentGridSize);
+ }
+ if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
+ }
}
void QtGridSelectionDialog::mousePressEvent(QMouseEvent*) {
- hide();
- setCurrentGridSize(currentGridSize);
+ hide();
+ setCurrentGridSize(currentGridSize);
}
void QtGridSelectionDialog::paintEvent(QPaintEvent*) {
- QPainter painter(this);
- QStyleOptionMenuItem option;
- option.state = QStyle::State_Enabled | QStyle::State_Selected;
- option.menuRect = QRect(QPoint(0,0), frameSize);
- for (int x = 0; x < currentGridSize.width(); x++) {
- for (int y = 0; y < currentGridSize.height(); y++) {
- int xPos = horizontalMargin + (x * (frameSize.width() + padding));
- int yPos = verticalMargin + (y * (frameSize.height() + padding));
- option.menuRect.moveTo(QPoint(xPos, yPos));
- option.rect = option.menuRect;
- style()->drawControl(QStyle::CE_MenuItem, &option, &painter, 0);
- }
- }
-
- QStyleOptionSizeGrip sizeGripOption;
- sizeGripOption.init(this);
- sizeGripOption.corner = Qt::BottomRightCorner;
- style()->drawControl(QStyle::CE_SizeGrip, &sizeGripOption, &painter, this);
+ QPainter painter(this);
+ QStyleOptionMenuItem option;
+ option.state = QStyle::State_Enabled | QStyle::State_Selected;
+ option.menuRect = QRect(QPoint(0,0), frameSize);
+ for (int x = 0; x < currentGridSize.width(); x++) {
+ for (int y = 0; y < currentGridSize.height(); y++) {
+ int xPos = horizontalMargin + (x * (frameSize.width() + padding));
+ int yPos = verticalMargin + (y * (frameSize.height() + padding));
+ option.menuRect.moveTo(QPoint(xPos, yPos));
+ option.rect = option.menuRect;
+ style()->drawControl(QStyle::CE_MenuItem, &option, &painter, 0);
+ }
+ }
+
+ QStyleOptionSizeGrip sizeGripOption;
+ sizeGripOption.init(this);
+ sizeGripOption.corner = Qt::BottomRightCorner;
+ style()->drawControl(QStyle::CE_SizeGrip, &sizeGripOption, &painter, this);
}
void QtGridSelectionDialog::showEvent(QShowEvent*) {
- int xPos = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) - frameSize.width()/2;
- int yPos = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) - frameSize.height()/2;
- QCursor::setPos(mapToGlobal(QPoint(xPos, yPos)));
- setMouseTracking(true);
+ int xPos = horizontalMargin + frameSize.width() + (padding + frameSize.width()) * (currentGridSize.width() - 1) - frameSize.width()/2;
+ int yPos = verticalMargin + frameSize.height() + (padding + frameSize.height()) * (currentGridSize.height() - 1) - frameSize.height()/2;
+ QCursor::setPos(mapToGlobal(QPoint(xPos, yPos)));
+ setMouseTracking(true);
}
void QtGridSelectionDialog::hideEvent(QHideEvent*) {
- setMouseTracking(false);
+ setMouseTracking(false);
}
void QtGridSelectionDialog::mouseMoveEvent(QMouseEvent*) {
- QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
- QSize newDimensions = currentGridSize;
- if (diff.x() > frameSize.width() * 1.5) {
- newDimensions -= QSize(diff.x() / (frameSize.width() * 1.5), 0);
- }
- if (diff.y() > frameSize.height() * 1.5) {
- newDimensions -= QSize(0, diff.y() / (frameSize.height() * 1.5));
- }
- if (minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize);
- resize(sizeHint());
- }
+ QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
+ QSize newDimensions = currentGridSize;
+ if (diff.x() > frameSize.width() * 1.5) {
+ newDimensions -= QSize(diff.x() / (frameSize.width() * 1.5), 0);
+ }
+ if (diff.y() > frameSize.height() * 1.5) {
+ newDimensions -= QSize(0, diff.y() / (frameSize.height() * 1.5));
+ }
+ if (minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newDimensions).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
}
void QtGridSelectionDialog::leaveEvent(QEvent *) {
- QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
- QSize newGridSize = currentGridSize;
- if (diff.x() < 0) {
- newGridSize += QSize(1,0);
- }
- if (diff.y() < 0) {
- newGridSize += QSize(0,1);
- }
- if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
- currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
- resize(sizeHint());
- }
+ QPoint diff = (frameGeometry().bottomRight() - QCursor::pos());
+ QSize newGridSize = currentGridSize;
+ if (diff.x() < 0) {
+ newGridSize += QSize(1,0);
+ }
+ if (diff.y() < 0) {
+ newGridSize += QSize(0,1);
+ }
+ if (minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize) != currentGridSize) {
+ currentGridSize = minGridSize.expandedTo(newGridSize).boundedTo(maxGridSize);
+ resize(sizeHint());
+ }
}
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.h b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
index abcc8b1..c763e68 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.h
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
@@ -11,47 +11,47 @@
namespace Swift {
- class QtGridSelectionDialog : public QWidget {
- Q_OBJECT
-
- Q_PROPERTY(QSize currentGridSize READ getCurrentGridSize WRITE setCurrentGridSize NOTIFY currentGridSizeChanged)
- Q_PROPERTY(QSize minGridSize READ getMinGridSize WRITE setMinGridSize NOTIFY minGridSizeChanged)
- Q_PROPERTY(QSize maxGridSize READ getMaxGridSize WRITE setMaxGridSize NOTIFY maxGridSizeChanged)
- public:
- explicit QtGridSelectionDialog(QWidget* parent = 0);
-
- virtual QSize sizeHint() const;
-
- void setCurrentGridSize(const QSize& size);
- QSize getCurrentGridSize() const;
- void setMinGridSize(const QSize& size);
- QSize getMinGridSize() const;
- void setMaxGridSize(const QSize& size);
- QSize getMaxGridSize() const;
-
- signals:
- void currentGridSizeChanged(QSize);
- void minGridSizeChanged(QSize);
- void maxGridSizeChanged(QSize);
-
- protected:
- void keyReleaseEvent(QKeyEvent* event);
- void mousePressEvent(QMouseEvent* event);
- void mouseMoveEvent(QMouseEvent* event);
- void paintEvent(QPaintEvent* event);
- void showEvent(QShowEvent* event);
- void hideEvent(QHideEvent* event);
- void leaveEvent(QEvent *event);
-
- private:
- int padding;
- int horizontalMargin;
- int verticalMargin;
-
- QSize frameSize;
-
- QSize currentGridSize;
- QSize minGridSize;
- QSize maxGridSize;
- };
+ class QtGridSelectionDialog : public QWidget {
+ Q_OBJECT
+
+ Q_PROPERTY(QSize currentGridSize READ getCurrentGridSize WRITE setCurrentGridSize NOTIFY currentGridSizeChanged)
+ Q_PROPERTY(QSize minGridSize READ getMinGridSize WRITE setMinGridSize NOTIFY minGridSizeChanged)
+ Q_PROPERTY(QSize maxGridSize READ getMaxGridSize WRITE setMaxGridSize NOTIFY maxGridSizeChanged)
+ public:
+ explicit QtGridSelectionDialog(QWidget* parent = 0);
+
+ virtual QSize sizeHint() const;
+
+ void setCurrentGridSize(const QSize& size);
+ QSize getCurrentGridSize() const;
+ void setMinGridSize(const QSize& size);
+ QSize getMinGridSize() const;
+ void setMaxGridSize(const QSize& size);
+ QSize getMaxGridSize() const;
+
+ signals:
+ void currentGridSizeChanged(QSize);
+ void minGridSizeChanged(QSize);
+ void maxGridSizeChanged(QSize);
+
+ protected:
+ void keyReleaseEvent(QKeyEvent* event);
+ void mousePressEvent(QMouseEvent* event);
+ void mouseMoveEvent(QMouseEvent* event);
+ void paintEvent(QPaintEvent* event);
+ void showEvent(QShowEvent* event);
+ void hideEvent(QHideEvent* event);
+ void leaveEvent(QEvent *event);
+
+ private:
+ int padding;
+ int horizontalMargin;
+ int verticalMargin;
+
+ QSize frameSize;
+
+ QSize currentGridSize;
+ QSize minGridSize;
+ QSize maxGridSize;
+ };
}
diff --git a/Swift/QtUI/UserSearch/ContactListDelegate.cpp b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
index 989743e..75e25a1 100644
--- a/Swift/QtUI/UserSearch/ContactListDelegate.cpp
+++ b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
@@ -26,29 +26,29 @@ ContactListDelegate::~ContactListDelegate() {
}
void ContactListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- if (!index.isValid()) {
- return;
- }
- const Contact::ref contact = static_cast<Contact*>(index.internalPointer())->shared_from_this();
- QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
- QString avatarPath = index.data(ContactListModel::AvatarRole).value<QString>();
- QIcon presenceIcon =index.data(ChatListRecentItem::PresenceIconRole).isValid() && !index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
- ? index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
- : QIcon(":/icons/offline.png");
- QString name = P2QSTRING(contact->name);
- QString statusText = P2QSTRING(contact->jid.toString());
- common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, 0, compact_);
+ if (!index.isValid()) {
+ return;
+ }
+ const Contact::ref contact = static_cast<Contact*>(index.internalPointer())->shared_from_this();
+ QColor nameColor = index.data(Qt::TextColorRole).value<QColor>();
+ QString avatarPath = index.data(ContactListModel::AvatarRole).value<QString>();
+ QIcon presenceIcon =index.data(ChatListRecentItem::PresenceIconRole).isValid() && !index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>().isNull()
+ ? index.data(ChatListRecentItem::PresenceIconRole).value<QIcon>()
+ : QIcon(":/icons/offline.png");
+ QString name = P2QSTRING(contact->name);
+ QString statusText = P2QSTRING(contact->jid.toString());
+ common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, 0, compact_);
}
QSize ContactListDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
void ContactListDelegate::setCompact(bool compact) {
- compact_ = compact;
+ compact_ = compact;
}
}
diff --git a/Swift/QtUI/UserSearch/ContactListDelegate.h b/Swift/QtUI/UserSearch/ContactListDelegate.h
index 7680aba..208246a 100644
--- a/Swift/QtUI/UserSearch/ContactListDelegate.h
+++ b/Swift/QtUI/UserSearch/ContactListDelegate.h
@@ -13,18 +13,18 @@
namespace Swift {
class ContactListDelegate : public QStyledItemDelegate {
- public:
- ContactListDelegate(bool compact);
- virtual ~ContactListDelegate();
+ public:
+ ContactListDelegate(bool compact);
+ virtual ~ContactListDelegate();
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- public slots:
- void setCompact(bool compact);
+ public slots:
+ void setCompact(bool compact);
- private:
- bool compact_;
- DelegateCommons common_;
+ private:
+ bool compact_;
+ DelegateCommons common_;
};
}
diff --git a/Swift/QtUI/UserSearch/ContactListModel.cpp b/Swift/QtUI/UserSearch/ContactListModel.cpp
index 3400924..376d3b1 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.cpp
+++ b/Swift/QtUI/UserSearch/ContactListModel.cpp
@@ -24,116 +24,116 @@
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;
- }
- return in;
+ 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;
+ }
+ return in;
}
ContactListModel::ContactListModel(bool editable) : QAbstractItemModel(), editable_(editable) {
}
void ContactListModel::setList(const std::vector<Contact::ref>& list) {
- emit layoutAboutToBeChanged();
- contacts_ = list;
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ contacts_ = list;
+ emit layoutChanged();
}
const std::vector<Contact::ref>& ContactListModel::getList() const {
- return contacts_;
+ return contacts_;
}
Contact::ref ContactListModel::getContact(const size_t i) const {
- return contacts_[i];
+ return contacts_[i];
}
Qt::ItemFlags ContactListModel::flags(const QModelIndex& index) const {
- Qt::ItemFlags flags = QAbstractItemModel::flags(index);
- if (index.isValid()) {
- flags = flags & ~Qt::ItemIsDropEnabled;
- } else {
- flags = Qt::ItemIsDropEnabled | flags;
- }
- return flags;
+ Qt::ItemFlags flags = QAbstractItemModel::flags(index);
+ if (index.isValid()) {
+ flags = flags & ~Qt::ItemIsDropEnabled;
+ } else {
+ flags = Qt::ItemIsDropEnabled | flags;
+ }
+ return flags;
}
int ContactListModel::columnCount(const QModelIndex&) const {
- return editable_ ? 2 : 1;
+ return editable_ ? 2 : 1;
}
QVariant ContactListModel::data(const QModelIndex& index, int role) const {
- if ((boost::numeric_cast<size_t>(index.row()) < contacts_.size()) && (index.column() == 0)) {
- const Contact::ref& contact = contacts_[index.row()];
- if (role == Qt::EditRole) {
- return P2QSTRING(contact->jid.toString());
- }
- return dataForContact(contact, role);
- } else {
- return QVariant();
- }
+ if ((boost::numeric_cast<size_t>(index.row()) < contacts_.size()) && (index.column() == 0)) {
+ const Contact::ref& contact = contacts_[index.row()];
+ if (role == Qt::EditRole) {
+ return P2QSTRING(contact->jid.toString());
+ }
+ return dataForContact(contact, role);
+ } else {
+ return QVariant();
+ }
}
QModelIndex ContactListModel::index(int row, int column, const QModelIndex& parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
- return boost::numeric_cast<size_t>(row) < contacts_.size() ? createIndex(row, column, contacts_[row].get()) : QModelIndex();
+ return boost::numeric_cast<size_t>(row) < contacts_.size() ? createIndex(row, column, contacts_[row].get()) : QModelIndex();
}
QModelIndex ContactListModel::parent(const QModelIndex& index) const {
- if (!index.isValid()) {
- return QModelIndex();
- }
- return QModelIndex();
+ if (!index.isValid()) {
+ return QModelIndex();
+ }
+ return QModelIndex();
}
int ContactListModel::rowCount(const QModelIndex& /*parent*/) const {
- return contacts_.size();
+ return contacts_.size();
}
bool ContactListModel::removeRows(int row, int /*count*/, const QModelIndex& /*parent*/) {
- if (boost::numeric_cast<size_t>(row) < contacts_.size()) {
- emit layoutAboutToBeChanged();
- contacts_.erase(contacts_.begin() + row);
- emit layoutChanged();
- onListChanged(getList());
- return true;
- }
- return false;
+ if (boost::numeric_cast<size_t>(row) < contacts_.size()) {
+ emit layoutAboutToBeChanged();
+ contacts_.erase(contacts_.begin() + row);
+ emit layoutChanged();
+ onListChanged(getList());
+ return true;
+ }
+ return false;
}
QVariant ContactListModel::dataForContact(const Contact::ref& contact, int role) const {
- switch (role) {
- case Qt::DisplayRole: return P2QSTRING(contact->name);
- case DetailTextRole: return P2QSTRING(contact->jid.toString());
- case AvatarRole: return QVariant(P2QSTRING(pathToString(contact->avatarPath)));
- case PresenceIconRole: return getPresenceIconForContact(contact);
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return P2QSTRING(contact->name);
+ case DetailTextRole: return P2QSTRING(contact->jid.toString());
+ case AvatarRole: return QVariant(P2QSTRING(pathToString(contact->avatarPath)));
+ case PresenceIconRole: return getPresenceIconForContact(contact);
+ default: return QVariant();
+ }
}
QIcon ContactListModel::getPresenceIconForContact(const Contact::ref& contact) const {
- return QIcon(statusShowTypeToIconPath(contact->statusType));
+ return QIcon(statusShowTypeToIconPath(contact->statusType));
}
}
diff --git a/Swift/QtUI/UserSearch/ContactListModel.h b/Swift/QtUI/UserSearch/ContactListModel.h
index e980120..9b61484 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.h
+++ b/Swift/QtUI/UserSearch/ContactListModel.h
@@ -27,41 +27,41 @@
#include <Swift/QtUI/ChatList/ChatListRecentItem.h>
namespace Swift {
- class ContactListModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- enum ContactRoles {
- DetailTextRole = Qt::UserRole,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2
- };
-
- public:
- ContactListModel(bool editable);
-
- void setList(const std::vector<Contact::ref>& list);
- const std::vector<Contact::ref>& getList() const;
- Contact::ref getContact(const size_t i) const;
-
- Qt::ItemFlags flags(const QModelIndex& index) const;
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
-
- private:
- QVariant dataForContact(const Contact::ref& contact, int role) const;
- QIcon getPresenceIconForContact(const Contact::ref& contact) const;
-
- signals:
- void onListChanged(std::vector<Contact::ref> list);
- void onJIDsDropped(const std::vector<JID>& contact);
-
- private:
- bool editable_;
- std::vector<Contact::ref> contacts_;
- };
+ class ContactListModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ enum ContactRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2
+ };
+
+ public:
+ ContactListModel(bool editable);
+
+ void setList(const std::vector<Contact::ref>& list);
+ const std::vector<Contact::ref>& getList() const;
+ Contact::ref getContact(const size_t i) const;
+
+ Qt::ItemFlags flags(const QModelIndex& index) const;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
+
+ private:
+ QVariant dataForContact(const Contact::ref& contact, int role) const;
+ QIcon getPresenceIconForContact(const Contact::ref& contact) const;
+
+ signals:
+ void onListChanged(std::vector<Contact::ref> list);
+ void onJIDsDropped(const std::vector<JID>& contact);
+
+ private:
+ bool editable_;
+ std::vector<Contact::ref> contacts_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.cpp b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
index 0d55880..99bd791 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.cpp
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
@@ -24,80 +24,80 @@
namespace Swift {
QtContactListWidget::QtContactListWidget(QWidget* parent, SettingsProvider* settings) : QTreeView(parent), settings_(settings), limited_(false) {
- contactListModel_ = new ContactListModel(true);
- setModel(contactListModel_);
+ contactListModel_ = new ContactListModel(true);
+ setModel(contactListModel_);
- connect(contactListModel_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SIGNAL(onListChanged(std::vector<Contact::ref>)));
- connect(contactListModel_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SIGNAL(onJIDsAdded(std::vector<JID>)));
+ connect(contactListModel_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SIGNAL(onListChanged(std::vector<Contact::ref>)));
+ connect(contactListModel_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SIGNAL(onJIDsAdded(std::vector<JID>)));
- setSelectionMode(QAbstractItemView::SingleSelection);
- setSelectionBehavior(QAbstractItemView::SelectRows);
- setUniformRowHeights(true);
+ setSelectionMode(QAbstractItemView::SingleSelection);
+ setSelectionBehavior(QAbstractItemView::SelectRows);
+ setUniformRowHeights(true);
- setAlternatingRowColors(true);
- setIndentation(0);
- setHeaderHidden(true);
- setExpandsOnDoubleClick(false);
- setItemsExpandable(false);
- setEditTriggers(QAbstractItemView::DoubleClicked);
+ setAlternatingRowColors(true);
+ setIndentation(0);
+ setHeaderHidden(true);
+ setExpandsOnDoubleClick(false);
+ setItemsExpandable(false);
+ setEditTriggers(QAbstractItemView::DoubleClicked);
- contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- removableItemDelegate_ = new QtRemovableItemDelegate(style());
+ contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ removableItemDelegate_ = new QtRemovableItemDelegate(style());
- setItemDelegateForColumn(0, contactListDelegate_);
- setItemDelegateForColumn(1, removableItemDelegate_);
+ setItemDelegateForColumn(0, contactListDelegate_);
+ setItemDelegateForColumn(1, removableItemDelegate_);
- header()->resizeSection(1, removableItemDelegate_->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
+ header()->resizeSection(1, removableItemDelegate_->sizeHint(QStyleOptionViewItem(), QModelIndex()).width());
- header()->setStretchLastSection(false);
+ header()->setStretchLastSection(false);
#if QT_VERSION >= 0x050000
- header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
- header()->setResizeMode(0, QHeaderView::Stretch);
+ header()->setResizeMode(0, QHeaderView::Stretch);
#endif
}
QtContactListWidget::~QtContactListWidget() {
- delete contactListDelegate_;
- delete removableItemDelegate_;
- delete contactListModel_;
+ delete contactListDelegate_;
+ delete removableItemDelegate_;
+ delete contactListModel_;
}
void QtContactListWidget::setList(const std::vector<Contact::ref>& list) {
- contactListModel_->setList(list);
+ contactListModel_->setList(list);
}
std::vector<Contact::ref> QtContactListWidget::getList() const {
- return contactListModel_->getList();
+ return contactListModel_->getList();
}
Contact::ref QtContactListWidget::getContact(const size_t i) {
- return contactListModel_->getContact(i);
+ return contactListModel_->getContact(i);
}
void QtContactListWidget::setMaximumNoOfContactsToOne(bool limited) {
- limited_ = limited;
+ limited_ = limited;
}
bool QtContactListWidget::isFull() const {
- return limited_ && (getList().size() == 1);
+ 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(size_t n = 0; n < contacts.size(); n++) {
- if (contactUpdate->jid == contacts[n]->jid) {
- contacts[n] = contactUpdate;
- break;
- }
- }
- }
- contactListModel_->setList(contacts);
+ std::vector<Contact::ref> contacts = contactListModel_->getList();
+ foreach(const Contact::ref& contactUpdate, contactUpdates) {
+ for(size_t n = 0; n < contacts.size(); n++) {
+ if (contactUpdate->jid == contacts[n]->jid) {
+ contacts[n] = contactUpdate;
+ break;
+ }
+ }
+ }
+ contactListModel_->setList(contacts);
}
void QtContactListWidget::handleSettingsChanged(const std::string&) {
- contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.h b/Swift/QtUI/UserSearch/QtContactListWidget.h
index 59bd8f3..f2483c3 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.h
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.h
@@ -31,33 +31,33 @@ class SettingsProvider;
class QtRemovableItemDelegate;
class QtContactListWidget : public QTreeView {
- Q_OBJECT
+ Q_OBJECT
public:
- QtContactListWidget(QWidget* parent, SettingsProvider* settings);
- virtual ~QtContactListWidget();
+ QtContactListWidget(QWidget* parent, SettingsProvider* settings);
+ virtual ~QtContactListWidget();
- void setList(const std::vector<Contact::ref>& list);
- std::vector<Contact::ref> getList() const;
- Contact::ref getContact(const size_t i);
- void setMaximumNoOfContactsToOne(bool limited);
- bool isFull() const;
+ void setList(const std::vector<Contact::ref>& list);
+ std::vector<Contact::ref> getList() const;
+ Contact::ref getContact(const size_t i);
+ void setMaximumNoOfContactsToOne(bool limited);
+ bool isFull() const;
public slots:
- void updateContacts(const std::vector<Contact::ref>& contactUpdates);
+ void updateContacts(const std::vector<Contact::ref>& contactUpdates);
signals:
- void onListChanged(std::vector<Contact::ref> list);
- void onJIDsAdded(const std::vector<JID>& jids);
+ void onListChanged(std::vector<Contact::ref> list);
+ void onJIDsAdded(const std::vector<JID>& jids);
private:
- void handleSettingsChanged(const std::string&);
+ void handleSettingsChanged(const std::string&);
private:
- SettingsProvider* settings_;
- ContactListModel* contactListModel_;
- ContactListDelegate* contactListDelegate_;
- QtRemovableItemDelegate* removableItemDelegate_;
- bool limited_;
+ SettingsProvider* settings_;
+ ContactListModel* contactListModel_;
+ ContactListDelegate* contactListDelegate_;
+ QtRemovableItemDelegate* removableItemDelegate_;
+ bool limited_;
};
}
diff --git a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
index 26d0f05..4e8f4e1 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
@@ -31,180 +31,180 @@
namespace Swift {
QtSuggestingJIDInput::QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings) : QLineEdit(parent), settings_(settings) {
- treeViewPopup_ = new QTreeView();
- treeViewPopup_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
- //treeViewPopup_->setAttribute(Qt::WA_ShowWithoutActivating);
- treeViewPopup_->setAlternatingRowColors(true);
- treeViewPopup_->setIndentation(0);
- treeViewPopup_->setHeaderHidden(true);
- treeViewPopup_->setExpandsOnDoubleClick(false);
- treeViewPopup_->setItemsExpandable(false);
- treeViewPopup_->setSelectionMode(QAbstractItemView::SingleSelection);
- treeViewPopup_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- treeViewPopup_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- QSizePolicy policy(treeViewPopup_->sizePolicy());
- policy.setVerticalPolicy(QSizePolicy::Expanding);
- treeViewPopup_->setSizePolicy(policy);
- treeViewPopup_->hide();
- treeViewPopup_->setFocusProxy(this);
- connect(treeViewPopup_, SIGNAL(clicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
- connect(treeViewPopup_, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
-
- contactListModel_ = new ContactListModel(false);
- treeViewPopup_->setModel(contactListModel_);
-
- contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- treeViewPopup_->setItemDelegate(contactListDelegate_);
-
- settings_->onSettingChanged.connect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
+ treeViewPopup_ = new QTreeView();
+ treeViewPopup_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
+ //treeViewPopup_->setAttribute(Qt::WA_ShowWithoutActivating);
+ treeViewPopup_->setAlternatingRowColors(true);
+ treeViewPopup_->setIndentation(0);
+ treeViewPopup_->setHeaderHidden(true);
+ treeViewPopup_->setExpandsOnDoubleClick(false);
+ treeViewPopup_->setItemsExpandable(false);
+ treeViewPopup_->setSelectionMode(QAbstractItemView::SingleSelection);
+ treeViewPopup_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
+ treeViewPopup_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ QSizePolicy policy(treeViewPopup_->sizePolicy());
+ policy.setVerticalPolicy(QSizePolicy::Expanding);
+ treeViewPopup_->setSizePolicy(policy);
+ treeViewPopup_->hide();
+ treeViewPopup_->setFocusProxy(this);
+ connect(treeViewPopup_, SIGNAL(clicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
+ connect(treeViewPopup_, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(handleClicked(QModelIndex)));
+
+ contactListModel_ = new ContactListModel(false);
+ treeViewPopup_->setModel(contactListModel_);
+
+ contactListDelegate_ = new ContactListDelegate(settings->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ treeViewPopup_->setItemDelegate(contactListDelegate_);
+
+ settings_->onSettingChanged.connect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
}
QtSuggestingJIDInput::~QtSuggestingJIDInput() {
- settings_->onSettingChanged.disconnect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
- delete treeViewPopup_;
- delete contactListDelegate_;
- delete contactListModel_;
+ settings_->onSettingChanged.disconnect(boost::bind(&QtSuggestingJIDInput::handleSettingsChanged, this, _1));
+ delete treeViewPopup_;
+ delete contactListDelegate_;
+ delete contactListModel_;
}
Contact::ref QtSuggestingJIDInput::getContact() {
- if (!!currentContact_) {
- return currentContact_;
- }
-
- if (!text().isEmpty()) {
- JID jid(Q2PSTRING(text()));
- if (jid.isValid()) {
- Contact::ref manualContact = boost::make_shared<Contact>();
- manualContact->name = jid.toString();
- manualContact->jid = jid;
- return manualContact;
- }
- }
- return boost::shared_ptr<Contact>();
+ if (!!currentContact_) {
+ return currentContact_;
+ }
+
+ if (!text().isEmpty()) {
+ JID jid(Q2PSTRING(text()));
+ if (jid.isValid()) {
+ Contact::ref manualContact = boost::make_shared<Contact>();
+ manualContact->name = jid.toString();
+ manualContact->jid = jid;
+ return manualContact;
+ }
+ }
+ return boost::shared_ptr<Contact>();
}
void QtSuggestingJIDInput::setSuggestions(const std::vector<Contact::ref>& suggestions) {
- contactListModel_->setList(suggestions);
- positionPopup();
- if (!suggestions.empty()) {
- treeViewPopup_->setCurrentIndex(contactListModel_->index(0, 0));
- showPopup();
- } else {
- currentContact_.reset();
- hidePopup();
- }
+ contactListModel_->setList(suggestions);
+ positionPopup();
+ if (!suggestions.empty()) {
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(0, 0));
+ showPopup();
+ } else {
+ currentContact_.reset();
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::clear() {
- setText("");
- currentContact_.reset();
+ setText("");
+ currentContact_.reset();
}
void QtSuggestingJIDInput::keyPressEvent(QKeyEvent* event) {
- if (event->key() == Qt::Key_Up) {
- if (contactListModel_->rowCount() > 0) {
- int row = treeViewPopup_->currentIndex().row();
- row = (row + contactListModel_->rowCount() - 1) % contactListModel_->rowCount();
- treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
- }
- } else if (event->key() == Qt::Key_Down) {
- if (contactListModel_->rowCount() > 0) {
- int row = treeViewPopup_->currentIndex().row();
- row = (row + contactListModel_->rowCount() + 1) % contactListModel_->rowCount();
- treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
- }
- } else if (event->key() == Qt::Key_Return && treeViewPopup_->isVisible()) {
- QModelIndex index = treeViewPopup_->currentIndex();
- if (!contactListModel_->getList().empty() && index.isValid()) {
- currentContact_ = contactListModel_->getContact(index.row());
- if (currentContact_->jid.isValid()) {
- setText(P2QSTRING(currentContact_->jid.toString()));
- } else {
- setText(P2QSTRING(currentContact_->name));
- }
- hidePopup();
- clearFocus();
- } else {
- currentContact_.reset();
- }
- editingDone();
- } else {
- QLineEdit::keyPressEvent(event);
- }
+ if (event->key() == Qt::Key_Up) {
+ if (contactListModel_->rowCount() > 0) {
+ int row = treeViewPopup_->currentIndex().row();
+ row = (row + contactListModel_->rowCount() - 1) % contactListModel_->rowCount();
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
+ }
+ } else if (event->key() == Qt::Key_Down) {
+ if (contactListModel_->rowCount() > 0) {
+ int row = treeViewPopup_->currentIndex().row();
+ row = (row + contactListModel_->rowCount() + 1) % contactListModel_->rowCount();
+ treeViewPopup_->setCurrentIndex(contactListModel_->index(row, 0));
+ }
+ } else if (event->key() == Qt::Key_Return && treeViewPopup_->isVisible()) {
+ QModelIndex index = treeViewPopup_->currentIndex();
+ if (!contactListModel_->getList().empty() && index.isValid()) {
+ currentContact_ = contactListModel_->getContact(index.row());
+ if (currentContact_->jid.isValid()) {
+ setText(P2QSTRING(currentContact_->jid.toString()));
+ } else {
+ setText(P2QSTRING(currentContact_->name));
+ }
+ hidePopup();
+ clearFocus();
+ } else {
+ currentContact_.reset();
+ }
+ editingDone();
+ } else {
+ QLineEdit::keyPressEvent(event);
+ }
}
void QtSuggestingJIDInput::hideEvent(QHideEvent* /* event */) {
- // Hide our popup when we are hidden (can happen when a dialog is closed by the user).
- treeViewPopup_->hide();
+ // Hide our popup when we are hidden (can happen when a dialog is closed by the user).
+ treeViewPopup_->hide();
}
void QtSuggestingJIDInput::handleApplicationFocusChanged(QWidget* /*old*/, QWidget* /*now*/) {
- /* Using the now argument gives use the wrong widget. This is part of the code needed
- to prevent stealing of focus when opening a the suggestion window. */
- QWidget* now = qApp->focusWidget();
- if (!now || (now != treeViewPopup_ && now != this && !now->isAncestorOf(this) && !now->isAncestorOf(treeViewPopup_) && !this->isAncestorOf(now) && !treeViewPopup_->isAncestorOf(now))) {
- hidePopup();
- }
+ /* Using the now argument gives use the wrong widget. This is part of the code needed
+ to prevent stealing of focus when opening a the suggestion window. */
+ QWidget* now = qApp->focusWidget();
+ if (!now || (now != treeViewPopup_ && now != this && !now->isAncestorOf(this) && !now->isAncestorOf(treeViewPopup_) && !this->isAncestorOf(now) && !treeViewPopup_->isAncestorOf(now))) {
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::handleSettingsChanged(const std::string& setting) {
- if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
- contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
- }
+ if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) {
+ contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ }
}
void QtSuggestingJIDInput::handleClicked(const QModelIndex& index) {
- if (index.isValid()) {
- currentContact_ = contactListModel_->getContact(index.row());
- onUserSelected(currentContact_);
- hidePopup();
- }
+ if (index.isValid()) {
+ currentContact_ = contactListModel_->getContact(index.row());
+ onUserSelected(currentContact_);
+ hidePopup();
+ }
}
void QtSuggestingJIDInput::positionPopup() {
- 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 = this->width();
- int height = 80;
-
- int screenWidth = geometry.x() + geometry.width();
- if (x + width > screenWidth) {
- x = screenWidth - width;
- }
-
- height = treeViewPopup_->sizeHintForRow(0) * contactListModel_->rowCount();
- height = height > 200 ? 200 : height;
-
- int marginLeft;
- int marginTop;
- int marginRight;
- int marginBottom;
- treeViewPopup_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
- height += marginTop + marginBottom;
- width += marginLeft + marginRight;
-
- treeViewPopup_->setGeometry(x, y, width, height);
- treeViewPopup_->move(x, y);
- treeViewPopup_->setMaximumWidth(width);
+ 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 = this->width();
+ int height = 80;
+
+ int screenWidth = geometry.x() + geometry.width();
+ if (x + width > screenWidth) {
+ x = screenWidth - width;
+ }
+
+ height = treeViewPopup_->sizeHintForRow(0) * contactListModel_->rowCount();
+ height = height > 200 ? 200 : height;
+
+ int marginLeft;
+ int marginTop;
+ int marginRight;
+ int marginBottom;
+ treeViewPopup_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
+ height += marginTop + marginBottom;
+ width += marginLeft + marginRight;
+
+ treeViewPopup_->setGeometry(x, y, width, height);
+ treeViewPopup_->move(x, y);
+ treeViewPopup_->setMaximumWidth(width);
}
void QtSuggestingJIDInput::showPopup() {
- treeViewPopup_->show();
- activateWindow();
- connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
- setFocus();
+ treeViewPopup_->show();
+ activateWindow();
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
+ setFocus();
}
void QtSuggestingJIDInput::hidePopup() {
- disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
- treeViewPopup_->hide();
+ disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
+ treeViewPopup_->hide();
- // Give focus back to input widget because the hide() call passes the focus to the wrong widget.
- setFocus();
+ // Give focus back to input widget because the hide() call passes the focus to the wrong widget.
+ setFocus();
}
}
diff --git a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
index 73840b4..2077d55 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
@@ -26,44 +26,44 @@ class SettingsProvider;
class ContactListModel;
class QtSuggestingJIDInput : public QLineEdit {
- Q_OBJECT
- public:
- QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings);
- virtual ~QtSuggestingJIDInput();
+ Q_OBJECT
+ public:
+ QtSuggestingJIDInput(QWidget* parent, SettingsProvider* settings);
+ virtual ~QtSuggestingJIDInput();
- Contact::ref getContact();
+ Contact::ref getContact();
- void setSuggestions(const std::vector<Contact::ref>& suggestions);
+ void setSuggestions(const std::vector<Contact::ref>& suggestions);
- void clear();
+ void clear();
- boost::signal<void (const Contact::ref&)> onUserSelected;
+ boost::signal<void (const Contact::ref&)> onUserSelected;
- signals:
- void editingDone();
+ signals:
+ void editingDone();
- protected:
- virtual void keyPressEvent(QKeyEvent* event);
- virtual void hideEvent(QHideEvent* event);
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ virtual void hideEvent(QHideEvent* event);
- private:
- void handleSettingsChanged(const std::string& setting);
+ private:
+ void handleSettingsChanged(const std::string& setting);
- private slots:
- void handleClicked(const QModelIndex& index);
- void handleApplicationFocusChanged(QWidget* old, QWidget* now);
+ private slots:
+ void handleClicked(const QModelIndex& index);
+ void handleApplicationFocusChanged(QWidget* old, QWidget* now);
- private:
- void positionPopup();
- void showPopup();
- void hidePopup();
+ private:
+ void positionPopup();
+ void showPopup();
+ void hidePopup();
- private:
- SettingsProvider* settings_;
- ContactListModel* contactListModel_;
- QTreeView* treeViewPopup_;
- ContactListDelegate* contactListDelegate_;
- Contact::ref currentContact_;
+ private:
+ SettingsProvider* settings_;
+ ContactListModel* contactListModel_;
+ QTreeView* treeViewPopup_;
+ ContactListDelegate* contactListDelegate_;
+ Contact::ref currentContact_;
};
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
index 4e8354f..601d6ac 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
@@ -19,10 +19,10 @@
namespace Swift {
QtUserSearchDetailsPage::QtUserSearchDetailsPage(const std::set<std::string>& groups) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->addWidget(new QLabel(tr("Please choose a name for the contact, and select the groups you want to add the contact to.")));
- editWidget = new QtContactEditWidget(groups, this);
- layout->addWidget(editWidget);
+ QVBoxLayout* layout = new QVBoxLayout(this);
+ layout->addWidget(new QLabel(tr("Please choose a name for the contact, and select the groups you want to add the contact to.")));
+ editWidget = new QtContactEditWidget(groups, this);
+ layout->addWidget(editWidget);
}
QtUserSearchDetailsPage::~QtUserSearchDetailsPage() {
@@ -30,27 +30,27 @@ QtUserSearchDetailsPage::~QtUserSearchDetailsPage() {
}
void QtUserSearchDetailsPage::setJID(const JID& jid) {
- contactJID = jid;
+ contactJID = jid;
}
void QtUserSearchDetailsPage::setNameSuggestions(const std::vector<std::string>& nameSuggestions) {
- editWidget->setNameSuggestions(nameSuggestions);
+ editWidget->setNameSuggestions(nameSuggestions);
}
void QtUserSearchDetailsPage::setName(const std::string& name) {
- editWidget->setName(name);
+ editWidget->setName(name);
}
std::set<std::string> QtUserSearchDetailsPage::getSelectedGroups() {
- return editWidget->getSelectedGroups();
+ return editWidget->getSelectedGroups();
}
std::string QtUserSearchDetailsPage::getName() {
- return editWidget->getName();
+ return editWidget->getName();
}
void QtUserSearchDetailsPage::clear() {
- editWidget->clear();
+ editWidget->clear();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
index 568dfe3..7185bce 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
@@ -18,28 +18,28 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFieldsPage.h>
namespace Swift {
- class QtContactEditWidget;
+ class QtContactEditWidget;
- class QtUserSearchDetailsPage : public QWizardPage {
- Q_OBJECT
- public:
- QtUserSearchDetailsPage(const std::set<std::string>& availableGroups);
- virtual ~QtUserSearchDetailsPage();
+ class QtUserSearchDetailsPage : public QWizardPage {
+ Q_OBJECT
+ public:
+ QtUserSearchDetailsPage(const std::set<std::string>& availableGroups);
+ virtual ~QtUserSearchDetailsPage();
- void setJID(const JID& jid);
- void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
- void setName(const std::string& name);
+ void setJID(const JID& jid);
+ void setNameSuggestions(const std::vector<std::string>& nameSuggestions);
+ void setName(const std::string& name);
- std::set<std::string> getSelectedGroups();
- std::string getName();
+ std::set<std::string> getSelectedGroups();
+ std::string getName();
- void clear();
+ void clear();
- signals:
- void onUserTriggersFinish();
+ signals:
+ void onUserTriggersFinish();
- private:
- QtContactEditWidget* editWidget;
- JID contactJID;
- };
+ private:
+ QtContactEditWidget* editWidget;
+ JID contactJID;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
index 9b02273..3a82a62 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
@@ -9,34 +9,34 @@
namespace Swift {
QtUserSearchFieldsPage::QtUserSearchFieldsPage() : formWidget_(0) {
- setupUi(this);
+ setupUi(this);
}
bool QtUserSearchFieldsPage::isComplete() const {
- if (formWidget_) {
- return formWidget_->isEnabled();
- } else {
- return nickInput_->isEnabled() || firstInput_->isEnabled() || lastInput_->isEnabled() || emailInput_->isEnabled();
- }
+ if (formWidget_) {
+ return formWidget_->isEnabled();
+ } else {
+ return nickInput_->isEnabled() || firstInput_->isEnabled() || lastInput_->isEnabled() || emailInput_->isEnabled();
+ }
}
QtFormWidget* QtUserSearchFieldsPage::getFormWidget() {
- return formWidget_;
+ return formWidget_;
}
void QtUserSearchFieldsPage::setFormWidget(QtFormWidget *widget) {
- if (formWidget_) {
- delete formWidget_;
- formWidget_ = NULL;
- }
- if (widget) {
- formContainer_->layout()->addWidget(widget);
- }
- formWidget_ = widget;
+ if (formWidget_) {
+ delete formWidget_;
+ formWidget_ = NULL;
+ }
+ if (widget) {
+ formContainer_->layout()->addWidget(widget);
+ }
+ formWidget_ = widget;
}
void QtUserSearchFieldsPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
index 29ff675..4089d05 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
@@ -12,19 +12,19 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFieldsPage.h>
namespace Swift {
- class QtUserSearchFieldsPage : public QWizardPage, public Ui::QtUserSearchFieldsPage {
- Q_OBJECT
- public:
- QtUserSearchFieldsPage();
- virtual bool isComplete() const;
+ class QtUserSearchFieldsPage : public QWizardPage, public Ui::QtUserSearchFieldsPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFieldsPage();
+ virtual bool isComplete() const;
- QtFormWidget* getFormWidget();
- void setFormWidget(QtFormWidget *widget);
+ QtFormWidget* getFormWidget();
+ void setFormWidget(QtFormWidget *widget);
- public slots:
- void emitCompletenessCheck();
+ public slots:
+ void emitCompletenessCheck();
- private:
- QtFormWidget *formWidget_;
- };
+ private:
+ QtFormWidget *formWidget_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
index 40ea1c0..1327a8f 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
@@ -25,78 +25,78 @@
namespace Swift {
QtUserSearchFirstMultiJIDPage::QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings) {
- setupUi(this);
- setTitle(title);
- QString introText = "";
- switch (type) {
- case UserSearchWindow::AddContact:
- introText = tr("Add another user to your contact list");
- break;
- case UserSearchWindow::ChatToContact:
- introText = tr("Chat to another user");
- break;
- case UserSearchWindow::InviteToChat:
- introText = tr("Invite contact to chat");
- break;
- }
-
- setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(introText));
-
- contactList_ = new QtContactListWidget(this, settings);
- horizontalLayout_5->addWidget(contactList_);
-
- jid_ = new QtSuggestingJIDInput(this, settings);
- horizontalLayout_6->insertWidget(0, jid_);
-
- connect(contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(emitCompletenessCheck()));
- connect(jid_, SIGNAL(editingDone()), this, SLOT(handleEditingDone()));
-
- setAcceptDrops(true);
+ setupUi(this);
+ setTitle(title);
+ QString introText = "";
+ switch (type) {
+ case UserSearchWindow::AddContact:
+ introText = tr("Add another user to your contact list");
+ break;
+ case UserSearchWindow::ChatToContact:
+ introText = tr("Chat to another user");
+ break;
+ case UserSearchWindow::InviteToChat:
+ introText = tr("Invite contact to chat");
+ break;
+ }
+
+ setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(introText));
+
+ contactList_ = new QtContactListWidget(this, settings);
+ horizontalLayout_5->addWidget(contactList_);
+
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ horizontalLayout_6->insertWidget(0, jid_);
+
+ connect(contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(emitCompletenessCheck()));
+ connect(jid_, SIGNAL(editingDone()), this, SLOT(handleEditingDone()));
+
+ setAcceptDrops(true);
}
bool QtUserSearchFirstMultiJIDPage::isComplete() const {
- return !contactList_->getList().empty();
+ return !contactList_->getList().empty();
}
void QtUserSearchFirstMultiJIDPage::reset() {
- jid_->clear();
- reason_->clear();
+ jid_->clear();
+ reason_->clear();
}
void QtUserSearchFirstMultiJIDPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
void QtUserSearchFirstMultiJIDPage::handleEditingDone() {
- addContactButton_->setFocus();
+ addContactButton_->setFocus();
}
void QtUserSearchFirstMultiJIDPage::dragEnterEvent(QDragEnterEvent *event) {
- if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")
- || event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
- if (!contactList_->isFull()) {
- event->acceptProposedAction();
- }
- }
+ if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")
+ || event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
+ if (!contactList_->isFull()) {
+ event->acceptProposedAction();
+ }
+ }
}
void QtUserSearchFirstMultiJIDPage::dropEvent(QDropEvent *event) {
- if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
- QByteArray dataBytes = event->mimeData()->data("application/vnd.swift.contact-jid-list");
- QDataStream dataStream(&dataBytes, QIODevice::ReadOnly);
- std::vector<JID> jids;
- while (!dataStream.atEnd()) {
- QString jidString;
- dataStream >> jidString;
- jids.push_back(Q2PSTRING(jidString));
- }
- onJIDsDropped(jids);
- } else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
- QMessageBox* messageBox = new QMessageBox(this);
- messageBox->setText(tr("You can't invite a room to chat."));
- messageBox->setWindowTitle(tr("Error inviting room to chat"));
- messageBox->show();
- }
+ if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) {
+ QByteArray dataBytes = event->mimeData()->data("application/vnd.swift.contact-jid-list");
+ QDataStream dataStream(&dataBytes, QIODevice::ReadOnly);
+ std::vector<JID> jids;
+ while (!dataStream.atEnd()) {
+ QString jidString;
+ dataStream >> jidString;
+ jids.push_back(Q2PSTRING(jidString));
+ }
+ onJIDsDropped(jids);
+ } else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-muc")) {
+ QMessageBox* messageBox = new QMessageBox(this);
+ messageBox->setText(tr("You can't invite a room to chat."));
+ messageBox->setWindowTitle(tr("Error inviting room to chat"));
+ messageBox->show();
+ }
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
index 82b8f93..d9147db 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
@@ -19,35 +19,35 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstMultiJIDPage.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
- class QtContactListWidget;
- class ContactSuggester;
- class AvatarManager;
- class VCardManager;
- class SettingsProvider;
- class QtSuggestingJIDInput;
-
- class QtUserSearchFirstMultiJIDPage : public QWizardPage, public Ui::QtUserSearchFirstMultiJIDPage {
- Q_OBJECT
- public:
- QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
- virtual bool isComplete() const;
- void reset();
-
- signals:
- void onJIDsDropped(std::vector<JID> jid);
-
- public slots:
- void emitCompletenessCheck();
- void handleEditingDone();
- virtual void dragEnterEvent(QDragEnterEvent *event);
- virtual void dropEvent(QDropEvent *event);
-
- public:
- QtContactListWidget* contactList_;
- QtSuggestingJIDInput* jid_;
- };
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
+ class QtContactListWidget;
+ class ContactSuggester;
+ class AvatarManager;
+ class VCardManager;
+ class SettingsProvider;
+ class QtSuggestingJIDInput;
+
+ class QtUserSearchFirstMultiJIDPage : public QWizardPage, public Ui::QtUserSearchFirstMultiJIDPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFirstMultiJIDPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
+ virtual bool isComplete() const;
+ void reset();
+
+ signals:
+ void onJIDsDropped(std::vector<JID> jid);
+
+ public slots:
+ void emitCompletenessCheck();
+ void handleEditingDone();
+ virtual void dragEnterEvent(QDragEnterEvent *event);
+ virtual void dropEvent(QDropEvent *event);
+
+ public:
+ QtContactListWidget* contactList_;
+ QtSuggestingJIDInput* jid_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
index 93157c7..5d0c9fa 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
@@ -13,37 +13,37 @@
namespace Swift {
QtUserSearchFirstPage::QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings) {
- setupUi(this);
- setTitle(title);
- setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(type == UserSearchWindow::AddContact ? tr("Add another user to your contact list") : tr("Chat to another user")));
- jid_ = new QtSuggestingJIDInput(this, settings);
- horizontalLayout_2->addWidget(jid_);
- jidWarning_ = new QLabel(this);
- jidWarning_->setPixmap(QPixmap(":icons/warn.png"));
- jidWarning_->hide();
- horizontalLayout_2->addWidget(jidWarning_);
- setTabOrder(byJID_, jid_);
- setTabOrder(jid_, byLocalSearch_);
- setTabOrder(byLocalSearch_, byRemoteSearch_);
- connect(jid_, SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
- connect(jid_, SIGNAL(editingDone()), this, SLOT(emitCompletenessCheck()));
- connect(service_->lineEdit(), SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
+ setupUi(this);
+ setTitle(title);
+ setSubTitle(QString(tr("%1. If you know their address you can enter it directly, or you can search for them.")).arg(type == UserSearchWindow::AddContact ? tr("Add another user to your contact list") : tr("Chat to another user")));
+ jid_ = new QtSuggestingJIDInput(this, settings);
+ horizontalLayout_2->addWidget(jid_);
+ jidWarning_ = new QLabel(this);
+ jidWarning_->setPixmap(QPixmap(":icons/warn.png"));
+ jidWarning_->hide();
+ horizontalLayout_2->addWidget(jidWarning_);
+ setTabOrder(byJID_, jid_);
+ setTabOrder(jid_, byLocalSearch_);
+ setTabOrder(byLocalSearch_, byRemoteSearch_);
+ connect(jid_, SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
+ connect(jid_, SIGNAL(editingDone()), this, SLOT(emitCompletenessCheck()));
+ connect(service_->lineEdit(), SIGNAL(textChanged(const QString&)), this, SLOT(emitCompletenessCheck()));
}
bool QtUserSearchFirstPage::isComplete() const {
- bool complete = false;
- if (byJID_->isChecked()) {
- complete = JID(Q2PSTRING(jid_->text().trimmed())).isValid() && jidWarning_->toolTip().isEmpty();
- } else if (byLocalSearch_->isChecked()) {
- complete = true;
- } else if (byRemoteSearch_->isChecked()) {
- complete = JID(Q2PSTRING(service_->currentText().trimmed())).isValid();
- }
- return complete;
+ bool complete = false;
+ if (byJID_->isChecked()) {
+ complete = JID(Q2PSTRING(jid_->text().trimmed())).isValid() && jidWarning_->toolTip().isEmpty();
+ } else if (byLocalSearch_->isChecked()) {
+ complete = true;
+ } else if (byRemoteSearch_->isChecked()) {
+ complete = JID(Q2PSTRING(service_->currentText().trimmed())).isValid();
+ }
+ return complete;
}
void QtUserSearchFirstPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
index 9e765a0..2e73e9e 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
@@ -14,20 +14,20 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstPage.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
- class QtUserSearchFirstPage : public QWizardPage, public Ui::QtUserSearchFirstPage {
- Q_OBJECT
- public:
- QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
- virtual bool isComplete() const;
- public slots:
- void emitCompletenessCheck();
- public:
- QtSuggestingJIDInput* jid_;
- QLabel* jidWarning_;
- };
+ class QtUserSearchFirstPage : public QWizardPage, public Ui::QtUserSearchFirstPage {
+ Q_OBJECT
+ public:
+ QtUserSearchFirstPage(UserSearchWindow::Type type, const QString& title, SettingsProvider* settings);
+ virtual bool isComplete() const;
+ public slots:
+ void emitCompletenessCheck();
+ public:
+ QtSuggestingJIDInput* jid_;
+ QLabel* jidWarning_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
index 6ec4a34..c8a9ad8 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
@@ -9,31 +9,31 @@
namespace Swift {
QtUserSearchResultsPage::QtUserSearchResultsPage() {
- setupUi(this);
- connect(results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- connect(results_, SIGNAL(activated(const QModelIndex&)), this, SIGNAL(onUserTriggersContinue()));
- connect(results_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- connect(results_, SIGNAL(entered(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
- results_->setExpandsOnDoubleClick(false);
- setNoResults(false);
+ setupUi(this);
+ connect(results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ connect(results_, SIGNAL(activated(const QModelIndex&)), this, SIGNAL(onUserTriggersContinue()));
+ connect(results_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ connect(results_, SIGNAL(entered(const QModelIndex&)), this, SLOT(emitCompletenessCheck()));
+ results_->setExpandsOnDoubleClick(false);
+ setNoResults(false);
}
bool QtUserSearchResultsPage::isComplete() const {
- return results_->currentIndex().isValid();
+ return results_->currentIndex().isValid();
}
void QtUserSearchResultsPage::setNoResults(bool noResults) {
- if (noResults) {
- results_->setEnabled(false);
- noResults_->show();
- } else {
- results_->setEnabled(true);
- noResults_->hide();
- }
+ if (noResults) {
+ results_->setEnabled(false);
+ noResults_->show();
+ } else {
+ results_->setEnabled(true);
+ noResults_->hide();
+ }
}
void QtUserSearchResultsPage::emitCompletenessCheck() {
- emit completeChanged();
+ emit completeChanged();
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
index d2ee566..33227e6 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
@@ -11,15 +11,15 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchResultsPage.h>
namespace Swift {
- class QtUserSearchResultsPage : public QWizardPage, public Ui::QtUserSearchResultsPage {
- Q_OBJECT
- public:
- QtUserSearchResultsPage();
- virtual bool isComplete() const;
- void setNoResults(bool noResults);
- signals:
- void onUserTriggersContinue();
- public slots:
- void emitCompletenessCheck();
- };
+ class QtUserSearchResultsPage : public QWizardPage, public Ui::QtUserSearchResultsPage {
+ Q_OBJECT
+ public:
+ QtUserSearchResultsPage();
+ virtual bool isComplete() const;
+ void setNoResults(bool noResults);
+ signals:
+ void onUserTriggersContinue();
+ public slots:
+ void emitCompletenessCheck();
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp b/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
index 52b17b0..1140b6e 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
@@ -37,592 +37,592 @@
namespace Swift {
QtUserSearchWindow::QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider) : eventStream_(eventStream), type_(type), model_(NULL), firstMultiJIDPage_(NULL), settings_(settingsProvider), searchNext_(false), supportsImpromptu_(false) {
- setupUi(this);
+ setupUi(this);
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- QString title;
- switch(type) {
- case AddContact:
- title = tr("Add Contact");
- break;
- case ChatToContact:
- title = tr("Chat to Users");
- break;
- case InviteToChat:
- title = tr("Add Users to Chat");
- break;
- }
- setWindowTitle(title);
-
- delegate_ = new UserSearchDelegate(this);
-
- setFirstPage(title);
- setSecondPage();
- setThirdPage();
-
- detailsPage_ = new QtUserSearchDetailsPage(groups);
- setPage(4, detailsPage_);
-
- connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(handleCurrentChanged(int)));
- connect(this, SIGNAL(accepted()), this, SLOT(handleAccepted()));
- clear();
+ QString title;
+ switch(type) {
+ case AddContact:
+ title = tr("Add Contact");
+ break;
+ case ChatToContact:
+ title = tr("Chat to Users");
+ break;
+ case InviteToChat:
+ title = tr("Add Users to Chat");
+ break;
+ }
+ setWindowTitle(title);
+
+ delegate_ = new UserSearchDelegate(this);
+
+ setFirstPage(title);
+ setSecondPage();
+ setThirdPage();
+
+ detailsPage_ = new QtUserSearchDetailsPage(groups);
+ setPage(4, detailsPage_);
+
+ connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(handleCurrentChanged(int)));
+ connect(this, SIGNAL(accepted()), this, SLOT(handleAccepted()));
+ clear();
}
QtUserSearchWindow::~QtUserSearchWindow() {
- delete model_;
+ delete model_;
}
void QtUserSearchWindow::handleCurrentChanged(int page) {
- searchNext_ = false;
- if (firstMultiJIDPage_) {
- firstMultiJIDPage_->reset();
- }
- resultsPage_->emitCompletenessCheck();
- if (page == 1 && lastPage_ == 3) {
- addSearchedJIDToList(getContact());
- setSecondPage();
- }
- else if (page == 2 && lastPage_ == 1) {
- setError("");
- /* next won't be called if JID is selected */
- JID server = getServerToSearch();
- clearForm();
- onFormRequested(server);
- setThirdPage();
- }
- else if (page == 3 && lastPage_ == 2) {
- JID server = getServerToSearch();
- handleSearch();
-
- if (type_ == AddContact) {
- bool remote = firstPage_->byRemoteSearch_->isChecked();
- firstPage_->byRemoteSearch_->setChecked(remote);
- firstPage_->service_->setEditText(P2QSTRING(server.toString()));
- } else {
- bool remote = firstMultiJIDPage_->byRemoteSearch_->isChecked();
- setFirstPage();
- firstMultiJIDPage_->byRemoteSearch_->setChecked(remote);
- firstMultiJIDPage_->service_->setEditText(P2QSTRING(server.toString()));
- }
- }
- else if (page == 4) {
- detailsPage_->clear();
- detailsPage_->setJID(getContactJID());
- onNameSuggestionRequested(getContactJID());
- }
- lastPage_ = page;
+ searchNext_ = false;
+ if (firstMultiJIDPage_) {
+ firstMultiJIDPage_->reset();
+ }
+ resultsPage_->emitCompletenessCheck();
+ if (page == 1 && lastPage_ == 3) {
+ addSearchedJIDToList(getContact());
+ setSecondPage();
+ }
+ else if (page == 2 && lastPage_ == 1) {
+ setError("");
+ /* next won't be called if JID is selected */
+ JID server = getServerToSearch();
+ clearForm();
+ onFormRequested(server);
+ setThirdPage();
+ }
+ else if (page == 3 && lastPage_ == 2) {
+ JID server = getServerToSearch();
+ handleSearch();
+
+ if (type_ == AddContact) {
+ bool remote = firstPage_->byRemoteSearch_->isChecked();
+ firstPage_->byRemoteSearch_->setChecked(remote);
+ firstPage_->service_->setEditText(P2QSTRING(server.toString()));
+ } else {
+ bool remote = firstMultiJIDPage_->byRemoteSearch_->isChecked();
+ setFirstPage();
+ firstMultiJIDPage_->byRemoteSearch_->setChecked(remote);
+ firstMultiJIDPage_->service_->setEditText(P2QSTRING(server.toString()));
+ }
+ }
+ else if (page == 4) {
+ detailsPage_->clear();
+ detailsPage_->setJID(getContactJID());
+ onNameSuggestionRequested(getContactJID());
+ }
+ lastPage_ = page;
}
JID QtUserSearchWindow::getServerToSearch() {
- if (type_ == AddContact) {
- return firstPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstPage_->service_->currentText().trimmed())) : myServer_;
- } else {
- return firstMultiJIDPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstMultiJIDPage_->service_->currentText().trimmed())) : myServer_;
- }
+ if (type_ == AddContact) {
+ return firstPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstPage_->service_->currentText().trimmed())) : myServer_;
+ } else {
+ return firstMultiJIDPage_->byRemoteSearch_->isChecked() ? JID(Q2PSTRING(firstMultiJIDPage_->service_->currentText().trimmed())) : myServer_;
+ }
}
void QtUserSearchWindow::handleAccepted() {
- JID jid;
- std::vector<JID> jids;
- switch(type_) {
- case AddContact:
- jid = getContactJID();
- eventStream_->send(boost::make_shared<AddContactUIEvent>(jid, detailsPage_->getName(), detailsPage_->getSelectedGroups()));
- break;
- case ChatToContact:
- if (contactVector_.size() == 1) {
- boost::shared_ptr<UIEvent> event(new RequestChatUIEvent(contactVector_[0]->jid));
- eventStream_->send(event);
- break;
- }
-
- foreach(Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
-
- eventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(jids, JID(), Q2PSTRING(firstMultiJIDPage_->reason_->text())));
- break;
- case InviteToChat:
- foreach(Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
- eventStream_->send(boost::make_shared<InviteToMUCUIEvent>(roomJID_, jids, Q2PSTRING(firstMultiJIDPage_->reason_->text())));
- break;
- }
+ JID jid;
+ std::vector<JID> jids;
+ switch(type_) {
+ case AddContact:
+ jid = getContactJID();
+ eventStream_->send(boost::make_shared<AddContactUIEvent>(jid, detailsPage_->getName(), detailsPage_->getSelectedGroups()));
+ break;
+ case ChatToContact:
+ if (contactVector_.size() == 1) {
+ boost::shared_ptr<UIEvent> event(new RequestChatUIEvent(contactVector_[0]->jid));
+ eventStream_->send(event);
+ break;
+ }
+
+ foreach(Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+
+ eventStream_->send(boost::make_shared<CreateImpromptuMUCUIEvent>(jids, JID(), Q2PSTRING(firstMultiJIDPage_->reason_->text())));
+ break;
+ case InviteToChat:
+ foreach(Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+ eventStream_->send(boost::make_shared<InviteToMUCUIEvent>(roomJID_, jids, Q2PSTRING(firstMultiJIDPage_->reason_->text())));
+ break;
+ }
}
void QtUserSearchWindow::handleContactSuggestionRequested(const QString& text) {
- std::string stdText = Q2PSTRING(text);
- onContactSuggestionsRequested(stdText);
+ std::string stdText = Q2PSTRING(text);
+ onContactSuggestionsRequested(stdText);
}
void QtUserSearchWindow::addContact() {
- if (!!firstMultiJIDPage_->jid_->getContact()) {
- contactVector_.push_back(firstMultiJIDPage_->jid_->getContact());
- firstMultiJIDPage_->jid_->clear();
- }
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->emitCompletenessCheck();
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
- }
+ if (!!firstMultiJIDPage_->jid_->getContact()) {
+ contactVector_.push_back(firstMultiJIDPage_->jid_->getContact());
+ firstMultiJIDPage_->jid_->clear();
+ }
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->emitCompletenessCheck();
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
+ }
}
void QtUserSearchWindow::setWarning(const boost::optional<std::string>& message) {
- if (message) {
- firstPage_->jidWarning_->setToolTip(P2QSTRING((*message)));
- firstPage_->jidWarning_->setAccessibleDescription(P2QSTRING((*message)));
- firstPage_->jidWarning_->show();
- }
- else {
- firstPage_->jidWarning_->setToolTip("");
- firstPage_->jidWarning_->setAccessibleDescription("");
- firstPage_->jidWarning_->hide();
- }
- firstPage_->emitCompletenessCheck();
+ if (message) {
+ firstPage_->jidWarning_->setToolTip(P2QSTRING((*message)));
+ firstPage_->jidWarning_->setAccessibleDescription(P2QSTRING((*message)));
+ firstPage_->jidWarning_->show();
+ }
+ else {
+ firstPage_->jidWarning_->setToolTip("");
+ firstPage_->jidWarning_->setAccessibleDescription("");
+ firstPage_->jidWarning_->hide();
+ }
+ firstPage_->emitCompletenessCheck();
}
int QtUserSearchWindow::nextId() const {
- if (type_ == AddContact) {
- switch (currentId()) {
- case 1: return firstPage_->byJID_->isChecked() ? (type_ == AddContact ? 4 : -1) : 2;
- case 2: return 3;
- case 3: return type_ == AddContact ? 4 : -1;
- case 4: return -1;
- default: return -1;
- }
- } else {
- switch (currentId()) {
- case 1: return searchNext_ ? 2 : -1;
- case 2: return 3;
- case 3: return 1;
- case 4: return -1;
- default: return -1;
- }
- }
+ if (type_ == AddContact) {
+ switch (currentId()) {
+ case 1: return firstPage_->byJID_->isChecked() ? (type_ == AddContact ? 4 : -1) : 2;
+ case 2: return 3;
+ case 3: return type_ == AddContact ? 4 : -1;
+ case 4: return -1;
+ default: return -1;
+ }
+ } else {
+ switch (currentId()) {
+ case 1: return searchNext_ ? 2 : -1;
+ case 2: return 3;
+ case 3: return 1;
+ case 4: return -1;
+ default: return -1;
+ }
+ }
}
void QtUserSearchWindow::handleFirstPageRadioChange() {
- if (firstPage_->byJID_->isChecked()) {
- firstPage_->jid_->setText("");
- firstPage_->jid_->setEnabled(true);
- firstPage_->service_->setEnabled(false);
- restart();
- }
- else if (firstPage_->byRemoteSearch_->isChecked()) {
- firstPage_->service_->setEditText("");
- firstPage_->jid_->setEnabled(false);
- firstPage_->service_->setEnabled(true);
- //firstPage_->jid_->setText("");
- restart();
- }
- else {
- firstPage_->jid_->setEnabled(false);
- firstPage_->service_->setEnabled(false);
- restart();
- }
+ if (firstPage_->byJID_->isChecked()) {
+ firstPage_->jid_->setText("");
+ firstPage_->jid_->setEnabled(true);
+ firstPage_->service_->setEnabled(false);
+ restart();
+ }
+ else if (firstPage_->byRemoteSearch_->isChecked()) {
+ firstPage_->service_->setEditText("");
+ firstPage_->jid_->setEnabled(false);
+ firstPage_->service_->setEnabled(true);
+ //firstPage_->jid_->setText("");
+ restart();
+ }
+ else {
+ firstPage_->jid_->setEnabled(false);
+ firstPage_->service_->setEnabled(false);
+ restart();
+ }
}
void QtUserSearchWindow::handleSearch() {
- boost::shared_ptr<SearchPayload> search(new SearchPayload());
- if (fieldsPage_->getFormWidget()) {
- search->setForm(fieldsPage_->getFormWidget()->getCompletedForm());
- search->getForm()->clearEmptyTextFields();
- } else {
- if (fieldsPage_->nickInput_->isEnabled() && !fieldsPage_->nickInput_->text().isEmpty()) {
- search->setNick(Q2PSTRING(fieldsPage_->nickInput_->text()));
- }
- if (fieldsPage_->firstInput_->isEnabled() && !fieldsPage_->firstInput_->text().isEmpty()) {
- search->setFirst(Q2PSTRING(fieldsPage_->firstInput_->text()));
- }
- if (fieldsPage_->lastInput_->isEnabled() && !fieldsPage_->lastInput_->text().isEmpty()) {
- search->setLast(Q2PSTRING(fieldsPage_->lastInput_->text()));
- }
- if (fieldsPage_->emailInput_->isEnabled() && !fieldsPage_->emailInput_->text().isEmpty()) {
- search->setEMail(Q2PSTRING(fieldsPage_->emailInput_->text()));
- }
- }
- onSearchRequested(search, getServerToSearch());
+ boost::shared_ptr<SearchPayload> search(new SearchPayload());
+ if (fieldsPage_->getFormWidget()) {
+ search->setForm(fieldsPage_->getFormWidget()->getCompletedForm());
+ search->getForm()->clearEmptyTextFields();
+ } else {
+ if (fieldsPage_->nickInput_->isEnabled() && !fieldsPage_->nickInput_->text().isEmpty()) {
+ search->setNick(Q2PSTRING(fieldsPage_->nickInput_->text()));
+ }
+ if (fieldsPage_->firstInput_->isEnabled() && !fieldsPage_->firstInput_->text().isEmpty()) {
+ search->setFirst(Q2PSTRING(fieldsPage_->firstInput_->text()));
+ }
+ if (fieldsPage_->lastInput_->isEnabled() && !fieldsPage_->lastInput_->text().isEmpty()) {
+ search->setLast(Q2PSTRING(fieldsPage_->lastInput_->text()));
+ }
+ if (fieldsPage_->emailInput_->isEnabled() && !fieldsPage_->emailInput_->text().isEmpty()) {
+ search->setEMail(Q2PSTRING(fieldsPage_->emailInput_->text()));
+ }
+ }
+ onSearchRequested(search, getServerToSearch());
}
JID QtUserSearchWindow::getContactJID() const {
- JID jid;
-
- bool useSearchResult;
- if (type_ == AddContact) {
- useSearchResult = !firstPage_->byJID_->isChecked();
- } else {
- useSearchResult = true;
- }
-
- if (useSearchResult) {
- if (dynamic_cast<UserSearchModel*>(model_)) {
- UserSearchResult* userItem = static_cast<UserSearchResult*>(resultsPage_->results_->currentIndex().internalPointer());
- if (userItem) { /* Remember to leave this if we change to dynamic cast */
- jid = userItem->getJID();
- }
- } else if (dynamic_cast<QtFormResultItemModel*>(model_)) {
- int row = resultsPage_->results_->currentIndex().row();
-
- Form::FormItem item = dynamic_cast<QtFormResultItemModel*>(model_)->getForm()->getItems().at(row);
- JID fallbackJid;
- foreach(FormField::ref field, item) {
- if (field->getType() == FormField::JIDSingleType) {
- jid = JID(field->getJIDSingleValue());
- break;
- }
- if (field->getName() == "jid") {
- fallbackJid = field->getValues()[0];
- }
- }
- if (!jid.isValid()) {
- jid = fallbackJid;
- }
- }
- }
- else {
- jid = JID(Q2PSTRING(firstPage_->jid_->text().trimmed()));
- }
- return jid;
+ JID jid;
+
+ bool useSearchResult;
+ if (type_ == AddContact) {
+ useSearchResult = !firstPage_->byJID_->isChecked();
+ } else {
+ useSearchResult = true;
+ }
+
+ if (useSearchResult) {
+ if (dynamic_cast<UserSearchModel*>(model_)) {
+ UserSearchResult* userItem = static_cast<UserSearchResult*>(resultsPage_->results_->currentIndex().internalPointer());
+ if (userItem) { /* Remember to leave this if we change to dynamic cast */
+ jid = userItem->getJID();
+ }
+ } else if (dynamic_cast<QtFormResultItemModel*>(model_)) {
+ int row = resultsPage_->results_->currentIndex().row();
+
+ Form::FormItem item = dynamic_cast<QtFormResultItemModel*>(model_)->getForm()->getItems().at(row);
+ JID fallbackJid;
+ foreach(FormField::ref field, item) {
+ if (field->getType() == FormField::JIDSingleType) {
+ jid = JID(field->getJIDSingleValue());
+ break;
+ }
+ if (field->getName() == "jid") {
+ fallbackJid = field->getValues()[0];
+ }
+ }
+ if (!jid.isValid()) {
+ jid = fallbackJid;
+ }
+ }
+ }
+ else {
+ jid = JID(Q2PSTRING(firstPage_->jid_->text().trimmed()));
+ }
+ return jid;
}
Contact::ref QtUserSearchWindow::getContact() const {
- return boost::make_shared<Contact>("", getContactJID(), StatusShow::None, "");
+ return boost::make_shared<Contact>("", getContactJID(), StatusShow::None, "");
}
void QtUserSearchWindow::addSearchedJIDToList(const Contact::ref& contact) {
- std::vector<JID> jids;
- jids.push_back(contact->jid);
- handleJIDsAdded(jids);
- firstMultiJIDPage_->jid_->clear();
+ std::vector<JID> jids;
+ jids.push_back(contact->jid);
+ handleJIDsAdded(jids);
+ firstMultiJIDPage_->jid_->clear();
}
void QtUserSearchWindow::handleOnSearchedJIDSelected(const Contact::ref& contact) {
- firstPage_->jid_->setText(P2QSTRING(contact->jid.toString()));
+ firstPage_->jid_->setText(P2QSTRING(contact->jid.toString()));
}
void QtUserSearchWindow::show() {
- clear();
- if (type_ == AddContact) {
- setWarning(boost::optional<std::string>());
- }
- QWidget::show();
+ clear();
+ if (type_ == AddContact) {
+ setWarning(boost::optional<std::string>());
+ }
+ QWidget::show();
}
void QtUserSearchWindow::addSavedServices(const std::vector<JID>& services) {
- if (type_ == AddContact) {
- firstPage_->service_->clear();
- foreach (JID jid, services) {
- firstPage_->service_->addItem(P2QSTRING(jid.toString()));
- }
- firstPage_->service_->clearEditText();
- } else {
- firstMultiJIDPage_->service_->clear();
- foreach (JID jid, services) {
- firstMultiJIDPage_->service_->addItem(P2QSTRING(jid.toString()));
- }
- firstMultiJIDPage_->service_->clearEditText();
- }
+ if (type_ == AddContact) {
+ firstPage_->service_->clear();
+ foreach (JID jid, services) {
+ firstPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstPage_->service_->clearEditText();
+ } else {
+ firstMultiJIDPage_->service_->clear();
+ foreach (JID jid, services) {
+ firstMultiJIDPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstMultiJIDPage_->service_->clearEditText();
+ }
}
void QtUserSearchWindow::setSearchFields(boost::shared_ptr<SearchPayload> fields) {
- fieldsPage_->fetchingThrobber_->hide();
- fieldsPage_->fetchingThrobber_->movie()->stop();
- fieldsPage_->fetchingLabel_->hide();
-
- fieldsPage_->instructionsLabel_->setText(fields->getInstructions() ? P2QSTRING(fields->getInstructions().get()) : "Enter search terms");
- if (fields->getForm()) {
- fieldsPage_->setFormWidget(new QtFormWidget(fields->getForm(), fieldsPage_));
- } else {
- fieldsPage_->setFormWidget(NULL);
- bool enabled[8] = {!!fields->getNick(), !!fields->getNick(), !!fields->getFirst(), !!fields->getFirst(), !!fields->getLast(), !!fields->getLast(), !!fields->getEMail(), !!fields->getEMail()};
- QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
- for (int i = 0; i < 8; i++) {
- legacySearchWidgets[i]->setVisible(enabled[i]);
- legacySearchWidgets[i]->setEnabled(enabled[i]);
- }
- }
- fieldsPage_->emitCompletenessCheck();
+ fieldsPage_->fetchingThrobber_->hide();
+ fieldsPage_->fetchingThrobber_->movie()->stop();
+ fieldsPage_->fetchingLabel_->hide();
+
+ fieldsPage_->instructionsLabel_->setText(fields->getInstructions() ? P2QSTRING(fields->getInstructions().get()) : "Enter search terms");
+ if (fields->getForm()) {
+ fieldsPage_->setFormWidget(new QtFormWidget(fields->getForm(), fieldsPage_));
+ } else {
+ fieldsPage_->setFormWidget(NULL);
+ bool enabled[8] = {!!fields->getNick(), !!fields->getNick(), !!fields->getFirst(), !!fields->getFirst(), !!fields->getLast(), !!fields->getLast(), !!fields->getEMail(), !!fields->getEMail()};
+ QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
+ for (int i = 0; i < 8; i++) {
+ legacySearchWidgets[i]->setVisible(enabled[i]);
+ legacySearchWidgets[i]->setEnabled(enabled[i]);
+ }
+ }
+ fieldsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setNameSuggestions(const std::vector<std::string>& suggestions) {
- if (detailsPage_) {
- detailsPage_->setNameSuggestions(suggestions);
- }
+ if (detailsPage_) {
+ detailsPage_->setNameSuggestions(suggestions);
+ }
}
void QtUserSearchWindow::prepopulateJIDAndName(const JID& jid, const std::string& name) {
- firstPage_->jid_->setText(P2QSTRING(jid.toBare().toString()));
- detailsPage_->setJID(jid);
- lastPage_ = 1;
- restart();
- next();
- detailsPage_->setName(name);
+ firstPage_->jid_->setText(P2QSTRING(jid.toBare().toString()));
+ detailsPage_->setJID(jid);
+ lastPage_ = 1;
+ restart();
+ next();
+ detailsPage_->setName(name);
}
void QtUserSearchWindow::setContactSuggestions(const std::vector<Contact::ref>& suggestions) {
- if (type_ == AddContact) {
- firstPage_->jid_->setSuggestions(suggestions);
- } else {
- firstMultiJIDPage_->jid_->setSuggestions(suggestions);
- }
+ if (type_ == AddContact) {
+ firstPage_->jid_->setSuggestions(suggestions);
+ } else {
+ firstMultiJIDPage_->jid_->setSuggestions(suggestions);
+ }
}
void QtUserSearchWindow::setJIDs(const std::vector<JID> &jids) {
- foreach(JID jid, jids) {
- addSearchedJIDToList(boost::make_shared<Contact>("", jid, StatusShow::None, ""));
- }
- onJIDUpdateRequested(jids);
+ foreach(JID jid, jids) {
+ addSearchedJIDToList(boost::make_shared<Contact>("", jid, StatusShow::None, ""));
+ }
+ onJIDUpdateRequested(jids);
}
void QtUserSearchWindow::setRoomJID(const JID& roomJID) {
- roomJID_ = roomJID;
+ roomJID_ = roomJID;
}
std::string QtUserSearchWindow::getReason() const {
- return Q2PSTRING(firstMultiJIDPage_->reason_->text());
+ return Q2PSTRING(firstMultiJIDPage_->reason_->text());
}
std::vector<JID> QtUserSearchWindow::getJIDs() const {
- std::vector<JID> jids;
- foreach (Contact::ref contact, contactVector_) {
- jids.push_back(contact->jid);
- }
- return jids;
+ std::vector<JID> jids;
+ foreach (Contact::ref contact, contactVector_) {
+ jids.push_back(contact->jid);
+ }
+ return jids;
}
void QtUserSearchWindow::setCanStartImpromptuChats(bool supportsImpromptu) {
- supportsImpromptu_ = supportsImpromptu;
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->contactList_->setMaximumNoOfContactsToOne(!supportsImpromptu_);
- }
+ supportsImpromptu_ = supportsImpromptu;
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->contactList_->setMaximumNoOfContactsToOne(!supportsImpromptu_);
+ }
}
void QtUserSearchWindow::updateContacts(const std::vector<Contact::ref>& contacts) {
- if (type_ != AddContact) {
- firstMultiJIDPage_->contactList_->updateContacts(contacts);
- }
+ if (type_ != AddContact) {
+ firstMultiJIDPage_->contactList_->updateContacts(contacts);
+ }
}
void QtUserSearchWindow::addContacts(const std::vector<Contact::ref>& contacts) {
- if (type_ != AddContact) {
- /* prevent duplicate JIDs from appearing in the contact list */
- foreach (Contact::ref newContact, contacts) {
- bool found = false;
- foreach (Contact::ref oldContact, contactVector_) {
- if (newContact->jid == oldContact->jid) {
- found = true;
- break;
- }
- }
- if (!found) {
- contactVector_.push_back(newContact);
- }
- }
- if (!supportsImpromptu_ && contactVector_.size() > 1) {
- contactVector_.resize(1); /* can't chat with more than one user */
- }
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->emitCompletenessCheck();
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? true : (contactVector_.size() < 1));
- }
- }
+ if (type_ != AddContact) {
+ /* prevent duplicate JIDs from appearing in the contact list */
+ foreach (Contact::ref newContact, contacts) {
+ bool found = false;
+ foreach (Contact::ref oldContact, contactVector_) {
+ if (newContact->jid == oldContact->jid) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ contactVector_.push_back(newContact);
+ }
+ }
+ if (!supportsImpromptu_ && contactVector_.size() > 1) {
+ contactVector_.resize(1); /* can't chat with more than one user */
+ }
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->emitCompletenessCheck();
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? true : (contactVector_.size() < 1));
+ }
+ }
}
void QtUserSearchWindow::setCanSupplyDescription(bool allowed) {
- firstMultiJIDPage_->label->setVisible(allowed);
- firstMultiJIDPage_->reason_->setVisible(allowed);
+ firstMultiJIDPage_->label->setVisible(allowed);
+ firstMultiJIDPage_->reason_->setVisible(allowed);
}
void QtUserSearchWindow::handleAddViaSearch() {
- searchNext_ = true;
- next();
+ searchNext_ = true;
+ next();
}
void QtUserSearchWindow::handleListChanged(std::vector<Contact::ref> list) {
- contactVector_ = list;
- if (type_ == ChatToContact) {
- firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
- }
+ contactVector_ = list;
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
+ }
}
void QtUserSearchWindow::handleJIDsAdded(std::vector<JID> jids) {
- onJIDAddRequested(jids);
+ onJIDAddRequested(jids);
}
void QtUserSearchWindow::setResults(const std::vector<UserSearchResult>& results) {
- UserSearchModel *newModel = new UserSearchModel();
- newModel->setResults(results);
- resultsPage_->results_->setModel(newModel);
- resultsPage_->results_->setItemDelegate(delegate_);
- resultsPage_->results_->setHeaderHidden(true);
- delete model_;
- model_ = newModel;
- resultsPage_->setNoResults(model_->rowCount() == 0);
- resultsPage_->emitCompletenessCheck();
+ UserSearchModel *newModel = new UserSearchModel();
+ newModel->setResults(results);
+ resultsPage_->results_->setModel(newModel);
+ resultsPage_->results_->setItemDelegate(delegate_);
+ resultsPage_->results_->setHeaderHidden(true);
+ delete model_;
+ model_ = newModel;
+ resultsPage_->setNoResults(model_->rowCount() == 0);
+ resultsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setResultsForm(Form::ref results) {
- QtFormResultItemModel *newModel = new QtFormResultItemModel(this);
- newModel->setForm(results);
- resultsPage_->results_->setModel(newModel);
- resultsPage_->results_->setItemDelegate(new QItemDelegate());
- resultsPage_->results_->setHeaderHidden(false);
+ QtFormResultItemModel *newModel = new QtFormResultItemModel(this);
+ newModel->setForm(results);
+ resultsPage_->results_->setModel(newModel);
+ resultsPage_->results_->setItemDelegate(new QItemDelegate());
+ resultsPage_->results_->setHeaderHidden(false);
#if QT_VERSION >= 0x050000
- resultsPage_->results_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
+ resultsPage_->results_->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
- resultsPage_->results_->header()->setResizeMode(QHeaderView::ResizeToContents);
+ resultsPage_->results_->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
- delete model_;
- model_ = newModel;
- resultsPage_->setNoResults(model_->rowCount() == 0);
- resultsPage_->emitCompletenessCheck();
+ delete model_;
+ model_ = newModel;
+ resultsPage_->setNoResults(model_->rowCount() == 0);
+ resultsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::setSelectedService(const JID& jid) {
- myServer_ = jid;
+ myServer_ = jid;
}
void QtUserSearchWindow::handleJIDEditingDone() {
- onJIDEditFieldChanged(JID(Q2PSTRING(firstPage_->jid_->text())));
+ onJIDEditFieldChanged(JID(Q2PSTRING(firstPage_->jid_->text())));
}
void QtUserSearchWindow::setFirstPage(QString title) {
- if (page(1) != 0) {
- removePage(1);
- }
- if (type_ == AddContact) {
- firstPage_ = new QtUserSearchFirstPage(type_, title.isEmpty() ? firstPage_->title() : title, settings_);
- connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
- connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleJIDEditingDone()), Qt::UniqueConnection);
- firstPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::handleOnSearchedJIDSelected, this, _1));
- connect(firstPage_->byJID_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
- connect(firstPage_->byLocalSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
- connect(firstPage_->byRemoteSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ if (page(1) != 0) {
+ removePage(1);
+ }
+ if (type_ == AddContact) {
+ firstPage_ = new QtUserSearchFirstPage(type_, title.isEmpty() ? firstPage_->title() : title, settings_);
+ connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
+ connect(firstPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleJIDEditingDone()), Qt::UniqueConnection);
+ firstPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::handleOnSearchedJIDSelected, this, _1));
+ connect(firstPage_->byJID_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ connect(firstPage_->byLocalSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
+ connect(firstPage_->byRemoteSearch_, SIGNAL(toggled(bool)), this, SLOT(handleFirstPageRadioChange()));
#if QT_VERSION >= 0x040700
- firstPage_->jid_->setPlaceholderText(tr("alice@wonderland.lit"));
+ firstPage_->jid_->setPlaceholderText(tr("alice@wonderland.lit"));
#endif
- firstPage_->service_->setEnabled(false);
- setPage(1, firstPage_);
- } else {
- firstMultiJIDPage_ = new QtUserSearchFirstMultiJIDPage(type_, title.isEmpty() ? firstMultiJIDPage_->title() : title, settings_);
- connect(firstMultiJIDPage_->addContactButton_, SIGNAL(clicked()), this, SLOT(addContact()));
- connect(firstMultiJIDPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
- firstMultiJIDPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::addSearchedJIDToList, this, _1));
- connect(firstMultiJIDPage_->addViaSearchButton_, SIGNAL(clicked()), this, SLOT(handleAddViaSearch()));
- connect(firstMultiJIDPage_->contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(handleListChanged(std::vector<Contact::ref>)));
- connect(firstMultiJIDPage_->contactList_, SIGNAL(onJIDsAdded(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
- connect(firstMultiJIDPage_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
- setPage(1, firstMultiJIDPage_);
- }
+ firstPage_->service_->setEnabled(false);
+ setPage(1, firstPage_);
+ } else {
+ firstMultiJIDPage_ = new QtUserSearchFirstMultiJIDPage(type_, title.isEmpty() ? firstMultiJIDPage_->title() : title, settings_);
+ connect(firstMultiJIDPage_->addContactButton_, SIGNAL(clicked()), this, SLOT(addContact()));
+ connect(firstMultiJIDPage_->jid_, SIGNAL(textEdited(QString)), this, SLOT(handleContactSuggestionRequested(QString)));
+ firstMultiJIDPage_->jid_->onUserSelected.connect(boost::bind(&QtUserSearchWindow::addSearchedJIDToList, this, _1));
+ connect(firstMultiJIDPage_->addViaSearchButton_, SIGNAL(clicked()), this, SLOT(handleAddViaSearch()));
+ connect(firstMultiJIDPage_->contactList_, SIGNAL(onListChanged(std::vector<Contact::ref>)), this, SLOT(handleListChanged(std::vector<Contact::ref>)));
+ connect(firstMultiJIDPage_->contactList_, SIGNAL(onJIDsAdded(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
+ connect(firstMultiJIDPage_, SIGNAL(onJIDsDropped(std::vector<JID>)), this, SLOT(handleJIDsAdded(std::vector<JID>)));
+ setPage(1, firstMultiJIDPage_);
+ }
}
void QtUserSearchWindow::setSecondPage() {
- if (page(2) != 0) {
- removePage(2);
- }
- fieldsPage_ = new QtUserSearchFieldsPage();
- fieldsPage_->fetchingThrobber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
- fieldsPage_->fetchingThrobber_->movie()->stop();
- setPage(2, fieldsPage_);
+ if (page(2) != 0) {
+ removePage(2);
+ }
+ fieldsPage_ = new QtUserSearchFieldsPage();
+ fieldsPage_->fetchingThrobber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this));
+ fieldsPage_->fetchingThrobber_->movie()->stop();
+ setPage(2, fieldsPage_);
}
void QtUserSearchWindow::setThirdPage() {
- if (page(3) != 0) {
- removePage(3);
- }
- resultsPage_ = new QtUserSearchResultsPage();
+ if (page(3) != 0) {
+ removePage(3);
+ }
+ resultsPage_ = new QtUserSearchResultsPage();
#ifdef SWIFT_PLATFORM_MACOSX
- resultsPage_->results_->setAlternatingRowColors(true);
+ resultsPage_->results_->setAlternatingRowColors(true);
#endif
- if (type_ == AddContact) {
- connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
- }
- else {
- connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
- }
- setPage(3, resultsPage_);
+ if (type_ == AddContact) {
+ connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
+ }
+ else {
+ connect(resultsPage_, SIGNAL(onUserTriggersContinue()), this, SLOT(next()));
+ }
+ setPage(3, resultsPage_);
}
void QtUserSearchWindow::clearForm() {
- fieldsPage_->fetchingThrobber_->show();
- fieldsPage_->fetchingThrobber_->movie()->start();
- fieldsPage_->fetchingLabel_->show();
- QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
- for (int i = 0; i < 8; i++) {
- legacySearchWidgets[i]->hide();
- if (QLineEdit* edit = qobject_cast<QLineEdit*>(legacySearchWidgets[i])) {
- edit->clear();
- }
- }
- fieldsPage_->emitCompletenessCheck();
+ fieldsPage_->fetchingThrobber_->show();
+ fieldsPage_->fetchingThrobber_->movie()->start();
+ fieldsPage_->fetchingLabel_->show();
+ QWidget* legacySearchWidgets[8] = {fieldsPage_->nickInputLabel_, fieldsPage_->nickInput_, fieldsPage_->firstInputLabel_, fieldsPage_->firstInput_, fieldsPage_->lastInputLabel_, fieldsPage_->lastInput_, fieldsPage_->emailInputLabel_, fieldsPage_->emailInput_};
+ for (int i = 0; i < 8; i++) {
+ legacySearchWidgets[i]->hide();
+ if (QLineEdit* edit = qobject_cast<QLineEdit*>(legacySearchWidgets[i])) {
+ edit->clear();
+ }
+ }
+ fieldsPage_->emitCompletenessCheck();
}
void QtUserSearchWindow::clear() {
- QString howText;
- if (type_ == AddContact) {
- firstPage_->errorLabel_->setVisible(false);
- howText = QString(tr("How would you like to find the user to add?"));
- firstPage_->howLabel_->setText(howText);
- firstPage_->byJID_->setChecked(true);
- handleFirstPageRadioChange();
- } else {
- contactVector_.clear();
- firstMultiJIDPage_->contactList_->setList(contactVector_);
- firstMultiJIDPage_->errorLabel_->setVisible(false);
- if (type_ == ChatToContact) {
- howText = QString(tr("List of participants:"));
- } else if (type_ == InviteToChat) {
- howText = QString(tr("Who do you want to invite to the chat?"));
- }
- firstMultiJIDPage_->howLabel_->setText(howText);
- }
- clearForm();
- resultsPage_->results_->setModel(NULL);
- delete model_;
- model_ = NULL;
- restart();
- lastPage_ = 1;
+ QString howText;
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->setVisible(false);
+ howText = QString(tr("How would you like to find the user to add?"));
+ firstPage_->howLabel_->setText(howText);
+ firstPage_->byJID_->setChecked(true);
+ handleFirstPageRadioChange();
+ } else {
+ contactVector_.clear();
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->errorLabel_->setVisible(false);
+ if (type_ == ChatToContact) {
+ howText = QString(tr("List of participants:"));
+ } else if (type_ == InviteToChat) {
+ howText = QString(tr("Who do you want to invite to the chat?"));
+ }
+ firstMultiJIDPage_->howLabel_->setText(howText);
+ }
+ clearForm();
+ resultsPage_->results_->setModel(NULL);
+ delete model_;
+ model_ = NULL;
+ restart();
+ lastPage_ = 1;
}
void QtUserSearchWindow::setError(const QString& error) {
- if (error.isEmpty()) {
- if (type_ == AddContact) {
- firstPage_->errorLabel_->hide();
- } else {
- firstMultiJIDPage_->errorLabel_->hide();
- }
- }
- else {
- if (type_ == AddContact) {
- firstPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
- firstPage_->errorLabel_->show();
- } else {
- firstMultiJIDPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
- firstMultiJIDPage_->errorLabel_->show();
- }
- restart();
- lastPage_ = 1;
- }
+ if (error.isEmpty()) {
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->hide();
+ } else {
+ firstMultiJIDPage_->errorLabel_->hide();
+ }
+ }
+ else {
+ if (type_ == AddContact) {
+ firstPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
+ firstPage_->errorLabel_->show();
+ } else {
+ firstMultiJIDPage_->errorLabel_->setText(QString("<font color='red'>%1</font>").arg(error));
+ firstMultiJIDPage_->errorLabel_->show();
+ }
+ restart();
+ lastPage_ = 1;
+ }
}
void QtUserSearchWindow::setSearchError(bool error) {
- if (error) {
- setError(tr("Error while searching"));
- }
+ if (error) {
+ setError(tr("Error while searching"));
+ }
}
void QtUserSearchWindow::setServerSupportsSearch(bool support) {
- if (!support) {
- setError(tr("This server doesn't support searching for users."));
- }
+ if (!support) {
+ setError(tr("This server doesn't support searching for users."));
+ }
}
}
diff --git a/Swift/QtUI/UserSearch/QtUserSearchWindow.h b/Swift/QtUI/UserSearch/QtUserSearchWindow.h
index 81d6e85..bcef0b9 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.h
@@ -15,92 +15,92 @@
#include <Swift/QtUI/UserSearch/ui_QtUserSearchWizard.h>
namespace Swift {
- class UserSearchModel;
- class UserSearchDelegate;
- class UserSearchResult;
- class UIEventStream;
- class QtUserSearchFirstPage;
- class QtUserSearchFirstMultiJIDPage;
- class QtUserSearchFieldsPage;
- class QtUserSearchResultsPage;
- class QtUserSearchDetailsPage;
- class QtFormResultItemModel;
- class SettingsProvider;
+ class UserSearchModel;
+ class UserSearchDelegate;
+ class UserSearchResult;
+ class UIEventStream;
+ class QtUserSearchFirstPage;
+ class QtUserSearchFirstMultiJIDPage;
+ class QtUserSearchFieldsPage;
+ class QtUserSearchResultsPage;
+ class QtUserSearchDetailsPage;
+ class QtFormResultItemModel;
+ class SettingsProvider;
- class QtUserSearchWindow : public QWizard, public UserSearchWindow, private Ui::QtUserSearchWizard {
- Q_OBJECT
- public:
- QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider);
- virtual ~QtUserSearchWindow();
+ class QtUserSearchWindow : public QWizard, public UserSearchWindow, private Ui::QtUserSearchWizard {
+ Q_OBJECT
+ public:
+ QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider);
+ virtual ~QtUserSearchWindow();
- virtual void addSavedServices(const std::vector<JID>& services);
+ virtual void addSavedServices(const std::vector<JID>& services);
- virtual void clear();
- virtual void show();
- virtual void setResults(const std::vector<UserSearchResult>& results);
- virtual void setResultsForm(Form::ref results);
- virtual void setSelectedService(const JID& jid);
- virtual void setServerSupportsSearch(bool error);
- virtual void setSearchError(bool error);
- virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields);
- virtual void setNameSuggestions(const std::vector<std::string>& suggestions);
- virtual void prepopulateJIDAndName(const JID& jid, const std::string& name);
- virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
- virtual void setJIDs(const std::vector<JID> &jids);
- virtual void setRoomJID(const JID &roomJID);
- virtual std::string getReason() const;
- virtual std::vector<JID> getJIDs() const;
- virtual void setCanStartImpromptuChats(bool supportsImpromptu);
- virtual void updateContacts(const std::vector<Contact::ref> &contacts);
- virtual void addContacts(const std::vector<Contact::ref>& contacts);
- virtual void setCanSupplyDescription(bool allowed);
- virtual void setWarning(const boost::optional<std::string>& message);
+ virtual void clear();
+ virtual void show();
+ virtual void setResults(const std::vector<UserSearchResult>& results);
+ virtual void setResultsForm(Form::ref results);
+ virtual void setSelectedService(const JID& jid);
+ virtual void setServerSupportsSearch(bool error);
+ virtual void setSearchError(bool error);
+ virtual void setSearchFields(boost::shared_ptr<SearchPayload> fields);
+ virtual void setNameSuggestions(const std::vector<std::string>& suggestions);
+ virtual void prepopulateJIDAndName(const JID& jid, const std::string& name);
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions);
+ virtual void setJIDs(const std::vector<JID> &jids);
+ virtual void setRoomJID(const JID &roomJID);
+ virtual std::string getReason() const;
+ virtual std::vector<JID> getJIDs() const;
+ virtual void setCanStartImpromptuChats(bool supportsImpromptu);
+ virtual void updateContacts(const std::vector<Contact::ref> &contacts);
+ virtual void addContacts(const std::vector<Contact::ref>& contacts);
+ virtual void setCanSupplyDescription(bool allowed);
+ virtual void setWarning(const boost::optional<std::string>& message);
- protected:
- virtual int nextId() const;
+ protected:
+ virtual int nextId() const;
- private slots:
- void handleFirstPageRadioChange();
- virtual void handleCurrentChanged(int);
- virtual void handleAccepted();
- void handleContactSuggestionRequested(const QString& text);
- void addContact();
- void handleAddViaSearch();
- void handleListChanged(std::vector<Contact::ref> list);
- void handleJIDsAdded(std::vector<JID> jids);
- void handleJIDEditingDone();
+ private slots:
+ void handleFirstPageRadioChange();
+ virtual void handleCurrentChanged(int);
+ virtual void handleAccepted();
+ void handleContactSuggestionRequested(const QString& text);
+ void addContact();
+ void handleAddViaSearch();
+ void handleListChanged(std::vector<Contact::ref> list);
+ void handleJIDsAdded(std::vector<JID> jids);
+ void handleJIDEditingDone();
- private:
- void setFirstPage(QString title = "");
- void setSecondPage();
- void setThirdPage();
+ private:
+ void setFirstPage(QString title = "");
+ void setSecondPage();
+ void setThirdPage();
- private:
- void clearForm();
- void setError(const QString& error);
- JID getServerToSearch();
- void handleSearch();
- JID getContactJID() const;
- Contact::ref getContact() const;
- void addSearchedJIDToList(const Contact::ref& contact);
- void handleOnSearchedJIDSelected(const Contact::ref& contact);
+ private:
+ void clearForm();
+ void setError(const QString& error);
+ JID getServerToSearch();
+ void handleSearch();
+ JID getContactJID() const;
+ Contact::ref getContact() const;
+ void addSearchedJIDToList(const Contact::ref& contact);
+ void handleOnSearchedJIDSelected(const Contact::ref& contact);
- private:
- UIEventStream* eventStream_;
- UserSearchWindow::Type type_;
- QAbstractItemModel* model_;
- UserSearchDelegate* delegate_;
- QtUserSearchFirstPage* firstPage_;
- QtUserSearchFirstMultiJIDPage* firstMultiJIDPage_;
- QtUserSearchFieldsPage* fieldsPage_;
- QtUserSearchResultsPage* resultsPage_;
- QtUserSearchDetailsPage* detailsPage_;
- JID myServer_;
- JID roomJID_;
- int lastPage_;
- std::vector<Contact::ref> contactVector_;
- SettingsProvider* settings_;
- bool searchNext_;
- bool supportsImpromptu_;
- };
+ private:
+ UIEventStream* eventStream_;
+ UserSearchWindow::Type type_;
+ QAbstractItemModel* model_;
+ UserSearchDelegate* delegate_;
+ QtUserSearchFirstPage* firstPage_;
+ QtUserSearchFirstMultiJIDPage* firstMultiJIDPage_;
+ QtUserSearchFieldsPage* fieldsPage_;
+ QtUserSearchResultsPage* resultsPage_;
+ QtUserSearchDetailsPage* detailsPage_;
+ JID myServer_;
+ JID roomJID_;
+ int lastPage_;
+ std::vector<Contact::ref> contactVector_;
+ SettingsProvider* settings_;
+ bool searchNext_;
+ bool supportsImpromptu_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/UserSearchDelegate.cpp b/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
index 1ac9eb3..8c7ca9a 100644
--- a/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
+++ b/Swift/QtUI/UserSearch/UserSearchDelegate.cpp
@@ -27,44 +27,44 @@ UserSearchDelegate::~UserSearchDelegate() {
}
QSize UserSearchDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const {
- //UserSearchItem* item = static_cast<UserSearchItem*>(index.internalPointer());
- QFontMetrics nameMetrics(common_.nameFont);
- QFontMetrics statusMetrics(common_.detailFont);
- int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
- return QSize(150, sizeByText);
+ //UserSearchItem* item = static_cast<UserSearchItem*>(index.internalPointer());
+ QFontMetrics nameMetrics(common_.nameFont);
+ QFontMetrics statusMetrics(common_.detailFont);
+ int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height();
+ return QSize(150, sizeByText);
}
-void UserSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
- UserSearchResult* item = static_cast<UserSearchResult*>(index.internalPointer());
- painter->save();
- QRect fullRegion(option.rect);
- if (option.state & QStyle::State_Selected) {
- painter->fillRect(fullRegion, option.palette.highlight());
- painter->setPen(option.palette.highlightedText().color());
- }
- else {
- QColor nameColor = UserSearchModel::data(item, Qt::TextColorRole).value<QColor> ();
- painter->setPen(QPen(nameColor));
- }
-
- QFontMetrics nameMetrics(common_.nameFont);
- painter->setFont(common_.nameFont);
- int extraFontWidth = nameMetrics.width("H");
- int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
- QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
-
- int nameHeight = nameMetrics.height() + common_.verticalMargin;
- QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
-
- painter->drawText(nameRegion, Qt::AlignTop, UserSearchModel::data(item, Qt::DisplayRole).toString());
-
- painter->setFont(common_.detailFont);
- painter->setPen(QPen(QColor(160, 160, 160)));
-
- QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
- painter->drawText(detailRegion, Qt::AlignTop, UserSearchModel::data(item, UserSearchModel::DetailTextRole).toString());
-
- painter->restore();
+void UserSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
+ UserSearchResult* item = static_cast<UserSearchResult*>(index.internalPointer());
+ painter->save();
+ QRect fullRegion(option.rect);
+ if (option.state & QStyle::State_Selected) {
+ painter->fillRect(fullRegion, option.palette.highlight());
+ painter->setPen(option.palette.highlightedText().color());
+ }
+ else {
+ QColor nameColor = UserSearchModel::data(item, Qt::TextColorRole).value<QColor> ();
+ painter->setPen(QPen(nameColor));
+ }
+
+ QFontMetrics nameMetrics(common_.nameFont);
+ painter->setFont(common_.nameFont);
+ int extraFontWidth = nameMetrics.width("H");
+ int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2;
+ QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0));
+
+ int nameHeight = nameMetrics.height() + common_.verticalMargin;
+ QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0));
+
+ painter->drawText(nameRegion, Qt::AlignTop, UserSearchModel::data(item, Qt::DisplayRole).toString());
+
+ painter->setFont(common_.detailFont);
+ painter->setPen(QPen(QColor(160, 160, 160)));
+
+ QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0));
+ painter->drawText(detailRegion, Qt::AlignTop, UserSearchModel::data(item, UserSearchModel::DetailTextRole).toString());
+
+ painter->restore();
}
}
diff --git a/Swift/QtUI/UserSearch/UserSearchDelegate.h b/Swift/QtUI/UserSearch/UserSearchDelegate.h
index 92fa0e8..8234689 100644
--- a/Swift/QtUI/UserSearch/UserSearchDelegate.h
+++ b/Swift/QtUI/UserSearch/UserSearchDelegate.h
@@ -13,18 +13,18 @@
#include <Swift/QtUI/Roster/DelegateCommons.h>
namespace Swift {
- class UserSearchDelegate : public QStyledItemDelegate {
- Q_OBJECT
-
- public:
- UserSearchDelegate(QObject* parent = 0);
- virtual ~UserSearchDelegate();
-
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
- QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const;
- private:
- DelegateCommons common_;
- };
+ class UserSearchDelegate : public QStyledItemDelegate {
+ Q_OBJECT
+
+ public:
+ UserSearchDelegate(QObject* parent = 0);
+ virtual ~UserSearchDelegate();
+
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+ QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const;
+ private:
+ DelegateCommons common_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/UserSearchModel.cpp b/Swift/QtUI/UserSearch/UserSearchModel.cpp
index ba6ede3..b6ac3cf 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.cpp
+++ b/Swift/QtUI/UserSearch/UserSearchModel.cpp
@@ -14,76 +14,76 @@ UserSearchModel::UserSearchModel() {
}
void UserSearchModel::clear() {
- emit layoutAboutToBeChanged();
- results_.clear();
- emit layoutChanged();
+ emit layoutAboutToBeChanged();
+ results_.clear();
+ emit layoutChanged();
}
void UserSearchModel::setResults(const std::vector<UserSearchResult>& results) {
- clear();
- emit layoutAboutToBeChanged();
- results_ = results;
- emit layoutChanged();
+ clear();
+ emit layoutAboutToBeChanged();
+ results_ = results;
+ emit layoutChanged();
}
int UserSearchModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ return 1;
}
QVariant UserSearchModel::data(const QModelIndex& index, int role) const {
- if (!index.isValid()) return QVariant();
- UserSearchResult* result = static_cast<UserSearchResult*>(index.internalPointer());
- return data(result, role);
+ if (!index.isValid()) return QVariant();
+ UserSearchResult* result = static_cast<UserSearchResult*>(index.internalPointer());
+ return data(result, role);
}
QVariant UserSearchModel::data(UserSearchResult* item, int role) {
- switch (role) {
- case Qt::DisplayRole: return QVariant(nameLine(item));
- case DetailTextRole: return QVariant(detailLine(item));
- default: return QVariant();
- }
+ switch (role) {
+ case Qt::DisplayRole: return QVariant(nameLine(item));
+ case DetailTextRole: return QVariant(detailLine(item));
+ default: return QVariant();
+ }
}
QString UserSearchModel::nameLine(UserSearchResult* item) {
- QString result;
- const std::map<std::string, std::string> fields = item->getFields();
- std::map<std::string, std::string>::const_iterator first = fields.find("first");
- if (first != fields.end()) {
- result += P2QSTRING((*first).second);
- }
- std::map<std::string, std::string>::const_iterator last = fields.find("last");
- if (last != fields.end()) {
- if (!result.isEmpty()) {
- result += " ";
- }
- result += P2QSTRING((*last).second);
- }
- if (result.isEmpty()) {
- result = P2QSTRING(item->getJID().toString());
- }
- return result;
+ QString result;
+ const std::map<std::string, std::string> fields = item->getFields();
+ std::map<std::string, std::string>::const_iterator first = fields.find("first");
+ if (first != fields.end()) {
+ result += P2QSTRING((*first).second);
+ }
+ std::map<std::string, std::string>::const_iterator last = fields.find("last");
+ if (last != fields.end()) {
+ if (!result.isEmpty()) {
+ result += " ";
+ }
+ result += P2QSTRING((*last).second);
+ }
+ if (result.isEmpty()) {
+ result = P2QSTRING(item->getJID().toString());
+ }
+ return result;
}
QString UserSearchModel::detailLine(UserSearchResult* item) {
- return P2QSTRING(item->getJID().toString());
+ return P2QSTRING(item->getJID().toString());
}
QModelIndex UserSearchModel::index(int row, int column, const QModelIndex & parent) const {
- if (!hasIndex(row, column, parent)) {
- return QModelIndex();
- }
- return row < static_cast<int>(results_.size()) ? createIndex(row, column, reinterpret_cast<void*>(const_cast<UserSearchResult*>(&(results_[row])))) : QModelIndex();
+ if (!hasIndex(row, column, parent)) {
+ return QModelIndex();
+ }
+ return row < static_cast<int>(results_.size()) ? createIndex(row, column, reinterpret_cast<void*>(const_cast<UserSearchResult*>(&(results_[row])))) : QModelIndex();
}
QModelIndex UserSearchModel::parent(const QModelIndex& /*index*/) const {
- return QModelIndex();
+ return QModelIndex();
}
int UserSearchModel::rowCount(const QModelIndex& parentIndex) const {
- if (!parentIndex.isValid()) {
- return results_.size();
- }
- return 0;
+ if (!parentIndex.isValid()) {
+ return results_.size();
+ }
+ return 0;
}
}
diff --git a/Swift/QtUI/UserSearch/UserSearchModel.h b/Swift/QtUI/UserSearch/UserSearchModel.h
index db3ef3a..0a57b28 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.h
+++ b/Swift/QtUI/UserSearch/UserSearchModel.h
@@ -14,28 +14,28 @@
#include <Swift/Controllers/Chat/UserSearchController.h>
namespace Swift {
- class UserSearchModel : public QAbstractItemModel {
- Q_OBJECT
- public:
- enum UserItemRoles {
- DetailTextRole = Qt::UserRole/*,
- AvatarRole = Qt::UserRole + 1,
- PresenceIconRole = Qt::UserRole + 2,
- StatusShowTypeRole = Qt::UserRole + 3*/
- };
- UserSearchModel();
- void clear();
- void setResults(const std::vector<UserSearchResult>& results);
- int columnCount(const QModelIndex& parent = QModelIndex()) const;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- static QVariant data(UserSearchResult* item, int role);
- QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex& index) const;
- int rowCount(const QModelIndex& parent = QModelIndex()) const;
- private:
- static QString nameLine(UserSearchResult* item);
- static QString detailLine(UserSearchResult* item);
- std::vector<UserSearchResult> results_;
- };
+ class UserSearchModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ enum UserItemRoles {
+ DetailTextRole = Qt::UserRole/*,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2,
+ StatusShowTypeRole = Qt::UserRole + 3*/
+ };
+ UserSearchModel();
+ void clear();
+ void setResults(const std::vector<UserSearchResult>& results);
+ int columnCount(const QModelIndex& parent = QModelIndex()) const;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ static QVariant data(UserSearchResult* item, int role);
+ QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex& index) const;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const;
+ private:
+ static QString nameLine(UserSearchResult* item);
+ static QString detailLine(UserSearchResult* item);
+ std::vector<UserSearchResult> results_;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/ColorWidget.cpp b/Swift/QtUI/Whiteboard/ColorWidget.cpp
index e12ade1..7669ecc 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.cpp
+++ b/Swift/QtUI/Whiteboard/ColorWidget.cpp
@@ -17,28 +17,28 @@
#include <QPainter>
namespace Swift {
- ColorWidget::ColorWidget(QWidget* parent) : QWidget(parent) {
- setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
- }
-
- QSize ColorWidget::sizeHint() const {
- return QSize(20, 20);
- }
-
- void ColorWidget::setColor(QColor color) {
- this->color = color;
- update();
- }
-
- void ColorWidget::paintEvent(QPaintEvent* /*event*/) {
- QPainter painter(this);
- painter.fillRect(0, 0, 20, 20, color);
- }
-
- void ColorWidget::mouseReleaseEvent(QMouseEvent* event) {
- if (event->button() == Qt::LeftButton) {
- emit clicked();
- }
- }
+ ColorWidget::ColorWidget(QWidget* parent) : QWidget(parent) {
+ setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+ }
+
+ QSize ColorWidget::sizeHint() const {
+ return QSize(20, 20);
+ }
+
+ void ColorWidget::setColor(QColor color) {
+ this->color = color;
+ update();
+ }
+
+ void ColorWidget::paintEvent(QPaintEvent* /*event*/) {
+ QPainter painter(this);
+ painter.fillRect(0, 0, 20, 20, color);
+ }
+
+ void ColorWidget::mouseReleaseEvent(QMouseEvent* event) {
+ if (event->button() == Qt::LeftButton) {
+ emit clicked();
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/ColorWidget.h b/Swift/QtUI/Whiteboard/ColorWidget.h
index ae1af0f..18dc73f 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.h
+++ b/Swift/QtUI/Whiteboard/ColorWidget.h
@@ -9,25 +9,25 @@
#include <QWidget>
namespace Swift {
- class ColorWidget : public QWidget {
- Q_OBJECT
- public:
- ColorWidget(QWidget* parent = 0);
- QSize sizeHint() const;
+ class ColorWidget : public QWidget {
+ Q_OBJECT
+ public:
+ ColorWidget(QWidget* parent = 0);
+ QSize sizeHint() const;
- public slots:
- void setColor(QColor color);
+ public slots:
+ void setColor(QColor color);
- private:
- QColor color;
+ private:
+ QColor color;
- protected:
- void paintEvent(QPaintEvent* /*event*/);
- void mouseReleaseEvent(QMouseEvent* event);
+ protected:
+ void paintEvent(QPaintEvent* /*event*/);
+ void mouseReleaseEvent(QMouseEvent* event);
- signals:
- void clicked();
+ signals:
+ void clicked();
- };
+ };
}
diff --git a/Swift/QtUI/Whiteboard/FreehandLineItem.cpp b/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
index f4808d6..4ac93b8 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
@@ -13,90 +13,90 @@
#include <Swift/QtUI/Whiteboard/FreehandLineItem.h>
namespace Swift {
- FreehandLineItem::FreehandLineItem(QGraphicsItem* parent) : QGraphicsItem(parent) {
- }
+ FreehandLineItem::FreehandLineItem(QGraphicsItem* parent) : QGraphicsItem(parent) {
+ }
- QRectF FreehandLineItem::boundingRect() const
- {
- return boundRect;
- }
+ QRectF FreehandLineItem::boundingRect() const
+ {
+ return boundRect;
+ }
- void FreehandLineItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
- {
- painter->setPen(pen_);
- if (points_.size() > 0) {
- QVector<QPointF>::const_iterator it = points_.begin();
- QPointF previous = *it;
- ++it;
- for (; it != points_.end(); ++it) {
- painter->drawLine(previous, *it);
- previous = *it;
- }
- }
- }
+ void FreehandLineItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
+ {
+ painter->setPen(pen_);
+ if (points_.size() > 0) {
+ QVector<QPointF>::const_iterator it = points_.begin();
+ QPointF previous = *it;
+ ++it;
+ for (; it != points_.end(); ++it) {
+ painter->drawLine(previous, *it);
+ previous = *it;
+ }
+ }
+ }
- void FreehandLineItem::setStartPoint(QPointF point)
- {
- points_.clear();
- points_.append(point);
- QRectF rect(point, point);
- prepareGeometryChange();
- boundRect = rect;
- }
+ void FreehandLineItem::setStartPoint(QPointF point)
+ {
+ points_.clear();
+ points_.append(point);
+ QRectF rect(point, point);
+ prepareGeometryChange();
+ boundRect = rect;
+ }
- void FreehandLineItem::lineTo(QPointF point)
- {
- qreal x1, x2, y1, y2;
- x1 = points_.last().x();
- x2 = point.x();
- y1 = points_.last().y();
- y2 = point.y();
- if (x1 > x2) {
- qreal temp = x1;
- x1 = x2;
- x2 = temp;
- }
- if (y1 > y2) {
- qreal temp = y1;
- y1 = y2;
- y2 = temp;
- }
- QRectF rect(x1-1, y1-1, x2+1-x1, y2+1-y1);
+ void FreehandLineItem::lineTo(QPointF point)
+ {
+ qreal x1, x2, y1, y2;
+ x1 = points_.last().x();
+ x2 = point.x();
+ y1 = points_.last().y();
+ y2 = point.y();
+ if (x1 > x2) {
+ qreal temp = x1;
+ x1 = x2;
+ x2 = temp;
+ }
+ if (y1 > y2) {
+ qreal temp = y1;
+ y1 = y2;
+ y2 = temp;
+ }
+ QRectF rect(x1-1, y1-1, x2+1-x1, y2+1-y1);
- points_.append(point);
+ points_.append(point);
- prepareGeometryChange();
- boundRect |= rect;
- }
+ prepareGeometryChange();
+ boundRect |= rect;
+ }
- bool FreehandLineItem::collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/) const
- {
- QVector<QPointF>::const_iterator it;
- QSizeF size(1,1);
- for (it = points_.begin(); it != points_.end(); ++it) {
- if (path.intersects(QRectF(*it, size))) {
- return true;
- }
- }
- return false;
- }
+ bool FreehandLineItem::collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/) const
+ {
+ QVector<QPointF>::const_iterator it;
+ QSizeF size(1,1);
+ for (it = points_.begin(); it != points_.end(); ++it) {
+ if (path.intersects(QRectF(*it, size))) {
+ return true;
+ }
+ }
+ return false;
+ }
- void FreehandLineItem::setPen(const QPen& pen)
- {
- pen_ = pen;
- update(boundRect);
- }
+ void FreehandLineItem::setPen(const QPen& pen)
+ {
+ pen_ = pen;
+ update(boundRect);
+ }
- QPen FreehandLineItem::pen() const
- {
- return pen_;
- }
+ QPen FreehandLineItem::pen() const
+ {
+ return pen_;
+ }
- const QVector<QPointF>& FreehandLineItem::points() const {
- return points_;
- }
+ const QVector<QPointF>& FreehandLineItem::points() const {
+ return points_;
+ }
- int FreehandLineItem::type() const {
- return Type;
- }
+ int FreehandLineItem::type() const {
+ return Type;
+ }
}
diff --git a/Swift/QtUI/Whiteboard/FreehandLineItem.h b/Swift/QtUI/Whiteboard/FreehandLineItem.h
index db37460..a2dab34 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.h
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.h
@@ -18,23 +18,23 @@
#include <QPainter>
namespace Swift {
- class FreehandLineItem : public QGraphicsItem {
- public:
- enum {Type = UserType + 1};
- FreehandLineItem(QGraphicsItem* parent = 0);
- QRectF boundingRect() const;
- void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/ = 0);
- void setStartPoint(QPointF point);
- void lineTo(QPointF point);
- bool collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/ = Qt::IntersectsItemShape) const;
- void setPen(const QPen& pen);
- QPen pen() const;
- const QVector<QPointF>& points() const;
- int type() const;
+ class FreehandLineItem : public QGraphicsItem {
+ public:
+ enum {Type = UserType + 1};
+ FreehandLineItem(QGraphicsItem* parent = 0);
+ QRectF boundingRect() const;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/ = 0);
+ void setStartPoint(QPointF point);
+ void lineTo(QPointF point);
+ bool collidesWithPath(const QPainterPath& path, Qt::ItemSelectionMode /*mode*/ = Qt::IntersectsItemShape) const;
+ void setPen(const QPen& pen);
+ QPen pen() const;
+ const QVector<QPointF>& points() const;
+ int type() const;
- private:
- QPen pen_;
- QVector<QPointF> points_;
- QRectF boundRect;
- };
+ private:
+ QPen pen_;
+ QVector<QPointF> points_;
+ QRectF boundRect;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/GView.cpp b/Swift/QtUI/Whiteboard/GView.cpp
index 9134d58..4deaaf6 100644
--- a/Swift/QtUI/Whiteboard/GView.cpp
+++ b/Swift/QtUI/Whiteboard/GView.cpp
@@ -15,489 +15,489 @@
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
- GView::GView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent), zValue(0), mousePressed(false), brush(QColor(Qt::white)), defaultBrush(QColor(Qt::white)), mode(GView::Select), lastItem(NULL), selectionRect(NULL), textDialog(NULL) {
- }
-
- void GView::setLineWidth(int i) {
- pen.setWidth(i);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultPen.setWidth(i);
- }
- }
-
- void GView::setLineColor(QColor color) {
- pen.setColor(color);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultPen.setColor(color);
- }
- lineColorChanged(color);
- }
-
- QColor GView::getLineColor() {
- return pen.color();
- }
-
- void GView::setBrushColor(QColor color) {
- brush.setColor(color);
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- } else {
- defaultBrush.setColor(color);
- }
- brushColorChanged(color);
- }
-
- QColor GView::getBrushColor() {
- return brush.color();
- }
-
- void GView::setMode(Mode mode) {
- this->mode = mode;
- lastItem = 0;
- deselect();
- }
-
- void GView::addItem(QGraphicsItem* item, QString id, int pos) {
- itemsMap_.insert(id, item);
- if (pos > items_.size()) {
- item->setZValue(zValue++);
- scene()->addItem(item);
- items_.append(item);
- } else {
- QGraphicsItem* temp = items_.at(pos-1);
- item->setZValue(temp->zValue());
- scene()->addItem(item);
- item->stackBefore(temp);
- items_.insert(pos-1, item);
- }
- }
-
- void GView::clear() {
- scene()->clear();
- items_.clear();
- itemsMap_.clear();
- lastItem = 0;
- selectionRect = 0;
- brush = QBrush(QColor(Qt::white));
- defaultBrush = QBrush(QColor(Qt::white));
- pen = QPen();
- pen.setWidth(1);
- defaultPen = pen;
- lineWidthChanged(1);
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- QGraphicsItem* GView::getItem(QString id) {
- return itemsMap_.value(id);
- }
-
- void GView::deleteItem(QString id) {
- deselect(id);
- QGraphicsItem* item = itemsMap_.value(id);
- items_.removeOne(item);
- itemsMap_.remove(id);
- scene()->removeItem(item);
- delete item;
- }
-
- QString GView::getNewID() {
- return P2QSTRING(idGenerator.generateID());
- }
-
- void GView::mouseMoveEvent(QMouseEvent* event)
- {
- if (!mousePressed) {
- return;
- }
-
- if (mode == Line) {
- QGraphicsLineItem* item = qgraphicsitem_cast<QGraphicsLineItem*>(lastItem);
- if(item != 0) {
- QLineF line = item->line();
- line.setP1(this->mapToScene(event->pos()));
- item->setLine(line);
-
- }
- }
- else if (mode == Rect) {
- QGraphicsRectItem* item = qgraphicsitem_cast<QGraphicsRectItem*>(lastItem);
- if (item != 0) {
- QPointF beginPoint = item->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- QRectF rect = item->rect();
- if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopLeft(beginPoint);
- rect.setBottomRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopRight(beginPoint);
- rect.setBottomLeft(newPoint);
- }
- else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomLeft(beginPoint);
- rect.setTopRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomRight(beginPoint);
- rect.setTopLeft(newPoint);
- }
- item->setRect(rect);
- }
- }
- else if (mode == Circle) {
- QGraphicsEllipseItem* item = qgraphicsitem_cast<QGraphicsEllipseItem*>(lastItem);
- QPainterPath path;
- QPointF beginPoint = item->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- QRectF rect = item->rect();
- if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopLeft(beginPoint);
- rect.setBottomRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
- rect.setTopRight(beginPoint);
- rect.setBottomLeft(newPoint);
- }
- else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomLeft(beginPoint);
- rect.setTopRight(newPoint);
- }
- else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
- rect.setBottomRight(beginPoint);
- rect.setTopLeft(newPoint);
- }
-
- item->setRect(rect);
- }
- else if (mode == HandLine) {
- FreehandLineItem* item = qgraphicsitem_cast<FreehandLineItem*>(lastItem);
- if (item != 0) {
- QPointF newPoint = this->mapToScene(event->pos());
- item->lineTo(newPoint);
- }
- }
- else if (mode == Polygon) {
- QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(lastItem);
- QPointF newPoint = this->mapToScene(event->pos());
- QPolygonF polygon = item->polygon();
- polygon.erase(polygon.end()-1);
- polygon.append(newPoint);
- item->setPolygon(polygon);
- }
- else if (mode == Select) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- if (item != 0) {
- QPainterPath path;
- QPointF beginPoint = selectionRect->data(0).toPointF();
- QPointF newPoint = this->mapToScene(event->pos());
- item->setPos(beginPoint + newPoint);
- selectionRect->setPos(beginPoint + newPoint);
- }
- }
- }
-
- void GView::mousePressEvent(QMouseEvent *event)
- {
- mousePressed = true;
- deselect();
- if (mode == Line) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsItem* item = scene()->addLine(point.x(), point.y(), point.x(), point.y(), pen);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == Rect) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsRectItem* item = scene()->addRect(point.x(), point.y(), 0, 0, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(0, point);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == Rubber) {
- QPointF point = this->mapToScene(event->pos());
- int w = pen.width();
- QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
- QList<QGraphicsItem*> list = scene()->items(rect);
- if (!list.isEmpty())
- {
- QGraphicsItem* item = scene()->items(rect).first();
- QString id = item->data(100).toString();
- int pos = items_.indexOf(item)+1;
- itemDeleted(id, pos);
- deleteItem(id);
- }
- }
- else if (mode == Circle) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsEllipseItem* item = scene()->addEllipse(point.x(), point.y(), 0, 0, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(0, point);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else if (mode == HandLine) {
- QPointF point = this->mapToScene(event->pos());
- FreehandLineItem* item = new FreehandLineItem;
- QString id = getNewID();
- item->setPen(pen);
- item->setStartPoint(point);
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- scene()->addItem(item);
- lastItem = item;
- }
- else if (mode == Text) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsTextItem* item = scene()->addText("");
- QString id = getNewID();
- item->setData(100, id);
- item->setData(101, items_.size());
- item->setDefaultTextColor(pen.color());
- textDialog = new TextDialog(item, this);
- connect(textDialog, SIGNAL(accepted(QGraphicsTextItem*)), this, SLOT(handleTextItemModified(QGraphicsTextItem*)));
- textDialog->setAttribute(Qt::WA_DeleteOnClose);
- textDialog->show();
- item->setPos(point);
- lastItem = item;
- }
- else if (mode == Polygon) {
- QPointF point = this->mapToScene(event->pos());
- QGraphicsPolygonItem* item = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
- if (item == 0) {
- QPolygonF polygon;
- polygon.append(point);
- polygon.append(point);
- item = scene()->addPolygon(polygon, pen, brush);
- QString id = getNewID();
- item->setZValue(10000000);
- item->setData(100, id);
- item->setData(101, items_.size());
- lastItem = item;
- }
- else {
- QPolygonF polygon;
- polygon = item->polygon();
- polygon.append(point);
- item->setPolygon(polygon);
- }
- }
- else if (mode == Select) {
- QPointF point = this->mapToScene(event->pos());
- int w = pen.width();
- if (w == 0) {
- w = 1;
- }
- QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
- QList<QGraphicsItem*> list = scene()->items(rect);
- if (!list.isEmpty()) {
- QPen pen;
- pen.setColor(QColor(Qt::gray));
- pen.setStyle(Qt::DashLine);
- QGraphicsItem *item = scene()->items(rect).first();
- selectionRect = scene()->addRect(item->boundingRect(), pen);
- selectionRect->setZValue(1000000);
- selectionRect->setData(0, item->pos()-point);
- selectionRect->setPos(item->pos());
- QVariant var(QVariant::UserType);
- var.setValue(item);
- selectionRect->setData(1, var);
- setActualPenAndBrushFromItem(item);
- }
- }
- }
-
- void GView::mouseReleaseEvent(QMouseEvent* /*event*/)
- {
- mousePressed = false;
- QGraphicsPolygonItem* polygon = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
- if (polygon && polygon->polygon().size() >= 3) {
- lastItemChanged(polygon, items_.indexOf(polygon)+1, Update);
- } else if (lastItem) {
- zValue++;
- lastItem->setZValue(zValue++);
- items_.append(lastItem);
- itemsMap_.insert(lastItem->data(100).toString(), lastItem);
-
- lastItemChanged(lastItem, items_.size(), New);
- } else if (selectionRect){
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- lastItemChanged(item, items_.indexOf(item)+1, Update);
- }
- }
-
-
- void GView::handleTextItemModified(QGraphicsTextItem* item) {
- lastItemChanged(item, item->data(101).toInt(), Update);
- }
-
- void GView::moveUpSelectedItem()
- {
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- int pos = items_.indexOf(item);
- if (pos < items_.size()-1) {
- lastItemChanged(item, pos+1, MoveUp);
- move(item, pos+2);
- }
- }
- }
-
- void GView::moveDownSelectedItem()
- {
- if (selectionRect) {
- QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
- int pos = items_.indexOf(item);
- if (pos > 0) {
- lastItemChanged(item, pos+1, MoveDown);
- move(item, pos);
- }
- }
- }
-
- void GView::move(QGraphicsItem* item, int npos) {
- int pos = items_.indexOf(item);
- QGraphicsItem* itemAfter = NULL;
- if (npos-1 > pos) {
- if (npos == items_.size()) {
- item->setZValue(zValue++);
- } else {
- itemAfter = items_.at(npos);
- }
-
- items_.insert(npos, item);
- items_.removeAt(pos);
- } else if (npos-1 < pos) {
- itemAfter = items_.at(npos-1);
- items_.insert(npos-1, item);
- items_.removeAt(pos+1);
- }
- if (itemAfter) {
- item->setZValue(itemAfter->zValue());
- item->stackBefore(itemAfter);
- }
- }
-
- void GView::changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush) {
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem) {
- lineItem->setPen(pen);
- }
-
- FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (handLineItem) {
- handLineItem->setPen(pen);
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem) {
- rectItem->setPen(pen);
- rectItem->setBrush(brush);
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem) {
- textItem->setDefaultTextColor(pen.color());
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- polygonItem->setPen(pen);
- polygonItem->setBrush(brush);
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- ellipseItem->setPen(pen);
- ellipseItem->setBrush(brush);
- }
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- void GView::setActualPenAndBrushFromItem(QGraphicsItem* item) {
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem) {
- pen = lineItem->pen();
- }
-
- FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (handLineItem) {
- pen = handLineItem->pen();
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem) {
- pen = rectItem->pen();
- brush = rectItem->brush();
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem) {
- pen.setColor(textItem->defaultTextColor());
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- pen = polygonItem->pen();
- brush = polygonItem->brush();
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- pen = ellipseItem->pen();
- brush = ellipseItem->brush();
- }
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
-
- void GView::deselect() {
- if (selectionRect != 0) {
- pen = defaultPen;
- brush = defaultBrush;
- scene()->removeItem(selectionRect);
- delete selectionRect;
- selectionRect = 0;
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
- }
-
- void GView::deselect(QString id) {
- if (selectionRect != 0) {
- QGraphicsItem* item = getItem(id);
- if (item && selectionRect->data(1).value<QGraphicsItem*>() == item) {
- pen = defaultPen;
- brush = defaultBrush;
- scene()->removeItem(selectionRect);
- delete selectionRect;
- selectionRect = 0;
- lineWidthChanged(pen.width());
- lineColorChanged(pen.color());
- brushColorChanged(brush.color());
- }
- }
- }
+ GView::GView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent), zValue(0), mousePressed(false), brush(QColor(Qt::white)), defaultBrush(QColor(Qt::white)), mode(GView::Select), lastItem(NULL), selectionRect(NULL), textDialog(NULL) {
+ }
+
+ void GView::setLineWidth(int i) {
+ pen.setWidth(i);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultPen.setWidth(i);
+ }
+ }
+
+ void GView::setLineColor(QColor color) {
+ pen.setColor(color);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultPen.setColor(color);
+ }
+ lineColorChanged(color);
+ }
+
+ QColor GView::getLineColor() {
+ return pen.color();
+ }
+
+ void GView::setBrushColor(QColor color) {
+ brush.setColor(color);
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ changePenAndBrush(selectionRect->data(1).value<QGraphicsItem*>(), pen, brush);
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ } else {
+ defaultBrush.setColor(color);
+ }
+ brushColorChanged(color);
+ }
+
+ QColor GView::getBrushColor() {
+ return brush.color();
+ }
+
+ void GView::setMode(Mode mode) {
+ this->mode = mode;
+ lastItem = 0;
+ deselect();
+ }
+
+ void GView::addItem(QGraphicsItem* item, QString id, int pos) {
+ itemsMap_.insert(id, item);
+ if (pos > items_.size()) {
+ item->setZValue(zValue++);
+ scene()->addItem(item);
+ items_.append(item);
+ } else {
+ QGraphicsItem* temp = items_.at(pos-1);
+ item->setZValue(temp->zValue());
+ scene()->addItem(item);
+ item->stackBefore(temp);
+ items_.insert(pos-1, item);
+ }
+ }
+
+ void GView::clear() {
+ scene()->clear();
+ items_.clear();
+ itemsMap_.clear();
+ lastItem = 0;
+ selectionRect = 0;
+ brush = QBrush(QColor(Qt::white));
+ defaultBrush = QBrush(QColor(Qt::white));
+ pen = QPen();
+ pen.setWidth(1);
+ defaultPen = pen;
+ lineWidthChanged(1);
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ QGraphicsItem* GView::getItem(QString id) {
+ return itemsMap_.value(id);
+ }
+
+ void GView::deleteItem(QString id) {
+ deselect(id);
+ QGraphicsItem* item = itemsMap_.value(id);
+ items_.removeOne(item);
+ itemsMap_.remove(id);
+ scene()->removeItem(item);
+ delete item;
+ }
+
+ QString GView::getNewID() {
+ return P2QSTRING(idGenerator.generateID());
+ }
+
+ void GView::mouseMoveEvent(QMouseEvent* event)
+ {
+ if (!mousePressed) {
+ return;
+ }
+
+ if (mode == Line) {
+ QGraphicsLineItem* item = qgraphicsitem_cast<QGraphicsLineItem*>(lastItem);
+ if(item != 0) {
+ QLineF line = item->line();
+ line.setP1(this->mapToScene(event->pos()));
+ item->setLine(line);
+
+ }
+ }
+ else if (mode == Rect) {
+ QGraphicsRectItem* item = qgraphicsitem_cast<QGraphicsRectItem*>(lastItem);
+ if (item != 0) {
+ QPointF beginPoint = item->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ QRectF rect = item->rect();
+ if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopLeft(beginPoint);
+ rect.setBottomRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopRight(beginPoint);
+ rect.setBottomLeft(newPoint);
+ }
+ else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomLeft(beginPoint);
+ rect.setTopRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomRight(beginPoint);
+ rect.setTopLeft(newPoint);
+ }
+ item->setRect(rect);
+ }
+ }
+ else if (mode == Circle) {
+ QGraphicsEllipseItem* item = qgraphicsitem_cast<QGraphicsEllipseItem*>(lastItem);
+ QPainterPath path;
+ QPointF beginPoint = item->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ QRectF rect = item->rect();
+ if (beginPoint.x() <= newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopLeft(beginPoint);
+ rect.setBottomRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() <= newPoint.y()) {
+ rect.setTopRight(beginPoint);
+ rect.setBottomLeft(newPoint);
+ }
+ else if (beginPoint.x() <= newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomLeft(beginPoint);
+ rect.setTopRight(newPoint);
+ }
+ else if (beginPoint.x() > newPoint.x() && beginPoint.y() > newPoint.y()) {
+ rect.setBottomRight(beginPoint);
+ rect.setTopLeft(newPoint);
+ }
+
+ item->setRect(rect);
+ }
+ else if (mode == HandLine) {
+ FreehandLineItem* item = qgraphicsitem_cast<FreehandLineItem*>(lastItem);
+ if (item != 0) {
+ QPointF newPoint = this->mapToScene(event->pos());
+ item->lineTo(newPoint);
+ }
+ }
+ else if (mode == Polygon) {
+ QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(lastItem);
+ QPointF newPoint = this->mapToScene(event->pos());
+ QPolygonF polygon = item->polygon();
+ polygon.erase(polygon.end()-1);
+ polygon.append(newPoint);
+ item->setPolygon(polygon);
+ }
+ else if (mode == Select) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ if (item != 0) {
+ QPainterPath path;
+ QPointF beginPoint = selectionRect->data(0).toPointF();
+ QPointF newPoint = this->mapToScene(event->pos());
+ item->setPos(beginPoint + newPoint);
+ selectionRect->setPos(beginPoint + newPoint);
+ }
+ }
+ }
+
+ void GView::mousePressEvent(QMouseEvent *event)
+ {
+ mousePressed = true;
+ deselect();
+ if (mode == Line) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsItem* item = scene()->addLine(point.x(), point.y(), point.x(), point.y(), pen);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == Rect) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsRectItem* item = scene()->addRect(point.x(), point.y(), 0, 0, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(0, point);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == Rubber) {
+ QPointF point = this->mapToScene(event->pos());
+ int w = pen.width();
+ QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
+ QList<QGraphicsItem*> list = scene()->items(rect);
+ if (!list.isEmpty())
+ {
+ QGraphicsItem* item = scene()->items(rect).first();
+ QString id = item->data(100).toString();
+ int pos = items_.indexOf(item)+1;
+ itemDeleted(id, pos);
+ deleteItem(id);
+ }
+ }
+ else if (mode == Circle) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsEllipseItem* item = scene()->addEllipse(point.x(), point.y(), 0, 0, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(0, point);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else if (mode == HandLine) {
+ QPointF point = this->mapToScene(event->pos());
+ FreehandLineItem* item = new FreehandLineItem;
+ QString id = getNewID();
+ item->setPen(pen);
+ item->setStartPoint(point);
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ scene()->addItem(item);
+ lastItem = item;
+ }
+ else if (mode == Text) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsTextItem* item = scene()->addText("");
+ QString id = getNewID();
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ item->setDefaultTextColor(pen.color());
+ textDialog = new TextDialog(item, this);
+ connect(textDialog, SIGNAL(accepted(QGraphicsTextItem*)), this, SLOT(handleTextItemModified(QGraphicsTextItem*)));
+ textDialog->setAttribute(Qt::WA_DeleteOnClose);
+ textDialog->show();
+ item->setPos(point);
+ lastItem = item;
+ }
+ else if (mode == Polygon) {
+ QPointF point = this->mapToScene(event->pos());
+ QGraphicsPolygonItem* item = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
+ if (item == 0) {
+ QPolygonF polygon;
+ polygon.append(point);
+ polygon.append(point);
+ item = scene()->addPolygon(polygon, pen, brush);
+ QString id = getNewID();
+ item->setZValue(10000000);
+ item->setData(100, id);
+ item->setData(101, items_.size());
+ lastItem = item;
+ }
+ else {
+ QPolygonF polygon;
+ polygon = item->polygon();
+ polygon.append(point);
+ item->setPolygon(polygon);
+ }
+ }
+ else if (mode == Select) {
+ QPointF point = this->mapToScene(event->pos());
+ int w = pen.width();
+ if (w == 0) {
+ w = 1;
+ }
+ QRectF rect(point.x()-w, point.y()-w, w*2, w*2);
+ QList<QGraphicsItem*> list = scene()->items(rect);
+ if (!list.isEmpty()) {
+ QPen pen;
+ pen.setColor(QColor(Qt::gray));
+ pen.setStyle(Qt::DashLine);
+ QGraphicsItem *item = scene()->items(rect).first();
+ selectionRect = scene()->addRect(item->boundingRect(), pen);
+ selectionRect->setZValue(1000000);
+ selectionRect->setData(0, item->pos()-point);
+ selectionRect->setPos(item->pos());
+ QVariant var(QVariant::UserType);
+ var.setValue(item);
+ selectionRect->setData(1, var);
+ setActualPenAndBrushFromItem(item);
+ }
+ }
+ }
+
+ void GView::mouseReleaseEvent(QMouseEvent* /*event*/)
+ {
+ mousePressed = false;
+ QGraphicsPolygonItem* polygon = dynamic_cast<QGraphicsPolygonItem*>(lastItem);
+ if (polygon && polygon->polygon().size() >= 3) {
+ lastItemChanged(polygon, items_.indexOf(polygon)+1, Update);
+ } else if (lastItem) {
+ zValue++;
+ lastItem->setZValue(zValue++);
+ items_.append(lastItem);
+ itemsMap_.insert(lastItem->data(100).toString(), lastItem);
+
+ lastItemChanged(lastItem, items_.size(), New);
+ } else if (selectionRect){
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ lastItemChanged(item, items_.indexOf(item)+1, Update);
+ }
+ }
+
+
+ void GView::handleTextItemModified(QGraphicsTextItem* item) {
+ lastItemChanged(item, item->data(101).toInt(), Update);
+ }
+
+ void GView::moveUpSelectedItem()
+ {
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ int pos = items_.indexOf(item);
+ if (pos < items_.size()-1) {
+ lastItemChanged(item, pos+1, MoveUp);
+ move(item, pos+2);
+ }
+ }
+ }
+
+ void GView::moveDownSelectedItem()
+ {
+ if (selectionRect) {
+ QGraphicsItem* item = selectionRect->data(1).value<QGraphicsItem*>();
+ int pos = items_.indexOf(item);
+ if (pos > 0) {
+ lastItemChanged(item, pos+1, MoveDown);
+ move(item, pos);
+ }
+ }
+ }
+
+ void GView::move(QGraphicsItem* item, int npos) {
+ int pos = items_.indexOf(item);
+ QGraphicsItem* itemAfter = NULL;
+ if (npos-1 > pos) {
+ if (npos == items_.size()) {
+ item->setZValue(zValue++);
+ } else {
+ itemAfter = items_.at(npos);
+ }
+
+ items_.insert(npos, item);
+ items_.removeAt(pos);
+ } else if (npos-1 < pos) {
+ itemAfter = items_.at(npos-1);
+ items_.insert(npos-1, item);
+ items_.removeAt(pos+1);
+ }
+ if (itemAfter) {
+ item->setZValue(itemAfter->zValue());
+ item->stackBefore(itemAfter);
+ }
+ }
+
+ void GView::changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush) {
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem) {
+ lineItem->setPen(pen);
+ }
+
+ FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (handLineItem) {
+ handLineItem->setPen(pen);
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem) {
+ rectItem->setPen(pen);
+ rectItem->setBrush(brush);
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem) {
+ textItem->setDefaultTextColor(pen.color());
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ polygonItem->setPen(pen);
+ polygonItem->setBrush(brush);
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ ellipseItem->setPen(pen);
+ ellipseItem->setBrush(brush);
+ }
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ void GView::setActualPenAndBrushFromItem(QGraphicsItem* item) {
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem) {
+ pen = lineItem->pen();
+ }
+
+ FreehandLineItem* handLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (handLineItem) {
+ pen = handLineItem->pen();
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem) {
+ pen = rectItem->pen();
+ brush = rectItem->brush();
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem) {
+ pen.setColor(textItem->defaultTextColor());
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ pen = polygonItem->pen();
+ brush = polygonItem->brush();
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ pen = ellipseItem->pen();
+ brush = ellipseItem->brush();
+ }
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+
+ void GView::deselect() {
+ if (selectionRect != 0) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = 0;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+
+ void GView::deselect(QString id) {
+ if (selectionRect != 0) {
+ QGraphicsItem* item = getItem(id);
+ if (item && selectionRect->data(1).value<QGraphicsItem*>() == item) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = 0;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/GView.h b/Swift/QtUI/Whiteboard/GView.h
index 1cf5275..396e381 100644
--- a/Swift/QtUI/Whiteboard/GView.h
+++ b/Swift/QtUI/Whiteboard/GView.h
@@ -25,60 +25,60 @@
#include <Swift/QtUI/Whiteboard/TextDialog.h>
namespace Swift {
- class GView : public QGraphicsView {
- Q_OBJECT
- public:
- enum Mode { Rubber, Line, Rect, Circle, HandLine, Text, Polygon, Select };
- enum Type { New, Update, MoveUp, MoveDown };
- GView(QGraphicsScene* scene, QWidget* parent = 0);
- void setLineWidth(int i);
- void setLineColor(QColor color);
- QColor getLineColor();
- void setBrushColor(QColor color);
- QColor getBrushColor();
- void setMode(Mode mode);
- void mouseMoveEvent(QMouseEvent* event);
- void mousePressEvent(QMouseEvent* event);
- void mouseReleaseEvent(QMouseEvent* /*event*/);
- void addItem(QGraphicsItem* item, QString id, int pos);
- void clear();
- QGraphicsItem* getItem(QString id);
- void deleteItem(QString id);
- QString getNewID();
- void move(QGraphicsItem* item, int npos);
- void deselect(QString id);
+ class GView : public QGraphicsView {
+ Q_OBJECT
+ public:
+ enum Mode { Rubber, Line, Rect, Circle, HandLine, Text, Polygon, Select };
+ enum Type { New, Update, MoveUp, MoveDown };
+ GView(QGraphicsScene* scene, QWidget* parent = 0);
+ void setLineWidth(int i);
+ void setLineColor(QColor color);
+ QColor getLineColor();
+ void setBrushColor(QColor color);
+ QColor getBrushColor();
+ void setMode(Mode mode);
+ void mouseMoveEvent(QMouseEvent* event);
+ void mousePressEvent(QMouseEvent* event);
+ void mouseReleaseEvent(QMouseEvent* /*event*/);
+ void addItem(QGraphicsItem* item, QString id, int pos);
+ void clear();
+ QGraphicsItem* getItem(QString id);
+ void deleteItem(QString id);
+ QString getNewID();
+ void move(QGraphicsItem* item, int npos);
+ void deselect(QString id);
- signals:
- void lastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
- void itemDeleted(QString id, int pos);
- void lineWidthChanged(int i);
- void lineColorChanged(QColor color);
- void brushColorChanged(QColor color);
+ signals:
+ void lastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
+ void itemDeleted(QString id, int pos);
+ void lineWidthChanged(int i);
+ void lineColorChanged(QColor color);
+ void brushColorChanged(QColor color);
- public slots:
- void moveUpSelectedItem();
- void moveDownSelectedItem();
+ public slots:
+ void moveUpSelectedItem();
+ void moveDownSelectedItem();
- private slots:
- void handleTextItemModified(QGraphicsTextItem*);
+ private slots:
+ void handleTextItemModified(QGraphicsTextItem*);
- private:
- void changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush);
- void setActualPenAndBrushFromItem(QGraphicsItem* item);
- void deselect();
+ private:
+ void changePenAndBrush(QGraphicsItem* item, QPen pen, QBrush brush);
+ void setActualPenAndBrushFromItem(QGraphicsItem* item);
+ void deselect();
- int zValue;
- bool mousePressed;
- QPen pen;
- QBrush brush;
- QPen defaultPen;
- QBrush defaultBrush;
- Mode mode;
- QGraphicsItem* lastItem;
- QGraphicsRectItem* selectionRect;
- TextDialog* textDialog;
- QMap<QString, QGraphicsItem*> itemsMap_;
- QList<QGraphicsItem*> items_;
- IDGenerator idGenerator;
- };
+ int zValue;
+ bool mousePressed;
+ QPen pen;
+ QBrush brush;
+ QPen defaultPen;
+ QBrush defaultBrush;
+ Mode mode;
+ QGraphicsItem* lastItem;
+ QGraphicsRectItem* selectionRect;
+ TextDialog* textDialog;
+ QMap<QString, QGraphicsItem*> itemsMap_;
+ QList<QGraphicsItem*> items_;
+ IDGenerator idGenerator;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
index ca887d1..26887e0 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
@@ -32,374 +32,374 @@
#include <Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h>
namespace Swift {
- QtWhiteboardWindow::QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession) : QWidget() {
+ QtWhiteboardWindow::QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession) : QWidget() {
#ifndef Q_OS_MAC
#ifdef Q_OS_WIN32
- setWindowIcon(QIcon(":/logo-icon-16-win.png"));
+ setWindowIcon(QIcon(":/logo-icon-16-win.png"));
#else
- setWindowIcon(QIcon(":/logo-icon-16.png"));
+ setWindowIcon(QIcon(":/logo-icon-16.png"));
#endif
#endif
- layout = new QVBoxLayout(this);
- hLayout = new QHBoxLayout;
- sidebarLayout = new QVBoxLayout;
- toolboxLayout = new QGridLayout;
-
- scene = new QGraphicsScene(this);
- scene->setSceneRect(0, 0, 400, 400);
-
- graphicsView = new GView(scene, this);
- graphicsView->setMode(GView::Line);
- connect(graphicsView, SIGNAL(lastItemChanged(QGraphicsItem*, int, GView::Type)), this, SLOT(handleLastItemChanged(QGraphicsItem*, int, GView::Type)));
- connect(graphicsView, SIGNAL(itemDeleted(QString, int)), this, SLOT(handleItemDeleted(QString, int)));
-
- widthBox = new QSpinBox(this);
- connect(widthBox, SIGNAL(valueChanged(int)), this, SLOT(changeLineWidth(int)));
- connect(graphicsView, SIGNAL(lineWidthChanged(int)), widthBox, SLOT(setValue(int)));
- widthBox->setValue(1);
-
- moveUpButton = new QPushButton("Move Up", this);
- connect(moveUpButton, SIGNAL(clicked()), graphicsView, SLOT(moveUpSelectedItem()));
-
- moveDownButton = new QPushButton("Move Down", this);
- connect(moveDownButton, SIGNAL(clicked()), graphicsView, SLOT(moveDownSelectedItem()));
-
- strokeLayout = new QHBoxLayout;
- strokeColor = new ColorWidget;
- strokeLayout->addWidget(new QLabel("Stroke:"));
- strokeLayout->addWidget(strokeColor);
- connect(strokeColor, SIGNAL(clicked()), this, SLOT(showColorDialog()));
- connect(graphicsView, SIGNAL(lineColorChanged(QColor)), strokeColor, SLOT(setColor(QColor)));
-
- fillLayout = new QHBoxLayout;
- fillColor = new ColorWidget;
- fillLayout->addWidget(new QLabel("Fill:"));
- fillLayout->addWidget(fillColor);
- connect(fillColor, SIGNAL(clicked()), this, SLOT(showBrushColorDialog()));
- connect(graphicsView, SIGNAL(brushColorChanged(QColor)), fillColor, SLOT(setColor(QColor)));
-
- rubberButton = new QToolButton(this);
- rubberButton->setIcon(QIcon(":/icons/eraser.png"));
- rubberButton->setCheckable(true);
- rubberButton->setAutoExclusive(true);
- connect(rubberButton, SIGNAL(clicked()), this, SLOT(setRubberMode()));
-
- lineButton = new QToolButton(this);
- lineButton->setIcon(QIcon(":/icons/line.png"));
- lineButton->setCheckable(true);
- lineButton->setAutoExclusive(true);
- lineButton->setChecked(true);
- connect(lineButton, SIGNAL(clicked()), this, SLOT(setLineMode()));
-
- rectButton = new QToolButton(this);
- rectButton->setIcon(QIcon(":/icons/rect.png"));
- rectButton->setCheckable(true);
- rectButton->setAutoExclusive(true);
- connect(rectButton, SIGNAL(clicked()), this, SLOT(setRectMode()));
-
- circleButton = new QToolButton(this);
- circleButton->setIcon(QIcon(":/icons/circle.png"));
- circleButton->setCheckable(true);
- circleButton->setAutoExclusive(true);
- connect(circleButton, SIGNAL(clicked()), this, SLOT(setCircleMode()));
-
- handLineButton = new QToolButton(this);
- handLineButton->setIcon(QIcon(":/icons/handline.png"));
- handLineButton->setCheckable(true);
- handLineButton->setAutoExclusive(true);
- connect(handLineButton, SIGNAL(clicked()), this, SLOT(setHandLineMode()));
-
- textButton = new QToolButton(this);
- textButton->setIcon(QIcon(":/icons/text.png"));
- textButton->setCheckable(true);
- textButton->setAutoExclusive(true);
- connect(textButton, SIGNAL(clicked()), this, SLOT(setTextMode()));
-
- polygonButton = new QToolButton(this);
- polygonButton->setIcon(QIcon(":/icons/polygon.png"));
- polygonButton->setCheckable(true);
- polygonButton->setAutoExclusive(true);
- connect(polygonButton, SIGNAL(clicked()), this, SLOT(setPolygonMode()));
-
- selectButton = new QToolButton(this);
- selectButton->setIcon(QIcon(":/icons/cursor.png"));
- selectButton->setCheckable(true);
- selectButton->setAutoExclusive(true);
- connect(selectButton, SIGNAL(clicked()), this, SLOT(setSelectMode()));
-
- toolboxLayout->addWidget(rubberButton, 0, 0);
- toolboxLayout->addWidget(selectButton, 0, 1);
- toolboxLayout->addWidget(lineButton, 0, 2);
- toolboxLayout->addWidget(circleButton, 1, 0);
- toolboxLayout->addWidget(handLineButton, 1, 1);
- toolboxLayout->addWidget(rectButton, 1, 2);
- toolboxLayout->addWidget(textButton, 2, 0);
- toolboxLayout->addWidget(polygonButton, 2, 1);
-
- sidebarLayout->addLayout(toolboxLayout);
- sidebarLayout->addSpacing(30);
- sidebarLayout->addWidget(moveUpButton);
- sidebarLayout->addWidget(moveDownButton);
- sidebarLayout->addSpacing(40);
- sidebarLayout->addWidget(widthBox);
- sidebarLayout->addLayout(strokeLayout);
- sidebarLayout->addLayout(fillLayout);
- sidebarLayout->addStretch();
- hLayout->addWidget(graphicsView);
- hLayout->addLayout(sidebarLayout);
- layout->addLayout(hLayout);
- this->setLayout(layout);
-
- setSession(whiteboardSession);
- }
-
- void QtWhiteboardWindow::handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation) {
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::New);
- insertOp->getElement()->accept(visitor);
- }
-
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::Update);
- updateOp->getElement()->accept(visitor);
- if (updateOp->getPos() != updateOp->getNewPos()) {
- graphicsView->move(graphicsView->getItem(P2QSTRING(updateOp->getElement()->getID())), updateOp->getNewPos());
- }
- }
-
- WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
- if (deleteOp) {
- graphicsView->deleteItem(P2QSTRING(deleteOp->getElementID()));
- }
- }
-
- void QtWhiteboardWindow::changeLineWidth(int i)
- {
- graphicsView->setLineWidth(i);
- }
-
- void QtWhiteboardWindow::showColorDialog()
- {
- QColor color = QColorDialog::getColor(graphicsView->getLineColor(), 0, "Select pen color", QColorDialog::ShowAlphaChannel);
- if(color.isValid())
- graphicsView->setLineColor(color);
- }
-
- void QtWhiteboardWindow::showBrushColorDialog()
- {
- QColor color = QColorDialog::getColor(graphicsView->getBrushColor(), 0, "Select brush color", QColorDialog::ShowAlphaChannel);
- if(color.isValid())
- graphicsView->setBrushColor(color);
- }
-
- void QtWhiteboardWindow::setRubberMode()
- {
- graphicsView->setMode(GView::Rubber);
- }
-
- void QtWhiteboardWindow::setLineMode()
- {
- graphicsView->setMode(GView::Line);
- }
-
- void QtWhiteboardWindow::setRectMode()
- {
- graphicsView->setMode(GView::Rect);
- }
-
- void QtWhiteboardWindow::setCircleMode()
- {
- graphicsView->setMode(GView::Circle);
- }
-
- void QtWhiteboardWindow::setHandLineMode()
- {
- graphicsView->setMode(GView::HandLine);
- }
-
- void QtWhiteboardWindow::setTextMode()
- {
- graphicsView->setMode(GView::Text);
- }
-
- void QtWhiteboardWindow::setPolygonMode()
- {
- graphicsView->setMode(GView::Polygon);
- }
-
- void QtWhiteboardWindow::setSelectMode()
- {
- graphicsView->setMode(GView::Select);
- }
-
- void QtWhiteboardWindow::show()
- {
- QWidget::show();
- }
-
- void QtWhiteboardWindow::setSession(WhiteboardSession::ref session) {
- graphicsView->clear();
- whiteboardSession_ = session;
- whiteboardSession_->onOperationReceived.connect(boost::bind(&QtWhiteboardWindow::handleWhiteboardOperationReceive, this, _1));
- whiteboardSession_->onRequestAccepted.connect(boost::bind(&QWidget::show, this));
- whiteboardSession_->onSessionTerminated.connect(boost::bind(&QtWhiteboardWindow::handleSessionTerminate, this));
- }
-
- void QtWhiteboardWindow::activateWindow() {
- QWidget::activateWindow();
- }
-
- void QtWhiteboardWindow::setName(const std::string& name) {
- setWindowTitle(P2QSTRING(name));
- }
-
- void QtWhiteboardWindow::handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type) {
- WhiteboardElement::ref el;
- QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
- if (lineItem != 0) {
- QLine line = lineItem->line().toLine();
- QColor color = lineItem->pen().color();
- WhiteboardLineElement::ref element = boost::make_shared<WhiteboardLineElement>(line.x1()+lineItem->pos().x(), line.y1()+lineItem->pos().y(), line.x2()+lineItem->pos().x(), line.y2()+lineItem->pos().y());
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
- element->setPenWidth(lineItem->pen().width());
-
- element->setID(lineItem->data(100).toString().toStdString());
- el = element;
- }
-
- FreehandLineItem* freehandLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
- if (freehandLineItem != 0) {
- WhiteboardFreehandPathElement::ref element = boost::make_shared<WhiteboardFreehandPathElement>();
- QColor color = freehandLineItem->pen().color();
- std::vector<std::pair<int, int> > points;
- QVector<QPointF>::const_iterator it = freehandLineItem->points().constBegin();
- for ( ; it != freehandLineItem->points().constEnd(); ++it) {
- points.push_back(std::pair<int, int>(
- boost::numeric_cast<int>(it->x()+item->pos().x()),
- boost::numeric_cast<int>(it->y()+item->pos().y())));
- }
-
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
- element->setPenWidth(freehandLineItem->pen().width());
- element->setPoints(points);
-
- element->setID(freehandLineItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
- if (rectItem != 0) {
- QRectF rect = rectItem->rect();
- WhiteboardRectElement::ref element = boost::make_shared<WhiteboardRectElement>(rect.x()+item->pos().x(), rect.y()+item->pos().y(), rect.width(), rect.height());
- QColor penColor = rectItem->pen().color();
- QColor brushColor = rectItem->brush().color();
-
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setPenWidth(rectItem->pen().width());
-
- element->setID(rectItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
- if (textItem != 0) {
- QPointF point = textItem->pos();
- WhiteboardTextElement::ref element = boost::make_shared<WhiteboardTextElement>(point.x(), point.y());
- element->setText(textItem->toPlainText().toStdString());
- element->setSize(textItem->font().pointSize());
- QColor color = textItem->defaultTextColor();
- element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
-
- element->setID(textItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
- if (polygonItem) {
- WhiteboardPolygonElement::ref element = boost::make_shared<WhiteboardPolygonElement>();
- QPolygonF polygon = polygonItem->polygon();
- std::vector<std::pair<int, int> > points;
- QVector<QPointF>::const_iterator it = polygon.begin();
- for (; it != polygon.end(); ++it) {
- points.push_back(std::pair<int, int>(
- boost::numeric_cast<int>(it->x()+item->pos().x()),
- boost::numeric_cast<int>(it->y()+item->pos().y())));
- }
-
- element->setPoints(points);
-
- QColor penColor = polygonItem->pen().color();
- QColor brushColor = polygonItem->brush().color();
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenWidth(polygonItem->pen().width());
-
- element->setID(polygonItem->data(100).toString().toStdString());
- el = element;
- }
-
- QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
- if (ellipseItem) {
- QRectF rect = ellipseItem->rect();
- int cx = boost::numeric_cast<int>(rect.x()+rect.width()/2 + item->pos().x());
- int cy = boost::numeric_cast<int>(rect.y()+rect.height()/2 + item->pos().y());
- int rx = boost::numeric_cast<int>(rect.width()/2);
- int ry = boost::numeric_cast<int>(rect.height()/2);
- WhiteboardEllipseElement::ref element = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
-
- QColor penColor = ellipseItem->pen().color();
- QColor brushColor = ellipseItem->brush().color();
- element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
- element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
- element->setPenWidth(ellipseItem->pen().width());
-
- element->setID(ellipseItem->data(100).toString().toStdString());
- el = element;
- }
-
- if (type == GView::New) {
- WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
- insertOp->setPos(pos);
- insertOp->setElement(el);
- whiteboardSession_->sendOperation(insertOp);
- } else {
- WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
- updateOp->setPos(pos);
- if (type == GView::Update) {
- updateOp->setNewPos(pos);
- } else if (type == GView::MoveUp) {
- updateOp->setNewPos(pos+1);
- } else if (type == GView::MoveDown) {
- updateOp->setNewPos(pos-1);
- }
- updateOp->setElement(el);
- whiteboardSession_->sendOperation(updateOp);
- }
- }
-
- void QtWhiteboardWindow::handleItemDeleted(QString id, int pos) {
- WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
- deleteOp->setElementID(Q2PSTRING(id));
- deleteOp->setPos(pos);
- whiteboardSession_->sendOperation(deleteOp);
- }
-
- void QtWhiteboardWindow::handleSessionTerminate() {
- hide();
- }
-
- void QtWhiteboardWindow::closeEvent(QCloseEvent* event) {
- QMessageBox box(this);
- box.setText(tr("Closing window is equivalent closing the session. Are you sure you want to do this?"));
- box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- box.setIcon(QMessageBox::Question);
- if (box.exec() == QMessageBox::Yes) {
- whiteboardSession_->cancel();
- } else {
- event->ignore();
- }
- }
+ layout = new QVBoxLayout(this);
+ hLayout = new QHBoxLayout;
+ sidebarLayout = new QVBoxLayout;
+ toolboxLayout = new QGridLayout;
+
+ scene = new QGraphicsScene(this);
+ scene->setSceneRect(0, 0, 400, 400);
+
+ graphicsView = new GView(scene, this);
+ graphicsView->setMode(GView::Line);
+ connect(graphicsView, SIGNAL(lastItemChanged(QGraphicsItem*, int, GView::Type)), this, SLOT(handleLastItemChanged(QGraphicsItem*, int, GView::Type)));
+ connect(graphicsView, SIGNAL(itemDeleted(QString, int)), this, SLOT(handleItemDeleted(QString, int)));
+
+ widthBox = new QSpinBox(this);
+ connect(widthBox, SIGNAL(valueChanged(int)), this, SLOT(changeLineWidth(int)));
+ connect(graphicsView, SIGNAL(lineWidthChanged(int)), widthBox, SLOT(setValue(int)));
+ widthBox->setValue(1);
+
+ moveUpButton = new QPushButton("Move Up", this);
+ connect(moveUpButton, SIGNAL(clicked()), graphicsView, SLOT(moveUpSelectedItem()));
+
+ moveDownButton = new QPushButton("Move Down", this);
+ connect(moveDownButton, SIGNAL(clicked()), graphicsView, SLOT(moveDownSelectedItem()));
+
+ strokeLayout = new QHBoxLayout;
+ strokeColor = new ColorWidget;
+ strokeLayout->addWidget(new QLabel("Stroke:"));
+ strokeLayout->addWidget(strokeColor);
+ connect(strokeColor, SIGNAL(clicked()), this, SLOT(showColorDialog()));
+ connect(graphicsView, SIGNAL(lineColorChanged(QColor)), strokeColor, SLOT(setColor(QColor)));
+
+ fillLayout = new QHBoxLayout;
+ fillColor = new ColorWidget;
+ fillLayout->addWidget(new QLabel("Fill:"));
+ fillLayout->addWidget(fillColor);
+ connect(fillColor, SIGNAL(clicked()), this, SLOT(showBrushColorDialog()));
+ connect(graphicsView, SIGNAL(brushColorChanged(QColor)), fillColor, SLOT(setColor(QColor)));
+
+ rubberButton = new QToolButton(this);
+ rubberButton->setIcon(QIcon(":/icons/eraser.png"));
+ rubberButton->setCheckable(true);
+ rubberButton->setAutoExclusive(true);
+ connect(rubberButton, SIGNAL(clicked()), this, SLOT(setRubberMode()));
+
+ lineButton = new QToolButton(this);
+ lineButton->setIcon(QIcon(":/icons/line.png"));
+ lineButton->setCheckable(true);
+ lineButton->setAutoExclusive(true);
+ lineButton->setChecked(true);
+ connect(lineButton, SIGNAL(clicked()), this, SLOT(setLineMode()));
+
+ rectButton = new QToolButton(this);
+ rectButton->setIcon(QIcon(":/icons/rect.png"));
+ rectButton->setCheckable(true);
+ rectButton->setAutoExclusive(true);
+ connect(rectButton, SIGNAL(clicked()), this, SLOT(setRectMode()));
+
+ circleButton = new QToolButton(this);
+ circleButton->setIcon(QIcon(":/icons/circle.png"));
+ circleButton->setCheckable(true);
+ circleButton->setAutoExclusive(true);
+ connect(circleButton, SIGNAL(clicked()), this, SLOT(setCircleMode()));
+
+ handLineButton = new QToolButton(this);
+ handLineButton->setIcon(QIcon(":/icons/handline.png"));
+ handLineButton->setCheckable(true);
+ handLineButton->setAutoExclusive(true);
+ connect(handLineButton, SIGNAL(clicked()), this, SLOT(setHandLineMode()));
+
+ textButton = new QToolButton(this);
+ textButton->setIcon(QIcon(":/icons/text.png"));
+ textButton->setCheckable(true);
+ textButton->setAutoExclusive(true);
+ connect(textButton, SIGNAL(clicked()), this, SLOT(setTextMode()));
+
+ polygonButton = new QToolButton(this);
+ polygonButton->setIcon(QIcon(":/icons/polygon.png"));
+ polygonButton->setCheckable(true);
+ polygonButton->setAutoExclusive(true);
+ connect(polygonButton, SIGNAL(clicked()), this, SLOT(setPolygonMode()));
+
+ selectButton = new QToolButton(this);
+ selectButton->setIcon(QIcon(":/icons/cursor.png"));
+ selectButton->setCheckable(true);
+ selectButton->setAutoExclusive(true);
+ connect(selectButton, SIGNAL(clicked()), this, SLOT(setSelectMode()));
+
+ toolboxLayout->addWidget(rubberButton, 0, 0);
+ toolboxLayout->addWidget(selectButton, 0, 1);
+ toolboxLayout->addWidget(lineButton, 0, 2);
+ toolboxLayout->addWidget(circleButton, 1, 0);
+ toolboxLayout->addWidget(handLineButton, 1, 1);
+ toolboxLayout->addWidget(rectButton, 1, 2);
+ toolboxLayout->addWidget(textButton, 2, 0);
+ toolboxLayout->addWidget(polygonButton, 2, 1);
+
+ sidebarLayout->addLayout(toolboxLayout);
+ sidebarLayout->addSpacing(30);
+ sidebarLayout->addWidget(moveUpButton);
+ sidebarLayout->addWidget(moveDownButton);
+ sidebarLayout->addSpacing(40);
+ sidebarLayout->addWidget(widthBox);
+ sidebarLayout->addLayout(strokeLayout);
+ sidebarLayout->addLayout(fillLayout);
+ sidebarLayout->addStretch();
+ hLayout->addWidget(graphicsView);
+ hLayout->addLayout(sidebarLayout);
+ layout->addLayout(hLayout);
+ this->setLayout(layout);
+
+ setSession(whiteboardSession);
+ }
+
+ void QtWhiteboardWindow::handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation) {
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::New);
+ insertOp->getElement()->accept(visitor);
+ }
+
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::Update);
+ updateOp->getElement()->accept(visitor);
+ if (updateOp->getPos() != updateOp->getNewPos()) {
+ graphicsView->move(graphicsView->getItem(P2QSTRING(updateOp->getElement()->getID())), updateOp->getNewPos());
+ }
+ }
+
+ WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ graphicsView->deleteItem(P2QSTRING(deleteOp->getElementID()));
+ }
+ }
+
+ void QtWhiteboardWindow::changeLineWidth(int i)
+ {
+ graphicsView->setLineWidth(i);
+ }
+
+ void QtWhiteboardWindow::showColorDialog()
+ {
+ QColor color = QColorDialog::getColor(graphicsView->getLineColor(), 0, "Select pen color", QColorDialog::ShowAlphaChannel);
+ if(color.isValid())
+ graphicsView->setLineColor(color);
+ }
+
+ void QtWhiteboardWindow::showBrushColorDialog()
+ {
+ QColor color = QColorDialog::getColor(graphicsView->getBrushColor(), 0, "Select brush color", QColorDialog::ShowAlphaChannel);
+ if(color.isValid())
+ graphicsView->setBrushColor(color);
+ }
+
+ void QtWhiteboardWindow::setRubberMode()
+ {
+ graphicsView->setMode(GView::Rubber);
+ }
+
+ void QtWhiteboardWindow::setLineMode()
+ {
+ graphicsView->setMode(GView::Line);
+ }
+
+ void QtWhiteboardWindow::setRectMode()
+ {
+ graphicsView->setMode(GView::Rect);
+ }
+
+ void QtWhiteboardWindow::setCircleMode()
+ {
+ graphicsView->setMode(GView::Circle);
+ }
+
+ void QtWhiteboardWindow::setHandLineMode()
+ {
+ graphicsView->setMode(GView::HandLine);
+ }
+
+ void QtWhiteboardWindow::setTextMode()
+ {
+ graphicsView->setMode(GView::Text);
+ }
+
+ void QtWhiteboardWindow::setPolygonMode()
+ {
+ graphicsView->setMode(GView::Polygon);
+ }
+
+ void QtWhiteboardWindow::setSelectMode()
+ {
+ graphicsView->setMode(GView::Select);
+ }
+
+ void QtWhiteboardWindow::show()
+ {
+ QWidget::show();
+ }
+
+ void QtWhiteboardWindow::setSession(WhiteboardSession::ref session) {
+ graphicsView->clear();
+ whiteboardSession_ = session;
+ whiteboardSession_->onOperationReceived.connect(boost::bind(&QtWhiteboardWindow::handleWhiteboardOperationReceive, this, _1));
+ whiteboardSession_->onRequestAccepted.connect(boost::bind(&QWidget::show, this));
+ whiteboardSession_->onSessionTerminated.connect(boost::bind(&QtWhiteboardWindow::handleSessionTerminate, this));
+ }
+
+ void QtWhiteboardWindow::activateWindow() {
+ QWidget::activateWindow();
+ }
+
+ void QtWhiteboardWindow::setName(const std::string& name) {
+ setWindowTitle(P2QSTRING(name));
+ }
+
+ void QtWhiteboardWindow::handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type) {
+ WhiteboardElement::ref el;
+ QGraphicsLineItem* lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item);
+ if (lineItem != 0) {
+ QLine line = lineItem->line().toLine();
+ QColor color = lineItem->pen().color();
+ WhiteboardLineElement::ref element = boost::make_shared<WhiteboardLineElement>(line.x1()+lineItem->pos().x(), line.y1()+lineItem->pos().y(), line.x2()+lineItem->pos().x(), line.y2()+lineItem->pos().y());
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+ element->setPenWidth(lineItem->pen().width());
+
+ element->setID(lineItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ FreehandLineItem* freehandLineItem = qgraphicsitem_cast<FreehandLineItem*>(item);
+ if (freehandLineItem != 0) {
+ WhiteboardFreehandPathElement::ref element = boost::make_shared<WhiteboardFreehandPathElement>();
+ QColor color = freehandLineItem->pen().color();
+ std::vector<std::pair<int, int> > points;
+ QVector<QPointF>::const_iterator it = freehandLineItem->points().constBegin();
+ for ( ; it != freehandLineItem->points().constEnd(); ++it) {
+ points.push_back(std::pair<int, int>(
+ boost::numeric_cast<int>(it->x()+item->pos().x()),
+ boost::numeric_cast<int>(it->y()+item->pos().y())));
+ }
+
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+ element->setPenWidth(freehandLineItem->pen().width());
+ element->setPoints(points);
+
+ element->setID(freehandLineItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsRectItem* rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item);
+ if (rectItem != 0) {
+ QRectF rect = rectItem->rect();
+ WhiteboardRectElement::ref element = boost::make_shared<WhiteboardRectElement>(rect.x()+item->pos().x(), rect.y()+item->pos().y(), rect.width(), rect.height());
+ QColor penColor = rectItem->pen().color();
+ QColor brushColor = rectItem->brush().color();
+
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setPenWidth(rectItem->pen().width());
+
+ element->setID(rectItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsTextItem* textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
+ if (textItem != 0) {
+ QPointF point = textItem->pos();
+ WhiteboardTextElement::ref element = boost::make_shared<WhiteboardTextElement>(point.x(), point.y());
+ element->setText(textItem->toPlainText().toStdString());
+ element->setSize(textItem->font().pointSize());
+ QColor color = textItem->defaultTextColor();
+ element->setColor(WhiteboardColor(color.red(), color.green(), color.blue(), color.alpha()));
+
+ element->setID(textItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsPolygonItem* polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
+ if (polygonItem) {
+ WhiteboardPolygonElement::ref element = boost::make_shared<WhiteboardPolygonElement>();
+ QPolygonF polygon = polygonItem->polygon();
+ std::vector<std::pair<int, int> > points;
+ QVector<QPointF>::const_iterator it = polygon.begin();
+ for (; it != polygon.end(); ++it) {
+ points.push_back(std::pair<int, int>(
+ boost::numeric_cast<int>(it->x()+item->pos().x()),
+ boost::numeric_cast<int>(it->y()+item->pos().y())));
+ }
+
+ element->setPoints(points);
+
+ QColor penColor = polygonItem->pen().color();
+ QColor brushColor = polygonItem->brush().color();
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenWidth(polygonItem->pen().width());
+
+ element->setID(polygonItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ QGraphicsEllipseItem* ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
+ if (ellipseItem) {
+ QRectF rect = ellipseItem->rect();
+ int cx = boost::numeric_cast<int>(rect.x()+rect.width()/2 + item->pos().x());
+ int cy = boost::numeric_cast<int>(rect.y()+rect.height()/2 + item->pos().y());
+ int rx = boost::numeric_cast<int>(rect.width()/2);
+ int ry = boost::numeric_cast<int>(rect.height()/2);
+ WhiteboardEllipseElement::ref element = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
+
+ QColor penColor = ellipseItem->pen().color();
+ QColor brushColor = ellipseItem->brush().color();
+ element->setPenColor(WhiteboardColor(penColor.red(), penColor.green(), penColor.blue(), penColor.alpha()));
+ element->setBrushColor(WhiteboardColor(brushColor.red(), brushColor.green(), brushColor.blue(), brushColor.alpha()));
+ element->setPenWidth(ellipseItem->pen().width());
+
+ element->setID(ellipseItem->data(100).toString().toStdString());
+ el = element;
+ }
+
+ if (type == GView::New) {
+ WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
+ insertOp->setPos(pos);
+ insertOp->setElement(el);
+ whiteboardSession_->sendOperation(insertOp);
+ } else {
+ WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
+ updateOp->setPos(pos);
+ if (type == GView::Update) {
+ updateOp->setNewPos(pos);
+ } else if (type == GView::MoveUp) {
+ updateOp->setNewPos(pos+1);
+ } else if (type == GView::MoveDown) {
+ updateOp->setNewPos(pos-1);
+ }
+ updateOp->setElement(el);
+ whiteboardSession_->sendOperation(updateOp);
+ }
+ }
+
+ void QtWhiteboardWindow::handleItemDeleted(QString id, int pos) {
+ WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
+ deleteOp->setElementID(Q2PSTRING(id));
+ deleteOp->setPos(pos);
+ whiteboardSession_->sendOperation(deleteOp);
+ }
+
+ void QtWhiteboardWindow::handleSessionTerminate() {
+ hide();
+ }
+
+ void QtWhiteboardWindow::closeEvent(QCloseEvent* event) {
+ QMessageBox box(this);
+ box.setText(tr("Closing window is equivalent closing the session. Are you sure you want to do this?"));
+ box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ box.setIcon(QMessageBox::Question);
+ if (box.exec() == QMessageBox::Yes) {
+ whiteboardSession_->cancel();
+ } else {
+ event->ignore();
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
index 862ae66..3b3f74e 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
@@ -35,61 +35,61 @@
#include <Swift/QtUI/Whiteboard/GView.h>
namespace Swift {
- class QtWhiteboardWindow : public QWidget, public WhiteboardWindow
- {
- Q_OBJECT
- public:
- QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession);
- void show();
- void setSession(WhiteboardSession::ref session);
- void activateWindow();
- void setName(const std::string& name);
+ class QtWhiteboardWindow : public QWidget, public WhiteboardWindow
+ {
+ Q_OBJECT
+ public:
+ QtWhiteboardWindow(WhiteboardSession::ref whiteboardSession);
+ void show();
+ void setSession(WhiteboardSession::ref session);
+ void activateWindow();
+ void setName(const std::string& name);
- private slots:
- void changeLineWidth(int i);
- void showColorDialog();
- void showBrushColorDialog();
- void setRubberMode();
- void setLineMode();
- void setRectMode();
- void setCircleMode();
- void setHandLineMode();
- void setTextMode();
- void setPolygonMode();
- void setSelectMode();
- void handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
- void handleItemDeleted(QString id, int pos);
+ private slots:
+ void changeLineWidth(int i);
+ void showColorDialog();
+ void showBrushColorDialog();
+ void setRubberMode();
+ void setLineMode();
+ void setRectMode();
+ void setCircleMode();
+ void setHandLineMode();
+ void setTextMode();
+ void setPolygonMode();
+ void setSelectMode();
+ void handleLastItemChanged(QGraphicsItem* item, int pos, GView::Type type);
+ void handleItemDeleted(QString id, int pos);
- private:
- void handleSessionTerminate();
- void handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation);
- void closeEvent(QCloseEvent* event);
+ private:
+ void handleSessionTerminate();
+ void handleWhiteboardOperationReceive(const WhiteboardOperation::ref operation);
+ void closeEvent(QCloseEvent* event);
- private:
- QGraphicsScene* scene;
- GView* graphicsView;
- QVBoxLayout* layout;
- QVBoxLayout* sidebarLayout;
- QHBoxLayout* hLayout;
- QGridLayout* toolboxLayout;
- QHBoxLayout* strokeLayout;
- QHBoxLayout* fillLayout;
- ColorWidget* strokeColor;
- ColorWidget* fillColor;
- QWidget* widget;
- QPushButton* moveUpButton;
- QPushButton* moveDownButton;
- QSpinBox* widthBox;
- QToolButton* rubberButton;
- QToolButton* lineButton;
- QToolButton* rectButton;
- QToolButton* circleButton;
- QToolButton* handLineButton;
- QToolButton* textButton;
- QToolButton* polygonButton;
- QToolButton* selectButton;
+ private:
+ QGraphicsScene* scene;
+ GView* graphicsView;
+ QVBoxLayout* layout;
+ QVBoxLayout* sidebarLayout;
+ QHBoxLayout* hLayout;
+ QGridLayout* toolboxLayout;
+ QHBoxLayout* strokeLayout;
+ QHBoxLayout* fillLayout;
+ ColorWidget* strokeColor;
+ ColorWidget* fillColor;
+ QWidget* widget;
+ QPushButton* moveUpButton;
+ QPushButton* moveDownButton;
+ QSpinBox* widthBox;
+ QToolButton* rubberButton;
+ QToolButton* lineButton;
+ QToolButton* rectButton;
+ QToolButton* circleButton;
+ QToolButton* handLineButton;
+ QToolButton* textButton;
+ QToolButton* polygonButton;
+ QToolButton* selectButton;
- std::string lastOpID;
- WhiteboardSession::ref whiteboardSession_;
- };
+ std::string lastOpID;
+ WhiteboardSession::ref whiteboardSession_;
+ };
}
diff --git a/Swift/QtUI/Whiteboard/TextDialog.cpp b/Swift/QtUI/Whiteboard/TextDialog.cpp
index 13d83d5..c15e7b4 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.cpp
+++ b/Swift/QtUI/Whiteboard/TextDialog.cpp
@@ -13,46 +13,46 @@
#include <Swift/QtUI/Whiteboard/TextDialog.h>
namespace Swift {
- TextDialog::TextDialog(QGraphicsTextItem* item, QWidget* parent) : QDialog(parent)
- {
- this->item = item;
-
- layout = new QVBoxLayout(this);
- hLayout = new QHBoxLayout;
-
- editor = new QLineEdit(this);
- connect(editor, SIGNAL(textChanged(const QString&)), this, SLOT(changeItemText(const QString&)));
-
- fontSizeBox = new QSpinBox(this);
- fontSizeBox->setMinimum(1);
- connect(fontSizeBox, SIGNAL(valueChanged(int)), this, SLOT(changeItemFontSize(int)));
- fontSizeBox->setValue(13);
-
-
- buttonBox = new QDialogButtonBox(this);
- buttonBox->setStandardButtons(QDialogButtonBox::Ok);
- connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
-
- hLayout->addWidget(editor);
- hLayout->addWidget(fontSizeBox);
- layout->addLayout(hLayout);
- layout->addWidget(buttonBox);
- }
-
- void TextDialog::changeItemText(const QString &text)
- {
- item->setPlainText(text);
- }
-
- void TextDialog::changeItemFontSize(int i)
- {
- QFont font = item->font();
- font.setPointSize(i);
- item->setFont(font);
- }
-
- void TextDialog::accept() {
- emit accepted(item);
- done(QDialog::Accepted);
- }
+ TextDialog::TextDialog(QGraphicsTextItem* item, QWidget* parent) : QDialog(parent)
+ {
+ this->item = item;
+
+ layout = new QVBoxLayout(this);
+ hLayout = new QHBoxLayout;
+
+ editor = new QLineEdit(this);
+ connect(editor, SIGNAL(textChanged(const QString&)), this, SLOT(changeItemText(const QString&)));
+
+ fontSizeBox = new QSpinBox(this);
+ fontSizeBox->setMinimum(1);
+ connect(fontSizeBox, SIGNAL(valueChanged(int)), this, SLOT(changeItemFontSize(int)));
+ fontSizeBox->setValue(13);
+
+
+ buttonBox = new QDialogButtonBox(this);
+ buttonBox->setStandardButtons(QDialogButtonBox::Ok);
+ connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
+
+ hLayout->addWidget(editor);
+ hLayout->addWidget(fontSizeBox);
+ layout->addLayout(hLayout);
+ layout->addWidget(buttonBox);
+ }
+
+ void TextDialog::changeItemText(const QString &text)
+ {
+ item->setPlainText(text);
+ }
+
+ void TextDialog::changeItemFontSize(int i)
+ {
+ QFont font = item->font();
+ font.setPointSize(i);
+ item->setFont(font);
+ }
+
+ void TextDialog::accept() {
+ emit accepted(item);
+ done(QDialog::Accepted);
+ }
}
diff --git a/Swift/QtUI/Whiteboard/TextDialog.h b/Swift/QtUI/Whiteboard/TextDialog.h
index 911bd37..31bd096 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.h
+++ b/Swift/QtUI/Whiteboard/TextDialog.h
@@ -23,27 +23,27 @@
#include <QVBoxLayout>
namespace Swift {
- class TextDialog : public QDialog
- {
- Q_OBJECT
- public:
- TextDialog(QGraphicsTextItem* item, QWidget* parent = 0);
-
- private:
- QGraphicsTextItem* item;
- QLineEdit* editor;
- QDialogButtonBox* buttonBox;
- QVBoxLayout* layout;
- QHBoxLayout* hLayout;
- QSpinBox* fontSizeBox;
-
- signals:
- void accepted(QGraphicsTextItem* item);
-
- private slots:
- void accept();
- void changeItemText(const QString &text);
- void changeItemFontSize(int i);
- };
+ class TextDialog : public QDialog
+ {
+ Q_OBJECT
+ public:
+ TextDialog(QGraphicsTextItem* item, QWidget* parent = 0);
+
+ private:
+ QGraphicsTextItem* item;
+ QLineEdit* editor;
+ QDialogButtonBox* buttonBox;
+ QVBoxLayout* layout;
+ QHBoxLayout* hLayout;
+ QSpinBox* fontSizeBox;
+
+ signals:
+ void accepted(QGraphicsTextItem* item);
+
+ private slots:
+ void accept();
+ void changeItemText(const QString &text);
+ void changeItemFontSize(int i);
+ };
}
diff --git a/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h b/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
index 4d37704..719725c 100644
--- a/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
+++ b/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
@@ -23,172 +23,172 @@
#include <Swift/QtUI/Whiteboard/GView.h>
namespace Swift {
- class WhiteboardElementDrawingVisitor : public WhiteboardElementVisitor {
- public:
- WhiteboardElementDrawingVisitor(GView* graphicsView, int pos, GView::Type type) : graphicsView_(graphicsView), pos_(pos), type_(type) {}
-
- void visit(WhiteboardLineElement& element) {
- QGraphicsLineItem *item;
- if (type_ == GView::New) {
- item = new QGraphicsLineItem(element.x1(), element.y1(), element.x2(), element.y2());
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- QLineF line(element.x1(), element.y1(), element.x2(), element.y2());
- item->setLine(line);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- if (item) {
- QPen pen;
- WhiteboardColor color = element.getColor();
- pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- pen.setWidth(element.getPenWidth());
- item->setPen(pen);
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardFreehandPathElement& element) {
- FreehandLineItem *item;
- if (type_ == GView::New) {
- item = new FreehandLineItem;
- } else {
- item = qgraphicsitem_cast<FreehandLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
-
- if (item) {
- QPen pen;
- WhiteboardColor color = element.getColor();
- pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- pen.setWidth(element.getPenWidth());
- item->setPen(pen);
-
- std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
- item->setStartPoint(QPointF(it->first, it->second));
- for (++it; it != element.getPoints().end(); ++it) {
- item->lineTo(QPointF(it->first, it->second));
- }
-
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- if (type_ == GView::New) {
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- }
- }
-
- void visit(WhiteboardRectElement& element) {
- QGraphicsRectItem* item;
- if (type_ == GView::New) {
- item = new QGraphicsRectItem(element.getX(), element.getY(), element.getWidth(), element.getHeight());
- graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsRectItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- QRectF rect(element.getX(), element.getY(), element.getWidth(), element.getHeight());
- item->setRect(rect);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
-
- if (item) {
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardPolygonElement& element) {
- QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
- if (item == 0 && type_ == GView::New) {
- item = new QGraphicsPolygonItem();
- QString id = P2QSTRING(element.getID());
- item->setData(100, id);
- graphicsView_->addItem(item, id, pos_);
- }
- graphicsView_->deselect(P2QSTRING(element.getID()));
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
-
- item->setPos(0,0);
- QPolygonF polygon;
- std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
- for (; it != element.getPoints().end(); ++it) {
- polygon.append(QPointF(it->first, it->second));
- }
- item->setPolygon(polygon);
- }
-
- void visit(WhiteboardTextElement& element) {
- QGraphicsTextItem* item;
- QString id = P2QSTRING(element.getID());
- if (type_ == GView::New) {
- item = new QGraphicsTextItem;
- graphicsView_->addItem(item, id, pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsTextItem*>(graphicsView_->getItem(id));
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- if (item) {
- item->setPlainText(P2QSTRING(element.getText()));
- item->setPos(QPointF(element.getX(), element.getY()));
- QFont font = item->font();
- font.setPointSize(element.getSize());
- item->setFont(font);
- WhiteboardColor color = element.getColor();
- item->setDefaultTextColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
- item->setData(100, id);
- }
- }
-
- void visit(WhiteboardEllipseElement& element) {
- QRectF rect;
- QGraphicsEllipseItem* item;
- QString id = P2QSTRING(element.getID());
- rect.setTopLeft(QPointF(element.getCX()-element.getRX(), element.getCY()-element.getRY()));
- rect.setBottomRight(QPointF(element.getCX()+element.getRX(), element.getCY()+element.getRY()));
- if (type_ == GView::New) {
- item = new QGraphicsEllipseItem(rect);
- graphicsView_->addItem(item, id, pos_);
- } else {
- item = qgraphicsitem_cast<QGraphicsEllipseItem*>(graphicsView_->getItem(id));
- item->setRect(rect);
- item->setPos(0,0);
- graphicsView_->deselect(P2QSTRING(element.getID()));
- }
- QPen pen;
- QBrush brush(Qt::SolidPattern);
- WhiteboardColor penColor = element.getPenColor();
- WhiteboardColor brushColor = element.getBrushColor();
- pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
- pen.setWidth(element.getPenWidth());
- brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
- item->setPen(pen);
- item->setBrush(brush);
- item->setData(100, id);
- }
-
- private:
- GView* graphicsView_;
- int pos_;
- GView::Type type_;
- };
+ class WhiteboardElementDrawingVisitor : public WhiteboardElementVisitor {
+ public:
+ WhiteboardElementDrawingVisitor(GView* graphicsView, int pos, GView::Type type) : graphicsView_(graphicsView), pos_(pos), type_(type) {}
+
+ void visit(WhiteboardLineElement& element) {
+ QGraphicsLineItem *item;
+ if (type_ == GView::New) {
+ item = new QGraphicsLineItem(element.x1(), element.y1(), element.x2(), element.y2());
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ QLineF line(element.x1(), element.y1(), element.x2(), element.y2());
+ item->setLine(line);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ if (item) {
+ QPen pen;
+ WhiteboardColor color = element.getColor();
+ pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ item->setPen(pen);
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardFreehandPathElement& element) {
+ FreehandLineItem *item;
+ if (type_ == GView::New) {
+ item = new FreehandLineItem;
+ } else {
+ item = qgraphicsitem_cast<FreehandLineItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+
+ if (item) {
+ QPen pen;
+ WhiteboardColor color = element.getColor();
+ pen.setColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ item->setPen(pen);
+
+ std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
+ item->setStartPoint(QPointF(it->first, it->second));
+ for (++it; it != element.getPoints().end(); ++it) {
+ item->lineTo(QPointF(it->first, it->second));
+ }
+
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ if (type_ == GView::New) {
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ }
+ }
+
+ void visit(WhiteboardRectElement& element) {
+ QGraphicsRectItem* item;
+ if (type_ == GView::New) {
+ item = new QGraphicsRectItem(element.getX(), element.getY(), element.getWidth(), element.getHeight());
+ graphicsView_->addItem(item, P2QSTRING(element.getID()), pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsRectItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ QRectF rect(element.getX(), element.getY(), element.getWidth(), element.getHeight());
+ item->setRect(rect);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+
+ if (item) {
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardPolygonElement& element) {
+ QGraphicsPolygonItem* item = qgraphicsitem_cast<QGraphicsPolygonItem*>(graphicsView_->getItem(P2QSTRING(element.getID())));
+ if (item == 0 && type_ == GView::New) {
+ item = new QGraphicsPolygonItem();
+ QString id = P2QSTRING(element.getID());
+ item->setData(100, id);
+ graphicsView_->addItem(item, id, pos_);
+ }
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+
+ item->setPos(0,0);
+ QPolygonF polygon;
+ std::vector<std::pair<int, int> >::const_iterator it = element.getPoints().begin();
+ for (; it != element.getPoints().end(); ++it) {
+ polygon.append(QPointF(it->first, it->second));
+ }
+ item->setPolygon(polygon);
+ }
+
+ void visit(WhiteboardTextElement& element) {
+ QGraphicsTextItem* item;
+ QString id = P2QSTRING(element.getID());
+ if (type_ == GView::New) {
+ item = new QGraphicsTextItem;
+ graphicsView_->addItem(item, id, pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsTextItem*>(graphicsView_->getItem(id));
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ if (item) {
+ item->setPlainText(P2QSTRING(element.getText()));
+ item->setPos(QPointF(element.getX(), element.getY()));
+ QFont font = item->font();
+ font.setPointSize(element.getSize());
+ item->setFont(font);
+ WhiteboardColor color = element.getColor();
+ item->setDefaultTextColor(QColor(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()));
+ item->setData(100, id);
+ }
+ }
+
+ void visit(WhiteboardEllipseElement& element) {
+ QRectF rect;
+ QGraphicsEllipseItem* item;
+ QString id = P2QSTRING(element.getID());
+ rect.setTopLeft(QPointF(element.getCX()-element.getRX(), element.getCY()-element.getRY()));
+ rect.setBottomRight(QPointF(element.getCX()+element.getRX(), element.getCY()+element.getRY()));
+ if (type_ == GView::New) {
+ item = new QGraphicsEllipseItem(rect);
+ graphicsView_->addItem(item, id, pos_);
+ } else {
+ item = qgraphicsitem_cast<QGraphicsEllipseItem*>(graphicsView_->getItem(id));
+ item->setRect(rect);
+ item->setPos(0,0);
+ graphicsView_->deselect(P2QSTRING(element.getID()));
+ }
+ QPen pen;
+ QBrush brush(Qt::SolidPattern);
+ WhiteboardColor penColor = element.getPenColor();
+ WhiteboardColor brushColor = element.getBrushColor();
+ pen.setColor(QColor(penColor.getRed(), penColor.getGreen(), penColor.getBlue(), penColor.getAlpha()));
+ pen.setWidth(element.getPenWidth());
+ brush.setColor(QColor(brushColor.getRed(), brushColor.getGreen(), brushColor.getBlue(), brushColor.getAlpha()));
+ item->setPen(pen);
+ item->setBrush(brush);
+ item->setData(100, id);
+ }
+
+ private:
+ GView* graphicsView_;
+ int pos_;
+ GView::Type type_;
+ };
}
diff --git a/Swift/QtUI/WinUIHelpers.cpp b/Swift/QtUI/WinUIHelpers.cpp
index c307937..30f18a6 100644
--- a/Swift/QtUI/WinUIHelpers.cpp
+++ b/Swift/QtUI/WinUIHelpers.cpp
@@ -24,44 +24,44 @@
namespace Swift {
void WinUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- if (chain.empty()) {
- return;
- }
+ 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;
- }
+ // 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();
- boost::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);
- }
+ ByteArray certAsDER = chain[0]->toDER();
+ boost::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);
- }
+ 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);
+ }
- CRYPTUI_VIEWCERTIFICATE_STRUCT viewDialogProperties = { 0 };
- viewDialogProperties.dwSize = sizeof(viewDialogProperties);
- viewDialogProperties.hwndParent = (HWND) parent->winId();
- viewDialogProperties.dwFlags = CRYPTUI_DISABLE_EDITPROPERTIES | CRYPTUI_DISABLE_ADDTOSTORE | CRYPTUI_ENABLE_REVOCATION_CHECKING;
- viewDialogProperties.pCertContext = certificate_chain.get();
- viewDialogProperties.cStores = 1;
- viewDialogProperties.rghStores = &chainStore;
- BOOL properties_changed;
+ CRYPTUI_VIEWCERTIFICATE_STRUCT viewDialogProperties = { 0 };
+ viewDialogProperties.dwSize = sizeof(viewDialogProperties);
+ viewDialogProperties.hwndParent = (HWND) parent->winId();
+ viewDialogProperties.dwFlags = CRYPTUI_DISABLE_EDITPROPERTIES | CRYPTUI_DISABLE_ADDTOSTORE | CRYPTUI_ENABLE_REVOCATION_CHECKING;
+ viewDialogProperties.pCertContext = certificate_chain.get();
+ viewDialogProperties.cStores = 1;
+ viewDialogProperties.rghStores = &chainStore;
+ BOOL properties_changed;
- // blocking call that shows modal certificate dialog
- BOOL rv = ::CryptUIDlgViewCertificate(&viewDialogProperties, &properties_changed);
+ // blocking call that shows modal certificate dialog
+ BOOL rv = ::CryptUIDlgViewCertificate(&viewDialogProperties, &properties_changed);
}
}
diff --git a/Swift/QtUI/WinUIHelpers.h b/Swift/QtUI/WinUIHelpers.h
index 2146cfd..36f5c9e 100644
--- a/Swift/QtUI/WinUIHelpers.h
+++ b/Swift/QtUI/WinUIHelpers.h
@@ -20,7 +20,7 @@ namespace Swift {
class WinUIHelpers {
public:
- static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
+ static void displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain);
};
}
diff --git a/Swift/QtUI/WindowsNotifier.cpp b/Swift/QtUI/WindowsNotifier.cpp
index 1241d8f..c954fab 100644
--- a/Swift/QtUI/WindowsNotifier.cpp
+++ b/Swift/QtUI/WindowsNotifier.cpp
@@ -19,38 +19,38 @@
namespace Swift {
WindowsNotifier::WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray) : tray(tray) {
- notifierWindow = new QtWin32NotifierWindow();
- snarlNotifier = new SnarlNotifier(name, notifierWindow, icon);
- connect(tray, SIGNAL(messageClicked()), SLOT(handleMessageClicked()));
+ notifierWindow = new QtWin32NotifierWindow();
+ snarlNotifier = new SnarlNotifier(name, notifierWindow, icon);
+ connect(tray, SIGNAL(messageClicked()), SLOT(handleMessageClicked()));
}
WindowsNotifier::~WindowsNotifier() {
- delete snarlNotifier;
- delete notifierWindow;
+ delete snarlNotifier;
+ delete notifierWindow;
}
void WindowsNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback) {
- if (snarlNotifier->isAvailable()) {
- snarlNotifier->showMessage(type, subject, description, picture, callback);
- return;
- }
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
- return;
- }
- lastCallback = callback;
- int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
- tray->showMessage(P2QSTRING(subject), P2QSTRING(description), type == SystemMessage ? QSystemTrayIcon::Information : QSystemTrayIcon::NoIcon, timeout * 1000);
+ if (snarlNotifier->isAvailable()) {
+ snarlNotifier->showMessage(type, subject, description, picture, callback);
+ return;
+ }
+ std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
+ if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) {
+ return;
+ }
+ lastCallback = callback;
+ int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS;
+ tray->showMessage(P2QSTRING(subject), P2QSTRING(description), type == SystemMessage ? QSystemTrayIcon::Information : QSystemTrayIcon::NoIcon, timeout * 1000);
}
void WindowsNotifier::handleMessageClicked() {
- if (lastCallback) {
- lastCallback();
- }
+ if (lastCallback) {
+ lastCallback();
+ }
}
void WindowsNotifier::purgeCallbacks() {
- lastCallback = boost::function<void()>();
+ lastCallback = boost::function<void()>();
}
}
diff --git a/Swift/QtUI/WindowsNotifier.h b/Swift/QtUI/WindowsNotifier.h
index 8412b6e..fae0795 100644
--- a/Swift/QtUI/WindowsNotifier.h
+++ b/Swift/QtUI/WindowsNotifier.h
@@ -16,23 +16,23 @@
class QSystemTrayIcon;
namespace Swift {
- class WindowsNotifier : public QObject, public Notifier {
- Q_OBJECT
+ class WindowsNotifier : public QObject, public Notifier {
+ Q_OBJECT
- public:
- WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray);
- ~WindowsNotifier();
+ public:
+ WindowsNotifier(const std::string& name, const boost::filesystem::path& icon, QSystemTrayIcon* tray);
+ ~WindowsNotifier();
- virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
- virtual void purgeCallbacks();
+ virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function<void()> callback);
+ virtual void purgeCallbacks();
- private slots:
- void handleMessageClicked();
+ private slots:
+ void handleMessageClicked();
- private:
- QSystemTrayIcon* tray;
- Win32NotifierWindow* notifierWindow;
- SnarlNotifier* snarlNotifier;
- boost::function<void()> lastCallback;
- };
+ private:
+ QSystemTrayIcon* tray;
+ Win32NotifierWindow* notifierWindow;
+ SnarlNotifier* snarlNotifier;
+ boost::function<void()> lastCallback;
+ };
}
diff --git a/Swift/QtUI/main.cpp b/Swift/QtUI/main.cpp
index 46b3853..86ba931 100644
--- a/Swift/QtUI/main.cpp
+++ b/Swift/QtUI/main.cpp
@@ -33,72 +33,72 @@
#include <Swift/QtUI/QtTranslator.h>
int main(int argc, char* argv[]) {
- Swift::PlatformApplicationPathProvider applicationPathProvider(SWIFT_APPLICATION_NAME);
+ Swift::PlatformApplicationPathProvider applicationPathProvider(SWIFT_APPLICATION_NAME);
- Swift::CrashReporter crashReporter(applicationPathProvider.getDataDir() / "crashes");
+ Swift::CrashReporter crashReporter(applicationPathProvider.getDataDir() / "crashes");
#if QT_VERSION < 0x050000
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
+ QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif
- // Parse program options
- boost::program_options::options_description desc = Swift::QtSwift::getOptionsDescription();
- boost::program_options::variables_map vm;
- try {
- boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
- } catch (const boost::program_options::unknown_option& option) {
+ // Parse program options
+ boost::program_options::options_description desc = Swift::QtSwift::getOptionsDescription();
+ boost::program_options::variables_map vm;
+ try {
+ boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
+ } catch (const boost::program_options::unknown_option& option) {
#if BOOST_VERSION >= 104200
- std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
+ std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl;
#else
- std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
+ std::cout << "Error: " << option.what() << " (continuing)" << std::endl;
#endif
- }
- boost::program_options::notify(vm);
- if (vm.count("help") > 0) {
- std::cout << SWIFT_APPLICATION_NAME << " is an instant messaging client for the XMPP network." << std::endl;
- std::cout << std::endl;
- std::cout << "Usage: " << argv[0] << " [OPTIONS]..." << std::endl;
- std::cout << std::endl;
- std::cout << desc << std::endl;
- return 1;
- }
- if (vm.count("version") > 0) {
- std::cout << SWIFT_APPLICATION_NAME << " " << buildVersion << std::endl;
- return 0;
- }
-
- // Translation
+ }
+ boost::program_options::notify(vm);
+ if (vm.count("help") > 0) {
+ std::cout << SWIFT_APPLICATION_NAME << " is an instant messaging client for the XMPP network." << std::endl;
+ std::cout << std::endl;
+ std::cout << "Usage: " << argv[0] << " [OPTIONS]..." << std::endl;
+ std::cout << std::endl;
+ std::cout << desc << std::endl;
+ return 1;
+ }
+ if (vm.count("version") > 0) {
+ std::cout << SWIFT_APPLICATION_NAME << " " << buildVersion << std::endl;
+ return 0;
+ }
+
+ // Translation
#if QT_VERSION < 0x050000
- QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
+ QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif
- boost::filesystem::path someTranslationPath = applicationPathProvider.getResourcePath("/translations/swift_en.qm");
+ boost::filesystem::path someTranslationPath = applicationPathProvider.getResourcePath("/translations/swift_en.qm");
- QTranslator qtTranslator;
- if (!someTranslationPath.empty()) {
+ QTranslator qtTranslator;
+ if (!someTranslationPath.empty()) {
#if QT_VERSION >= 0x040800
- if (vm.count("language") > 0) {
- qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + P2QSTRING(vm["language"].as<std::string>()), P2QSTRING(Swift::pathToString(someTranslationPath.parent_path())));
- }
- else {
- qtTranslator.load(QLocale::system(), QString(SWIFT_APPLICATION_NAME).toLower(), "_", P2QSTRING(Swift::pathToString(someTranslationPath)));
- }
+ if (vm.count("language") > 0) {
+ qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + P2QSTRING(vm["language"].as<std::string>()), P2QSTRING(Swift::pathToString(someTranslationPath.parent_path())));
+ }
+ else {
+ qtTranslator.load(QLocale::system(), QString(SWIFT_APPLICATION_NAME).toLower(), "_", P2QSTRING(Swift::pathToString(someTranslationPath)));
+ }
#else
- //std::cout << "Loading " << std::string(QLocale::system().name().toUtf8()) << std::endl;
- qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + QLocale::system().name(), P2QSTRING(Swift::pathToString(someTranslationPath)));
+ //std::cout << "Loading " << std::string(QLocale::system().name().toUtf8()) << std::endl;
+ qtTranslator.load(QString(SWIFT_APPLICATION_NAME).toLower() + "_" + QLocale::system().name(), P2QSTRING(Swift::pathToString(someTranslationPath)));
#endif
- }
+ }
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
- app.installTranslator(&qtTranslator);
- QtTranslator swiftTranslator;
- Swift::Translator::setInstance(&swiftTranslator);
+ app.installTranslator(&qtTranslator);
+ QtTranslator swiftTranslator;
+ Swift::Translator::setInstance(&swiftTranslator);
- Swift::QtSwift swift(vm);
- int result = app.exec();
+ Swift::QtSwift swift(vm);
+ int result = app.exec();
- Swift::Translator::setInstance(NULL);
+ Swift::Translator::setInstance(NULL);
- return result;
+ return result;
}
diff --git a/Swift/QtUI/swift-open-uri.cpp b/Swift/QtUI/swift-open-uri.cpp
index 735cf5e..23a8851 100644
--- a/Swift/QtUI/swift-open-uri.cpp
+++ b/Swift/QtUI/swift-open-uri.cpp
@@ -11,21 +11,21 @@
#include <QDBusMessage>
int main(int argc, char* argv[]) {
- QCoreApplication app(argc, argv);
+ QCoreApplication app(argc, argv);
- QDBusConnection bus = QDBusConnection::sessionBus();
- if (!bus.isConnected()) {
- return -1;
- }
- if (argc != 2) {
- std::cerr << "Usage: " << argv[0] << " uri" << std::endl;
- return -1;
- }
+ QDBusConnection bus = QDBusConnection::sessionBus();
+ if (!bus.isConnected()) {
+ return -1;
+ }
+ if (argc != 2) {
+ std::cerr << "Usage: " << argv[0] << " uri" << std::endl;
+ return -1;
+ }
- QDBusMessage msg = QDBusMessage::createMethodCall("im.swift.Swift.URIHandler", "/", "im.swift.Swift.URIHandler", "openURI");
- msg << argv[1];
+ QDBusMessage msg = QDBusMessage::createMethodCall("im.swift.Swift.URIHandler", "/", "im.swift.Swift.URIHandler", "openURI");
+ msg << argv[1];
- bus.call(msg);
+ bus.call(msg);
- return 0;
+ return 0;
}
diff --git a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
index a1f3d4c..1cdf467 100644
--- a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
+++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
@@ -18,83 +18,83 @@ OutgoingAdHocCommandSession::OutgoingAdHocCommandSession(const JID& to, const st
}
OutgoingAdHocCommandSession::~OutgoingAdHocCommandSession() {
- connection_.disconnect();
+ connection_.disconnect();
}
void OutgoingAdHocCommandSession::handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error) {
- if (error) {
- onError(error);
- } else {
- const std::vector<Command::Action>& actions = payload->getAvailableActions();
- actionStates_.clear();
- if (payload->getStatus() == Command::Executing ) {
- actionStates_[Command::Cancel] = EnabledAndPresent;
- actionStates_[Command::Complete] = Present;
- if (std::find(actions.begin(), actions.end(), Command::Complete) != actions.end()) {
- actionStates_[Command::Complete] = EnabledAndPresent;
- }
-
- if (getIsMultiStage()) {
- actionStates_[Command::Next] = Present;
- actionStates_[Command::Prev] = Present;
- }
-
- if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()) {
- actionStates_[Command::Next] = EnabledAndPresent;
- }
- if (std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) {
- actionStates_[Command::Prev] = EnabledAndPresent;
- }
- }
-
- sessionID_ = payload->getSessionID();
- if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()
- || std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) {
- isMultiStage_ = true;
- }
- onNextStageReceived(payload);
- }
+ if (error) {
+ onError(error);
+ } else {
+ const std::vector<Command::Action>& actions = payload->getAvailableActions();
+ actionStates_.clear();
+ if (payload->getStatus() == Command::Executing ) {
+ actionStates_[Command::Cancel] = EnabledAndPresent;
+ actionStates_[Command::Complete] = Present;
+ if (std::find(actions.begin(), actions.end(), Command::Complete) != actions.end()) {
+ actionStates_[Command::Complete] = EnabledAndPresent;
+ }
+
+ if (getIsMultiStage()) {
+ actionStates_[Command::Next] = Present;
+ actionStates_[Command::Prev] = Present;
+ }
+
+ if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()) {
+ actionStates_[Command::Next] = EnabledAndPresent;
+ }
+ if (std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) {
+ actionStates_[Command::Prev] = EnabledAndPresent;
+ }
+ }
+
+ sessionID_ = payload->getSessionID();
+ if (std::find(actions.begin(), actions.end(), Command::Next) != actions.end()
+ || std::find(actions.begin(), actions.end(), Command::Prev) != actions.end()) {
+ isMultiStage_ = true;
+ }
+ onNextStageReceived(payload);
+ }
}
bool OutgoingAdHocCommandSession::getIsMultiStage() const {
- return isMultiStage_;
+ return isMultiStage_;
}
void OutgoingAdHocCommandSession::start() {
- boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, boost::make_shared<Command>(commandNode_), iqRouter_);
- connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2));
- commandRequest->send();
+ boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, boost::make_shared<Command>(commandNode_), iqRouter_);
+ connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2));
+ commandRequest->send();
}
void OutgoingAdHocCommandSession::cancel() {
- if (!sessionID_.empty()) {
- submitForm(Form::ref(), Command::Cancel);
- }
+ if (!sessionID_.empty()) {
+ submitForm(Form::ref(), Command::Cancel);
+ }
}
void OutgoingAdHocCommandSession::goBack() {
- submitForm(Form::ref(), Command::Prev);
+ submitForm(Form::ref(), Command::Prev);
}
void OutgoingAdHocCommandSession::complete(Form::ref form) {
- submitForm(form, Command::Complete);
+ submitForm(form, Command::Complete);
}
void OutgoingAdHocCommandSession::goNext(Form::ref form) {
- submitForm(form, Command::Next);
+ submitForm(form, Command::Next);
}
void OutgoingAdHocCommandSession::submitForm(Form::ref form, Command::Action action) {
- boost::shared_ptr<Command> command(boost::make_shared<Command>(commandNode_, sessionID_, action));
- command->setForm(form);
- boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, command, iqRouter_);
- connection_.disconnect();
- connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2));
- commandRequest->send();
+ boost::shared_ptr<Command> command(boost::make_shared<Command>(commandNode_, sessionID_, action));
+ command->setForm(form);
+ boost::shared_ptr<GenericRequest<Command> > commandRequest = boost::make_shared< GenericRequest<Command> >(IQ::Set, to_, command, iqRouter_);
+ connection_.disconnect();
+ connection_ = commandRequest->onResponse.connect(boost::bind(&OutgoingAdHocCommandSession::handleResponse, this, _1, _2));
+ commandRequest->send();
}
OutgoingAdHocCommandSession::ActionState OutgoingAdHocCommandSession::getActionState(Command::Action action) const {
- return get(actionStates_, action, Absent);
+ return get(actionStates_, action, Absent);
}
}
diff --git a/Swiften/AdHoc/OutgoingAdHocCommandSession.h b/Swiften/AdHoc/OutgoingAdHocCommandSession.h
index 73dc7a1..fdb6e35 100644
--- a/Swiften/AdHoc/OutgoingAdHocCommandSession.h
+++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.h
@@ -18,82 +18,82 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class IQRouter;
- class MainWindow;
- class UIEventStream;
+ class IQRouter;
+ class MainWindow;
+ class UIEventStream;
- class SWIFTEN_API OutgoingAdHocCommandSession {
- public:
+ class SWIFTEN_API OutgoingAdHocCommandSession {
+ public:
- /**
- * Availability of action.
- */
- enum ActionState {
- Absent /** Action isn't applicable to this command. */ = 0,
- Present /** Action is applicable to this command */= 1,
- Enabled /** Action is applicable and currently available */ = 2,
- EnabledAndPresent = 3};
+ /**
+ * Availability of action.
+ */
+ enum ActionState {
+ Absent /** Action isn't applicable to this command. */ = 0,
+ Present /** Action is applicable to this command */= 1,
+ Enabled /** Action is applicable and currently available */ = 2,
+ EnabledAndPresent = 3};
- OutgoingAdHocCommandSession(const JID& to, const std::string& commandNode, IQRouter* iqRouter);
- ~OutgoingAdHocCommandSession();
- /**
- * Send initial request to the target.
- */
- void start();
- /**
- * Cancel command session with the target.
- */
- void cancel();
- /**
- * Return to the previous stage.
- */
- void goBack();
- /**
- * Send the form to complete the command.
- * \param form Form for submission - if missing the command will be submitted with no form.
- */
- void complete(Form::ref form);
- /**
- * Send the form to advance to the next stage of the command.
- * \param form Form for submission - if missing the command will be submitted with no form.
- */
- void goNext(Form::ref form);
+ OutgoingAdHocCommandSession(const JID& to, const std::string& commandNode, IQRouter* iqRouter);
+ ~OutgoingAdHocCommandSession();
+ /**
+ * Send initial request to the target.
+ */
+ void start();
+ /**
+ * Cancel command session with the target.
+ */
+ void cancel();
+ /**
+ * Return to the previous stage.
+ */
+ void goBack();
+ /**
+ * Send the form to complete the command.
+ * \param form Form for submission - if missing the command will be submitted with no form.
+ */
+ void complete(Form::ref form);
+ /**
+ * Send the form to advance to the next stage of the command.
+ * \param form Form for submission - if missing the command will be submitted with no form.
+ */
+ void goNext(Form::ref form);
- /**
- * Is the form multi-stage?
- */
- bool getIsMultiStage() const;
+ /**
+ * Is the form multi-stage?
+ */
+ bool getIsMultiStage() const;
- /**
- * Emitted when the form for the next stage is available.
- */
- boost::signal<void (Command::ref)> onNextStageReceived;
+ /**
+ * Emitted when the form for the next stage is available.
+ */
+ boost::signal<void (Command::ref)> onNextStageReceived;
- /**
- * Emitted on error.
- */
- boost::signal<void (ErrorPayload::ref)> onError;
+ /**
+ * Emitted on error.
+ */
+ boost::signal<void (ErrorPayload::ref)> onError;
- /**
- * Get the state of a given action.
- * This is useful for a UI to determine which buttons should be visible,
- * and which enabled.
- * Use for Next, Prev, Cancel and Complete only.
- * If no actions are available, the command has completed.
- */
- ActionState getActionState(Command::Action action) const;
+ /**
+ * Get the state of a given action.
+ * This is useful for a UI to determine which buttons should be visible,
+ * and which enabled.
+ * Use for Next, Prev, Cancel and Complete only.
+ * If no actions are available, the command has completed.
+ */
+ ActionState getActionState(Command::Action action) const;
- private:
- void handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error);
- void submitForm(Form::ref, Command::Action action);
+ private:
+ void handleResponse(boost::shared_ptr<Command> payload, ErrorPayload::ref error);
+ void submitForm(Form::ref, Command::Action action);
- private:
- JID to_;
- std::string commandNode_;
- IQRouter* iqRouter_;
- bool isMultiStage_;
- std::string sessionID_;
- std::map<Command::Action, ActionState> actionStates_;
- boost::bsignals::connection connection_;
- };
+ private:
+ JID to_;
+ std::string commandNode_;
+ IQRouter* iqRouter_;
+ bool isMultiStage_;
+ std::string sessionID_;
+ std::map<Command::Action, ActionState> actionStates_;
+ boost::bsignals::connection connection_;
+ };
}
diff --git a/Swiften/Avatars/AvatarManager.h b/Swiften/Avatars/AvatarManager.h
index 20b4725..ffd6608 100644
--- a/Swiften/Avatars/AvatarManager.h
+++ b/Swiften/Avatars/AvatarManager.h
@@ -13,15 +13,15 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class JID;
+ class JID;
- class SWIFTEN_API AvatarManager {
- public:
- virtual ~AvatarManager();
+ class SWIFTEN_API AvatarManager {
+ public:
+ virtual ~AvatarManager();
- virtual ByteArray getAvatar(const JID&) const = 0;
- virtual boost::filesystem::path getAvatarPath(const JID&) const = 0;
+ virtual ByteArray getAvatar(const JID&) const = 0;
+ virtual boost::filesystem::path getAvatarPath(const JID&) const = 0;
- boost::signal<void (const JID&)> onAvatarChanged;
- };
+ boost::signal<void (const JID&)> onAvatarChanged;
+ };
}
diff --git a/Swiften/Avatars/AvatarManagerImpl.cpp b/Swiften/Avatars/AvatarManagerImpl.cpp
index f15c16c..6e98b1b 100644
--- a/Swiften/Avatars/AvatarManagerImpl.cpp
+++ b/Swiften/Avatars/AvatarManagerImpl.cpp
@@ -17,50 +17,50 @@
namespace Swift {
AvatarManagerImpl::AvatarManagerImpl(VCardManager* vcardManager, StanzaChannel* stanzaChannel, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : avatarStorage(avatarStorage) {
- vcardUpdateAvatarManager = new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto, mucRegistry);
- combinedAvatarProvider.addProvider(vcardUpdateAvatarManager);
+ vcardUpdateAvatarManager = new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto, mucRegistry);
+ combinedAvatarProvider.addProvider(vcardUpdateAvatarManager);
- vcardAvatarManager = new VCardAvatarManager(vcardManager, avatarStorage, crypto, mucRegistry);
- combinedAvatarProvider.addProvider(vcardAvatarManager);
+ vcardAvatarManager = new VCardAvatarManager(vcardManager, avatarStorage, crypto, mucRegistry);
+ combinedAvatarProvider.addProvider(vcardAvatarManager);
- offlineAvatarManager = new OfflineAvatarManager(avatarStorage);
- combinedAvatarProvider.addProvider(offlineAvatarManager);
+ offlineAvatarManager = new OfflineAvatarManager(avatarStorage);
+ combinedAvatarProvider.addProvider(offlineAvatarManager);
- combinedAvatarProvider.onAvatarChanged.connect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1));
+ combinedAvatarProvider.onAvatarChanged.connect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1));
}
AvatarManagerImpl::~AvatarManagerImpl() {
- combinedAvatarProvider.onAvatarChanged.disconnect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1));
+ combinedAvatarProvider.onAvatarChanged.disconnect(boost::bind(&AvatarManagerImpl::handleCombinedAvatarChanged, this, _1));
- combinedAvatarProvider.removeProvider(offlineAvatarManager);
- delete offlineAvatarManager;
- combinedAvatarProvider.removeProvider(vcardAvatarManager);
- delete vcardAvatarManager;
- combinedAvatarProvider.removeProvider(vcardUpdateAvatarManager);
- delete vcardUpdateAvatarManager;
+ combinedAvatarProvider.removeProvider(offlineAvatarManager);
+ delete offlineAvatarManager;
+ combinedAvatarProvider.removeProvider(vcardAvatarManager);
+ delete vcardAvatarManager;
+ combinedAvatarProvider.removeProvider(vcardUpdateAvatarManager);
+ delete vcardUpdateAvatarManager;
}
boost::filesystem::path AvatarManagerImpl::getAvatarPath(const JID& jid) const {
- boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
- if (hash && !hash->empty()) {
- return avatarStorage->getAvatarPath(*hash);
- }
- return boost::filesystem::path();
+ boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
+ if (hash && !hash->empty()) {
+ return avatarStorage->getAvatarPath(*hash);
+ }
+ return boost::filesystem::path();
}
ByteArray AvatarManagerImpl::getAvatar(const JID& jid) const {
- boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
- if (hash && !hash->empty()) {
- return avatarStorage->getAvatar(*hash);
- }
- return ByteArray();
+ boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
+ if (hash && !hash->empty()) {
+ return avatarStorage->getAvatar(*hash);
+ }
+ return ByteArray();
}
void AvatarManagerImpl::handleCombinedAvatarChanged(const JID& jid) {
- boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
- assert(hash);
- offlineAvatarManager->setAvatar(jid, *hash);
- onAvatarChanged(jid);
+ boost::optional<std::string> hash = combinedAvatarProvider.getAvatarHash(jid);
+ assert(hash);
+ offlineAvatarManager->setAvatar(jid, *hash);
+ onAvatarChanged(jid);
}
}
diff --git a/Swiften/Avatars/AvatarManagerImpl.h b/Swiften/Avatars/AvatarManagerImpl.h
index 69af924..7176c25 100644
--- a/Swiften/Avatars/AvatarManagerImpl.h
+++ b/Swiften/Avatars/AvatarManagerImpl.h
@@ -10,32 +10,32 @@
#include <Swiften/Avatars/CombinedAvatarProvider.h>
namespace Swift {
- class MUCRegistry;
- class AvatarStorage;
- class StanzaChannel;
- class VCardManager;
- class VCardUpdateAvatarManager;
- class VCardAvatarManager;
- class OfflineAvatarManager;
- class CryptoProvider;
-
- class AvatarManagerImpl : public AvatarManager {
- public:
- AvatarManagerImpl(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
- virtual ~AvatarManagerImpl();
-
- virtual boost::filesystem::path getAvatarPath(const JID&) const;
- virtual ByteArray getAvatar(const JID&) const;
-
- private:
- void handleCombinedAvatarChanged(const JID& jid);
-
-
- private:
- CombinedAvatarProvider combinedAvatarProvider;
- AvatarStorage* avatarStorage;
- VCardUpdateAvatarManager* vcardUpdateAvatarManager;
- VCardAvatarManager* vcardAvatarManager;
- OfflineAvatarManager* offlineAvatarManager;
- };
+ class MUCRegistry;
+ class AvatarStorage;
+ class StanzaChannel;
+ class VCardManager;
+ class VCardUpdateAvatarManager;
+ class VCardAvatarManager;
+ class OfflineAvatarManager;
+ class CryptoProvider;
+
+ class AvatarManagerImpl : public AvatarManager {
+ public:
+ AvatarManagerImpl(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
+ virtual ~AvatarManagerImpl();
+
+ virtual boost::filesystem::path getAvatarPath(const JID&) const;
+ virtual ByteArray getAvatar(const JID&) const;
+
+ private:
+ void handleCombinedAvatarChanged(const JID& jid);
+
+
+ private:
+ CombinedAvatarProvider combinedAvatarProvider;
+ AvatarStorage* avatarStorage;
+ VCardUpdateAvatarManager* vcardUpdateAvatarManager;
+ VCardAvatarManager* vcardAvatarManager;
+ OfflineAvatarManager* offlineAvatarManager;
+ };
}
diff --git a/Swiften/Avatars/AvatarMemoryStorage.h b/Swiften/Avatars/AvatarMemoryStorage.h
index 7a4bdd3..bc40a26 100644
--- a/Swiften/Avatars/AvatarMemoryStorage.h
+++ b/Swiften/Avatars/AvatarMemoryStorage.h
@@ -15,30 +15,30 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API AvatarMemoryStorage : public AvatarStorage {
- public:
- virtual bool hasAvatar(const std::string& hash) const { return avatars.find(hash) != avatars.end(); }
- virtual void addAvatar(const std::string& hash, const ByteArray& avatar) { avatars[hash] = avatar; }
- virtual ByteArray getAvatar(const std::string& hash) const {
- std::map<std::string, ByteArray>::const_iterator i = avatars.find(hash);
- return i == avatars.end() ? ByteArray() : i->second;
- }
-
- virtual boost::filesystem::path getAvatarPath(const std::string& hash) const {
- return boost::filesystem::path("/avatars") / hash;
- }
-
- virtual void setAvatarForJID(const JID& jid, const std::string& hash) {
- jidAvatars[jid] = hash;
- }
-
- virtual std::string getAvatarForJID(const JID& jid) const {
- std::map<JID, std::string>::const_iterator i = jidAvatars.find(jid);
- return i == jidAvatars.end() ? "" : i->second;
- }
-
- private:
- std::map<std::string, ByteArray> avatars;
- std::map<JID, std::string> jidAvatars;
- };
+ class SWIFTEN_API AvatarMemoryStorage : public AvatarStorage {
+ public:
+ virtual bool hasAvatar(const std::string& hash) const { return avatars.find(hash) != avatars.end(); }
+ virtual void addAvatar(const std::string& hash, const ByteArray& avatar) { avatars[hash] = avatar; }
+ virtual ByteArray getAvatar(const std::string& hash) const {
+ std::map<std::string, ByteArray>::const_iterator i = avatars.find(hash);
+ return i == avatars.end() ? ByteArray() : i->second;
+ }
+
+ virtual boost::filesystem::path getAvatarPath(const std::string& hash) const {
+ return boost::filesystem::path("/avatars") / hash;
+ }
+
+ virtual void setAvatarForJID(const JID& jid, const std::string& hash) {
+ jidAvatars[jid] = hash;
+ }
+
+ virtual std::string getAvatarForJID(const JID& jid) const {
+ std::map<JID, std::string>::const_iterator i = jidAvatars.find(jid);
+ return i == jidAvatars.end() ? "" : i->second;
+ }
+
+ private:
+ std::map<std::string, ByteArray> avatars;
+ std::map<JID, std::string> jidAvatars;
+ };
}
diff --git a/Swiften/Avatars/AvatarProvider.h b/Swiften/Avatars/AvatarProvider.h
index 8289ecd..77d9cba 100644
--- a/Swiften/Avatars/AvatarProvider.h
+++ b/Swiften/Avatars/AvatarProvider.h
@@ -12,14 +12,14 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class JID;
+ class JID;
- class SWIFTEN_API AvatarProvider {
- public:
- virtual ~AvatarProvider();
+ class SWIFTEN_API AvatarProvider {
+ public:
+ virtual ~AvatarProvider();
- virtual boost::optional<std::string> getAvatarHash(const JID&) const = 0;
+ virtual boost::optional<std::string> getAvatarHash(const JID&) const = 0;
- boost::signal<void (const JID&)> onAvatarChanged;
- };
+ boost::signal<void (const JID&)> onAvatarChanged;
+ };
}
diff --git a/Swiften/Avatars/AvatarStorage.h b/Swiften/Avatars/AvatarStorage.h
index 2885dd0..dc3eb34 100644
--- a/Swiften/Avatars/AvatarStorage.h
+++ b/Swiften/Avatars/AvatarStorage.h
@@ -14,19 +14,19 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- class JID;
+ class JID;
- class SWIFTEN_API AvatarStorage {
- public:
- virtual ~AvatarStorage();
+ class SWIFTEN_API AvatarStorage {
+ public:
+ virtual ~AvatarStorage();
- virtual bool hasAvatar(const std::string& hash) const = 0;
- virtual void addAvatar(const std::string& hash, const ByteArray& avatar) = 0;
- virtual ByteArray getAvatar(const std::string& hash) const = 0;
- virtual boost::filesystem::path getAvatarPath(const std::string& hash) const = 0;
+ virtual bool hasAvatar(const std::string& hash) const = 0;
+ virtual void addAvatar(const std::string& hash, const ByteArray& avatar) = 0;
+ virtual ByteArray getAvatar(const std::string& hash) const = 0;
+ virtual boost::filesystem::path getAvatarPath(const std::string& hash) const = 0;
- virtual void setAvatarForJID(const JID& jid, const std::string& hash) = 0;
- virtual std::string getAvatarForJID(const JID& jid) const = 0;
- };
+ virtual void setAvatarForJID(const JID& jid, const std::string& hash) = 0;
+ virtual std::string getAvatarForJID(const JID& jid) const = 0;
+ };
}
diff --git a/Swiften/Avatars/CombinedAvatarProvider.cpp b/Swiften/Avatars/CombinedAvatarProvider.cpp
index 896346f..465512f 100644
--- a/Swiften/Avatars/CombinedAvatarProvider.cpp
+++ b/Swiften/Avatars/CombinedAvatarProvider.cpp
@@ -15,48 +15,48 @@
namespace Swift {
boost::optional<std::string> CombinedAvatarProvider::getAvatarHash(const JID& jid) const {
- return getCombinedAvatarAndCache(jid);
+ return getCombinedAvatarAndCache(jid);
}
void CombinedAvatarProvider::addProvider(AvatarProvider* provider) {
- provider->onAvatarChanged.connect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1));
- providers.push_back(provider);
+ provider->onAvatarChanged.connect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1));
+ providers.push_back(provider);
}
void CombinedAvatarProvider::removeProvider(AvatarProvider* provider) {
- std::vector<AvatarProvider*>::iterator i = std::remove(providers.begin(), providers.end(), provider);
- for(std::vector<AvatarProvider*>::iterator j = i; j < providers.end(); ++j) {
- provider->onAvatarChanged.disconnect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1));
- }
- providers.erase(i, providers.end());
+ std::vector<AvatarProvider*>::iterator i = std::remove(providers.begin(), providers.end(), provider);
+ for(std::vector<AvatarProvider*>::iterator j = i; j < providers.end(); ++j) {
+ provider->onAvatarChanged.disconnect(boost::bind(&CombinedAvatarProvider::handleAvatarChanged, this, _1));
+ }
+ providers.erase(i, providers.end());
}
void CombinedAvatarProvider::handleAvatarChanged(const JID& jid) {
- std::string oldHash;
- std::map<JID, std::string>::const_iterator i = avatars.find(jid);
- if (i != avatars.end()) {
- oldHash = i->second;
- }
- boost::optional<std::string> newHash = getCombinedAvatarAndCache(jid);
- if (newHash != oldHash) {
- SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL") << std::endl;
- onAvatarChanged(jid);
- }
+ std::string oldHash;
+ std::map<JID, std::string>::const_iterator i = avatars.find(jid);
+ if (i != avatars.end()) {
+ oldHash = i->second;
+ }
+ boost::optional<std::string> newHash = getCombinedAvatarAndCache(jid);
+ if (newHash != oldHash) {
+ SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL") << std::endl;
+ onAvatarChanged(jid);
+ }
}
boost::optional<std::string> CombinedAvatarProvider::getCombinedAvatarAndCache(const JID& jid) const {
- SWIFT_LOG(debug) << "JID: " << jid << std::endl;
- boost::optional<std::string> hash;
- for (size_t i = 0; i < providers.size() && !hash; ++i) {
- hash = providers[i]->getAvatarHash(jid);
- SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL") << std::endl;
- }
- if (hash) {
- avatars[jid] = *hash;
- } else {
- avatars[jid] = "";
- }
- return hash;
+ SWIFT_LOG(debug) << "JID: " << jid << std::endl;
+ boost::optional<std::string> hash;
+ for (size_t i = 0; i < providers.size() && !hash; ++i) {
+ hash = providers[i]->getAvatarHash(jid);
+ SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL") << std::endl;
+ }
+ if (hash) {
+ avatars[jid] = *hash;
+ } else {
+ avatars[jid] = "";
+ }
+ return hash;
}
}
diff --git a/Swiften/Avatars/CombinedAvatarProvider.h b/Swiften/Avatars/CombinedAvatarProvider.h
index c458514..f667ad2 100644
--- a/Swiften/Avatars/CombinedAvatarProvider.h
+++ b/Swiften/Avatars/CombinedAvatarProvider.h
@@ -14,19 +14,19 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API CombinedAvatarProvider : public AvatarProvider {
- public:
- virtual boost::optional<std::string> getAvatarHash(const JID&) const;
+ class SWIFTEN_API CombinedAvatarProvider : public AvatarProvider {
+ public:
+ virtual boost::optional<std::string> getAvatarHash(const JID&) const;
- void addProvider(AvatarProvider*);
- void removeProvider(AvatarProvider*);
+ void addProvider(AvatarProvider*);
+ void removeProvider(AvatarProvider*);
- private:
- void handleAvatarChanged(const JID&);
- boost::optional<std::string> getCombinedAvatarAndCache(const JID&) const;
+ private:
+ void handleAvatarChanged(const JID&);
+ boost::optional<std::string> getCombinedAvatarAndCache(const JID&) const;
- private:
- std::vector<AvatarProvider*> providers;
- mutable std::map<JID, std::string> avatars;
- };
+ private:
+ std::vector<AvatarProvider*> providers;
+ mutable std::map<JID, std::string> avatars;
+ };
}
diff --git a/Swiften/Avatars/DummyAvatarManager.h b/Swiften/Avatars/DummyAvatarManager.h
index 7d0793c..f079be1 100644
--- a/Swiften/Avatars/DummyAvatarManager.h
+++ b/Swiften/Avatars/DummyAvatarManager.h
@@ -12,22 +12,22 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class DummyAvatarManager : public AvatarManager {
- public:
- virtual boost::filesystem::path getAvatarPath(const JID& j) const {
- return boost::filesystem::path("/avatars") / j.toString();
- }
+ class DummyAvatarManager : public AvatarManager {
+ public:
+ virtual boost::filesystem::path getAvatarPath(const JID& j) const {
+ return boost::filesystem::path("/avatars") / j.toString();
+ }
- virtual ByteArray getAvatar(const JID& jid) const {
- std::map<JID, ByteArray>::const_iterator i = avatars.find(jid);
- if (i != avatars.end()) {
- return i->second;
- }
- else {
- return ByteArray();
- }
- }
+ virtual ByteArray getAvatar(const JID& jid) const {
+ std::map<JID, ByteArray>::const_iterator i = avatars.find(jid);
+ if (i != avatars.end()) {
+ return i->second;
+ }
+ else {
+ return ByteArray();
+ }
+ }
- std::map<JID, ByteArray> avatars;
- };
+ std::map<JID, ByteArray> avatars;
+ };
}
diff --git a/Swiften/Avatars/NullAvatarManager.h b/Swiften/Avatars/NullAvatarManager.h
index e9f3028..adc1acc 100644
--- a/Swiften/Avatars/NullAvatarManager.h
+++ b/Swiften/Avatars/NullAvatarManager.h
@@ -9,14 +9,14 @@
#include <Swiften/Avatars/AvatarManager.h>
namespace Swift {
- class NullAvatarManager : public AvatarManager {
- public:
- virtual boost::filesystem::path getAvatarPath(const JID&) const {
- return boost::filesystem::path();
- }
+ class NullAvatarManager : public AvatarManager {
+ public:
+ virtual boost::filesystem::path getAvatarPath(const JID&) const {
+ return boost::filesystem::path();
+ }
- virtual ByteArray getAvatar(const JID&) const {
- return ByteArray();
- }
- };
+ virtual ByteArray getAvatar(const JID&) const {
+ return ByteArray();
+ }
+ };
}
diff --git a/Swiften/Avatars/OfflineAvatarManager.cpp b/Swiften/Avatars/OfflineAvatarManager.cpp
index d462f08..e2468e6 100644
--- a/Swiften/Avatars/OfflineAvatarManager.cpp
+++ b/Swiften/Avatars/OfflineAvatarManager.cpp
@@ -19,14 +19,14 @@ OfflineAvatarManager::~OfflineAvatarManager() {
}
boost::optional<std::string> OfflineAvatarManager::getAvatarHash(const JID& jid) const {
- return avatarStorage->getAvatarForJID(jid);
+ return avatarStorage->getAvatarForJID(jid);
}
void OfflineAvatarManager::setAvatar(const JID& jid, const std::string& hash) {
- if (getAvatarHash(jid) != hash) {
- avatarStorage->setAvatarForJID(jid, hash);
- onAvatarChanged(jid);
- }
+ if (getAvatarHash(jid) != hash) {
+ avatarStorage->setAvatarForJID(jid, hash);
+ onAvatarChanged(jid);
+ }
}
}
diff --git a/Swiften/Avatars/OfflineAvatarManager.h b/Swiften/Avatars/OfflineAvatarManager.h
index 22345ae..11b1d5f 100644
--- a/Swiften/Avatars/OfflineAvatarManager.h
+++ b/Swiften/Avatars/OfflineAvatarManager.h
@@ -10,17 +10,17 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class AvatarStorage;
+ class AvatarStorage;
- class SWIFTEN_API OfflineAvatarManager : public AvatarProvider {
- public:
- OfflineAvatarManager(AvatarStorage*);
- ~OfflineAvatarManager();
+ class SWIFTEN_API OfflineAvatarManager : public AvatarProvider {
+ public:
+ OfflineAvatarManager(AvatarStorage*);
+ ~OfflineAvatarManager();
- virtual boost::optional<std::string> getAvatarHash(const JID&) const;
- void setAvatar(const JID&, const std::string& hash);
+ virtual boost::optional<std::string> getAvatarHash(const JID&) const;
+ void setAvatar(const JID&, const std::string& hash);
- private:
- AvatarStorage* avatarStorage;
- };
+ private:
+ AvatarStorage* avatarStorage;
+ };
}
diff --git a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
index d3004cd..79769a8 100644
--- a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
+++ b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
@@ -31,113 +31,113 @@
using namespace Swift;
class AvatarManagerImplTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(AvatarManagerImplTest);
- CPPUNIT_TEST(testGetSetAvatar);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- ownerJID = JID("owner@domain.com/theowner");
- stanzaChannel = boost::make_shared<DummyStanzaChannel>();
- iqRouter = boost::make_shared<IQRouter>(stanzaChannel.get());
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- vcardStorage = boost::make_shared<VCardMemoryStorage>(crypto.get());
- vcardManager = boost::make_shared<VCardManager>(ownerJID, iqRouter.get(), vcardStorage.get());
- avatarStorage = boost::make_shared<AvatarMemoryStorage>();
- mucRegistry = boost::make_shared<DummyMUCRegistry>();
- avatarManager = boost::make_shared<AvatarManagerImpl>(vcardManager.get(), stanzaChannel.get(), avatarStorage.get(), crypto.get(), mucRegistry.get());
- }
-
- void testGetSetAvatar() {
- /* initially we have no knowledge of the user or their avatar */
- JID personJID("person@domain.com/theperson");
- ByteArray avatar = avatarManager->getAvatar(personJID.toBare());
- CPPUNIT_ASSERT(!avatar.size());
-
- /* notify the 'owner' JID that our avatar has changed */
-
- ByteArray fullAvatar = createByteArray("abcdefg");
- boost::shared_ptr<VCardUpdate> vcardUpdate = boost::make_shared<VCardUpdate>();
- vcardUpdate->setPhotoHash(Hexify::hexify(crypto->getSHA1Hash(fullAvatar)));
- boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
- presence->setTo(ownerJID);
- presence->setFrom(personJID);
- presence->setType(Presence::Available);
- presence->addPayload(vcardUpdate);
- stanzaChannel->onPresenceReceived(presence);
-
- /* reply to the avatar request with our new avatar */
-
- CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
- boost::shared_ptr<IQ> request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]);
- stanzaChannel->sentStanzas.pop_back();
- CPPUNIT_ASSERT(!!request);
- boost::shared_ptr<VCard> vcard = request->getPayload<VCard>();
- CPPUNIT_ASSERT(!!vcard);
-
- boost::shared_ptr<IQ> reply = boost::make_shared<IQ>(IQ::Result);
- reply->setTo(request->getFrom());
- reply->setFrom(request->getTo());
- reply->setID(request->getID());
- vcard->setPhoto(fullAvatar);
- reply->addPayload(vcard);
- stanzaChannel->onIQReceived(reply);
-
- /* check hash through avatarManager that it received the correct photo */
-
- ByteArray reportedAvatar = avatarManager->getAvatar(personJID.toBare());
- CPPUNIT_ASSERT_EQUAL(byteArrayToString(fullAvatar), byteArrayToString(reportedAvatar));
-
- /* send new presence to notify of blank avatar */
-
- vcardUpdate = boost::make_shared<VCardUpdate>();
- presence = boost::make_shared<Presence>();
- presence->setTo(ownerJID);
- presence->setFrom(personJID);
- presence->setType(Presence::Available);
- presence->addPayload(vcardUpdate);
- stanzaChannel->onPresenceReceived(presence);
-
- /* reply to the avatar request with our EMPTY avatar */
-
- CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
- request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]);
- stanzaChannel->sentStanzas.pop_back();
- CPPUNIT_ASSERT(!!request);
- vcard = request->getPayload<VCard>();
- CPPUNIT_ASSERT(!!vcard);
-
- ByteArray blankAvatar = createByteArray("");
- reply = boost::make_shared<IQ>(IQ::Result);
- reply->setTo(request->getFrom());
- reply->setFrom(request->getTo());
- reply->setID(request->getID());
- vcard->setPhoto(blankAvatar);
- reply->addPayload(vcard);
- stanzaChannel->onIQReceived(reply);
-
- /* check hash through avatarManager that it received the correct photo */
-
- reportedAvatar = avatarManager->getAvatar(personJID.toBare());
- CPPUNIT_ASSERT_EQUAL(byteArrayToString(blankAvatar), byteArrayToString(reportedAvatar));
- }
-
- struct DummyMUCRegistry : public MUCRegistry {
- bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
- std::vector<JID> mucs_;
- };
-
- private:
-
- JID ownerJID;
- boost::shared_ptr<DummyStanzaChannel> stanzaChannel;
- boost::shared_ptr<IQRouter> iqRouter;
- boost::shared_ptr<CryptoProvider> crypto;
- boost::shared_ptr<VCardMemoryStorage> vcardStorage;
- boost::shared_ptr<VCardManager> vcardManager;
- boost::shared_ptr<AvatarMemoryStorage> avatarStorage;
- boost::shared_ptr<DummyMUCRegistry> mucRegistry;
- boost::shared_ptr<AvatarManagerImpl> avatarManager;
+ CPPUNIT_TEST_SUITE(AvatarManagerImplTest);
+ CPPUNIT_TEST(testGetSetAvatar);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ ownerJID = JID("owner@domain.com/theowner");
+ stanzaChannel = boost::make_shared<DummyStanzaChannel>();
+ iqRouter = boost::make_shared<IQRouter>(stanzaChannel.get());
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ vcardStorage = boost::make_shared<VCardMemoryStorage>(crypto.get());
+ vcardManager = boost::make_shared<VCardManager>(ownerJID, iqRouter.get(), vcardStorage.get());
+ avatarStorage = boost::make_shared<AvatarMemoryStorage>();
+ mucRegistry = boost::make_shared<DummyMUCRegistry>();
+ avatarManager = boost::make_shared<AvatarManagerImpl>(vcardManager.get(), stanzaChannel.get(), avatarStorage.get(), crypto.get(), mucRegistry.get());
+ }
+
+ void testGetSetAvatar() {
+ /* initially we have no knowledge of the user or their avatar */
+ JID personJID("person@domain.com/theperson");
+ ByteArray avatar = avatarManager->getAvatar(personJID.toBare());
+ CPPUNIT_ASSERT(!avatar.size());
+
+ /* notify the 'owner' JID that our avatar has changed */
+
+ ByteArray fullAvatar = createByteArray("abcdefg");
+ boost::shared_ptr<VCardUpdate> vcardUpdate = boost::make_shared<VCardUpdate>();
+ vcardUpdate->setPhotoHash(Hexify::hexify(crypto->getSHA1Hash(fullAvatar)));
+ boost::shared_ptr<Presence> presence = boost::make_shared<Presence>();
+ presence->setTo(ownerJID);
+ presence->setFrom(personJID);
+ presence->setType(Presence::Available);
+ presence->addPayload(vcardUpdate);
+ stanzaChannel->onPresenceReceived(presence);
+
+ /* reply to the avatar request with our new avatar */
+
+ CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
+ boost::shared_ptr<IQ> request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]);
+ stanzaChannel->sentStanzas.pop_back();
+ CPPUNIT_ASSERT(!!request);
+ boost::shared_ptr<VCard> vcard = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!vcard);
+
+ boost::shared_ptr<IQ> reply = boost::make_shared<IQ>(IQ::Result);
+ reply->setTo(request->getFrom());
+ reply->setFrom(request->getTo());
+ reply->setID(request->getID());
+ vcard->setPhoto(fullAvatar);
+ reply->addPayload(vcard);
+ stanzaChannel->onIQReceived(reply);
+
+ /* check hash through avatarManager that it received the correct photo */
+
+ ByteArray reportedAvatar = avatarManager->getAvatar(personJID.toBare());
+ CPPUNIT_ASSERT_EQUAL(byteArrayToString(fullAvatar), byteArrayToString(reportedAvatar));
+
+ /* send new presence to notify of blank avatar */
+
+ vcardUpdate = boost::make_shared<VCardUpdate>();
+ presence = boost::make_shared<Presence>();
+ presence->setTo(ownerJID);
+ presence->setFrom(personJID);
+ presence->setType(Presence::Available);
+ presence->addPayload(vcardUpdate);
+ stanzaChannel->onPresenceReceived(presence);
+
+ /* reply to the avatar request with our EMPTY avatar */
+
+ CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
+ request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]);
+ stanzaChannel->sentStanzas.pop_back();
+ CPPUNIT_ASSERT(!!request);
+ vcard = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!vcard);
+
+ ByteArray blankAvatar = createByteArray("");
+ reply = boost::make_shared<IQ>(IQ::Result);
+ reply->setTo(request->getFrom());
+ reply->setFrom(request->getTo());
+ reply->setID(request->getID());
+ vcard->setPhoto(blankAvatar);
+ reply->addPayload(vcard);
+ stanzaChannel->onIQReceived(reply);
+
+ /* check hash through avatarManager that it received the correct photo */
+
+ reportedAvatar = avatarManager->getAvatar(personJID.toBare());
+ CPPUNIT_ASSERT_EQUAL(byteArrayToString(blankAvatar), byteArrayToString(reportedAvatar));
+ }
+
+ struct DummyMUCRegistry : public MUCRegistry {
+ bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
+ std::vector<JID> mucs_;
+ };
+
+ private:
+
+ JID ownerJID;
+ boost::shared_ptr<DummyStanzaChannel> stanzaChannel;
+ boost::shared_ptr<IQRouter> iqRouter;
+ boost::shared_ptr<CryptoProvider> crypto;
+ boost::shared_ptr<VCardMemoryStorage> vcardStorage;
+ boost::shared_ptr<VCardManager> vcardManager;
+ boost::shared_ptr<AvatarMemoryStorage> avatarStorage;
+ boost::shared_ptr<DummyMUCRegistry> mucRegistry;
+ boost::shared_ptr<AvatarManagerImpl> avatarManager;
};
diff --git a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
index 1a18585..fb4cd8f 100644
--- a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
+++ b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
@@ -29,351 +29,351 @@
using namespace Swift;
class CombinedAvatarProviderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CombinedAvatarProviderTest);
- CPPUNIT_TEST(testGetAvatarWithNoAvatarProviderReturnsEmpty);
- CPPUNIT_TEST(testGetAvatarWithSingleAvatarProvider);
- CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar);
- CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar);
- CPPUNIT_TEST(testProviderUpdateTriggersChange);
- CPPUNIT_TEST(testProviderUpdateWithoutChangeDoesNotTriggerChange);
- CPPUNIT_TEST(testProviderSecondUpdateTriggersChange);
- CPPUNIT_TEST(testProviderUpdateWithAvatarDisappearingTriggersChange);
- CPPUNIT_TEST(testProviderUpdateAfterAvatarDisappearedTriggersChange);
- CPPUNIT_TEST(testProviderUpdateAfterGetDoesNotTriggerChange);
- CPPUNIT_TEST(testProviderUpdateBareJIDAfterGetFullJID);
- CPPUNIT_TEST(testRemoveProviderDisconnectsUpdates);
- CPPUNIT_TEST(testAddRemoveFallthrough);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- avatarProvider1 = new DummyAvatarProvider();
- avatarProvider2 = new DummyAvatarProvider();
- user1 = JID("user1@bar.com/bla");
- user2 = JID("user2@foo.com/baz");
- avatarHash1 = "ABCDEFG";
- avatarHash2 = "XYZU";
- avatarHash3 = "IDGH";
- }
-
- void tearDown() {
- delete avatarProvider1;
- delete avatarProvider2;
- }
-
- void testGetAvatarWithNoAvatarProviderReturnsEmpty() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
-
- boost::optional<std::string> hash = testling->getAvatarHash(user1);
- CPPUNIT_ASSERT(!hash);
- }
-
- void testGetAvatarWithSingleAvatarProvider() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- avatarProvider1->avatars[user1] = avatarHash1;
- testling->addProvider(avatarProvider1);
-
- boost::optional<std::string> hash = testling->getAvatarHash(user1);
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
- }
-
- void testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider2->avatars[user1] = avatarHash2;
- testling->addProvider(avatarProvider1);
- testling->addProvider(avatarProvider2);
-
- boost::optional<std::string> hash = testling->getAvatarHash(user1);
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
- }
-
- void testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- avatarProvider2->avatars[user1] = avatarHash2;
- testling->addProvider(avatarProvider1);
- testling->addProvider(avatarProvider2);
-
- boost::optional<std::string> hash = testling->getAvatarHash(user1);
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash);
- }
-
- void testProviderUpdateTriggersChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- }
-
- void testProviderUpdateWithoutChangeDoesNotTriggerChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- testling->addProvider(avatarProvider2);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
- changes.clear();
-
- avatarProvider2->avatars[user1] = avatarHash2;
- avatarProvider2->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testProviderSecondUpdateTriggersChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
- changes.clear();
- avatarProvider1->avatars[user1] = avatarHash2;
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- }
-
-
- void testProviderUpdateWithAvatarDisappearingTriggersChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
- changes.clear();
- avatarProvider1->avatars.clear();
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- }
-
- void testProviderUpdateAfterAvatarDisappearedTriggersChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
- avatarProvider1->avatars.clear();
- avatarProvider1->onAvatarChanged(user1);
- changes.clear();
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- }
-
-
- void testProviderUpdateAfterGetDoesNotTriggerChange() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
-
- testling->getAvatarHash(user1);
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testRemoveProviderDisconnectsUpdates() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- testling->addProvider(avatarProvider1);
- testling->addProvider(avatarProvider2);
- testling->removeProvider(avatarProvider1);
- avatarProvider1->avatars[user1] = avatarHash1;
- avatarProvider2->avatars[user1] = avatarHash2;
- avatarProvider1->onAvatarChanged(user1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testProviderUpdateBareJIDAfterGetFullJID() {
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- avatarProvider1->useBare = true;
- testling->addProvider(avatarProvider1);
-
- avatarProvider1->avatars[user1.toBare()] = avatarHash1;
- testling->getAvatarHash(user1);
- avatarProvider1->avatars[user1.toBare()] = avatarHash2;
- avatarProvider1->onAvatarChanged(user1.toBare());
-
- boost::optional<std::string> hash = testling->getAvatarHash(user1);
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash);
- }
-
- void testAddRemoveFallthrough() {
- JID ownJID = JID("user0@own.com/res");
- JID user1 = JID("user1@bar.com/bla");
-
- boost::shared_ptr<CryptoProvider> crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- DummyStanzaChannel* stanzaChannel = new DummyStanzaChannel();
- stanzaChannel->setAvailable(true);
- IQRouter* iqRouter = new IQRouter(stanzaChannel);
- DummyMUCRegistry* mucRegistry = new DummyMUCRegistry();
- AvatarMemoryStorage* avatarStorage = new AvatarMemoryStorage();
- VCardMemoryStorage* vcardStorage = new VCardMemoryStorage(crypto.get());
- VCardManager* vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
-
- boost::shared_ptr<VCardUpdateAvatarManager> updateManager(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
- updateManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
-
- boost::shared_ptr<VCardAvatarManager> manager(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry));
- manager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
-
- boost::shared_ptr<OfflineAvatarManager> offlineManager(new OfflineAvatarManager(avatarStorage));
- offlineManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
-
- boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
- avatarProvider1->useBare = true;
- testling->addProvider(updateManager.get());
- testling->addProvider(manager.get());
- testling->addProvider(offlineManager.get());
-
- /* place an avatar in the cache, check that it reads back OK */
-
- CPPUNIT_ASSERT_EQUAL(size_t(0), changes.size());
-
- ByteArray avatar1 = createByteArray("abcdefg");
- std::string avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
- VCard::ref vcard1(new VCard());
- vcard1->setPhoto(avatar1);
-
- vcardStorage->setVCard(user1.toBare(), vcard1);
- boost::optional<std::string> testHash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(testHash);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash);
-
- VCard::ref storedVCard = vcardStorage->getVCard(user1.toBare());
- CPPUNIT_ASSERT(!!storedVCard);
- testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto()));
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash);
-
- /* change the avatar by sending an VCard IQ */
-
- vcardManager->requestVCard(user1.toBare());
- CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
- IQ::ref request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back());
- VCard::ref payload = request->getPayload<VCard>();
- CPPUNIT_ASSERT(!!payload);
- stanzaChannel->sentStanzas.pop_back();
-
- ByteArray avatar2 = createByteArray("1234567");
- std::string avatar2Hash = Hexify::hexify(crypto->getSHA1Hash(avatar2));
- VCard::ref vcard2(new VCard());
- vcard2->setPhoto(avatar2);
-
- IQ::ref reply = boost::make_shared<IQ>();
- reply->setTo(request->getFrom());
- reply->setFrom(request->getTo());
- reply->setID(request->getID());
- reply->addPayload(vcard2);
- reply->setType(IQ::Result);
-
- stanzaChannel->onIQReceived(reply);
-
- /* check that we changed the avatar successfully and that we were notified about the changes */
-
- testHash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(testHash);
- CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash);
- CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size());
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]);
- changes.clear();
- storedVCard = vcardStorage->getVCard(user1.toBare());
- CPPUNIT_ASSERT(!!storedVCard);
- testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto()));
- CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash);
-
- /* change the avatar to the empty avatar */
-
- vcardManager->requestVCard(user1.toBare());
- CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
- request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back());
- payload = request->getPayload<VCard>();
- CPPUNIT_ASSERT(!!payload);
- stanzaChannel->sentStanzas.pop_back();
-
- VCard::ref vcard3(new VCard());
- reply = boost::make_shared<IQ>();
- reply->setTo(request->getFrom());
- reply->setFrom(request->getTo());
- reply->setID(request->getID());
- reply->addPayload(vcard3);
- reply->setType(IQ::Result);
- stanzaChannel->onIQReceived(reply);
-
- /* check that we changed the avatar successfully */
-
- testHash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(testHash);
- CPPUNIT_ASSERT_EQUAL(std::string(""), *testHash);
- CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size());
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]);
- changes.clear();
- storedVCard = vcardStorage->getVCard(user1.toBare());
- CPPUNIT_ASSERT(!!storedVCard);
- CPPUNIT_ASSERT(!storedVCard->getPhoto().size());
-
- delete vcardManager;
- delete vcardStorage;
- delete mucRegistry;
- delete iqRouter;
- delete stanzaChannel;
- }
-
- private:
- boost::shared_ptr<CombinedAvatarProvider> createProvider() {
- boost::shared_ptr<CombinedAvatarProvider> result(new CombinedAvatarProvider());
- result->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
- return result;
- }
-
- void handleAvatarChanged(const JID& jid) {
- changes.push_back(jid);
- }
-
- private:
- struct DummyAvatarProvider : public AvatarProvider {
- DummyAvatarProvider() : useBare(false) {
- }
-
- boost::optional<std::string> getAvatarHash(const JID& jid) const {
- JID actualJID = useBare ? jid.toBare() : jid;
- std::map<JID, std::string>::const_iterator i = avatars.find(actualJID);
- if (i != avatars.end()) {
- return i->second;
- }
- else {
- return boost::optional<std::string>();
- }
- }
-
- bool useBare;
- std::map<JID, std::string> avatars;
- };
-
- struct DummyMUCRegistry : public MUCRegistry {
- bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
- std::vector<JID> mucs_;
- };
-
- DummyAvatarProvider* avatarProvider1;
- DummyAvatarProvider* avatarProvider2;
- JID user1;
- JID user2;
- std::string avatarHash1;
- std::string avatarHash2;
- std::string avatarHash3;
- std::vector<JID> changes;
+ CPPUNIT_TEST_SUITE(CombinedAvatarProviderTest);
+ CPPUNIT_TEST(testGetAvatarWithNoAvatarProviderReturnsEmpty);
+ CPPUNIT_TEST(testGetAvatarWithSingleAvatarProvider);
+ CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar);
+ CPPUNIT_TEST(testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar);
+ CPPUNIT_TEST(testProviderUpdateTriggersChange);
+ CPPUNIT_TEST(testProviderUpdateWithoutChangeDoesNotTriggerChange);
+ CPPUNIT_TEST(testProviderSecondUpdateTriggersChange);
+ CPPUNIT_TEST(testProviderUpdateWithAvatarDisappearingTriggersChange);
+ CPPUNIT_TEST(testProviderUpdateAfterAvatarDisappearedTriggersChange);
+ CPPUNIT_TEST(testProviderUpdateAfterGetDoesNotTriggerChange);
+ CPPUNIT_TEST(testProviderUpdateBareJIDAfterGetFullJID);
+ CPPUNIT_TEST(testRemoveProviderDisconnectsUpdates);
+ CPPUNIT_TEST(testAddRemoveFallthrough);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ avatarProvider1 = new DummyAvatarProvider();
+ avatarProvider2 = new DummyAvatarProvider();
+ user1 = JID("user1@bar.com/bla");
+ user2 = JID("user2@foo.com/baz");
+ avatarHash1 = "ABCDEFG";
+ avatarHash2 = "XYZU";
+ avatarHash3 = "IDGH";
+ }
+
+ void tearDown() {
+ delete avatarProvider1;
+ delete avatarProvider2;
+ }
+
+ void testGetAvatarWithNoAvatarProviderReturnsEmpty() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(!hash);
+ }
+
+ void testGetAvatarWithSingleAvatarProvider() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ testling->addProvider(avatarProvider1);
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
+ }
+
+ void testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider2->avatars[user1] = avatarHash2;
+ testling->addProvider(avatarProvider1);
+ testling->addProvider(avatarProvider2);
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
+ }
+
+ void testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider2->avatars[user1] = avatarHash2;
+ testling->addProvider(avatarProvider1);
+ testling->addProvider(avatarProvider2);
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash);
+ }
+
+ void testProviderUpdateTriggersChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ }
+
+ void testProviderUpdateWithoutChangeDoesNotTriggerChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ testling->addProvider(avatarProvider2);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+ changes.clear();
+
+ avatarProvider2->avatars[user1] = avatarHash2;
+ avatarProvider2->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testProviderSecondUpdateTriggersChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+ changes.clear();
+ avatarProvider1->avatars[user1] = avatarHash2;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ }
+
+
+ void testProviderUpdateWithAvatarDisappearingTriggersChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+ changes.clear();
+ avatarProvider1->avatars.clear();
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ }
+
+ void testProviderUpdateAfterAvatarDisappearedTriggersChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+ avatarProvider1->avatars.clear();
+ avatarProvider1->onAvatarChanged(user1);
+ changes.clear();
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ }
+
+
+ void testProviderUpdateAfterGetDoesNotTriggerChange() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+
+ testling->getAvatarHash(user1);
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testRemoveProviderDisconnectsUpdates() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1);
+ testling->addProvider(avatarProvider2);
+ testling->removeProvider(avatarProvider1);
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider2->avatars[user1] = avatarHash2;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testProviderUpdateBareJIDAfterGetFullJID() {
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->useBare = true;
+ testling->addProvider(avatarProvider1);
+
+ avatarProvider1->avatars[user1.toBare()] = avatarHash1;
+ testling->getAvatarHash(user1);
+ avatarProvider1->avatars[user1.toBare()] = avatarHash2;
+ avatarProvider1->onAvatarChanged(user1.toBare());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash);
+ }
+
+ void testAddRemoveFallthrough() {
+ JID ownJID = JID("user0@own.com/res");
+ JID user1 = JID("user1@bar.com/bla");
+
+ boost::shared_ptr<CryptoProvider> crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ DummyStanzaChannel* stanzaChannel = new DummyStanzaChannel();
+ stanzaChannel->setAvailable(true);
+ IQRouter* iqRouter = new IQRouter(stanzaChannel);
+ DummyMUCRegistry* mucRegistry = new DummyMUCRegistry();
+ AvatarMemoryStorage* avatarStorage = new AvatarMemoryStorage();
+ VCardMemoryStorage* vcardStorage = new VCardMemoryStorage(crypto.get());
+ VCardManager* vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
+
+ boost::shared_ptr<VCardUpdateAvatarManager> updateManager(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
+ updateManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ boost::shared_ptr<VCardAvatarManager> manager(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry));
+ manager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ boost::shared_ptr<OfflineAvatarManager> offlineManager(new OfflineAvatarManager(avatarStorage));
+ offlineManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ boost::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->useBare = true;
+ testling->addProvider(updateManager.get());
+ testling->addProvider(manager.get());
+ testling->addProvider(offlineManager.get());
+
+ /* place an avatar in the cache, check that it reads back OK */
+
+ CPPUNIT_ASSERT_EQUAL(size_t(0), changes.size());
+
+ ByteArray avatar1 = createByteArray("abcdefg");
+ std::string avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
+ VCard::ref vcard1(new VCard());
+ vcard1->setPhoto(avatar1);
+
+ vcardStorage->setVCard(user1.toBare(), vcard1);
+ boost::optional<std::string> testHash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(testHash);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash);
+
+ VCard::ref storedVCard = vcardStorage->getVCard(user1.toBare());
+ CPPUNIT_ASSERT(!!storedVCard);
+ testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto()));
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *testHash);
+
+ /* change the avatar by sending an VCard IQ */
+
+ vcardManager->requestVCard(user1.toBare());
+ CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
+ IQ::ref request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back());
+ VCard::ref payload = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!payload);
+ stanzaChannel->sentStanzas.pop_back();
+
+ ByteArray avatar2 = createByteArray("1234567");
+ std::string avatar2Hash = Hexify::hexify(crypto->getSHA1Hash(avatar2));
+ VCard::ref vcard2(new VCard());
+ vcard2->setPhoto(avatar2);
+
+ IQ::ref reply = boost::make_shared<IQ>();
+ reply->setTo(request->getFrom());
+ reply->setFrom(request->getTo());
+ reply->setID(request->getID());
+ reply->addPayload(vcard2);
+ reply->setType(IQ::Result);
+
+ stanzaChannel->onIQReceived(reply);
+
+ /* check that we changed the avatar successfully and that we were notified about the changes */
+
+ testHash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(testHash);
+ CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash);
+ CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size());
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]);
+ changes.clear();
+ storedVCard = vcardStorage->getVCard(user1.toBare());
+ CPPUNIT_ASSERT(!!storedVCard);
+ testHash = Hexify::hexify(crypto->getSHA1Hash(storedVCard->getPhoto()));
+ CPPUNIT_ASSERT_EQUAL(avatar2Hash, *testHash);
+
+ /* change the avatar to the empty avatar */
+
+ vcardManager->requestVCard(user1.toBare());
+ CPPUNIT_ASSERT_EQUAL(size_t(1), stanzaChannel->sentStanzas.size());
+ request = boost::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back());
+ payload = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!payload);
+ stanzaChannel->sentStanzas.pop_back();
+
+ VCard::ref vcard3(new VCard());
+ reply = boost::make_shared<IQ>();
+ reply->setTo(request->getFrom());
+ reply->setFrom(request->getTo());
+ reply->setID(request->getID());
+ reply->addPayload(vcard3);
+ reply->setType(IQ::Result);
+ stanzaChannel->onIQReceived(reply);
+
+ /* check that we changed the avatar successfully */
+
+ testHash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(testHash);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *testHash);
+ CPPUNIT_ASSERT_EQUAL(size_t(3), changes.size());
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[2]);
+ changes.clear();
+ storedVCard = vcardStorage->getVCard(user1.toBare());
+ CPPUNIT_ASSERT(!!storedVCard);
+ CPPUNIT_ASSERT(!storedVCard->getPhoto().size());
+
+ delete vcardManager;
+ delete vcardStorage;
+ delete mucRegistry;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ private:
+ boost::shared_ptr<CombinedAvatarProvider> createProvider() {
+ boost::shared_ptr<CombinedAvatarProvider> result(new CombinedAvatarProvider());
+ result->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+ return result;
+ }
+
+ void handleAvatarChanged(const JID& jid) {
+ changes.push_back(jid);
+ }
+
+ private:
+ struct DummyAvatarProvider : public AvatarProvider {
+ DummyAvatarProvider() : useBare(false) {
+ }
+
+ boost::optional<std::string> getAvatarHash(const JID& jid) const {
+ JID actualJID = useBare ? jid.toBare() : jid;
+ std::map<JID, std::string>::const_iterator i = avatars.find(actualJID);
+ if (i != avatars.end()) {
+ return i->second;
+ }
+ else {
+ return boost::optional<std::string>();
+ }
+ }
+
+ bool useBare;
+ std::map<JID, std::string> avatars;
+ };
+
+ struct DummyMUCRegistry : public MUCRegistry {
+ bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
+ std::vector<JID> mucs_;
+ };
+
+ DummyAvatarProvider* avatarProvider1;
+ DummyAvatarProvider* avatarProvider2;
+ JID user1;
+ JID user2;
+ std::string avatarHash1;
+ std::string avatarHash2;
+ std::string avatarHash3;
+ std::vector<JID> changes;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CombinedAvatarProviderTest);
diff --git a/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp
index 2f585aa..5a28995 100644
--- a/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp
+++ b/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp
@@ -27,150 +27,150 @@
using namespace Swift;
class VCardAvatarManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(VCardAvatarManagerTest);
- CPPUNIT_TEST(testGetAvatarHashKnownAvatar);
- CPPUNIT_TEST(testGetAvatarHashEmptyAvatar);
- CPPUNIT_TEST(testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar);
- CPPUNIT_TEST(testGetAvatarHashUnknownAvatarUnknownVCard);
- CPPUNIT_TEST(testVCardUpdateTriggersUpdate);
- CPPUNIT_TEST(testGetAvatarHashKnownAvatarUnknownVCard);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- ownJID = JID("foo@fum.com/bum");
- stanzaChannel = new DummyStanzaChannel();
- stanzaChannel->setAvailable(true);
- iqRouter = new IQRouter(stanzaChannel);
- mucRegistry = new DummyMUCRegistry();
- avatarStorage = new AvatarMemoryStorage();
- vcardStorage = new VCardMemoryStorage(crypto.get());
- vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
- avatar1 = createByteArray("abcdefg");
- avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
- user1 = JID("user1@bar.com/bla");
- user2 = JID("user2@foo.com/baz");
- }
-
- void tearDown() {
- delete vcardManager;
- delete vcardStorage;
- delete avatarStorage;
- delete mucRegistry;
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testGetAvatarHashKnownAvatar() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
- storeVCardWithPhoto(user1.toBare(), avatar1);
- avatarStorage->addAvatar(avatar1Hash, avatar1);
-
- boost::optional<std::string> result = testling->getAvatarHash(user1);
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result);
- }
-
- void testGetAvatarHashEmptyAvatar() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
- storeEmptyVCard(user1.toBare());
-
- boost::optional<std::string> result = testling->getAvatarHash(user1);
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(std::string(), *result);
- }
-
- void testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
- storeVCardWithPhoto(user1.toBare(), avatar1);
-
- boost::optional<std::string> result = testling->getAvatarHash(user1);
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result);
- CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash));
- CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash));
- }
-
- void testGetAvatarHashUnknownAvatarUnknownVCard() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
-
- boost::optional<std::string> result = testling->getAvatarHash(user1);
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(std::string(), *result);
- }
-
- void testGetAvatarHashKnownAvatarUnknownVCard() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
-
- avatarStorage->setAvatarForJID(user1, avatar1Hash);
-
- boost::optional<std::string> result = testling->getAvatarHash(user1);
-
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(std::string(), *result);
- }
-
-
- void testVCardUpdateTriggersUpdate() {
- boost::shared_ptr<VCardAvatarManager> testling = createManager();
- vcardManager->requestVCard(user1);
- sendVCardResult();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- }
-
- private:
- boost::shared_ptr<VCardAvatarManager> createManager() {
- boost::shared_ptr<VCardAvatarManager> result(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry));
- result->onAvatarChanged.connect(boost::bind(&VCardAvatarManagerTest::handleAvatarChanged, this, _1));
- return result;
- }
-
- void storeVCardWithPhoto(const JID& jid, const ByteArray& avatar) {
- VCard::ref vcard(new VCard());
- vcard->setPhoto(avatar);
- vcardStorage->setVCard(jid, vcard);
- }
-
- void storeEmptyVCard(const JID& jid) {
- VCard::ref vcard(new VCard());
- vcardStorage->setVCard(jid, vcard);
- }
-
- void handleAvatarChanged(const JID& jid) {
- changes.push_back(jid);
- }
-
- void sendVCardResult() {
- VCard::ref vcard(new VCard());
- vcard->setFullName("Foo Bar");
- stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard));
- }
-
- private:
- struct DummyMUCRegistry : public MUCRegistry {
- bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
- std::vector<JID> mucs_;
- };
-
- JID ownJID;
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- DummyMUCRegistry* mucRegistry;
- AvatarMemoryStorage* avatarStorage;
- VCardManager* vcardManager;
- VCardMemoryStorage* vcardStorage;
- ByteArray avatar1;
- std::string avatar1Hash;
- std::vector<JID> changes;
- JID user1;
- JID user2;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(VCardAvatarManagerTest);
+ CPPUNIT_TEST(testGetAvatarHashKnownAvatar);
+ CPPUNIT_TEST(testGetAvatarHashEmptyAvatar);
+ CPPUNIT_TEST(testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar);
+ CPPUNIT_TEST(testGetAvatarHashUnknownAvatarUnknownVCard);
+ CPPUNIT_TEST(testVCardUpdateTriggersUpdate);
+ CPPUNIT_TEST(testGetAvatarHashKnownAvatarUnknownVCard);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ ownJID = JID("foo@fum.com/bum");
+ stanzaChannel = new DummyStanzaChannel();
+ stanzaChannel->setAvailable(true);
+ iqRouter = new IQRouter(stanzaChannel);
+ mucRegistry = new DummyMUCRegistry();
+ avatarStorage = new AvatarMemoryStorage();
+ vcardStorage = new VCardMemoryStorage(crypto.get());
+ vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
+ avatar1 = createByteArray("abcdefg");
+ avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
+ user1 = JID("user1@bar.com/bla");
+ user2 = JID("user2@foo.com/baz");
+ }
+
+ void tearDown() {
+ delete vcardManager;
+ delete vcardStorage;
+ delete avatarStorage;
+ delete mucRegistry;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testGetAvatarHashKnownAvatar() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+ storeVCardWithPhoto(user1.toBare(), avatar1);
+ avatarStorage->addAvatar(avatar1Hash, avatar1);
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result);
+ }
+
+ void testGetAvatarHashEmptyAvatar() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+ storeEmptyVCard(user1.toBare());
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(std::string(), *result);
+ }
+
+ void testGetAvatarHashUnknownAvatarKnownVCardStoresAvatar() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+ storeVCardWithPhoto(user1.toBare(), avatar1);
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *result);
+ CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash));
+ CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash));
+ }
+
+ void testGetAvatarHashUnknownAvatarUnknownVCard() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(std::string(), *result);
+ }
+
+ void testGetAvatarHashKnownAvatarUnknownVCard() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+
+ avatarStorage->setAvatarForJID(user1, avatar1Hash);
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(std::string(), *result);
+ }
+
+
+ void testVCardUpdateTriggersUpdate() {
+ boost::shared_ptr<VCardAvatarManager> testling = createManager();
+ vcardManager->requestVCard(user1);
+ sendVCardResult();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ }
+
+ private:
+ boost::shared_ptr<VCardAvatarManager> createManager() {
+ boost::shared_ptr<VCardAvatarManager> result(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry));
+ result->onAvatarChanged.connect(boost::bind(&VCardAvatarManagerTest::handleAvatarChanged, this, _1));
+ return result;
+ }
+
+ void storeVCardWithPhoto(const JID& jid, const ByteArray& avatar) {
+ VCard::ref vcard(new VCard());
+ vcard->setPhoto(avatar);
+ vcardStorage->setVCard(jid, vcard);
+ }
+
+ void storeEmptyVCard(const JID& jid) {
+ VCard::ref vcard(new VCard());
+ vcardStorage->setVCard(jid, vcard);
+ }
+
+ void handleAvatarChanged(const JID& jid) {
+ changes.push_back(jid);
+ }
+
+ void sendVCardResult() {
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Foo Bar");
+ stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard));
+ }
+
+ private:
+ struct DummyMUCRegistry : public MUCRegistry {
+ bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
+ std::vector<JID> mucs_;
+ };
+
+ JID ownJID;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ DummyMUCRegistry* mucRegistry;
+ AvatarMemoryStorage* avatarStorage;
+ VCardManager* vcardManager;
+ VCardMemoryStorage* vcardStorage;
+ ByteArray avatar1;
+ std::string avatar1Hash;
+ std::vector<JID> changes;
+ JID user1;
+ JID user2;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardAvatarManagerTest);
diff --git a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
index f9747a1..5f6c691 100644
--- a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
+++ b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
@@ -27,186 +27,186 @@
using namespace Swift;
class VCardUpdateAvatarManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(VCardUpdateAvatarManagerTest);
- CPPUNIT_TEST(testUpdate_NewHashNewVCardRequestsVCard);
- CPPUNIT_TEST(testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive);
- CPPUNIT_TEST(testUpdate_KnownHash);
- CPPUNIT_TEST(testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification);
- CPPUNIT_TEST(testVCardWithEmptyPhoto);
- CPPUNIT_TEST(testStanzaChannelReset_ClearsHash);
- CPPUNIT_TEST(testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- ownJID = JID("foo@fum.com/bum");
- stanzaChannel = new DummyStanzaChannel();
- stanzaChannel->setAvailable(true);
- iqRouter = new IQRouter(stanzaChannel);
- mucRegistry = new DummyMUCRegistry();
- avatarStorage = new AvatarMemoryStorage();
- vcardStorage = new VCardMemoryStorage(crypto.get());
- vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
- avatar1 = createByteArray("abcdefg");
- avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
- user1 = JID("user1@bar.com/bla");
- user2 = JID("user2@foo.com/baz");
- }
-
-
- void tearDown() {
- delete vcardManager;
- delete vcardStorage;
- delete avatarStorage;
- delete mucRegistry;
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testUpdate_NewHashNewVCardRequestsVCard() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, user1.toBare(), IQ::Get));
- }
-
- void testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
- stanzaChannel->onIQReceived(createVCardResult(avatar1));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
- boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
- CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash));
- CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash));
- }
-
- void testUpdate_KnownHash() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
- stanzaChannel->onIQReceived(createVCardResult(avatar1));
- changes.clear();
- stanzaChannel->sentStanzas.clear();
-
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
- stanzaChannel->onIQReceived(createVCardResult(avatar1));
- changes.clear();
- stanzaChannel->sentStanzas.clear();
-
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user2, avatar1Hash));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user2.toBare(), changes[0]);
- boost::optional<std::string> hash = testling->getAvatarHash(user2.toBare());
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
- }
-
- void testVCardWithEmptyPhoto() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- vcardManager->requestVCard(JID("foo@bar.com"));
- stanzaChannel->onIQReceived(createVCardResult(ByteArray()));
-
- CPPUNIT_ASSERT(!avatarStorage->hasAvatar(Hexify::hexify(crypto->getSHA1Hash(ByteArray()))));
- boost::optional<std::string> hash = testling->getAvatarHash(JID("foo@bar.com"));
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(std::string(), *hash);
- }
-
- void testStanzaChannelReset_ClearsHash() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
- stanzaChannel->onIQReceived(createVCardResult(avatar1));
- changes.clear();
- stanzaChannel->sentStanzas.clear();
-
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
- boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(!hash);
- //CPPUNIT_ASSERT_EQUAL(std::string(""), *hash);
- }
-
- void testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash() {
- boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
- stanzaChannel->onIQReceived(createVCardResult(avatar1));
- changes.clear();
- stanzaChannel->sentStanzas.clear();
-
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
- boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
- }
-
- private:
- boost::shared_ptr<VCardUpdateAvatarManager> createManager() {
- boost::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
- result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1));
- return result;
- }
-
- boost::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setFrom(jid);
- presence->addPayload(boost::make_shared<VCardUpdate>(hash));
- return presence;
- }
-
- IQ::ref createVCardResult(const ByteArray& avatar) {
- VCard::ref vcard(new VCard());
- if (!avatar.empty()) {
- vcard->setPhoto(avatar);
- }
- return IQ::createResult(JID("baz@fum.com"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
- }
-
- void handleAvatarChanged(const JID& jid) {
- changes.push_back(jid);
- }
-
- private:
- struct DummyMUCRegistry : public MUCRegistry {
- bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
- std::vector<JID> mucs_;
- };
-
- JID ownJID;
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- DummyMUCRegistry* mucRegistry;
- AvatarMemoryStorage* avatarStorage;
- VCardManager* vcardManager;
- VCardMemoryStorage* vcardStorage;
- ByteArray avatar1;
- std::string avatar1Hash;
- std::vector<JID> changes;
- JID user1;
- JID user2;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(VCardUpdateAvatarManagerTest);
+ CPPUNIT_TEST(testUpdate_NewHashNewVCardRequestsVCard);
+ CPPUNIT_TEST(testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive);
+ CPPUNIT_TEST(testUpdate_KnownHash);
+ CPPUNIT_TEST(testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification);
+ CPPUNIT_TEST(testVCardWithEmptyPhoto);
+ CPPUNIT_TEST(testStanzaChannelReset_ClearsHash);
+ CPPUNIT_TEST(testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ ownJID = JID("foo@fum.com/bum");
+ stanzaChannel = new DummyStanzaChannel();
+ stanzaChannel->setAvailable(true);
+ iqRouter = new IQRouter(stanzaChannel);
+ mucRegistry = new DummyMUCRegistry();
+ avatarStorage = new AvatarMemoryStorage();
+ vcardStorage = new VCardMemoryStorage(crypto.get());
+ vcardManager = new VCardManager(ownJID, iqRouter, vcardStorage);
+ avatar1 = createByteArray("abcdefg");
+ avatar1Hash = Hexify::hexify(crypto->getSHA1Hash(avatar1));
+ user1 = JID("user1@bar.com/bla");
+ user2 = JID("user2@foo.com/baz");
+ }
+
+
+ void tearDown() {
+ delete vcardManager;
+ delete vcardStorage;
+ delete avatarStorage;
+ delete mucRegistry;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testUpdate_NewHashNewVCardRequestsVCard() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, user1.toBare(), IQ::Get));
+ }
+
+ void testUpdate_NewHashStoresAvatarAndEmitsNotificationOnVCardReceive() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+ stanzaChannel->onIQReceived(createVCardResult(avatar1));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
+ boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
+ CPPUNIT_ASSERT(avatarStorage->hasAvatar(avatar1Hash));
+ CPPUNIT_ASSERT_EQUAL(avatar1, avatarStorage->getAvatar(avatar1Hash));
+ }
+
+ void testUpdate_KnownHash() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+ stanzaChannel->onIQReceived(createVCardResult(avatar1));
+ changes.clear();
+ stanzaChannel->sentStanzas.clear();
+
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testUpdate_KnownHashFromDifferentUserDoesNotRequestVCardButTriggersNotification() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+ stanzaChannel->onIQReceived(createVCardResult(avatar1));
+ changes.clear();
+ stanzaChannel->sentStanzas.clear();
+
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user2, avatar1Hash));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user2.toBare(), changes[0]);
+ boost::optional<std::string> hash = testling->getAvatarHash(user2.toBare());
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
+ }
+
+ void testVCardWithEmptyPhoto() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ vcardManager->requestVCard(JID("foo@bar.com"));
+ stanzaChannel->onIQReceived(createVCardResult(ByteArray()));
+
+ CPPUNIT_ASSERT(!avatarStorage->hasAvatar(Hexify::hexify(crypto->getSHA1Hash(ByteArray()))));
+ boost::optional<std::string> hash = testling->getAvatarHash(JID("foo@bar.com"));
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(std::string(), *hash);
+ }
+
+ void testStanzaChannelReset_ClearsHash() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+ stanzaChannel->onIQReceived(createVCardResult(avatar1));
+ changes.clear();
+ stanzaChannel->sentStanzas.clear();
+
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
+ boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(!hash);
+ //CPPUNIT_ASSERT_EQUAL(std::string(""), *hash);
+ }
+
+ void testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash() {
+ boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+ stanzaChannel->onIQReceived(createVCardResult(avatar1));
+ changes.clear();
+ stanzaChannel->sentStanzas.clear();
+
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
+ boost::optional<std::string> hash = testling->getAvatarHash(user1.toBare());
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatar1Hash, *hash);
+ }
+
+ private:
+ boost::shared_ptr<VCardUpdateAvatarManager> createManager() {
+ boost::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
+ result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1));
+ return result;
+ }
+
+ boost::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(boost::make_shared<VCardUpdate>(hash));
+ return presence;
+ }
+
+ IQ::ref createVCardResult(const ByteArray& avatar) {
+ VCard::ref vcard(new VCard());
+ if (!avatar.empty()) {
+ vcard->setPhoto(avatar);
+ }
+ return IQ::createResult(JID("baz@fum.com"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
+ }
+
+ void handleAvatarChanged(const JID& jid) {
+ changes.push_back(jid);
+ }
+
+ private:
+ struct DummyMUCRegistry : public MUCRegistry {
+ bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
+ std::vector<JID> mucs_;
+ };
+
+ JID ownJID;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ DummyMUCRegistry* mucRegistry;
+ AvatarMemoryStorage* avatarStorage;
+ VCardManager* vcardManager;
+ VCardMemoryStorage* vcardStorage;
+ ByteArray avatar1;
+ std::string avatar1Hash;
+ std::vector<JID> changes;
+ JID user1;
+ JID user2;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardUpdateAvatarManagerTest);
diff --git a/Swiften/Avatars/VCardAvatarManager.cpp b/Swiften/Avatars/VCardAvatarManager.cpp
index 675cd00..919d833 100644
--- a/Swiften/Avatars/VCardAvatarManager.cpp
+++ b/Swiften/Avatars/VCardAvatarManager.cpp
@@ -19,44 +19,44 @@
namespace Swift {
VCardAvatarManager::VCardAvatarManager(VCardManager* vcardManager, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : vcardManager_(vcardManager), avatarStorage_(avatarStorage), crypto_(crypto), mucRegistry_(mucRegistry) {
- vcardManager_->onVCardChanged.connect(boost::bind(&VCardAvatarManager::handleVCardChanged, this, _1));
+ vcardManager_->onVCardChanged.connect(boost::bind(&VCardAvatarManager::handleVCardChanged, this, _1));
}
void VCardAvatarManager::handleVCardChanged(const JID& from) {
- // We don't check whether the avatar actually changed. Direct use of this
- // manager could cause unnecessary updates, but in practice, this will be
- // caught by the wrapping CombinedAvatarManager anyway.
- onAvatarChanged(from);
+ // We don't check whether the avatar actually changed. Direct use of this
+ // manager could cause unnecessary updates, but in practice, this will be
+ // caught by the wrapping CombinedAvatarManager anyway.
+ onAvatarChanged(from);
}
boost::optional<std::string> VCardAvatarManager::getAvatarHash(const JID& jid) const {
- JID avatarJID = getAvatarJID(jid);
- std::string hash = vcardManager_->getPhotoHash(avatarJID);
- if (!hash.empty()) {
- if (!avatarStorage_->hasAvatar(hash)) {
- VCard::ref vCard = vcardManager_->getVCard(avatarJID);
- if (vCard) {
- std::string newHash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto()));
- if (newHash != hash) {
- // Shouldn't happen, but sometimes seem to. Might be fixed if we
- // move to a safer backend.
- SWIFT_LOG(warning) << "Inconsistent vCard photo hash cache";
- hash = newHash;
- }
- avatarStorage_->addAvatar(hash, vCard->getPhoto());
- }
- else {
- // Can happen if the cache is inconsistent.
- hash = "";
- }
- }
- }
- return hash;
+ JID avatarJID = getAvatarJID(jid);
+ std::string hash = vcardManager_->getPhotoHash(avatarJID);
+ if (!hash.empty()) {
+ if (!avatarStorage_->hasAvatar(hash)) {
+ VCard::ref vCard = vcardManager_->getVCard(avatarJID);
+ if (vCard) {
+ std::string newHash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto()));
+ if (newHash != hash) {
+ // Shouldn't happen, but sometimes seem to. Might be fixed if we
+ // move to a safer backend.
+ SWIFT_LOG(warning) << "Inconsistent vCard photo hash cache";
+ hash = newHash;
+ }
+ avatarStorage_->addAvatar(hash, vCard->getPhoto());
+ }
+ else {
+ // Can happen if the cache is inconsistent.
+ hash = "";
+ }
+ }
+ }
+ return hash;
}
JID VCardAvatarManager::getAvatarJID(const JID& jid) const {
- JID bareFrom = jid.toBare();
- return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom;
+ JID bareFrom = jid.toBare();
+ return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom;
}
}
diff --git a/Swiften/Avatars/VCardAvatarManager.h b/Swiften/Avatars/VCardAvatarManager.h
index d914da3..03b3afa 100644
--- a/Swiften/Avatars/VCardAvatarManager.h
+++ b/Swiften/Avatars/VCardAvatarManager.h
@@ -11,25 +11,25 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class MUCRegistry;
- class AvatarStorage;
- class VCardManager;
- class CryptoProvider;
+ class MUCRegistry;
+ class AvatarStorage;
+ class VCardManager;
+ class CryptoProvider;
- class SWIFTEN_API VCardAvatarManager : public AvatarProvider {
- public:
- VCardAvatarManager(VCardManager*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
+ class SWIFTEN_API VCardAvatarManager : public AvatarProvider {
+ public:
+ VCardAvatarManager(VCardManager*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
- boost::optional<std::string> getAvatarHash(const JID&) const;
+ boost::optional<std::string> getAvatarHash(const JID&) const;
- private:
- void handleVCardChanged(const JID& from);
- JID getAvatarJID(const JID& o) const;
+ private:
+ void handleVCardChanged(const JID& from);
+ JID getAvatarJID(const JID& o) const;
- private:
- VCardManager* vcardManager_;
- AvatarStorage* avatarStorage_;
- CryptoProvider* crypto_;
- MUCRegistry* mucRegistry_;
- };
+ private:
+ VCardManager* vcardManager_;
+ AvatarStorage* avatarStorage_;
+ CryptoProvider* crypto_;
+ MUCRegistry* mucRegistry_;
+ };
}
diff --git a/Swiften/Avatars/VCardUpdateAvatarManager.cpp b/Swiften/Avatars/VCardUpdateAvatarManager.cpp
index 42c210d..e40eee3 100644
--- a/Swiften/Avatars/VCardUpdateAvatarManager.cpp
+++ b/Swiften/Avatars/VCardUpdateAvatarManager.cpp
@@ -21,84 +21,84 @@
namespace Swift {
VCardUpdateAvatarManager::VCardUpdateAvatarManager(VCardManager* vcardManager, StanzaChannel* stanzaChannel, AvatarStorage* avatarStorage, CryptoProvider* crypto, MUCRegistry* mucRegistry) : vcardManager_(vcardManager), avatarStorage_(avatarStorage), crypto_(crypto), mucRegistry_(mucRegistry) {
- stanzaChannel->onPresenceReceived.connect(boost::bind(&VCardUpdateAvatarManager::handlePresenceReceived, this, _1));
- stanzaChannel->onAvailableChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged, this, _1));
- vcardManager_->onVCardChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleVCardChanged, this, _1, _2));
+ stanzaChannel->onPresenceReceived.connect(boost::bind(&VCardUpdateAvatarManager::handlePresenceReceived, this, _1));
+ stanzaChannel->onAvailableChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged, this, _1));
+ vcardManager_->onVCardChanged.connect(boost::bind(&VCardUpdateAvatarManager::handleVCardChanged, this, _1, _2));
}
void VCardUpdateAvatarManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) {
- boost::shared_ptr<VCardUpdate> update = presence->getPayload<VCardUpdate>();
- if (!update || presence->getPayload<ErrorPayload>()) {
- return;
- }
- JID from = getAvatarJID(presence->getFrom());
- if (getAvatarHash(from) == update->getPhotoHash()) {
- return;
- }
- SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash() << std::endl;
- if (avatarStorage_->hasAvatar(update->getPhotoHash())) {
- setAvatarHash(from, update->getPhotoHash());
- }
- else {
- vcardManager_->requestVCard(from);
- }
+ boost::shared_ptr<VCardUpdate> update = presence->getPayload<VCardUpdate>();
+ if (!update || presence->getPayload<ErrorPayload>()) {
+ return;
+ }
+ JID from = getAvatarJID(presence->getFrom());
+ if (getAvatarHash(from) == update->getPhotoHash()) {
+ return;
+ }
+ SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash() << std::endl;
+ if (avatarStorage_->hasAvatar(update->getPhotoHash())) {
+ setAvatarHash(from, update->getPhotoHash());
+ }
+ else {
+ vcardManager_->requestVCard(from);
+ }
}
void VCardUpdateAvatarManager::handleVCardChanged(const JID& from, VCard::ref vCard) {
- if (!vCard) {
- SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload" << std::endl;
- return;
- }
+ if (!vCard) {
+ SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload" << std::endl;
+ return;
+ }
- if (vCard->getPhoto().empty()) {
- setAvatarHash(from, "");
- }
- else {
- std::string hash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto()));
- if (!avatarStorage_->hasAvatar(hash)) {
- avatarStorage_->addAvatar(hash, vCard->getPhoto());
- }
- setAvatarHash(from, hash);
- }
+ if (vCard->getPhoto().empty()) {
+ setAvatarHash(from, "");
+ }
+ else {
+ std::string hash = Hexify::hexify(crypto_->getSHA1Hash(vCard->getPhoto()));
+ if (!avatarStorage_->hasAvatar(hash)) {
+ avatarStorage_->addAvatar(hash, vCard->getPhoto());
+ }
+ setAvatarHash(from, hash);
+ }
}
void VCardUpdateAvatarManager::setAvatarHash(const JID& from, const std::string& hash) {
- SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash << std::endl;
- avatarHashes_[from] = hash;
- onAvatarChanged(from);
+ SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash << std::endl;
+ avatarHashes_[from] = hash;
+ onAvatarChanged(from);
}
/*
void VCardUpdateAvatarManager::setAvatar(const JID& jid, const ByteArray& avatar) {
- std::string hash = Hexify::hexify(SHA1::getHash(avatar));
- avatarStorage_->addAvatar(hash, avatar);
- setAvatarHash(getAvatarJID(jid), hash);
+ std::string hash = Hexify::hexify(SHA1::getHash(avatar));
+ avatarStorage_->addAvatar(hash, avatar);
+ setAvatarHash(getAvatarJID(jid), hash);
}
*/
boost::optional<std::string> VCardUpdateAvatarManager::getAvatarHash(const JID& jid) const {
- std::map<JID, std::string>::const_iterator i = avatarHashes_.find(getAvatarJID(jid));
- if (i != avatarHashes_.end()) {
- return i->second;
- }
- else {
- return boost::optional<std::string>();
- }
+ std::map<JID, std::string>::const_iterator i = avatarHashes_.find(getAvatarJID(jid));
+ if (i != avatarHashes_.end()) {
+ return i->second;
+ }
+ else {
+ return boost::optional<std::string>();
+ }
}
JID VCardUpdateAvatarManager::getAvatarJID(const JID& jid) const {
- JID bareFrom = jid.toBare();
- return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom;
+ JID bareFrom = jid.toBare();
+ return (mucRegistry_ && mucRegistry_->isMUC(bareFrom)) ? jid : bareFrom;
}
void VCardUpdateAvatarManager::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- std::map<JID, std::string> oldAvatarHashes;
- avatarHashes_.swap(oldAvatarHashes);
- for(std::map<JID, std::string>::const_iterator i = oldAvatarHashes.begin(); i != oldAvatarHashes.end(); ++i) {
- onAvatarChanged(i->first);
- }
- }
+ if (available) {
+ std::map<JID, std::string> oldAvatarHashes;
+ avatarHashes_.swap(oldAvatarHashes);
+ for(std::map<JID, std::string>::const_iterator i = oldAvatarHashes.begin(); i != oldAvatarHashes.end(); ++i) {
+ onAvatarChanged(i->first);
+ }
+ }
}
diff --git a/Swiften/Avatars/VCardUpdateAvatarManager.h b/Swiften/Avatars/VCardUpdateAvatarManager.h
index ffc615e..07fe011 100644
--- a/Swiften/Avatars/VCardUpdateAvatarManager.h
+++ b/Swiften/Avatars/VCardUpdateAvatarManager.h
@@ -18,30 +18,30 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class MUCRegistry;
- class AvatarStorage;
- class StanzaChannel;
- class VCardManager;
- class CryptoProvider;
-
- class SWIFTEN_API VCardUpdateAvatarManager : public AvatarProvider, public boost::bsignals::trackable {
- public:
- VCardUpdateAvatarManager(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
-
- boost::optional<std::string> getAvatarHash(const JID&) const;
-
- private:
- void handlePresenceReceived(boost::shared_ptr<Presence>);
- void handleStanzaChannelAvailableChanged(bool);
- void handleVCardChanged(const JID& from, VCard::ref);
- void setAvatarHash(const JID& from, const std::string& hash);
- JID getAvatarJID(const JID& o) const;
-
- private:
- VCardManager* vcardManager_;
- AvatarStorage* avatarStorage_;
- CryptoProvider* crypto_;
- MUCRegistry* mucRegistry_;
- std::map<JID, std::string> avatarHashes_;
- };
+ class MUCRegistry;
+ class AvatarStorage;
+ class StanzaChannel;
+ class VCardManager;
+ class CryptoProvider;
+
+ class SWIFTEN_API VCardUpdateAvatarManager : public AvatarProvider, public boost::bsignals::trackable {
+ public:
+ VCardUpdateAvatarManager(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = NULL);
+
+ boost::optional<std::string> getAvatarHash(const JID&) const;
+
+ private:
+ void handlePresenceReceived(boost::shared_ptr<Presence>);
+ void handleStanzaChannelAvailableChanged(bool);
+ void handleVCardChanged(const JID& from, VCard::ref);
+ void setAvatarHash(const JID& from, const std::string& hash);
+ JID getAvatarJID(const JID& o) const;
+
+ private:
+ VCardManager* vcardManager_;
+ AvatarStorage* avatarStorage_;
+ CryptoProvider* crypto_;
+ MUCRegistry* mucRegistry_;
+ std::map<JID, std::string> avatarHashes_;
+ };
}
diff --git a/Swiften/Base/API.h b/Swiften/Base/API.h
index 729b88b..06359ba 100644
--- a/Swiften/Base/API.h
+++ b/Swiften/Base/API.h
@@ -10,7 +10,7 @@
#include <boost/config.hpp>
#ifdef SWIFTEN_STATIC
-# define SWIFTEN_API
+# define SWIFTEN_API
#else
# ifdef SWIFTEN_PLATFORM_WINDOWS
# ifdef SWIFTEN_BUILDING
@@ -21,7 +21,7 @@
# elif __GNUC__ >= 4
# define SWIFTEN_API __attribute__((visibility("default")))
# else
-# define SWIFTEN_API
+# define SWIFTEN_API
# endif
#endif
@@ -30,9 +30,9 @@
# define SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(cls)
#else
# define SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(cls) \
- cls(const cls&) = default;
+ cls(const cls&) = default;
# define SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(cls) \
- cls& operator=(const cls&) = default;
+ cls& operator=(const cls&) = default;
#endif
#ifdef BOOST_NO_NOEXCEPT
diff --git a/Swiften/Base/Algorithm.h b/Swiften/Base/Algorithm.h
index 99a0053..c481aa8 100644
--- a/Swiften/Base/Algorithm.h
+++ b/Swiften/Base/Algorithm.h
@@ -14,142 +14,142 @@
namespace Swift {
- /*
- * Generic erase()
- */
- namespace Detail {
- struct VectorCategory {};
- struct ListCategory {};
- struct MapCategory {};
-
- template<typename T>
- struct ContainerTraits;
-
- template<typename A, typename B>
- struct ContainerTraits< std::vector<A, B> > {
- typedef VectorCategory Category;
- };
-
- template<>
- struct ContainerTraits< std::string > {
- typedef VectorCategory Category;
- };
-
- template<typename A, typename B>
- struct ContainerTraits< std::list<A, B> > {
- typedef ListCategory Category;
- };
-
- template<typename A, typename B, typename C, typename D>
- struct ContainerTraits< std::map<A, B, C, D> > {
- typedef MapCategory Category;
- };
-
- template<typename C, typename V>
- void eraseImpl(C& c, const V& v, VectorCategory) {
- c.erase(std::remove(c.begin(), c.end(), v), c.end());
- }
-
- template<typename C, typename V>
- void eraseImpl(C& c, const V& v, ListCategory) {
- c.remove(v);
- }
-
- template<typename C, typename V>
- void eraseImpl(C& c, const V& v, MapCategory) {
- for (typename C::iterator it = c.begin(); it != c.end(); ) {
- if (it->second == v) {
- c.erase(it++);
- }
- else {
- ++it;
- }
- }
- }
-
- template<typename C, typename P>
- void eraseIfImpl(C& c, const P& p, MapCategory) {
- for (typename C::iterator it = c.begin(); it != c.end(); ) {
- if (p(*it)) {
- c.erase(it++);
- }
- else {
- ++it;
- }
- }
- }
-
- template<typename C, typename P>
- void eraseIfImpl(C& c, const P& p, VectorCategory) {
- c.erase(std::remove_if(c.begin(), c.end(), p), c.end());
- }
- }
-
- template<typename C, typename V>
- void erase(C& container, const V& value) {
- Detail::eraseImpl(container, value, typename Detail::ContainerTraits<C>::Category());
- }
-
- template<typename C, typename P>
- void eraseIf(C& container, const P& predicate) {
- Detail::eraseIfImpl(container, predicate, typename Detail::ContainerTraits<C>::Category());
- }
-
- template<typename Source, typename Target>
- void append(Target& target, const Source& source) {
- target.insert(target.end(), source.begin(), source.end());
- }
-
- template<typename Source, typename Target>
- void assign(Target& target, const Source& source) {
- target.assign(source.begin(), source.end());
- }
-
- template<typename A, typename B, typename C, typename D>
- B get(const std::map<A, B, C, D>& map, const A& key, const B& defaultValue) {
- typename std::map<A, B, C, D>::const_iterator i = map.find(key);
- if (i != map.end()) {
- return i->second;
- }
- else {
- return defaultValue;
- }
- }
-
- template<typename Container>
- void safeClear(Container& c) {
- std::fill(c.begin(), c.end(), 0);
- c.clear();
- }
-
- /*
- * Functors
- */
- template<typename K, typename V>
- class PairFirstEquals {
- public:
- PairFirstEquals(const K& value) : value(value) {
- }
-
- bool operator()(const std::pair<K,V>& pair) const {
- return pair.first == value;
- }
-
- private:
- K value;
- };
-
- template<typename K, typename V>
- class PairSecondEquals {
- public:
- PairSecondEquals(const V& value) : value(value) {
- }
-
- bool operator()(const std::pair<K,V>& pair) const {
- return pair.second == value;
- }
-
- private:
- V value;
- };
+ /*
+ * Generic erase()
+ */
+ namespace Detail {
+ struct VectorCategory {};
+ struct ListCategory {};
+ struct MapCategory {};
+
+ template<typename T>
+ struct ContainerTraits;
+
+ template<typename A, typename B>
+ struct ContainerTraits< std::vector<A, B> > {
+ typedef VectorCategory Category;
+ };
+
+ template<>
+ struct ContainerTraits< std::string > {
+ typedef VectorCategory Category;
+ };
+
+ template<typename A, typename B>
+ struct ContainerTraits< std::list<A, B> > {
+ typedef ListCategory Category;
+ };
+
+ template<typename A, typename B, typename C, typename D>
+ struct ContainerTraits< std::map<A, B, C, D> > {
+ typedef MapCategory Category;
+ };
+
+ template<typename C, typename V>
+ void eraseImpl(C& c, const V& v, VectorCategory) {
+ c.erase(std::remove(c.begin(), c.end(), v), c.end());
+ }
+
+ template<typename C, typename V>
+ void eraseImpl(C& c, const V& v, ListCategory) {
+ c.remove(v);
+ }
+
+ template<typename C, typename V>
+ void eraseImpl(C& c, const V& v, MapCategory) {
+ for (typename C::iterator it = c.begin(); it != c.end(); ) {
+ if (it->second == v) {
+ c.erase(it++);
+ }
+ else {
+ ++it;
+ }
+ }
+ }
+
+ template<typename C, typename P>
+ void eraseIfImpl(C& c, const P& p, MapCategory) {
+ for (typename C::iterator it = c.begin(); it != c.end(); ) {
+ if (p(*it)) {
+ c.erase(it++);
+ }
+ else {
+ ++it;
+ }
+ }
+ }
+
+ template<typename C, typename P>
+ void eraseIfImpl(C& c, const P& p, VectorCategory) {
+ c.erase(std::remove_if(c.begin(), c.end(), p), c.end());
+ }
+ }
+
+ template<typename C, typename V>
+ void erase(C& container, const V& value) {
+ Detail::eraseImpl(container, value, typename Detail::ContainerTraits<C>::Category());
+ }
+
+ template<typename C, typename P>
+ void eraseIf(C& container, const P& predicate) {
+ Detail::eraseIfImpl(container, predicate, typename Detail::ContainerTraits<C>::Category());
+ }
+
+ template<typename Source, typename Target>
+ void append(Target& target, const Source& source) {
+ target.insert(target.end(), source.begin(), source.end());
+ }
+
+ template<typename Source, typename Target>
+ void assign(Target& target, const Source& source) {
+ target.assign(source.begin(), source.end());
+ }
+
+ template<typename A, typename B, typename C, typename D>
+ B get(const std::map<A, B, C, D>& map, const A& key, const B& defaultValue) {
+ typename std::map<A, B, C, D>::const_iterator i = map.find(key);
+ if (i != map.end()) {
+ return i->second;
+ }
+ else {
+ return defaultValue;
+ }
+ }
+
+ template<typename Container>
+ void safeClear(Container& c) {
+ std::fill(c.begin(), c.end(), 0);
+ c.clear();
+ }
+
+ /*
+ * Functors
+ */
+ template<typename K, typename V>
+ class PairFirstEquals {
+ public:
+ PairFirstEquals(const K& value) : value(value) {
+ }
+
+ bool operator()(const std::pair<K,V>& pair) const {
+ return pair.first == value;
+ }
+
+ private:
+ K value;
+ };
+
+ template<typename K, typename V>
+ class PairSecondEquals {
+ public:
+ PairSecondEquals(const V& value) : value(value) {
+ }
+
+ bool operator()(const std::pair<K,V>& pair) const {
+ return pair.second == value;
+ }
+
+ private:
+ V value;
+ };
}
diff --git a/Swiften/Base/Atomic.h b/Swiften/Base/Atomic.h
index bca3683..9640500 100644
--- a/Swiften/Base/Atomic.h
+++ b/Swiften/Base/Atomic.h
@@ -12,34 +12,34 @@
namespace Swift {
/**
- * This class template provides a read/write access synchronized wrapper for other types.
+ * This class template provides a read/write access synchronized wrapper for other types.
*/
template <typename ValueType>
class Atomic {
- public:
- Atomic(const ValueType& v) : value_(v) {
- }
-
- /**
- * Synchronized write access.
- */
- Atomic<ValueType>& operator=(const ValueType& newValue) {
- boost::lock_guard<boost::mutex> lock(valueMutex_);
- value_ = newValue;
- return *this;
- }
-
- /**
- * Synchronized read access.
- */
- operator ValueType() {
- boost::lock_guard<boost::mutex> lock(valueMutex_);
- return value_;
- }
-
- private:
- boost::mutex valueMutex_;
- ValueType value_;
+ public:
+ Atomic(const ValueType& v) : value_(v) {
+ }
+
+ /**
+ * Synchronized write access.
+ */
+ Atomic<ValueType>& operator=(const ValueType& newValue) {
+ boost::lock_guard<boost::mutex> lock(valueMutex_);
+ value_ = newValue;
+ return *this;
+ }
+
+ /**
+ * Synchronized read access.
+ */
+ operator ValueType() {
+ boost::lock_guard<boost::mutex> lock(valueMutex_);
+ return value_;
+ }
+
+ private:
+ boost::mutex valueMutex_;
+ ValueType value_;
};
}
diff --git a/Swiften/Base/BoostRandomGenerator.cpp b/Swiften/Base/BoostRandomGenerator.cpp
index 8826680..8db3ca6 100644
--- a/Swiften/Base/BoostRandomGenerator.cpp
+++ b/Swiften/Base/BoostRandomGenerator.cpp
@@ -15,13 +15,13 @@
namespace Swift {
BoostRandomGenerator::BoostRandomGenerator() {
- // FIXME: Not a good seed
- generator.seed(static_cast<unsigned int>(std::time(0)));
+ // FIXME: Not a good seed
+ generator.seed(static_cast<unsigned int>(std::time(0)));
}
int BoostRandomGenerator::generateRandomInteger(int maximum) {
- boost::uniform_int<> distribution(0, maximum);
- return distribution(generator);
+ boost::uniform_int<> distribution(0, maximum);
+ return distribution(generator);
}
}
diff --git a/Swiften/Base/BoostRandomGenerator.h b/Swiften/Base/BoostRandomGenerator.h
index 5f1786b..ff715c3 100644
--- a/Swiften/Base/BoostRandomGenerator.h
+++ b/Swiften/Base/BoostRandomGenerator.h
@@ -13,13 +13,13 @@
#include <Swiften/Base/RandomGenerator.h>
namespace Swift {
- class SWIFTEN_API BoostRandomGenerator : public RandomGenerator {
- public:
- BoostRandomGenerator();
+ class SWIFTEN_API BoostRandomGenerator : public RandomGenerator {
+ public:
+ BoostRandomGenerator();
- int generateRandomInteger(int max) SWIFTEN_OVERRIDE;
+ int generateRandomInteger(int max) SWIFTEN_OVERRIDE;
- private:
- boost::mt19937 generator;
- };
+ private:
+ boost::mt19937 generator;
+ };
}
diff --git a/Swiften/Base/ByteArray.cpp b/Swiften/Base/ByteArray.cpp
index 5fc0752..882421d 100644
--- a/Swiften/Base/ByteArray.cpp
+++ b/Swiften/Base/ByteArray.cpp
@@ -14,37 +14,37 @@ namespace Swift {
static const int BUFFER_SIZE = 4096;
void readByteArrayFromFile(ByteArray& data, const boost::filesystem::path& file) {
- boost::filesystem::ifstream input(file, std::ios_base::in|std::ios_base::binary);
- while (input.good()) {
- size_t oldSize = data.size();
- data.resize(oldSize + BUFFER_SIZE);
- input.read(reinterpret_cast<char*>(&data[oldSize]), BUFFER_SIZE);
- data.resize(oldSize + boost::numeric_cast<size_t>(input.gcount()));
- }
- input.close();
+ boost::filesystem::ifstream input(file, std::ios_base::in|std::ios_base::binary);
+ while (input.good()) {
+ size_t oldSize = data.size();
+ data.resize(oldSize + BUFFER_SIZE);
+ input.read(reinterpret_cast<char*>(&data[oldSize]), BUFFER_SIZE);
+ data.resize(oldSize + boost::numeric_cast<size_t>(input.gcount()));
+ }
+ input.close();
}
std::vector<unsigned char> createByteArray(const std::string& s) {
- return std::vector<unsigned char>(s.begin(), s.end());
+ return std::vector<unsigned char>(s.begin(), s.end());
}
std::vector<unsigned char> createByteArray(const char* c) {
- std::vector<unsigned char> data;
- while (*c) {
- data.push_back(static_cast<unsigned char>(*c));
- ++c;
- }
- return data;
+ std::vector<unsigned char> data;
+ while (*c) {
+ data.push_back(static_cast<unsigned char>(*c));
+ ++c;
+ }
+ return data;
}
std::string byteArrayToString(const ByteArray& b) {
- size_t i;
- for (i = b.size(); i > 0; --i) {
- if (b[i - 1] != 0) {
- break;
- }
- }
- return i > 0 ? std::string(reinterpret_cast<const char*>(vecptr(b)), i) : "";
+ size_t i;
+ for (i = b.size(); i > 0; --i) {
+ if (b[i - 1] != 0) {
+ break;
+ }
+ }
+ return i > 0 ? std::string(reinterpret_cast<const char*>(vecptr(b)), i) : "";
}
}
diff --git a/Swiften/Base/ByteArray.h b/Swiften/Base/ByteArray.h
index 75f184a..c0babdf 100644
--- a/Swiften/Base/ByteArray.h
+++ b/Swiften/Base/ByteArray.h
@@ -14,35 +14,35 @@
#include <Swiften/Base/API.h>
namespace Swift {
- typedef std::vector<unsigned char> ByteArray;
+ typedef std::vector<unsigned char> ByteArray;
- SWIFTEN_API ByteArray createByteArray(const std::string& s);
- SWIFTEN_API ByteArray createByteArray(const char* c);
+ SWIFTEN_API ByteArray createByteArray(const std::string& s);
+ SWIFTEN_API ByteArray createByteArray(const char* c);
- inline ByteArray createByteArray(const unsigned char* c, size_t n) {
- return ByteArray(c, c + n);
- }
+ inline ByteArray createByteArray(const unsigned char* c, size_t n) {
+ return ByteArray(c, c + n);
+ }
- inline ByteArray createByteArray(const char* c, size_t n) {
- return ByteArray(c, c + n);
- }
+ inline ByteArray createByteArray(const char* c, size_t n) {
+ return ByteArray(c, c + n);
+ }
- inline ByteArray createByteArray(char c) {
- return std::vector<unsigned char>(1, static_cast<unsigned char>(c));
- }
+ inline ByteArray createByteArray(char c) {
+ return std::vector<unsigned char>(1, static_cast<unsigned char>(c));
+ }
- template<typename T, typename A>
- static const T* vecptr(const std::vector<T, A>& v) {
- return v.empty() ? NULL : &v[0];
- }
+ template<typename T, typename A>
+ static const T* vecptr(const std::vector<T, A>& v) {
+ return v.empty() ? NULL : &v[0];
+ }
- template<typename T, typename A>
- static T* vecptr(std::vector<T, A>& v) {
- return v.empty() ? NULL : &v[0];
- }
-
- SWIFTEN_API std::string byteArrayToString(const ByteArray& b);
+ template<typename T, typename A>
+ static T* vecptr(std::vector<T, A>& v) {
+ return v.empty() ? NULL : &v[0];
+ }
- SWIFTEN_API void readByteArrayFromFile(ByteArray&, const boost::filesystem::path& file);
+ SWIFTEN_API std::string byteArrayToString(const ByteArray& b);
+
+ SWIFTEN_API void readByteArrayFromFile(ByteArray&, const boost::filesystem::path& file);
}
diff --git a/Swiften/Base/Concat.h b/Swiften/Base/Concat.h
index 1d158d5..df5d77b 100644
--- a/Swiften/Base/Concat.h
+++ b/Swiften/Base/Concat.h
@@ -9,67 +9,67 @@
#include <algorithm>
namespace Swift {
- template<typename C>
- C concat(const C& c1, const C& c2) {
- C result;
- result.resize(c1.size() + c2.size());
- std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2) {
+ C result;
+ result.resize(c1.size() + c2.size());
+ std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size());
- std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size());
+ std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size());
- std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size());
+ std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size());
- std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size());
+ std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size());
- std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size());
+ std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size());
- std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size());
+ std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size());
- std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size());
+ std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin()))))))));
+ return result;
+ }
- template<typename C>
- C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8, const C& c9) {
- C result;
- result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size() + c9.size());
- std::copy(c9.begin(), c9.end(), std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))))));
- return result;
- }
+ template<typename C>
+ C concat(const C& c1, const C& c2, const C& c3, const C& c4, const C& c5, const C& c6, const C& c7, const C& c8, const C& c9) {
+ C result;
+ result.resize(c1.size() + c2.size() + c3.size() + c4.size() + c5.size() + c6.size() + c7.size() + c8.size() + c9.size());
+ std::copy(c9.begin(), c9.end(), std::copy(c8.begin(), c8.end(), std::copy(c7.begin(), c7.end(), std::copy(c6.begin(), c6.end(), std::copy(c5.begin(), c5.end(), std::copy(c4.begin(), c4.end(), std::copy(c3.begin(), c3.end(), std::copy(c2.begin(), c2.end(), std::copy(c1.begin(), c1.end(), result.begin())))))))));
+ return result;
+ }
}
diff --git a/Swiften/Base/DateTime.cpp b/Swiften/Base/DateTime.cpp
index 9ca5fac..4443566 100644
--- a/Swiften/Base/DateTime.cpp
+++ b/Swiften/Base/DateTime.cpp
@@ -19,30 +19,30 @@
namespace Swift {
boost::posix_time::ptime stringToDateTime(const std::string& string) {
- static std::locale locale(std::locale::classic(), new boost::local_time::local_time_input_facet("%Y-%m-%d %H:%M:%S%F%ZP"));
- std::istringstream stream(string);
- stream.imbue(locale);
- boost::local_time::local_date_time result(boost::date_time::not_a_date_time);
- stream >> result;
- return result.utc_time();
+ static std::locale locale(std::locale::classic(), new boost::local_time::local_time_input_facet("%Y-%m-%d %H:%M:%S%F%ZP"));
+ std::istringstream stream(string);
+ stream.imbue(locale);
+ boost::local_time::local_date_time result(boost::date_time::not_a_date_time);
+ stream >> result;
+ return result.utc_time();
}
std::string dateTimeToString(const boost::posix_time::ptime& time) {
- std::string stampString = std::string(boost::posix_time::to_iso_extended_string(time));
- String::replaceAll(stampString, ',', ".");
- stampString += "Z";
- return stampString;
+ std::string stampString = std::string(boost::posix_time::to_iso_extended_string(time));
+ String::replaceAll(stampString, ',', ".");
+ stampString += "Z";
+ return stampString;
}
std::string dateTimeToLocalString(const boost::posix_time::ptime& time) {
- std::string localString;
- try {
- localString = boost::posix_time::to_simple_string(boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(time));
- }
- catch(std::out_of_range& exception) {
- SWIFT_LOG(debug) << exception.what() << std::endl;
- }
- return localString;
+ std::string localString;
+ try {
+ localString = boost::posix_time::to_simple_string(boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(time));
+ }
+ catch(std::out_of_range& exception) {
+ SWIFT_LOG(debug) << exception.what() << std::endl;
+ }
+ return localString;
}
}
diff --git a/Swiften/Base/DateTime.h b/Swiften/Base/DateTime.h
index 8f07982..36cff65 100644
--- a/Swiften/Base/DateTime.h
+++ b/Swiften/Base/DateTime.h
@@ -11,19 +11,19 @@
#include <Swiften/Base/API.h>
namespace Swift {
- /**
- * Converts a date formatted according to XEP-0082 into a ptime
- * object (in UTC).
- */
- SWIFTEN_API boost::posix_time::ptime stringToDateTime(const std::string& string);
+ /**
+ * Converts a date formatted according to XEP-0082 into a ptime
+ * object (in UTC).
+ */
+ SWIFTEN_API boost::posix_time::ptime stringToDateTime(const std::string& string);
- /**
- * Converts a UTC ptime object to a XEP-0082 formatted string.
- */
- SWIFTEN_API std::string dateTimeToString(const boost::posix_time::ptime& time);
+ /**
+ * Converts a UTC ptime object to a XEP-0082 formatted string.
+ */
+ SWIFTEN_API std::string dateTimeToString(const boost::posix_time::ptime& time);
- /**
- * Converts a UTC ptime object to a localized human readable string.
- */
- SWIFTEN_API std::string dateTimeToLocalString(const boost::posix_time::ptime& time);
+ /**
+ * Converts a UTC ptime object to a localized human readable string.
+ */
+ SWIFTEN_API std::string dateTimeToLocalString(const boost::posix_time::ptime& time);
}
diff --git a/Swiften/Base/Debug.cpp b/Swiften/Base/Debug.cpp
index 82dbec6..2d306d5 100644
--- a/Swiften/Base/Debug.cpp
+++ b/Swiften/Base/Debug.cpp
@@ -16,126 +16,126 @@
#include <Swiften/Serializer/XMPPSerializer.h>
std::ostream& operator<<(std::ostream& os, const Swift::ClientError& error) {
- os << "ClientError(";
- switch(error.getType()) {
- case Swift::ClientError::UnknownError:
- os << "UnknownError";
- break;
- case Swift::ClientError::DomainNameResolveError:
- os << "DomainNameResolveError";
- break;
- case Swift::ClientError::ConnectionError:
- os << "ConnectionError";
- break;
- case Swift::ClientError::ConnectionReadError:
- os << "ConnectionReadError";
- break;
- case Swift::ClientError::ConnectionWriteError:
- os << "ConnectionWriteError";
- break;
- case Swift::ClientError::XMLError:
- os << "XMLError";
- break;
- case Swift::ClientError::AuthenticationFailedError:
- os << "AuthenticationFailedError";
- break;
- case Swift::ClientError::CompressionFailedError:
- os << "CompressionFailedError";
- break;
- case Swift::ClientError::ServerVerificationFailedError:
- os << "ServerVerificationFailedError";
- break;
- case Swift::ClientError::NoSupportedAuthMechanismsError:
- os << "NoSupportedAuthMechanismsError";
- break;
- case Swift::ClientError::UnexpectedElementError:
- os << "UnexpectedElementError";
- break;
- case Swift::ClientError::ResourceBindError:
- os << "ResourceBindError";
- break;
- case Swift::ClientError::SessionStartError:
- os << "SessionStartError";
- break;
- case Swift::ClientError::StreamError:
- os << "StreamError";
- break;
- case Swift::ClientError::TLSError:
- os << "TLSError";
- break;
- case Swift::ClientError::ClientCertificateLoadError:
- os << "ClientCertificateLoadError";
- break;
- case Swift::ClientError::ClientCertificateError:
- os << "ClientCertificateError";
- break;
- case Swift::ClientError::CertificateCardRemoved:
- os << "CertificateCardRemoved";
- break;
- case Swift::ClientError::UnknownCertificateError:
- os << "UnknownCertificateError";
- break;
- case Swift::ClientError::CertificateExpiredError:
- os << "CertificateExpiredError";
- break;
- case Swift::ClientError::CertificateNotYetValidError:
- os << "CertificateNotYetValidError";
- break;
- case Swift::ClientError::CertificateSelfSignedError:
- os << "CertificateSelfSignedError";
- break;
- case Swift::ClientError::CertificateRejectedError:
- os << "CertificateRejectedError";
- break;
- case Swift::ClientError::CertificateUntrustedError:
- os << "CertificateUntrustedError";
- break;
- case Swift::ClientError::InvalidCertificatePurposeError:
- os << "InvalidCertificatePurposeError";
- break;
- case Swift::ClientError::CertificatePathLengthExceededError:
- os << "CertificatePathLengthExceededError";
- break;
- case Swift::ClientError::InvalidCertificateSignatureError:
- os << "InvalidCertificateSignatureError";
- break;
- case Swift::ClientError::InvalidCAError:
- os << "InvalidCAError";
- break;
- case Swift::ClientError::InvalidServerIdentityError:
- os << "InvalidServerIdentityError";
- break;
- case Swift::ClientError::RevokedError:
- os << "RevokedError";
- break;
- case Swift::ClientError::RevocationCheckFailedError:
- os << "RevocationCheckFailedError";
- break;
- }
- os << ")";
- return os;
+ os << "ClientError(";
+ switch(error.getType()) {
+ case Swift::ClientError::UnknownError:
+ os << "UnknownError";
+ break;
+ case Swift::ClientError::DomainNameResolveError:
+ os << "DomainNameResolveError";
+ break;
+ case Swift::ClientError::ConnectionError:
+ os << "ConnectionError";
+ break;
+ case Swift::ClientError::ConnectionReadError:
+ os << "ConnectionReadError";
+ break;
+ case Swift::ClientError::ConnectionWriteError:
+ os << "ConnectionWriteError";
+ break;
+ case Swift::ClientError::XMLError:
+ os << "XMLError";
+ break;
+ case Swift::ClientError::AuthenticationFailedError:
+ os << "AuthenticationFailedError";
+ break;
+ case Swift::ClientError::CompressionFailedError:
+ os << "CompressionFailedError";
+ break;
+ case Swift::ClientError::ServerVerificationFailedError:
+ os << "ServerVerificationFailedError";
+ break;
+ case Swift::ClientError::NoSupportedAuthMechanismsError:
+ os << "NoSupportedAuthMechanismsError";
+ break;
+ case Swift::ClientError::UnexpectedElementError:
+ os << "UnexpectedElementError";
+ break;
+ case Swift::ClientError::ResourceBindError:
+ os << "ResourceBindError";
+ break;
+ case Swift::ClientError::SessionStartError:
+ os << "SessionStartError";
+ break;
+ case Swift::ClientError::StreamError:
+ os << "StreamError";
+ break;
+ case Swift::ClientError::TLSError:
+ os << "TLSError";
+ break;
+ case Swift::ClientError::ClientCertificateLoadError:
+ os << "ClientCertificateLoadError";
+ break;
+ case Swift::ClientError::ClientCertificateError:
+ os << "ClientCertificateError";
+ break;
+ case Swift::ClientError::CertificateCardRemoved:
+ os << "CertificateCardRemoved";
+ break;
+ case Swift::ClientError::UnknownCertificateError:
+ os << "UnknownCertificateError";
+ break;
+ case Swift::ClientError::CertificateExpiredError:
+ os << "CertificateExpiredError";
+ break;
+ case Swift::ClientError::CertificateNotYetValidError:
+ os << "CertificateNotYetValidError";
+ break;
+ case Swift::ClientError::CertificateSelfSignedError:
+ os << "CertificateSelfSignedError";
+ break;
+ case Swift::ClientError::CertificateRejectedError:
+ os << "CertificateRejectedError";
+ break;
+ case Swift::ClientError::CertificateUntrustedError:
+ os << "CertificateUntrustedError";
+ break;
+ case Swift::ClientError::InvalidCertificatePurposeError:
+ os << "InvalidCertificatePurposeError";
+ break;
+ case Swift::ClientError::CertificatePathLengthExceededError:
+ os << "CertificatePathLengthExceededError";
+ break;
+ case Swift::ClientError::InvalidCertificateSignatureError:
+ os << "InvalidCertificateSignatureError";
+ break;
+ case Swift::ClientError::InvalidCAError:
+ os << "InvalidCAError";
+ break;
+ case Swift::ClientError::InvalidServerIdentityError:
+ os << "InvalidServerIdentityError";
+ break;
+ case Swift::ClientError::RevokedError:
+ os << "RevokedError";
+ break;
+ case Swift::ClientError::RevocationCheckFailedError:
+ os << "RevocationCheckFailedError";
+ break;
+ }
+ os << ")";
+ return os;
}
std::ostream& operator<<(std::ostream& os, Swift::Element* ele) {
- using namespace Swift;
+ using namespace Swift;
- boost::shared_ptr<Element> element = boost::shared_ptr<Element>(ele);
+ boost::shared_ptr<Element> element = boost::shared_ptr<Element>(ele);
- boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
- if (payload) {
- FullPayloadSerializerCollection payloadSerializerCollection;
- PayloadSerializer *serializer = payloadSerializerCollection.getPayloadSerializer(payload);
- os << "Payload(" << serializer->serialize(payload) << ")";
- return os;
- }
- boost::shared_ptr<ToplevelElement> topLevelElement = boost::dynamic_pointer_cast<ToplevelElement>(element);
- if (topLevelElement) {
- FullPayloadSerializerCollection payloadSerializerCollection;
- XMPPSerializer xmppSerializer(&payloadSerializerCollection, ClientStreamType, false);
- SafeByteArray serialized = xmppSerializer.serializeElement(topLevelElement);
- os << "TopLevelElement(" << safeByteArrayToString(serialized) << ")";
- return os;
- }
- os << "Element(Unknown)";
- return os;
+ boost::shared_ptr<Payload> payload = boost::dynamic_pointer_cast<Payload>(element);
+ if (payload) {
+ FullPayloadSerializerCollection payloadSerializerCollection;
+ PayloadSerializer *serializer = payloadSerializerCollection.getPayloadSerializer(payload);
+ os << "Payload(" << serializer->serialize(payload) << ")";
+ return os;
+ }
+ boost::shared_ptr<ToplevelElement> topLevelElement = boost::dynamic_pointer_cast<ToplevelElement>(element);
+ if (topLevelElement) {
+ FullPayloadSerializerCollection payloadSerializerCollection;
+ XMPPSerializer xmppSerializer(&payloadSerializerCollection, ClientStreamType, false);
+ SafeByteArray serialized = xmppSerializer.serializeElement(topLevelElement);
+ os << "TopLevelElement(" << safeByteArrayToString(serialized) << ")";
+ return os;
+ }
+ os << "Element(Unknown)";
+ return os;
}
diff --git a/Swiften/Base/Debug.h b/Swiften/Base/Debug.h
index 33d439e..18e7fb4 100644
--- a/Swiften/Base/Debug.h
+++ b/Swiften/Base/Debug.h
@@ -7,12 +7,12 @@
#include <iosfwd>
namespace Swift {
- class ClientError;
- class Element;
+ class ClientError;
+ class Element;
}
namespace boost {
- template<class T> class shared_ptr;
+ template<class T> class shared_ptr;
}
std::ostream& operator<<(std::ostream& os, const Swift::ClientError& error);
diff --git a/Swiften/Base/Error.h b/Swiften/Base/Error.h
index 3589bf0..d470b89 100644
--- a/Swiften/Base/Error.h
+++ b/Swiften/Base/Error.h
@@ -9,10 +9,10 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API Error {
- public:
- Error() {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Error)
- virtual ~Error();
- };
+ class SWIFTEN_API Error {
+ public:
+ Error() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Error)
+ virtual ~Error();
+ };
}
diff --git a/Swiften/Base/FileSize.cpp b/Swiften/Base/FileSize.cpp
index 32ab5f5..d9ab5ec 100644
--- a/Swiften/Base/FileSize.cpp
+++ b/Swiften/Base/FileSize.cpp
@@ -11,14 +11,14 @@
namespace Swift {
std::string formatSize(const boost::uintmax_t bytes) {
- static const char *siPrefix[] = {"k", "M", "G", "T", "P", "E", "Z", "Y", NULL};
- int power = 0;
- double engBytes = bytes;
- while (engBytes >= 1000) {
- ++power;
- engBytes = engBytes / 1000.0;
- }
- return str( boost::format("%.1lf %sB") % engBytes % (power > 0 ? siPrefix[power-1] : "") );
+ static const char *siPrefix[] = {"k", "M", "G", "T", "P", "E", "Z", "Y", NULL};
+ int power = 0;
+ double engBytes = bytes;
+ while (engBytes >= 1000) {
+ ++power;
+ engBytes = engBytes / 1000.0;
+ }
+ return str( boost::format("%.1lf %sB") % engBytes % (power > 0 ? siPrefix[power-1] : "") );
}
}
diff --git a/Swiften/Base/IDGenerator.cpp b/Swiften/Base/IDGenerator.cpp
index 6e5ed88..5aa471c 100644
--- a/Swiften/Base/IDGenerator.cpp
+++ b/Swiften/Base/IDGenerator.cpp
@@ -17,8 +17,8 @@ IDGenerator::IDGenerator() {
}
std::string IDGenerator::generateID() {
- static boost::uuids::random_generator generator;
- return boost::lexical_cast<std::string>(generator());
+ static boost::uuids::random_generator generator;
+ return boost::lexical_cast<std::string>(generator());
}
}
diff --git a/Swiften/Base/IDGenerator.h b/Swiften/Base/IDGenerator.h
index d5407df..d1b5964 100644
--- a/Swiften/Base/IDGenerator.h
+++ b/Swiften/Base/IDGenerator.h
@@ -11,10 +11,10 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API IDGenerator {
- public:
- IDGenerator();
+ class SWIFTEN_API IDGenerator {
+ public:
+ IDGenerator();
- std::string generateID();
- };
+ std::string generateID();
+ };
}
diff --git a/Swiften/Base/Listenable.h b/Swiften/Base/Listenable.h
index 655599a..ae83f4e 100644
--- a/Swiften/Base/Listenable.h
+++ b/Swiften/Base/Listenable.h
@@ -14,42 +14,42 @@
#include <Swiften/Base/API.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API Listenable {
- public:
- void addListener(T* listener) {
- listeners.push_back(listener);
- }
-
- void removeListener(T* listener) {
- listeners.erase(std::remove(listeners.begin(), listeners.end(), listener), listeners.end());
- }
-
- protected:
- template<typename F>
- void notifyListeners(F event) {
- for (typename std::vector<T*>::iterator i = listeners.begin(); i != listeners.end(); ++i) {
- event(*i);
- }
- }
-
- template<typename F, typename A1>
- void notifyListeners(F f, const A1& a1) {
- notifyListeners(boost::bind(f, _1, a1));
- }
-
- template<typename F, typename A1, typename A2>
- void notifyListeners(F f, const A1& a1, const A2& a2) {
- notifyListeners(boost::bind(f, _1, a1, a2));
- }
-
- template<typename F, typename A1, typename A2, typename A3>
- void notifyListeners(F f, const A1& a1, const A2& a2, const A3& a3) {
- notifyListeners(boost::bind(f, _1, a1, a2, a3));
- }
-
- private:
- std::vector<T*> listeners;
- };
+ template<typename T>
+ class SWIFTEN_API Listenable {
+ public:
+ void addListener(T* listener) {
+ listeners.push_back(listener);
+ }
+
+ void removeListener(T* listener) {
+ listeners.erase(std::remove(listeners.begin(), listeners.end(), listener), listeners.end());
+ }
+
+ protected:
+ template<typename F>
+ void notifyListeners(F event) {
+ for (typename std::vector<T*>::iterator i = listeners.begin(); i != listeners.end(); ++i) {
+ event(*i);
+ }
+ }
+
+ template<typename F, typename A1>
+ void notifyListeners(F f, const A1& a1) {
+ notifyListeners(boost::bind(f, _1, a1));
+ }
+
+ template<typename F, typename A1, typename A2>
+ void notifyListeners(F f, const A1& a1, const A2& a2) {
+ notifyListeners(boost::bind(f, _1, a1, a2));
+ }
+
+ template<typename F, typename A1, typename A2, typename A3>
+ void notifyListeners(F f, const A1& a1, const A2& a2, const A3& a3) {
+ notifyListeners(boost::bind(f, _1, a1, a2, a3));
+ }
+
+ private:
+ std::vector<T*> listeners;
+ };
}
diff --git a/Swiften/Base/Log.cpp b/Swiften/Base/Log.cpp
index 4879766..0efac7e 100644
--- a/Swiften/Base/Log.cpp
+++ b/Swiften/Base/Log.cpp
@@ -22,30 +22,30 @@ Log::Log() {
Log::~Log() {
#if defined(SWIFT_ANDROID_LOGGING) && defined(__ANDROID__)
- __android_log_print(ANDROID_LOG_VERBOSE, "Swift", stream.str().c_str(), 1);
+ __android_log_print(ANDROID_LOG_VERBOSE, "Swift", stream.str().c_str(), 1);
#else
- // Using stdio for thread safety (POSIX file i/o calls are guaranteed to be atomic)
- fprintf(stderr, "%s", stream.str().c_str());
- fflush(stderr);
+ // Using stdio for thread safety (POSIX file i/o calls are guaranteed to be atomic)
+ fprintf(stderr, "%s", stream.str().c_str());
+ fflush(stderr);
#endif
}
std::ostringstream& Log::getStream(
- Severity /*severity*/,
- const std::string& severityString,
- const std::string& file,
- int line,
- const std::string& function) {
- stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": ";
- return stream;
+ Severity /*severity*/,
+ const std::string& severityString,
+ const std::string& file,
+ int line,
+ const std::string& function) {
+ stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": ";
+ return stream;
}
Log::Severity Log::getLogLevel() {
- return logLevel;
+ return logLevel;
}
void Log::setLogLevel(Severity level) {
- logLevel = level;
+ logLevel = level;
}
}
diff --git a/Swiften/Base/Log.h b/Swiften/Base/Log.h
index 76251df..33c969d 100644
--- a/Swiften/Base/Log.h
+++ b/Swiften/Base/Log.h
@@ -11,34 +11,34 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API Log {
- public:
- enum Severity {
- error, warning, info, debug
- };
-
- Log();
- ~Log();
-
- std::ostringstream& getStream(
- Severity severity,
- const std::string& severityString,
- const std::string& file,
- int line,
- const std::string& function);
-
- static Severity getLogLevel();
- static void setLogLevel(Severity level);
-
- private:
- std::ostringstream stream;
- };
+ class SWIFTEN_API Log {
+ public:
+ enum Severity {
+ error, warning, info, debug
+ };
+
+ Log();
+ ~Log();
+
+ std::ostringstream& getStream(
+ Severity severity,
+ const std::string& severityString,
+ const std::string& file,
+ int line,
+ const std::string& function);
+
+ static Severity getLogLevel();
+ static void setLogLevel(Severity level);
+
+ private:
+ std::ostringstream stream;
+ };
}
#define SWIFT_LOG(severity) \
- if (Log::severity > Log::getLogLevel()) ; \
- else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__)
+ if (Log::severity > Log::getLogLevel()) ; \
+ else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__)
#define SWIFT_LOG_ASSERT(test, severity) \
- if (Log::severity > Log::getLogLevel() || (test)) ; \
- else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) << "Assertion failed: " << #test << ". "
+ if (Log::severity > Log::getLogLevel() || (test)) ; \
+ else Log().getStream(Log::severity, #severity, __FILE__, __LINE__, __FUNCTION__) << "Assertion failed: " << #test << ". "
diff --git a/Swiften/Base/Path.cpp b/Swiften/Base/Path.cpp
index 448efd8..ffee09b 100644
--- a/Swiften/Base/Path.cpp
+++ b/Swiften/Base/Path.cpp
@@ -13,16 +13,16 @@ using namespace Swift;
boost::filesystem::path Swift::stringToPath(const std::string& path) {
#ifdef SWIFTEN_PLATFORM_WINDOWS
- return boost::filesystem::path(convertStringToWString(path));
+ return boost::filesystem::path(convertStringToWString(path));
#else
- return boost::filesystem::path(path);
+ return boost::filesystem::path(path);
#endif
}
std::string Swift::pathToString(const boost::filesystem::path& path) {
#ifdef SWIFTEN_PLATFORM_WINDOWS
- return convertWStringToString(path.native());
+ return convertWStringToString(path.native());
#else
- return path.native();
+ return path.native();
#endif
}
diff --git a/Swiften/Base/Path.h b/Swiften/Base/Path.h
index 1567a1d..40141b5 100644
--- a/Swiften/Base/Path.h
+++ b/Swiften/Base/Path.h
@@ -13,17 +13,17 @@
#include <Swiften/Base/API.h>
namespace Swift {
- /**
- * Creates a path for the given UTF-8 encoded string.
- * This works independently of global locale settings.
- */
- SWIFTEN_API boost::filesystem::path stringToPath(const std::string&);
-
- /**
- * Returns the UTF-8 representation of the given path
- * This works independently of global locale settings.
- */
- SWIFTEN_API std::string pathToString(const boost::filesystem::path&);
+ /**
+ * Creates a path for the given UTF-8 encoded string.
+ * This works independently of global locale settings.
+ */
+ SWIFTEN_API boost::filesystem::path stringToPath(const std::string&);
+
+ /**
+ * Returns the UTF-8 representation of the given path
+ * This works independently of global locale settings.
+ */
+ SWIFTEN_API std::string pathToString(const boost::filesystem::path&);
}
diff --git a/Swiften/Base/Paths.cpp b/Swiften/Base/Paths.cpp
index c0256e5..cbb16f3 100644
--- a/Swiften/Base/Paths.cpp
+++ b/Swiften/Base/Paths.cpp
@@ -21,28 +21,28 @@ namespace Swift {
boost::filesystem::path Paths::getExecutablePath() {
#if defined(SWIFTEN_PLATFORM_MACOSX)
- ByteArray path;
- uint32_t size = 4096;
- path.resize(size);
- if (_NSGetExecutablePath(const_cast<char*>(reinterpret_cast<const char*>(vecptr(path))), &size) == 0) {
- return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path();
- }
+ ByteArray path;
+ uint32_t size = 4096;
+ path.resize(size);
+ if (_NSGetExecutablePath(const_cast<char*>(reinterpret_cast<const char*>(vecptr(path))), &size) == 0) {
+ return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path();
+ }
#elif defined(SWIFTEN_PLATFORM_LINUX)
- ByteArray path;
- path.resize(4096);
- size_t size = static_cast<size_t>(readlink("/proc/self/exe", reinterpret_cast<char*>(vecptr(path)), path.size()));
- if (size > 0) {
- path.resize(size);
- return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path();
- }
+ ByteArray path;
+ path.resize(4096);
+ size_t size = static_cast<size_t>(readlink("/proc/self/exe", reinterpret_cast<char*>(vecptr(path)), path.size()));
+ if (size > 0) {
+ path.resize(size);
+ return boost::filesystem::path(std::string(reinterpret_cast<const char*>(vecptr(path)), path.size()).c_str()).parent_path();
+ }
#elif defined(SWIFTEN_PLATFORM_WINDOWS)
- std::vector<wchar_t> data;
- data.resize(2048);
- GetModuleFileNameW(NULL, vecptr(data), data.size());
- return boost::filesystem::path(
- std::wstring(vecptr(data), data.size())).parent_path();
+ std::vector<wchar_t> data;
+ data.resize(2048);
+ GetModuleFileNameW(NULL, vecptr(data), data.size());
+ return boost::filesystem::path(
+ std::wstring(vecptr(data), data.size())).parent_path();
#endif
- return boost::filesystem::path();
+ return boost::filesystem::path();
}
}
diff --git a/Swiften/Base/Paths.h b/Swiften/Base/Paths.h
index 0a11b48..71b55fb 100644
--- a/Swiften/Base/Paths.h
+++ b/Swiften/Base/Paths.h
@@ -11,8 +11,8 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API Paths {
- public:
- static boost::filesystem::path getExecutablePath();
- };
+ class SWIFTEN_API Paths {
+ public:
+ static boost::filesystem::path getExecutablePath();
+ };
}
diff --git a/Swiften/Base/RandomGenerator.h b/Swiften/Base/RandomGenerator.h
index b322245..06677ec 100644
--- a/Swiften/Base/RandomGenerator.h
+++ b/Swiften/Base/RandomGenerator.h
@@ -11,14 +11,14 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API RandomGenerator {
- public:
- virtual ~RandomGenerator();
+ class SWIFTEN_API RandomGenerator {
+ public:
+ virtual ~RandomGenerator();
- /**
- * Generates a random integer between 0 and 'max',
- * 'max' inclusive.
- */
- virtual int generateRandomInteger(int max) = 0;
- };
+ /**
+ * Generates a random integer between 0 and 'max',
+ * 'max' inclusive.
+ */
+ virtual int generateRandomInteger(int max) = 0;
+ };
}
diff --git a/Swiften/Base/Regex.cpp b/Swiften/Base/Regex.cpp
index bc7f3ac..7843833 100644
--- a/Swiften/Base/Regex.cpp
+++ b/Swiften/Base/Regex.cpp
@@ -18,20 +18,20 @@
namespace Swift {
- namespace Regex {
- std::string escape(const std::string& source) {
- // escape regex special characters: ^.$| etc
- // these need to be escaped: [\^\$\|.........]
- // and then C++ requires '\' to be escaped, too....
- static const boost::regex esc("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\{\\}\\\\])");
- // matched character should be prepended with '\'
- // replace matched special character with \\\1
- // and escape once more for C++ rules...
- static const std::string rep("\\\\\\1");
- return boost::regex_replace(source, esc, rep);
- }
-
- }
+ namespace Regex {
+ std::string escape(const std::string& source) {
+ // escape regex special characters: ^.$| etc
+ // these need to be escaped: [\^\$\|.........]
+ // and then C++ requires '\' to be escaped, too....
+ static const boost::regex esc("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\{\\}\\\\])");
+ // matched character should be prepended with '\'
+ // replace matched special character with \\\1
+ // and escape once more for C++ rules...
+ static const std::string rep("\\\\\\1");
+ return boost::regex_replace(source, esc, rep);
+ }
+
+ }
}
-
+
diff --git a/Swiften/Base/Regex.h b/Swiften/Base/Regex.h
index 4bffc4d..7d352c0 100644
--- a/Swiften/Base/Regex.h
+++ b/Swiften/Base/Regex.h
@@ -12,8 +12,8 @@
namespace Swift {
- namespace Regex {
- SWIFTEN_API std::string escape(const std::string& source);
- }
+ namespace Regex {
+ SWIFTEN_API std::string escape(const std::string& source);
+ }
}
diff --git a/Swiften/Base/SafeAllocator.cpp b/Swiften/Base/SafeAllocator.cpp
index 87d5fbe..446ed2d 100644
--- a/Swiften/Base/SafeAllocator.cpp
+++ b/Swiften/Base/SafeAllocator.cpp
@@ -15,12 +15,12 @@ namespace Swift {
void secureZeroMemory(char* memory, size_t numberOfBytes) {
#ifdef SWIFTEN_PLATFORM_WINDOWS
- SecureZeroMemory(memory, numberOfBytes);
+ SecureZeroMemory(memory, numberOfBytes);
#else
- volatile char* p = memory;
- for (size_t i = 0; i < numberOfBytes; ++i) {
- *(p++) = 0;
- }
+ volatile char* p = memory;
+ for (size_t i = 0; i < numberOfBytes; ++i) {
+ *(p++) = 0;
+ }
#endif
}
diff --git a/Swiften/Base/SafeAllocator.h b/Swiften/Base/SafeAllocator.h
index 07bec70..0369ec4 100644
--- a/Swiften/Base/SafeAllocator.h
+++ b/Swiften/Base/SafeAllocator.h
@@ -12,25 +12,25 @@
#include <Swiften/Base/API.h>
namespace Swift {
- void secureZeroMemory(char* memory, size_t numberOfBytes);
-
- template<typename T>
- class SWIFTEN_API SafeAllocator : public std::allocator<T> {
- public:
- template <class U> struct rebind {
- typedef SafeAllocator<U> other;
- };
-
- SafeAllocator() SWIFTEN_NOEXCEPT {}
- SafeAllocator(const SafeAllocator&) SWIFTEN_NOEXCEPT : std::allocator<T>() {}
- template <class U> SafeAllocator(const SafeAllocator<U>&) SWIFTEN_NOEXCEPT {}
- ~SafeAllocator() SWIFTEN_NOEXCEPT {}
-
- void deallocate (T* p, size_t num) {
- secureZeroMemory(reinterpret_cast<char*>(p), num);
- std::allocator<T>::deallocate(p, num);
- }
-
- SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(SafeAllocator)
- };
+ void secureZeroMemory(char* memory, size_t numberOfBytes);
+
+ template<typename T>
+ class SWIFTEN_API SafeAllocator : public std::allocator<T> {
+ public:
+ template <class U> struct rebind {
+ typedef SafeAllocator<U> other;
+ };
+
+ SafeAllocator() SWIFTEN_NOEXCEPT {}
+ SafeAllocator(const SafeAllocator&) SWIFTEN_NOEXCEPT : std::allocator<T>() {}
+ template <class U> SafeAllocator(const SafeAllocator<U>&) SWIFTEN_NOEXCEPT {}
+ ~SafeAllocator() SWIFTEN_NOEXCEPT {}
+
+ void deallocate (T* p, size_t num) {
+ secureZeroMemory(reinterpret_cast<char*>(p), num);
+ std::allocator<T>::deallocate(p, num);
+ }
+
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(SafeAllocator)
+ };
}
diff --git a/Swiften/Base/SafeByteArray.cpp b/Swiften/Base/SafeByteArray.cpp
index 9ae73f6..dd3736e 100644
--- a/Swiften/Base/SafeByteArray.cpp
+++ b/Swiften/Base/SafeByteArray.cpp
@@ -11,12 +11,12 @@ using namespace Swift;
namespace Swift {
SafeByteArray createSafeByteArray(const char* c) {
- SafeByteArray data;
- while (*c) {
- data.push_back(static_cast<unsigned char>(*c));
- ++c;
- }
- return data;
+ SafeByteArray data;
+ while (*c) {
+ data.push_back(static_cast<unsigned char>(*c));
+ ++c;
+ }
+ return data;
}
}
diff --git a/Swiften/Base/SafeByteArray.h b/Swiften/Base/SafeByteArray.h
index 77be012..f824194 100644
--- a/Swiften/Base/SafeByteArray.h
+++ b/Swiften/Base/SafeByteArray.h
@@ -15,46 +15,46 @@
#include <Swiften/Base/SafeAllocator.h>
namespace Swift {
- typedef std::vector<unsigned char, SafeAllocator<unsigned char> > SafeByteArray;
+ typedef std::vector<unsigned char, SafeAllocator<unsigned char> > SafeByteArray;
- inline SafeByteArray createSafeByteArray(const ByteArray& a) {
- return SafeByteArray(a.begin(), a.end());
- }
+ inline SafeByteArray createSafeByteArray(const ByteArray& a) {
+ return SafeByteArray(a.begin(), a.end());
+ }
- SWIFTEN_API SafeByteArray createSafeByteArray(const char* c);
+ SWIFTEN_API SafeByteArray createSafeByteArray(const char* c);
- inline SafeByteArray createSafeByteArray(const std::string& s) {
- return SafeByteArray(s.begin(), s.end());
- }
+ inline SafeByteArray createSafeByteArray(const std::string& s) {
+ return SafeByteArray(s.begin(), s.end());
+ }
- inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const std::string& s) {
- return boost::make_shared<SafeByteArray>(s.begin(), s.end());
- }
+ inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const std::string& s) {
+ return boost::make_shared<SafeByteArray>(s.begin(), s.end());
+ }
- inline SafeByteArray createSafeByteArray(char c) {
- return SafeByteArray(1, static_cast<unsigned char>(c));
- }
+ inline SafeByteArray createSafeByteArray(char c) {
+ return SafeByteArray(1, static_cast<unsigned char>(c));
+ }
- inline SafeByteArray createSafeByteArray(const char* c, size_t n) {
- return SafeByteArray(c, c + n);
- }
+ inline SafeByteArray createSafeByteArray(const char* c, size_t n) {
+ return SafeByteArray(c, c + n);
+ }
- inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const char* c, size_t n) {
- return boost::make_shared<SafeByteArray>(c, c + n);
- }
+ inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const char* c, size_t n) {
+ return boost::make_shared<SafeByteArray>(c, c + n);
+ }
- inline SafeByteArray createSafeByteArray(const unsigned char* c, size_t n) {
- return SafeByteArray(c, c + n);
- }
+ inline SafeByteArray createSafeByteArray(const unsigned char* c, size_t n) {
+ return SafeByteArray(c, c + n);
+ }
- inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const unsigned char* c, size_t n) {
- return boost::make_shared<SafeByteArray>(c, c + n);
- }
+ inline boost::shared_ptr<SafeByteArray> createSafeByteArrayRef(const unsigned char* c, size_t n) {
+ return boost::make_shared<SafeByteArray>(c, c + n);
+ }
- /* WARNING! This breaks the safety of the data in the safe byte array.
- * Do not use in modes that require data safety. */
- inline std::string safeByteArrayToString(const SafeByteArray& b) {
- return byteArrayToString(ByteArray(b.begin(), b.end()));
- }
+ /* WARNING! This breaks the safety of the data in the safe byte array.
+ * Do not use in modes that require data safety. */
+ inline std::string safeByteArrayToString(const SafeByteArray& b) {
+ return byteArrayToString(ByteArray(b.begin(), b.end()));
+ }
}
diff --git a/Swiften/Base/SafeString.h b/Swiften/Base/SafeString.h
index bb5f64f..5e54537 100644
--- a/Swiften/Base/SafeString.h
+++ b/Swiften/Base/SafeString.h
@@ -10,24 +10,24 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API SafeString {
- public:
- SafeString(const SafeByteArray& data) : data(data) {
- }
+ class SWIFTEN_API SafeString {
+ public:
+ SafeString(const SafeByteArray& data) : data(data) {
+ }
- SafeString(const std::string& s) {
- data = createSafeByteArray(s);
- }
+ SafeString(const std::string& s) {
+ data = createSafeByteArray(s);
+ }
- SafeString(const char* s) {
- data = createSafeByteArray(s);
- }
+ SafeString(const char* s) {
+ data = createSafeByteArray(s);
+ }
- operator SafeByteArray () const {
- return data;
- }
+ operator SafeByteArray () const {
+ return data;
+ }
- private:
- SafeByteArray data;
- };
+ private:
+ SafeByteArray data;
+ };
}
diff --git a/Swiften/Base/SimpleIDGenerator.cpp b/Swiften/Base/SimpleIDGenerator.cpp
index 97d59f9..072dd39 100644
--- a/Swiften/Base/SimpleIDGenerator.cpp
+++ b/Swiften/Base/SimpleIDGenerator.cpp
@@ -12,23 +12,23 @@ SimpleIDGenerator::SimpleIDGenerator() {
}
std::string SimpleIDGenerator::generateID() {
- bool carry = true;
- size_t i = 0;
- while (carry && i < currentID.size()) {
- char c = currentID[i];
- if (c >= 'z') {
- currentID[i] = 'a';
- }
- else {
- currentID[i] = c+1;
- carry = false;
- }
- ++i;
- }
- if (carry) {
- currentID += 'a';
- }
- return currentID;
+ bool carry = true;
+ size_t i = 0;
+ while (carry && i < currentID.size()) {
+ char c = currentID[i];
+ if (c >= 'z') {
+ currentID[i] = 'a';
+ }
+ else {
+ currentID[i] = c+1;
+ carry = false;
+ }
+ ++i;
+ }
+ if (carry) {
+ currentID += 'a';
+ }
+ return currentID;
}
}
diff --git a/Swiften/Base/SimpleIDGenerator.h b/Swiften/Base/SimpleIDGenerator.h
index e4fa3f5..49ba59e 100644
--- a/Swiften/Base/SimpleIDGenerator.h
+++ b/Swiften/Base/SimpleIDGenerator.h
@@ -13,18 +13,18 @@
namespace Swift {
- /**
- * @brief The SimpleIDGenerator class implements a IDGenerator generating consecutive ID strings from
- * the lower case latin alphabet.
- */
+ /**
+ * @brief The SimpleIDGenerator class implements a IDGenerator generating consecutive ID strings from
+ * the lower case latin alphabet.
+ */
- class SWIFTEN_API SimpleIDGenerator : public IDGenerator {
- public:
- SimpleIDGenerator();
+ class SWIFTEN_API SimpleIDGenerator : public IDGenerator {
+ public:
+ SimpleIDGenerator();
- std::string generateID();
+ std::string generateID();
- private:
- std::string currentID;
- };
+ private:
+ std::string currentID;
+ };
}
diff --git a/Swiften/Base/StartStopper.h b/Swiften/Base/StartStopper.h
index 1808861..af1a72d 100644
--- a/Swiften/Base/StartStopper.h
+++ b/Swiften/Base/StartStopper.h
@@ -7,17 +7,17 @@
#pragma once
namespace Swift {
- template<typename T> class StartStopper {
- public:
- StartStopper(T* target) : target(target) {
- target->start();
- }
+ template<typename T> class StartStopper {
+ public:
+ StartStopper(T* target) : target(target) {
+ target->start();
+ }
- ~StartStopper() {
- target->stop();
- }
-
- private:
- T* target;
- };
+ ~StartStopper() {
+ target->stop();
+ }
+
+ private:
+ T* target;
+ };
}
diff --git a/Swiften/Base/String.cpp b/Swiften/Base/String.cpp
index 5807957..91128ff 100644
--- a/Swiften/Base/String.cpp
+++ b/Swiften/Base/String.cpp
@@ -20,133 +20,133 @@
namespace Swift {
static inline size_t sequenceLength(char firstByte) {
- if ((firstByte & 0x80) == 0) {
- return 1;
- }
- if ((firstByte & 0xE0) == 0xC0) {
- return 2;
- }
- if ((firstByte & 0xF0) == 0xE0) {
- return 3;
- }
- if ((firstByte & 0xF8) == 0xF0) {
- return 4;
- }
- if ((firstByte & 0xFC) == 0xF8) {
- return 5;
- }
- if ((firstByte & 0xFE) == 0xFC) {
- return 6;
- }
- assert(false);
- return 1;
+ if ((firstByte & 0x80) == 0) {
+ return 1;
+ }
+ if ((firstByte & 0xE0) == 0xC0) {
+ return 2;
+ }
+ if ((firstByte & 0xF0) == 0xE0) {
+ return 3;
+ }
+ if ((firstByte & 0xF8) == 0xF0) {
+ return 4;
+ }
+ if ((firstByte & 0xFC) == 0xF8) {
+ return 5;
+ }
+ if ((firstByte & 0xFE) == 0xFC) {
+ return 6;
+ }
+ assert(false);
+ return 1;
}
std::vector<unsigned int> String::getUnicodeCodePoints(const std::string& s) {
- std::vector<unsigned int> result;
- for (size_t i = 0; i < s.size();) {
- unsigned int codePoint = 0;
- char firstChar = s[i];
- size_t length = sequenceLength(firstChar);
-
- // First character is special
- size_t firstCharBitSize = 7 - length;
- if (length == 1) {
- firstCharBitSize = 7;
- }
- codePoint = firstChar & ((1<<(firstCharBitSize+1)) - 1);
-
- for (size_t j = 1; j < length; ++j) {
- codePoint = (codePoint<<6) | (s[i+j] & 0x3F);
- }
- result.push_back(codePoint);
- i += length;
- }
- return result;
+ std::vector<unsigned int> result;
+ for (size_t i = 0; i < s.size();) {
+ unsigned int codePoint = 0;
+ char firstChar = s[i];
+ size_t length = sequenceLength(firstChar);
+
+ // First character is special
+ size_t firstCharBitSize = 7 - length;
+ if (length == 1) {
+ firstCharBitSize = 7;
+ }
+ codePoint = firstChar & ((1<<(firstCharBitSize+1)) - 1);
+
+ for (size_t j = 1; j < length; ++j) {
+ codePoint = (codePoint<<6) | (s[i+j] & 0x3F);
+ }
+ result.push_back(codePoint);
+ i += length;
+ }
+ return result;
}
std::pair<std::string,std::string> String::getSplittedAtFirst(const std::string& s, char c) {
- assert((c & 0x80) == 0);
- size_t firstMatch = s.find(c);
- if (firstMatch != s.npos) {
- return std::make_pair(s.substr(0,firstMatch),s.substr(firstMatch+1,s.npos));
- }
- else {
- return std::make_pair(s, "");
- }
+ assert((c & 0x80) == 0);
+ size_t firstMatch = s.find(c);
+ if (firstMatch != s.npos) {
+ return std::make_pair(s.substr(0,firstMatch),s.substr(firstMatch+1,s.npos));
+ }
+ else {
+ return std::make_pair(s, "");
+ }
}
void String::replaceAll(std::string& src, char c, const std::string& s) {
- size_t lastPos = 0;
- size_t matchingIndex = 0;
- while ((matchingIndex = src.find(c, lastPos)) != src.npos) {
- src.replace(matchingIndex, 1, s);
- lastPos = matchingIndex + s.size();
- }
+ size_t lastPos = 0;
+ size_t matchingIndex = 0;
+ while ((matchingIndex = src.find(c, lastPos)) != src.npos) {
+ src.replace(matchingIndex, 1, s);
+ lastPos = matchingIndex + s.size();
+ }
}
std::vector<std::string> String::split(const std::string& s, char c) {
- assert((c & 0x80) == 0);
- std::vector<std::string> result;
- std::string accumulator;
- for (size_t i = 0; i < s.size(); ++i) {
- if (s[i] == c) {
- result.push_back(accumulator);
- accumulator = "";
- }
- else {
- accumulator += s[i];
- }
- }
- result.push_back(accumulator);
- return result;
+ assert((c & 0x80) == 0);
+ std::vector<std::string> result;
+ std::string accumulator;
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == c) {
+ result.push_back(accumulator);
+ accumulator = "";
+ }
+ else {
+ accumulator += s[i];
+ }
+ }
+ result.push_back(accumulator);
+ return result;
}
std::string String::convertIntToHexString(int h) {
- std::stringstream ss;
- ss << std::setbase(16);
- ss << h;
- return ss.str();
+ std::stringstream ss;
+ ss << std::setbase(16);
+ ss << h;
+ return ss.str();
}
int String::convertHexStringToInt(const std::string& s) {
- std::stringstream ss;
- int h;
- ss << std::setbase(16);
- ss << s;
- ss >> h;
- return h;
+ std::stringstream ss;
+ int h;
+ ss << std::setbase(16);
+ ss << s;
+ ss >> h;
+ return h;
}
#ifdef SWIFTEN_PLATFORM_WINDOWS
std::string convertWStringToString(const std::wstring& s) {
- int utf8Size = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, NULL, NULL);
- if (utf8Size < 0) {
- throw std::runtime_error("Conversion error");
- }
- std::vector<char> utf8Data(utf8Size);
- int result = WideCharToMultiByte(
- CP_UTF8, 0, s.c_str(), -1, vecptr(utf8Data), utf8Data.size(), NULL, NULL);
- if (result < 0) {
- throw std::runtime_error("Conversion error");
- }
- return std::string(vecptr(utf8Data), utf8Size-1 /* trailing 0 character */);
+ int utf8Size = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, NULL, 0, NULL, NULL);
+ if (utf8Size < 0) {
+ throw std::runtime_error("Conversion error");
+ }
+ std::vector<char> utf8Data(utf8Size);
+ int result = WideCharToMultiByte(
+ CP_UTF8, 0, s.c_str(), -1, vecptr(utf8Data), utf8Data.size(), NULL, NULL);
+ if (result < 0) {
+ throw std::runtime_error("Conversion error");
+ }
+ return std::string(vecptr(utf8Data), utf8Size-1 /* trailing 0 character */);
}
std::wstring convertStringToWString(const std::string& s) {
- int utf16Size = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
- if (utf16Size < 0) {
- throw std::runtime_error("Conversion error");
- }
- std::vector<wchar_t> utf16Data(utf16Size);
- int result = MultiByteToWideChar(
- CP_UTF8, 0, s.c_str(), -1, vecptr(utf16Data), utf16Data.size());
- if (result < 0) {
- throw std::runtime_error("Conversion error");
- }
- return std::wstring(vecptr(utf16Data), utf16Size-1 /* trailing 0 character */);
+ int utf16Size = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
+ if (utf16Size < 0) {
+ throw std::runtime_error("Conversion error");
+ }
+ std::vector<wchar_t> utf16Data(utf16Size);
+ int result = MultiByteToWideChar(
+ CP_UTF8, 0, s.c_str(), -1, vecptr(utf16Data), utf16Data.size());
+ if (result < 0) {
+ throw std::runtime_error("Conversion error");
+ }
+ return std::wstring(vecptr(utf16Data), utf16Size-1 /* trailing 0 character */);
}
#endif
diff --git a/Swiften/Base/String.h b/Swiften/Base/String.h
index a82df63..f19dca5 100644
--- a/Swiften/Base/String.h
+++ b/Swiften/Base/String.h
@@ -13,45 +13,45 @@
#include <Swiften/Base/API.h>
#include <Swiften/Base/Platform.h>
#define SWIFTEN_STRING_TO_CFSTRING(a) \
- CFStringCreateWithBytes(NULL, reinterpret_cast<const UInt8*>(a.c_str()), a.size(), kCFStringEncodingUTF8, false)
+ CFStringCreateWithBytes(NULL, reinterpret_cast<const UInt8*>(a.c_str()), a.size(), kCFStringEncodingUTF8, false)
namespace Swift {
- namespace String {
- SWIFTEN_API std::vector<unsigned int> getUnicodeCodePoints(const std::string&);
- SWIFTEN_API std::pair<std::string, std::string> getSplittedAtFirst(const std::string&, char c);
- SWIFTEN_API std::vector<std::string> split(const std::string&, char c);
- SWIFTEN_API void replaceAll(std::string&, char c, const std::string& s);
+ namespace String {
+ SWIFTEN_API std::vector<unsigned int> getUnicodeCodePoints(const std::string&);
+ SWIFTEN_API std::pair<std::string, std::string> getSplittedAtFirst(const std::string&, char c);
+ SWIFTEN_API std::vector<std::string> split(const std::string&, char c);
+ SWIFTEN_API void replaceAll(std::string&, char c, const std::string& s);
- inline bool beginsWith(const std::string& s, char c) {
- return s.size() > 0 && s[0] == c;
- }
+ inline bool beginsWith(const std::string& s, char c) {
+ return s.size() > 0 && s[0] == c;
+ }
- inline bool endsWith(const std::string& s, char c) {
- return s.size() > 0 && s[s.size()-1] == c;
- }
+ inline bool endsWith(const std::string& s, char c) {
+ return s.size() > 0 && s[s.size()-1] == c;
+ }
- std::string convertIntToHexString(int h);
- int convertHexStringToInt(const std::string& s);
+ std::string convertIntToHexString(int h);
+ int convertHexStringToInt(const std::string& s);
- }
+ }
#ifdef SWIFTEN_PLATFORM_WINDOWS
- SWIFTEN_API std::string convertWStringToString(const std::wstring& s);
- SWIFTEN_API std::wstring convertStringToWString(const std::string& s);
+ SWIFTEN_API std::string convertWStringToString(const std::wstring& s);
+ SWIFTEN_API std::wstring convertStringToWString(const std::string& s);
#endif
- class SWIFTEN_API makeString {
- public:
- template <typename T> makeString& operator<<(T const& v) {
- stream << v;
- return *this;
- }
+ class SWIFTEN_API makeString {
+ public:
+ template <typename T> makeString& operator<<(T const& v) {
+ stream << v;
+ return *this;
+ }
- operator std::string() const {
- return stream.str();
- }
+ operator std::string() const {
+ return stream.str();
+ }
- private:
- std::ostringstream stream;
- };
+ private:
+ std::ostringstream stream;
+ };
}
diff --git a/Swiften/Base/URL.cpp b/Swiften/Base/URL.cpp
index 28eba1e..a9a1140 100644
--- a/Swiften/Base/URL.cpp
+++ b/Swiften/Base/URL.cpp
@@ -11,104 +11,104 @@
namespace Swift {
int URL::getPortOrDefaultPort(const URL& url) {
- if (url.getPort()) {
- return *url.getPort();
- }
- else if (url.getScheme() == "http") {
- return 80;
- }
- else if (url.getScheme() == "https") {
- return 443;
- }
- else {
- std::cerr << "Unknown scheme: " + url.getScheme() << std::endl;
- return 80;
- }
+ if (url.getPort()) {
+ return *url.getPort();
+ }
+ else if (url.getScheme() == "http") {
+ return 80;
+ }
+ else if (url.getScheme() == "https") {
+ return 443;
+ }
+ else {
+ std::cerr << "Unknown scheme: " + url.getScheme() << std::endl;
+ return 80;
+ }
}
URL URL::fromString(const std::string& urlString) {
- size_t colonIndex = urlString.find(':');
- if (colonIndex == std::string::npos) {
- return URL();
- }
- std::string scheme = urlString.substr(0, colonIndex);
+ size_t colonIndex = urlString.find(':');
+ if (colonIndex == std::string::npos) {
+ return URL();
+ }
+ std::string scheme = urlString.substr(0, colonIndex);
- // Authority
- if (urlString.size() > colonIndex + 2 && urlString[colonIndex+1] == '/' && urlString[colonIndex+2] == '/') {
- size_t authorityIndex = colonIndex + 3;
- size_t slashIndex = urlString.find('/', authorityIndex);
- std::string authority;
- std::string path;
- if (slashIndex == std::string::npos) {
- authority = urlString.substr(authorityIndex);
- path = "";
- }
- else {
- authority = urlString.substr(authorityIndex, slashIndex - authorityIndex);
- path = unescape(urlString.substr(slashIndex));
- }
+ // Authority
+ if (urlString.size() > colonIndex + 2 && urlString[colonIndex+1] == '/' && urlString[colonIndex+2] == '/') {
+ size_t authorityIndex = colonIndex + 3;
+ size_t slashIndex = urlString.find('/', authorityIndex);
+ std::string authority;
+ std::string path;
+ if (slashIndex == std::string::npos) {
+ authority = urlString.substr(authorityIndex);
+ path = "";
+ }
+ else {
+ authority = urlString.substr(authorityIndex, slashIndex - authorityIndex);
+ path = unescape(urlString.substr(slashIndex));
+ }
- size_t atIndex = authority.find('@');
- std::string userInfo;
- std::string hostAndPort;
- if (atIndex != std::string::npos) {
- userInfo = authority.substr(0, atIndex);
- hostAndPort = authority.substr(atIndex + 1);
- }
- else {
- userInfo = "";
- hostAndPort = authority;
- }
+ size_t atIndex = authority.find('@');
+ std::string userInfo;
+ std::string hostAndPort;
+ if (atIndex != std::string::npos) {
+ userInfo = authority.substr(0, atIndex);
+ hostAndPort = authority.substr(atIndex + 1);
+ }
+ else {
+ userInfo = "";
+ hostAndPort = authority;
+ }
- std::string host;
- boost::optional<int> port;
- colonIndex = hostAndPort.find(':');
- if (colonIndex != std::string::npos) {
- host = unescape(hostAndPort.substr(0, colonIndex));
- try {
- port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1));
- }
- catch (const boost::bad_lexical_cast&) {
- return URL();
- }
- }
- else {
- host = unescape(hostAndPort);
- }
+ std::string host;
+ boost::optional<int> port;
+ colonIndex = hostAndPort.find(':');
+ if (colonIndex != std::string::npos) {
+ host = unescape(hostAndPort.substr(0, colonIndex));
+ try {
+ port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1));
+ }
+ catch (const boost::bad_lexical_cast&) {
+ return URL();
+ }
+ }
+ else {
+ host = unescape(hostAndPort);
+ }
- if (port) {
- return URL(scheme, host, *port, path);
- }
- else {
- return URL(scheme, host, path);
- }
- }
- else {
- // We don't support URLs without authorities yet
- return URL();
- }
+ if (port) {
+ return URL(scheme, host, *port, path);
+ }
+ else {
+ return URL(scheme, host, path);
+ }
+ }
+ else {
+ // We don't support URLs without authorities yet
+ return URL();
+ }
}
// FIXME: Escape non-ascii characters
std::string URL::toString() const {
- if (empty) {
- return "";
- }
- std::string result = scheme + "://";
- if (!user.empty()) {
- result += user;
- if (!password.empty()) {
- result += ":" + password;
- }
- result += "@";
- }
- result += host;
- if (port) {
- result += ":";
- result += boost::lexical_cast<std::string>(*port);
- }
- result += path;
- return result;
+ if (empty) {
+ return "";
+ }
+ std::string result = scheme + "://";
+ if (!user.empty()) {
+ result += user;
+ if (!password.empty()) {
+ result += ":" + password;
+ }
+ result += "@";
+ }
+ result += host;
+ if (port) {
+ result += ":";
+ result += boost::lexical_cast<std::string>(*port);
+ }
+ result += path;
+ return result;
}
// Disabling this code for now, since GCC4.5+boost1.42 (on ubuntu) seems to
@@ -118,72 +118,72 @@ std::string URL::toString() const {
struct PercentEncodedCharacterFinder {
template<typename Iterator>
boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) {
- boost::iterator_range<Iterator> r = boost::first_finder("%")(begin, end);
- if (r.end() == end) {
- return r;
- }
- else {
- if (r.end() + 1 == end || r.end() + 2 == end) {
- throw std::runtime_error("Incomplete escape character");
- }
- else {
- r.advance_end(2);
- return r;
- }
- }
+ boost::iterator_range<Iterator> r = boost::first_finder("%")(begin, end);
+ if (r.end() == end) {
+ return r;
+ }
+ else {
+ if (r.end() + 1 == end || r.end() + 2 == end) {
+ throw std::runtime_error("Incomplete escape character");
+ }
+ else {
+ r.advance_end(2);
+ return r;
+ }
+ }
}
};
struct PercentUnencodeFormatter {
template<typename FindResult>
std::string operator()(const FindResult& match) const {
- std::stringstream s;
- s << std::hex << std::string(match.begin() + 1, match.end());
- unsigned int value;
- s >> value;
- if (s.fail() || s.bad()) {
- throw std::runtime_error("Invalid escape character");
- }
- unsigned char charValue = static_cast<unsigned char>(value);
- return std::string(reinterpret_cast<const char*>(&charValue), 1);
+ std::stringstream s;
+ s << std::hex << std::string(match.begin() + 1, match.end());
+ unsigned int value;
+ s >> value;
+ if (s.fail() || s.bad()) {
+ throw std::runtime_error("Invalid escape character");
+ }
+ unsigned char charValue = static_cast<unsigned char>(value);
+ return std::string(reinterpret_cast<const char*>(&charValue), 1);
}
};
std::string unescape(const std::string& s) {
- try {
- return boost::find_format_all_copy(s, PercentEncodedCharacterFinder(), PercentUnencodeFormatter());
- }
- catch (const std::exception&) {
- return "";
- }
+ try {
+ return boost::find_format_all_copy(s, PercentEncodedCharacterFinder(), PercentUnencodeFormatter());
+ }
+ catch (const std::exception&) {
+ return "";
+ }
}
#endif
std::string URL::unescape(const std::string& str) {
- std::string result;
- for (size_t i = 0; i < str.size(); ++i) {
- if (str[i] == '%') {
- if (i + 3 < str.size()) {
- std::stringstream s;
- s << std::hex << str.substr(i+1, 2);
- unsigned int value;
- s >> value;
- if (s.fail() || s.bad()) {
- return "";
- }
- unsigned char charValue = static_cast<unsigned char>(value);
- result += std::string(reinterpret_cast<const char*>(&charValue), 1);
- i += 2;
- }
- else {
- return "";
- }
- }
- else {
- result += str[i];
- }
- }
- return result;
+ std::string result;
+ for (size_t i = 0; i < str.size(); ++i) {
+ if (str[i] == '%') {
+ if (i + 3 < str.size()) {
+ std::stringstream s;
+ s << std::hex << str.substr(i+1, 2);
+ unsigned int value;
+ s >> value;
+ if (s.fail() || s.bad()) {
+ return "";
+ }
+ unsigned char charValue = static_cast<unsigned char>(value);
+ result += std::string(reinterpret_cast<const char*>(&charValue), 1);
+ i += 2;
+ }
+ else {
+ return "";
+ }
+ }
+ else {
+ result += str[i];
+ }
+ }
+ return result;
}
}
diff --git a/Swiften/Base/URL.h b/Swiften/Base/URL.h
index e172682..1a03efe 100644
--- a/Swiften/Base/URL.h
+++ b/Swiften/Base/URL.h
@@ -16,66 +16,66 @@
namespace Swift {
class SWIFTEN_API URL {
- public:
-
- URL() : scheme(""), user(""), password(""), host(""), path(""), empty(true) {
- }
-
- URL(const std::string& scheme, const std::string& host, int port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) {
- }
-
- URL(const std::string& scheme, const std::string& host, const std::string& path) : scheme(scheme), user(), password(), host(host), path(path), empty(false) {
- }
-
- /**
- * Whether the URL is empty.
- */
- bool isEmpty() const {
- return empty;
- }
-
- /**
- * Scheme used for the URL (http, https etc.)
- */
- const std::string& getScheme() const {
- return scheme;
- }
-
- /**
- * Hostname
- */
- const std::string& getHost() const {
- return host;
- }
-
- /**
- * Port number
- */
- boost::optional<int> getPort() const {
- return port;
- }
-
- /**
- * Path
- */
- const std::string& getPath() const {
- return path;
- }
-
- std::string toString() const;
-
- static int getPortOrDefaultPort(const URL& url);
- static URL fromString(const std::string&);
- static std::string unescape(const std::string&);
-
-
- private:
- std::string scheme;
- std::string user;
- std::string password;
- std::string host;
- boost::optional<int> port;
- std::string path;
- bool empty;
- };
+ public:
+
+ URL() : scheme(""), user(""), password(""), host(""), path(""), empty(true) {
+ }
+
+ URL(const std::string& scheme, const std::string& host, int port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) {
+ }
+
+ URL(const std::string& scheme, const std::string& host, const std::string& path) : scheme(scheme), user(), password(), host(host), path(path), empty(false) {
+ }
+
+ /**
+ * Whether the URL is empty.
+ */
+ bool isEmpty() const {
+ return empty;
+ }
+
+ /**
+ * Scheme used for the URL (http, https etc.)
+ */
+ const std::string& getScheme() const {
+ return scheme;
+ }
+
+ /**
+ * Hostname
+ */
+ const std::string& getHost() const {
+ return host;
+ }
+
+ /**
+ * Port number
+ */
+ boost::optional<int> getPort() const {
+ return port;
+ }
+
+ /**
+ * Path
+ */
+ const std::string& getPath() const {
+ return path;
+ }
+
+ std::string toString() const;
+
+ static int getPortOrDefaultPort(const URL& url);
+ static URL fromString(const std::string&);
+ static std::string unescape(const std::string&);
+
+
+ private:
+ std::string scheme;
+ std::string user;
+ std::string password;
+ std::string host;
+ boost::optional<int> port;
+ std::string path;
+ bool empty;
+ };
}
diff --git a/Swiften/Base/UnitTest/ByteArrayTest.cpp b/Swiften/Base/UnitTest/ByteArrayTest.cpp
index ce6b9db..2eb601b 100644
--- a/Swiften/Base/UnitTest/ByteArrayTest.cpp
+++ b/Swiften/Base/UnitTest/ByteArrayTest.cpp
@@ -14,44 +14,44 @@
using namespace Swift;
class ByteArrayTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ByteArrayTest);
- CPPUNIT_TEST(testGetData_NoData);
- CPPUNIT_TEST(testToString);
- CPPUNIT_TEST(testToString_NullTerminated);
- CPPUNIT_TEST(testToString_TwoNullTerminated);
- CPPUNIT_TEST(testToString_AllNull);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ByteArrayTest);
+ CPPUNIT_TEST(testGetData_NoData);
+ CPPUNIT_TEST(testToString);
+ CPPUNIT_TEST(testToString_NullTerminated);
+ CPPUNIT_TEST(testToString_TwoNullTerminated);
+ CPPUNIT_TEST(testToString_AllNull);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetData_NoData() {
- ByteArray testling;
+ public:
+ void testGetData_NoData() {
+ ByteArray testling;
- CPPUNIT_ASSERT_EQUAL(reinterpret_cast<const char*>(NULL), reinterpret_cast<const char*>(vecptr(testling)));
- }
+ CPPUNIT_ASSERT_EQUAL(reinterpret_cast<const char*>(NULL), reinterpret_cast<const char*>(vecptr(testling)));
+ }
- void testToString() {
- ByteArray testling(createByteArray("abcde"));
+ void testToString() {
+ ByteArray testling(createByteArray("abcde"));
- CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
+ }
- void testToString_NullTerminated() {
- ByteArray testling(createByteArray("abcde\0", 6));
+ void testToString_NullTerminated() {
+ ByteArray testling(createByteArray("abcde\0", 6));
- CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
+ }
- void testToString_TwoNullTerminated() {
- ByteArray testling(createByteArray("abcde\0\0", 7));
+ void testToString_TwoNullTerminated() {
+ ByteArray testling(createByteArray("abcde\0\0", 7));
- CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("abcde"), byteArrayToString(testling));
+ }
- void testToString_AllNull() {
- ByteArray testling(createByteArray("\0\0", 2));
+ void testToString_AllNull() {
+ ByteArray testling(createByteArray("\0\0", 2));
- CPPUNIT_ASSERT_EQUAL(std::string(""), byteArrayToString(testling));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), byteArrayToString(testling));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ByteArrayTest);
diff --git a/Swiften/Base/UnitTest/DateTimeTest.cpp b/Swiften/Base/UnitTest/DateTimeTest.cpp
index 527e251..6a82d96 100644
--- a/Swiften/Base/UnitTest/DateTimeTest.cpp
+++ b/Swiften/Base/UnitTest/DateTimeTest.cpp
@@ -16,37 +16,37 @@
using namespace Swift;
class DateTimeTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DateTimeTest);
- CPPUNIT_TEST(testStringToDateTime_UTC);
- CPPUNIT_TEST(testStringToDateTime_WithTimezone);
- CPPUNIT_TEST(testDateTimeToString);
- CPPUNIT_TEST(testDateTimeToLocalStringNotThrowingException);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DateTimeTest);
+ CPPUNIT_TEST(testStringToDateTime_UTC);
+ CPPUNIT_TEST(testStringToDateTime_WithTimezone);
+ CPPUNIT_TEST(testDateTimeToString);
+ CPPUNIT_TEST(testDateTimeToLocalStringNotThrowingException);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testStringToDateTime_UTC() {
- boost::posix_time::ptime time = stringToDateTime("1969-07-21T02:56:15Z");
+ public:
+ void testStringToDateTime_UTC() {
+ boost::posix_time::ptime time = stringToDateTime("1969-07-21T02:56:15Z");
- CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time));
+ }
- void testStringToDateTime_WithTimezone() {
- boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00");
+ void testStringToDateTime_WithTimezone() {
+ boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00");
- CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15"), boost::posix_time::to_iso_extended_string(time));
+ }
- void testDateTimeToString() {
- boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00");
+ void testDateTimeToString() {
+ boost::posix_time::ptime time = stringToDateTime("1969-07-20T21:56:15-05:00");
- CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15Z"), dateTimeToString(time));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("1969-07-21T02:56:15Z"), dateTimeToString(time));
+ }
- void testDateTimeToLocalStringNotThrowingException() {
- boost::posix_time::ptime time = stringToDateTime("1954-07-20T21:56:15-05:00");
+ void testDateTimeToLocalStringNotThrowingException() {
+ boost::posix_time::ptime time = stringToDateTime("1954-07-20T21:56:15-05:00");
- CPPUNIT_ASSERT_EQUAL(std::string(""), dateTimeToLocalString(time));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), dateTimeToLocalString(time));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DateTimeTest);
diff --git a/Swiften/Base/UnitTest/IDGeneratorTest.cpp b/Swiften/Base/UnitTest/IDGeneratorTest.cpp
index d03969b..08bd48b 100644
--- a/Swiften/Base/UnitTest/IDGeneratorTest.cpp
+++ b/Swiften/Base/UnitTest/IDGeneratorTest.cpp
@@ -15,27 +15,27 @@ using namespace Swift;
class IDGeneratorTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(IDGeneratorTest);
- CPPUNIT_TEST(testGenerate);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- IDGeneratorTest() {}
-
- void setUp() {
- generatedIDs_.clear();
- }
-
- void testGenerate() {
- IDGenerator testling;
- for (unsigned int i = 0; i < 26*4; ++i) {
- std::string id = testling.generateID();
- CPPUNIT_ASSERT(generatedIDs_.insert(id).second);
- }
- }
-
- private:
- std::set<std::string> generatedIDs_;
+ CPPUNIT_TEST_SUITE(IDGeneratorTest);
+ CPPUNIT_TEST(testGenerate);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ IDGeneratorTest() {}
+
+ void setUp() {
+ generatedIDs_.clear();
+ }
+
+ void testGenerate() {
+ IDGenerator testling;
+ for (unsigned int i = 0; i < 26*4; ++i) {
+ std::string id = testling.generateID();
+ CPPUNIT_ASSERT(generatedIDs_.insert(id).second);
+ }
+ }
+
+ private:
+ std::set<std::string> generatedIDs_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IDGeneratorTest);
diff --git a/Swiften/Base/UnitTest/PathTest.cpp b/Swiften/Base/UnitTest/PathTest.cpp
index b22b570..dd2233b 100644
--- a/Swiften/Base/UnitTest/PathTest.cpp
+++ b/Swiften/Base/UnitTest/PathTest.cpp
@@ -13,23 +13,23 @@
using namespace Swift;
class PathTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PathTest);
- CPPUNIT_TEST(testStringToPath);
- CPPUNIT_TEST(testPathToString);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PathTest);
+ CPPUNIT_TEST(testStringToPath);
+ CPPUNIT_TEST(testPathToString);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testStringToPath() {
+ public:
+ void testStringToPath() {
#ifdef SWIFTEN_PLATFORM_WINDOWS
- CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == stringToPath("tron\xc3\xa7on").native());
+ CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == stringToPath("tron\xc3\xa7on").native());
#else
- CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), stringToPath("tron\xc3\xa7on").native());
+ CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), stringToPath("tron\xc3\xa7on").native());
#endif
- }
+ }
- void testPathToString() {
- CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), pathToString(stringToPath("tron\xc3\xa7on")));
- }
+ void testPathToString() {
+ CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), pathToString(stringToPath("tron\xc3\xa7on")));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PathTest);
diff --git a/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp b/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp
index 1c5fb2b..9b49c0a 100644
--- a/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp
+++ b/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp
@@ -15,27 +15,27 @@ using namespace Swift;
class SimpleIDGeneratorTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SimpleIDGeneratorTest);
- CPPUNIT_TEST(testGenerate);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- SimpleIDGeneratorTest() {}
-
- void setUp() {
- generatedIDs_.clear();
- }
-
- void testGenerate() {
- SimpleIDGenerator testling;
- for (unsigned int i = 0; i < 26*4; ++i) {
- std::string id = testling.generateID();
- CPPUNIT_ASSERT(generatedIDs_.insert(id).second);
- }
- }
-
- private:
- std::set<std::string> generatedIDs_;
+ CPPUNIT_TEST_SUITE(SimpleIDGeneratorTest);
+ CPPUNIT_TEST(testGenerate);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ SimpleIDGeneratorTest() {}
+
+ void setUp() {
+ generatedIDs_.clear();
+ }
+
+ void testGenerate() {
+ SimpleIDGenerator testling;
+ for (unsigned int i = 0; i < 26*4; ++i) {
+ std::string id = testling.generateID();
+ CPPUNIT_ASSERT(generatedIDs_.insert(id).second);
+ }
+ }
+
+ private:
+ std::set<std::string> generatedIDs_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SimpleIDGeneratorTest);
diff --git a/Swiften/Base/UnitTest/StringTest.cpp b/Swiften/Base/UnitTest/StringTest.cpp
index a17a253..e2e1665 100644
--- a/Swiften/Base/UnitTest/StringTest.cpp
+++ b/Swiften/Base/UnitTest/StringTest.cpp
@@ -15,115 +15,115 @@
using namespace Swift;
class StringTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StringTest);
- CPPUNIT_TEST(testGetUnicodeCodePoints);
- CPPUNIT_TEST(testGetSplittedAtFirst);
- CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtBegin);
- CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtEnd);
- CPPUNIT_TEST(testGetSplittedAtFirst_NoSuchCharacter);
- CPPUNIT_TEST(testReplaceAll);
- CPPUNIT_TEST(testReplaceAll_LastChar);
- CPPUNIT_TEST(testReplaceAll_ConsecutiveChars);
- CPPUNIT_TEST(testReplaceAll_MatchingReplace);
- CPPUNIT_TEST(testSplit);
+ CPPUNIT_TEST_SUITE(StringTest);
+ CPPUNIT_TEST(testGetUnicodeCodePoints);
+ CPPUNIT_TEST(testGetSplittedAtFirst);
+ CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtBegin);
+ CPPUNIT_TEST(testGetSplittedAtFirst_CharacterAtEnd);
+ CPPUNIT_TEST(testGetSplittedAtFirst_NoSuchCharacter);
+ CPPUNIT_TEST(testReplaceAll);
+ CPPUNIT_TEST(testReplaceAll_LastChar);
+ CPPUNIT_TEST(testReplaceAll_ConsecutiveChars);
+ CPPUNIT_TEST(testReplaceAll_MatchingReplace);
+ CPPUNIT_TEST(testSplit);
#ifdef SWIFTEN_PLATFORM_WINDOWS
- CPPUNIT_TEST(testConvertWStringToString);
- CPPUNIT_TEST(testConvertStringToWString);
+ CPPUNIT_TEST(testConvertWStringToString);
+ CPPUNIT_TEST(testConvertStringToWString);
#endif
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetUnicodeCodePoints() {
- std::string testling("$\xc2\xa2\xe2\x82\xac\xf4\x8a\xaf\x8d");
- std::vector<unsigned int> points = String::getUnicodeCodePoints(testling);
+ public:
+ void testGetUnicodeCodePoints() {
+ std::string testling("$\xc2\xa2\xe2\x82\xac\xf4\x8a\xaf\x8d");
+ std::vector<unsigned int> points = String::getUnicodeCodePoints(testling);
- CPPUNIT_ASSERT_EQUAL(0x24U, points[0]);
- CPPUNIT_ASSERT_EQUAL(0xA2U, points[1]);
- CPPUNIT_ASSERT_EQUAL(0x20ACU, points[2]);
- CPPUNIT_ASSERT_EQUAL(0x10ABCDU, points[3]);
- }
+ CPPUNIT_ASSERT_EQUAL(0x24U, points[0]);
+ CPPUNIT_ASSERT_EQUAL(0xA2U, points[1]);
+ CPPUNIT_ASSERT_EQUAL(0x20ACU, points[2]);
+ CPPUNIT_ASSERT_EQUAL(0x10ABCDU, points[3]);
+ }
- void testGetSplittedAtFirst() {
- std::string testling("ab@cd@ef");
+ void testGetSplittedAtFirst() {
+ std::string testling("ab@cd@ef");
- std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
- CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
- CPPUNIT_ASSERT_EQUAL(std::string("cd@ef"), result.second);
- }
+ std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
+ CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
+ CPPUNIT_ASSERT_EQUAL(std::string("cd@ef"), result.second);
+ }
- void testGetSplittedAtFirst_CharacterAtBegin() {
- std::string testling(" ab");
+ void testGetSplittedAtFirst_CharacterAtBegin() {
+ std::string testling(" ab");
- std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, ' ');
- CPPUNIT_ASSERT(result.first.empty());
- CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.second);
- }
+ std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, ' ');
+ CPPUNIT_ASSERT(result.first.empty());
+ CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.second);
+ }
- void testGetSplittedAtFirst_CharacterAtEnd() {
- std::string testling("ab@");
+ void testGetSplittedAtFirst_CharacterAtEnd() {
+ std::string testling("ab@");
- std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
- CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
- CPPUNIT_ASSERT(result.second.empty());
- }
+ std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
+ CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
+ CPPUNIT_ASSERT(result.second.empty());
+ }
- void testGetSplittedAtFirst_NoSuchCharacter() {
- std::string testling("ab");
+ void testGetSplittedAtFirst_NoSuchCharacter() {
+ std::string testling("ab");
- std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
- CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
- CPPUNIT_ASSERT(result.second.empty());
- }
+ std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
+ CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
+ CPPUNIT_ASSERT(result.second.empty());
+ }
- void testReplaceAll() {
- std::string testling("abcbd");
+ void testReplaceAll() {
+ std::string testling("abcbd");
- String::replaceAll(testling, 'b', "xyz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling);
- }
+ String::replaceAll(testling, 'b', "xyz");
- void testReplaceAll_LastChar() {
- std::string testling("abc");
+ CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling);
+ }
- String::replaceAll(testling, 'c', "xyz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("abxyz"), testling);
- }
+ void testReplaceAll_LastChar() {
+ std::string testling("abc");
- void testReplaceAll_ConsecutiveChars() {
- std::string testling("abbc");
+ String::replaceAll(testling, 'c', "xyz");
- String::replaceAll(testling, 'b',"xyz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling);
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("abxyz"), testling);
+ }
- void testReplaceAll_MatchingReplace() {
- std::string testling("abc");
+ void testReplaceAll_ConsecutiveChars() {
+ std::string testling("abbc");
- String::replaceAll(testling, 'b',"bbb");
-
- CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling);
- }
+ String::replaceAll(testling, 'b',"xyz");
- void testSplit() {
- std::vector<std::string> result = String::split("abc def ghi", ' ');
+ CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling);
+ }
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(result.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("abc"), result[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("def"), result[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("ghi"), result[2]);
- }
+ void testReplaceAll_MatchingReplace() {
+ std::string testling("abc");
+
+ String::replaceAll(testling, 'b',"bbb");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling);
+ }
+
+ void testSplit() {
+ std::vector<std::string> result = String::split("abc def ghi", ' ');
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(result.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("abc"), result[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("def"), result[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("ghi"), result[2]);
+ }
#ifdef SWIFTEN_PLATFORM_WINDOWS
- void testConvertWStringToString() {
- CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), convertWStringToString(std::wstring(L"tron\xe7on")));
- }
+ void testConvertWStringToString() {
+ CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), convertWStringToString(std::wstring(L"tron\xe7on")));
+ }
- void testConvertStringToWString() {
- CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == convertStringToWString(std::string("tron\xc3\xa7on")));
- }
+ void testConvertStringToWString() {
+ CPPUNIT_ASSERT(std::wstring(L"tron\xe7on") == convertStringToWString(std::string("tron\xc3\xa7on")));
+ }
#endif
};
diff --git a/Swiften/Base/UnitTest/URLTest.cpp b/Swiften/Base/UnitTest/URLTest.cpp
index d88269a..2d2ceba 100644
--- a/Swiften/Base/UnitTest/URLTest.cpp
+++ b/Swiften/Base/UnitTest/URLTest.cpp
@@ -14,102 +14,102 @@
using namespace Swift;
class URLTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(URLTest);
- CPPUNIT_TEST(testFromString);
- CPPUNIT_TEST(testFromString_WithoutPath);
- CPPUNIT_TEST(testFromString_WithRootPath);
- CPPUNIT_TEST(testFromString_WithPort);
- CPPUNIT_TEST(testFromString_WithPortOnePartPath);
- CPPUNIT_TEST(testFromString_WithPortWithoutPath);
- CPPUNIT_TEST(testFromString_WithUserInfo);
- CPPUNIT_TEST(testFromString_NonASCIIHost);
- CPPUNIT_TEST(testFromString_NonASCIIPath);
- CPPUNIT_TEST(testToString);
- CPPUNIT_TEST(testToString_WithPort);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testFromString() {
- URL url = URL::fromString("http://foo.bar/baz/bam");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT(!url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
- }
-
- void testFromString_WithoutPath() {
- URL url = URL::fromString("http://foo.bar");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT(!url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath());
- }
-
- void testFromString_WithRootPath() {
- URL url = URL::fromString("http://foo.bar/");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT(!url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string("/"), url.getPath());
- }
-
- void testFromString_WithPort() {
- URL url = URL::fromString("http://foo.bar:1234/baz/bam");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT_EQUAL(1234, *url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
- }
-
- void testFromString_WithPortOnePartPath() {
- URL url = URL::fromString("http://foo.bar:11440/http-bind/");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT_EQUAL(11440, *url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string("/http-bind/"), url.getPath());
- }
-
- void testFromString_WithPortWithoutPath() {
- URL url = URL::fromString("http://foo.bar:1234");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT_EQUAL(1234, *url.getPort());
- CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath());
- }
-
- void testFromString_WithUserInfo() {
- URL url = URL::fromString("http://user:pass@foo.bar/baz/bam");
-
- CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
- CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
- CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
- }
-
- void testFromString_NonASCIIHost() {
- URL url = URL::fromString("http://www.tron%C3%A7on.be/baz/bam");
-
- CPPUNIT_ASSERT_EQUAL(std::string("www.tron\xc3\xa7on.be"), url.getHost());
- }
-
- void testFromString_NonASCIIPath() {
- URL url = URL::fromString("http://foo.bar/baz/tron%C3%A7on/bam");
-
- CPPUNIT_ASSERT_EQUAL(std::string("/baz/tron\xc3\xa7on/bam"), url.getPath());
- }
-
- void testToString() {
- CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar/baz/bam"), URL("http", "foo.bar", "/baz/bam").toString());
- }
-
- void testToString_WithPort() {
- CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar:1234/baz/bam"), URL("http", "foo.bar", 1234, "/baz/bam").toString());
- }
+ CPPUNIT_TEST_SUITE(URLTest);
+ CPPUNIT_TEST(testFromString);
+ CPPUNIT_TEST(testFromString_WithoutPath);
+ CPPUNIT_TEST(testFromString_WithRootPath);
+ CPPUNIT_TEST(testFromString_WithPort);
+ CPPUNIT_TEST(testFromString_WithPortOnePartPath);
+ CPPUNIT_TEST(testFromString_WithPortWithoutPath);
+ CPPUNIT_TEST(testFromString_WithUserInfo);
+ CPPUNIT_TEST(testFromString_NonASCIIHost);
+ CPPUNIT_TEST(testFromString_NonASCIIPath);
+ CPPUNIT_TEST(testToString);
+ CPPUNIT_TEST(testToString_WithPort);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testFromString() {
+ URL url = URL::fromString("http://foo.bar/baz/bam");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT(!url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
+ }
+
+ void testFromString_WithoutPath() {
+ URL url = URL::fromString("http://foo.bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT(!url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath());
+ }
+
+ void testFromString_WithRootPath() {
+ URL url = URL::fromString("http://foo.bar/");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT(!url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string("/"), url.getPath());
+ }
+
+ void testFromString_WithPort() {
+ URL url = URL::fromString("http://foo.bar:1234/baz/bam");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(1234, *url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
+ }
+
+ void testFromString_WithPortOnePartPath() {
+ URL url = URL::fromString("http://foo.bar:11440/http-bind/");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(11440, *url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string("/http-bind/"), url.getPath());
+ }
+
+ void testFromString_WithPortWithoutPath() {
+ URL url = URL::fromString("http://foo.bar:1234");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(1234, *url.getPort());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath());
+ }
+
+ void testFromString_WithUserInfo() {
+ URL url = URL::fromString("http://user:pass@foo.bar/baz/bam");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath());
+ }
+
+ void testFromString_NonASCIIHost() {
+ URL url = URL::fromString("http://www.tron%C3%A7on.be/baz/bam");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("www.tron\xc3\xa7on.be"), url.getHost());
+ }
+
+ void testFromString_NonASCIIPath() {
+ URL url = URL::fromString("http://foo.bar/baz/tron%C3%A7on/bam");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("/baz/tron\xc3\xa7on/bam"), url.getPath());
+ }
+
+ void testToString() {
+ CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar/baz/bam"), URL("http", "foo.bar", "/baz/bam").toString());
+ }
+
+ void testToString_WithPort() {
+ CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar:1234/baz/bam"), URL("http", "foo.bar", 1234, "/baz/bam").toString());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(URLTest);
diff --git a/Swiften/Base/WindowsRegistry.h b/Swiften/Base/WindowsRegistry.h
index 31ece7a..6243dd2 100644
--- a/Swiften/Base/WindowsRegistry.h
+++ b/Swiften/Base/WindowsRegistry.h
@@ -9,49 +9,49 @@
#include <windows.h>
namespace Swift {
- class WindowsRegistry {
- public:
- static bool isFIPSEnabled() {
- char* pathForXP = "System\\CurrentControlSet\\Control\\Lsa";
- char* pathSinceVista = "System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy";
- char* keyForXP = "FIPSAlgorithmPolicy";
- char* keySinceVista = "Enabled";
-
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
-
- char* keyForOS = osvi.dwMajorVersion < 6 ? keyForXP : keySinceVista;
- char* pathForOS = osvi.dwMajorVersion < 6 ? pathForXP : pathSinceVista;
-
- /* http://support.microsoft.com/kb/811833 */
- /* http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx */
- HKEY key;
- bool result = false;
- if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- pathForOS,
- 0,
- KEY_READ,
- &key) != ERROR_SUCCESS) {
- /* If we can't find the key that says we're FIPS, we're not FIPS */
- return result;
- }
- DWORD keyType = REG_DWORD;
- DWORD data;
- DWORD length = sizeof(data);
-
- if (RegQueryValueEx(key,
- keyForOS,
- NULL,
- &keyType,
- (LPBYTE)&data,
- &length) == ERROR_SUCCESS) {
- result = data != 0;
- }
-
- RegCloseKey(key);
- return result;
- }
- };
+ class WindowsRegistry {
+ public:
+ static bool isFIPSEnabled() {
+ char* pathForXP = "System\\CurrentControlSet\\Control\\Lsa";
+ char* pathSinceVista = "System\\CurrentControlSet\\Control\\Lsa\\FIPSAlgorithmPolicy";
+ char* keyForXP = "FIPSAlgorithmPolicy";
+ char* keySinceVista = "Enabled";
+
+ OSVERSIONINFO osvi;
+ ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ GetVersionEx(&osvi);
+
+ char* keyForOS = osvi.dwMajorVersion < 6 ? keyForXP : keySinceVista;
+ char* pathForOS = osvi.dwMajorVersion < 6 ? pathForXP : pathSinceVista;
+
+ /* http://support.microsoft.com/kb/811833 */
+ /* http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx */
+ HKEY key;
+ bool result = false;
+ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+ pathForOS,
+ 0,
+ KEY_READ,
+ &key) != ERROR_SUCCESS) {
+ /* If we can't find the key that says we're FIPS, we're not FIPS */
+ return result;
+ }
+ DWORD keyType = REG_DWORD;
+ DWORD data;
+ DWORD length = sizeof(data);
+
+ if (RegQueryValueEx(key,
+ keyForOS,
+ NULL,
+ &keyType,
+ (LPBYTE)&data,
+ &length) == ERROR_SUCCESS) {
+ result = data != 0;
+ }
+
+ RegCloseKey(key);
+ return result;
+ }
+ };
}
diff --git a/Swiften/Base/boost_bsignals.h b/Swiften/Base/boost_bsignals.h
index 005c7dc..62f7cb3 100644
--- a/Swiften/Base/boost_bsignals.h
+++ b/Swiften/Base/boost_bsignals.h
@@ -17,7 +17,7 @@
#include <boost/signal.hpp>
namespace boost {
- namespace bsignals = signals;
+ namespace bsignals = signals;
}
#if defined(signals) && defined(Q_SIGNALS) && !defined(QT_MOC_CPP)
diff --git a/Swiften/Base/format.h b/Swiften/Base/format.h
index 07fcd88..e5696b0 100644
--- a/Swiften/Base/format.h
+++ b/Swiften/Base/format.h
@@ -11,16 +11,16 @@
#include <boost/format.hpp>
namespace Swift {
- inline boost::format format(const std::string& s) {
- using namespace boost::io;
- try {
- boost::format fmter(s);
- fmter.exceptions(no_error_bits);
- return fmter;
- }
- catch (...) {
- std::cerr << "Error: Invalid translation: " << s << std::endl;
- throw;
- }
- }
+ inline boost::format format(const std::string& s) {
+ using namespace boost::io;
+ try {
+ boost::format fmter(s);
+ fmter.exceptions(no_error_bits);
+ return fmter;
+ }
+ catch (...) {
+ std::cerr << "Error: Invalid translation: " << s << std::endl;
+ throw;
+ }
+ }
}
diff --git a/Swiften/Base/sleep.cpp b/Swiften/Base/sleep.cpp
index 0c450c3..5a0d729 100644
--- a/Swiften/Base/sleep.cpp
+++ b/Swiften/Base/sleep.cpp
@@ -12,14 +12,14 @@
namespace Swift {
void sleep(unsigned int msecs) {
- boost::xtime xt;
+ boost::xtime xt;
#if BOOST_VERSION >= 105000
- boost::xtime_get(&xt, boost::TIME_UTC_);
+ boost::xtime_get(&xt, boost::TIME_UTC_);
#else
- boost::xtime_get(&xt, boost::TIME_UTC);
+ boost::xtime_get(&xt, boost::TIME_UTC);
#endif
- xt.nsec += msecs*1000000;
- boost::thread::sleep(xt);
+ xt.nsec += msecs*1000000;
+ boost::thread::sleep(xt);
}
}
diff --git a/Swiften/Base/sleep.h b/Swiften/Base/sleep.h
index d2bec72..744e19f 100644
--- a/Swiften/Base/sleep.h
+++ b/Swiften/Base/sleep.h
@@ -9,5 +9,5 @@
#include <Swiften/Base/API.h>
namespace Swift {
- SWIFTEN_API void sleep(unsigned int msecs);
+ SWIFTEN_API void sleep(unsigned int msecs);
}
diff --git a/Swiften/Chat/ChatStateNotifier.cpp b/Swiften/Chat/ChatStateNotifier.cpp
index b2b7f4b..c623ce1 100644
--- a/Swiften/Chat/ChatStateNotifier.cpp
+++ b/Swiften/Chat/ChatStateNotifier.cpp
@@ -17,77 +17,77 @@
namespace Swift {
ChatStateNotifier::ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager) : stanzaChannel_(stanzaChannel), entityCapsManager_(entityCapsManager), contact_(contact) {
- setContact(contact);
- entityCapsManager_->onCapsChanged.connect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1));
+ setContact(contact);
+ entityCapsManager_->onCapsChanged.connect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1));
}
ChatStateNotifier::~ChatStateNotifier() {
- entityCapsManager_->onCapsChanged.disconnect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1));
+ entityCapsManager_->onCapsChanged.disconnect(boost::bind(&ChatStateNotifier::handleCapsChanged, this, _1));
}
void ChatStateNotifier::setContact(const JID& contact) {
- contactHasSentActive_ = false;
- userIsTyping_ = false;
- contactIsOnline_ = false;
- contact_ = contact;
- handleCapsChanged(contact_);
+ contactHasSentActive_ = false;
+ userIsTyping_ = false;
+ contactIsOnline_ = false;
+ contact_ = contact;
+ handleCapsChanged(contact_);
}
void ChatStateNotifier::setContactIsOnline(bool online) {
- contactIsOnline_ = online;
+ contactIsOnline_ = online;
}
void ChatStateNotifier::setUserIsTyping() {
- bool should = contactShouldReceiveStates();
- if (should && !userIsTyping_) {
- userIsTyping_ = true;
- changeState(ChatState::Composing);
- }
+ bool should = contactShouldReceiveStates();
+ if (should && !userIsTyping_) {
+ userIsTyping_ = true;
+ changeState(ChatState::Composing);
+ }
}
void ChatStateNotifier::userSentMessage() {
- userIsTyping_ = false;
+ userIsTyping_ = false;
}
void ChatStateNotifier::userCancelledNewMessage() {
- if (userIsTyping_) {
- userIsTyping_ = false;
- changeState(ChatState::Active);
- }
+ if (userIsTyping_) {
+ userIsTyping_ = false;
+ changeState(ChatState::Active);
+ }
}
void ChatStateNotifier::receivedMessageFromContact(bool hasActiveElement) {
- contactHasSentActive_ = hasActiveElement;
+ contactHasSentActive_ = hasActiveElement;
}
bool ChatStateNotifier::contactShouldReceiveStates() {
- /* So, yes, the XEP says to look at caps, but it also says that once you've
- heard from the contact, the active state overrides this.
- *HOWEVER* it says that the MUST NOT send csn if you haven't received
- active is OPTIONAL behaviour for if you haven't got caps.*/
- return contactIsOnline_ && (contactHasSentActive_ || contactHas85Caps_);
+ /* So, yes, the XEP says to look at caps, but it also says that once you've
+ heard from the contact, the active state overrides this.
+ *HOWEVER* it says that the MUST NOT send csn if you haven't received
+ active is OPTIONAL behaviour for if you haven't got caps.*/
+ return contactIsOnline_ && (contactHasSentActive_ || contactHas85Caps_);
}
void ChatStateNotifier::changeState(ChatState::ChatStateType state) {
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setTo(contact_);
- message->addPayload(boost::make_shared<ChatState>(state));
- stanzaChannel_->sendMessage(message);
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setTo(contact_);
+ message->addPayload(boost::make_shared<ChatState>(state));
+ stanzaChannel_->sendMessage(message);
}
void ChatStateNotifier::addChatStateRequest(Message::ref message) {
- if (contactShouldReceiveStates()) {
- message->addPayload(boost::make_shared<ChatState>(ChatState::Active));
- }
+ if (contactShouldReceiveStates()) {
+ message->addPayload(boost::make_shared<ChatState>(ChatState::Active));
+ }
}
void ChatStateNotifier::handleCapsChanged(const JID& jid) {
- if (jid == contact_) {
- DiscoInfo::ref caps = entityCapsManager_->getCaps(contact_);
- bool hasCSN = caps && caps->hasFeature(DiscoInfo::ChatStatesFeature);
- contactHas85Caps_ = hasCSN;
- }
+ if (jid == contact_) {
+ DiscoInfo::ref caps = entityCapsManager_->getCaps(contact_);
+ bool hasCSN = caps && caps->hasFeature(DiscoInfo::ChatStatesFeature);
+ contactHas85Caps_ = hasCSN;
+ }
}
}
diff --git a/Swiften/Chat/ChatStateNotifier.h b/Swiften/Chat/ChatStateNotifier.h
index 609fed4..a53fad8 100644
--- a/Swiften/Chat/ChatStateNotifier.h
+++ b/Swiften/Chat/ChatStateNotifier.h
@@ -15,37 +15,37 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class StanzaChannel;
- class EntityCapsProvider;
-
- class SWIFTEN_API ChatStateNotifier {
- public:
- ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager);
- ~ChatStateNotifier();
-
- void setContact(const JID& contact);
-
- void addChatStateRequest(Message::ref message);
-
- void setUserIsTyping();
- void userSentMessage();
- void userCancelledNewMessage();
-
- void receivedMessageFromContact(bool hasActiveElement);
- void setContactIsOnline(bool online);
-
- private:
- bool contactShouldReceiveStates();
- void changeState(ChatState::ChatStateType type);
- void handleCapsChanged(const JID& contact);
-
- private:
- StanzaChannel* stanzaChannel_;
- EntityCapsProvider* entityCapsManager_;
- JID contact_;
- bool contactHas85Caps_;
- bool contactHasSentActive_;
- bool userIsTyping_;
- bool contactIsOnline_;
- };
+ class StanzaChannel;
+ class EntityCapsProvider;
+
+ class SWIFTEN_API ChatStateNotifier {
+ public:
+ ChatStateNotifier(StanzaChannel* stanzaChannel, const JID& contact, EntityCapsProvider* entityCapsManager);
+ ~ChatStateNotifier();
+
+ void setContact(const JID& contact);
+
+ void addChatStateRequest(Message::ref message);
+
+ void setUserIsTyping();
+ void userSentMessage();
+ void userCancelledNewMessage();
+
+ void receivedMessageFromContact(bool hasActiveElement);
+ void setContactIsOnline(bool online);
+
+ private:
+ bool contactShouldReceiveStates();
+ void changeState(ChatState::ChatStateType type);
+ void handleCapsChanged(const JID& contact);
+
+ private:
+ StanzaChannel* stanzaChannel_;
+ EntityCapsProvider* entityCapsManager_;
+ JID contact_;
+ bool contactHas85Caps_;
+ bool contactHasSentActive_;
+ bool userIsTyping_;
+ bool contactIsOnline_;
+ };
}
diff --git a/Swiften/Chat/ChatStateTracker.cpp b/Swiften/Chat/ChatStateTracker.cpp
index 34b7a04..5141872 100644
--- a/Swiften/Chat/ChatStateTracker.cpp
+++ b/Swiften/Chat/ChatStateTracker.cpp
@@ -8,30 +8,30 @@
namespace Swift {
ChatStateTracker::ChatStateTracker() {
- currentState_ = ChatState::Gone;
+ currentState_ = ChatState::Gone;
}
void ChatStateTracker::handleMessageReceived(boost::shared_ptr<Message> message) {
- if (message->getType() == Message::Error) {
- return;
- }
- boost::shared_ptr<ChatState> statePayload = message->getPayload<ChatState>();
- if (statePayload) {
- changeState(statePayload->getChatState());;
- }
+ if (message->getType() == Message::Error) {
+ return;
+ }
+ boost::shared_ptr<ChatState> statePayload = message->getPayload<ChatState>();
+ if (statePayload) {
+ changeState(statePayload->getChatState());;
+ }
}
void ChatStateTracker::handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
- if (newPresence->getType() == Presence::Unavailable) {
- onChatStateChange(ChatState::Gone);
- }
+ if (newPresence->getType() == Presence::Unavailable) {
+ onChatStateChange(ChatState::Gone);
+ }
}
void ChatStateTracker::changeState(ChatState::ChatStateType state) {
- if (state != currentState_) {
- currentState_ = state;
- onChatStateChange(state);
- }
+ if (state != currentState_) {
+ currentState_ = state;
+ onChatStateChange(state);
+ }
}
}
diff --git a/Swiften/Chat/ChatStateTracker.h b/Swiften/Chat/ChatStateTracker.h
index b756b98..f31da0b 100644
--- a/Swiften/Chat/ChatStateTracker.h
+++ b/Swiften/Chat/ChatStateTracker.h
@@ -15,14 +15,14 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- class SWIFTEN_API ChatStateTracker {
- public:
- ChatStateTracker();
- void handleMessageReceived(boost::shared_ptr<Message> message);
- void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
- boost::signal<void (ChatState::ChatStateType)> onChatStateChange;
- private:
- void changeState(ChatState::ChatStateType state);
- ChatState::ChatStateType currentState_;
- };
+ class SWIFTEN_API ChatStateTracker {
+ public:
+ ChatStateTracker();
+ void handleMessageReceived(boost::shared_ptr<Message> message);
+ void handlePresenceChange(boost::shared_ptr<Presence> newPresence);
+ boost::signal<void (ChatState::ChatStateType)> onChatStateChange;
+ private:
+ void changeState(ChatState::ChatStateType state);
+ ChatState::ChatStateType currentState_;
+ };
}
diff --git a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
index b293f9d..af43ced 100644
--- a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
+++ b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
@@ -17,153 +17,153 @@
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();
-
+ 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_;
- delete entityCapsProvider;
- delete stanzaChannel;
- }
-
- void testStartTypingReply_CapsNotIncluded() {
- notifier_->setUserIsTyping();
- CPPUNIT_ASSERT_EQUAL(0, getComposingCount());
- }
-
- void testSendTwoMessages() {
- setContactHas85Caps();
- notifier_->setUserIsTyping();
- notifier_->userSentMessage();
- notifier_->setUserIsTyping();
- notifier_->userSentMessage();
- CPPUNIT_ASSERT_EQUAL(2, getComposingCount());
- }
-
- void testCancelledNewMessage() {
- setContactHas85Caps();
- notifier_->setUserIsTyping();
- notifier_->userCancelledNewMessage();
- CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
- CPPUNIT_ASSERT_EQUAL(1, getActiveCount());
- CPPUNIT_ASSERT_EQUAL(ChatState::Active, stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getPayload<ChatState>()->getChatState());
- }
-
-
- void testContactShouldReceiveStates_CapsOnly() {
- setContactHas85Caps();
- boost::shared_ptr<Message> message(new Message());
- notifier_->addChatStateRequest(message);
- CPPUNIT_ASSERT(message->getPayload<ChatState>());
- CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
- }
-
- void testContactShouldReceiveStates_CapsNorActive() {
- boost::shared_ptr<Message> message(new Message());
- notifier_->addChatStateRequest(message);
- CPPUNIT_ASSERT(!message->getPayload<ChatState>());
- }
-
- void testContactShouldReceiveStates_ActiveOverrideOn() {
- notifier_->receivedMessageFromContact(true);
- boost::shared_ptr<Message> message(new Message());
- notifier_->addChatStateRequest(message);
- CPPUNIT_ASSERT(message->getPayload<ChatState>());
- CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
- }
-
- void testContactShouldReceiveStates_ActiveOverrideOff() {
- setContactHas85Caps();
- notifier_->receivedMessageFromContact(false);
- /* I originally read the MUST NOT send after receiving without Active and
- * thought this should check for false, but I later found it was OPTIONAL
- * (MAY) behaviour only for if you didn't receive caps.
- */
- boost::shared_ptr<Message> message(new Message());
- notifier_->addChatStateRequest(message);
- CPPUNIT_ASSERT(message->getPayload<ChatState>());
- CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
- }
-
-
- void testStartTypingReply_CapsIncluded() {
- setContactHas85Caps();
- notifier_->setUserIsTyping();
- CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
- }
-
- void testContinueTypingReply_CapsIncluded() {
- setContactHas85Caps();
- 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(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) {
- if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) {
- result++;
- }
- }
- return result;
- }
-
- int getActiveCount() const {
- int result = 0;
- foreach(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) {
- if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Active) {
- result++;
- }
- }
- return result;
- }
-
- private:
- DummyStanzaChannel* stanzaChannel;
- DummyEntityCapsProvider* entityCapsProvider;
- ChatStateNotifier* notifier_;
+ 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_;
+ delete entityCapsProvider;
+ delete stanzaChannel;
+ }
+
+ void testStartTypingReply_CapsNotIncluded() {
+ notifier_->setUserIsTyping();
+ CPPUNIT_ASSERT_EQUAL(0, getComposingCount());
+ }
+
+ void testSendTwoMessages() {
+ setContactHas85Caps();
+ notifier_->setUserIsTyping();
+ notifier_->userSentMessage();
+ notifier_->setUserIsTyping();
+ notifier_->userSentMessage();
+ CPPUNIT_ASSERT_EQUAL(2, getComposingCount());
+ }
+
+ void testCancelledNewMessage() {
+ setContactHas85Caps();
+ notifier_->setUserIsTyping();
+ notifier_->userCancelledNewMessage();
+ CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
+ CPPUNIT_ASSERT_EQUAL(1, getActiveCount());
+ CPPUNIT_ASSERT_EQUAL(ChatState::Active, stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getPayload<ChatState>()->getChatState());
+ }
+
+
+ void testContactShouldReceiveStates_CapsOnly() {
+ setContactHas85Caps();
+ boost::shared_ptr<Message> message(new Message());
+ notifier_->addChatStateRequest(message);
+ CPPUNIT_ASSERT(message->getPayload<ChatState>());
+ CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
+ }
+
+ void testContactShouldReceiveStates_CapsNorActive() {
+ boost::shared_ptr<Message> message(new Message());
+ notifier_->addChatStateRequest(message);
+ CPPUNIT_ASSERT(!message->getPayload<ChatState>());
+ }
+
+ void testContactShouldReceiveStates_ActiveOverrideOn() {
+ notifier_->receivedMessageFromContact(true);
+ boost::shared_ptr<Message> message(new Message());
+ notifier_->addChatStateRequest(message);
+ CPPUNIT_ASSERT(message->getPayload<ChatState>());
+ CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
+ }
+
+ void testContactShouldReceiveStates_ActiveOverrideOff() {
+ setContactHas85Caps();
+ notifier_->receivedMessageFromContact(false);
+ /* I originally read the MUST NOT send after receiving without Active and
+ * thought this should check for false, but I later found it was OPTIONAL
+ * (MAY) behaviour only for if you didn't receive caps.
+ */
+ boost::shared_ptr<Message> message(new Message());
+ notifier_->addChatStateRequest(message);
+ CPPUNIT_ASSERT(message->getPayload<ChatState>());
+ CPPUNIT_ASSERT_EQUAL(ChatState::Active, message->getPayload<ChatState>()->getChatState());
+ }
+
+
+ void testStartTypingReply_CapsIncluded() {
+ setContactHas85Caps();
+ notifier_->setUserIsTyping();
+ CPPUNIT_ASSERT_EQUAL(1, getComposingCount());
+ }
+
+ void testContinueTypingReply_CapsIncluded() {
+ setContactHas85Caps();
+ 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(boost::shared_ptr<Stanza> stanza, stanzaChannel->sentStanzas) {
+ if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ int getActiveCount() const {
+ int result = 0;
+ foreach(boost::shared_ptr<Stanza> 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/BlockList.cpp b/Swiften/Client/BlockList.cpp
index abf9412..cb77080 100644
--- a/Swiften/Client/BlockList.cpp
+++ b/Swiften/Client/BlockList.cpp
@@ -15,8 +15,8 @@ BlockList::~BlockList() {
}
bool BlockList::isBlocked(const JID& jid) const {
- const std::vector<JID>& items = getItems();
- return (std::find(items.begin(), items.end(), jid.toBare()) != items.end()) ||
- (std::find(items.begin(), items.end(), JID(jid.getDomain())) != items.end()) ||
- (std::find(items.begin(), items.end(), jid) != items.end());
+ const std::vector<JID>& items = getItems();
+ return (std::find(items.begin(), items.end(), jid.toBare()) != items.end()) ||
+ (std::find(items.begin(), items.end(), JID(jid.getDomain())) != items.end()) ||
+ (std::find(items.begin(), items.end(), jid) != items.end());
}
diff --git a/Swiften/Client/BlockList.h b/Swiften/Client/BlockList.h
index 1ee1ad9..c200f20 100644
--- a/Swiften/Client/BlockList.h
+++ b/Swiften/Client/BlockList.h
@@ -13,25 +13,25 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API BlockList {
- public:
- enum State {
- Init,
- Requesting,
- Available,
- Error
- };
- virtual ~BlockList();
-
- virtual State getState() const = 0;
-
- virtual const std::vector<JID>& getItems() const = 0;
-
- bool isBlocked(const JID& jid) const;
-
- public:
- boost::signal<void ()> onStateChanged;
- boost::signal<void (const JID&)> onItemAdded;
- boost::signal<void (const JID&)> onItemRemoved;
- };
+ class SWIFTEN_API BlockList {
+ public:
+ enum State {
+ Init,
+ Requesting,
+ Available,
+ Error
+ };
+ virtual ~BlockList();
+
+ virtual State getState() const = 0;
+
+ virtual const std::vector<JID>& getItems() const = 0;
+
+ bool isBlocked(const JID& jid) const;
+
+ public:
+ boost::signal<void ()> onStateChanged;
+ boost::signal<void (const JID&)> onItemAdded;
+ boost::signal<void (const JID&)> onItemRemoved;
+ };
}
diff --git a/Swiften/Client/BlockListImpl.cpp b/Swiften/Client/BlockListImpl.cpp
index 4abaa37..ebffff8 100644
--- a/Swiften/Client/BlockListImpl.cpp
+++ b/Swiften/Client/BlockListImpl.cpp
@@ -17,58 +17,58 @@ 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) {
- if (std::find(newItems.begin(), newItems.end(), jid) == newItems.end()) {
- onItemRemoved(jid);
- }
- }
+ // JIDs which are in the current list but not in the new list, are removed.
+ foreach (const JID& 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) {
- if (std::find(items.begin(), items.end(), jid) == items.end()) {
- onItemAdded(jid);
- }
- }
- items = newItems;
+ // JIDs which are in the new list but not in the current list, are added.
+ foreach (const JID& 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);
- }
+ 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);
- }
+ 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();
- }
+ if (this->state != state) {
+ this->state = state;
+ onStateChanged();
+ }
}
void BlockListImpl::addItems(const std::vector<JID>& items) {
- foreach (const JID& item, items) {
- addItem(item);
- }
+ foreach (const JID& item, items) {
+ addItem(item);
+ }
}
void BlockListImpl::removeItems(const std::vector<JID>& items) {
- std::vector<JID> itemsToRemove = items;
- foreach (const JID& item, itemsToRemove) {
- removeItem(item);
- }
+ std::vector<JID> itemsToRemove = items;
+ foreach (const JID& item, itemsToRemove) {
+ removeItem(item);
+ }
}
void BlockListImpl::removeAllItems() {
- removeItems(items);
+ removeItems(items);
}
diff --git a/Swiften/Client/BlockListImpl.h b/Swiften/Client/BlockListImpl.h
index e203d68..edf459a 100644
--- a/Swiften/Client/BlockListImpl.h
+++ b/Swiften/Client/BlockListImpl.h
@@ -9,29 +9,29 @@
#include <Swiften/Client/BlockList.h>
namespace Swift {
- class BlockListImpl : public BlockList {
- public:
- BlockListImpl();
-
- virtual State getState() const {
- return state;
- }
-
- void setState(State state);
-
- virtual const std::vector<JID>& getItems() const {
- return items;
- }
-
- void setItems(const std::vector<JID>& newItems);
- void addItem(const JID& item);
- void removeItem(const JID& item);
- void addItems(const std::vector<JID>& items);
- void removeItems(const std::vector<JID>& items);
- void removeAllItems();
-
- private:
- State state;
- std::vector<JID> items;
- };
+ class BlockListImpl : public BlockList {
+ public:
+ BlockListImpl();
+
+ virtual State getState() const {
+ return state;
+ }
+
+ void setState(State state);
+
+ virtual const std::vector<JID>& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector<JID>& newItems);
+ void addItem(const JID& item);
+ void removeItem(const JID& item);
+ void addItems(const std::vector<JID>& items);
+ void removeItems(const std::vector<JID>& items);
+ void removeAllItems();
+
+ private:
+ State state;
+ std::vector<JID> items;
+ };
}
diff --git a/Swiften/Client/Client.cpp b/Swiften/Client/Client.cpp
index f1266e9..89b66b8 100644
--- a/Swiften/Client/Client.cpp
+++ b/Swiften/Client/Client.cpp
@@ -39,160 +39,160 @@
namespace Swift {
Client::Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages) : CoreClient(jid, password, networkFactories), storages(storages) {
- memoryStorages = new MemoryStorages(networkFactories->getCryptoProvider());
+ memoryStorages = new MemoryStorages(networkFactories->getCryptoProvider());
- softwareVersionResponder = new SoftwareVersionResponder(getIQRouter());
- softwareVersionResponder->start();
+ softwareVersionResponder = new SoftwareVersionResponder(getIQRouter());
+ softwareVersionResponder->start();
- roster = new XMPPRosterImpl();
- rosterController = new XMPPRosterController(getIQRouter(), roster, getStorages()->getRosterStorage());
+ roster = new XMPPRosterImpl();
+ rosterController = new XMPPRosterController(getIQRouter(), roster, getStorages()->getRosterStorage());
- subscriptionManager = new SubscriptionManager(getStanzaChannel());
+ subscriptionManager = new SubscriptionManager(getStanzaChannel());
- presenceOracle = new PresenceOracle(getStanzaChannel(), roster);
- presenceOracle->onPresenceChange.connect(boost::ref(onPresenceChange));
+ presenceOracle = new PresenceOracle(getStanzaChannel(), roster);
+ presenceOracle->onPresenceChange.connect(boost::ref(onPresenceChange));
- stanzaChannelPresenceSender = new StanzaChannelPresenceSender(getStanzaChannel());
- directedPresenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender);
- discoManager = new ClientDiscoManager(getIQRouter(), directedPresenceSender, networkFactories->getCryptoProvider());
+ stanzaChannelPresenceSender = new StanzaChannelPresenceSender(getStanzaChannel());
+ directedPresenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender);
+ discoManager = new ClientDiscoManager(getIQRouter(), directedPresenceSender, networkFactories->getCryptoProvider());
- mucRegistry = new MUCRegistry();
- mucManager = new MUCManager(getStanzaChannel(), getIQRouter(), directedPresenceSender, mucRegistry);
+ mucRegistry = new MUCRegistry();
+ mucManager = new MUCManager(getStanzaChannel(), getIQRouter(), directedPresenceSender, mucRegistry);
- vcardManager = new VCardManager(jid, getIQRouter(), getStorages()->getVCardStorage());
- avatarManager = new AvatarManagerImpl(vcardManager, getStanzaChannel(), getStorages()->getAvatarStorage(), networkFactories->getCryptoProvider(), mucRegistry);
- capsManager = new CapsManager(getStorages()->getCapsStorage(), getStanzaChannel(), getIQRouter(), networkFactories->getCryptoProvider());
- entityCapsManager = new EntityCapsManager(capsManager, getStanzaChannel());
+ vcardManager = new VCardManager(jid, getIQRouter(), getStorages()->getVCardStorage());
+ avatarManager = new AvatarManagerImpl(vcardManager, getStanzaChannel(), getStorages()->getAvatarStorage(), networkFactories->getCryptoProvider(), mucRegistry);
+ capsManager = new CapsManager(getStorages()->getCapsStorage(), getStanzaChannel(), getIQRouter(), networkFactories->getCryptoProvider());
+ entityCapsManager = new EntityCapsManager(capsManager, getStanzaChannel());
- nickManager = new NickManagerImpl(jid.toBare(), vcardManager);
- nickResolver = new NickResolver(jid.toBare(), roster, vcardManager, mucRegistry);
+ nickManager = new NickManagerImpl(jid.toBare(), vcardManager);
+ nickResolver = new NickResolver(jid.toBare(), roster, vcardManager, mucRegistry);
- blindCertificateTrustChecker = new BlindCertificateTrustChecker();
-
- jingleSessionManager = new JingleSessionManager(getIQRouter());
- blockListManager = new ClientBlockListManager(getIQRouter());
+ blindCertificateTrustChecker = new BlindCertificateTrustChecker();
- whiteboardSessionManager = NULL;
+ jingleSessionManager = new JingleSessionManager(getIQRouter());
+ blockListManager = new ClientBlockListManager(getIQRouter());
+
+ whiteboardSessionManager = NULL;
#ifdef SWIFT_EXPERIMENTAL_WB
- whiteboardSessionManager = new WhiteboardSessionManager(getIQRouter(), getStanzaChannel(), presenceOracle, getEntityCapsProvider());
+ whiteboardSessionManager = new WhiteboardSessionManager(getIQRouter(), getStanzaChannel(), presenceOracle, getEntityCapsProvider());
#endif
- pubsubManager = new PubSubManagerImpl(getStanzaChannel(), getIQRouter());
+ pubsubManager = new PubSubManagerImpl(getStanzaChannel(), getIQRouter());
#ifdef SWIFT_EXPERIMENTAL_FT
- fileTransferManager = new FileTransferManagerImpl(
- getJID(),
- jingleSessionManager,
- getIQRouter(),
- getEntityCapsProvider(),
- presenceOracle,
- getNetworkFactories()->getConnectionFactory(),
- getNetworkFactories()->getConnectionServerFactory(),
- getNetworkFactories()->getTimerFactory(),
- getNetworkFactories()->getDomainNameResolver(),
- getNetworkFactories()->getNetworkEnvironment(),
- getNetworkFactories()->getNATTraverser(),
- getNetworkFactories()->getCryptoProvider());
+ fileTransferManager = new FileTransferManagerImpl(
+ getJID(),
+ jingleSessionManager,
+ getIQRouter(),
+ getEntityCapsProvider(),
+ presenceOracle,
+ getNetworkFactories()->getConnectionFactory(),
+ getNetworkFactories()->getConnectionServerFactory(),
+ getNetworkFactories()->getTimerFactory(),
+ getNetworkFactories()->getDomainNameResolver(),
+ getNetworkFactories()->getNetworkEnvironment(),
+ getNetworkFactories()->getNATTraverser(),
+ getNetworkFactories()->getCryptoProvider());
#else
- fileTransferManager = new DummyFileTransferManager();
+ fileTransferManager = new DummyFileTransferManager();
#endif
}
Client::~Client() {
- delete pubsubManager;
- delete whiteboardSessionManager;
+ delete pubsubManager;
+ delete whiteboardSessionManager;
+
+ delete fileTransferManager;
+ delete blockListManager;
+ delete jingleSessionManager;
- delete fileTransferManager;
- delete blockListManager;
- delete jingleSessionManager;
-
- delete blindCertificateTrustChecker;
+ delete blindCertificateTrustChecker;
- delete nickResolver;
- delete nickManager;
+ delete nickResolver;
+ delete nickManager;
- delete entityCapsManager;
- delete capsManager;
- delete avatarManager;
- delete vcardManager;
+ delete entityCapsManager;
+ delete capsManager;
+ delete avatarManager;
+ delete vcardManager;
- delete mucManager;
- delete mucRegistry;
+ delete mucManager;
+ delete mucRegistry;
- delete discoManager;
- delete directedPresenceSender;
- delete stanzaChannelPresenceSender;
+ delete discoManager;
+ delete directedPresenceSender;
+ delete stanzaChannelPresenceSender;
- delete presenceOracle;
- delete subscriptionManager;
- delete rosterController;
- delete roster;
+ delete presenceOracle;
+ delete subscriptionManager;
+ delete rosterController;
+ delete roster;
- softwareVersionResponder->stop();
- delete softwareVersionResponder;
+ softwareVersionResponder->stop();
+ delete softwareVersionResponder;
- delete memoryStorages;
+ delete memoryStorages;
}
XMPPRoster* Client::getRoster() const {
- return roster;
+ return roster;
}
void Client::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os) {
- softwareVersionResponder->setVersion(name, version, os);
+ softwareVersionResponder->setVersion(name, version, os);
}
void Client::handleConnected() {
- discoManager->handleConnected();
+ discoManager->handleConnected();
}
void Client::requestRoster() {
- // FIXME: We should set this once when the session is finished, but there
- // is currently no callback for this
- if (getSession()) {
- rosterController->setUseVersioning(getSession()->getRosterVersioningSupported());
- }
- rosterController->requestRoster();
+ // FIXME: We should set this once when the session is finished, but there
+ // is currently no callback for this
+ if (getSession()) {
+ rosterController->setUseVersioning(getSession()->getRosterVersioningSupported());
+ }
+ rosterController->requestRoster();
}
Presence::ref Client::getLastPresence(const JID& jid) const {
- return presenceOracle->getLastPresence(jid);
+ return presenceOracle->getLastPresence(jid);
}
Presence::ref Client::getHighestPriorityPresence(const JID& bareJID) const {
- return presenceOracle->getHighestPriorityPresence(bareJID);
+ return presenceOracle->getHighestPriorityPresence(bareJID);
}
Storages* Client::getStorages() const {
- if (storages) {
- return storages;
- }
- return memoryStorages;
+ if (storages) {
+ return storages;
+ }
+ return memoryStorages;
}
PresenceSender* Client::getPresenceSender() const {
- return discoManager->getPresenceSender();
+ return discoManager->getPresenceSender();
}
EntityCapsProvider* Client::getEntityCapsProvider() const {
- return entityCapsManager;
+ return entityCapsManager;
}
void Client::setAlwaysTrustCertificates() {
- setCertificateTrustChecker(blindCertificateTrustChecker);
+ setCertificateTrustChecker(blindCertificateTrustChecker);
}
NickManager* Client::getNickManager() const {
- return nickManager;
+ return nickManager;
}
FileTransferManager* Client::getFileTransferManager() const {
- return fileTransferManager;
+ return fileTransferManager;
}
WhiteboardSessionManager* Client::getWhiteboardSessionManager() const {
- return whiteboardSessionManager;
+ return whiteboardSessionManager;
}
}
diff --git a/Swiften/Client/Client.h b/Swiften/Client/Client.h
index f7a372e..a3d11a1 100644
--- a/Swiften/Client/Client.h
+++ b/Swiften/Client/Client.h
@@ -11,196 +11,196 @@
#include <Swiften/Client/CoreClient.h>
namespace Swift {
- class SoftwareVersionResponder;
- class BlindCertificateTrustChecker;
- class XMPPRoster;
- class XMPPRosterImpl;
- class MUCManager;
- class XMPPRosterController;
- class PresenceOracle;
- class PresenceSender;
- class DirectedPresenceSender;
- class StanzaChannelPresenceSender;
- class MUCRegistry;
- class Storages;
- class MemoryStorages;
- class VCardManager;
- class AvatarManager;
- class CapsManager;
- class EntityCapsManager;
- class EntityCapsProvider;
- class NickResolver;
- class SubscriptionManager;
- class ClientDiscoManager;
- class NickManager;
- class FileTransferManager;
- class JingleSessionManager;
- class FileTransferManager;
- class WhiteboardSessionManager;
- class ClientBlockListManager;
- class PubSubManager;
-
- /**
- * Provides the core functionality for writing XMPP client software.
- *
- * Besides connecting to an XMPP server, this class also provides interfaces for
- * performing most tasks on the XMPP network.
- */
- class SWIFTEN_API Client : public CoreClient {
- public:
- /**
- * Constructs a client for the given JID with the given password.
- *
- * \param storages The interfaces for storing cache information etc. If
- * this is NULL,
- * all data will be stored in memory (and be lost on shutdown)
- */
- Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages = NULL);
- virtual ~Client();
-
-
- /**
- * Sets the software version of the client.
- *
- * This will be used to respond to version queries from other entities.
- */
- void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os = "");
-
- /**
- * Returns a representation of the roster.
- *
- * The roster is initially empty. To populate it, call requestRoster(),
- * which will request the roster from the server. When the roster has
- * been requested, it will also be kept up to date when it is updated on
- * the server side.
- *
- * This pointer remains the same across the lifetime of Client. All
- * changes to the roster (e.g. after the initial roster request, or after
- * subsequent roster updates) are notified through the XMPPRoster's
- * signals.
- *
- * \see requestRoster()
- */
- XMPPRoster* getRoster() const;
-
- /**
- * Requests the roster from the server.
- *
- * \see getRoster()
- */
- void requestRoster();
-
- /**
- * Returns the last received presence for the given (full) JID.
- */
- boost::shared_ptr<Presence> getLastPresence(const JID& jid) const;
-
- /**
- * Returns the presence with the highest priority received for the given JID.
- */
- boost::shared_ptr<Presence> getHighestPriorityPresence(const JID& bareJID) const;
-
- PresenceOracle* getPresenceOracle() const {
- return presenceOracle;
- }
-
- PresenceSender* getPresenceSender() const;
-
- MUCManager* getMUCManager() const {
- return mucManager;
- }
-
- MUCRegistry* getMUCRegistry() const {
- return mucRegistry;
- }
-
- VCardManager* getVCardManager() const {
- return vcardManager;
- }
-
- AvatarManager* getAvatarManager() const {
- return avatarManager;
- }
-
- EntityCapsProvider* getEntityCapsProvider() const;
-
- NickManager* getNickManager() const;
-
- NickResolver* getNickResolver() const {
- return nickResolver;
- }
-
- SubscriptionManager* getSubscriptionManager() const {
- return subscriptionManager;
- }
-
- ClientDiscoManager* getDiscoManager() const {
- return discoManager;
- }
-
- ClientBlockListManager* getClientBlockListManager() const {
- return blockListManager;
- }
-
- /**
- * Returns a FileTransferManager for the client. This is only available after the onConnected
- * signal has been fired.
- *
- * WARNING: File transfer will only work if Swiften is built in 'experimental' mode.
- */
- FileTransferManager* getFileTransferManager() const;
-
- /**
- * Configures the client to always trust a non-validating
- * TLS certificate from the server.
- * This is equivalent to setting a BlindCertificateTrustChecker
- * using setCertificateTrustChecker().
- */
- void setAlwaysTrustCertificates();
-
- WhiteboardSessionManager* getWhiteboardSessionManager() const;
-
- PubSubManager* getPubSubManager() const {
- return pubsubManager;
- }
-
-
- public:
- /**
- * This signal is emitted when a JID changes presence.
- */
- boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChange;
-
- private:
- Storages* getStorages() const;
-
- protected:
- void handleConnected();
-
- private:
- Storages* storages;
- MemoryStorages* memoryStorages;
- SoftwareVersionResponder* softwareVersionResponder;
- XMPPRosterImpl* roster;
- XMPPRosterController* rosterController;
- PresenceOracle* presenceOracle;
- DirectedPresenceSender* directedPresenceSender;
- StanzaChannelPresenceSender* stanzaChannelPresenceSender;
- MUCRegistry* mucRegistry;
- VCardManager* vcardManager;
- AvatarManager* avatarManager;
- CapsManager* capsManager;
- EntityCapsManager* entityCapsManager;
- NickManager* nickManager;
- NickResolver* nickResolver;
- SubscriptionManager* subscriptionManager;
- MUCManager* mucManager;
- ClientDiscoManager* discoManager;
- JingleSessionManager* jingleSessionManager;
- FileTransferManager* fileTransferManager;
- BlindCertificateTrustChecker* blindCertificateTrustChecker;
- WhiteboardSessionManager* whiteboardSessionManager;
- ClientBlockListManager* blockListManager;
- PubSubManager* pubsubManager;
- };
+ class SoftwareVersionResponder;
+ class BlindCertificateTrustChecker;
+ class XMPPRoster;
+ class XMPPRosterImpl;
+ class MUCManager;
+ class XMPPRosterController;
+ class PresenceOracle;
+ class PresenceSender;
+ class DirectedPresenceSender;
+ class StanzaChannelPresenceSender;
+ class MUCRegistry;
+ class Storages;
+ class MemoryStorages;
+ class VCardManager;
+ class AvatarManager;
+ class CapsManager;
+ class EntityCapsManager;
+ class EntityCapsProvider;
+ class NickResolver;
+ class SubscriptionManager;
+ class ClientDiscoManager;
+ class NickManager;
+ class FileTransferManager;
+ class JingleSessionManager;
+ class FileTransferManager;
+ class WhiteboardSessionManager;
+ class ClientBlockListManager;
+ class PubSubManager;
+
+ /**
+ * Provides the core functionality for writing XMPP client software.
+ *
+ * Besides connecting to an XMPP server, this class also provides interfaces for
+ * performing most tasks on the XMPP network.
+ */
+ class SWIFTEN_API Client : public CoreClient {
+ public:
+ /**
+ * Constructs a client for the given JID with the given password.
+ *
+ * \param storages The interfaces for storing cache information etc. If
+ * this is NULL,
+ * all data will be stored in memory (and be lost on shutdown)
+ */
+ Client(const JID& jid, const SafeString& password, NetworkFactories* networkFactories, Storages* storages = NULL);
+ virtual ~Client();
+
+
+ /**
+ * Sets the software version of the client.
+ *
+ * This will be used to respond to version queries from other entities.
+ */
+ void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os = "");
+
+ /**
+ * Returns a representation of the roster.
+ *
+ * The roster is initially empty. To populate it, call requestRoster(),
+ * which will request the roster from the server. When the roster has
+ * been requested, it will also be kept up to date when it is updated on
+ * the server side.
+ *
+ * This pointer remains the same across the lifetime of Client. All
+ * changes to the roster (e.g. after the initial roster request, or after
+ * subsequent roster updates) are notified through the XMPPRoster's
+ * signals.
+ *
+ * \see requestRoster()
+ */
+ XMPPRoster* getRoster() const;
+
+ /**
+ * Requests the roster from the server.
+ *
+ * \see getRoster()
+ */
+ void requestRoster();
+
+ /**
+ * Returns the last received presence for the given (full) JID.
+ */
+ boost::shared_ptr<Presence> getLastPresence(const JID& jid) const;
+
+ /**
+ * Returns the presence with the highest priority received for the given JID.
+ */
+ boost::shared_ptr<Presence> getHighestPriorityPresence(const JID& bareJID) const;
+
+ PresenceOracle* getPresenceOracle() const {
+ return presenceOracle;
+ }
+
+ PresenceSender* getPresenceSender() const;
+
+ MUCManager* getMUCManager() const {
+ return mucManager;
+ }
+
+ MUCRegistry* getMUCRegistry() const {
+ return mucRegistry;
+ }
+
+ VCardManager* getVCardManager() const {
+ return vcardManager;
+ }
+
+ AvatarManager* getAvatarManager() const {
+ return avatarManager;
+ }
+
+ EntityCapsProvider* getEntityCapsProvider() const;
+
+ NickManager* getNickManager() const;
+
+ NickResolver* getNickResolver() const {
+ return nickResolver;
+ }
+
+ SubscriptionManager* getSubscriptionManager() const {
+ return subscriptionManager;
+ }
+
+ ClientDiscoManager* getDiscoManager() const {
+ return discoManager;
+ }
+
+ ClientBlockListManager* getClientBlockListManager() const {
+ return blockListManager;
+ }
+
+ /**
+ * Returns a FileTransferManager for the client. This is only available after the onConnected
+ * signal has been fired.
+ *
+ * WARNING: File transfer will only work if Swiften is built in 'experimental' mode.
+ */
+ FileTransferManager* getFileTransferManager() const;
+
+ /**
+ * Configures the client to always trust a non-validating
+ * TLS certificate from the server.
+ * This is equivalent to setting a BlindCertificateTrustChecker
+ * using setCertificateTrustChecker().
+ */
+ void setAlwaysTrustCertificates();
+
+ WhiteboardSessionManager* getWhiteboardSessionManager() const;
+
+ PubSubManager* getPubSubManager() const {
+ return pubsubManager;
+ }
+
+
+ public:
+ /**
+ * This signal is emitted when a JID changes presence.
+ */
+ boost::signal<void (boost::shared_ptr<Presence>)> onPresenceChange;
+
+ private:
+ Storages* getStorages() const;
+
+ protected:
+ void handleConnected();
+
+ private:
+ Storages* storages;
+ MemoryStorages* memoryStorages;
+ SoftwareVersionResponder* softwareVersionResponder;
+ XMPPRosterImpl* roster;
+ XMPPRosterController* rosterController;
+ PresenceOracle* presenceOracle;
+ DirectedPresenceSender* directedPresenceSender;
+ StanzaChannelPresenceSender* stanzaChannelPresenceSender;
+ MUCRegistry* mucRegistry;
+ VCardManager* vcardManager;
+ AvatarManager* avatarManager;
+ CapsManager* capsManager;
+ EntityCapsManager* entityCapsManager;
+ NickManager* nickManager;
+ NickResolver* nickResolver;
+ SubscriptionManager* subscriptionManager;
+ MUCManager* mucManager;
+ ClientDiscoManager* discoManager;
+ JingleSessionManager* jingleSessionManager;
+ FileTransferManager* fileTransferManager;
+ BlindCertificateTrustChecker* blindCertificateTrustChecker;
+ WhiteboardSessionManager* whiteboardSessionManager;
+ ClientBlockListManager* blockListManager;
+ PubSubManager* pubsubManager;
+ };
}
diff --git a/Swiften/Client/ClientBlockListManager.cpp b/Swiften/Client/ClientBlockListManager.cpp
index fa7cd42..84a5639 100644
--- a/Swiften/Client/ClientBlockListManager.cpp
+++ b/Swiften/Client/ClientBlockListManager.cpp
@@ -16,54 +16,54 @@
using namespace Swift;
namespace {
- class BlockResponder : public SetResponder<BlockPayload> {
- public:
- BlockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<BlockPayload>(iqRouter), blockList(blockList) {
- }
-
- virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<BlockPayload> payload) {
- if (getIQRouter()->isAccountJID(from)) {
- if (payload) {
- blockList->addItems(payload->getItems());
- }
- sendResponse(from, id, boost::shared_ptr<BlockPayload>());
- }
- else {
- sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
- }
- return true;
- }
-
- private:
- boost::shared_ptr<BlockListImpl> blockList;
- };
-
- class UnblockResponder : public SetResponder<UnblockPayload> {
- public:
- UnblockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<UnblockPayload>(iqRouter), blockList(blockList) {
- }
-
- virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<UnblockPayload> payload) {
- if (getIQRouter()->isAccountJID(from)) {
- if (payload) {
- if (payload->getItems().empty()) {
- blockList->removeAllItems();
- }
- else {
- blockList->removeItems(payload->getItems());
- }
- }
- sendResponse(from, id, boost::shared_ptr<UnblockPayload>());
- }
- else {
- sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
- }
- return true;
- }
-
- private:
- boost::shared_ptr<BlockListImpl> blockList;
- };
+ class BlockResponder : public SetResponder<BlockPayload> {
+ public:
+ BlockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<BlockPayload>(iqRouter), blockList(blockList) {
+ }
+
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<BlockPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ if (payload) {
+ blockList->addItems(payload->getItems());
+ }
+ sendResponse(from, id, boost::shared_ptr<BlockPayload>());
+ }
+ else {
+ sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
+ }
+ return true;
+ }
+
+ private:
+ boost::shared_ptr<BlockListImpl> blockList;
+ };
+
+ class UnblockResponder : public SetResponder<UnblockPayload> {
+ public:
+ UnblockResponder(boost::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<UnblockPayload>(iqRouter), blockList(blockList) {
+ }
+
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<UnblockPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ if (payload) {
+ if (payload->getItems().empty()) {
+ blockList->removeAllItems();
+ }
+ else {
+ blockList->removeItems(payload->getItems());
+ }
+ }
+ sendResponse(from, id, boost::shared_ptr<UnblockPayload>());
+ }
+ else {
+ sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
+ }
+ return true;
+ }
+
+ private:
+ boost::shared_ptr<BlockListImpl> blockList;
+ };
}
ClientBlockListManager::ClientBlockListManager(IQRouter* iqRouter) : iqRouter(iqRouter) {
@@ -71,69 +71,69 @@ ClientBlockListManager::ClientBlockListManager(IQRouter* iqRouter) : iqRouter(iq
}
ClientBlockListManager::~ClientBlockListManager() {
- if (blockList && blockList->getState() == BlockList::Available) {
- unblockResponder->stop();
- blockResponder->stop();
- }
+ if (blockList && blockList->getState() == BlockList::Available) {
+ unblockResponder->stop();
+ blockResponder->stop();
+ }
}
boost::shared_ptr<BlockList> ClientBlockListManager::getBlockList() {
- if (!blockList) {
- blockList = boost::make_shared<BlockListImpl>();
- blockList->setState(BlockList::Init);
- }
- return blockList;
+ if (!blockList) {
+ blockList = boost::make_shared<BlockListImpl>();
+ blockList->setState(BlockList::Init);
+ }
+ return blockList;
}
boost::shared_ptr<BlockList> ClientBlockListManager::requestBlockList() {
- if (!blockList) {
- blockList = boost::make_shared<BlockListImpl>();
- }
- blockList->setState(BlockList::Requesting);
- boost::shared_ptr<GenericRequest<BlockListPayload> > getRequest = boost::make_shared< GenericRequest<BlockListPayload> >(IQ::Get, JID(), boost::make_shared<BlockListPayload>(), iqRouter);
- getRequest->onResponse.connect(boost::bind(&ClientBlockListManager::handleBlockListReceived, this, _1, _2));
- getRequest->send();
- return blockList;
+ if (!blockList) {
+ blockList = boost::make_shared<BlockListImpl>();
+ }
+ blockList->setState(BlockList::Requesting);
+ boost::shared_ptr<GenericRequest<BlockListPayload> > getRequest = boost::make_shared< GenericRequest<BlockListPayload> >(IQ::Get, JID(), boost::make_shared<BlockListPayload>(), iqRouter);
+ getRequest->onResponse.connect(boost::bind(&ClientBlockListManager::handleBlockListReceived, this, _1, _2));
+ getRequest->send();
+ return blockList;
}
GenericRequest<BlockPayload>::ref ClientBlockListManager::createBlockJIDRequest(const JID& jid) {
- return createBlockJIDsRequest(std::vector<JID>(1, jid));
+ return createBlockJIDsRequest(std::vector<JID>(1, jid));
}
GenericRequest<BlockPayload>::ref ClientBlockListManager::createBlockJIDsRequest(const std::vector<JID>& jids) {
- boost::shared_ptr<BlockPayload> payload = boost::make_shared<BlockPayload>(jids);
- return boost::make_shared< GenericRequest<BlockPayload> >(IQ::Set, JID(), payload, iqRouter);
+ boost::shared_ptr<BlockPayload> payload = boost::make_shared<BlockPayload>(jids);
+ return boost::make_shared< GenericRequest<BlockPayload> >(IQ::Set, JID(), payload, iqRouter);
}
GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockJIDRequest(const JID& jid) {
- return createUnblockJIDsRequest(std::vector<JID>(1, jid));
+ return createUnblockJIDsRequest(std::vector<JID>(1, jid));
}
GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockJIDsRequest(const std::vector<JID>& jids) {
- boost::shared_ptr<UnblockPayload> payload = boost::make_shared<UnblockPayload>(jids);
- return boost::make_shared< GenericRequest<UnblockPayload> >(IQ::Set, JID(), payload, iqRouter);
+ boost::shared_ptr<UnblockPayload> payload = boost::make_shared<UnblockPayload>(jids);
+ return boost::make_shared< GenericRequest<UnblockPayload> >(IQ::Set, JID(), payload, iqRouter);
}
GenericRequest<UnblockPayload>::ref ClientBlockListManager::createUnblockAllRequest() {
- return createUnblockJIDsRequest(std::vector<JID>());
+ return createUnblockJIDsRequest(std::vector<JID>());
}
void ClientBlockListManager::handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref error) {
- if (error || !payload) {
- blockList->setState(BlockList::Error);
- }
- else {
- blockList->setItems(payload->getItems());
- blockList->setState(BlockList::Available);
- if (!blockResponder) {
- blockResponder = boost::make_shared<BlockResponder>(blockList, iqRouter);
- blockResponder->start();
- }
- if (!unblockResponder) {
- unblockResponder = boost::make_shared<UnblockResponder>(blockList, iqRouter);
- unblockResponder->start();
- }
- }
+ if (error || !payload) {
+ blockList->setState(BlockList::Error);
+ }
+ else {
+ blockList->setItems(payload->getItems());
+ blockList->setState(BlockList::Available);
+ if (!blockResponder) {
+ blockResponder = boost::make_shared<BlockResponder>(blockList, iqRouter);
+ blockResponder->start();
+ }
+ if (!unblockResponder) {
+ unblockResponder = boost::make_shared<UnblockResponder>(blockList, iqRouter);
+ unblockResponder->start();
+ }
+ }
}
diff --git a/Swiften/Client/ClientBlockListManager.h b/Swiften/Client/ClientBlockListManager.h
index 1aafdc6..63ff1cd 100644
--- a/Swiften/Client/ClientBlockListManager.h
+++ b/Swiften/Client/ClientBlockListManager.h
@@ -20,38 +20,38 @@
#include <Swiften/Queries/SetResponder.h>
namespace Swift {
- class IQRouter;
-
- class SWIFTEN_API ClientBlockListManager {
- public:
- ClientBlockListManager(IQRouter *iqRouter);
- ~ClientBlockListManager();
-
- /**
- * Returns the blocklist.
- */
- boost::shared_ptr<BlockList> getBlockList();
-
- /**
- * Get the blocklist from the server.
- */
- boost::shared_ptr<BlockList> requestBlockList();
-
- GenericRequest<BlockPayload>::ref createBlockJIDRequest(const JID& jid);
- GenericRequest<BlockPayload>::ref createBlockJIDsRequest(const std::vector<JID>& jids);
-
- GenericRequest<UnblockPayload>::ref createUnblockJIDRequest(const JID& jid);
- GenericRequest<UnblockPayload>::ref createUnblockJIDsRequest(const std::vector<JID>& jids);
- GenericRequest<UnblockPayload>::ref createUnblockAllRequest();
-
- private:
- void handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref);
-
- private:
- IQRouter* iqRouter;
- boost::shared_ptr<SetResponder<BlockPayload> > blockResponder;
- boost::shared_ptr<SetResponder<UnblockPayload> > unblockResponder;
- boost::shared_ptr<BlockListImpl> blockList;
- };
+ class IQRouter;
+
+ class SWIFTEN_API ClientBlockListManager {
+ public:
+ ClientBlockListManager(IQRouter *iqRouter);
+ ~ClientBlockListManager();
+
+ /**
+ * Returns the blocklist.
+ */
+ boost::shared_ptr<BlockList> getBlockList();
+
+ /**
+ * Get the blocklist from the server.
+ */
+ boost::shared_ptr<BlockList> requestBlockList();
+
+ GenericRequest<BlockPayload>::ref createBlockJIDRequest(const JID& jid);
+ GenericRequest<BlockPayload>::ref createBlockJIDsRequest(const std::vector<JID>& jids);
+
+ GenericRequest<UnblockPayload>::ref createUnblockJIDRequest(const JID& jid);
+ GenericRequest<UnblockPayload>::ref createUnblockJIDsRequest(const std::vector<JID>& jids);
+ GenericRequest<UnblockPayload>::ref createUnblockAllRequest();
+
+ private:
+ void handleBlockListReceived(boost::shared_ptr<BlockListPayload> payload, ErrorPayload::ref);
+
+ private:
+ IQRouter* iqRouter;
+ boost::shared_ptr<SetResponder<BlockPayload> > blockResponder;
+ boost::shared_ptr<SetResponder<UnblockPayload> > unblockResponder;
+ boost::shared_ptr<BlockListImpl> blockList;
+ };
}
diff --git a/Swiften/Client/ClientError.h b/Swiften/Client/ClientError.h
index 19de42b..5ae1086 100644
--- a/Swiften/Client/ClientError.h
+++ b/Swiften/Client/ClientError.h
@@ -10,56 +10,56 @@
#include <boost/system/system_error.hpp>
namespace Swift {
- class ClientError {
- public:
- enum Type {
- UnknownError,
- DomainNameResolveError,
- ConnectionError,
- ConnectionReadError,
- ConnectionWriteError,
- XMLError,
- AuthenticationFailedError,
- CompressionFailedError,
- ServerVerificationFailedError,
- NoSupportedAuthMechanismsError,
- UnexpectedElementError,
- ResourceBindError,
- SessionStartError,
- StreamError,
- TLSError,
- ClientCertificateLoadError,
- ClientCertificateError,
+ class ClientError {
+ public:
+ enum Type {
+ UnknownError,
+ DomainNameResolveError,
+ ConnectionError,
+ ConnectionReadError,
+ ConnectionWriteError,
+ XMLError,
+ AuthenticationFailedError,
+ CompressionFailedError,
+ ServerVerificationFailedError,
+ NoSupportedAuthMechanismsError,
+ UnexpectedElementError,
+ ResourceBindError,
+ SessionStartError,
+ StreamError,
+ TLSError,
+ ClientCertificateLoadError,
+ ClientCertificateError,
- // Certifate on smartcard was removed
- CertificateCardRemoved,
+ // Certifate on smartcard was removed
+ CertificateCardRemoved,
- // Certificate verification errors
- UnknownCertificateError,
- CertificateExpiredError,
- CertificateNotYetValidError,
- CertificateSelfSignedError,
- CertificateRejectedError,
- CertificateUntrustedError,
- InvalidCertificatePurposeError,
- CertificatePathLengthExceededError,
- InvalidCertificateSignatureError,
- InvalidCAError,
- InvalidServerIdentityError,
- RevokedError,
- RevocationCheckFailedError
- };
+ // Certificate verification errors
+ UnknownCertificateError,
+ CertificateExpiredError,
+ CertificateNotYetValidError,
+ CertificateSelfSignedError,
+ CertificateRejectedError,
+ CertificateUntrustedError,
+ InvalidCertificatePurposeError,
+ CertificatePathLengthExceededError,
+ InvalidCertificateSignatureError,
+ InvalidCAError,
+ InvalidServerIdentityError,
+ RevokedError,
+ RevocationCheckFailedError
+ };
- ClientError(Type type = UnknownError) : type_(type) {}
+ ClientError(Type type = UnknownError) : type_(type) {}
- Type getType() const { return type_; }
+ Type getType() const { return type_; }
- void setErrorCode(boost::shared_ptr<boost::system::error_code> errorCode) { errorCode_ = errorCode; }
+ void setErrorCode(boost::shared_ptr<boost::system::error_code> errorCode) { errorCode_ = errorCode; }
- boost::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; }
+ boost::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; }
- private:
- Type type_;
- boost::shared_ptr<boost::system::error_code> errorCode_;
- };
+ private:
+ Type type_;
+ boost::shared_ptr<boost::system::error_code> errorCode_;
+ };
}
diff --git a/Swiften/Client/ClientOptions.h b/Swiften/Client/ClientOptions.h
index bef5833..c902388 100644
--- a/Swiften/Client/ClientOptions.h
+++ b/Swiften/Client/ClientOptions.h
@@ -14,149 +14,149 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class HTTPTrafficFilter;
-
- struct SWIFTEN_API ClientOptions {
- enum UseTLS {
- NeverUseTLS,
- UseTLSWhenAvailable,
- RequireTLS
- };
-
- enum ProxyType {
- NoProxy,
- SystemConfiguredProxy,
- SOCKS5Proxy,
- HTTPConnectProxy
- };
-
- ClientOptions() :
- useStreamCompression(true),
- useTLS(UseTLSWhenAvailable),
- allowPLAINWithoutTLS(false),
- useStreamResumption(false),
- forgetPassword(false),
- useAcks(true),
- singleSignOn(false),
- manualHostname(""),
- manualPort(-1),
- proxyType(SystemConfiguredProxy),
- manualProxyHostname(""),
- manualProxyPort(-1),
- boshHTTPConnectProxyAuthID(""),
- boshHTTPConnectProxyAuthPassword("") {
- }
-
- /**
- * Whether ZLib stream compression should be used when available.
- *
- * Default: true
- */
- bool useStreamCompression;
-
- /**
- * Sets whether TLS encryption should be used.
- *
- * Default: UseTLSWhenAvailable
- */
- UseTLS useTLS;
-
- /**
- * Sets whether plaintext authentication is
- * allowed over non-TLS-encrypted connections.
- *
- * Default: false
- */
- bool allowPLAINWithoutTLS;
-
- /**
- * Use XEP-196 stream resumption when available.
- *
- * Default: false
- */
- bool useStreamResumption;
-
- /**
- * Forget the password once it's used.
- * This makes the Client useless after the first login attempt.
- *
- * FIXME: This is a temporary workaround.
- *
- * Default: false
- */
- bool forgetPassword;
-
- /**
- * Use XEP-0198 acks in the stream when available.
- * Default: true
- */
- bool useAcks;
-
- /**
- * Use Single Sign On.
- * Default: false
- */
- bool singleSignOn;
-
- /**
- * The hostname to connect to.
- * Leave this empty for standard XMPP connection, based on the JID domain.
- */
- std::string manualHostname;
-
- /**
- * The port to connect to.
- * Leave this to -1 to use the port discovered by SRV lookups, and 5222 as a
- * fallback.
- */
- int manualPort;
-
- /**
- * The type of proxy to use for connecting to the XMPP
- * server.
- */
- ProxyType proxyType;
-
- /**
- * Override the system-configured proxy hostname.
- */
- std::string manualProxyHostname;
-
- /**
- * Override the system-configured proxy port.
- */
- int manualProxyPort;
-
- /**
- * If non-empty, use BOSH instead of direct TCP, with the given URL.
- * Default: empty (no BOSH)
- */
- URL boshURL;
-
- /**
- * If non-empty, BOSH connections will try to connect over this HTTP CONNECT
- * proxy instead of directly.
- * Default: empty (no proxy)
- */
- URL boshHTTPConnectProxyURL;
-
- /**
- * If this and matching Password are non-empty, BOSH connections over
- * HTTP CONNECT proxies will use these credentials for proxy access.
- * Default: empty (no authentication needed by the proxy)
- */
- SafeString boshHTTPConnectProxyAuthID;
- SafeString boshHTTPConnectProxyAuthPassword;
-
- /**
- * This can be initialized with a custom HTTPTrafficFilter, which allows HTTP CONNECT
- * proxy initialization to be customized.
- */
- boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter;
-
- /**
- * Options passed to the TLS stack
- */
- TLSOptions tlsOptions;
- };
+ class HTTPTrafficFilter;
+
+ struct SWIFTEN_API ClientOptions {
+ enum UseTLS {
+ NeverUseTLS,
+ UseTLSWhenAvailable,
+ RequireTLS
+ };
+
+ enum ProxyType {
+ NoProxy,
+ SystemConfiguredProxy,
+ SOCKS5Proxy,
+ HTTPConnectProxy
+ };
+
+ ClientOptions() :
+ useStreamCompression(true),
+ useTLS(UseTLSWhenAvailable),
+ allowPLAINWithoutTLS(false),
+ useStreamResumption(false),
+ forgetPassword(false),
+ useAcks(true),
+ singleSignOn(false),
+ manualHostname(""),
+ manualPort(-1),
+ proxyType(SystemConfiguredProxy),
+ manualProxyHostname(""),
+ manualProxyPort(-1),
+ boshHTTPConnectProxyAuthID(""),
+ boshHTTPConnectProxyAuthPassword("") {
+ }
+
+ /**
+ * Whether ZLib stream compression should be used when available.
+ *
+ * Default: true
+ */
+ bool useStreamCompression;
+
+ /**
+ * Sets whether TLS encryption should be used.
+ *
+ * Default: UseTLSWhenAvailable
+ */
+ UseTLS useTLS;
+
+ /**
+ * Sets whether plaintext authentication is
+ * allowed over non-TLS-encrypted connections.
+ *
+ * Default: false
+ */
+ bool allowPLAINWithoutTLS;
+
+ /**
+ * Use XEP-196 stream resumption when available.
+ *
+ * Default: false
+ */
+ bool useStreamResumption;
+
+ /**
+ * Forget the password once it's used.
+ * This makes the Client useless after the first login attempt.
+ *
+ * FIXME: This is a temporary workaround.
+ *
+ * Default: false
+ */
+ bool forgetPassword;
+
+ /**
+ * Use XEP-0198 acks in the stream when available.
+ * Default: true
+ */
+ bool useAcks;
+
+ /**
+ * Use Single Sign On.
+ * Default: false
+ */
+ bool singleSignOn;
+
+ /**
+ * The hostname to connect to.
+ * Leave this empty for standard XMPP connection, based on the JID domain.
+ */
+ std::string manualHostname;
+
+ /**
+ * The port to connect to.
+ * Leave this to -1 to use the port discovered by SRV lookups, and 5222 as a
+ * fallback.
+ */
+ int manualPort;
+
+ /**
+ * The type of proxy to use for connecting to the XMPP
+ * server.
+ */
+ ProxyType proxyType;
+
+ /**
+ * Override the system-configured proxy hostname.
+ */
+ std::string manualProxyHostname;
+
+ /**
+ * Override the system-configured proxy port.
+ */
+ int manualProxyPort;
+
+ /**
+ * If non-empty, use BOSH instead of direct TCP, with the given URL.
+ * Default: empty (no BOSH)
+ */
+ URL boshURL;
+
+ /**
+ * If non-empty, BOSH connections will try to connect over this HTTP CONNECT
+ * proxy instead of directly.
+ * Default: empty (no proxy)
+ */
+ URL boshHTTPConnectProxyURL;
+
+ /**
+ * If this and matching Password are non-empty, BOSH connections over
+ * HTTP CONNECT proxies will use these credentials for proxy access.
+ * Default: empty (no authentication needed by the proxy)
+ */
+ SafeString boshHTTPConnectProxyAuthID;
+ SafeString boshHTTPConnectProxyAuthPassword;
+
+ /**
+ * This can be initialized with a custom HTTPTrafficFilter, which allows HTTP CONNECT
+ * proxy initialization to be customized.
+ */
+ boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter;
+
+ /**
+ * Options passed to the TLS stack
+ */
+ TLSOptions tlsOptions;
+ };
}
diff --git a/Swiften/Client/ClientSession.cpp b/Swiften/Client/ClientSession.cpp
index 52b8cfb..e38dde8 100644
--- a/Swiften/Client/ClientSession.cpp
+++ b/Swiften/Client/ClientSession.cpp
@@ -51,35 +51,35 @@
#endif
#define CHECK_STATE_OR_RETURN(a) \
- if (!checkState(a)) { return; }
+ if (!checkState(a)) { return; }
namespace Swift {
ClientSession::ClientSession(
- const JID& jid,
- boost::shared_ptr<SessionStream> stream,
- IDNConverter* idnConverter,
- CryptoProvider* crypto) :
- localJID(jid),
- state(Initial),
- stream(stream),
- idnConverter(idnConverter),
- crypto(crypto),
- allowPLAINOverNonTLS(false),
- useStreamCompression(true),
- useTLS(UseTLSWhenAvailable),
- useAcks(true),
- needSessionStart(false),
- needResourceBind(false),
- needAcking(false),
- rosterVersioningSupported(false),
- authenticator(NULL),
- certificateTrustChecker(NULL),
- singleSignOn(false),
- authenticationPort(-1) {
+ const JID& jid,
+ boost::shared_ptr<SessionStream> stream,
+ IDNConverter* idnConverter,
+ CryptoProvider* crypto) :
+ localJID(jid),
+ state(Initial),
+ stream(stream),
+ idnConverter(idnConverter),
+ crypto(crypto),
+ allowPLAINOverNonTLS(false),
+ useStreamCompression(true),
+ useTLS(UseTLSWhenAvailable),
+ useAcks(true),
+ needSessionStart(false),
+ needResourceBind(false),
+ needAcking(false),
+ rosterVersioningSupported(false),
+ authenticator(NULL),
+ certificateTrustChecker(NULL),
+ singleSignOn(false),
+ authenticationPort(-1) {
#ifdef SWIFTEN_PLATFORM_WIN32
if (WindowsRegistry::isFIPSEnabled()) {
- SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl;
+ SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl;
}
#endif
}
@@ -88,427 +88,427 @@ ClientSession::~ClientSession() {
}
void ClientSession::start() {
- stream->onStreamStartReceived.connect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1));
- stream->onElementReceived.connect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1));
- stream->onClosed.connect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1));
- stream->onTLSEncrypted.connect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this()));
-
- assert(state == Initial);
- state = WaitingForStreamStart;
- sendStreamHeader();
+ stream->onStreamStartReceived.connect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1));
+ stream->onElementReceived.connect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1));
+ stream->onClosed.connect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1));
+ stream->onTLSEncrypted.connect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this()));
+
+ assert(state == Initial);
+ state = WaitingForStreamStart;
+ sendStreamHeader();
}
void ClientSession::sendStreamHeader() {
- ProtocolHeader header;
- header.setTo(getRemoteJID());
- stream->writeHeader(header);
+ ProtocolHeader header;
+ header.setTo(getRemoteJID());
+ stream->writeHeader(header);
}
void ClientSession::sendStanza(boost::shared_ptr<Stanza> stanza) {
- stream->writeElement(stanza);
- if (stanzaAckRequester_) {
- stanzaAckRequester_->handleStanzaSent(stanza);
- }
+ stream->writeElement(stanza);
+ if (stanzaAckRequester_) {
+ stanzaAckRequester_->handleStanzaSent(stanza);
+ }
}
void ClientSession::handleStreamStart(const ProtocolHeader&) {
- CHECK_STATE_OR_RETURN(WaitingForStreamStart);
- state = Negotiating;
+ CHECK_STATE_OR_RETURN(WaitingForStreamStart);
+ state = Negotiating;
}
void ClientSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) {
- if (stanzaAckResponder_) {
- stanzaAckResponder_->handleStanzaReceived();
- }
- if (getState() == Initialized) {
- onStanzaReceived(stanza);
- }
- else if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(element)) {
- if (state == BindingResource) {
- boost::shared_ptr<ResourceBind> resourceBind(iq->getPayload<ResourceBind>());
- if (iq->getType() == IQ::Error && iq->getID() == "session-bind") {
- finishSession(Error::ResourceBindError);
- }
- else if (!resourceBind) {
- finishSession(Error::UnexpectedElementError);
- }
- else if (iq->getType() == IQ::Result) {
- localJID = resourceBind->getJID();
- if (!localJID.isValid()) {
- finishSession(Error::ResourceBindError);
- }
- needResourceBind = false;
- continueSessionInitialization();
- }
- else {
- finishSession(Error::UnexpectedElementError);
- }
- }
- else if (state == StartingSession) {
- if (iq->getType() == IQ::Result) {
- needSessionStart = false;
- continueSessionInitialization();
- }
- else if (iq->getType() == IQ::Error) {
- finishSession(Error::SessionStartError);
- }
- else {
- finishSession(Error::UnexpectedElementError);
- }
- }
- else {
- finishSession(Error::UnexpectedElementError);
- }
- }
- }
- else if (boost::dynamic_pointer_cast<StanzaAckRequest>(element)) {
- if (stanzaAckResponder_) {
- stanzaAckResponder_->handleAckRequestReceived();
- }
- }
- else if (boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(element)) {
- if (stanzaAckRequester_) {
- if (ack->isValid()) {
- stanzaAckRequester_->handleAckReceived(ack->getHandledStanzasCount());
- }
- else {
- SWIFT_LOG(warning) << "Got invalid ack from server";
- }
- }
- else {
- SWIFT_LOG(warning) << "Ignoring ack";
- }
- }
- else if (StreamError::ref streamError = boost::dynamic_pointer_cast<StreamError>(element)) {
- finishSession(Error::StreamError);
- }
- else if (getState() == Initialized) {
- boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
- if (stanza) {
- if (stanzaAckResponder_) {
- stanzaAckResponder_->handleStanzaReceived();
- }
- onStanzaReceived(stanza);
- }
- }
- else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) {
- CHECK_STATE_OR_RETURN(Negotiating);
-
- if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) {
- state = WaitingForEncrypt;
- stream->writeElement(boost::make_shared<StartTLSRequest>());
- }
- else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) {
- finishSession(Error::NoSupportedAuthMechanismsError);
- }
- else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) {
- state = Compressing;
- stream->writeElement(boost::make_shared<CompressRequest>("zlib"));
- }
- else if (streamFeatures->hasAuthenticationMechanisms()) {
+ if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) {
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleStanzaReceived();
+ }
+ if (getState() == Initialized) {
+ onStanzaReceived(stanza);
+ }
+ else if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(element)) {
+ if (state == BindingResource) {
+ boost::shared_ptr<ResourceBind> resourceBind(iq->getPayload<ResourceBind>());
+ if (iq->getType() == IQ::Error && iq->getID() == "session-bind") {
+ finishSession(Error::ResourceBindError);
+ }
+ else if (!resourceBind) {
+ finishSession(Error::UnexpectedElementError);
+ }
+ else if (iq->getType() == IQ::Result) {
+ localJID = resourceBind->getJID();
+ if (!localJID.isValid()) {
+ finishSession(Error::ResourceBindError);
+ }
+ needResourceBind = false;
+ continueSessionInitialization();
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
+ }
+ else if (state == StartingSession) {
+ if (iq->getType() == IQ::Result) {
+ needSessionStart = false;
+ continueSessionInitialization();
+ }
+ else if (iq->getType() == IQ::Error) {
+ finishSession(Error::SessionStartError);
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
+ }
+ }
+ else if (boost::dynamic_pointer_cast<StanzaAckRequest>(element)) {
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleAckRequestReceived();
+ }
+ }
+ else if (boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(element)) {
+ if (stanzaAckRequester_) {
+ if (ack->isValid()) {
+ stanzaAckRequester_->handleAckReceived(ack->getHandledStanzasCount());
+ }
+ else {
+ SWIFT_LOG(warning) << "Got invalid ack from server";
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "Ignoring ack";
+ }
+ }
+ else if (StreamError::ref streamError = boost::dynamic_pointer_cast<StreamError>(element)) {
+ finishSession(Error::StreamError);
+ }
+ else if (getState() == Initialized) {
+ boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
+ if (stanza) {
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleStanzaReceived();
+ }
+ onStanzaReceived(stanza);
+ }
+ }
+ else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) {
+ CHECK_STATE_OR_RETURN(Negotiating);
+
+ if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) {
+ state = WaitingForEncrypt;
+ stream->writeElement(boost::make_shared<StartTLSRequest>());
+ }
+ else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) {
+ finishSession(Error::NoSupportedAuthMechanismsError);
+ }
+ else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) {
+ state = Compressing;
+ stream->writeElement(boost::make_shared<CompressRequest>("zlib"));
+ }
+ else if (streamFeatures->hasAuthenticationMechanisms()) {
#ifdef SWIFTEN_PLATFORM_WIN32
- if (singleSignOn) {
- const boost::optional<std::string> authenticationHostname = streamFeatures->getAuthenticationHostname();
- bool gssapiSupported = streamFeatures->hasAuthenticationMechanism("GSSAPI") && authenticationHostname && !authenticationHostname->empty();
-
- if (!gssapiSupported) {
- finishSession(Error::NoSupportedAuthMechanismsError);
- }
- else {
- WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = new WindowsGSSAPIClientAuthenticator(*authenticationHostname, localJID.getDomain(), authenticationPort);
- boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError);
-
- authenticator = gssapiAuthenticator;
-
- if (!gssapiAuthenticator->isError()) {
- state = Authenticating;
- stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse()));
- }
- else {
- error->errorCode = gssapiAuthenticator->getErrorCode();
- finishSession(error);
- }
- }
- }
- else
+ if (singleSignOn) {
+ const boost::optional<std::string> authenticationHostname = streamFeatures->getAuthenticationHostname();
+ bool gssapiSupported = streamFeatures->hasAuthenticationMechanism("GSSAPI") && authenticationHostname && !authenticationHostname->empty();
+
+ if (!gssapiSupported) {
+ finishSession(Error::NoSupportedAuthMechanismsError);
+ }
+ else {
+ WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = new WindowsGSSAPIClientAuthenticator(*authenticationHostname, localJID.getDomain(), authenticationPort);
+ boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError);
+
+ authenticator = gssapiAuthenticator;
+
+ if (!gssapiAuthenticator->isError()) {
+ state = Authenticating;
+ stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse()));
+ }
+ else {
+ error->errorCode = gssapiAuthenticator->getErrorCode();
+ finishSession(error);
+ }
+ }
+ }
+ else
#endif
- if (stream->hasTLSCertificate()) {
- if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) {
- authenticator = new EXTERNALClientAuthenticator();
- state = Authenticating;
- stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray("")));
- }
- else {
- finishSession(Error::TLSClientCertificateError);
- }
- }
- else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) {
- authenticator = new EXTERNALClientAuthenticator();
- state = Authenticating;
- stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray("")));
- }
- else if (streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1") || streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS")) {
- std::ostringstream s;
- ByteArray finishMessage;
- bool plus = streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS");
- if (stream->isTLSEncrypted()) {
- finishMessage = stream->getTLSFinishMessage();
- plus &= !finishMessage.empty();
- }
- s << boost::uuids::random_generator()();
- SCRAMSHA1ClientAuthenticator* scramAuthenticator = new SCRAMSHA1ClientAuthenticator(s.str(), plus, idnConverter, crypto);
- if (!finishMessage.empty()) {
- scramAuthenticator->setTLSChannelBindingData(finishMessage);
- }
- authenticator = scramAuthenticator;
- state = WaitingForCredentials;
- onNeedCredentials();
- }
- else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) {
- authenticator = new PLAINClientAuthenticator();
- state = WaitingForCredentials;
- onNeedCredentials();
- }
- else if (streamFeatures->hasAuthenticationMechanism("DIGEST-MD5") && crypto->isMD5AllowedForCrypto()) {
- std::ostringstream s;
- s << boost::uuids::random_generator()();
- // FIXME: Host should probably be the actual host
- authenticator = new DIGESTMD5ClientAuthenticator(localJID.getDomain(), s.str(), crypto);
- state = WaitingForCredentials;
- onNeedCredentials();
- }
- else {
- finishSession(Error::NoSupportedAuthMechanismsError);
- }
- }
- else {
- // Start the session
- rosterVersioningSupported = streamFeatures->hasRosterVersioning();
- stream->setWhitespacePingEnabled(true);
- needSessionStart = streamFeatures->hasSession();
- needResourceBind = streamFeatures->hasResourceBind();
- needAcking = streamFeatures->hasStreamManagement() && useAcks;
- if (!needResourceBind) {
- // Resource binding is a MUST
- finishSession(Error::ResourceBindError);
- }
- else {
- continueSessionInitialization();
- }
- }
- }
- else if (boost::dynamic_pointer_cast<Compressed>(element)) {
- CHECK_STATE_OR_RETURN(Compressing);
- state = WaitingForStreamStart;
- stream->addZLibCompression();
- stream->resetXMPPParser();
- sendStreamHeader();
- }
- else if (boost::dynamic_pointer_cast<CompressFailure>(element)) {
- finishSession(Error::CompressionFailedError);
- }
- else if (boost::dynamic_pointer_cast<StreamManagementEnabled>(element)) {
- stanzaAckRequester_ = boost::make_shared<StanzaAckRequester>();
- stanzaAckRequester_->onRequestAck.connect(boost::bind(&ClientSession::requestAck, shared_from_this()));
- stanzaAckRequester_->onStanzaAcked.connect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1));
- stanzaAckResponder_ = boost::make_shared<StanzaAckResponder>();
- stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1));
- needAcking = false;
- continueSessionInitialization();
- }
- else if (boost::dynamic_pointer_cast<StreamManagementFailed>(element)) {
- needAcking = false;
- continueSessionInitialization();
- }
- else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) {
- CHECK_STATE_OR_RETURN(Authenticating);
- assert(authenticator);
- if (authenticator->setChallenge(challenge->getValue())) {
- stream->writeElement(boost::make_shared<AuthResponse>(authenticator->getResponse()));
- }
+ if (stream->hasTLSCertificate()) {
+ if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) {
+ authenticator = new EXTERNALClientAuthenticator();
+ state = Authenticating;
+ stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray("")));
+ }
+ else {
+ finishSession(Error::TLSClientCertificateError);
+ }
+ }
+ else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) {
+ authenticator = new EXTERNALClientAuthenticator();
+ state = Authenticating;
+ stream->writeElement(boost::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray("")));
+ }
+ else if (streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1") || streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS")) {
+ std::ostringstream s;
+ ByteArray finishMessage;
+ bool plus = streamFeatures->hasAuthenticationMechanism("SCRAM-SHA-1-PLUS");
+ if (stream->isTLSEncrypted()) {
+ finishMessage = stream->getTLSFinishMessage();
+ plus &= !finishMessage.empty();
+ }
+ s << boost::uuids::random_generator()();
+ SCRAMSHA1ClientAuthenticator* scramAuthenticator = new SCRAMSHA1ClientAuthenticator(s.str(), plus, idnConverter, crypto);
+ if (!finishMessage.empty()) {
+ scramAuthenticator->setTLSChannelBindingData(finishMessage);
+ }
+ authenticator = scramAuthenticator;
+ state = WaitingForCredentials;
+ onNeedCredentials();
+ }
+ else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) {
+ authenticator = new PLAINClientAuthenticator();
+ state = WaitingForCredentials;
+ onNeedCredentials();
+ }
+ else if (streamFeatures->hasAuthenticationMechanism("DIGEST-MD5") && crypto->isMD5AllowedForCrypto()) {
+ std::ostringstream s;
+ s << boost::uuids::random_generator()();
+ // FIXME: Host should probably be the actual host
+ authenticator = new DIGESTMD5ClientAuthenticator(localJID.getDomain(), s.str(), crypto);
+ state = WaitingForCredentials;
+ onNeedCredentials();
+ }
+ else {
+ finishSession(Error::NoSupportedAuthMechanismsError);
+ }
+ }
+ else {
+ // Start the session
+ rosterVersioningSupported = streamFeatures->hasRosterVersioning();
+ stream->setWhitespacePingEnabled(true);
+ needSessionStart = streamFeatures->hasSession();
+ needResourceBind = streamFeatures->hasResourceBind();
+ needAcking = streamFeatures->hasStreamManagement() && useAcks;
+ if (!needResourceBind) {
+ // Resource binding is a MUST
+ finishSession(Error::ResourceBindError);
+ }
+ else {
+ continueSessionInitialization();
+ }
+ }
+ }
+ else if (boost::dynamic_pointer_cast<Compressed>(element)) {
+ CHECK_STATE_OR_RETURN(Compressing);
+ state = WaitingForStreamStart;
+ stream->addZLibCompression();
+ stream->resetXMPPParser();
+ sendStreamHeader();
+ }
+ else if (boost::dynamic_pointer_cast<CompressFailure>(element)) {
+ finishSession(Error::CompressionFailedError);
+ }
+ else if (boost::dynamic_pointer_cast<StreamManagementEnabled>(element)) {
+ stanzaAckRequester_ = boost::make_shared<StanzaAckRequester>();
+ stanzaAckRequester_->onRequestAck.connect(boost::bind(&ClientSession::requestAck, shared_from_this()));
+ stanzaAckRequester_->onStanzaAcked.connect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1));
+ stanzaAckResponder_ = boost::make_shared<StanzaAckResponder>();
+ stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1));
+ needAcking = false;
+ continueSessionInitialization();
+ }
+ else if (boost::dynamic_pointer_cast<StreamManagementFailed>(element)) {
+ needAcking = false;
+ continueSessionInitialization();
+ }
+ else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) {
+ CHECK_STATE_OR_RETURN(Authenticating);
+ assert(authenticator);
+ if (authenticator->setChallenge(challenge->getValue())) {
+ stream->writeElement(boost::make_shared<AuthResponse>(authenticator->getResponse()));
+ }
#ifdef SWIFTEN_PLATFORM_WIN32
- else if (WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = dynamic_cast<WindowsGSSAPIClientAuthenticator*>(authenticator)) {
- boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError);
+ else if (WindowsGSSAPIClientAuthenticator* gssapiAuthenticator = dynamic_cast<WindowsGSSAPIClientAuthenticator*>(authenticator)) {
+ boost::shared_ptr<Error> error = boost::make_shared<Error>(Error::AuthenticationFailedError);
- error->errorCode = gssapiAuthenticator->getErrorCode();
- finishSession(error);
- }
+ error->errorCode = gssapiAuthenticator->getErrorCode();
+ finishSession(error);
+ }
#endif
- else {
- finishSession(Error::AuthenticationFailedError);
- }
- }
- else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) {
- CHECK_STATE_OR_RETURN(Authenticating);
- assert(authenticator);
- if (!authenticator->setChallenge(authSuccess->getValue())) {
- finishSession(Error::ServerVerificationFailedError);
- }
- else {
- state = WaitingForStreamStart;
- delete authenticator;
- authenticator = NULL;
- stream->resetXMPPParser();
- sendStreamHeader();
- }
- }
- else if (dynamic_cast<AuthFailure*>(element.get())) {
- finishSession(Error::AuthenticationFailedError);
- }
- else if (dynamic_cast<TLSProceed*>(element.get())) {
- CHECK_STATE_OR_RETURN(WaitingForEncrypt);
- state = Encrypting;
- stream->addTLSEncryption();
- }
- else if (dynamic_cast<StartTLSFailure*>(element.get())) {
- finishSession(Error::TLSError);
- }
- else {
- // FIXME Not correct?
- state = Initialized;
- onInitialized();
- }
+ else {
+ finishSession(Error::AuthenticationFailedError);
+ }
+ }
+ else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) {
+ CHECK_STATE_OR_RETURN(Authenticating);
+ assert(authenticator);
+ if (!authenticator->setChallenge(authSuccess->getValue())) {
+ finishSession(Error::ServerVerificationFailedError);
+ }
+ else {
+ state = WaitingForStreamStart;
+ delete authenticator;
+ authenticator = NULL;
+ stream->resetXMPPParser();
+ sendStreamHeader();
+ }
+ }
+ else if (dynamic_cast<AuthFailure*>(element.get())) {
+ finishSession(Error::AuthenticationFailedError);
+ }
+ else if (dynamic_cast<TLSProceed*>(element.get())) {
+ CHECK_STATE_OR_RETURN(WaitingForEncrypt);
+ state = Encrypting;
+ stream->addTLSEncryption();
+ }
+ else if (dynamic_cast<StartTLSFailure*>(element.get())) {
+ finishSession(Error::TLSError);
+ }
+ else {
+ // FIXME Not correct?
+ state = Initialized;
+ onInitialized();
+ }
}
void ClientSession::continueSessionInitialization() {
- if (needResourceBind) {
- state = BindingResource;
- boost::shared_ptr<ResourceBind> resourceBind(boost::make_shared<ResourceBind>());
- if (!localJID.getResource().empty()) {
- resourceBind->setResource(localJID.getResource());
- }
- sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind));
- }
- else if (needAcking) {
- state = EnablingSessionManagement;
- stream->writeElement(boost::make_shared<EnableStreamManagement>());
- }
- else if (needSessionStart) {
- state = StartingSession;
- sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", boost::make_shared<StartSession>()));
- }
- else {
- state = Initialized;
- onInitialized();
- }
+ if (needResourceBind) {
+ state = BindingResource;
+ boost::shared_ptr<ResourceBind> resourceBind(boost::make_shared<ResourceBind>());
+ if (!localJID.getResource().empty()) {
+ resourceBind->setResource(localJID.getResource());
+ }
+ sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind));
+ }
+ else if (needAcking) {
+ state = EnablingSessionManagement;
+ stream->writeElement(boost::make_shared<EnableStreamManagement>());
+ }
+ else if (needSessionStart) {
+ state = StartingSession;
+ sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", boost::make_shared<StartSession>()));
+ }
+ else {
+ state = Initialized;
+ onInitialized();
+ }
}
bool ClientSession::checkState(State state) {
- if (this->state != state) {
- finishSession(Error::UnexpectedElementError);
- return false;
- }
- return true;
+ if (this->state != state) {
+ finishSession(Error::UnexpectedElementError);
+ return false;
+ }
+ return true;
}
void ClientSession::sendCredentials(const SafeByteArray& password) {
- assert(WaitingForCredentials);
- assert(authenticator);
- state = Authenticating;
- authenticator->setCredentials(localJID.getNode(), password);
- stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse()));
+ assert(WaitingForCredentials);
+ assert(authenticator);
+ state = Authenticating;
+ authenticator->setCredentials(localJID.getNode(), password);
+ stream->writeElement(boost::make_shared<AuthRequest>(authenticator->getName(), authenticator->getResponse()));
}
void ClientSession::handleTLSEncrypted() {
- CHECK_STATE_OR_RETURN(Encrypting);
-
- std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain();
- boost::shared_ptr<CertificateVerificationError> verificationError = stream->getPeerCertificateVerificationError();
- if (verificationError) {
- checkTrustOrFinish(certificateChain, verificationError);
- }
- else {
- ServerIdentityVerifier identityVerifier(localJID, idnConverter);
- if (!certificateChain.empty() && identityVerifier.certificateVerifies(certificateChain[0])) {
- continueAfterTLSEncrypted();
- }
- else {
- checkTrustOrFinish(certificateChain, boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity));
- }
- }
+ CHECK_STATE_OR_RETURN(Encrypting);
+
+ std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain();
+ boost::shared_ptr<CertificateVerificationError> verificationError = stream->getPeerCertificateVerificationError();
+ if (verificationError) {
+ checkTrustOrFinish(certificateChain, verificationError);
+ }
+ else {
+ ServerIdentityVerifier identityVerifier(localJID, idnConverter);
+ if (!certificateChain.empty() && identityVerifier.certificateVerifies(certificateChain[0])) {
+ continueAfterTLSEncrypted();
+ }
+ else {
+ checkTrustOrFinish(certificateChain, boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity));
+ }
+ }
}
void ClientSession::checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error) {
- if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) {
- continueAfterTLSEncrypted();
- }
- else {
- finishSession(error);
- }
+ if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) {
+ continueAfterTLSEncrypted();
+ }
+ else {
+ finishSession(error);
+ }
}
void ClientSession::continueAfterTLSEncrypted() {
- state = WaitingForStreamStart;
- stream->resetXMPPParser();
- sendStreamHeader();
+ state = WaitingForStreamStart;
+ stream->resetXMPPParser();
+ sendStreamHeader();
}
void ClientSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) {
- State previousState = state;
- state = Finished;
-
- if (stanzaAckRequester_) {
- stanzaAckRequester_->onRequestAck.disconnect(boost::bind(&ClientSession::requestAck, shared_from_this()));
- stanzaAckRequester_->onStanzaAcked.disconnect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1));
- stanzaAckRequester_.reset();
- }
- if (stanzaAckResponder_) {
- stanzaAckResponder_->onAck.disconnect(boost::bind(&ClientSession::ack, shared_from_this(), _1));
- stanzaAckResponder_.reset();
- }
- stream->setWhitespacePingEnabled(false);
- stream->onStreamStartReceived.disconnect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1));
- stream->onElementReceived.disconnect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1));
- stream->onClosed.disconnect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1));
- stream->onTLSEncrypted.disconnect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this()));
-
- if (previousState == Finishing) {
- onFinished(error_);
- }
- else {
- onFinished(streamError);
- }
+ State previousState = state;
+ state = Finished;
+
+ if (stanzaAckRequester_) {
+ stanzaAckRequester_->onRequestAck.disconnect(boost::bind(&ClientSession::requestAck, shared_from_this()));
+ stanzaAckRequester_->onStanzaAcked.disconnect(boost::bind(&ClientSession::handleStanzaAcked, shared_from_this(), _1));
+ stanzaAckRequester_.reset();
+ }
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->onAck.disconnect(boost::bind(&ClientSession::ack, shared_from_this(), _1));
+ stanzaAckResponder_.reset();
+ }
+ stream->setWhitespacePingEnabled(false);
+ stream->onStreamStartReceived.disconnect(boost::bind(&ClientSession::handleStreamStart, shared_from_this(), _1));
+ stream->onElementReceived.disconnect(boost::bind(&ClientSession::handleElement, shared_from_this(), _1));
+ stream->onClosed.disconnect(boost::bind(&ClientSession::handleStreamClosed, shared_from_this(), _1));
+ stream->onTLSEncrypted.disconnect(boost::bind(&ClientSession::handleTLSEncrypted, shared_from_this()));
+
+ if (previousState == Finishing) {
+ onFinished(error_);
+ }
+ else {
+ onFinished(streamError);
+ }
}
void ClientSession::finish() {
- finishSession(boost::shared_ptr<Error>());
+ finishSession(boost::shared_ptr<Error>());
}
void ClientSession::finishSession(Error::Type error) {
- finishSession(boost::make_shared<Swift::ClientSession::Error>(error));
+ finishSession(boost::make_shared<Swift::ClientSession::Error>(error));
}
void ClientSession::finishSession(boost::shared_ptr<Swift::Error> error) {
- state = Finishing;
- if (!error_) {
- error_ = error;
- }
- else {
- SWIFT_LOG(warning) << "Session finished twice";
- }
- assert(stream->isOpen());
- if (stanzaAckResponder_) {
- stanzaAckResponder_->handleAckRequestReceived();
- }
- if (authenticator) {
- delete authenticator;
- authenticator = NULL;
- }
- stream->writeFooter();
- stream->close();
+ state = Finishing;
+ if (!error_) {
+ error_ = error;
+ }
+ else {
+ SWIFT_LOG(warning) << "Session finished twice";
+ }
+ assert(stream->isOpen());
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleAckRequestReceived();
+ }
+ if (authenticator) {
+ delete authenticator;
+ authenticator = NULL;
+ }
+ stream->writeFooter();
+ stream->close();
}
void ClientSession::requestAck() {
- stream->writeElement(boost::make_shared<StanzaAckRequest>());
+ stream->writeElement(boost::make_shared<StanzaAckRequest>());
}
void ClientSession::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
- onStanzaAcked(stanza);
+ onStanzaAcked(stanza);
}
void ClientSession::ack(unsigned int handledStanzasCount) {
- stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount));
+ stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount));
}
}
diff --git a/Swiften/Client/ClientSession.h b/Swiften/Client/ClientSession.h
index a125c71..b1b6755 100644
--- a/Swiften/Client/ClientSession.h
+++ b/Swiften/Client/ClientSession.h
@@ -21,182 +21,182 @@
#include <Swiften/StreamManagement/StanzaAckResponder.h>
namespace Swift {
- class ClientAuthenticator;
- class CertificateTrustChecker;
- class IDNConverter;
- class CryptoProvider;
-
- class SWIFTEN_API ClientSession : public boost::enable_shared_from_this<ClientSession> {
- public:
- enum State {
- Initial,
- WaitingForStreamStart,
- Negotiating,
- Compressing,
- WaitingForEncrypt,
- Encrypting,
- WaitingForCredentials,
- Authenticating,
- EnablingSessionManagement,
- BindingResource,
- StartingSession,
- Initialized,
- Finishing,
- Finished
- };
-
- struct Error : public Swift::Error {
- enum Type {
- AuthenticationFailedError,
- CompressionFailedError,
- ServerVerificationFailedError,
- NoSupportedAuthMechanismsError,
- UnexpectedElementError,
- ResourceBindError,
- SessionStartError,
- TLSClientCertificateError,
- TLSError,
- StreamError
- } type;
- boost::shared_ptr<boost::system::error_code> errorCode;
- Error(Type type) : type(type) {}
- };
-
- enum UseTLS {
- NeverUseTLS,
- UseTLSWhenAvailable,
- RequireTLS
- };
-
- ~ClientSession();
-
- static boost::shared_ptr<ClientSession> create(const JID& jid, boost::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto) {
- return boost::shared_ptr<ClientSession>(new ClientSession(jid, stream, idnConverter, crypto));
- }
-
- State getState() const {
- return state;
- }
-
- void setAllowPLAINOverNonTLS(bool b) {
- allowPLAINOverNonTLS = b;
- }
-
- void setUseStreamCompression(bool b) {
- useStreamCompression = b;
- }
-
- void setUseTLS(UseTLS b) {
- useTLS = b;
- }
-
- void setUseAcks(bool b) {
- useAcks = b;
- }
-
-
- bool getStreamManagementEnabled() const {
- // Explicitly convert to bool. In C++11, it would be cleaner to
- // compare to nullptr.
- return static_cast<bool>(stanzaAckRequester_);
- }
-
- bool getRosterVersioningSupported() const {
- return rosterVersioningSupported;
- }
-
- std::vector<Certificate::ref> getPeerCertificateChain() const {
- return stream->getPeerCertificateChain();
- }
-
- const JID& getLocalJID() const {
- return localJID;
- }
-
- void start();
- void finish();
-
- bool isFinished() const {
- return getState() == Finished;
- }
-
- void sendCredentials(const SafeByteArray& password);
- void sendStanza(boost::shared_ptr<Stanza>);
-
- void setCertificateTrustChecker(CertificateTrustChecker* checker) {
- certificateTrustChecker = checker;
- }
-
- void setSingleSignOn(bool b) {
- singleSignOn = b;
- }
-
- /**
- * Sets the port number used in Kerberos authentication
- * Does not affect network connectivity.
- */
- void setAuthenticationPort(int i) {
- authenticationPort = i;
- }
-
- public:
- boost::signal<void ()> onNeedCredentials;
- boost::signal<void ()> onInitialized;
- boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished;
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived;
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
-
- private:
- ClientSession(
- const JID& jid,
- boost::shared_ptr<SessionStream>,
- IDNConverter* idnConverter,
- CryptoProvider* crypto);
-
- void finishSession(Error::Type error);
- void finishSession(boost::shared_ptr<Swift::Error> error);
-
- JID getRemoteJID() const {
- return JID("", localJID.getDomain());
- }
-
- void sendStreamHeader();
-
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamStart(const ProtocolHeader&);
- void handleStreamClosed(boost::shared_ptr<Swift::Error>);
-
- void handleTLSEncrypted();
-
- bool checkState(State);
- void continueSessionInitialization();
-
- void requestAck();
- void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
- void ack(unsigned int handledStanzasCount);
- void continueAfterTLSEncrypted();
- void checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error);
-
- private:
- JID localJID;
- State state;
- boost::shared_ptr<SessionStream> stream;
- IDNConverter* idnConverter;
- CryptoProvider* crypto;
- bool allowPLAINOverNonTLS;
- bool useStreamCompression;
- UseTLS useTLS;
- bool useAcks;
- bool needSessionStart;
- bool needResourceBind;
- bool needAcking;
- bool rosterVersioningSupported;
- ClientAuthenticator* authenticator;
- boost::shared_ptr<StanzaAckRequester> stanzaAckRequester_;
- boost::shared_ptr<StanzaAckResponder> stanzaAckResponder_;
- boost::shared_ptr<Swift::Error> error_;
- CertificateTrustChecker* certificateTrustChecker;
- bool singleSignOn;
- int authenticationPort;
- };
+ class ClientAuthenticator;
+ class CertificateTrustChecker;
+ class IDNConverter;
+ class CryptoProvider;
+
+ class SWIFTEN_API ClientSession : public boost::enable_shared_from_this<ClientSession> {
+ public:
+ enum State {
+ Initial,
+ WaitingForStreamStart,
+ Negotiating,
+ Compressing,
+ WaitingForEncrypt,
+ Encrypting,
+ WaitingForCredentials,
+ Authenticating,
+ EnablingSessionManagement,
+ BindingResource,
+ StartingSession,
+ Initialized,
+ Finishing,
+ Finished
+ };
+
+ struct Error : public Swift::Error {
+ enum Type {
+ AuthenticationFailedError,
+ CompressionFailedError,
+ ServerVerificationFailedError,
+ NoSupportedAuthMechanismsError,
+ UnexpectedElementError,
+ ResourceBindError,
+ SessionStartError,
+ TLSClientCertificateError,
+ TLSError,
+ StreamError
+ } type;
+ boost::shared_ptr<boost::system::error_code> errorCode;
+ Error(Type type) : type(type) {}
+ };
+
+ enum UseTLS {
+ NeverUseTLS,
+ UseTLSWhenAvailable,
+ RequireTLS
+ };
+
+ ~ClientSession();
+
+ static boost::shared_ptr<ClientSession> create(const JID& jid, boost::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto) {
+ return boost::shared_ptr<ClientSession>(new ClientSession(jid, stream, idnConverter, crypto));
+ }
+
+ State getState() const {
+ return state;
+ }
+
+ void setAllowPLAINOverNonTLS(bool b) {
+ allowPLAINOverNonTLS = b;
+ }
+
+ void setUseStreamCompression(bool b) {
+ useStreamCompression = b;
+ }
+
+ void setUseTLS(UseTLS b) {
+ useTLS = b;
+ }
+
+ void setUseAcks(bool b) {
+ useAcks = b;
+ }
+
+
+ bool getStreamManagementEnabled() const {
+ // Explicitly convert to bool. In C++11, it would be cleaner to
+ // compare to nullptr.
+ return static_cast<bool>(stanzaAckRequester_);
+ }
+
+ bool getRosterVersioningSupported() const {
+ return rosterVersioningSupported;
+ }
+
+ std::vector<Certificate::ref> getPeerCertificateChain() const {
+ return stream->getPeerCertificateChain();
+ }
+
+ const JID& getLocalJID() const {
+ return localJID;
+ }
+
+ void start();
+ void finish();
+
+ bool isFinished() const {
+ return getState() == Finished;
+ }
+
+ void sendCredentials(const SafeByteArray& password);
+ void sendStanza(boost::shared_ptr<Stanza>);
+
+ void setCertificateTrustChecker(CertificateTrustChecker* checker) {
+ certificateTrustChecker = checker;
+ }
+
+ void setSingleSignOn(bool b) {
+ singleSignOn = b;
+ }
+
+ /**
+ * Sets the port number used in Kerberos authentication
+ * Does not affect network connectivity.
+ */
+ void setAuthenticationPort(int i) {
+ authenticationPort = i;
+ }
+
+ public:
+ boost::signal<void ()> onNeedCredentials;
+ boost::signal<void ()> onInitialized;
+ boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished;
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived;
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
+
+ private:
+ ClientSession(
+ const JID& jid,
+ boost::shared_ptr<SessionStream>,
+ IDNConverter* idnConverter,
+ CryptoProvider* crypto);
+
+ void finishSession(Error::Type error);
+ void finishSession(boost::shared_ptr<Swift::Error> error);
+
+ JID getRemoteJID() const {
+ return JID("", localJID.getDomain());
+ }
+
+ void sendStreamHeader();
+
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+ void handleStreamClosed(boost::shared_ptr<Swift::Error>);
+
+ void handleTLSEncrypted();
+
+ bool checkState(State);
+ void continueSessionInitialization();
+
+ void requestAck();
+ void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
+ void ack(unsigned int handledStanzasCount);
+ void continueAfterTLSEncrypted();
+ void checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error);
+
+ private:
+ JID localJID;
+ State state;
+ boost::shared_ptr<SessionStream> stream;
+ IDNConverter* idnConverter;
+ CryptoProvider* crypto;
+ bool allowPLAINOverNonTLS;
+ bool useStreamCompression;
+ UseTLS useTLS;
+ bool useAcks;
+ bool needSessionStart;
+ bool needResourceBind;
+ bool needAcking;
+ bool rosterVersioningSupported;
+ ClientAuthenticator* authenticator;
+ boost::shared_ptr<StanzaAckRequester> stanzaAckRequester_;
+ boost::shared_ptr<StanzaAckResponder> stanzaAckResponder_;
+ boost::shared_ptr<Swift::Error> error_;
+ CertificateTrustChecker* certificateTrustChecker;
+ bool singleSignOn;
+ int authenticationPort;
+ };
}
diff --git a/Swiften/Client/ClientSessionStanzaChannel.cpp b/Swiften/Client/ClientSessionStanzaChannel.cpp
index 3dc8c59..1340b7c 100644
--- a/Swiften/Client/ClientSessionStanzaChannel.cpp
+++ b/Swiften/Client/ClientSessionStanzaChannel.cpp
@@ -13,100 +13,100 @@
namespace Swift {
ClientSessionStanzaChannel::~ClientSessionStanzaChannel() {
- if (session) {
- session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
- session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
- session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
- session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
- session.reset();
- }
+ if (session) {
+ session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
+ session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
+ session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
+ session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
+ session.reset();
+ }
}
void ClientSessionStanzaChannel::setSession(boost::shared_ptr<ClientSession> session) {
- assert(!this->session);
- this->session = session;
- session->onInitialized.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
- session->onFinished.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
- session->onStanzaReceived.connect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
- session->onStanzaAcked.connect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
+ assert(!this->session);
+ this->session = session;
+ session->onInitialized.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
+ session->onFinished.connect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
+ session->onStanzaReceived.connect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
+ session->onStanzaAcked.connect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
}
void ClientSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) {
- send(iq);
+ send(iq);
}
void ClientSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) {
- send(message);
+ send(message);
}
void ClientSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) {
- send(presence);
+ send(presence);
}
std::string ClientSessionStanzaChannel::getNewIQID() {
- return idGenerator.generateID();
+ return idGenerator.generateID();
}
void ClientSessionStanzaChannel::send(boost::shared_ptr<Stanza> stanza) {
- if (!isAvailable()) {
- std::cerr << "Warning: Client: Trying to send a stanza while disconnected." << std::endl;
- return;
- }
- session->sendStanza(stanza);
+ if (!isAvailable()) {
+ std::cerr << "Warning: Client: Trying to send a stanza while disconnected." << std::endl;
+ return;
+ }
+ session->sendStanza(stanza);
}
void ClientSessionStanzaChannel::handleSessionFinished(boost::shared_ptr<Error>) {
- session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
- session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
- session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
- session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
- session.reset();
+ session->onFinished.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionFinished, this, _1));
+ session->onStanzaReceived.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanza, this, _1));
+ session->onStanzaAcked.disconnect(boost::bind(&ClientSessionStanzaChannel::handleStanzaAcked, this, _1));
+ session->onInitialized.disconnect(boost::bind(&ClientSessionStanzaChannel::handleSessionInitialized, this));
+ session.reset();
- onAvailableChanged(false);
+ onAvailableChanged(false);
}
void ClientSessionStanzaChannel::handleStanza(boost::shared_ptr<Stanza> stanza) {
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza);
- if (message) {
- onMessageReceived(message);
- return;
- }
-
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza);
- if (presence) {
- onPresenceReceived(presence);
- return;
- }
-
- boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza);
- if (iq) {
- onIQReceived(iq);
- return;
- }
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza);
+ if (message) {
+ onMessageReceived(message);
+ return;
+ }
+
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza);
+ if (presence) {
+ onPresenceReceived(presence);
+ return;
+ }
+
+ boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza);
+ if (iq) {
+ onIQReceived(iq);
+ return;
+ }
}
bool ClientSessionStanzaChannel::getStreamManagementEnabled() const {
- if (session) {
- return session->getStreamManagementEnabled();
- }
- return false;
+ if (session) {
+ return session->getStreamManagementEnabled();
+ }
+ return false;
}
std::vector<Certificate::ref> ClientSessionStanzaChannel::getPeerCertificateChain() const {
- if (session) {
- return session->getPeerCertificateChain();
- }
- return std::vector<Certificate::ref>();
+ if (session) {
+ return session->getPeerCertificateChain();
+ }
+ return std::vector<Certificate::ref>();
}
void ClientSessionStanzaChannel::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
- onStanzaAcked(stanza);
+ onStanzaAcked(stanza);
}
void ClientSessionStanzaChannel::handleSessionInitialized() {
- onAvailableChanged(true);
+ onAvailableChanged(true);
}
}
diff --git a/Swiften/Client/ClientSessionStanzaChannel.h b/Swiften/Client/ClientSessionStanzaChannel.h
index 0ffcd9d..d3b302b 100644
--- a/Swiften/Client/ClientSessionStanzaChannel.h
+++ b/Swiften/Client/ClientSessionStanzaChannel.h
@@ -17,36 +17,36 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- /**
- * StanzaChannel implementation around a ClientSession.
- */
- class SWIFTEN_API ClientSessionStanzaChannel : public StanzaChannel {
- public:
- virtual ~ClientSessionStanzaChannel();
-
- void setSession(boost::shared_ptr<ClientSession> session);
-
- void sendIQ(boost::shared_ptr<IQ> iq);
- void sendMessage(boost::shared_ptr<Message> message);
- void sendPresence(boost::shared_ptr<Presence> presence);
- bool getStreamManagementEnabled() const;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
-
- bool isAvailable() const {
- return session && session->getState() == ClientSession::Initialized;
- }
-
- private:
- std::string getNewIQID();
- void send(boost::shared_ptr<Stanza> stanza);
- void handleSessionFinished(boost::shared_ptr<Error> error);
- void handleStanza(boost::shared_ptr<Stanza> stanza);
- void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
- void handleSessionInitialized();
-
- private:
- IDGenerator idGenerator;
- boost::shared_ptr<ClientSession> session;
- };
+ /**
+ * StanzaChannel implementation around a ClientSession.
+ */
+ class SWIFTEN_API ClientSessionStanzaChannel : public StanzaChannel {
+ public:
+ virtual ~ClientSessionStanzaChannel();
+
+ void setSession(boost::shared_ptr<ClientSession> session);
+
+ void sendIQ(boost::shared_ptr<IQ> iq);
+ void sendMessage(boost::shared_ptr<Message> message);
+ void sendPresence(boost::shared_ptr<Presence> presence);
+ bool getStreamManagementEnabled() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+
+ bool isAvailable() const {
+ return session && session->getState() == ClientSession::Initialized;
+ }
+
+ private:
+ std::string getNewIQID();
+ void send(boost::shared_ptr<Stanza> stanza);
+ void handleSessionFinished(boost::shared_ptr<Error> error);
+ void handleStanza(boost::shared_ptr<Stanza> stanza);
+ void handleStanzaAcked(boost::shared_ptr<Stanza> stanza);
+ void handleSessionInitialized();
+
+ private:
+ IDGenerator idGenerator;
+ boost::shared_ptr<ClientSession> session;
+ };
}
diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp
index a34aecc..4852aa1 100644
--- a/Swiften/Client/ClientXMLTracer.cpp
+++ b/Swiften/Client/ClientXMLTracer.cpp
@@ -16,41 +16,41 @@ namespace Swift {
ClientXMLTracer::ClientXMLTracer(CoreClient* client, bool bosh) : bosh(bosh) {
#ifdef SWIFTEN_PLATFORM_WIN32
- beautifier = new XMLBeautifier(true, false);
+ beautifier = new XMLBeautifier(true, false);
#else
- beautifier = new XMLBeautifier(true, true);
+ beautifier = new XMLBeautifier(true, true);
#endif
- onDataReadConnection = client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1));
- onDataWrittenConnection = client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1));
+ onDataReadConnection = client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1));
+ onDataWrittenConnection = client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1));
}
ClientXMLTracer::~ClientXMLTracer() {
- delete beautifier;
+ delete beautifier;
}
void ClientXMLTracer::printData(char direction, const SafeByteArray& data) {
- printLine(direction);
- if (bosh) {
- std::string line = byteArrayToString(ByteArray(data.begin(), data.end()));
+ printLine(direction);
+ if (bosh) {
+ std::string line = byteArrayToString(ByteArray(data.begin(), data.end()));
// Disabled because it swallows bits of XML (namespaces, if I recall)
-// size_t endOfHTTP = line.find("\r\n\r\n");
-// if (false && endOfHTTP != std::string::npos) {
-// std::cerr << line.substr(0, endOfHTTP) << std::endl << beautifier->beautify(line.substr(endOfHTTP)) << std::endl;
-// }
-// else {
- std::cerr << line << std::endl;
-// }
- }
- else {
- std::cerr << beautifier->beautify(byteArrayToString(ByteArray(data.begin(), data.end()))) << std::endl;
- }
+// size_t endOfHTTP = line.find("\r\n\r\n");
+// if (false && endOfHTTP != std::string::npos) {
+// std::cerr << line.substr(0, endOfHTTP) << std::endl << beautifier->beautify(line.substr(endOfHTTP)) << std::endl;
+// }
+// else {
+ std::cerr << line << std::endl;
+// }
+ }
+ else {
+ std::cerr << beautifier->beautify(byteArrayToString(ByteArray(data.begin(), data.end()))) << std::endl;
+ }
}
void ClientXMLTracer::printLine(char c) {
- for (unsigned int i = 0; i < 80; ++i) {
- std::cerr << c;
- }
- std::cerr << std::endl;
+ for (unsigned int i = 0; i < 80; ++i) {
+ std::cerr << c;
+ }
+ std::cerr << std::endl;
}
}
diff --git a/Swiften/Client/ClientXMLTracer.h b/Swiften/Client/ClientXMLTracer.h
index bbaced9..ccecb41 100644
--- a/Swiften/Client/ClientXMLTracer.h
+++ b/Swiften/Client/ClientXMLTracer.h
@@ -12,19 +12,19 @@
#include <Swiften/Client/XMLBeautifier.h>
namespace Swift {
- class SWIFTEN_API ClientXMLTracer {
- public:
- ClientXMLTracer(CoreClient* client, bool bosh = false);
- ~ClientXMLTracer();
+ class SWIFTEN_API ClientXMLTracer {
+ public:
+ ClientXMLTracer(CoreClient* client, bool bosh = false);
+ ~ClientXMLTracer();
- private:
- void printData(char direction, const SafeByteArray& data);
- void printLine(char c);
+ private:
+ void printData(char direction, const SafeByteArray& data);
+ void printLine(char c);
- private:
- XMLBeautifier *beautifier;
- bool bosh;
- boost::bsignals::scoped_connection onDataReadConnection;
- boost::bsignals::scoped_connection onDataWrittenConnection;
- };
+ private:
+ XMLBeautifier *beautifier;
+ bool bosh;
+ boost::bsignals::scoped_connection onDataReadConnection;
+ boost::bsignals::scoped_connection onDataWrittenConnection;
+ };
}
diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp
index 6fc491c..fd7f894 100644
--- a/Swiften/Client/CoreClient.cpp
+++ b/Swiften/Client/CoreClient.cpp
@@ -32,448 +32,448 @@
namespace Swift {
CoreClient::CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories) : jid_(jid), password_(password), networkFactories(networkFactories), disconnectRequested_(false), certificateTrustChecker(NULL) {
- 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);
+ 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();
- delete iqRouter_;
-
- stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1));
- stanzaChannel_->onMessageReceived.disconnect(boost::bind(&CoreClient::handleMessageReceived, this, _1));
- stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&CoreClient::handlePresenceReceived, this, _1));
- stanzaChannel_->onStanzaAcked.disconnect(boost::bind(&CoreClient::handleStanzaAcked, this, _1));
- delete stanzaChannel_;
+ forceReset();
+ delete iqRouter_;
+
+ stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1));
+ stanzaChannel_->onMessageReceived.disconnect(boost::bind(&CoreClient::handleMessageReceived, this, _1));
+ stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&CoreClient::handlePresenceReceived, this, _1));
+ stanzaChannel_->onStanzaAcked.disconnect(boost::bind(&CoreClient::handleStanzaAcked, this, _1));
+ delete stanzaChannel_;
}
void CoreClient::connect(const ClientOptions& o) {
- SWIFT_LOG(debug) << "Connecting ";
-
- forceReset();
- disconnectRequested_ = false;
-
- options = o;
-
-
- // Determine connection types to use
- assert(proxyConnectionFactories.empty());
- bool useDirectConnection = true;
- HostAddressPort systemSOCKS5Proxy = networkFactories->getProxyProvider()->getSOCKS5Proxy();
- HostAddressPort systemHTTPConnectProxy = networkFactories->getProxyProvider()->getHTTPConnectProxy();
- switch (o.proxyType) {
- case ClientOptions::NoProxy:
- SWIFT_LOG(debug) << " without a proxy" << std::endl;
- break;
- case ClientOptions::SystemConfiguredProxy:
- SWIFT_LOG(debug) << " with a system configured proxy" << std::endl;
- if (systemSOCKS5Proxy.isValid()) {
- SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort() << std::endl;
- proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemSOCKS5Proxy.getAddress().toString(), systemSOCKS5Proxy.getPort()));
- }
- if (systemHTTPConnectProxy.isValid()) {
- SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl;
- proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort()));
- }
- break;
- case ClientOptions::SOCKS5Proxy: {
- SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl;
- std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname;
- int proxyPort = o.manualProxyPort == -1 ? systemSOCKS5Proxy.getPort() : o.manualProxyPort;
- SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
- proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort));
- useDirectConnection = false;
- break;
- }
- case ClientOptions::HTTPConnectProxy: {
- SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl;
- std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname;
- int proxyPort = o.manualProxyPort == -1 ? systemHTTPConnectProxy.getPort() : o.manualProxyPort;
- SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
- proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter));
- useDirectConnection = false;
- break;
- }
- }
- std::vector<ConnectionFactory*> connectionFactories(proxyConnectionFactories);
- if (useDirectConnection) {
- connectionFactories.push_back(networkFactories->getConnectionFactory());
- }
-
- // Create connector
- std::string host = o.manualHostname.empty() ? jid_.getDomain() : o.manualHostname;
- int port = o.manualPort;
- boost::optional<std::string> serviceLookupPrefix;
- if (o.manualHostname.empty()) {
- serviceLookupPrefix = "_xmpp-client._tcp.";
- }
- assert(!connector_);
- if (options.boshURL.isEmpty()) {
- connector_ = boost::make_shared<ChainedConnector>(host, port, serviceLookupPrefix, networkFactories->getDomainNameResolver(), connectionFactories, networkFactories->getTimerFactory());
- connector_->onConnectFinished.connect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2));
- connector_->setTimeoutMilliseconds(2*60*1000);
- connector_->start();
- }
- else {
- /* Autodiscovery of which proxy works is largely ok with a TCP session, because this is a one-off. With BOSH
- * it would be quite painful given that potentially every stanza could be sent on a new connection.
- */
- boost::shared_ptr<BOSHSessionStream> boshSessionStream_ = boost::shared_ptr<BOSHSessionStream>(new BOSHSessionStream(
- options.boshURL,
- getPayloadParserFactories(),
- getPayloadSerializers(),
- networkFactories->getConnectionFactory(),
- networkFactories->getTLSContextFactory(),
- networkFactories->getTimerFactory(),
- networkFactories->getXMLParserFactory(),
- networkFactories->getEventLoop(),
- networkFactories->getDomainNameResolver(),
- host,
- options.boshHTTPConnectProxyURL,
- options.boshHTTPConnectProxyAuthID,
- options.boshHTTPConnectProxyAuthPassword,
- options.tlsOptions,
- options.httpTrafficFilter));
- sessionStream_ = boshSessionStream_;
- sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1));
- sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1));
- if (certificate_ && !certificate_->isNull()) {
- SWIFT_LOG(debug) << "set certificate" << std::endl;
- sessionStream_->setTLSCertificate(certificate_);
- }
- boshSessionStream_->open();
- bindSessionToStream();
- }
+ SWIFT_LOG(debug) << "Connecting ";
+
+ forceReset();
+ disconnectRequested_ = false;
+
+ options = o;
+
+
+ // Determine connection types to use
+ assert(proxyConnectionFactories.empty());
+ bool useDirectConnection = true;
+ HostAddressPort systemSOCKS5Proxy = networkFactories->getProxyProvider()->getSOCKS5Proxy();
+ HostAddressPort systemHTTPConnectProxy = networkFactories->getProxyProvider()->getHTTPConnectProxy();
+ switch (o.proxyType) {
+ case ClientOptions::NoProxy:
+ SWIFT_LOG(debug) << " without a proxy" << std::endl;
+ break;
+ case ClientOptions::SystemConfiguredProxy:
+ SWIFT_LOG(debug) << " with a system configured proxy" << std::endl;
+ if (systemSOCKS5Proxy.isValid()) {
+ SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort() << std::endl;
+ proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemSOCKS5Proxy.getAddress().toString(), systemSOCKS5Proxy.getPort()));
+ }
+ if (systemHTTPConnectProxy.isValid()) {
+ SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl;
+ proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort()));
+ }
+ break;
+ case ClientOptions::SOCKS5Proxy: {
+ SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl;
+ std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname;
+ int proxyPort = o.manualProxyPort == -1 ? systemSOCKS5Proxy.getPort() : o.manualProxyPort;
+ SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
+ proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort));
+ useDirectConnection = false;
+ break;
+ }
+ case ClientOptions::HTTPConnectProxy: {
+ SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl;
+ std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname;
+ int proxyPort = o.manualProxyPort == -1 ? systemHTTPConnectProxy.getPort() : o.manualProxyPort;
+ SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
+ proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter));
+ useDirectConnection = false;
+ break;
+ }
+ }
+ std::vector<ConnectionFactory*> connectionFactories(proxyConnectionFactories);
+ if (useDirectConnection) {
+ connectionFactories.push_back(networkFactories->getConnectionFactory());
+ }
+
+ // Create connector
+ std::string host = o.manualHostname.empty() ? jid_.getDomain() : o.manualHostname;
+ int port = o.manualPort;
+ boost::optional<std::string> serviceLookupPrefix;
+ if (o.manualHostname.empty()) {
+ serviceLookupPrefix = "_xmpp-client._tcp.";
+ }
+ assert(!connector_);
+ if (options.boshURL.isEmpty()) {
+ connector_ = boost::make_shared<ChainedConnector>(host, port, serviceLookupPrefix, networkFactories->getDomainNameResolver(), connectionFactories, networkFactories->getTimerFactory());
+ connector_->onConnectFinished.connect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2));
+ connector_->setTimeoutMilliseconds(2*60*1000);
+ connector_->start();
+ }
+ else {
+ /* Autodiscovery of which proxy works is largely ok with a TCP session, because this is a one-off. With BOSH
+ * it would be quite painful given that potentially every stanza could be sent on a new connection.
+ */
+ boost::shared_ptr<BOSHSessionStream> boshSessionStream_ = boost::shared_ptr<BOSHSessionStream>(new BOSHSessionStream(
+ options.boshURL,
+ getPayloadParserFactories(),
+ getPayloadSerializers(),
+ networkFactories->getConnectionFactory(),
+ networkFactories->getTLSContextFactory(),
+ networkFactories->getTimerFactory(),
+ networkFactories->getXMLParserFactory(),
+ networkFactories->getEventLoop(),
+ networkFactories->getDomainNameResolver(),
+ host,
+ options.boshHTTPConnectProxyURL,
+ options.boshHTTPConnectProxyAuthID,
+ options.boshHTTPConnectProxyAuthPassword,
+ options.tlsOptions,
+ options.httpTrafficFilter));
+ sessionStream_ = boshSessionStream_;
+ sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1));
+ sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1));
+ if (certificate_ && !certificate_->isNull()) {
+ SWIFT_LOG(debug) << "set certificate" << std::endl;
+ sessionStream_->setTLSCertificate(certificate_);
+ }
+ boshSessionStream_->open();
+ bindSessionToStream();
+ }
}
void CoreClient::bindSessionToStream() {
- session_ = ClientSession::create(jid_, sessionStream_, networkFactories->getIDNConverter(), networkFactories->getCryptoProvider());
- session_->setCertificateTrustChecker(certificateTrustChecker);
- session_->setUseStreamCompression(options.useStreamCompression);
- session_->setAllowPLAINOverNonTLS(options.allowPLAINWithoutTLS);
- session_->setSingleSignOn(options.singleSignOn);
- session_->setAuthenticationPort(options.manualPort);
- switch(options.useTLS) {
- case ClientOptions::UseTLSWhenAvailable:
- session_->setUseTLS(ClientSession::UseTLSWhenAvailable);
- break;
- case ClientOptions::NeverUseTLS:
- session_->setUseTLS(ClientSession::NeverUseTLS);
- break;
- case ClientOptions::RequireTLS:
- session_->setUseTLS(ClientSession::RequireTLS);
- break;
- }
- session_->setUseAcks(options.useAcks);
- stanzaChannel_->setSession(session_);
- session_->onFinished.connect(boost::bind(&CoreClient::handleSessionFinished, this, _1));
- session_->onNeedCredentials.connect(boost::bind(&CoreClient::handleNeedCredentials, this));
- session_->start();
+ session_ = ClientSession::create(jid_, sessionStream_, networkFactories->getIDNConverter(), networkFactories->getCryptoProvider());
+ session_->setCertificateTrustChecker(certificateTrustChecker);
+ session_->setUseStreamCompression(options.useStreamCompression);
+ session_->setAllowPLAINOverNonTLS(options.allowPLAINWithoutTLS);
+ session_->setSingleSignOn(options.singleSignOn);
+ session_->setAuthenticationPort(options.manualPort);
+ switch(options.useTLS) {
+ case ClientOptions::UseTLSWhenAvailable:
+ session_->setUseTLS(ClientSession::UseTLSWhenAvailable);
+ break;
+ case ClientOptions::NeverUseTLS:
+ session_->setUseTLS(ClientSession::NeverUseTLS);
+ break;
+ case ClientOptions::RequireTLS:
+ session_->setUseTLS(ClientSession::RequireTLS);
+ break;
+ }
+ session_->setUseAcks(options.useAcks);
+ stanzaChannel_->setSession(session_);
+ session_->onFinished.connect(boost::bind(&CoreClient::handleSessionFinished, this, _1));
+ session_->onNeedCredentials.connect(boost::bind(&CoreClient::handleNeedCredentials, this));
+ session_->start();
}
/**
* Only called for TCP sessions. BOSH is handled inside the BOSHSessionStream.
*/
void CoreClient::handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) {
- resetConnector();
- if (!connection) {
- if (options.forgetPassword) {
- purgePassword();
- }
- boost::optional<ClientError> clientError;
- if (!disconnectRequested_) {
- clientError = boost::dynamic_pointer_cast<DomainNameResolveError>(error) ? boost::optional<ClientError>(ClientError::DomainNameResolveError) : boost::optional<ClientError>(ClientError::ConnectionError);
- }
- onDisconnected(clientError);
- }
- else {
- assert(!connection_);
- assert(!sessionStream_);
-
- if (certificate_ && certificate_->isNull()) {
- //certificate cannot be read so do not initailise session
- onDisconnected(boost::optional<ClientError>(ClientError::ClientCertificateLoadError));
- return;
- }
-
- connection_ = connection;
-
- sessionStream_ = boost::make_shared<BasicSessionStream>(ClientStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), networkFactories->getTLSContextFactory(), networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), options.tlsOptions);
- if (certificate_) {
- sessionStream_->setTLSCertificate(certificate_);
- }
- sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1));
- sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1));
-
- bindSessionToStream();
- }
+ resetConnector();
+ if (!connection) {
+ if (options.forgetPassword) {
+ purgePassword();
+ }
+ boost::optional<ClientError> clientError;
+ if (!disconnectRequested_) {
+ clientError = boost::dynamic_pointer_cast<DomainNameResolveError>(error) ? boost::optional<ClientError>(ClientError::DomainNameResolveError) : boost::optional<ClientError>(ClientError::ConnectionError);
+ }
+ onDisconnected(clientError);
+ }
+ else {
+ assert(!connection_);
+ assert(!sessionStream_);
+
+ if (certificate_ && certificate_->isNull()) {
+ //certificate cannot be read so do not initailise session
+ onDisconnected(boost::optional<ClientError>(ClientError::ClientCertificateLoadError));
+ return;
+ }
+
+ connection_ = connection;
+
+ sessionStream_ = boost::make_shared<BasicSessionStream>(ClientStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), networkFactories->getTLSContextFactory(), networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), options.tlsOptions);
+ if (certificate_) {
+ sessionStream_->setTLSCertificate(certificate_);
+ }
+ sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1));
+ sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1));
+
+ bindSessionToStream();
+ }
}
void CoreClient::disconnect() {
- // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between
- // connector finishing without a connection due to an error or because of a disconnect.
- disconnectRequested_ = true;
- if (session_ && !session_->isFinished()) {
- session_->finish();
- }
- else if (connector_) {
- connector_->stop();
- }
+ // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between
+ // connector finishing without a connection due to an error or because of a disconnect.
+ disconnectRequested_ = true;
+ if (session_ && !session_->isFinished()) {
+ session_->finish();
+ }
+ else if (connector_) {
+ connector_->stop();
+ }
}
void CoreClient::setCertificate(CertificateWithKey::ref certificate) {
- certificate_ = certificate;
+ certificate_ = certificate;
}
void CoreClient::handleSessionFinished(boost::shared_ptr<Error> error) {
- if (options.forgetPassword) {
- purgePassword();
- }
- resetSession();
-
- boost::optional<ClientError> actualError;
- if (error) {
- ClientError clientError;
- if (boost::shared_ptr<ClientSession::Error> actualError = boost::dynamic_pointer_cast<ClientSession::Error>(error)) {
- switch(actualError->type) {
- case ClientSession::Error::AuthenticationFailedError:
- clientError = ClientError(ClientError::AuthenticationFailedError);
- break;
- case ClientSession::Error::CompressionFailedError:
- clientError = ClientError(ClientError::CompressionFailedError);
- break;
- case ClientSession::Error::ServerVerificationFailedError:
- clientError = ClientError(ClientError::ServerVerificationFailedError);
- break;
- case ClientSession::Error::NoSupportedAuthMechanismsError:
- clientError = ClientError(ClientError::NoSupportedAuthMechanismsError);
- break;
- case ClientSession::Error::UnexpectedElementError:
- clientError = ClientError(ClientError::UnexpectedElementError);
- break;
- case ClientSession::Error::ResourceBindError:
- clientError = ClientError(ClientError::ResourceBindError);
- break;
- case ClientSession::Error::SessionStartError:
- clientError = ClientError(ClientError::SessionStartError);
- break;
- case ClientSession::Error::TLSError:
- clientError = ClientError(ClientError::TLSError);
- break;
- case ClientSession::Error::TLSClientCertificateError:
- clientError = ClientError(ClientError::ClientCertificateError);
- break;
- case ClientSession::Error::StreamError:
- clientError = ClientError(ClientError::StreamError);
- break;
- }
- clientError.setErrorCode(actualError->errorCode);
- }
- else if (boost::shared_ptr<TLSError> actualError = boost::dynamic_pointer_cast<TLSError>(error)) {
- switch(actualError->getType()) {
- case TLSError::CertificateCardRemoved:
- clientError = ClientError(ClientError::CertificateCardRemoved);
- break;
- case TLSError::UnknownError:
- clientError = ClientError(ClientError::TLSError);
- break;
- }
- }
- else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) {
- switch(actualError->type) {
- case SessionStream::SessionStreamError::ParseError:
- clientError = ClientError(ClientError::XMLError);
- break;
- case SessionStream::SessionStreamError::TLSError:
- clientError = ClientError(ClientError::TLSError);
- break;
- case SessionStream::SessionStreamError::InvalidTLSCertificateError:
- clientError = ClientError(ClientError::ClientCertificateLoadError);
- break;
- case SessionStream::SessionStreamError::ConnectionReadError:
- clientError = ClientError(ClientError::ConnectionReadError);
- break;
- case SessionStream::SessionStreamError::ConnectionWriteError:
- clientError = ClientError(ClientError::ConnectionWriteError);
- break;
- }
- }
- else if (boost::shared_ptr<CertificateVerificationError> verificationError = boost::dynamic_pointer_cast<CertificateVerificationError>(error)) {
- switch(verificationError->getType()) {
- case CertificateVerificationError::UnknownError:
- clientError = ClientError(ClientError::UnknownCertificateError);
- break;
- case CertificateVerificationError::Expired:
- clientError = ClientError(ClientError::CertificateExpiredError);
- break;
- case CertificateVerificationError::NotYetValid:
- clientError = ClientError(ClientError::CertificateNotYetValidError);
- break;
- case CertificateVerificationError::SelfSigned:
- clientError = ClientError(ClientError::CertificateSelfSignedError);
- break;
- case CertificateVerificationError::Rejected:
- clientError = ClientError(ClientError::CertificateRejectedError);
- break;
- case CertificateVerificationError::Untrusted:
- clientError = ClientError(ClientError::CertificateUntrustedError);
- break;
- case CertificateVerificationError::InvalidPurpose:
- clientError = ClientError(ClientError::InvalidCertificatePurposeError);
- break;
- case CertificateVerificationError::PathLengthExceeded:
- clientError = ClientError(ClientError::CertificatePathLengthExceededError);
- break;
- case CertificateVerificationError::InvalidSignature:
- clientError = ClientError(ClientError::InvalidCertificateSignatureError);
- break;
- case CertificateVerificationError::InvalidCA:
- clientError = ClientError(ClientError::InvalidCAError);
- break;
- case CertificateVerificationError::InvalidServerIdentity:
- clientError = ClientError(ClientError::InvalidServerIdentityError);
- break;
- case CertificateVerificationError::Revoked:
- clientError = ClientError(ClientError::RevokedError);
- break;
- case CertificateVerificationError::RevocationCheckFailed:
- clientError = ClientError(ClientError::RevocationCheckFailedError);
- break;
- }
- }
- actualError = boost::optional<ClientError>(clientError);
- }
- onDisconnected(actualError);
+ if (options.forgetPassword) {
+ purgePassword();
+ }
+ resetSession();
+
+ boost::optional<ClientError> actualError;
+ if (error) {
+ ClientError clientError;
+ if (boost::shared_ptr<ClientSession::Error> actualError = boost::dynamic_pointer_cast<ClientSession::Error>(error)) {
+ switch(actualError->type) {
+ case ClientSession::Error::AuthenticationFailedError:
+ clientError = ClientError(ClientError::AuthenticationFailedError);
+ break;
+ case ClientSession::Error::CompressionFailedError:
+ clientError = ClientError(ClientError::CompressionFailedError);
+ break;
+ case ClientSession::Error::ServerVerificationFailedError:
+ clientError = ClientError(ClientError::ServerVerificationFailedError);
+ break;
+ case ClientSession::Error::NoSupportedAuthMechanismsError:
+ clientError = ClientError(ClientError::NoSupportedAuthMechanismsError);
+ break;
+ case ClientSession::Error::UnexpectedElementError:
+ clientError = ClientError(ClientError::UnexpectedElementError);
+ break;
+ case ClientSession::Error::ResourceBindError:
+ clientError = ClientError(ClientError::ResourceBindError);
+ break;
+ case ClientSession::Error::SessionStartError:
+ clientError = ClientError(ClientError::SessionStartError);
+ break;
+ case ClientSession::Error::TLSError:
+ clientError = ClientError(ClientError::TLSError);
+ break;
+ case ClientSession::Error::TLSClientCertificateError:
+ clientError = ClientError(ClientError::ClientCertificateError);
+ break;
+ case ClientSession::Error::StreamError:
+ clientError = ClientError(ClientError::StreamError);
+ break;
+ }
+ clientError.setErrorCode(actualError->errorCode);
+ }
+ else if (boost::shared_ptr<TLSError> actualError = boost::dynamic_pointer_cast<TLSError>(error)) {
+ switch(actualError->getType()) {
+ case TLSError::CertificateCardRemoved:
+ clientError = ClientError(ClientError::CertificateCardRemoved);
+ break;
+ case TLSError::UnknownError:
+ clientError = ClientError(ClientError::TLSError);
+ break;
+ }
+ }
+ else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) {
+ switch(actualError->type) {
+ case SessionStream::SessionStreamError::ParseError:
+ clientError = ClientError(ClientError::XMLError);
+ break;
+ case SessionStream::SessionStreamError::TLSError:
+ clientError = ClientError(ClientError::TLSError);
+ break;
+ case SessionStream::SessionStreamError::InvalidTLSCertificateError:
+ clientError = ClientError(ClientError::ClientCertificateLoadError);
+ break;
+ case SessionStream::SessionStreamError::ConnectionReadError:
+ clientError = ClientError(ClientError::ConnectionReadError);
+ break;
+ case SessionStream::SessionStreamError::ConnectionWriteError:
+ clientError = ClientError(ClientError::ConnectionWriteError);
+ break;
+ }
+ }
+ else if (boost::shared_ptr<CertificateVerificationError> verificationError = boost::dynamic_pointer_cast<CertificateVerificationError>(error)) {
+ switch(verificationError->getType()) {
+ case CertificateVerificationError::UnknownError:
+ clientError = ClientError(ClientError::UnknownCertificateError);
+ break;
+ case CertificateVerificationError::Expired:
+ clientError = ClientError(ClientError::CertificateExpiredError);
+ break;
+ case CertificateVerificationError::NotYetValid:
+ clientError = ClientError(ClientError::CertificateNotYetValidError);
+ break;
+ case CertificateVerificationError::SelfSigned:
+ clientError = ClientError(ClientError::CertificateSelfSignedError);
+ break;
+ case CertificateVerificationError::Rejected:
+ clientError = ClientError(ClientError::CertificateRejectedError);
+ break;
+ case CertificateVerificationError::Untrusted:
+ clientError = ClientError(ClientError::CertificateUntrustedError);
+ break;
+ case CertificateVerificationError::InvalidPurpose:
+ clientError = ClientError(ClientError::InvalidCertificatePurposeError);
+ break;
+ case CertificateVerificationError::PathLengthExceeded:
+ clientError = ClientError(ClientError::CertificatePathLengthExceededError);
+ break;
+ case CertificateVerificationError::InvalidSignature:
+ clientError = ClientError(ClientError::InvalidCertificateSignatureError);
+ break;
+ case CertificateVerificationError::InvalidCA:
+ clientError = ClientError(ClientError::InvalidCAError);
+ break;
+ case CertificateVerificationError::InvalidServerIdentity:
+ clientError = ClientError(ClientError::InvalidServerIdentityError);
+ break;
+ case CertificateVerificationError::Revoked:
+ clientError = ClientError(ClientError::RevokedError);
+ break;
+ case CertificateVerificationError::RevocationCheckFailed:
+ clientError = ClientError(ClientError::RevocationCheckFailedError);
+ break;
+ }
+ }
+ actualError = boost::optional<ClientError>(clientError);
+ }
+ onDisconnected(actualError);
}
void CoreClient::handleNeedCredentials() {
- assert(session_);
- session_->sendCredentials(password_);
- if (options.forgetPassword) {
- purgePassword();
- }
+ assert(session_);
+ session_->sendCredentials(password_);
+ if (options.forgetPassword) {
+ purgePassword();
+ }
}
void CoreClient::handleDataRead(const SafeByteArray& data) {
- onDataRead(data);
+ onDataRead(data);
}
void CoreClient::handleDataWritten(const SafeByteArray& data) {
- onDataWritten(data);
+ onDataWritten(data);
}
void CoreClient::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- iqRouter_->setJID(session_->getLocalJID());
- handleConnected();
- onConnected();
- }
+ if (available) {
+ iqRouter_->setJID(session_->getLocalJID());
+ handleConnected();
+ onConnected();
+ }
}
void CoreClient::sendMessage(boost::shared_ptr<Message> message) {
- stanzaChannel_->sendMessage(message);
+ stanzaChannel_->sendMessage(message);
}
void CoreClient::sendPresence(boost::shared_ptr<Presence> presence) {
- stanzaChannel_->sendPresence(presence);
+ stanzaChannel_->sendPresence(presence);
}
void CoreClient::sendData(const std::string& data) {
- sessionStream_->writeData(data);
+ sessionStream_->writeData(data);
}
bool CoreClient::isActive() const {
- return (session_ && !session_->isFinished()) || connector_;
+ return (session_ && !session_->isFinished()) || connector_;
}
void CoreClient::setCertificateTrustChecker(CertificateTrustChecker* checker) {
- certificateTrustChecker = checker;
+ certificateTrustChecker = checker;
}
void CoreClient::handlePresenceReceived(Presence::ref presence) {
- onPresenceReceived(presence);
+ onPresenceReceived(presence);
}
void CoreClient::handleMessageReceived(Message::ref message) {
- onMessageReceived(message);
+ onMessageReceived(message);
}
void CoreClient::handleStanzaAcked(Stanza::ref stanza) {
- onStanzaAcked(stanza);
+ onStanzaAcked(stanza);
}
bool CoreClient::isAvailable() const {
- return stanzaChannel_->isAvailable();
+ return stanzaChannel_->isAvailable();
}
bool CoreClient::getStreamManagementEnabled() const {
- return stanzaChannel_->getStreamManagementEnabled();
+ return stanzaChannel_->getStreamManagementEnabled();
}
bool CoreClient::isStreamEncrypted() const {
- return sessionStream_->isTLSEncrypted();
+ return sessionStream_->isTLSEncrypted();
}
StanzaChannel* CoreClient::getStanzaChannel() const {
- return stanzaChannel_;
+ return stanzaChannel_;
}
const JID& CoreClient::getJID() const {
- if (session_) {
- return session_->getLocalJID();
- }
- else {
- return jid_;
- }
+ if (session_) {
+ return session_->getLocalJID();
+ }
+ else {
+ return jid_;
+ }
}
void CoreClient::purgePassword() {
- safeClear(password_);
+ safeClear(password_);
}
void CoreClient::resetConnector() {
- connector_->onConnectFinished.disconnect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2));
- connector_.reset();
- foreach(ConnectionFactory* f, proxyConnectionFactories) {
- delete f;
- }
- proxyConnectionFactories.clear();
+ connector_->onConnectFinished.disconnect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2));
+ connector_.reset();
+ foreach(ConnectionFactory* 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 (boost::dynamic_pointer_cast<BOSHSessionStream>(sessionStream_)) {
- sessionStream_->close();
- }
- sessionStream_.reset();
- connection_.reset();
+ 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 (boost::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();
- }
+ 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/CoreClient.h b/Swiften/Client/CoreClient.h
index 002a704..3efc38f 100644
--- a/Swiften/Client/CoreClient.h
+++ b/Swiften/Client/CoreClient.h
@@ -20,223 +20,223 @@
#include <Swiften/TLS/CertificateWithKey.h>
namespace Swift {
- class ChainedConnector;
- class Message;
- class Presence;
- class Error;
- class IQRouter;
- class TLSContextFactory;
- class ConnectionFactory;
- class Connection;
- class TimerFactory;
- class ClientSession;
- class StanzaChannel;
- class Stanza;
- class SessionStream;
- class CertificateTrustChecker;
- class NetworkFactories;
- class ClientSessionStanzaChannel;
-
- /**
- * The central class for communicating with an XMPP server.
- *
- * This class is responsible for setting up the connection with the XMPP
- * server, authenticating, and initializing the session.
- *
- * This class can be used directly in your application, although the Client
- * subclass provides more functionality and interfaces, and is better suited
- * for most needs.
- */
- class SWIFTEN_API CoreClient : public Entity {
- public:
- /**
- * Constructs a client for the given JID with the given password.
- */
- CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories);
- virtual ~CoreClient();
-
- /**
- * Set a client certificate to use for strong authentication with the server.
- * Ensure that it is of the correct type for the TLS engine in use.
- * This means, largely, PKCS12Certificate for OpenSSL and CAPICertificate for CAPI.
- */
- void setCertificate(CertificateWithKey::ref certificate);
-
- /**
- * Connects the client to the server.
- *
- * After the connection is established, the client will set
- * initialize the stream and authenticate.
- */
- void connect(const ClientOptions& = ClientOptions());
-
- /**
- * Disconnects the client from the server.
- */
- void disconnect();
-
- /**
- * Sends a message.
- */
- void sendMessage(boost::shared_ptr<Message>);
-
- /**
- * Sends a presence stanza.
- */
- void sendPresence(boost::shared_ptr<Presence>);
-
- /**
- * Sends raw, unchecked data.
- */
- void sendData(const std::string& data);
-
- /**
- * Returns the IQ router for this client.
- */
- IQRouter* getIQRouter() const {
- return iqRouter_;
- }
-
- /**
- * Checks whether the client is connected to the server,
- * and stanzas can be sent.
- */
- bool isAvailable() const;
-
- /**
- * Checks whether the client is active.
- *
- * A client is active when it is connected or connecting to the server.
- */
- bool isActive() const;
-
- /**
- * Returns the JID of the client.
- * After the session was initialized, this returns the bound JID.
- */
- const JID& getJID() const;
-
- /**
- * Checks whether stream management is enabled.
- *
- * If stream management is enabled, onStanzaAcked will be
- * emitted when a stanza is received by the server.
- *
- * \see onStanzaAcked
- */
- bool getStreamManagementEnabled() const;
-
- /**
- * Checks whether stream encryption (TLS) is currently active.
- */
- bool isStreamEncrypted() const;
-
- StanzaChannel* getStanzaChannel() const;
-
- /**
- * Sets the certificate trust checker.
- *
- * This checker will be called when the server sends a
- * TLS certificate that does not validate. If the trust checker
- * says the certificate is trusted, then connecting will proceed;
- * if not, the connection will end with an error.
- */
- void setCertificateTrustChecker(CertificateTrustChecker*);
-
- public:
- /**
- * Emitted when the client was disconnected from the network.
- *
- * If the connection was due to a non-recoverable error, the type
- * of error will be passed as a parameter.
- */
- boost::signal<void (const boost::optional<ClientError>&)> onDisconnected;
-
- /**
- * Emitted when the client is connected and authenticated,
- * and stanzas can be sent.
- */
- boost::signal<void ()> onConnected;
-
- /**
- * Emitted when the client receives data.
- *
- * This signal is emitted before the XML data is parsed,
- * so this data is unformatted.
- */
- boost::signal<void (const SafeByteArray&)> onDataRead;
-
- /**
- * Emitted when the client sends data.
- *
- * This signal is emitted after the XML was serialized, and
- * is unformatted.
- */
- boost::signal<void (const SafeByteArray&)> onDataWritten;
-
- /**
- * Emitted when a message is received.
- */
- boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
-
- /**
- * Emitted when a presence stanza is received.
- */
- boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
-
- /**
- * Emitted when the server acknowledges receipt of a
- * stanza (if acknowledgements are available).
- *
- * \see getStreamManagementEnabled()
- */
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
-
- protected:
- boost::shared_ptr<ClientSession> getSession() const {
- return session_;
- }
-
- NetworkFactories* getNetworkFactories() const {
- return networkFactories;
- }
-
- /**
- * Called before onConnected signal is emmitted.
- */
- virtual void handleConnected() {}
-
- private:
- void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error> error);
- void handleStanzaChannelAvailableChanged(bool available);
- void handleSessionFinished(boost::shared_ptr<Error>);
- void handleNeedCredentials();
- void handleDataRead(const SafeByteArray&);
- void handleDataWritten(const SafeByteArray&);
- void handlePresenceReceived(boost::shared_ptr<Presence>);
- void handleMessageReceived(boost::shared_ptr<Message>);
- void handleStanzaAcked(boost::shared_ptr<Stanza>);
- void purgePassword();
- void bindSessionToStream();
-
- void resetConnector();
- void resetSession();
- void forceReset();
-
- private:
- JID jid_;
- SafeByteArray password_;
- NetworkFactories* networkFactories;
- ClientSessionStanzaChannel* stanzaChannel_;
- IQRouter* iqRouter_;
- ClientOptions options;
- boost::shared_ptr<ChainedConnector> connector_;
- std::vector<ConnectionFactory*> proxyConnectionFactories;
- boost::shared_ptr<Connection> connection_;
- boost::shared_ptr<SessionStream> sessionStream_;
- boost::shared_ptr<ClientSession> session_;
- CertificateWithKey::ref certificate_;
- bool disconnectRequested_;
- CertificateTrustChecker* certificateTrustChecker;
- };
+ class ChainedConnector;
+ class Message;
+ class Presence;
+ class Error;
+ class IQRouter;
+ class TLSContextFactory;
+ class ConnectionFactory;
+ class Connection;
+ class TimerFactory;
+ class ClientSession;
+ class StanzaChannel;
+ class Stanza;
+ class SessionStream;
+ class CertificateTrustChecker;
+ class NetworkFactories;
+ class ClientSessionStanzaChannel;
+
+ /**
+ * The central class for communicating with an XMPP server.
+ *
+ * This class is responsible for setting up the connection with the XMPP
+ * server, authenticating, and initializing the session.
+ *
+ * This class can be used directly in your application, although the Client
+ * subclass provides more functionality and interfaces, and is better suited
+ * for most needs.
+ */
+ class SWIFTEN_API CoreClient : public Entity {
+ public:
+ /**
+ * Constructs a client for the given JID with the given password.
+ */
+ CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories);
+ virtual ~CoreClient();
+
+ /**
+ * Set a client certificate to use for strong authentication with the server.
+ * Ensure that it is of the correct type for the TLS engine in use.
+ * This means, largely, PKCS12Certificate for OpenSSL and CAPICertificate for CAPI.
+ */
+ void setCertificate(CertificateWithKey::ref certificate);
+
+ /**
+ * Connects the client to the server.
+ *
+ * After the connection is established, the client will set
+ * initialize the stream and authenticate.
+ */
+ void connect(const ClientOptions& = ClientOptions());
+
+ /**
+ * Disconnects the client from the server.
+ */
+ void disconnect();
+
+ /**
+ * Sends a message.
+ */
+ void sendMessage(boost::shared_ptr<Message>);
+
+ /**
+ * Sends a presence stanza.
+ */
+ void sendPresence(boost::shared_ptr<Presence>);
+
+ /**
+ * Sends raw, unchecked data.
+ */
+ void sendData(const std::string& data);
+
+ /**
+ * Returns the IQ router for this client.
+ */
+ IQRouter* getIQRouter() const {
+ return iqRouter_;
+ }
+
+ /**
+ * Checks whether the client is connected to the server,
+ * and stanzas can be sent.
+ */
+ bool isAvailable() const;
+
+ /**
+ * Checks whether the client is active.
+ *
+ * A client is active when it is connected or connecting to the server.
+ */
+ bool isActive() const;
+
+ /**
+ * Returns the JID of the client.
+ * After the session was initialized, this returns the bound JID.
+ */
+ const JID& getJID() const;
+
+ /**
+ * Checks whether stream management is enabled.
+ *
+ * If stream management is enabled, onStanzaAcked will be
+ * emitted when a stanza is received by the server.
+ *
+ * \see onStanzaAcked
+ */
+ bool getStreamManagementEnabled() const;
+
+ /**
+ * Checks whether stream encryption (TLS) is currently active.
+ */
+ bool isStreamEncrypted() const;
+
+ StanzaChannel* getStanzaChannel() const;
+
+ /**
+ * Sets the certificate trust checker.
+ *
+ * This checker will be called when the server sends a
+ * TLS certificate that does not validate. If the trust checker
+ * says the certificate is trusted, then connecting will proceed;
+ * if not, the connection will end with an error.
+ */
+ void setCertificateTrustChecker(CertificateTrustChecker*);
+
+ public:
+ /**
+ * Emitted when the client was disconnected from the network.
+ *
+ * If the connection was due to a non-recoverable error, the type
+ * of error will be passed as a parameter.
+ */
+ boost::signal<void (const boost::optional<ClientError>&)> onDisconnected;
+
+ /**
+ * Emitted when the client is connected and authenticated,
+ * and stanzas can be sent.
+ */
+ boost::signal<void ()> onConnected;
+
+ /**
+ * Emitted when the client receives data.
+ *
+ * This signal is emitted before the XML data is parsed,
+ * so this data is unformatted.
+ */
+ boost::signal<void (const SafeByteArray&)> onDataRead;
+
+ /**
+ * Emitted when the client sends data.
+ *
+ * This signal is emitted after the XML was serialized, and
+ * is unformatted.
+ */
+ boost::signal<void (const SafeByteArray&)> onDataWritten;
+
+ /**
+ * Emitted when a message is received.
+ */
+ boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
+
+ /**
+ * Emitted when a presence stanza is received.
+ */
+ boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
+
+ /**
+ * Emitted when the server acknowledges receipt of a
+ * stanza (if acknowledgements are available).
+ *
+ * \see getStreamManagementEnabled()
+ */
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
+
+ protected:
+ boost::shared_ptr<ClientSession> getSession() const {
+ return session_;
+ }
+
+ NetworkFactories* getNetworkFactories() const {
+ return networkFactories;
+ }
+
+ /**
+ * Called before onConnected signal is emmitted.
+ */
+ virtual void handleConnected() {}
+
+ private:
+ void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error> error);
+ void handleStanzaChannelAvailableChanged(bool available);
+ void handleSessionFinished(boost::shared_ptr<Error>);
+ void handleNeedCredentials();
+ void handleDataRead(const SafeByteArray&);
+ void handleDataWritten(const SafeByteArray&);
+ void handlePresenceReceived(boost::shared_ptr<Presence>);
+ void handleMessageReceived(boost::shared_ptr<Message>);
+ void handleStanzaAcked(boost::shared_ptr<Stanza>);
+ void purgePassword();
+ void bindSessionToStream();
+
+ void resetConnector();
+ void resetSession();
+ void forceReset();
+
+ private:
+ JID jid_;
+ SafeByteArray password_;
+ NetworkFactories* networkFactories;
+ ClientSessionStanzaChannel* stanzaChannel_;
+ IQRouter* iqRouter_;
+ ClientOptions options;
+ boost::shared_ptr<ChainedConnector> connector_;
+ std::vector<ConnectionFactory*> proxyConnectionFactories;
+ boost::shared_ptr<Connection> connection_;
+ boost::shared_ptr<SessionStream> sessionStream_;
+ boost::shared_ptr<ClientSession> session_;
+ CertificateWithKey::ref certificate_;
+ bool disconnectRequested_;
+ CertificateTrustChecker* certificateTrustChecker;
+ };
}
diff --git a/Swiften/Client/DummyNickManager.h b/Swiften/Client/DummyNickManager.h
index 2f5f13f..52a8401 100644
--- a/Swiften/Client/DummyNickManager.h
+++ b/Swiften/Client/DummyNickManager.h
@@ -9,15 +9,15 @@
#include <Swiften/Client/NickManager.h>
namespace Swift {
- class VCardManager;
+ class VCardManager;
- class DummyNickManager : public NickManager {
- public:
- std::string getOwnNick() const {
- return "";
- }
+ class DummyNickManager : public NickManager {
+ public:
+ std::string getOwnNick() const {
+ return "";
+ }
- void setOwnNick(const std::string&) {
- }
- };
+ void setOwnNick(const std::string&) {
+ }
+ };
}
diff --git a/Swiften/Client/DummyStanzaChannel.h b/Swiften/Client/DummyStanzaChannel.h
index 0373cc4..0e52f62 100644
--- a/Swiften/Client/DummyStanzaChannel.h
+++ b/Swiften/Client/DummyStanzaChannel.h
@@ -11,79 +11,79 @@
#include <Swiften/Client/StanzaChannel.h>
namespace Swift {
- class DummyStanzaChannel : public StanzaChannel {
- public:
- DummyStanzaChannel() : available_(true) {}
-
- virtual void sendStanza(boost::shared_ptr<Stanza> stanza) {
- sentStanzas.push_back(stanza);
- }
-
- void setAvailable(bool available) {
- available_ = available;
- onAvailableChanged(available);
- }
-
- virtual void sendIQ(boost::shared_ptr<IQ> iq) {
- sentStanzas.push_back(iq);
- }
-
- virtual void sendMessage(boost::shared_ptr<Message> message) {
- sentStanzas.push_back(message);
- }
-
- virtual void sendPresence(boost::shared_ptr<Presence> presence) {
- sentStanzas.push_back(presence);
- }
-
- virtual std::string getNewIQID() {
- return "test-id";
- }
-
- virtual bool isAvailable() const {
- return available_;
- }
-
- virtual bool getStreamManagementEnabled() const {
- return false;
- }
-
- template<typename T> bool isRequestAtIndex(size_t index, const JID& jid, IQ::Type type) {
- if (index >= sentStanzas.size()) {
- return false;
- }
- boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
- return iqStanza && iqStanza->getType() == type && iqStanza->getTo() == jid && iqStanza->getPayload<T>();
- }
-
- bool isResultAtIndex(size_t index, const std::string& id) {
- if (index >= sentStanzas.size()) {
- return false;
- }
- boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
- return iqStanza && iqStanza->getType() == IQ::Result && iqStanza->getID() == id;
- }
-
- bool isErrorAtIndex(size_t index, const std::string& id) {
- if (index >= sentStanzas.size()) {
- return false;
- }
- boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
- return iqStanza && iqStanza->getType() == IQ::Error && iqStanza->getID() == id;
- }
-
- template<typename T> boost::shared_ptr<T> getStanzaAtIndex(size_t index) {
- if (sentStanzas.size() <= index) {
- return boost::shared_ptr<T>();
- }
- return boost::dynamic_pointer_cast<T>(sentStanzas[index]);
- }
-
- std::vector<Certificate::ref> getPeerCertificateChain() const {
- return std::vector<Certificate::ref>();
- }
-
- std::vector<boost::shared_ptr<Stanza> > sentStanzas;
- bool available_;
- };
+ class DummyStanzaChannel : public StanzaChannel {
+ public:
+ DummyStanzaChannel() : available_(true) {}
+
+ virtual void sendStanza(boost::shared_ptr<Stanza> stanza) {
+ sentStanzas.push_back(stanza);
+ }
+
+ void setAvailable(bool available) {
+ available_ = available;
+ onAvailableChanged(available);
+ }
+
+ virtual void sendIQ(boost::shared_ptr<IQ> iq) {
+ sentStanzas.push_back(iq);
+ }
+
+ virtual void sendMessage(boost::shared_ptr<Message> message) {
+ sentStanzas.push_back(message);
+ }
+
+ virtual void sendPresence(boost::shared_ptr<Presence> presence) {
+ sentStanzas.push_back(presence);
+ }
+
+ virtual std::string getNewIQID() {
+ return "test-id";
+ }
+
+ virtual bool isAvailable() const {
+ return available_;
+ }
+
+ virtual bool getStreamManagementEnabled() const {
+ return false;
+ }
+
+ template<typename T> bool isRequestAtIndex(size_t index, const JID& jid, IQ::Type type) {
+ if (index >= sentStanzas.size()) {
+ return false;
+ }
+ boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
+ return iqStanza && iqStanza->getType() == type && iqStanza->getTo() == jid && iqStanza->getPayload<T>();
+ }
+
+ bool isResultAtIndex(size_t index, const std::string& id) {
+ if (index >= sentStanzas.size()) {
+ return false;
+ }
+ boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
+ return iqStanza && iqStanza->getType() == IQ::Result && iqStanza->getID() == id;
+ }
+
+ bool isErrorAtIndex(size_t index, const std::string& id) {
+ if (index >= sentStanzas.size()) {
+ return false;
+ }
+ boost::shared_ptr<IQ> iqStanza = boost::dynamic_pointer_cast<IQ>(sentStanzas[index]);
+ return iqStanza && iqStanza->getType() == IQ::Error && iqStanza->getID() == id;
+ }
+
+ template<typename T> boost::shared_ptr<T> getStanzaAtIndex(size_t index) {
+ if (sentStanzas.size() <= index) {
+ return boost::shared_ptr<T>();
+ }
+ return boost::dynamic_pointer_cast<T>(sentStanzas[index]);
+ }
+
+ std::vector<Certificate::ref> getPeerCertificateChain() const {
+ return std::vector<Certificate::ref>();
+ }
+
+ std::vector<boost::shared_ptr<Stanza> > sentStanzas;
+ bool available_;
+ };
}
diff --git a/Swiften/Client/MemoryStorages.cpp b/Swiften/Client/MemoryStorages.cpp
index 8825fa2..14aa63a 100644
--- a/Swiften/Client/MemoryStorages.cpp
+++ b/Swiften/Client/MemoryStorages.cpp
@@ -16,48 +16,48 @@
namespace Swift {
MemoryStorages::MemoryStorages(CryptoProvider* crypto) {
- vcardStorage = new VCardMemoryStorage(crypto);
- capsStorage = new CapsMemoryStorage();
- avatarStorage = new AvatarMemoryStorage();
- rosterStorage = new RosterMemoryStorage();
+ vcardStorage = new VCardMemoryStorage(crypto);
+ capsStorage = new CapsMemoryStorage();
+ avatarStorage = new AvatarMemoryStorage();
+ rosterStorage = new RosterMemoryStorage();
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- historyStorage = new SQLiteHistoryStorage(":memory:");
+ historyStorage = new SQLiteHistoryStorage(":memory:");
#else
- historyStorage = NULL;
+ historyStorage = NULL;
#endif
}
MemoryStorages::~MemoryStorages() {
- delete rosterStorage;
- delete avatarStorage;
- delete capsStorage;
- delete vcardStorage;
+ delete rosterStorage;
+ delete avatarStorage;
+ delete capsStorage;
+ delete vcardStorage;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- delete historyStorage;
+ delete historyStorage;
#endif
}
VCardStorage* MemoryStorages::getVCardStorage() const {
- return vcardStorage;
+ return vcardStorage;
}
CapsStorage* MemoryStorages::getCapsStorage() const {
- return capsStorage;
+ return capsStorage;
}
AvatarStorage* MemoryStorages::getAvatarStorage() const {
- return avatarStorage;
+ return avatarStorage;
}
RosterStorage* MemoryStorages::getRosterStorage() const {
- return rosterStorage;
+ return rosterStorage;
}
HistoryStorage* MemoryStorages::getHistoryStorage() const {
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- return historyStorage;
+ return historyStorage;
#else
- return NULL;
+ return NULL;
#endif
}
diff --git a/Swiften/Client/MemoryStorages.h b/Swiften/Client/MemoryStorages.h
index 49f18f5..b905ed9 100644
--- a/Swiften/Client/MemoryStorages.h
+++ b/Swiften/Client/MemoryStorages.h
@@ -10,29 +10,29 @@
#include <Swiften/Client/Storages.h>
namespace Swift {
- class VCardMemoryStorage;
- class CryptoProvider;
+ class VCardMemoryStorage;
+ class CryptoProvider;
- /**
- * An implementation of Storages for storing all
- * controller data in memory.
- */
- class SWIFTEN_API MemoryStorages : public Storages {
- public:
- MemoryStorages(CryptoProvider*);
- virtual ~MemoryStorages();
+ /**
+ * An implementation of Storages for storing all
+ * controller data in memory.
+ */
+ class SWIFTEN_API MemoryStorages : public Storages {
+ public:
+ MemoryStorages(CryptoProvider*);
+ virtual ~MemoryStorages();
- virtual VCardStorage* getVCardStorage() const;
- virtual AvatarStorage* getAvatarStorage() const;
- virtual CapsStorage* getCapsStorage() const;
- virtual RosterStorage* getRosterStorage() const;
- virtual HistoryStorage* getHistoryStorage() const;
+ virtual VCardStorage* getVCardStorage() const;
+ virtual AvatarStorage* getAvatarStorage() const;
+ virtual CapsStorage* getCapsStorage() const;
+ virtual RosterStorage* getRosterStorage() const;
+ virtual HistoryStorage* getHistoryStorage() const;
- private:
- VCardMemoryStorage* vcardStorage;
- AvatarStorage* avatarStorage;
- CapsStorage* capsStorage;
- RosterStorage* rosterStorage;
- HistoryStorage* historyStorage;
- };
+ private:
+ VCardMemoryStorage* vcardStorage;
+ AvatarStorage* avatarStorage;
+ CapsStorage* capsStorage;
+ RosterStorage* rosterStorage;
+ HistoryStorage* historyStorage;
+ };
}
diff --git a/Swiften/Client/NickManager.h b/Swiften/Client/NickManager.h
index f05c122..4769bad 100644
--- a/Swiften/Client/NickManager.h
+++ b/Swiften/Client/NickManager.h
@@ -12,13 +12,13 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class SWIFTEN_API NickManager {
- public:
- virtual ~NickManager();
+ class SWIFTEN_API NickManager {
+ public:
+ virtual ~NickManager();
- virtual std::string getOwnNick() const = 0;
- virtual void setOwnNick(const std::string& nick) = 0;
+ virtual std::string getOwnNick() const = 0;
+ virtual void setOwnNick(const std::string& nick) = 0;
- boost::signal<void (const std::string&)> onOwnNickChanged;
- };
+ boost::signal<void (const std::string&)> onOwnNickChanged;
+ };
}
diff --git a/Swiften/Client/NickManagerImpl.cpp b/Swiften/Client/NickManagerImpl.cpp
index f755424..f8fef39 100644
--- a/Swiften/Client/NickManagerImpl.cpp
+++ b/Swiften/Client/NickManagerImpl.cpp
@@ -13,38 +13,38 @@
namespace Swift {
NickManagerImpl::NickManagerImpl(const JID& ownJID, VCardManager* vcardManager) : ownJID(ownJID), vcardManager(vcardManager) {
- vcardManager->onVCardChanged.connect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2));
+ vcardManager->onVCardChanged.connect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2));
- updateOwnNickFromVCard(vcardManager->getVCard(ownJID.toBare()));
+ updateOwnNickFromVCard(vcardManager->getVCard(ownJID.toBare()));
}
NickManagerImpl::~NickManagerImpl() {
- vcardManager->onVCardChanged.disconnect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2));
+ vcardManager->onVCardChanged.disconnect(boost::bind(&NickManagerImpl::handleVCardReceived, this, _1, _2));
}
std::string NickManagerImpl::getOwnNick() const {
- return ownNick;
+ return ownNick;
}
void NickManagerImpl::setOwnNick(const std::string&) {
}
void NickManagerImpl::handleVCardReceived(const JID& jid, VCard::ref vcard) {
- if (!jid.equals(ownJID, JID::WithoutResource)) {
- return;
- }
- updateOwnNickFromVCard(vcard);
+ if (!jid.equals(ownJID, JID::WithoutResource)) {
+ return;
+ }
+ updateOwnNickFromVCard(vcard);
}
void NickManagerImpl::updateOwnNickFromVCard(VCard::ref vcard) {
- std::string nick;
- if (vcard && !vcard->getNickname().empty()) {
- nick = vcard->getNickname();
- }
- if (ownNick != nick) {
- ownNick = nick;
- onOwnNickChanged(ownNick);
- }
+ std::string nick;
+ if (vcard && !vcard->getNickname().empty()) {
+ nick = vcard->getNickname();
+ }
+ if (ownNick != nick) {
+ ownNick = nick;
+ onOwnNickChanged(ownNick);
+ }
}
}
diff --git a/Swiften/Client/NickManagerImpl.h b/Swiften/Client/NickManagerImpl.h
index 51a8624..a413378 100644
--- a/Swiften/Client/NickManagerImpl.h
+++ b/Swiften/Client/NickManagerImpl.h
@@ -13,23 +13,23 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class VCardManager;
+ class VCardManager;
- class NickManagerImpl : public NickManager {
- public:
- NickManagerImpl(const JID& ownJID, VCardManager* vcardManager);
- virtual ~NickManagerImpl();
+ class NickManagerImpl : public NickManager {
+ public:
+ NickManagerImpl(const JID& ownJID, VCardManager* vcardManager);
+ virtual ~NickManagerImpl();
- std::string getOwnNick() const;
- void setOwnNick(const std::string& nick);
+ std::string getOwnNick() const;
+ void setOwnNick(const std::string& nick);
- private:
- void handleVCardReceived(const JID& jid, VCard::ref vCard);
- void updateOwnNickFromVCard(VCard::ref vcard);
+ private:
+ void handleVCardReceived(const JID& jid, VCard::ref vCard);
+ void updateOwnNickFromVCard(VCard::ref vcard);
- private:
- JID ownJID;
- VCardManager* vcardManager;
- std::string ownNick;
- };
+ private:
+ JID ownJID;
+ VCardManager* vcardManager;
+ std::string ownNick;
+ };
}
diff --git a/Swiften/Client/NickResolver.cpp b/Swiften/Client/NickResolver.cpp
index 4136a42..c424447 100644
--- a/Swiften/Client/NickResolver.cpp
+++ b/Swiften/Client/NickResolver.cpp
@@ -21,59 +21,59 @@
namespace Swift {
NickResolver::NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry) : ownJID_(ownJID) {
- xmppRoster_ = xmppRoster;
- vcardManager_ = vcardManager;
- if (vcardManager_) {
- vcardManager_->onVCardChanged.connect(boost::bind(&NickResolver::handleVCardReceived, this, _1, _2));
- }
- mucRegistry_ = mucRegistry;
- xmppRoster_->onJIDUpdated.connect(boost::bind(&NickResolver::handleJIDUpdated, this, _1, _2, _3));
- xmppRoster_->onJIDAdded.connect(boost::bind(&NickResolver::handleJIDAdded, this, _1));
+ xmppRoster_ = xmppRoster;
+ vcardManager_ = vcardManager;
+ if (vcardManager_) {
+ vcardManager_->onVCardChanged.connect(boost::bind(&NickResolver::handleVCardReceived, this, _1, _2));
+ }
+ mucRegistry_ = mucRegistry;
+ xmppRoster_->onJIDUpdated.connect(boost::bind(&NickResolver::handleJIDUpdated, this, _1, _2, _3));
+ xmppRoster_->onJIDAdded.connect(boost::bind(&NickResolver::handleJIDAdded, this, _1));
}
void NickResolver::handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& /*groups*/) {
- onNickChanged(jid, previousNick);
+ onNickChanged(jid, previousNick);
}
void NickResolver::handleJIDAdded(const JID& jid) {
- std::string oldNick(jidToNick(jid));
- onNickChanged(jid, oldNick);
+ std::string oldNick(jidToNick(jid));
+ onNickChanged(jid, oldNick);
}
std::string NickResolver::jidToNick(const JID& jid) {
- if (jid.toBare() == ownJID_) {
- if (!ownNick_.empty()) {
- return ownNick_;
- }
- }
- std::string nick;
+ if (jid.toBare() == ownJID_) {
+ if (!ownNick_.empty()) {
+ return ownNick_;
+ }
+ }
+ std::string nick;
- if (mucRegistry_ && mucRegistry_->isMUC(jid.toBare()) ) {
- return jid.getResource().empty() ? jid.toBare().toString() : jid.getResource();
- }
+ if (mucRegistry_ && mucRegistry_->isMUC(jid.toBare()) ) {
+ return jid.getResource().empty() ? jid.toBare().toString() : jid.getResource();
+ }
- if (xmppRoster_->containsJID(jid) && !xmppRoster_->getNameForJID(jid).empty()) {
- return xmppRoster_->getNameForJID(jid);
- }
+ if (xmppRoster_->containsJID(jid) && !xmppRoster_->getNameForJID(jid).empty()) {
+ return xmppRoster_->getNameForJID(jid);
+ }
- return jid.toBare();
+ return jid.toBare();
}
void NickResolver::handleVCardReceived(const JID& jid, VCard::ref ownVCard) {
- if (!jid.equals(ownJID_, JID::WithoutResource)) {
- return;
- }
- std::string initialNick = ownNick_;
- ownNick_ = ownJID_.toString();
- if (ownVCard) {
- if (!ownVCard->getNickname().empty()) {
- ownNick_ = ownVCard->getNickname();
- } else if (!ownVCard->getGivenName().empty()) {
- ownNick_ = ownVCard->getGivenName();
- } else if (!ownVCard->getFullName().empty()) {
- ownNick_ = ownVCard->getFullName();
- }
- }
+ if (!jid.equals(ownJID_, JID::WithoutResource)) {
+ return;
+ }
+ std::string initialNick = ownNick_;
+ ownNick_ = ownJID_.toString();
+ if (ownVCard) {
+ if (!ownVCard->getNickname().empty()) {
+ ownNick_ = ownVCard->getNickname();
+ } else if (!ownVCard->getGivenName().empty()) {
+ ownNick_ = ownVCard->getGivenName();
+ } else if (!ownVCard->getFullName().empty()) {
+ ownNick_ = ownVCard->getFullName();
+ }
+ }
}
}
diff --git a/Swiften/Client/NickResolver.h b/Swiften/Client/NickResolver.h
index c3e6f05..b187796 100644
--- a/Swiften/Client/NickResolver.h
+++ b/Swiften/Client/NickResolver.h
@@ -17,28 +17,28 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class XMPPRoster;
- class MUCRegistry;
- class VCardManager;
-
- class SWIFTEN_API NickResolver {
- public:
- NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry);
-
- std::string jidToNick(const JID& jid);
-
- boost::signal<void (const JID&, const std::string& /*previousNick*/)> onNickChanged;
-
- private:
- void handleVCardReceived(const JID& jid, VCard::ref vCard);
- void handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& groups);
- void handleJIDAdded(const JID& jid);
-
- private:
- JID ownJID_;
- std::string ownNick_;
- XMPPRoster* xmppRoster_;
- MUCRegistry* mucRegistry_;
- VCardManager* vcardManager_;
- };
+ class XMPPRoster;
+ class MUCRegistry;
+ class VCardManager;
+
+ class SWIFTEN_API NickResolver {
+ public:
+ NickResolver(const JID& ownJID, XMPPRoster* xmppRoster, VCardManager* vcardManager, MUCRegistry* mucRegistry);
+
+ std::string jidToNick(const JID& jid);
+
+ boost::signal<void (const JID&, const std::string& /*previousNick*/)> onNickChanged;
+
+ private:
+ void handleVCardReceived(const JID& jid, VCard::ref vCard);
+ void handleJIDUpdated(const JID& jid, const std::string& previousNick, const std::vector<std::string>& groups);
+ void handleJIDAdded(const JID& jid);
+
+ private:
+ JID ownJID_;
+ std::string ownNick_;
+ XMPPRoster* xmppRoster_;
+ MUCRegistry* mucRegistry_;
+ VCardManager* vcardManager_;
+ };
}
diff --git a/Swiften/Client/StanzaChannel.h b/Swiften/Client/StanzaChannel.h
index bf81c6a..ec36634 100644
--- a/Swiften/Client/StanzaChannel.h
+++ b/Swiften/Client/StanzaChannel.h
@@ -16,17 +16,17 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class SWIFTEN_API StanzaChannel : public IQChannel {
- public:
- virtual void sendMessage(boost::shared_ptr<Message>) = 0;
- virtual void sendPresence(boost::shared_ptr<Presence>) = 0;
- virtual bool isAvailable() const = 0;
- virtual bool getStreamManagementEnabled() const = 0;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
+ class SWIFTEN_API StanzaChannel : public IQChannel {
+ public:
+ virtual void sendMessage(boost::shared_ptr<Message>) = 0;
+ virtual void sendPresence(boost::shared_ptr<Presence>) = 0;
+ virtual bool isAvailable() const = 0;
+ virtual bool getStreamManagementEnabled() const = 0;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
- boost::signal<void (bool /* isAvailable */)> onAvailableChanged;
- boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
- boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
- };
+ boost::signal<void (bool /* isAvailable */)> onAvailableChanged;
+ boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
+ boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
+ };
}
diff --git a/Swiften/Client/Storages.h b/Swiften/Client/Storages.h
index 3187cf7..9485831 100644
--- a/Swiften/Client/Storages.h
+++ b/Swiften/Client/Storages.h
@@ -9,24 +9,24 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class VCardStorage;
- class AvatarStorage;
- class CapsStorage;
- class RosterStorage;
- class HistoryStorage;
+ class VCardStorage;
+ class AvatarStorage;
+ class CapsStorage;
+ class RosterStorage;
+ class HistoryStorage;
- /**
- * An interface to hold storage classes for different
- * controllers.
- */
- class SWIFTEN_API Storages {
- public:
- virtual ~Storages();
+ /**
+ * An interface to hold storage classes for different
+ * controllers.
+ */
+ class SWIFTEN_API Storages {
+ public:
+ virtual ~Storages();
- virtual VCardStorage* getVCardStorage() const = 0;
- virtual AvatarStorage* getAvatarStorage() const = 0;
- virtual CapsStorage* getCapsStorage() const = 0;
- virtual RosterStorage* getRosterStorage() const = 0;
- virtual HistoryStorage* getHistoryStorage() const = 0;
- };
+ virtual VCardStorage* getVCardStorage() const = 0;
+ virtual AvatarStorage* getAvatarStorage() const = 0;
+ virtual CapsStorage* getCapsStorage() const = 0;
+ virtual RosterStorage* getRosterStorage() const = 0;
+ virtual HistoryStorage* getHistoryStorage() const = 0;
+ };
}
diff --git a/Swiften/Client/UnitTest/BlockListImplTest.cpp b/Swiften/Client/UnitTest/BlockListImplTest.cpp
index 9e5bc1a..0502f46 100644
--- a/Swiften/Client/UnitTest/BlockListImplTest.cpp
+++ b/Swiften/Client/UnitTest/BlockListImplTest.cpp
@@ -17,75 +17,75 @@
using namespace Swift;
class BlockListImplTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BlockListImplTest);
- CPPUNIT_TEST(testSetItemsToSubset);
- CPPUNIT_TEST(testSetItemsToSuperset);
- CPPUNIT_TEST(testSetItemsAllDifferent);
- CPPUNIT_TEST_SUITE_END();
-
- public:
-
- void testSetItemsToSubset() {
- std::vector<JID> subset;
- subset.push_back(JID("a@example.com"));
-
- blockList_->setItems(subset);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), addedJIDs_.size());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), removedJIDs_.size());
- }
-
- void testSetItemsToSuperset() {
- std::vector<JID> superset;
- superset.push_back(JID("a@example.com"));
- superset.push_back(JID("b@example.com"));
- superset.push_back(JID("c@example.com"));
-
- blockList_->setItems(superset);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), addedJIDs_.size());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), removedJIDs_.size());
- }
-
- void testSetItemsAllDifferent() {
- std::vector<JID> newBlockList;
- newBlockList.push_back(JID("x@example.com"));
- newBlockList.push_back(JID("y@example.com"));
- newBlockList.push_back(JID("z@example.com"));
-
- blockList_->setItems(newBlockList);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), addedJIDs_.size());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), removedJIDs_.size());
- }
-
- void setUp() {
- blockList_ = boost::make_shared<BlockListImpl>();
- addedJIDs_.clear();
- removedJIDs_.clear();
- blockList_->addItem(JID("a@example.com"));
- blockList_->addItem(JID("b@example.com"));
-
- blockList_->onItemAdded.connect(boost::bind(&BlockListImplTest::handleBlockListItemAdded, this, _1));
- blockList_->onItemRemoved.connect(boost::bind(&BlockListImplTest::handleBlockListItemRemoved, this, _1));
- }
-
- void tearDown() {
- blockList_.reset();
- }
-
- void handleBlockListItemAdded(const JID& jid) {
- addedJIDs_.push_back(jid);
- }
-
- void handleBlockListItemRemoved(const JID& jid) {
- removedJIDs_.push_back(jid);
- }
-
- private:
- boost::shared_ptr<BlockListImpl> blockList_;
- std::vector<JID> addedJIDs_;
- std::vector<JID> removedJIDs_;
+ CPPUNIT_TEST_SUITE(BlockListImplTest);
+ CPPUNIT_TEST(testSetItemsToSubset);
+ CPPUNIT_TEST(testSetItemsToSuperset);
+ CPPUNIT_TEST(testSetItemsAllDifferent);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+
+ void testSetItemsToSubset() {
+ std::vector<JID> subset;
+ subset.push_back(JID("a@example.com"));
+
+ blockList_->setItems(subset);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), addedJIDs_.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), removedJIDs_.size());
+ }
+
+ void testSetItemsToSuperset() {
+ std::vector<JID> superset;
+ superset.push_back(JID("a@example.com"));
+ superset.push_back(JID("b@example.com"));
+ superset.push_back(JID("c@example.com"));
+
+ blockList_->setItems(superset);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), addedJIDs_.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), removedJIDs_.size());
+ }
+
+ void testSetItemsAllDifferent() {
+ std::vector<JID> newBlockList;
+ newBlockList.push_back(JID("x@example.com"));
+ newBlockList.push_back(JID("y@example.com"));
+ newBlockList.push_back(JID("z@example.com"));
+
+ blockList_->setItems(newBlockList);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), addedJIDs_.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), removedJIDs_.size());
+ }
+
+ void setUp() {
+ blockList_ = boost::make_shared<BlockListImpl>();
+ addedJIDs_.clear();
+ removedJIDs_.clear();
+ blockList_->addItem(JID("a@example.com"));
+ blockList_->addItem(JID("b@example.com"));
+
+ blockList_->onItemAdded.connect(boost::bind(&BlockListImplTest::handleBlockListItemAdded, this, _1));
+ blockList_->onItemRemoved.connect(boost::bind(&BlockListImplTest::handleBlockListItemRemoved, this, _1));
+ }
+
+ void tearDown() {
+ blockList_.reset();
+ }
+
+ void handleBlockListItemAdded(const JID& jid) {
+ addedJIDs_.push_back(jid);
+ }
+
+ void handleBlockListItemRemoved(const JID& jid) {
+ removedJIDs_.push_back(jid);
+ }
+
+ private:
+ boost::shared_ptr<BlockListImpl> blockList_;
+ std::vector<JID> addedJIDs_;
+ std::vector<JID> removedJIDs_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(BlockListImplTest);
diff --git a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
index 53c39b5..ef2f537 100644
--- a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
+++ b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
@@ -25,170 +25,170 @@
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);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
- }
-
- void testBlockCommand() {
- // start with an already fetched block list
- helperInitialBlockListFetch(std::vector<JID>(1, JID("iago@shakespeare.lit")));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size());
- CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
-
- GenericRequest<BlockPayload>::ref blockRequest = clientBlockListManager_->createBlockJIDRequest(JID("romeo@montague.net"));
- blockRequest->send();
- IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
- CPPUNIT_ASSERT(request.get() != NULL);
- boost::shared_ptr<BlockPayload> blockPayload = request->getPayload<BlockPayload>();
- CPPUNIT_ASSERT(blockPayload.get() != NULL);
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), blockPayload->getItems().at(0));
-
- IQ::ref blockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
- stanzaChannel_->sendIQ(blockRequestResponse);
- stanzaChannel_->onIQReceived(blockRequestResponse);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size());
-
- // send block push
- boost::shared_ptr<BlockPayload> pushPayload = boost::make_shared<BlockPayload>();
- pushPayload->addItem(JID("romeo@montague.net"));
- IQ::ref blockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
- stanzaChannel_->sendIQ(blockPush);
- stanzaChannel_->onIQReceived(blockPush);
-
- std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems();
- CPPUNIT_ASSERT(blockedJIDs.end() != std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net")));
- }
-
- void testUnblockCommand() {
- // start with an already fetched block list
- std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit"));
- initialBlockList.push_back(JID("romeo@montague.net"));
- helperInitialBlockListFetch(initialBlockList);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
- CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
-
- GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockJIDRequest(JID("romeo@montague.net"));
- unblockRequest->send();
- IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
- CPPUNIT_ASSERT(request.get() != NULL);
- boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
- CPPUNIT_ASSERT(unblockPayload.get() != NULL);
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), unblockPayload->getItems().at(0));
-
- IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
- stanzaChannel_->sendIQ(unblockRequestResponse);
- stanzaChannel_->onIQReceived(unblockRequestResponse);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
-
- // send block push
- boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>();
- pushPayload->addItem(JID("romeo@montague.net"));
- IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
- stanzaChannel_->sendIQ(unblockPush);
- stanzaChannel_->onIQReceived(unblockPush);
-
- std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems();
- CPPUNIT_ASSERT(blockedJIDs.end() == std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net")));
- }
-
- void testUnblockAllCommand() {
- // start with an already fetched block list
- std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit"));
- initialBlockList.push_back(JID("romeo@montague.net"));
- initialBlockList.push_back(JID("benvolio@montague.net"));
- helperInitialBlockListFetch(initialBlockList);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size());
- CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
-
- GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockAllRequest();
- unblockRequest->send();
- IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
- CPPUNIT_ASSERT(request.get() != NULL);
- boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
- CPPUNIT_ASSERT(unblockPayload.get() != NULL);
- CPPUNIT_ASSERT_EQUAL(true, unblockPayload->getItems().empty());
-
- IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
- stanzaChannel_->sendIQ(unblockRequestResponse);
- stanzaChannel_->onIQReceived(unblockRequestResponse);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size());
-
- // send block push
- boost::shared_ptr<UnblockPayload> pushPayload = boost::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) {
- boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
- CPPUNIT_ASSERT(blockList);
-
- // check for IQ request
- IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0);
- CPPUNIT_ASSERT(request.get() != NULL);
- boost::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>();
- CPPUNIT_ASSERT(requestPayload.get() != NULL);
-
- CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState());
- CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState());
-
- // build IQ response
- boost::shared_ptr<BlockListPayload> responsePayload = boost::make_shared<BlockListPayload>();
- foreach(const JID& 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(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);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
+ }
+
+ void testBlockCommand() {
+ // start with an already fetched block list
+ helperInitialBlockListFetch(std::vector<JID>(1, JID("iago@shakespeare.lit")));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
+
+ GenericRequest<BlockPayload>::ref blockRequest = clientBlockListManager_->createBlockJIDRequest(JID("romeo@montague.net"));
+ blockRequest->send();
+ IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
+ CPPUNIT_ASSERT(request.get() != NULL);
+ boost::shared_ptr<BlockPayload> blockPayload = request->getPayload<BlockPayload>();
+ CPPUNIT_ASSERT(blockPayload.get() != NULL);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), blockPayload->getItems().at(0));
+
+ IQ::ref blockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
+ stanzaChannel_->sendIQ(blockRequestResponse);
+ stanzaChannel_->onIQReceived(blockRequestResponse);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), clientBlockListManager_->getBlockList()->getItems().size());
+
+ // send block push
+ boost::shared_ptr<BlockPayload> pushPayload = boost::make_shared<BlockPayload>();
+ pushPayload->addItem(JID("romeo@montague.net"));
+ IQ::ref blockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
+ stanzaChannel_->sendIQ(blockPush);
+ stanzaChannel_->onIQReceived(blockPush);
+
+ std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems();
+ CPPUNIT_ASSERT(blockedJIDs.end() != std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net")));
+ }
+
+ void testUnblockCommand() {
+ // start with an already fetched block list
+ std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit"));
+ initialBlockList.push_back(JID("romeo@montague.net"));
+ helperInitialBlockListFetch(initialBlockList);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
+
+ GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockJIDRequest(JID("romeo@montague.net"));
+ unblockRequest->send();
+ IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
+ CPPUNIT_ASSERT(request.get() != NULL);
+ boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
+ CPPUNIT_ASSERT(unblockPayload.get() != NULL);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), unblockPayload->getItems().at(0));
+
+ IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
+ stanzaChannel_->sendIQ(unblockRequestResponse);
+ stanzaChannel_->onIQReceived(unblockRequestResponse);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), clientBlockListManager_->getBlockList()->getItems().size());
+
+ // send block push
+ boost::shared_ptr<UnblockPayload> pushPayload = boost::make_shared<UnblockPayload>();
+ pushPayload->addItem(JID("romeo@montague.net"));
+ IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
+ stanzaChannel_->sendIQ(unblockPush);
+ stanzaChannel_->onIQReceived(unblockPush);
+
+ std::vector<JID> blockedJIDs = clientBlockListManager_->getBlockList()->getItems();
+ CPPUNIT_ASSERT(blockedJIDs.end() == std::find(blockedJIDs.begin(), blockedJIDs.end(), JID("romeo@montague.net")));
+ }
+
+ void testUnblockAllCommand() {
+ // start with an already fetched block list
+ std::vector<JID> initialBlockList = std::vector<JID>(1, JID("iago@shakespeare.lit"));
+ initialBlockList.push_back(JID("romeo@montague.net"));
+ initialBlockList.push_back(JID("benvolio@montague.net"));
+ helperInitialBlockListFetch(initialBlockList);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
+
+ GenericRequest<UnblockPayload>::ref unblockRequest = clientBlockListManager_->createUnblockAllRequest();
+ unblockRequest->send();
+ IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(2);
+ CPPUNIT_ASSERT(request.get() != NULL);
+ boost::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
+ CPPUNIT_ASSERT(unblockPayload.get() != NULL);
+ CPPUNIT_ASSERT_EQUAL(true, unblockPayload->getItems().empty());
+
+ IQ::ref unblockRequestResponse = IQ::createResult(request->getFrom(), JID(), request->getID());
+ stanzaChannel_->sendIQ(unblockRequestResponse);
+ stanzaChannel_->onIQReceived(unblockRequestResponse);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), clientBlockListManager_->getBlockList()->getItems().size());
+
+ // send block push
+ boost::shared_ptr<UnblockPayload> pushPayload = boost::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) {
+ boost::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
+ CPPUNIT_ASSERT(blockList);
+
+ // check for IQ request
+ IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0);
+ CPPUNIT_ASSERT(request.get() != NULL);
+ boost::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>();
+ CPPUNIT_ASSERT(requestPayload.get() != NULL);
+
+ CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState());
+ CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState());
+
+ // build IQ response
+ boost::shared_ptr<BlockListPayload> responsePayload = boost::make_shared<BlockListPayload>();
+ foreach(const JID& 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/UnitTest/ClientSessionTest.cpp b/Swiften/Client/UnitTest/ClientSessionTest.cpp
index 396edf6..335b537 100644
--- a/Swiften/Client/UnitTest/ClientSessionTest.cpp
+++ b/Swiften/Client/UnitTest/ClientSessionTest.cpp
@@ -41,789 +41,789 @@
using namespace Swift;
class ClientSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ClientSessionTest);
- CPPUNIT_TEST(testStart_Error);
- CPPUNIT_TEST(testStart_StreamError);
- CPPUNIT_TEST(testStartTLS);
- CPPUNIT_TEST(testStartTLS_ServerError);
- CPPUNIT_TEST(testStartTLS_ConnectError);
- CPPUNIT_TEST(testStartTLS_InvalidIdentity);
- CPPUNIT_TEST(testStart_StreamFeaturesWithoutResourceBindingFails);
- CPPUNIT_TEST(testAuthenticate);
- CPPUNIT_TEST(testAuthenticate_Unauthorized);
- CPPUNIT_TEST(testAuthenticate_NoValidAuthMechanisms);
- CPPUNIT_TEST(testAuthenticate_PLAINOverNonTLS);
- CPPUNIT_TEST(testAuthenticate_RequireTLS);
- CPPUNIT_TEST(testAuthenticate_EXTERNAL);
- CPPUNIT_TEST(testStreamManagement);
- CPPUNIT_TEST(testStreamManagement_Failed);
- CPPUNIT_TEST(testUnexpectedChallenge);
- CPPUNIT_TEST(testFinishAcksStanzas);
- /*
- CPPUNIT_TEST(testResourceBind);
- CPPUNIT_TEST(testResourceBind_ChangeResource);
- CPPUNIT_TEST(testResourceBind_EmptyResource);
- CPPUNIT_TEST(testResourceBind_Error);
- CPPUNIT_TEST(testSessionStart);
- CPPUNIT_TEST(testSessionStart_Error);
- CPPUNIT_TEST(testSessionStart_AfterResourceBind);
- CPPUNIT_TEST(testWhitespacePing);
- CPPUNIT_TEST(testReceiveElementAfterSessionStarted);
- CPPUNIT_TEST(testSendElement);
- */
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
- server = boost::make_shared<MockSessionStream>();
- sessionFinishedReceived = false;
- needCredentials = false;
- blindCertificateTrustChecker = new BlindCertificateTrustChecker();
- }
-
- void tearDown() {
- delete blindCertificateTrustChecker;
- }
-
- void testStart_Error() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->breakConnection();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStart_StreamError() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->sendStreamStart();
- server->sendStreamError();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStartTLS() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->setCertificateTrustChecker(blindCertificateTrustChecker);
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithStartTLS();
- server->receiveStartTLS();
- CPPUNIT_ASSERT(!server->tlsEncrypted);
- server->sendTLSProceed();
- CPPUNIT_ASSERT(server->tlsEncrypted);
- server->onTLSEncrypted();
- server->receiveStreamStart();
- server->sendStreamStart();
-
- session->finish();
- }
-
- void testStartTLS_ServerError() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithStartTLS();
- server->receiveStartTLS();
- server->sendTLSFailure();
-
- CPPUNIT_ASSERT(!server->tlsEncrypted);
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStartTLS_ConnectError() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithStartTLS();
- server->receiveStartTLS();
- server->sendTLSProceed();
- server->breakTLS();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStartTLS_InvalidIdentity() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithStartTLS();
- server->receiveStartTLS();
- CPPUNIT_ASSERT(!server->tlsEncrypted);
- server->sendTLSProceed();
- CPPUNIT_ASSERT(server->tlsEncrypted);
- server->onTLSEncrypted();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidServerIdentity, boost::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError)->getType());
- }
-
- void testStart_StreamFeaturesWithoutResourceBindingFails() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendEmptyStreamFeatures();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testAuthenticate() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
- CPPUNIT_ASSERT(needCredentials);
- CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
- session->sendCredentials(createSafeByteArray("mypass"));
- server->receiveAuthRequest("PLAIN");
- server->sendAuthSuccess();
- server->receiveStreamStart();
-
- session->finish();
- }
-
- void testAuthenticate_Unauthorized() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
- CPPUNIT_ASSERT(needCredentials);
- CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
- session->sendCredentials(createSafeByteArray("mypass"));
- server->receiveAuthRequest("PLAIN");
- server->sendAuthFailure();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testAuthenticate_PLAINOverNonTLS() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->setAllowPLAINOverNonTLS(false);
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testAuthenticate_RequireTLS() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->setUseTLS(ClientSession::RequireTLS);
- session->setAllowPLAINOverNonTLS(true);
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithMultipleAuthentication();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testAuthenticate_NoValidAuthMechanisms() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithUnknownAuthentication();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testAuthenticate_EXTERNAL() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithEXTERNALAuthentication();
- server->receiveAuthRequest("EXTERNAL");
- server->sendAuthSuccess();
- server->receiveStreamStart();
-
- session->finish();
- }
-
- void testUnexpectedChallenge() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithEXTERNALAuthentication();
- server->receiveAuthRequest("EXTERNAL");
- server->sendChallenge();
- server->sendChallenge();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStreamManagement() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
- session->sendCredentials(createSafeByteArray("mypass"));
- server->receiveAuthRequest("PLAIN");
- server->sendAuthSuccess();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithBindAndStreamManagement();
- server->receiveBind();
- server->sendBindResult();
- server->receiveStreamManagementEnable();
- server->sendStreamManagementEnabled();
-
- CPPUNIT_ASSERT(session->getStreamManagementEnabled());
- // TODO: Test if the requesters & responders do their work
- CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState());
-
- session->finish();
- }
-
- void testStreamManagement_Failed() {
- boost::shared_ptr<ClientSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
- session->sendCredentials(createSafeByteArray("mypass"));
- server->receiveAuthRequest("PLAIN");
- server->sendAuthSuccess();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithBindAndStreamManagement();
- server->receiveBind();
- server->sendBindResult();
- server->receiveStreamManagementEnable();
- server->sendStreamManagementFailed();
-
- CPPUNIT_ASSERT(!session->getStreamManagementEnabled());
- CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState());
-
- session->finish();
- }
-
- void testFinishAcksStanzas() {
- boost::shared_ptr<ClientSession> session(createSession());
- initializeSession(session);
- server->sendMessage();
- server->sendMessage();
- server->sendMessage();
-
- session->finish();
-
- server->receiveAck(3);
- }
-
- private:
- boost::shared_ptr<ClientSession> createSession() {
- boost::shared_ptr<ClientSession> session = ClientSession::create(JID("me@foo.com"), server, idnConverter.get(), crypto.get());
- session->onFinished.connect(boost::bind(&ClientSessionTest::handleSessionFinished, this, _1));
- session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::handleSessionNeedCredentials, this));
- session->setAllowPLAINOverNonTLS(true);
- return session;
- }
-
- void initializeSession(boost::shared_ptr<ClientSession> session) {
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithPLAINAuthentication();
- session->sendCredentials(createSafeByteArray("mypass"));
- server->receiveAuthRequest("PLAIN");
- server->sendAuthSuccess();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->sendStreamFeaturesWithBindAndStreamManagement();
- server->receiveBind();
- server->sendBindResult();
- server->receiveStreamManagementEnable();
- server->sendStreamManagementEnabled();
- }
-
- void handleSessionFinished(boost::shared_ptr<Error> error) {
- sessionFinishedReceived = true;
- sessionFinishedError = error;
- }
-
- void handleSessionNeedCredentials() {
- needCredentials = true;
- }
-
- class MockSessionStream : public SessionStream {
- public:
- struct Event {
- Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
- Event(const ProtocolHeader& header) : header(header), footer(false) {}
- Event() : footer(true) {}
-
- boost::shared_ptr<ToplevelElement> element;
- boost::optional<ProtocolHeader> header;
- bool footer;
- };
-
- MockSessionStream() : available(true), canTLSEncrypt(true), tlsEncrypted(false), compressed(false), whitespacePingEnabled(false), resetCount(0) {
- }
-
- virtual void close() {
- onClosed(boost::shared_ptr<Error>());
- }
-
- virtual bool isOpen() {
- return available;
- }
-
- virtual void writeHeader(const ProtocolHeader& header) {
- receivedEvents.push_back(Event(header));
- }
-
- virtual void writeFooter() {
- receivedEvents.push_back(Event());
- }
-
- virtual void writeElement(boost::shared_ptr<ToplevelElement> element) {
- receivedEvents.push_back(Event(element));
- }
-
- virtual void writeData(const std::string&) {
- }
-
- virtual bool supportsTLSEncryption() {
- return canTLSEncrypt;
- }
-
- virtual void addTLSEncryption() {
- tlsEncrypted = true;
- }
-
- virtual bool isTLSEncrypted() {
- return tlsEncrypted;
- }
-
- virtual ByteArray getTLSFinishMessage() const {
- return ByteArray();
- }
-
- virtual Certificate::ref getPeerCertificate() const {
- return Certificate::ref(new SimpleCertificate());
- }
-
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const {
- return std::vector<Certificate::ref>();
- }
-
- virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
- return boost::shared_ptr<CertificateVerificationError>();
- }
-
- virtual bool supportsZLibCompression() {
- return true;
- }
-
- virtual void addZLibCompression() {
- compressed = true;
- }
-
- virtual void setWhitespacePingEnabled(bool enabled) {
- whitespacePingEnabled = enabled;
- }
-
- virtual void resetXMPPParser() {
- resetCount++;
- }
-
- void breakConnection() {
- onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError));
- }
-
- void breakTLS() {
- onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::TLSError));
- }
-
-
- void sendStreamStart() {
- ProtocolHeader header;
- header.setTo("foo.com");
- return onStreamStartReceived(header);
- }
-
- void sendStreamFeaturesWithStartTLS() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->setHasStartTLS();
- onElementReceived(streamFeatures);
- }
-
- void sendChallenge() {
- onElementReceived(boost::make_shared<AuthChallenge>());
- }
-
- void sendStreamError() {
- onElementReceived(boost::make_shared<StreamError>());
- }
-
- void sendTLSProceed() {
- onElementReceived(boost::make_shared<TLSProceed>());
- }
-
- void sendTLSFailure() {
- onElementReceived(boost::make_shared<StartTLSFailure>());
- }
-
- void sendStreamFeaturesWithMultipleAuthentication() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->addAuthenticationMechanism("PLAIN");
- streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
- streamFeatures->addAuthenticationMechanism("SCRAM-SHA1");
- onElementReceived(streamFeatures);
- }
-
- void sendStreamFeaturesWithPLAINAuthentication() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->addAuthenticationMechanism("PLAIN");
- onElementReceived(streamFeatures);
- }
-
- void sendStreamFeaturesWithEXTERNALAuthentication() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->addAuthenticationMechanism("EXTERNAL");
- onElementReceived(streamFeatures);
- }
-
- void sendStreamFeaturesWithUnknownAuthentication() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->addAuthenticationMechanism("UNKNOWN");
- onElementReceived(streamFeatures);
- }
-
- void sendStreamFeaturesWithBindAndStreamManagement() {
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->setHasResourceBind();
- streamFeatures->setHasStreamManagement();
- onElementReceived(streamFeatures);
- }
-
- void sendEmptyStreamFeatures() {
- onElementReceived(boost::make_shared<StreamFeatures>());
- }
-
- void sendAuthSuccess() {
- onElementReceived(boost::make_shared<AuthSuccess>());
- }
-
- void sendAuthFailure() {
- onElementReceived(boost::make_shared<AuthFailure>());
- }
-
- void sendStreamManagementEnabled() {
- onElementReceived(boost::make_shared<StreamManagementEnabled>());
- }
-
- void sendStreamManagementFailed() {
- onElementReceived(boost::make_shared<StreamManagementFailed>());
- }
-
- void sendBindResult() {
- boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
- resourceBind->setJID(JID("foo@bar.com/bla"));
- boost::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind);
- onElementReceived(iq);
- }
-
- void sendMessage() {
- boost::shared_ptr<Message> message = boost::make_shared<Message>();
- message->setTo(JID("foo@bar.com/bla"));
- onElementReceived(message);
- }
-
- void receiveStreamStart() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.header);
- }
-
- void receiveStartTLS() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<StartTLSRequest>(event.element));
- }
-
- void receiveAuthRequest(const std::string& mech) {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- boost::shared_ptr<AuthRequest> request(boost::dynamic_pointer_cast<AuthRequest>(event.element));
- CPPUNIT_ASSERT(request);
- CPPUNIT_ASSERT_EQUAL(mech, request->getMechanism());
- }
-
- void receiveStreamManagementEnable() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<EnableStreamManagement>(event.element));
- }
-
- void receiveBind() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(event.element);
- CPPUNIT_ASSERT(iq);
- CPPUNIT_ASSERT(iq->getPayload<ResourceBind>());
- bindID = iq->getID();
- }
-
- void receiveAck(unsigned int n) {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(event.element);
- CPPUNIT_ASSERT(ack);
- CPPUNIT_ASSERT_EQUAL(n, ack->getHandledStanzasCount());
- }
-
- Event popEvent() {
- CPPUNIT_ASSERT(!receivedEvents.empty());
- Event event = receivedEvents.front();
- receivedEvents.pop_front();
- return event;
- }
-
- bool available;
- bool canTLSEncrypt;
- bool tlsEncrypted;
- bool compressed;
- bool whitespacePingEnabled;
- std::string bindID;
- int resetCount;
- std::deque<Event> receivedEvents;
- };
-
- boost::shared_ptr<IDNConverter> idnConverter;
- boost::shared_ptr<MockSessionStream> server;
- bool sessionFinishedReceived;
- bool needCredentials;
- boost::shared_ptr<Error> sessionFinishedError;
- BlindCertificateTrustChecker* blindCertificateTrustChecker;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(ClientSessionTest);
+ CPPUNIT_TEST(testStart_Error);
+ CPPUNIT_TEST(testStart_StreamError);
+ CPPUNIT_TEST(testStartTLS);
+ CPPUNIT_TEST(testStartTLS_ServerError);
+ CPPUNIT_TEST(testStartTLS_ConnectError);
+ CPPUNIT_TEST(testStartTLS_InvalidIdentity);
+ CPPUNIT_TEST(testStart_StreamFeaturesWithoutResourceBindingFails);
+ CPPUNIT_TEST(testAuthenticate);
+ CPPUNIT_TEST(testAuthenticate_Unauthorized);
+ CPPUNIT_TEST(testAuthenticate_NoValidAuthMechanisms);
+ CPPUNIT_TEST(testAuthenticate_PLAINOverNonTLS);
+ CPPUNIT_TEST(testAuthenticate_RequireTLS);
+ CPPUNIT_TEST(testAuthenticate_EXTERNAL);
+ CPPUNIT_TEST(testStreamManagement);
+ CPPUNIT_TEST(testStreamManagement_Failed);
+ CPPUNIT_TEST(testUnexpectedChallenge);
+ CPPUNIT_TEST(testFinishAcksStanzas);
+ /*
+ CPPUNIT_TEST(testResourceBind);
+ CPPUNIT_TEST(testResourceBind_ChangeResource);
+ CPPUNIT_TEST(testResourceBind_EmptyResource);
+ CPPUNIT_TEST(testResourceBind_Error);
+ CPPUNIT_TEST(testSessionStart);
+ CPPUNIT_TEST(testSessionStart_Error);
+ CPPUNIT_TEST(testSessionStart_AfterResourceBind);
+ CPPUNIT_TEST(testWhitespacePing);
+ CPPUNIT_TEST(testReceiveElementAfterSessionStarted);
+ CPPUNIT_TEST(testSendElement);
+ */
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ server = boost::make_shared<MockSessionStream>();
+ sessionFinishedReceived = false;
+ needCredentials = false;
+ blindCertificateTrustChecker = new BlindCertificateTrustChecker();
+ }
+
+ void tearDown() {
+ delete blindCertificateTrustChecker;
+ }
+
+ void testStart_Error() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->breakConnection();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStart_StreamError() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->sendStreamStart();
+ server->sendStreamError();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->setCertificateTrustChecker(blindCertificateTrustChecker);
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithStartTLS();
+ server->receiveStartTLS();
+ CPPUNIT_ASSERT(!server->tlsEncrypted);
+ server->sendTLSProceed();
+ CPPUNIT_ASSERT(server->tlsEncrypted);
+ server->onTLSEncrypted();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+
+ session->finish();
+ }
+
+ void testStartTLS_ServerError() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithStartTLS();
+ server->receiveStartTLS();
+ server->sendTLSFailure();
+
+ CPPUNIT_ASSERT(!server->tlsEncrypted);
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS_ConnectError() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithStartTLS();
+ server->receiveStartTLS();
+ server->sendTLSProceed();
+ server->breakTLS();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS_InvalidIdentity() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithStartTLS();
+ server->receiveStartTLS();
+ CPPUNIT_ASSERT(!server->tlsEncrypted);
+ server->sendTLSProceed();
+ CPPUNIT_ASSERT(server->tlsEncrypted);
+ server->onTLSEncrypted();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidServerIdentity, boost::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError)->getType());
+ }
+
+ void testStart_StreamFeaturesWithoutResourceBindingFails() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendEmptyStreamFeatures();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ CPPUNIT_ASSERT(needCredentials);
+ CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+
+ session->finish();
+ }
+
+ void testAuthenticate_Unauthorized() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ CPPUNIT_ASSERT(needCredentials);
+ CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthFailure();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_PLAINOverNonTLS() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->setAllowPLAINOverNonTLS(false);
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_RequireTLS() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->setUseTLS(ClientSession::RequireTLS);
+ session->setAllowPLAINOverNonTLS(true);
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithMultipleAuthentication();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_NoValidAuthMechanisms() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithUnknownAuthentication();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_EXTERNAL() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithEXTERNALAuthentication();
+ server->receiveAuthRequest("EXTERNAL");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+
+ session->finish();
+ }
+
+ void testUnexpectedChallenge() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithEXTERNALAuthentication();
+ server->receiveAuthRequest("EXTERNAL");
+ server->sendChallenge();
+ server->sendChallenge();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStreamManagement() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithBindAndStreamManagement();
+ server->receiveBind();
+ server->sendBindResult();
+ server->receiveStreamManagementEnable();
+ server->sendStreamManagementEnabled();
+
+ CPPUNIT_ASSERT(session->getStreamManagementEnabled());
+ // TODO: Test if the requesters & responders do their work
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState());
+
+ session->finish();
+ }
+
+ void testStreamManagement_Failed() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithBindAndStreamManagement();
+ server->receiveBind();
+ server->sendBindResult();
+ server->receiveStreamManagementEnable();
+ server->sendStreamManagementFailed();
+
+ CPPUNIT_ASSERT(!session->getStreamManagementEnabled());
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Initialized, session->getState());
+
+ session->finish();
+ }
+
+ void testFinishAcksStanzas() {
+ boost::shared_ptr<ClientSession> session(createSession());
+ initializeSession(session);
+ server->sendMessage();
+ server->sendMessage();
+ server->sendMessage();
+
+ session->finish();
+
+ server->receiveAck(3);
+ }
+
+ private:
+ boost::shared_ptr<ClientSession> createSession() {
+ boost::shared_ptr<ClientSession> session = ClientSession::create(JID("me@foo.com"), server, idnConverter.get(), crypto.get());
+ session->onFinished.connect(boost::bind(&ClientSessionTest::handleSessionFinished, this, _1));
+ session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::handleSessionNeedCredentials, this));
+ session->setAllowPLAINOverNonTLS(true);
+ return session;
+ }
+
+ void initializeSession(boost::shared_ptr<ClientSession> session) {
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithBindAndStreamManagement();
+ server->receiveBind();
+ server->sendBindResult();
+ server->receiveStreamManagementEnable();
+ server->sendStreamManagementEnabled();
+ }
+
+ void handleSessionFinished(boost::shared_ptr<Error> error) {
+ sessionFinishedReceived = true;
+ sessionFinishedError = error;
+ }
+
+ void handleSessionNeedCredentials() {
+ needCredentials = true;
+ }
+
+ class MockSessionStream : public SessionStream {
+ public:
+ struct Event {
+ Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
+ Event(const ProtocolHeader& header) : header(header), footer(false) {}
+ Event() : footer(true) {}
+
+ boost::shared_ptr<ToplevelElement> element;
+ boost::optional<ProtocolHeader> header;
+ bool footer;
+ };
+
+ MockSessionStream() : available(true), canTLSEncrypt(true), tlsEncrypted(false), compressed(false), whitespacePingEnabled(false), resetCount(0) {
+ }
+
+ virtual void close() {
+ onClosed(boost::shared_ptr<Error>());
+ }
+
+ virtual bool isOpen() {
+ return available;
+ }
+
+ virtual void writeHeader(const ProtocolHeader& header) {
+ receivedEvents.push_back(Event(header));
+ }
+
+ virtual void writeFooter() {
+ receivedEvents.push_back(Event());
+ }
+
+ virtual void writeElement(boost::shared_ptr<ToplevelElement> element) {
+ receivedEvents.push_back(Event(element));
+ }
+
+ virtual void writeData(const std::string&) {
+ }
+
+ virtual bool supportsTLSEncryption() {
+ return canTLSEncrypt;
+ }
+
+ virtual void addTLSEncryption() {
+ tlsEncrypted = true;
+ }
+
+ virtual bool isTLSEncrypted() {
+ return tlsEncrypted;
+ }
+
+ virtual ByteArray getTLSFinishMessage() const {
+ return ByteArray();
+ }
+
+ virtual Certificate::ref getPeerCertificate() const {
+ return Certificate::ref(new SimpleCertificate());
+ }
+
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const {
+ return std::vector<Certificate::ref>();
+ }
+
+ virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
+ return boost::shared_ptr<CertificateVerificationError>();
+ }
+
+ virtual bool supportsZLibCompression() {
+ return true;
+ }
+
+ virtual void addZLibCompression() {
+ compressed = true;
+ }
+
+ virtual void setWhitespacePingEnabled(bool enabled) {
+ whitespacePingEnabled = enabled;
+ }
+
+ virtual void resetXMPPParser() {
+ resetCount++;
+ }
+
+ void breakConnection() {
+ onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError));
+ }
+
+ void breakTLS() {
+ onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::TLSError));
+ }
+
+
+ void sendStreamStart() {
+ ProtocolHeader header;
+ header.setTo("foo.com");
+ return onStreamStartReceived(header);
+ }
+
+ void sendStreamFeaturesWithStartTLS() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->setHasStartTLS();
+ onElementReceived(streamFeatures);
+ }
+
+ void sendChallenge() {
+ onElementReceived(boost::make_shared<AuthChallenge>());
+ }
+
+ void sendStreamError() {
+ onElementReceived(boost::make_shared<StreamError>());
+ }
+
+ void sendTLSProceed() {
+ onElementReceived(boost::make_shared<TLSProceed>());
+ }
+
+ void sendTLSFailure() {
+ onElementReceived(boost::make_shared<StartTLSFailure>());
+ }
+
+ void sendStreamFeaturesWithMultipleAuthentication() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("PLAIN");
+ streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
+ streamFeatures->addAuthenticationMechanism("SCRAM-SHA1");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithPLAINAuthentication() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("PLAIN");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithEXTERNALAuthentication() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("EXTERNAL");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithUnknownAuthentication() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("UNKNOWN");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithBindAndStreamManagement() {
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->setHasResourceBind();
+ streamFeatures->setHasStreamManagement();
+ onElementReceived(streamFeatures);
+ }
+
+ void sendEmptyStreamFeatures() {
+ onElementReceived(boost::make_shared<StreamFeatures>());
+ }
+
+ void sendAuthSuccess() {
+ onElementReceived(boost::make_shared<AuthSuccess>());
+ }
+
+ void sendAuthFailure() {
+ onElementReceived(boost::make_shared<AuthFailure>());
+ }
+
+ void sendStreamManagementEnabled() {
+ onElementReceived(boost::make_shared<StreamManagementEnabled>());
+ }
+
+ void sendStreamManagementFailed() {
+ onElementReceived(boost::make_shared<StreamManagementFailed>());
+ }
+
+ void sendBindResult() {
+ boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
+ resourceBind->setJID(JID("foo@bar.com/bla"));
+ boost::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind);
+ onElementReceived(iq);
+ }
+
+ void sendMessage() {
+ boost::shared_ptr<Message> message = boost::make_shared<Message>();
+ message->setTo(JID("foo@bar.com/bla"));
+ onElementReceived(message);
+ }
+
+ void receiveStreamStart() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.header);
+ }
+
+ void receiveStartTLS() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<StartTLSRequest>(event.element));
+ }
+
+ void receiveAuthRequest(const std::string& mech) {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ boost::shared_ptr<AuthRequest> request(boost::dynamic_pointer_cast<AuthRequest>(event.element));
+ CPPUNIT_ASSERT(request);
+ CPPUNIT_ASSERT_EQUAL(mech, request->getMechanism());
+ }
+
+ void receiveStreamManagementEnable() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<EnableStreamManagement>(event.element));
+ }
+
+ void receiveBind() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(event.element);
+ CPPUNIT_ASSERT(iq);
+ CPPUNIT_ASSERT(iq->getPayload<ResourceBind>());
+ bindID = iq->getID();
+ }
+
+ void receiveAck(unsigned int n) {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ boost::shared_ptr<StanzaAck> ack = boost::dynamic_pointer_cast<StanzaAck>(event.element);
+ CPPUNIT_ASSERT(ack);
+ CPPUNIT_ASSERT_EQUAL(n, ack->getHandledStanzasCount());
+ }
+
+ Event popEvent() {
+ CPPUNIT_ASSERT(!receivedEvents.empty());
+ Event event = receivedEvents.front();
+ receivedEvents.pop_front();
+ return event;
+ }
+
+ bool available;
+ bool canTLSEncrypt;
+ bool tlsEncrypted;
+ bool compressed;
+ bool whitespacePingEnabled;
+ std::string bindID;
+ int resetCount;
+ std::deque<Event> receivedEvents;
+ };
+
+ boost::shared_ptr<IDNConverter> idnConverter;
+ boost::shared_ptr<MockSessionStream> server;
+ bool sessionFinishedReceived;
+ bool needCredentials;
+ boost::shared_ptr<Error> sessionFinishedError;
+ BlindCertificateTrustChecker* blindCertificateTrustChecker;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ClientSessionTest);
#if 0
- void testAuthenticate() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::setNeedCredentials, this));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithAuthentication();
- session->startSession();
- processEvents();
- CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
- CPPUNIT_ASSERT(needCredentials_);
-
- getMockServer()->expectAuth("me", "mypass");
- getMockServer()->sendAuthSuccess();
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- session->sendCredentials("mypass");
- CPPUNIT_ASSERT_EQUAL(ClientSession::Authenticating, session->getState());
- processEvents();
- CPPUNIT_ASSERT_EQUAL(ClientSession::Negotiating, session->getState());
- }
-
- void testAuthenticate_Unauthorized() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithAuthentication();
- session->startSession();
- processEvents();
-
- getMockServer()->expectAuth("me", "mypass");
- getMockServer()->sendAuthFailure();
- session->sendCredentials("mypass");
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
- CPPUNIT_ASSERT_EQUAL(ClientSession::AuthenticationFailedError, *session->getError());
- }
-
- void testAuthenticate_NoValidAuthMechanisms() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithUnsupportedAuthentication();
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
- CPPUNIT_ASSERT_EQUAL(ClientSession::NoSupportedAuthMechanismsError, *session->getError());
- }
-
- void testResourceBind() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithResourceBind();
- getMockServer()->expectResourceBind("Bar", "session-bind");
- // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::BindingResource, session->getState());
- getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind");
- session->startSession();
-
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
- CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar"), session->getLocalJID());
- }
-
- void testResourceBind_ChangeResource() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithResourceBind();
- getMockServer()->expectResourceBind("Bar", "session-bind");
- getMockServer()->sendResourceBindResponse("me@foo.com/Bar123", "session-bind");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
- CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar123"), session->getLocalJID());
- }
-
- void testResourceBind_EmptyResource() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithResourceBind();
- getMockServer()->expectResourceBind("", "session-bind");
- getMockServer()->sendResourceBindResponse("me@foo.com/NewResource", "session-bind");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
- CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/NewResource"), session->getLocalJID());
- }
-
- void testResourceBind_Error() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithResourceBind();
- getMockServer()->expectResourceBind("", "session-bind");
- getMockServer()->sendError("session-bind");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
- CPPUNIT_ASSERT_EQUAL(ClientSession::ResourceBindError, *session->getError());
- }
-
- void testSessionStart() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithSession();
- getMockServer()->expectSessionStart("session-start");
- // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::StartingSession, session->getState());
- getMockServer()->sendSessionStartResponse("session-start");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
- CPPUNIT_ASSERT(sessionStarted_);
- }
-
- void testSessionStart_Error() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithSession();
- getMockServer()->expectSessionStart("session-start");
- getMockServer()->sendError("session-start");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStartError, *session->getError());
- }
-
- void testSessionStart_AfterResourceBind() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeaturesWithResourceBindAndSession();
- getMockServer()->expectResourceBind("Bar", "session-bind");
- getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind");
- getMockServer()->expectSessionStart("session-start");
- getMockServer()->sendSessionStartResponse("session-start");
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
- CPPUNIT_ASSERT(sessionStarted_);
- }
-
- void testWhitespacePing() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeatures();
- session->startSession();
- processEvents();
- CPPUNIT_ASSERT(session->getWhitespacePingLayer());
- }
-
- void testReceiveElementAfterSessionStarted() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeatures();
- session->startSession();
- processEvents();
-
- getMockServer()->expectMessage();
- session->sendElement(boost::make_shared<Message>()));
- }
-
- void testSendElement() {
- boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
- session->onElementReceived.connect(boost::bind(&ClientSessionTest::addReceivedElement, this, _1));
- getMockServer()->expectStreamStart();
- getMockServer()->sendStreamStart();
- getMockServer()->sendStreamFeatures();
- getMockServer()->sendMessage();
- session->startSession();
- processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedElements_.size()));
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Message>(receivedElements_[0]));
- }
+ void testAuthenticate() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ session->onNeedCredentials.connect(boost::bind(&ClientSessionTest::setNeedCredentials, this));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithAuthentication();
+ session->startSession();
+ processEvents();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::WaitingForCredentials, session->getState());
+ CPPUNIT_ASSERT(needCredentials_);
+
+ getMockServer()->expectAuth("me", "mypass");
+ getMockServer()->sendAuthSuccess();
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ session->sendCredentials("mypass");
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Authenticating, session->getState());
+ processEvents();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Negotiating, session->getState());
+ }
+
+ void testAuthenticate_Unauthorized() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithAuthentication();
+ session->startSession();
+ processEvents();
+
+ getMockServer()->expectAuth("me", "mypass");
+ getMockServer()->sendAuthFailure();
+ session->sendCredentials("mypass");
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
+ CPPUNIT_ASSERT_EQUAL(ClientSession::AuthenticationFailedError, *session->getError());
+ }
+
+ void testAuthenticate_NoValidAuthMechanisms() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithUnsupportedAuthentication();
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
+ CPPUNIT_ASSERT_EQUAL(ClientSession::NoSupportedAuthMechanismsError, *session->getError());
+ }
+
+ void testResourceBind() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithResourceBind();
+ getMockServer()->expectResourceBind("Bar", "session-bind");
+ // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::BindingResource, session->getState());
+ getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind");
+ session->startSession();
+
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
+ CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar"), session->getLocalJID());
+ }
+
+ void testResourceBind_ChangeResource() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithResourceBind();
+ getMockServer()->expectResourceBind("Bar", "session-bind");
+ getMockServer()->sendResourceBindResponse("me@foo.com/Bar123", "session-bind");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
+ CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/Bar123"), session->getLocalJID());
+ }
+
+ void testResourceBind_EmptyResource() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithResourceBind();
+ getMockServer()->expectResourceBind("", "session-bind");
+ getMockServer()->sendResourceBindResponse("me@foo.com/NewResource", "session-bind");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
+ CPPUNIT_ASSERT_EQUAL(JID("me@foo.com/NewResource"), session->getLocalJID());
+ }
+
+ void testResourceBind_Error() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithResourceBind();
+ getMockServer()->expectResourceBind("", "session-bind");
+ getMockServer()->sendError("session-bind");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
+ CPPUNIT_ASSERT_EQUAL(ClientSession::ResourceBindError, *session->getError());
+ }
+
+ void testSessionStart() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithSession();
+ getMockServer()->expectSessionStart("session-start");
+ // FIXME: Check CPPUNIT_ASSERT_EQUAL(ClientSession::StartingSession, session->getState());
+ getMockServer()->sendSessionStartResponse("session-start");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
+ CPPUNIT_ASSERT(sessionStarted_);
+ }
+
+ void testSessionStart_Error() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithSession();
+ getMockServer()->expectSessionStart("session-start");
+ getMockServer()->sendError("session-start");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::Error, session->getState());
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStartError, *session->getError());
+ }
+
+ void testSessionStart_AfterResourceBind() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeaturesWithResourceBindAndSession();
+ getMockServer()->expectResourceBind("Bar", "session-bind");
+ getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind");
+ getMockServer()->expectSessionStart("session-start");
+ getMockServer()->sendSessionStartResponse("session-start");
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
+ CPPUNIT_ASSERT(sessionStarted_);
+ }
+
+ void testWhitespacePing() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeatures();
+ session->startSession();
+ processEvents();
+ CPPUNIT_ASSERT(session->getWhitespacePingLayer());
+ }
+
+ void testReceiveElementAfterSessionStarted() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeatures();
+ session->startSession();
+ processEvents();
+
+ getMockServer()->expectMessage();
+ session->sendElement(boost::make_shared<Message>()));
+ }
+
+ void testSendElement() {
+ boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ session->onElementReceived.connect(boost::bind(&ClientSessionTest::addReceivedElement, this, _1));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeatures();
+ getMockServer()->sendMessage();
+ session->startSession();
+ processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedElements_.size()));
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Message>(receivedElements_[0]));
+ }
#endif
diff --git a/Swiften/Client/UnitTest/NickResolverTest.cpp b/Swiften/Client/UnitTest/NickResolverTest.cpp
index c7d7a3a..855b15a 100644
--- a/Swiften/Client/UnitTest/NickResolverTest.cpp
+++ b/Swiften/Client/UnitTest/NickResolverTest.cpp
@@ -20,134 +20,134 @@
using namespace Swift;
class NickResolverTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(NickResolverTest);
- CPPUNIT_TEST(testNoMatch);
- CPPUNIT_TEST(testZeroLengthMatch);
- CPPUNIT_TEST(testMatch);
- CPPUNIT_TEST(testOverwrittenMatch);
- CPPUNIT_TEST(testRemovedMatch);
- CPPUNIT_TEST(testMUCNick);
- CPPUNIT_TEST(testMUCNoNick);
- CPPUNIT_TEST(testRemovedMatch);
- CPPUNIT_TEST(testOwnNickFullOnly);
- CPPUNIT_TEST(testOwnNickGivenAndFull);
- CPPUNIT_TEST(testOwnNickNickEtAl);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- ownJID_ = JID("kev@wonderland.lit");
- xmppRoster_ = new XMPPRosterImpl();
- stanzaChannel_ = new DummyStanzaChannel();
- iqRouter_ = new IQRouter(stanzaChannel_);
- vCardStorage_ = new VCardMemoryStorage(crypto.get());
- vCardManager_ = new VCardManager(ownJID_, iqRouter_, vCardStorage_);
- registry_ = new MUCRegistry();
- resolver_ = new NickResolver(ownJID_, xmppRoster_, vCardManager_, registry_);
- }
-
- void tearDown() {
- delete resolver_;
- delete registry_;
- delete vCardManager_;
- delete iqRouter_;
- delete stanzaChannel_;
- delete vCardStorage_;
- delete xmppRoster_;
- }
-
- void testMUCNick() {
- registry_->addMUC(JID("foo@bar"));
- JID testJID("foo@bar/baz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("baz"), resolver_->jidToNick(testJID));
- }
-
- void testMUCNoNick() {
- registry_->addMUC(JID("foo@bar"));
- JID testJID("foo@bar");
-
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
- }
-
-
- void testNoMatch() {
- JID testJID("foo@bar/baz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
- }
-
- void testZeroLengthMatch() {
- JID testJID("foo@bar/baz");
- xmppRoster_->addContact(testJID, "", groups_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
- }
-
- void testMatch() {
- JID testJID("foo@bar/baz");
- xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both);
-
- CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID));
- }
-
- void testOverwrittenMatch() {
- JID testJID("foo@bar/baz");
- xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both);
- xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both);
-
- CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID));
- }
-
- void testRemovedMatch() {
- JID testJID("foo@bar/baz");
- xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both);
- xmppRoster_->removeContact(testJID);
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
- }
-
- void testOwnNickFullOnly() {
- populateOwnVCard("", "", "Kevin Smith");
- CPPUNIT_ASSERT_EQUAL(std::string("Kevin Smith"), resolver_->jidToNick(ownJID_));
- }
-
- void testOwnNickGivenAndFull() {
- populateOwnVCard("", "Kevin", "Kevin Smith");
- CPPUNIT_ASSERT_EQUAL(std::string("Kevin"), resolver_->jidToNick(ownJID_));
- }
-
- void testOwnNickNickEtAl() {
- populateOwnVCard("Kev", "Kevin", "Kevin Smith");
- CPPUNIT_ASSERT_EQUAL(std::string("Kev"), resolver_->jidToNick(ownJID_));
- }
-
- void populateOwnVCard(const std::string& nick, const std::string& given, const std::string& full) {
- VCard::ref vcard(new VCard());
- if (!nick.empty()) {
- vcard->setNickname(nick);
- }
- if (!given.empty()) {
- vcard->setGivenName(given);
- }
- if (!full.empty()) {
- vcard->setFullName(full);
- }
- vCardManager_->requestVCard(ownJID_);
- IQ::ref result(IQ::createResult(JID(), stanzaChannel_->sentStanzas[0]->getID(), vcard));
- stanzaChannel_->onIQReceived(result);
- }
-
- private:
- std::vector<std::string> groups_;
- XMPPRosterImpl* xmppRoster_;
- VCardStorage* vCardStorage_;
- IQRouter* iqRouter_;
- DummyStanzaChannel* stanzaChannel_;
- VCardManager* vCardManager_;
- MUCRegistry* registry_;
- NickResolver* resolver_;
- JID ownJID_;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(NickResolverTest);
+ CPPUNIT_TEST(testNoMatch);
+ CPPUNIT_TEST(testZeroLengthMatch);
+ CPPUNIT_TEST(testMatch);
+ CPPUNIT_TEST(testOverwrittenMatch);
+ CPPUNIT_TEST(testRemovedMatch);
+ CPPUNIT_TEST(testMUCNick);
+ CPPUNIT_TEST(testMUCNoNick);
+ CPPUNIT_TEST(testRemovedMatch);
+ CPPUNIT_TEST(testOwnNickFullOnly);
+ CPPUNIT_TEST(testOwnNickGivenAndFull);
+ CPPUNIT_TEST(testOwnNickNickEtAl);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ ownJID_ = JID("kev@wonderland.lit");
+ xmppRoster_ = new XMPPRosterImpl();
+ stanzaChannel_ = new DummyStanzaChannel();
+ iqRouter_ = new IQRouter(stanzaChannel_);
+ vCardStorage_ = new VCardMemoryStorage(crypto.get());
+ vCardManager_ = new VCardManager(ownJID_, iqRouter_, vCardStorage_);
+ registry_ = new MUCRegistry();
+ resolver_ = new NickResolver(ownJID_, xmppRoster_, vCardManager_, registry_);
+ }
+
+ void tearDown() {
+ delete resolver_;
+ delete registry_;
+ delete vCardManager_;
+ delete iqRouter_;
+ delete stanzaChannel_;
+ delete vCardStorage_;
+ delete xmppRoster_;
+ }
+
+ void testMUCNick() {
+ registry_->addMUC(JID("foo@bar"));
+ JID testJID("foo@bar/baz");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("baz"), resolver_->jidToNick(testJID));
+ }
+
+ void testMUCNoNick() {
+ registry_->addMUC(JID("foo@bar"));
+ JID testJID("foo@bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
+ }
+
+
+ void testNoMatch() {
+ JID testJID("foo@bar/baz");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
+ }
+
+ void testZeroLengthMatch() {
+ JID testJID("foo@bar/baz");
+ xmppRoster_->addContact(testJID, "", groups_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
+ }
+
+ void testMatch() {
+ JID testJID("foo@bar/baz");
+ xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID));
+ }
+
+ void testOverwrittenMatch() {
+ JID testJID("foo@bar/baz");
+ xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both);
+ xmppRoster_->addContact(testJID, "Test", groups_, RosterItemPayload::Both);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Test"), resolver_->jidToNick(testJID));
+ }
+
+ void testRemovedMatch() {
+ JID testJID("foo@bar/baz");
+ xmppRoster_->addContact(testJID, "FailTest", groups_, RosterItemPayload::Both);
+ xmppRoster_->removeContact(testJID);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), resolver_->jidToNick(testJID));
+ }
+
+ void testOwnNickFullOnly() {
+ populateOwnVCard("", "", "Kevin Smith");
+ CPPUNIT_ASSERT_EQUAL(std::string("Kevin Smith"), resolver_->jidToNick(ownJID_));
+ }
+
+ void testOwnNickGivenAndFull() {
+ populateOwnVCard("", "Kevin", "Kevin Smith");
+ CPPUNIT_ASSERT_EQUAL(std::string("Kevin"), resolver_->jidToNick(ownJID_));
+ }
+
+ void testOwnNickNickEtAl() {
+ populateOwnVCard("Kev", "Kevin", "Kevin Smith");
+ CPPUNIT_ASSERT_EQUAL(std::string("Kev"), resolver_->jidToNick(ownJID_));
+ }
+
+ void populateOwnVCard(const std::string& nick, const std::string& given, const std::string& full) {
+ VCard::ref vcard(new VCard());
+ if (!nick.empty()) {
+ vcard->setNickname(nick);
+ }
+ if (!given.empty()) {
+ vcard->setGivenName(given);
+ }
+ if (!full.empty()) {
+ vcard->setFullName(full);
+ }
+ vCardManager_->requestVCard(ownJID_);
+ IQ::ref result(IQ::createResult(JID(), stanzaChannel_->sentStanzas[0]->getID(), vcard));
+ stanzaChannel_->onIQReceived(result);
+ }
+
+ private:
+ std::vector<std::string> groups_;
+ XMPPRosterImpl* xmppRoster_;
+ VCardStorage* vCardStorage_;
+ IQRouter* iqRouter_;
+ DummyStanzaChannel* stanzaChannel_;
+ VCardManager* vCardManager_;
+ MUCRegistry* registry_;
+ NickResolver* resolver_;
+ JID ownJID_;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(NickResolverTest);
diff --git a/Swiften/Client/XMLBeautifier.cpp b/Swiften/Client/XMLBeautifier.cpp
index 78a10ec..f084bb3 100644
--- a/Swiften/Client/XMLBeautifier.cpp
+++ b/Swiften/Client/XMLBeautifier.cpp
@@ -22,26 +22,26 @@
namespace Swift {
XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(NULL), lastWasStepDown(false) {
- factory = new PlatformXMLParserFactory();
+ factory = new PlatformXMLParserFactory();
}
XMLBeautifier::~XMLBeautifier() {
- delete factory;
+ 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();
+ 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 << " ";
- }
+ for (int i = 0; i < intLevel; ++i) {
+ buffer << " ";
+ }
}
// all bold but reset
@@ -56,78 +56,78 @@ static const char colorYellow[] = "\x1b[01;33m";
std::string XMLBeautifier::styleTag(const std::string& text) const {
- std::string result;
- result += colorYellow;
- result += text;
- result += colorReset;
- return result;
+ std::string result;
+ result += colorYellow;
+ result += text;
+ result += colorReset;
+ return result;
}
std::string XMLBeautifier::styleNamespace(const std::string& text) const {
- std::string result;
- result += colorRed;
- result += text;
- result += colorReset;
- return result;
+ std::string result;
+ result += colorRed;
+ result += text;
+ result += colorReset;
+ return result;
}
std::string XMLBeautifier::styleAttribute(const std::string& text) const {
- std::string result;
- result += colorGreen;
- result += text;
- result += colorReset;
- return result;
+ 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;
+ 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()) {
- 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);
+ 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()) {
+ 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;
+ --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;
+ buffer << data;
+ lastWasStepDown = false;
}
}
diff --git a/Swiften/Client/XMLBeautifier.h b/Swiften/Client/XMLBeautifier.h
index 233c68e..a765bc5 100644
--- a/Swiften/Client/XMLBeautifier.h
+++ b/Swiften/Client/XMLBeautifier.h
@@ -26,36 +26,36 @@ namespace Swift {
class SWIFTEN_API XMLBeautifier : public XMLParserClient {
public:
- XMLBeautifier(bool indention, bool coloring);
- virtual ~XMLBeautifier();
+ XMLBeautifier(bool indention, bool coloring);
+ virtual ~XMLBeautifier();
- std::string beautify(const std::string&);
+ std::string beautify(const std::string&);
private:
- void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- void handleEndElement(const std::string& element, const std::string& ns);
- void handleCharacterData(const std::string& data);
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
private:
- void indent();
+ void indent();
private:
- std::string styleTag(const std::string& text) const;
- std::string styleNamespace(const std::string& text) const;
- std::string styleAttribute(const std::string& text) const;
- std::string styleValue(const std::string& text) const;
+ std::string styleTag(const std::string& text) const;
+ std::string styleNamespace(const std::string& text) const;
+ std::string styleAttribute(const std::string& text) const;
+ std::string styleValue(const std::string& text) const;
private:
- bool doIndention;
- bool doColoring;
+ bool doIndention;
+ bool doColoring;
- int intLevel;
- std::string inputBuffer;
- std::stringstream buffer;
- XMLParserFactory* factory;
- XMLParser* parser;
+ int intLevel;
+ std::string inputBuffer;
+ std::stringstream buffer;
+ XMLParserFactory* factory;
+ XMLParser* parser;
- bool lastWasStepDown;
- std::stack<std::string> parentNSs;
+ bool lastWasStepDown;
+ std::stack<std::string> parentNSs;
};
}
diff --git a/Swiften/Component/Component.cpp b/Swiften/Component/Component.cpp
index 1340de2..e6835bd 100644
--- a/Swiften/Component/Component.cpp
+++ b/Swiften/Component/Component.cpp
@@ -11,17 +11,17 @@
namespace Swift {
Component::Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories) : CoreComponent(jid, secret, networkFactories) {
- softwareVersionResponder = new SoftwareVersionResponder(getIQRouter());
- softwareVersionResponder->start();
+ softwareVersionResponder = new SoftwareVersionResponder(getIQRouter());
+ softwareVersionResponder->start();
}
Component::~Component() {
- softwareVersionResponder->stop();
- delete softwareVersionResponder;
+ softwareVersionResponder->stop();
+ delete softwareVersionResponder;
}
void Component::setSoftwareVersion(const std::string& name, const std::string& version) {
- softwareVersionResponder->setVersion(name, version);
+ softwareVersionResponder->setVersion(name, version);
}
}
diff --git a/Swiften/Component/Component.h b/Swiften/Component/Component.h
index 63aa9f7..a7ef621 100644
--- a/Swiften/Component/Component.h
+++ b/Swiften/Component/Component.h
@@ -10,27 +10,27 @@
#include <Swiften/Component/CoreComponent.h>
namespace Swift {
- class SoftwareVersionResponder;
+ class SoftwareVersionResponder;
- /**
- * Provides the core functionality for writing XMPP component software.
- *
- * Besides connecting to an XMPP server, this class also provides interfaces for
- * performing most component tasks on the XMPP network.
- */
- class SWIFTEN_API Component : public CoreComponent {
- public:
- Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories);
- virtual ~Component();
+ /**
+ * Provides the core functionality for writing XMPP component software.
+ *
+ * Besides connecting to an XMPP server, this class also provides interfaces for
+ * performing most component tasks on the XMPP network.
+ */
+ class SWIFTEN_API Component : public CoreComponent {
+ public:
+ Component(const JID& jid, const std::string& secret, NetworkFactories* networkFactories);
+ virtual ~Component();
- /**
- * Sets the software version of the client.
- *
- * This will be used to respond to version queries from other entities.
- */
- void setSoftwareVersion(const std::string& name, const std::string& version);
+ /**
+ * Sets the software version of the client.
+ *
+ * This will be used to respond to version queries from other entities.
+ */
+ void setSoftwareVersion(const std::string& name, const std::string& version);
- private:
- SoftwareVersionResponder* softwareVersionResponder;
- };
+ private:
+ SoftwareVersionResponder* softwareVersionResponder;
+ };
}
diff --git a/Swiften/Component/ComponentConnector.cpp b/Swiften/Component/ComponentConnector.cpp
index 7a2121a..410c19e 100644
--- a/Swiften/Component/ComponentConnector.cpp
+++ b/Swiften/Component/ComponentConnector.cpp
@@ -21,88 +21,88 @@ ComponentConnector::ComponentConnector(const std::string& hostname, int port, Do
}
void ComponentConnector::setTimeoutMilliseconds(int milliseconds) {
- timeoutMilliseconds = milliseconds;
+ timeoutMilliseconds = milliseconds;
}
void ComponentConnector::start() {
- assert(!currentConnection);
- assert(!timer);
- assert(!addressQuery);
- addressQuery = resolver->createAddressQuery(hostname);
- addressQuery->onResult.connect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2));
- if (timeoutMilliseconds > 0) {
- timer = timerFactory->createTimer(timeoutMilliseconds);
- timer->onTick.connect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this()));
- timer->start();
- }
- addressQuery->run();
+ assert(!currentConnection);
+ assert(!timer);
+ assert(!addressQuery);
+ addressQuery = resolver->createAddressQuery(hostname);
+ addressQuery->onResult.connect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2));
+ if (timeoutMilliseconds > 0) {
+ timer = timerFactory->createTimer(timeoutMilliseconds);
+ timer->onTick.connect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this()));
+ timer->start();
+ }
+ addressQuery->run();
}
void ComponentConnector::stop() {
- finish(boost::shared_ptr<Connection>());
+ finish(boost::shared_ptr<Connection>());
}
void ComponentConnector::handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) {
- addressQuery.reset();
- if (error || addresses.empty()) {
- finish(boost::shared_ptr<Connection>());
- }
- else {
- addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end());
- tryNextAddress();
- }
+ addressQuery.reset();
+ if (error || addresses.empty()) {
+ finish(boost::shared_ptr<Connection>());
+ }
+ else {
+ addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end());
+ tryNextAddress();
+ }
}
void ComponentConnector::tryNextAddress() {
- assert(!addressQueryResults.empty());
- HostAddress address = addressQueryResults.front();
- addressQueryResults.pop_front();
- tryConnect(HostAddressPort(address, port));
+ assert(!addressQueryResults.empty());
+ HostAddress address = addressQueryResults.front();
+ addressQueryResults.pop_front();
+ tryConnect(HostAddressPort(address, port));
}
void ComponentConnector::tryConnect(const HostAddressPort& target) {
- assert(!currentConnection);
- currentConnection = connectionFactory->createConnection();
- currentConnection->onConnectFinished.connect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
- currentConnection->connect(target);
+ assert(!currentConnection);
+ currentConnection = connectionFactory->createConnection();
+ currentConnection->onConnectFinished.connect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection->connect(target);
}
void ComponentConnector::handleConnectionConnectFinished(bool error) {
- currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
- if (error) {
- currentConnection.reset();
- if (!addressQueryResults.empty()) {
- tryNextAddress();
- }
- else {
- finish(boost::shared_ptr<Connection>());
- }
- }
- else {
- finish(currentConnection);
- }
+ currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
+ if (error) {
+ currentConnection.reset();
+ if (!addressQueryResults.empty()) {
+ tryNextAddress();
+ }
+ else {
+ finish(boost::shared_ptr<Connection>());
+ }
+ }
+ else {
+ finish(currentConnection);
+ }
}
void ComponentConnector::finish(boost::shared_ptr<Connection> connection) {
- if (timer) {
- timer->stop();
- timer->onTick.disconnect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this()));
- timer.reset();
- }
- if (addressQuery) {
- addressQuery->onResult.disconnect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2));
- addressQuery.reset();
- }
- if (currentConnection) {
- currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
- currentConnection.reset();
- }
- onConnectFinished(connection);
+ if (timer) {
+ timer->stop();
+ timer->onTick.disconnect(boost::bind(&ComponentConnector::handleTimeout, shared_from_this()));
+ timer.reset();
+ }
+ if (addressQuery) {
+ addressQuery->onResult.disconnect(boost::bind(&ComponentConnector::handleAddressQueryResult, shared_from_this(), _1, _2));
+ addressQuery.reset();
+ }
+ if (currentConnection) {
+ currentConnection->onConnectFinished.disconnect(boost::bind(&ComponentConnector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection.reset();
+ }
+ onConnectFinished(connection);
}
void ComponentConnector::handleTimeout() {
- finish(boost::shared_ptr<Connection>());
+ finish(boost::shared_ptr<Connection>());
}
}
diff --git a/Swiften/Component/ComponentConnector.h b/Swiften/Component/ComponentConnector.h
index 008236b..68cb0d7 100644
--- a/Swiften/Component/ComponentConnector.h
+++ b/Swiften/Component/ComponentConnector.h
@@ -19,48 +19,48 @@
#include <Swiften/Network/Timer.h>
namespace Swift {
- class DomainNameAddressQuery;
- class DomainNameResolver;
- class ConnectionFactory;
- class TimerFactory;
+ class DomainNameAddressQuery;
+ class DomainNameResolver;
+ class ConnectionFactory;
+ class TimerFactory;
- class SWIFTEN_API ComponentConnector : public boost::bsignals::trackable, public boost::enable_shared_from_this<ComponentConnector> {
- public:
- typedef boost::shared_ptr<ComponentConnector> ref;
+ class SWIFTEN_API ComponentConnector : public boost::bsignals::trackable, public boost::enable_shared_from_this<ComponentConnector> {
+ public:
+ typedef boost::shared_ptr<ComponentConnector> ref;
- static ComponentConnector::ref create(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) {
- return ref(new ComponentConnector(hostname, port, resolver, connectionFactory, timerFactory));
- }
+ static ComponentConnector::ref create(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) {
+ return ref(new ComponentConnector(hostname, port, resolver, connectionFactory, timerFactory));
+ }
- void setTimeoutMilliseconds(int milliseconds);
+ void setTimeoutMilliseconds(int milliseconds);
- void start();
- void stop();
+ void start();
+ void stop();
- boost::signal<void (boost::shared_ptr<Connection>)> onConnectFinished;
+ boost::signal<void (boost::shared_ptr<Connection>)> onConnectFinished;
- private:
- ComponentConnector(const std::string& hostname, int port, DomainNameResolver*, ConnectionFactory*, TimerFactory*);
+ private:
+ ComponentConnector(const std::string& hostname, int port, DomainNameResolver*, ConnectionFactory*, TimerFactory*);
- void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error);
- void tryNextAddress();
- void tryConnect(const HostAddressPort& target);
+ void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error);
+ void tryNextAddress();
+ void tryConnect(const HostAddressPort& target);
- void handleConnectionConnectFinished(bool error);
- void finish(boost::shared_ptr<Connection>);
- void handleTimeout();
+ void handleConnectionConnectFinished(bool error);
+ void finish(boost::shared_ptr<Connection>);
+ void handleTimeout();
- private:
- std::string hostname;
- int port;
- DomainNameResolver* resolver;
- ConnectionFactory* connectionFactory;
- TimerFactory* timerFactory;
- int timeoutMilliseconds;
- boost::shared_ptr<Timer> timer;
- boost::shared_ptr<DomainNameAddressQuery> addressQuery;
- std::deque<HostAddress> addressQueryResults;
- boost::shared_ptr<Connection> currentConnection;
- };
+ private:
+ std::string hostname;
+ int port;
+ DomainNameResolver* resolver;
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+ int timeoutMilliseconds;
+ boost::shared_ptr<Timer> timer;
+ boost::shared_ptr<DomainNameAddressQuery> addressQuery;
+ std::deque<HostAddress> addressQueryResults;
+ boost::shared_ptr<Connection> currentConnection;
+ };
}
diff --git a/Swiften/Component/ComponentError.h b/Swiften/Component/ComponentError.h
index 7609b9a..dca8c99 100644
--- a/Swiften/Component/ComponentError.h
+++ b/Swiften/Component/ComponentError.h
@@ -9,23 +9,23 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API ComponentError {
- public:
- enum Type {
- UnknownError,
- ConnectionError,
- ConnectionReadError,
- ConnectionWriteError,
- XMLError,
- AuthenticationFailedError,
- UnexpectedElementError
- };
+ class SWIFTEN_API ComponentError {
+ public:
+ enum Type {
+ UnknownError,
+ ConnectionError,
+ ConnectionReadError,
+ ConnectionWriteError,
+ XMLError,
+ AuthenticationFailedError,
+ UnexpectedElementError
+ };
- ComponentError(Type type = UnknownError) : type_(type) {}
+ ComponentError(Type type = UnknownError) : type_(type) {}
- Type getType() const { return type_; }
+ Type getType() const { return type_; }
- private:
- Type type_;
- };
+ private:
+ Type type_;
+ };
}
diff --git a/Swiften/Component/ComponentHandshakeGenerator.cpp b/Swiften/Component/ComponentHandshakeGenerator.cpp
index a0eacab..647b3da 100644
--- a/Swiften/Component/ComponentHandshakeGenerator.cpp
+++ b/Swiften/Component/ComponentHandshakeGenerator.cpp
@@ -13,13 +13,13 @@
namespace Swift {
std::string ComponentHandshakeGenerator::getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto) {
- std::string concatenatedString = streamID + secret;
- String::replaceAll(concatenatedString, '&', "&amp;");
- String::replaceAll(concatenatedString, '<', "&lt;");
- String::replaceAll(concatenatedString, '>', "&gt;");
- String::replaceAll(concatenatedString, '\'', "&apos;");
- String::replaceAll(concatenatedString, '"', "&quot;");
- return Hexify::hexify(crypto->getSHA1Hash(createByteArray(concatenatedString)));
+ std::string concatenatedString = streamID + secret;
+ String::replaceAll(concatenatedString, '&', "&amp;");
+ String::replaceAll(concatenatedString, '<', "&lt;");
+ String::replaceAll(concatenatedString, '>', "&gt;");
+ String::replaceAll(concatenatedString, '\'', "&apos;");
+ String::replaceAll(concatenatedString, '"', "&quot;");
+ return Hexify::hexify(crypto->getSHA1Hash(createByteArray(concatenatedString)));
}
}
diff --git a/Swiften/Component/ComponentHandshakeGenerator.h b/Swiften/Component/ComponentHandshakeGenerator.h
index 7d9f60c..0aafb83 100644
--- a/Swiften/Component/ComponentHandshakeGenerator.h
+++ b/Swiften/Component/ComponentHandshakeGenerator.h
@@ -11,11 +11,11 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class SWIFTEN_API ComponentHandshakeGenerator {
- public:
- static std::string getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto);
- };
+ class SWIFTEN_API ComponentHandshakeGenerator {
+ public:
+ static std::string getHandshake(const std::string& streamID, const std::string& secret, CryptoProvider* crypto);
+ };
}
diff --git a/Swiften/Component/ComponentSession.cpp b/Swiften/Component/ComponentSession.cpp
index 79660de..46c88db 100644
--- a/Swiften/Component/ComponentSession.cpp
+++ b/Swiften/Component/ComponentSession.cpp
@@ -24,99 +24,99 @@ ComponentSession::~ComponentSession() {
}
void ComponentSession::start() {
- stream->onStreamStartReceived.connect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
- stream->onElementReceived.connect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
- stream->onClosed.connect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
+ stream->onStreamStartReceived.connect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
+ stream->onElementReceived.connect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
+ stream->onClosed.connect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
- assert(state == Initial);
- state = WaitingForStreamStart;
- sendStreamHeader();
+ assert(state == Initial);
+ state = WaitingForStreamStart;
+ sendStreamHeader();
}
void ComponentSession::sendStreamHeader() {
- ProtocolHeader header;
- header.setTo(jid);
- stream->writeHeader(header);
+ ProtocolHeader header;
+ header.setTo(jid);
+ stream->writeHeader(header);
}
void ComponentSession::sendStanza(boost::shared_ptr<Stanza> stanza) {
- stream->writeElement(stanza);
+ stream->writeElement(stanza);
}
void ComponentSession::handleStreamStart(const ProtocolHeader& header) {
- checkState(WaitingForStreamStart);
- state = Authenticating;
- stream->writeElement(ComponentHandshake::ref(new ComponentHandshake(ComponentHandshakeGenerator::getHandshake(header.getID(), secret, crypto))));
+ checkState(WaitingForStreamStart);
+ state = Authenticating;
+ stream->writeElement(ComponentHandshake::ref(new ComponentHandshake(ComponentHandshakeGenerator::getHandshake(header.getID(), secret, crypto))));
}
void ComponentSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) {
- if (getState() == Initialized) {
- onStanzaReceived(stanza);
- }
- else {
- finishSession(Error::UnexpectedElementError);
- }
- }
- else if (boost::dynamic_pointer_cast<ComponentHandshake>(element)) {
- if (!checkState(Authenticating)) {
- return;
- }
- stream->setWhitespacePingEnabled(true);
- state = Initialized;
- onInitialized();
- }
- else if (getState() == Authenticating) {
- if (boost::dynamic_pointer_cast<StreamFeatures>(element)) {
- // M-Link sends stream features, so swallow that.
- }
- else {
- // FIXME: We should actually check the element received
- finishSession(Error::AuthenticationFailedError);
- }
- }
- else {
- finishSession(Error::UnexpectedElementError);
- }
+ if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) {
+ if (getState() == Initialized) {
+ onStanzaReceived(stanza);
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
+ }
+ else if (boost::dynamic_pointer_cast<ComponentHandshake>(element)) {
+ if (!checkState(Authenticating)) {
+ return;
+ }
+ stream->setWhitespacePingEnabled(true);
+ state = Initialized;
+ onInitialized();
+ }
+ else if (getState() == Authenticating) {
+ if (boost::dynamic_pointer_cast<StreamFeatures>(element)) {
+ // M-Link sends stream features, so swallow that.
+ }
+ else {
+ // FIXME: We should actually check the element received
+ finishSession(Error::AuthenticationFailedError);
+ }
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
}
bool ComponentSession::checkState(State state) {
- if (this->state != state) {
- finishSession(Error::UnexpectedElementError);
- return false;
- }
- return true;
+ if (this->state != state) {
+ finishSession(Error::UnexpectedElementError);
+ return false;
+ }
+ return true;
}
void ComponentSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) {
- State oldState = state;
- state = Finished;
- stream->setWhitespacePingEnabled(false);
- stream->onStreamStartReceived.disconnect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
- stream->onElementReceived.disconnect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
- stream->onClosed.disconnect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
- if (oldState == Finishing) {
- onFinished(error);
- }
- else {
- onFinished(streamError);
- }
+ State oldState = state;
+ state = Finished;
+ stream->setWhitespacePingEnabled(false);
+ stream->onStreamStartReceived.disconnect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
+ stream->onElementReceived.disconnect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
+ stream->onClosed.disconnect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
+ if (oldState == Finishing) {
+ onFinished(error);
+ }
+ else {
+ onFinished(streamError);
+ }
}
void ComponentSession::finish() {
- finishSession(boost::shared_ptr<Error>());
+ finishSession(boost::shared_ptr<Error>());
}
void ComponentSession::finishSession(Error::Type error) {
- finishSession(boost::make_shared<Swift::ComponentSession::Error>(error));
+ finishSession(boost::make_shared<Swift::ComponentSession::Error>(error));
}
void ComponentSession::finishSession(boost::shared_ptr<Swift::Error> finishError) {
- state = Finishing;
- error = finishError;
- assert(stream->isOpen());
- stream->writeFooter();
- stream->close();
+ state = Finishing;
+ error = finishError;
+ assert(stream->isOpen());
+ stream->writeFooter();
+ stream->close();
}
}
diff --git a/Swiften/Component/ComponentSession.h b/Swiften/Component/ComponentSession.h
index 3a750cc..608bb79 100644
--- a/Swiften/Component/ComponentSession.h
+++ b/Swiften/Component/ComponentSession.h
@@ -20,68 +20,68 @@
#include <Swiften/Session/SessionStream.h>
namespace Swift {
- class ComponentAuthenticator;
- class CryptoProvider;
-
- class SWIFTEN_API ComponentSession : public boost::enable_shared_from_this<ComponentSession> {
- public:
- enum State {
- Initial,
- WaitingForStreamStart,
- Authenticating,
- Initialized,
- Finishing,
- Finished
- };
-
- struct Error : public Swift::Error {
- enum Type {
- AuthenticationFailedError,
- UnexpectedElementError
- } type;
- Error(Type type) : type(type) {}
- };
-
- ~ComponentSession();
-
- static boost::shared_ptr<ComponentSession> create(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream, CryptoProvider* crypto) {
- return boost::shared_ptr<ComponentSession>(new ComponentSession(jid, secret, stream, crypto));
- }
-
- State getState() const {
- return state;
- }
-
- void start();
- void finish();
-
- void sendStanza(boost::shared_ptr<Stanza>);
-
- public:
- boost::signal<void ()> onInitialized;
- boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished;
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived;
-
- private:
- ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream>, CryptoProvider*);
-
- void finishSession(Error::Type error);
- void finishSession(boost::shared_ptr<Swift::Error> error);
-
- void sendStreamHeader();
-
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamStart(const ProtocolHeader&);
- void handleStreamClosed(boost::shared_ptr<Swift::Error>);
-
- bool checkState(State);
-
- private:
- JID jid;
- std::string secret;
- boost::shared_ptr<SessionStream> stream;
- CryptoProvider* crypto;
- boost::shared_ptr<Swift::Error> error;
- State state;
- };
+ class ComponentAuthenticator;
+ class CryptoProvider;
+
+ class SWIFTEN_API ComponentSession : public boost::enable_shared_from_this<ComponentSession> {
+ public:
+ enum State {
+ Initial,
+ WaitingForStreamStart,
+ Authenticating,
+ Initialized,
+ Finishing,
+ Finished
+ };
+
+ struct Error : public Swift::Error {
+ enum Type {
+ AuthenticationFailedError,
+ UnexpectedElementError
+ } type;
+ Error(Type type) : type(type) {}
+ };
+
+ ~ComponentSession();
+
+ static boost::shared_ptr<ComponentSession> create(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream, CryptoProvider* crypto) {
+ return boost::shared_ptr<ComponentSession>(new ComponentSession(jid, secret, stream, crypto));
+ }
+
+ State getState() const {
+ return state;
+ }
+
+ void start();
+ void finish();
+
+ void sendStanza(boost::shared_ptr<Stanza>);
+
+ public:
+ boost::signal<void ()> onInitialized;
+ boost::signal<void (boost::shared_ptr<Swift::Error>)> onFinished;
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaReceived;
+
+ private:
+ ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream>, CryptoProvider*);
+
+ void finishSession(Error::Type error);
+ void finishSession(boost::shared_ptr<Swift::Error> error);
+
+ void sendStreamHeader();
+
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+ void handleStreamClosed(boost::shared_ptr<Swift::Error>);
+
+ bool checkState(State);
+
+ private:
+ JID jid;
+ std::string secret;
+ boost::shared_ptr<SessionStream> stream;
+ CryptoProvider* crypto;
+ boost::shared_ptr<Swift::Error> error;
+ State state;
+ };
}
diff --git a/Swiften/Component/ComponentSessionStanzaChannel.cpp b/Swiften/Component/ComponentSessionStanzaChannel.cpp
index 7ff374f..ffb1f13 100644
--- a/Swiften/Component/ComponentSessionStanzaChannel.cpp
+++ b/Swiften/Component/ComponentSessionStanzaChannel.cpp
@@ -13,68 +13,68 @@
namespace Swift {
void ComponentSessionStanzaChannel::setSession(boost::shared_ptr<ComponentSession> session) {
- assert(!this->session);
- this->session = session;
- session->onInitialized.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this));
- session->onFinished.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1));
- session->onStanzaReceived.connect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1));
+ assert(!this->session);
+ this->session = session;
+ session->onInitialized.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this));
+ session->onFinished.connect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1));
+ session->onStanzaReceived.connect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1));
}
void ComponentSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) {
- send(iq);
+ send(iq);
}
void ComponentSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) {
- send(message);
+ send(message);
}
void ComponentSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) {
- send(presence);
+ send(presence);
}
std::string ComponentSessionStanzaChannel::getNewIQID() {
- return idGenerator.generateID();
+ return idGenerator.generateID();
}
void ComponentSessionStanzaChannel::send(boost::shared_ptr<Stanza> stanza) {
- if (!isAvailable()) {
- std::cerr << "Warning: Component: Trying to send a stanza while disconnected." << std::endl;
- return;
- }
- session->sendStanza(stanza);
+ if (!isAvailable()) {
+ std::cerr << "Warning: Component: Trying to send a stanza while disconnected." << std::endl;
+ return;
+ }
+ session->sendStanza(stanza);
}
void ComponentSessionStanzaChannel::handleSessionFinished(boost::shared_ptr<Error>) {
- session->onFinished.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1));
- session->onStanzaReceived.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1));
- session->onInitialized.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this));
- session.reset();
+ session->onFinished.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionFinished, this, _1));
+ session->onStanzaReceived.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleStanza, this, _1));
+ session->onInitialized.disconnect(boost::bind(&ComponentSessionStanzaChannel::handleSessionInitialized, this));
+ session.reset();
- onAvailableChanged(false);
+ onAvailableChanged(false);
}
void ComponentSessionStanzaChannel::handleStanza(boost::shared_ptr<Stanza> stanza) {
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza);
- if (message) {
- onMessageReceived(message);
- return;
- }
-
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza);
- if (presence) {
- onPresenceReceived(presence);
- return;
- }
-
- boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza);
- if (iq) {
- onIQReceived(iq);
- return;
- }
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(stanza);
+ if (message) {
+ onMessageReceived(message);
+ return;
+ }
+
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(stanza);
+ if (presence) {
+ onPresenceReceived(presence);
+ return;
+ }
+
+ boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza);
+ if (iq) {
+ onIQReceived(iq);
+ return;
+ }
}
void ComponentSessionStanzaChannel::handleSessionInitialized() {
- onAvailableChanged(true);
+ onAvailableChanged(true);
}
}
diff --git a/Swiften/Component/ComponentSessionStanzaChannel.h b/Swiften/Component/ComponentSessionStanzaChannel.h
index a507904..31931ea 100644
--- a/Swiften/Component/ComponentSessionStanzaChannel.h
+++ b/Swiften/Component/ComponentSessionStanzaChannel.h
@@ -17,40 +17,40 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- /**
- * StanzaChannel implementation around a ComponentSession.
- */
- class SWIFTEN_API ComponentSessionStanzaChannel : public StanzaChannel {
- public:
- void setSession(boost::shared_ptr<ComponentSession> session);
-
- void sendIQ(boost::shared_ptr<IQ> iq);
- void sendMessage(boost::shared_ptr<Message> message);
- void sendPresence(boost::shared_ptr<Presence> presence);
-
- bool getStreamManagementEnabled() const {
- return false;
- }
-
- std::vector<Certificate::ref> getPeerCertificateChain() const {
- // TODO: actually implement this method
- return std::vector<Certificate::ref>();
- }
-
- bool isAvailable() const {
- return session && session->getState() == ComponentSession::Initialized;
- }
-
- private:
- std::string getNewIQID();
- void send(boost::shared_ptr<Stanza> stanza);
- void handleSessionFinished(boost::shared_ptr<Error> error);
- void handleStanza(boost::shared_ptr<Stanza> stanza);
- void handleSessionInitialized();
-
- private:
- IDGenerator idGenerator;
- boost::shared_ptr<ComponentSession> session;
- };
+ /**
+ * StanzaChannel implementation around a ComponentSession.
+ */
+ class SWIFTEN_API ComponentSessionStanzaChannel : public StanzaChannel {
+ public:
+ void setSession(boost::shared_ptr<ComponentSession> session);
+
+ void sendIQ(boost::shared_ptr<IQ> iq);
+ void sendMessage(boost::shared_ptr<Message> message);
+ void sendPresence(boost::shared_ptr<Presence> presence);
+
+ bool getStreamManagementEnabled() const {
+ return false;
+ }
+
+ std::vector<Certificate::ref> getPeerCertificateChain() const {
+ // TODO: actually implement this method
+ return std::vector<Certificate::ref>();
+ }
+
+ bool isAvailable() const {
+ return session && session->getState() == ComponentSession::Initialized;
+ }
+
+ private:
+ std::string getNewIQID();
+ void send(boost::shared_ptr<Stanza> stanza);
+ void handleSessionFinished(boost::shared_ptr<Error> error);
+ void handleStanza(boost::shared_ptr<Stanza> stanza);
+ void handleSessionInitialized();
+
+ private:
+ IDGenerator idGenerator;
+ boost::shared_ptr<ComponentSession> session;
+ };
}
diff --git a/Swiften/Component/ComponentXMLTracer.cpp b/Swiften/Component/ComponentXMLTracer.cpp
index 49d948b..94d4ec2 100644
--- a/Swiften/Component/ComponentXMLTracer.cpp
+++ b/Swiften/Component/ComponentXMLTracer.cpp
@@ -13,20 +13,20 @@
namespace Swift {
ComponentXMLTracer::ComponentXMLTracer(CoreComponent* client) {
- client->onDataRead.connect(boost::bind(&ComponentXMLTracer::printData, '<', _1));
- client->onDataWritten.connect(boost::bind(&ComponentXMLTracer::printData, '>', _1));
+ client->onDataRead.connect(boost::bind(&ComponentXMLTracer::printData, '<', _1));
+ client->onDataWritten.connect(boost::bind(&ComponentXMLTracer::printData, '>', _1));
}
void ComponentXMLTracer::printData(char direction, const SafeByteArray& data) {
- printLine(direction);
- std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
+ printLine(direction);
+ std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
}
void ComponentXMLTracer::printLine(char c) {
- for (unsigned int i = 0; i < 80; ++i) {
- std::cerr << c;
- }
- std::cerr << std::endl;
+ for (unsigned int i = 0; i < 80; ++i) {
+ std::cerr << c;
+ }
+ std::cerr << std::endl;
}
}
diff --git a/Swiften/Component/ComponentXMLTracer.h b/Swiften/Component/ComponentXMLTracer.h
index 2c07305..d34930b 100644
--- a/Swiften/Component/ComponentXMLTracer.h
+++ b/Swiften/Component/ComponentXMLTracer.h
@@ -10,12 +10,12 @@
#include <Swiften/Component/Component.h>
namespace Swift {
- class SWIFTEN_API ComponentXMLTracer {
- public:
- ComponentXMLTracer(CoreComponent* component);
+ class SWIFTEN_API ComponentXMLTracer {
+ public:
+ ComponentXMLTracer(CoreComponent* component);
- private:
- static void printData(char direction, const SafeByteArray& data);
- static void printLine(char c);
- };
+ private:
+ static void printData(char direction, const SafeByteArray& data);
+ static void printLine(char c);
+ };
}
diff --git a/Swiften/Component/CoreComponent.cpp b/Swiften/Component/CoreComponent.cpp
index fbf59f3..0b8e01c 100644
--- a/Swiften/Component/CoreComponent.cpp
+++ b/Swiften/Component/CoreComponent.cpp
@@ -23,148 +23,148 @@
namespace Swift {
CoreComponent::CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories) : networkFactories(networkFactories), jid_(jid), secret_(secret), disconnectRequested_(false) {
- stanzaChannel_ = new ComponentSessionStanzaChannel();
- stanzaChannel_->onMessageReceived.connect(boost::ref(onMessageReceived));
- stanzaChannel_->onPresenceReceived.connect(boost::ref(onPresenceReceived));
- stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1));
+ stanzaChannel_ = new ComponentSessionStanzaChannel();
+ stanzaChannel_->onMessageReceived.connect(boost::ref(onMessageReceived));
+ stanzaChannel_->onPresenceReceived.connect(boost::ref(onPresenceReceived));
+ stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1));
- iqRouter_ = new IQRouter(stanzaChannel_);
- iqRouter_->setFrom(jid);
+ iqRouter_ = new IQRouter(stanzaChannel_);
+ iqRouter_->setFrom(jid);
}
CoreComponent::~CoreComponent() {
- if (session_ || connection_) {
- std::cerr << "Warning: Component not disconnected properly" << std::endl;
- }
- delete iqRouter_;
-
- stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1));
- stanzaChannel_->onMessageReceived.disconnect(boost::ref(onMessageReceived));
- stanzaChannel_->onPresenceReceived.disconnect(boost::ref(onPresenceReceived));
- delete stanzaChannel_;
+ if (session_ || connection_) {
+ std::cerr << "Warning: Component not disconnected properly" << std::endl;
+ }
+ delete iqRouter_;
+
+ stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1));
+ stanzaChannel_->onMessageReceived.disconnect(boost::ref(onMessageReceived));
+ stanzaChannel_->onPresenceReceived.disconnect(boost::ref(onPresenceReceived));
+ delete stanzaChannel_;
}
void CoreComponent::connect(const std::string& host, int port) {
- assert(!connector_);
- connector_ = ComponentConnector::create(host, port, networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory());
- connector_->onConnectFinished.connect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1));
- connector_->setTimeoutMilliseconds(60*1000);
- connector_->start();
+ assert(!connector_);
+ connector_ = ComponentConnector::create(host, port, networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory());
+ connector_->onConnectFinished.connect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1));
+ connector_->setTimeoutMilliseconds(60*1000);
+ connector_->start();
}
void CoreComponent::handleConnectorFinished(boost::shared_ptr<Connection> connection) {
- connector_->onConnectFinished.disconnect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1));
- connector_.reset();
- if (!connection) {
- if (!disconnectRequested_) {
- onError(ComponentError::ConnectionError);
- }
- }
- else {
- assert(!connection_);
- connection_ = connection;
-
- assert(!sessionStream_);
- sessionStream_ = boost::shared_ptr<BasicSessionStream>(new BasicSessionStream(ComponentStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), NULL, networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), TLSOptions()));
- sessionStream_->onDataRead.connect(boost::bind(&CoreComponent::handleDataRead, this, _1));
- sessionStream_->onDataWritten.connect(boost::bind(&CoreComponent::handleDataWritten, this, _1));
-
- session_ = ComponentSession::create(jid_, secret_, sessionStream_, networkFactories->getCryptoProvider());
- stanzaChannel_->setSession(session_);
- session_->onFinished.connect(boost::bind(&CoreComponent::handleSessionFinished, this, _1));
- session_->start();
- }
+ connector_->onConnectFinished.disconnect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1));
+ connector_.reset();
+ if (!connection) {
+ if (!disconnectRequested_) {
+ onError(ComponentError::ConnectionError);
+ }
+ }
+ else {
+ assert(!connection_);
+ connection_ = connection;
+
+ assert(!sessionStream_);
+ sessionStream_ = boost::shared_ptr<BasicSessionStream>(new BasicSessionStream(ComponentStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), NULL, networkFactories->getTimerFactory(), networkFactories->getXMLParserFactory(), TLSOptions()));
+ sessionStream_->onDataRead.connect(boost::bind(&CoreComponent::handleDataRead, this, _1));
+ sessionStream_->onDataWritten.connect(boost::bind(&CoreComponent::handleDataWritten, this, _1));
+
+ session_ = ComponentSession::create(jid_, secret_, sessionStream_, networkFactories->getCryptoProvider());
+ stanzaChannel_->setSession(session_);
+ session_->onFinished.connect(boost::bind(&CoreComponent::handleSessionFinished, this, _1));
+ session_->start();
+ }
}
void CoreComponent::disconnect() {
- // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between
- // connector finishing without a connection due to an error or because of a disconnect.
- disconnectRequested_ = true;
- if (session_) {
- session_->finish();
- }
- else if (connector_) {
- connector_->stop();
- assert(!session_);
- }
- //assert(!session_); /* commenting out until we have time to refactor to be like CoreClient */
- //assert(!sessionStream_);
- //assert(!connector_);
- disconnectRequested_ = false;
+ // FIXME: We should be able to do without this boolean. We just have to make sure we can tell the difference between
+ // connector finishing without a connection due to an error or because of a disconnect.
+ disconnectRequested_ = true;
+ if (session_) {
+ session_->finish();
+ }
+ else if (connector_) {
+ connector_->stop();
+ assert(!session_);
+ }
+ //assert(!session_); /* commenting out until we have time to refactor to be like CoreClient */
+ //assert(!sessionStream_);
+ //assert(!connector_);
+ disconnectRequested_ = false;
}
void CoreComponent::handleSessionFinished(boost::shared_ptr<Error> error) {
- session_->onFinished.disconnect(boost::bind(&CoreComponent::handleSessionFinished, this, _1));
- session_.reset();
-
- sessionStream_->onDataRead.disconnect(boost::bind(&CoreComponent::handleDataRead, this, _1));
- sessionStream_->onDataWritten.disconnect(boost::bind(&CoreComponent::handleDataWritten, this, _1));
- sessionStream_.reset();
-
- connection_->disconnect();
- connection_.reset();
-
- if (error) {
- ComponentError componentError;
- if (boost::shared_ptr<ComponentSession::Error> actualError = boost::dynamic_pointer_cast<ComponentSession::Error>(error)) {
- switch(actualError->type) {
- case ComponentSession::Error::AuthenticationFailedError:
- componentError = ComponentError(ComponentError::AuthenticationFailedError);
- break;
- case ComponentSession::Error::UnexpectedElementError:
- componentError = ComponentError(ComponentError::UnexpectedElementError);
- break;
- }
- }
- else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) {
- switch(actualError->type) {
- case SessionStream::SessionStreamError::ParseError:
- componentError = ComponentError(ComponentError::XMLError);
- break;
- case SessionStream::SessionStreamError::TLSError:
- assert(false);
- componentError = ComponentError(ComponentError::UnknownError);
- break;
- case SessionStream::SessionStreamError::InvalidTLSCertificateError:
- assert(false);
- componentError = ComponentError(ComponentError::UnknownError);
- break;
- case SessionStream::SessionStreamError::ConnectionReadError:
- componentError = ComponentError(ComponentError::ConnectionReadError);
- break;
- case SessionStream::SessionStreamError::ConnectionWriteError:
- componentError = ComponentError(ComponentError::ConnectionWriteError);
- break;
- }
- }
- onError(componentError);
- }
+ session_->onFinished.disconnect(boost::bind(&CoreComponent::handleSessionFinished, this, _1));
+ session_.reset();
+
+ sessionStream_->onDataRead.disconnect(boost::bind(&CoreComponent::handleDataRead, this, _1));
+ sessionStream_->onDataWritten.disconnect(boost::bind(&CoreComponent::handleDataWritten, this, _1));
+ sessionStream_.reset();
+
+ connection_->disconnect();
+ connection_.reset();
+
+ if (error) {
+ ComponentError componentError;
+ if (boost::shared_ptr<ComponentSession::Error> actualError = boost::dynamic_pointer_cast<ComponentSession::Error>(error)) {
+ switch(actualError->type) {
+ case ComponentSession::Error::AuthenticationFailedError:
+ componentError = ComponentError(ComponentError::AuthenticationFailedError);
+ break;
+ case ComponentSession::Error::UnexpectedElementError:
+ componentError = ComponentError(ComponentError::UnexpectedElementError);
+ break;
+ }
+ }
+ else if (boost::shared_ptr<SessionStream::SessionStreamError> actualError = boost::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) {
+ switch(actualError->type) {
+ case SessionStream::SessionStreamError::ParseError:
+ componentError = ComponentError(ComponentError::XMLError);
+ break;
+ case SessionStream::SessionStreamError::TLSError:
+ assert(false);
+ componentError = ComponentError(ComponentError::UnknownError);
+ break;
+ case SessionStream::SessionStreamError::InvalidTLSCertificateError:
+ assert(false);
+ componentError = ComponentError(ComponentError::UnknownError);
+ break;
+ case SessionStream::SessionStreamError::ConnectionReadError:
+ componentError = ComponentError(ComponentError::ConnectionReadError);
+ break;
+ case SessionStream::SessionStreamError::ConnectionWriteError:
+ componentError = ComponentError(ComponentError::ConnectionWriteError);
+ break;
+ }
+ }
+ onError(componentError);
+ }
}
void CoreComponent::handleDataRead(const SafeByteArray& data) {
- onDataRead(data);
+ onDataRead(data);
}
void CoreComponent::handleDataWritten(const SafeByteArray& data) {
- onDataWritten(data);
+ onDataWritten(data);
}
void CoreComponent::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- onConnected();
- }
+ if (available) {
+ onConnected();
+ }
}
void CoreComponent::sendMessage(boost::shared_ptr<Message> message) {
- stanzaChannel_->sendMessage(message);
+ stanzaChannel_->sendMessage(message);
}
void CoreComponent::sendPresence(boost::shared_ptr<Presence> presence) {
- stanzaChannel_->sendPresence(presence);
+ stanzaChannel_->sendPresence(presence);
}
void CoreComponent::sendData(const std::string& data) {
- sessionStream_->writeData(data);
+ sessionStream_->writeData(data);
}
}
diff --git a/Swiften/Component/CoreComponent.h b/Swiften/Component/CoreComponent.h
index 12b38eb..ff88173 100644
--- a/Swiften/Component/CoreComponent.h
+++ b/Swiften/Component/CoreComponent.h
@@ -26,79 +26,79 @@
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
namespace Swift {
- class EventLoop;
- class IQRouter;
- class NetworkFactories;
- class ComponentSession;
- class BasicSessionStream;
-
- /**
- * The central class for communicating with an XMPP server as a component.
- *
- * This class is responsible for setting up the connection with the XMPP
- * server and authenticating the component.
- *
- * This class can be used directly in your application, although the Component
- * subclass provides more functionality and interfaces, and is better suited
- * for most needs.
- */
- class SWIFTEN_API CoreComponent : public Entity {
- public:
- CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories);
- virtual ~CoreComponent();
-
- void connect(const std::string& host, int port);
- void disconnect();
-
- void sendMessage(boost::shared_ptr<Message>);
- void sendPresence(boost::shared_ptr<Presence>);
- void sendData(const std::string& data);
-
- IQRouter* getIQRouter() const {
- return iqRouter_;
- }
-
- StanzaChannel* getStanzaChannel() const {
- return stanzaChannel_;
- }
-
- bool isAvailable() const {
- return stanzaChannel_->isAvailable();
- }
-
- /**
- * Returns the JID of the component
- */
- const JID& getJID() const {
- return jid_;
- }
-
- public:
- boost::signal<void (const ComponentError&)> onError;
- boost::signal<void ()> onConnected;
- boost::signal<void (const SafeByteArray&)> onDataRead;
- boost::signal<void (const SafeByteArray&)> onDataWritten;
-
- boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
- boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
-
- private:
- void handleConnectorFinished(boost::shared_ptr<Connection>);
- void handleStanzaChannelAvailableChanged(bool available);
- void handleSessionFinished(boost::shared_ptr<Error>);
- void handleDataRead(const SafeByteArray&);
- void handleDataWritten(const SafeByteArray&);
-
- private:
- NetworkFactories* networkFactories;
- JID jid_;
- std::string secret_;
- ComponentSessionStanzaChannel* stanzaChannel_;
- IQRouter* iqRouter_;
- ComponentConnector::ref connector_;
- boost::shared_ptr<Connection> connection_;
- boost::shared_ptr<BasicSessionStream> sessionStream_;
- boost::shared_ptr<ComponentSession> session_;
- bool disconnectRequested_;
- };
+ class EventLoop;
+ class IQRouter;
+ class NetworkFactories;
+ class ComponentSession;
+ class BasicSessionStream;
+
+ /**
+ * The central class for communicating with an XMPP server as a component.
+ *
+ * This class is responsible for setting up the connection with the XMPP
+ * server and authenticating the component.
+ *
+ * This class can be used directly in your application, although the Component
+ * subclass provides more functionality and interfaces, and is better suited
+ * for most needs.
+ */
+ class SWIFTEN_API CoreComponent : public Entity {
+ public:
+ CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories);
+ virtual ~CoreComponent();
+
+ void connect(const std::string& host, int port);
+ void disconnect();
+
+ void sendMessage(boost::shared_ptr<Message>);
+ void sendPresence(boost::shared_ptr<Presence>);
+ void sendData(const std::string& data);
+
+ IQRouter* getIQRouter() const {
+ return iqRouter_;
+ }
+
+ StanzaChannel* getStanzaChannel() const {
+ return stanzaChannel_;
+ }
+
+ bool isAvailable() const {
+ return stanzaChannel_->isAvailable();
+ }
+
+ /**
+ * Returns the JID of the component
+ */
+ const JID& getJID() const {
+ return jid_;
+ }
+
+ public:
+ boost::signal<void (const ComponentError&)> onError;
+ boost::signal<void ()> onConnected;
+ boost::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signal<void (const SafeByteArray&)> onDataWritten;
+
+ boost::signal<void (boost::shared_ptr<Message>)> onMessageReceived;
+ boost::signal<void (boost::shared_ptr<Presence>) > onPresenceReceived;
+
+ private:
+ void handleConnectorFinished(boost::shared_ptr<Connection>);
+ void handleStanzaChannelAvailableChanged(bool available);
+ void handleSessionFinished(boost::shared_ptr<Error>);
+ void handleDataRead(const SafeByteArray&);
+ void handleDataWritten(const SafeByteArray&);
+
+ private:
+ NetworkFactories* networkFactories;
+ JID jid_;
+ std::string secret_;
+ ComponentSessionStanzaChannel* stanzaChannel_;
+ IQRouter* iqRouter_;
+ ComponentConnector::ref connector_;
+ boost::shared_ptr<Connection> connection_;
+ boost::shared_ptr<BasicSessionStream> sessionStream_;
+ boost::shared_ptr<ComponentSession> session_;
+ bool disconnectRequested_;
+ };
}
diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
index 3968c2c..04a6a9e 100644
--- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
@@ -21,190 +21,190 @@
using namespace Swift;
class ComponentConnectorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ComponentConnectorTest);
- CPPUNIT_TEST(testConnect);
- CPPUNIT_TEST(testConnect_FirstAddressHostFails);
- CPPUNIT_TEST(testConnect_NoHosts);
- CPPUNIT_TEST(testConnect_TimeoutDuringResolve);
- CPPUNIT_TEST(testConnect_TimeoutDuringConnect);
- CPPUNIT_TEST(testConnect_NoTimeout);
- CPPUNIT_TEST(testStop_Timeout);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- host1 = HostAddress("1.1.1.1");
- host2 = HostAddress("2.2.2.2");
- eventLoop = new DummyEventLoop();
- resolver = new StaticDomainNameResolver(eventLoop);
- connectionFactory = new MockConnectionFactory(eventLoop);
- timerFactory = new DummyTimerFactory();
- }
-
- void tearDown() {
- delete timerFactory;
- delete connectionFactory;
- delete resolver;
- delete eventLoop;
- }
-
- void testConnect() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
- resolver->addAddress("foo.com", host1);
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(HostAddressPort(host1, 1234) == *(connections[0]->hostAddressPort));
- }
-
- void testConnect_FirstAddressHostFails() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
- resolver->addAddress("foo.com", host1);
- resolver->addAddress("foo.com", host2);
- connectionFactory->failingPorts.push_back(HostAddressPort(host1, 1234));
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(HostAddressPort(host2, 1234) == *(connections[0]->hostAddressPort));
- }
-
- void testConnect_NoHosts() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
-
- void testConnect_TimeoutDuringResolve() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
-
- testling->setTimeoutMilliseconds(10);
- resolver->setIsResponsive(false);
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
- void testConnect_TimeoutDuringConnect() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
- testling->setTimeoutMilliseconds(10);
- resolver->addAddress("foo.com", host1);
- connectionFactory->isResponsive = false;
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
- void testConnect_NoTimeout() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
- testling->setTimeoutMilliseconds(10);
- resolver->addAddress("foo.com", host1);
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- }
-
- void testStop_Timeout() {
- ComponentConnector::ref testling(createConnector("foo.com", 1234));
- testling->setTimeoutMilliseconds(10);
- resolver->addAddress("foo.com", host1);
-
- testling->start();
- testling->stop();
-
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
- private:
- ComponentConnector::ref createConnector(const std::string& hostname, int port) {
- ComponentConnector::ref connector = ComponentConnector::create(hostname, port, resolver, connectionFactory, timerFactory);
- connector->onConnectFinished.connect(boost::bind(&ComponentConnectorTest::handleConnectorFinished, this, _1));
- return connector;
- }
-
- void handleConnectorFinished(boost::shared_ptr<Connection> connection) {
- boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
- if (connection) {
- assert(c);
- }
- connections.push_back(c);
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {}
-
- void listen() { assert(false); }
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- if (isResponsive) {
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
- }
-
- void disconnect() { assert(false); }
- void write(const SafeByteArray&) { assert(false); }
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- bool isResponsive;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop));
- }
-
- EventLoop* eventLoop;
- bool isResponsive;
- std::vector<HostAddressPort> failingPorts;
- };
-
- private:
- HostAddress host1;
- HostAddress host2;
- DummyEventLoop* eventLoop;
- StaticDomainNameResolver* resolver;
- MockConnectionFactory* connectionFactory;
- DummyTimerFactory* timerFactory;
- std::vector< boost::shared_ptr<MockConnection> > connections;
+ CPPUNIT_TEST_SUITE(ComponentConnectorTest);
+ CPPUNIT_TEST(testConnect);
+ CPPUNIT_TEST(testConnect_FirstAddressHostFails);
+ CPPUNIT_TEST(testConnect_NoHosts);
+ CPPUNIT_TEST(testConnect_TimeoutDuringResolve);
+ CPPUNIT_TEST(testConnect_TimeoutDuringConnect);
+ CPPUNIT_TEST(testConnect_NoTimeout);
+ CPPUNIT_TEST(testStop_Timeout);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ host1 = HostAddress("1.1.1.1");
+ host2 = HostAddress("2.2.2.2");
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ connectionFactory = new MockConnectionFactory(eventLoop);
+ timerFactory = new DummyTimerFactory();
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete connectionFactory;
+ delete resolver;
+ delete eventLoop;
+ }
+
+ void testConnect() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+ resolver->addAddress("foo.com", host1);
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(HostAddressPort(host1, 1234) == *(connections[0]->hostAddressPort));
+ }
+
+ void testConnect_FirstAddressHostFails() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+ resolver->addAddress("foo.com", host1);
+ resolver->addAddress("foo.com", host2);
+ connectionFactory->failingPorts.push_back(HostAddressPort(host1, 1234));
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(HostAddressPort(host2, 1234) == *(connections[0]->hostAddressPort));
+ }
+
+ void testConnect_NoHosts() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+
+ void testConnect_TimeoutDuringResolve() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+
+ testling->setTimeoutMilliseconds(10);
+ resolver->setIsResponsive(false);
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+ void testConnect_TimeoutDuringConnect() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+ testling->setTimeoutMilliseconds(10);
+ resolver->addAddress("foo.com", host1);
+ connectionFactory->isResponsive = false;
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+ void testConnect_NoTimeout() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+ testling->setTimeoutMilliseconds(10);
+ resolver->addAddress("foo.com", host1);
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ }
+
+ void testStop_Timeout() {
+ ComponentConnector::ref testling(createConnector("foo.com", 1234));
+ testling->setTimeoutMilliseconds(10);
+ resolver->addAddress("foo.com", host1);
+
+ testling->start();
+ testling->stop();
+
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+ private:
+ ComponentConnector::ref createConnector(const std::string& hostname, int port) {
+ ComponentConnector::ref connector = ComponentConnector::create(hostname, port, resolver, connectionFactory, timerFactory);
+ connector->onConnectFinished.connect(boost::bind(&ComponentConnectorTest::handleConnectorFinished, this, _1));
+ return connector;
+ }
+
+ void handleConnectorFinished(boost::shared_ptr<Connection> connection) {
+ boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
+ if (connection) {
+ assert(c);
+ }
+ connections.push_back(c);
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {}
+
+ void listen() { assert(false); }
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ if (isResponsive) {
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+ }
+
+ void disconnect() { assert(false); }
+ void write(const SafeByteArray&) { assert(false); }
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ bool isResponsive;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop));
+ }
+
+ EventLoop* eventLoop;
+ bool isResponsive;
+ std::vector<HostAddressPort> failingPorts;
+ };
+
+ private:
+ HostAddress host1;
+ HostAddress host2;
+ DummyEventLoop* eventLoop;
+ StaticDomainNameResolver* resolver;
+ MockConnectionFactory* connectionFactory;
+ DummyTimerFactory* timerFactory;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ComponentConnectorTest);
diff --git a/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp b/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp
index 570ccf1..82f43f6 100644
--- a/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp
@@ -14,28 +14,28 @@
using namespace Swift;
class ComponentHandshakeGeneratorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ComponentHandshakeGeneratorTest);
- CPPUNIT_TEST(testGetHandshake);
- CPPUNIT_TEST(testGetHandshake_SpecialChars);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
-
- void testGetHandshake() {
- std::string result = ComponentHandshakeGenerator::getHandshake("myid", "mysecret", crypto.get());
- CPPUNIT_ASSERT_EQUAL(std::string("4011cd31f9b99ac089a0cd7ce297da7323fa2525"), result);
- }
-
- void testGetHandshake_SpecialChars() {
- std::string result = ComponentHandshakeGenerator::getHandshake("&<", ">'\"", crypto.get());
- CPPUNIT_ASSERT_EQUAL(std::string("33631b3e0aaeb2a11c4994c917919324028873fe"), result);
- }
-
- private:
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(ComponentHandshakeGeneratorTest);
+ CPPUNIT_TEST(testGetHandshake);
+ CPPUNIT_TEST(testGetHandshake_SpecialChars);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
+
+ void testGetHandshake() {
+ std::string result = ComponentHandshakeGenerator::getHandshake("myid", "mysecret", crypto.get());
+ CPPUNIT_ASSERT_EQUAL(std::string("4011cd31f9b99ac089a0cd7ce297da7323fa2525"), result);
+ }
+
+ void testGetHandshake_SpecialChars() {
+ std::string result = ComponentHandshakeGenerator::getHandshake("&<", ">'\"", crypto.get());
+ CPPUNIT_ASSERT_EQUAL(std::string("33631b3e0aaeb2a11c4994c917919324028873fe"), result);
+ }
+
+ private:
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ComponentHandshakeGeneratorTest);
diff --git a/Swiften/Component/UnitTest/ComponentSessionTest.cpp b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
index 61c8ce9..1726794 100644
--- a/Swiften/Component/UnitTest/ComponentSessionTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
@@ -22,201 +22,201 @@
using namespace Swift;
class ComponentSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ComponentSessionTest);
- CPPUNIT_TEST(testStart);
- CPPUNIT_TEST(testStart_Error);
- CPPUNIT_TEST(testStart_Unauthorized);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- server = boost::make_shared<MockSessionStream>();
- sessionFinishedReceived = false;
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
-
- void testStart() {
- boost::shared_ptr<ComponentSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->receiveHandshake();
- server->sendHandshakeResponse();
-
- CPPUNIT_ASSERT(server->whitespacePingEnabled);
-
- session->finish();
- CPPUNIT_ASSERT(!server->whitespacePingEnabled);
-
- }
-
- void testStart_Error() {
- boost::shared_ptr<ComponentSession> session(createSession());
- session->start();
- server->breakConnection();
-
- CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- void testStart_Unauthorized() {
- boost::shared_ptr<ComponentSession> session(createSession());
- session->start();
- server->receiveStreamStart();
- server->sendStreamStart();
- server->receiveHandshake();
- server->sendHandshakeError();
-
- CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState());
- CPPUNIT_ASSERT(sessionFinishedReceived);
- CPPUNIT_ASSERT(sessionFinishedError);
- }
-
- private:
- boost::shared_ptr<ComponentSession> createSession() {
- boost::shared_ptr<ComponentSession> session = ComponentSession::create(JID("service.foo.com"), "servicesecret", server, crypto.get());
- session->onFinished.connect(boost::bind(&ComponentSessionTest::handleSessionFinished, this, _1));
- return session;
- }
-
- void handleSessionFinished(boost::shared_ptr<Error> error) {
- sessionFinishedReceived = true;
- sessionFinishedError = error;
- }
-
- class MockSessionStream : public SessionStream {
- public:
- struct Event {
- Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
- Event(const ProtocolHeader& header) : header(header), footer(false) {}
- Event() : footer(true) {}
-
- boost::shared_ptr<ToplevelElement> element;
- boost::optional<ProtocolHeader> header;
- bool footer;
- };
-
- MockSessionStream() : available(true), whitespacePingEnabled(false), resetCount(0) {
- }
-
- virtual void close() {
- onClosed(boost::shared_ptr<Error>());
- }
-
- virtual bool isOpen() {
- return available;
- }
-
- virtual void writeHeader(const ProtocolHeader& header) {
- receivedEvents.push_back(Event(header));
- }
-
- virtual void writeFooter() {
- receivedEvents.push_back(Event());
- }
-
- virtual void writeElement(boost::shared_ptr<ToplevelElement> element) {
- receivedEvents.push_back(Event(element));
- }
-
- virtual void writeData(const std::string&) {
- }
-
- virtual bool supportsTLSEncryption() {
- return false;
- }
-
- virtual void addTLSEncryption() {
- assert(false);
- }
-
- virtual bool isTLSEncrypted() {
- return false;
- }
-
- virtual ByteArray getTLSFinishMessage() const {
- return ByteArray();
- }
-
- virtual Certificate::ref getPeerCertificate() const {
- return Certificate::ref();
- }
-
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const {
- return std::vector<Certificate::ref>();
- }
-
- virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
- return boost::shared_ptr<CertificateVerificationError>();
- }
-
- virtual bool supportsZLibCompression() {
- return true;
- }
-
- virtual void addZLibCompression() {
- assert(false);
- }
-
- virtual void setWhitespacePingEnabled(bool enabled) {
- whitespacePingEnabled = enabled;
- }
-
- virtual void resetXMPPParser() {
- resetCount++;
- }
-
- void breakConnection() {
- onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError));
- }
-
- void sendStreamStart() {
- ProtocolHeader header;
- header.setFrom("service.foo.com");
- return onStreamStartReceived(header);
- }
-
- void sendHandshakeResponse() {
- onElementReceived(ComponentHandshake::ref(new ComponentHandshake()));
- }
-
- void sendHandshakeError() {
- // FIXME: This isn't the correct element
- onElementReceived(AuthFailure::ref(new AuthFailure()));
- }
-
- void receiveStreamStart() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.header);
- }
-
- void receiveHandshake() {
- Event event = popEvent();
- CPPUNIT_ASSERT(event.element);
- ComponentHandshake::ref handshake(boost::dynamic_pointer_cast<ComponentHandshake>(event.element));
- CPPUNIT_ASSERT(handshake);
- CPPUNIT_ASSERT_EQUAL(std::string("4c4f8a41141722c8bbfbdd92d827f7b2fc0a542b"), handshake->getData());
- }
-
- Event popEvent() {
- CPPUNIT_ASSERT(!receivedEvents.empty());
- Event event = receivedEvents.front();
- receivedEvents.pop_front();
- return event;
- }
-
- bool available;
- bool whitespacePingEnabled;
- std::string bindID;
- int resetCount;
- std::deque<Event> receivedEvents;
- };
-
- boost::shared_ptr<MockSessionStream> server;
- bool sessionFinishedReceived;
- boost::shared_ptr<Error> sessionFinishedError;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(ComponentSessionTest);
+ CPPUNIT_TEST(testStart);
+ CPPUNIT_TEST(testStart_Error);
+ CPPUNIT_TEST(testStart_Unauthorized);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ server = boost::make_shared<MockSessionStream>();
+ sessionFinishedReceived = false;
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
+
+ void testStart() {
+ boost::shared_ptr<ComponentSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->receiveHandshake();
+ server->sendHandshakeResponse();
+
+ CPPUNIT_ASSERT(server->whitespacePingEnabled);
+
+ session->finish();
+ CPPUNIT_ASSERT(!server->whitespacePingEnabled);
+
+ }
+
+ void testStart_Error() {
+ boost::shared_ptr<ComponentSession> session(createSession());
+ session->start();
+ server->breakConnection();
+
+ CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStart_Unauthorized() {
+ boost::shared_ptr<ComponentSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->receiveHandshake();
+ server->sendHandshakeError();
+
+ CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ private:
+ boost::shared_ptr<ComponentSession> createSession() {
+ boost::shared_ptr<ComponentSession> session = ComponentSession::create(JID("service.foo.com"), "servicesecret", server, crypto.get());
+ session->onFinished.connect(boost::bind(&ComponentSessionTest::handleSessionFinished, this, _1));
+ return session;
+ }
+
+ void handleSessionFinished(boost::shared_ptr<Error> error) {
+ sessionFinishedReceived = true;
+ sessionFinishedError = error;
+ }
+
+ class MockSessionStream : public SessionStream {
+ public:
+ struct Event {
+ Event(boost::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
+ Event(const ProtocolHeader& header) : header(header), footer(false) {}
+ Event() : footer(true) {}
+
+ boost::shared_ptr<ToplevelElement> element;
+ boost::optional<ProtocolHeader> header;
+ bool footer;
+ };
+
+ MockSessionStream() : available(true), whitespacePingEnabled(false), resetCount(0) {
+ }
+
+ virtual void close() {
+ onClosed(boost::shared_ptr<Error>());
+ }
+
+ virtual bool isOpen() {
+ return available;
+ }
+
+ virtual void writeHeader(const ProtocolHeader& header) {
+ receivedEvents.push_back(Event(header));
+ }
+
+ virtual void writeFooter() {
+ receivedEvents.push_back(Event());
+ }
+
+ virtual void writeElement(boost::shared_ptr<ToplevelElement> element) {
+ receivedEvents.push_back(Event(element));
+ }
+
+ virtual void writeData(const std::string&) {
+ }
+
+ virtual bool supportsTLSEncryption() {
+ return false;
+ }
+
+ virtual void addTLSEncryption() {
+ assert(false);
+ }
+
+ virtual bool isTLSEncrypted() {
+ return false;
+ }
+
+ virtual ByteArray getTLSFinishMessage() const {
+ return ByteArray();
+ }
+
+ virtual Certificate::ref getPeerCertificate() const {
+ return Certificate::ref();
+ }
+
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const {
+ return std::vector<Certificate::ref>();
+ }
+
+ virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
+ return boost::shared_ptr<CertificateVerificationError>();
+ }
+
+ virtual bool supportsZLibCompression() {
+ return true;
+ }
+
+ virtual void addZLibCompression() {
+ assert(false);
+ }
+
+ virtual void setWhitespacePingEnabled(bool enabled) {
+ whitespacePingEnabled = enabled;
+ }
+
+ virtual void resetXMPPParser() {
+ resetCount++;
+ }
+
+ void breakConnection() {
+ onClosed(boost::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError));
+ }
+
+ void sendStreamStart() {
+ ProtocolHeader header;
+ header.setFrom("service.foo.com");
+ return onStreamStartReceived(header);
+ }
+
+ void sendHandshakeResponse() {
+ onElementReceived(ComponentHandshake::ref(new ComponentHandshake()));
+ }
+
+ void sendHandshakeError() {
+ // FIXME: This isn't the correct element
+ onElementReceived(AuthFailure::ref(new AuthFailure()));
+ }
+
+ void receiveStreamStart() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.header);
+ }
+
+ void receiveHandshake() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ ComponentHandshake::ref handshake(boost::dynamic_pointer_cast<ComponentHandshake>(event.element));
+ CPPUNIT_ASSERT(handshake);
+ CPPUNIT_ASSERT_EQUAL(std::string("4c4f8a41141722c8bbfbdd92d827f7b2fc0a542b"), handshake->getData());
+ }
+
+ Event popEvent() {
+ CPPUNIT_ASSERT(!receivedEvents.empty());
+ Event event = receivedEvents.front();
+ receivedEvents.pop_front();
+ return event;
+ }
+
+ bool available;
+ bool whitespacePingEnabled;
+ std::string bindID;
+ int resetCount;
+ std::deque<Event> receivedEvents;
+ };
+
+ boost::shared_ptr<MockSessionStream> server;
+ bool sessionFinishedReceived;
+ boost::shared_ptr<Error> sessionFinishedError;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ComponentSessionTest);
diff --git a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
index 584a4f7..ca99201 100644
--- a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
@@ -17,28 +17,28 @@ using namespace Swift;
class ZLibCompressorTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ZLibCompressorTest);
- CPPUNIT_TEST(testProcess);
- CPPUNIT_TEST(testProcess_Twice);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ZLibCompressorTest);
+ CPPUNIT_TEST(testProcess);
+ CPPUNIT_TEST(testProcess_Twice);
+ CPPUNIT_TEST_SUITE_END();
- public:
- ZLibCompressorTest() {}
+ public:
+ ZLibCompressorTest() {}
- void testProcess() {
- ZLibCompressor testling;
- SafeByteArray result = testling.process(createSafeByteArray("foo"));
+ void testProcess() {
+ ZLibCompressor testling;
+ SafeByteArray result = testling.process(createSafeByteArray("foo"));
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11), result);
+ }
- void testProcess_Twice() {
- ZLibCompressor testling;
- testling.process(createSafeByteArray("foo"));
- SafeByteArray result = testling.process(createSafeByteArray("bar"));
+ void testProcess_Twice() {
+ ZLibCompressor testling;
+ testling.process(createSafeByteArray("foo"));
+ SafeByteArray result = testling.process(createSafeByteArray("bar"));
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff",9), result);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ZLibCompressorTest);
diff --git a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
index 7e57676..5873c0e 100644
--- a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
@@ -19,62 +19,62 @@ using namespace Swift;
class ZLibDecompressorTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ZLibDecompressorTest);
- CPPUNIT_TEST(testProcess);
- CPPUNIT_TEST(testProcess_Twice);
- CPPUNIT_TEST(testProcess_Invalid);
- CPPUNIT_TEST(testProcess_Huge);
- CPPUNIT_TEST(testProcess_ChunkSize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- ZLibDecompressorTest() {}
-
- void testProcess() {
- ZLibDecompressor testling;
- SafeByteArray result = testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), result);
- }
-
- void testProcess_Twice() {
- ZLibDecompressor testling;
- testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
- SafeByteArray result = testling.process(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("bar"), result);
- }
-
- void testProcess_Invalid() {
- ZLibDecompressor testling;
- CPPUNIT_ASSERT_THROW(testling.process(createSafeByteArray("invalid")), ZLibException);
- }
-
- void testProcess_Huge() {
- std::vector<char> data;
- data.reserve(2048);
- for (unsigned int i = 0; i < 2048; ++i) {
- data.push_back(static_cast<char>(i));
- }
- SafeByteArray original(createSafeByteArray(&data[0], data.size()));
- SafeByteArray compressed = ZLibCompressor().process(original);
- SafeByteArray decompressed = ZLibDecompressor().process(compressed);
-
- CPPUNIT_ASSERT_EQUAL(original, decompressed);
- }
-
- void testProcess_ChunkSize() {
- std::vector<char> data;
- data.reserve(1024);
- for (unsigned int i = 0; i < 1024; ++i) {
- data.push_back(static_cast<char>(i));
- }
- SafeByteArray original(createSafeByteArray(&data[0], data.size()));
- SafeByteArray compressed = ZLibCompressor().process(original);
- SafeByteArray decompressed = ZLibDecompressor().process(compressed);
-
- CPPUNIT_ASSERT_EQUAL(original, decompressed);
- }
+ CPPUNIT_TEST_SUITE(ZLibDecompressorTest);
+ CPPUNIT_TEST(testProcess);
+ CPPUNIT_TEST(testProcess_Twice);
+ CPPUNIT_TEST(testProcess_Invalid);
+ CPPUNIT_TEST(testProcess_Huge);
+ CPPUNIT_TEST(testProcess_ChunkSize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ ZLibDecompressorTest() {}
+
+ void testProcess() {
+ ZLibDecompressor testling;
+ SafeByteArray result = testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), result);
+ }
+
+ void testProcess_Twice() {
+ ZLibDecompressor testling;
+ testling.process(createSafeByteArray("\x78\xda\x4a\xcb\xcf\x07\x00\x00\x00\xff\xff", 11));
+ SafeByteArray result = testling.process(createSafeByteArray("\x4a\x4a\x2c\x02\x00\x00\x00\xff\xff", 9));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("bar"), result);
+ }
+
+ void testProcess_Invalid() {
+ ZLibDecompressor testling;
+ CPPUNIT_ASSERT_THROW(testling.process(createSafeByteArray("invalid")), ZLibException);
+ }
+
+ void testProcess_Huge() {
+ std::vector<char> data;
+ data.reserve(2048);
+ for (unsigned int i = 0; i < 2048; ++i) {
+ data.push_back(static_cast<char>(i));
+ }
+ SafeByteArray original(createSafeByteArray(&data[0], data.size()));
+ SafeByteArray compressed = ZLibCompressor().process(original);
+ SafeByteArray decompressed = ZLibDecompressor().process(compressed);
+
+ CPPUNIT_ASSERT_EQUAL(original, decompressed);
+ }
+
+ void testProcess_ChunkSize() {
+ std::vector<char> data;
+ data.reserve(1024);
+ for (unsigned int i = 0; i < 1024; ++i) {
+ data.push_back(static_cast<char>(i));
+ }
+ SafeByteArray original(createSafeByteArray(&data[0], data.size()));
+ SafeByteArray compressed = ZLibCompressor().process(original);
+ SafeByteArray decompressed = ZLibDecompressor().process(compressed);
+
+ CPPUNIT_ASSERT_EQUAL(original, decompressed);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ZLibDecompressorTest);
diff --git a/Swiften/Compress/ZLibCodecompressor.cpp b/Swiften/Compress/ZLibCodecompressor.cpp
index 7c413b7..fd6d3b0 100644
--- a/Swiften/Compress/ZLibCodecompressor.cpp
+++ b/Swiften/Compress/ZLibCodecompressor.cpp
@@ -23,36 +23,36 @@ static const size_t CHUNK_SIZE = 1024; // If you change this, also change the un
ZLibCodecompressor::ZLibCodecompressor() : p(boost::make_shared<Private>()) {
- memset(&p->stream, 0, sizeof(z_stream));
- p->stream.zalloc = Z_NULL;
- p->stream.zfree = Z_NULL;
- p->stream.opaque = Z_NULL;
+ memset(&p->stream, 0, sizeof(z_stream));
+ p->stream.zalloc = Z_NULL;
+ p->stream.zfree = Z_NULL;
+ p->stream.opaque = Z_NULL;
}
ZLibCodecompressor::~ZLibCodecompressor() {
}
SafeByteArray ZLibCodecompressor::process(const SafeByteArray& input) {
- SafeByteArray output;
- p->stream.avail_in = static_cast<unsigned int>(input.size());
- p->stream.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input)));
- size_t outputPosition = 0;
- do {
- output.resize(outputPosition + CHUNK_SIZE);
- p->stream.avail_out = CHUNK_SIZE;
- p->stream.next_out = reinterpret_cast<Bytef*>(vecptr(output) + outputPosition);
- int result = processZStream();
- if (result != Z_OK && result != Z_BUF_ERROR) {
- throw ZLibException(/* p->stream.msg */);
- }
- outputPosition += CHUNK_SIZE;
- }
- while (p->stream.avail_out == 0);
- if (p->stream.avail_in != 0) {
- throw ZLibException();
- }
- output.resize(outputPosition - p->stream.avail_out);
- return output;
+ SafeByteArray output;
+ p->stream.avail_in = static_cast<unsigned int>(input.size());
+ p->stream.next_in = reinterpret_cast<Bytef*>(const_cast<unsigned char*>(vecptr(input)));
+ size_t outputPosition = 0;
+ do {
+ output.resize(outputPosition + CHUNK_SIZE);
+ p->stream.avail_out = CHUNK_SIZE;
+ p->stream.next_out = reinterpret_cast<Bytef*>(vecptr(output) + outputPosition);
+ int result = processZStream();
+ if (result != Z_OK && result != Z_BUF_ERROR) {
+ throw ZLibException(/* p->stream.msg */);
+ }
+ outputPosition += CHUNK_SIZE;
+ }
+ while (p->stream.avail_out == 0);
+ if (p->stream.avail_in != 0) {
+ throw ZLibException();
+ }
+ output.resize(outputPosition - p->stream.avail_out);
+ return output;
}
}
diff --git a/Swiften/Compress/ZLibCodecompressor.h b/Swiften/Compress/ZLibCodecompressor.h
index 3907258..253c34a 100644
--- a/Swiften/Compress/ZLibCodecompressor.h
+++ b/Swiften/Compress/ZLibCodecompressor.h
@@ -10,16 +10,16 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API ZLibCodecompressor {
- public:
- ZLibCodecompressor();
- virtual ~ZLibCodecompressor();
+ class SWIFTEN_API ZLibCodecompressor {
+ public:
+ ZLibCodecompressor();
+ virtual ~ZLibCodecompressor();
- SafeByteArray process(const SafeByteArray& data);
- virtual int processZStream() = 0;
+ SafeByteArray process(const SafeByteArray& data);
+ virtual int processZStream() = 0;
- protected:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ protected:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Compress/ZLibCodecompressor_Private.h b/Swiften/Compress/ZLibCodecompressor_Private.h
index db761c3..2adc4b6 100644
--- a/Swiften/Compress/ZLibCodecompressor_Private.h
+++ b/Swiften/Compress/ZLibCodecompressor_Private.h
@@ -11,7 +11,7 @@
#include <Swiften/Compress/ZLibCodecompressor.h>
namespace Swift {
- struct ZLibCodecompressor::Private {
- z_stream stream;
- };
+ struct ZLibCodecompressor::Private {
+ z_stream stream;
+ };
}
diff --git a/Swiften/Compress/ZLibCompressor.cpp b/Swiften/Compress/ZLibCompressor.cpp
index 8887c46..a2fef15 100644
--- a/Swiften/Compress/ZLibCompressor.cpp
+++ b/Swiften/Compress/ZLibCompressor.cpp
@@ -16,17 +16,17 @@
namespace Swift {
ZLibCompressor::ZLibCompressor() {
- int result = deflateInit(&p->stream, COMPRESSION_LEVEL);
- assert(result == Z_OK);
- (void) result;
+ int result = deflateInit(&p->stream, COMPRESSION_LEVEL);
+ assert(result == Z_OK);
+ (void) result;
}
ZLibCompressor::~ZLibCompressor() {
- deflateEnd(&p->stream);
+ deflateEnd(&p->stream);
}
int ZLibCompressor::processZStream() {
- return deflate(&p->stream, Z_SYNC_FLUSH);
+ return deflate(&p->stream, Z_SYNC_FLUSH);
}
}
diff --git a/Swiften/Compress/ZLibCompressor.h b/Swiften/Compress/ZLibCompressor.h
index c92b8c0..59ebbb9 100644
--- a/Swiften/Compress/ZLibCompressor.h
+++ b/Swiften/Compress/ZLibCompressor.h
@@ -10,14 +10,14 @@
#include <Swiften/Compress/ZLibCodecompressor.h>
namespace Swift {
- class SWIFTEN_API ZLibCompressor : public ZLibCodecompressor {
- public:
- ZLibCompressor();
- virtual ~ZLibCompressor();
+ class SWIFTEN_API ZLibCompressor : public ZLibCodecompressor {
+ public:
+ ZLibCompressor();
+ virtual ~ZLibCompressor();
- virtual int processZStream();
+ virtual int processZStream();
- private:
- static const int COMPRESSION_LEVEL = 9;
- };
+ private:
+ static const int COMPRESSION_LEVEL = 9;
+ };
}
diff --git a/Swiften/Compress/ZLibDecompressor.cpp b/Swiften/Compress/ZLibDecompressor.cpp
index 3024150..adc40c5 100644
--- a/Swiften/Compress/ZLibDecompressor.cpp
+++ b/Swiften/Compress/ZLibDecompressor.cpp
@@ -16,17 +16,17 @@
namespace Swift {
ZLibDecompressor::ZLibDecompressor() {
- int result = inflateInit(&p->stream);
- assert(result == Z_OK);
- (void) result;
+ int result = inflateInit(&p->stream);
+ assert(result == Z_OK);
+ (void) result;
}
ZLibDecompressor::~ZLibDecompressor() {
- inflateEnd(&p->stream);
+ inflateEnd(&p->stream);
}
int ZLibDecompressor::processZStream() {
- return inflate(&p->stream, Z_SYNC_FLUSH);
+ return inflate(&p->stream, Z_SYNC_FLUSH);
}
}
diff --git a/Swiften/Compress/ZLibDecompressor.h b/Swiften/Compress/ZLibDecompressor.h
index b758be3..9c2dd4f 100644
--- a/Swiften/Compress/ZLibDecompressor.h
+++ b/Swiften/Compress/ZLibDecompressor.h
@@ -10,11 +10,11 @@
#include <Swiften/Compress/ZLibCodecompressor.h>
namespace Swift {
- class SWIFTEN_API ZLibDecompressor : public ZLibCodecompressor {
- public:
- ZLibDecompressor();
- virtual ~ZLibDecompressor();
+ class SWIFTEN_API ZLibDecompressor : public ZLibCodecompressor {
+ public:
+ ZLibDecompressor();
+ virtual ~ZLibDecompressor();
- virtual int processZStream();
- };
+ virtual int processZStream();
+ };
}
diff --git a/Swiften/Compress/ZLibException.h b/Swiften/Compress/ZLibException.h
index e73bcec..2201e62 100644
--- a/Swiften/Compress/ZLibException.h
+++ b/Swiften/Compress/ZLibException.h
@@ -7,8 +7,8 @@
#pragma once
namespace Swift {
- class ZLibException {
- public:
- ZLibException() {}
- };
+ class ZLibException {
+ public:
+ ZLibException() {}
+ };
}
diff --git a/Swiften/Config/swiften-config.cpp b/Swiften/Config/swiften-config.cpp
index 6016d5f..1a15702 100644
--- a/Swiften/Config/swiften-config.cpp
+++ b/Swiften/Config/swiften-config.cpp
@@ -24,103 +24,103 @@
using namespace Swift;
static void printFlags(const std::vector<std::string>& flags) {
- for (size_t i = 0; i < flags.size(); ++i) {
- if (i > 0) {
- std::cout << " ";
- }
- std::cout << flags[i];
- }
- std::cout << std::endl;
+ for (size_t i = 0; i < flags.size(); ++i) {
+ if (i > 0) {
+ std::cout << " ";
+ }
+ std::cout << flags[i];
+ }
+ std::cout << std::endl;
}
int main(int argc, char* argv[]) {
- boost::program_options::options_description desc;
- desc.add_options()
- ("help", "Show this help message")
- ("version", "Show version information")
- ("libs", "List the library flags")
- ("cflags", "List the compiler & preprocessor flags")
- ;
- boost::program_options::variables_map vm;
- try {
- boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
- boost::program_options::notify(vm);
- }
- catch (const boost::program_options::unknown_option& option) {
+ boost::program_options::options_description desc;
+ desc.add_options()
+ ("help", "Show this help message")
+ ("version", "Show version information")
+ ("libs", "List the library flags")
+ ("cflags", "List the compiler & preprocessor flags")
+ ;
+ boost::program_options::variables_map vm;
+ try {
+ boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
+ boost::program_options::notify(vm);
+ }
+ catch (const boost::program_options::unknown_option& option) {
#if BOOST_VERSION >= 104200
- std::cout << "Ignoring unknown option " << option.get_option_name() << std::endl;
+ std::cout << "Ignoring unknown option " << option.get_option_name() << std::endl;
#else
- std::cout << "Error: " << option.what() << std::endl;
+ std::cout << "Error: " << option.what() << std::endl;
#endif
- }
- catch (const boost::program_options::error& e) {
- std::cout << "Error: " << e.what() << std::endl;
- return -1;
- }
+ }
+ catch (const boost::program_options::error& e) {
+ std::cout << "Error: " << e.what() << std::endl;
+ return -1;
+ }
- if (vm.count("help") > 0) {
- std::cout << "swiften-config outputs the Swiften build options." << std::endl;
- std::cout << std::endl;
- std::cout << "Usage: swiften-config [OPTIONS]..." << std::endl;
- std::cout << std::endl;
- std::cout << desc << "\n";
- return 0;
- }
- if (vm.count("version") > 0) {
- std::cout << "swiften-config " << SWIFTEN_VERSION_STRING << std::endl;
- return 0;
- }
+ if (vm.count("help") > 0) {
+ std::cout << "swiften-config outputs the Swiften build options." << std::endl;
+ std::cout << std::endl;
+ std::cout << "Usage: swiften-config [OPTIONS]..." << std::endl;
+ std::cout << std::endl;
+ std::cout << desc << "\n";
+ return 0;
+ }
+ if (vm.count("version") > 0) {
+ std::cout << "swiften-config " << SWIFTEN_VERSION_STRING << std::endl;
+ return 0;
+ }
- // Read in all variables
- std::vector<std::string> libs;
- for (size_t i = 0; LIBFLAGS[i]; ++i) {
- libs.push_back(LIBFLAGS[i]);
- }
- std::vector<std::string> cflags;
- for (size_t i = 0; CPPFLAGS[i]; ++i) {
- cflags.push_back(CPPFLAGS[i]);
- }
+ // Read in all variables
+ std::vector<std::string> libs;
+ for (size_t i = 0; LIBFLAGS[i]; ++i) {
+ libs.push_back(LIBFLAGS[i]);
+ }
+ std::vector<std::string> cflags;
+ for (size_t i = 0; CPPFLAGS[i]; ++i) {
+ cflags.push_back(CPPFLAGS[i]);
+ }
- // Detect whether we're running in-place or not
- boost::filesystem::path executablePath = Paths::getExecutablePath();
- boost::filesystem::path topSourcePath = executablePath / ".." / "..";
- boost::filesystem::path topInstallPath = executablePath / "..";
- bool inPlace = !boost::filesystem::exists(topInstallPath / "include" / "Swiften" / "Swiften.h");
+ // Detect whether we're running in-place or not
+ boost::filesystem::path executablePath = Paths::getExecutablePath();
+ boost::filesystem::path topSourcePath = executablePath / ".." / "..";
+ boost::filesystem::path topInstallPath = executablePath / "..";
+ bool inPlace = !boost::filesystem::exists(topInstallPath / "include" / "Swiften" / "Swiften.h");
- // Replace "#" variables with the correct path
- for(size_t i = 0; i < libs.size(); ++i) {
- if (inPlace) {
- std::string lib = libs[i];
- boost::replace_all(lib, "#", pathToString(topSourcePath));
- libs[i] = lib;
- }
- else {
- std::string lib = libs[i];
- boost::replace_all(lib, "#", pathToString(topInstallPath / "lib"));
- boost::erase_all(lib, "/Swiften");
- libs[i] = lib;
- }
- }
- for(size_t i = 0; i < cflags.size(); ++i) {
- if (inPlace) {
- std::string cflag = cflags[i];
- boost::replace_all(cflag, "#", pathToString(topSourcePath));
- cflags[i] = cflag;
- }
- else {
- std::string cflag = cflags[i];
- boost::replace_all(cflag, "#", pathToString(topInstallPath / "include"));
- cflags[i] = cflag;
- }
- }
+ // Replace "#" variables with the correct path
+ for(size_t i = 0; i < libs.size(); ++i) {
+ if (inPlace) {
+ std::string lib = libs[i];
+ boost::replace_all(lib, "#", pathToString(topSourcePath));
+ libs[i] = lib;
+ }
+ else {
+ std::string lib = libs[i];
+ boost::replace_all(lib, "#", pathToString(topInstallPath / "lib"));
+ boost::erase_all(lib, "/Swiften");
+ libs[i] = lib;
+ }
+ }
+ for(size_t i = 0; i < cflags.size(); ++i) {
+ if (inPlace) {
+ std::string cflag = cflags[i];
+ boost::replace_all(cflag, "#", pathToString(topSourcePath));
+ cflags[i] = cflag;
+ }
+ else {
+ std::string cflag = cflags[i];
+ boost::replace_all(cflag, "#", pathToString(topInstallPath / "include"));
+ cflags[i] = cflag;
+ }
+ }
- // Print the requested variable
- if (vm.count("libs") > 0) {
- printFlags(libs);
- }
- if (vm.count("cflags") > 0) {
- printFlags(cflags);
- }
- return 0;
+ // Print the requested variable
+ if (vm.count("libs") > 0) {
+ printFlags(libs);
+ }
+ if (vm.count("cflags") > 0) {
+ printFlags(cflags);
+ }
+ return 0;
}
diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp
index 27bbb09..9fbdb2a 100644
--- a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp
+++ b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp
@@ -19,94 +19,94 @@
using namespace Swift;
namespace {
- class SHA1Hash : public Hash {
- public:
- SHA1Hash() : finalized(false) {
- if (!CC_SHA1_Init(&context)) {
- assert(false);
- }
- }
-
- ~SHA1Hash() {
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
- assert(!finalized);
- std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH);
- CC_SHA1_Final(vecptr(result), &context);
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- assert(!finalized);
- if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) {
- assert(false);
- }
- return *this;
- }
-
- private:
- CC_SHA1_CTX context;
- bool finalized;
- };
-
- class MD5Hash : public Hash {
- public:
- MD5Hash() : finalized(false) {
- if (!CC_MD5_Init(&context)) {
- assert(false);
- }
- }
-
- ~MD5Hash() {
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
- assert(!finalized);
- std::vector<unsigned char> result(CC_MD5_DIGEST_LENGTH);
- CC_MD5_Final(vecptr(result), &context);
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- assert(!finalized);
- if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) {
- assert(false);
- }
- return *this;
- }
-
- private:
- CC_MD5_CTX context;
- bool finalized;
- };
-
- template<typename T>
- ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) {
- std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH);
- CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result));
- return result;
- }
+ class SHA1Hash : public Hash {
+ public:
+ SHA1Hash() : finalized(false) {
+ if (!CC_SHA1_Init(&context)) {
+ assert(false);
+ }
+ }
+
+ ~SHA1Hash() {
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
+ assert(!finalized);
+ std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH);
+ CC_SHA1_Final(vecptr(result), &context);
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ assert(!finalized);
+ if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ CC_SHA1_CTX context;
+ bool finalized;
+ };
+
+ class MD5Hash : public Hash {
+ public:
+ MD5Hash() : finalized(false) {
+ if (!CC_MD5_Init(&context)) {
+ assert(false);
+ }
+ }
+
+ ~MD5Hash() {
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
+ assert(!finalized);
+ std::vector<unsigned char> result(CC_MD5_DIGEST_LENGTH);
+ CC_MD5_Final(vecptr(result), &context);
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ assert(!finalized);
+ if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ CC_MD5_CTX context;
+ bool finalized;
+ };
+
+ template<typename T>
+ ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) {
+ std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH);
+ CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result));
+ return result;
+ }
}
CommonCryptoCryptoProvider::CommonCryptoCryptoProvider() {
@@ -116,22 +116,22 @@ CommonCryptoCryptoProvider::~CommonCryptoCryptoProvider() {
}
Hash* CommonCryptoCryptoProvider::createSHA1() {
- return new SHA1Hash();
+ return new SHA1Hash();
}
Hash* CommonCryptoCryptoProvider::createMD5() {
- return new MD5Hash();
+ return new MD5Hash();
}
ByteArray CommonCryptoCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data);
+ return getHMACSHA1Internal(key, data);
}
ByteArray CommonCryptoCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data);
+ return getHMACSHA1Internal(key, data);
}
bool CommonCryptoCryptoProvider::isMD5AllowedForCrypto() const {
- return true;
+ return true;
}
diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.h b/Swiften/Crypto/CommonCryptoCryptoProvider.h
index b9e14fc..8fa7fa6 100644
--- a/Swiften/Crypto/CommonCryptoCryptoProvider.h
+++ b/Swiften/Crypto/CommonCryptoCryptoProvider.h
@@ -11,15 +11,15 @@
#include <Swiften/Crypto/CryptoProvider.h>
namespace Swift {
- class SWIFTEN_API CommonCryptoCryptoProvider : public CryptoProvider {
- public:
- CommonCryptoCryptoProvider();
- ~CommonCryptoCryptoProvider();
+ class SWIFTEN_API CommonCryptoCryptoProvider : public CryptoProvider {
+ public:
+ CommonCryptoCryptoProvider();
+ ~CommonCryptoCryptoProvider();
- virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
- virtual Hash* createMD5() SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
- };
+ virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
+ virtual Hash* createMD5() SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Crypto/CryptoProvider.h b/Swiften/Crypto/CryptoProvider.h
index 1fe2b2c..a86468c 100644
--- a/Swiften/Crypto/CryptoProvider.h
+++ b/Swiften/Crypto/CryptoProvider.h
@@ -12,25 +12,25 @@
#include <Swiften/Crypto/Hash.h>
namespace Swift {
- class Hash;
+ class Hash;
- class SWIFTEN_API CryptoProvider {
- public:
- virtual ~CryptoProvider();
+ class SWIFTEN_API CryptoProvider {
+ public:
+ virtual ~CryptoProvider();
- virtual Hash* createSHA1() = 0;
- virtual Hash* createMD5() = 0;
- virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) = 0;
- virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) = 0;
- virtual bool isMD5AllowedForCrypto() const = 0;
+ virtual Hash* createSHA1() = 0;
+ virtual Hash* createMD5() = 0;
+ virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) = 0;
+ virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) = 0;
+ virtual bool isMD5AllowedForCrypto() const = 0;
- // Convenience
- template<typename T> ByteArray getSHA1Hash(const T& data) {
- return boost::shared_ptr<Hash>(createSHA1())->update(data).getHash();
- }
+ // Convenience
+ template<typename T> ByteArray getSHA1Hash(const T& data) {
+ return boost::shared_ptr<Hash>(createSHA1())->update(data).getHash();
+ }
- template<typename T> ByteArray getMD5Hash(const T& data) {
- return boost::shared_ptr<Hash>(createMD5())->update(data).getHash();
- }
- };
+ template<typename T> ByteArray getMD5Hash(const T& data) {
+ return boost::shared_ptr<Hash>(createMD5())->update(data).getHash();
+ }
+ };
}
diff --git a/Swiften/Crypto/Hash.h b/Swiften/Crypto/Hash.h
index f3a8937..a9ed323 100644
--- a/Swiften/Crypto/Hash.h
+++ b/Swiften/Crypto/Hash.h
@@ -13,13 +13,13 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API Hash {
- public:
- virtual ~Hash();
+ class SWIFTEN_API Hash {
+ public:
+ virtual ~Hash();
- virtual Hash& update(const ByteArray& data) = 0;
- virtual Hash& update(const SafeByteArray& data) = 0;
+ virtual Hash& update(const ByteArray& data) = 0;
+ virtual Hash& update(const SafeByteArray& data) = 0;
- virtual std::vector<unsigned char> getHash() = 0;
- };
+ virtual std::vector<unsigned char> getHash() = 0;
+ };
}
diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.cpp b/Swiften/Crypto/OpenSSLCryptoProvider.cpp
index 91387d2..c785041 100644
--- a/Swiften/Crypto/OpenSSLCryptoProvider.cpp
+++ b/Swiften/Crypto/OpenSSLCryptoProvider.cpp
@@ -20,96 +20,96 @@
using namespace Swift;
namespace {
- class SHA1Hash : public Hash {
- public:
- SHA1Hash() : finalized(false) {
- if (!SHA1_Init(&context)) {
- assert(false);
- }
- }
-
- ~SHA1Hash() {
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
- assert(!finalized);
- std::vector<unsigned char> result(SHA_DIGEST_LENGTH);
- SHA1_Final(vecptr(result), &context);
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- assert(!finalized);
- if (!SHA1_Update(&context, vecptr(data), data.size())) {
- assert(false);
- }
- return *this;
- }
-
- private:
- SHA_CTX context;
- bool finalized;
- };
-
- class MD5Hash : public Hash {
- public:
- MD5Hash() : finalized(false) {
- if (!MD5_Init(&context)) {
- assert(false);
- }
- }
-
- ~MD5Hash() {
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
- assert(!finalized);
- std::vector<unsigned char> result(MD5_DIGEST_LENGTH);
- MD5_Final(vecptr(result), &context);
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- assert(!finalized);
- if (!MD5_Update(&context, vecptr(data), data.size())) {
- assert(false);
- }
- return *this;
- }
-
- private:
- MD5_CTX context;
- bool finalized;
- };
-
-
- template<typename T>
- ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) {
- unsigned int len = SHA_DIGEST_LENGTH;
- std::vector<unsigned char> result(len);
- HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len);
- return result;
- }
+ class SHA1Hash : public Hash {
+ public:
+ SHA1Hash() : finalized(false) {
+ if (!SHA1_Init(&context)) {
+ assert(false);
+ }
+ }
+
+ ~SHA1Hash() {
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
+ assert(!finalized);
+ std::vector<unsigned char> result(SHA_DIGEST_LENGTH);
+ SHA1_Final(vecptr(result), &context);
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ assert(!finalized);
+ if (!SHA1_Update(&context, vecptr(data), data.size())) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ SHA_CTX context;
+ bool finalized;
+ };
+
+ class MD5Hash : public Hash {
+ public:
+ MD5Hash() : finalized(false) {
+ if (!MD5_Init(&context)) {
+ assert(false);
+ }
+ }
+
+ ~MD5Hash() {
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE {
+ assert(!finalized);
+ std::vector<unsigned char> result(MD5_DIGEST_LENGTH);
+ MD5_Final(vecptr(result), &context);
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ assert(!finalized);
+ if (!MD5_Update(&context, vecptr(data), data.size())) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ MD5_CTX context;
+ bool finalized;
+ };
+
+
+ template<typename T>
+ ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) {
+ unsigned int len = SHA_DIGEST_LENGTH;
+ std::vector<unsigned char> result(len);
+ HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len);
+ return result;
+ }
}
OpenSSLCryptoProvider::OpenSSLCryptoProvider() {
@@ -119,22 +119,22 @@ OpenSSLCryptoProvider::~OpenSSLCryptoProvider() {
}
Hash* OpenSSLCryptoProvider::createSHA1() {
- return new SHA1Hash();
+ return new SHA1Hash();
}
Hash* OpenSSLCryptoProvider::createMD5() {
- return new MD5Hash();
+ return new MD5Hash();
}
ByteArray OpenSSLCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data);
+ return getHMACSHA1Internal(key, data);
}
ByteArray OpenSSLCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data);
+ return getHMACSHA1Internal(key, data);
}
bool OpenSSLCryptoProvider::isMD5AllowedForCrypto() const {
- return true;
+ return true;
}
diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.h b/Swiften/Crypto/OpenSSLCryptoProvider.h
index 3cc528a..6e0c01b 100644
--- a/Swiften/Crypto/OpenSSLCryptoProvider.h
+++ b/Swiften/Crypto/OpenSSLCryptoProvider.h
@@ -10,15 +10,15 @@
#include <Swiften/Crypto/CryptoProvider.h>
namespace Swift {
- class OpenSSLCryptoProvider : public CryptoProvider {
- public:
- OpenSSLCryptoProvider();
- ~OpenSSLCryptoProvider();
+ class OpenSSLCryptoProvider : public CryptoProvider {
+ public:
+ OpenSSLCryptoProvider();
+ ~OpenSSLCryptoProvider();
- virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
- virtual Hash* createMD5() SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
- };
+ virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
+ virtual Hash* createMD5() SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Crypto/PlatformCryptoProvider.cpp b/Swiften/Crypto/PlatformCryptoProvider.cpp
index 759909d..d67b284 100644
--- a/Swiften/Crypto/PlatformCryptoProvider.cpp
+++ b/Swiften/Crypto/PlatformCryptoProvider.cpp
@@ -21,12 +21,12 @@ using namespace Swift;
CryptoProvider* PlatformCryptoProvider::create() {
#if defined(SWIFTEN_PLATFORM_WIN32)
- return new WindowsCryptoProvider();
+ return new WindowsCryptoProvider();
#elif defined(HAVE_COMMONCRYPTO_CRYPTO_PROVIDER)
- return new CommonCryptoCryptoProvider();
+ return new CommonCryptoCryptoProvider();
#elif defined(HAVE_OPENSSL_CRYPTO_PROVIDER)
- return new OpenSSLCryptoProvider();
+ return new OpenSSLCryptoProvider();
#endif
- assert(false);
- return NULL;
+ assert(false);
+ return NULL;
}
diff --git a/Swiften/Crypto/PlatformCryptoProvider.h b/Swiften/Crypto/PlatformCryptoProvider.h
index 9584ab9..1133ae5 100644
--- a/Swiften/Crypto/PlatformCryptoProvider.h
+++ b/Swiften/Crypto/PlatformCryptoProvider.h
@@ -9,9 +9,9 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- namespace PlatformCryptoProvider {
- SWIFTEN_API CryptoProvider* create();
- }
+ namespace PlatformCryptoProvider {
+ SWIFTEN_API CryptoProvider* create();
+ }
}
diff --git a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
index 3e40ecf..d37e776 100644
--- a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
+++ b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
@@ -26,123 +26,123 @@ using namespace Swift;
template <typename CryptoProviderType>
class CryptoProviderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CryptoProviderTest);
+ CPPUNIT_TEST_SUITE(CryptoProviderTest);
- CPPUNIT_TEST(testGetSHA1Hash);
- CPPUNIT_TEST(testGetSHA1Hash_TwoUpdates);
- CPPUNIT_TEST(testGetSHA1Hash_NoData);
- CPPUNIT_TEST(testGetSHA1HashStatic);
- CPPUNIT_TEST(testGetSHA1HashStatic_Twice);
- CPPUNIT_TEST(testGetSHA1HashStatic_NoData);
+ CPPUNIT_TEST(testGetSHA1Hash);
+ CPPUNIT_TEST(testGetSHA1Hash_TwoUpdates);
+ CPPUNIT_TEST(testGetSHA1Hash_NoData);
+ CPPUNIT_TEST(testGetSHA1HashStatic);
+ CPPUNIT_TEST(testGetSHA1HashStatic_Twice);
+ CPPUNIT_TEST(testGetSHA1HashStatic_NoData);
- CPPUNIT_TEST(testGetMD5Hash_Empty);
- CPPUNIT_TEST(testGetMD5Hash_Alphabet);
- CPPUNIT_TEST(testMD5Incremental);
+ CPPUNIT_TEST(testGetMD5Hash_Empty);
+ CPPUNIT_TEST(testGetMD5Hash_Alphabet);
+ CPPUNIT_TEST(testMD5Incremental);
- CPPUNIT_TEST(testGetHMACSHA1);
- CPPUNIT_TEST(testGetHMACSHA1_KeyLongerThanBlockSize);
-
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST(testGetHMACSHA1);
+ CPPUNIT_TEST(testGetHMACSHA1_KeyLongerThanBlockSize);
- public:
- void setUp() {
- provider = new CryptoProviderType();
- }
+ CPPUNIT_TEST_SUITE_END();
- void tearDown() {
- delete provider;
- }
+ public:
+ void setUp() {
+ provider = new CryptoProviderType();
+ }
- ////////////////////////////////////////////////////////////
- // SHA-1
- ////////////////////////////////////////////////////////////
-
- void testGetSHA1Hash() {
- boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
- sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
+ void tearDown() {
+ delete provider;
+ }
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash());
- }
+ ////////////////////////////////////////////////////////////
+ // SHA-1
+ ////////////////////////////////////////////////////////////
- void testGetSHA1Hash_TwoUpdates() {
- boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
- sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<"));
- sha->update(createByteArray("http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
+ void testGetSHA1Hash() {
+ boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
+ sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash());
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash());
+ }
- void testGetSHA1Hash_NoData() {
- boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
- sha->update(std::vector<unsigned char>());
+ void testGetSHA1Hash_TwoUpdates() {
+ boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
+ sha->update(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<"));
+ sha->update(createByteArray("http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), sha->getHash());
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), sha->getHash());
+ }
- void testGetSHA1HashStatic() {
- ByteArray result(provider->getSHA1Hash(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result);
- }
+ void testGetSHA1Hash_NoData() {
+ boost::shared_ptr<Hash> sha = boost::shared_ptr<Hash>(provider->createSHA1());
+ sha->update(std::vector<unsigned char>());
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), sha->getHash());
+ }
- void testGetSHA1HashStatic_Twice() {
- ByteArray input(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
- provider->getSHA1Hash(input);
- ByteArray result(provider->getSHA1Hash(input));
+ void testGetSHA1HashStatic() {
+ ByteArray result(provider->getSHA1Hash(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<")));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result);
+ }
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result);
- }
- void testGetSHA1HashStatic_NoData() {
- ByteArray result(provider->getSHA1Hash(ByteArray()));
+ void testGetSHA1HashStatic_Twice() {
+ ByteArray input(createByteArray("client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<"));
+ provider->getSHA1Hash(input);
+ ByteArray result(provider->getSHA1Hash(input));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), result);
- }
-
-
- ////////////////////////////////////////////////////////////
- // MD5
- ////////////////////////////////////////////////////////////
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed"), result);
+ }
- void testGetMD5Hash_Empty() {
- ByteArray result(provider->getMD5Hash(createByteArray("")));
+ void testGetSHA1HashStatic_NoData() {
+ ByteArray result(provider->getSHA1Hash(ByteArray()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e", 16), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90\xaf\xd8\x07\x09"), result);
+ }
- void testGetMD5Hash_Alphabet() {
- ByteArray result(provider->getMD5Hash(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
- }
+ ////////////////////////////////////////////////////////////
+ // MD5
+ ////////////////////////////////////////////////////////////
- void testMD5Incremental() {
- boost::shared_ptr<Hash> testling = boost::shared_ptr<Hash>(provider->createMD5());
- testling->update(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
- testling->update(createByteArray("abcdefghijklmnopqrstuvwxyz0123456789"));
+ void testGetMD5Hash_Empty() {
+ ByteArray result(provider->getMD5Hash(createByteArray("")));
- ByteArray result = testling->getHash();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e", 16), result);
+ }
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
- }
+ void testGetMD5Hash_Alphabet() {
+ ByteArray result(provider->getMD5Hash(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
+ }
- ////////////////////////////////////////////////////////////
- // HMAC-SHA1
- ////////////////////////////////////////////////////////////
+ void testMD5Incremental() {
+ boost::shared_ptr<Hash> testling = boost::shared_ptr<Hash>(provider->createMD5());
+ testling->update(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
+ testling->update(createByteArray("abcdefghijklmnopqrstuvwxyz0123456789"));
- void testGetHMACSHA1() {
- ByteArray result(provider->getHMACSHA1(createSafeByteArray("foo"), createByteArray("foobar")));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xa4\xee\xba\x8e\x63\x3d\x77\x88\x69\xf5\x68\xd0\x5a\x1b\x3d\xc7\x2b\xfd\x4\xdd"), result);
- }
+ ByteArray result = testling->getHash();
- void testGetHMACSHA1_KeyLongerThanBlockSize() {
- ByteArray result(provider->getHMACSHA1(createSafeByteArray("---------|---------|---------|---------|---------|----------|---------|"), createByteArray("foobar")));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xd6""n""\x8f""P|1""\xd3"",""\x6"" ""\xb9\xe3""gg""\x8e\xcf"" ]+""\xa"), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
+ }
- private:
- CryptoProviderType* provider;
+
+ ////////////////////////////////////////////////////////////
+ // HMAC-SHA1
+ ////////////////////////////////////////////////////////////
+
+ void testGetHMACSHA1() {
+ ByteArray result(provider->getHMACSHA1(createSafeByteArray("foo"), createByteArray("foobar")));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xa4\xee\xba\x8e\x63\x3d\x77\x88\x69\xf5\x68\xd0\x5a\x1b\x3d\xc7\x2b\xfd\x4\xdd"), result);
+ }
+
+ void testGetHMACSHA1_KeyLongerThanBlockSize() {
+ ByteArray result(provider->getHMACSHA1(createSafeByteArray("---------|---------|---------|---------|---------|----------|---------|"), createByteArray("foobar")));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xd6""n""\x8f""P|1""\xd3"",""\x6"" ""\xb9\xe3""gg""\x8e\xcf"" ]+""\xa"), result);
+ }
+
+ private:
+ CryptoProviderType* provider;
};
#ifdef SWIFTEN_PLATFORM_WIN32
diff --git a/Swiften/Crypto/WindowsCryptoProvider.cpp b/Swiften/Crypto/WindowsCryptoProvider.cpp
index db4b2bf..e0410c6 100644
--- a/Swiften/Crypto/WindowsCryptoProvider.cpp
+++ b/Swiften/Crypto/WindowsCryptoProvider.cpp
@@ -27,196 +27,196 @@
using namespace Swift;
struct WindowsCryptoProvider::Private {
- HCRYPTPROV context;
+ HCRYPTPROV context;
};
namespace {
- class WindowsHash : public Hash {
- public:
- WindowsHash(HCRYPTPROV context, ALG_ID algorithm) : hash(NULL) {
- if (!CryptCreateHash(context, algorithm, 0, 0, &hash)) {
- assert(false);
- }
- }
-
- virtual ~WindowsHash() {
- CryptDestroyHash(hash);
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() {
- std::vector<unsigned char> result;
- DWORD hashLength = sizeof(DWORD);
- DWORD hashSize;
- CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
- result.resize(static_cast<size_t>(hashSize));
- if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
- assert(false);
- }
- result.resize(static_cast<size_t>(hashSize));
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) {
- assert(false);
- }
- return *this;
- }
-
- private:
- HCRYPTHASH hash;
- };
+ class WindowsHash : public Hash {
+ public:
+ WindowsHash(HCRYPTPROV context, ALG_ID algorithm) : hash(NULL) {
+ if (!CryptCreateHash(context, algorithm, 0, 0, &hash)) {
+ assert(false);
+ }
+ }
+
+ virtual ~WindowsHash() {
+ CryptDestroyHash(hash);
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() {
+ std::vector<unsigned char> result;
+ DWORD hashLength = sizeof(DWORD);
+ DWORD hashSize;
+ CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
+ result.resize(static_cast<size_t>(hashSize));
+ if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
+ assert(false);
+ }
+ result.resize(static_cast<size_t>(hashSize));
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ HCRYPTHASH hash;
+ };
#if 0 // NOT YET DONE
- // Haven't tested the code below properly yet, but figured out after writing
- // it that PLAINTEXTKEYBLOB doesn't work on XP or 2k, and the workaround is a
- // bit too ugly to try this now. So, using our own algorithm for now. See
- // http://support.microsoft.com/kb/228786/en-us
-
- // MSDN describes this as PLAINTEXTKEYBLOB, but this struct doesn't exist,
- // and seems to even conflict with the PLAINTEXTKEYBLOB constant. Redefining
- // here.
- struct PlainTextKeyBlob {
- BLOBHEADER hdr;
- DWORD dwKeySize;
- };
-
- class HMACHash : public Hash {
- public:
- template<typename T>
- HMACHash(HCRYPTPROV context, const T& rawKey) : hash(NULL) {
- // Import raw key
- T blobData(sizeof(PlainTextKeyBlob) + rawKey.size());
- PlainTextKeyBlob* blob = reinterpret_cast<PlainTextKeyBlob*>(vecptr(blobData));
- blob->hdr.bType = PLAINTEXTKEYBLOB;
- blob->hdr.bVersion = CUR_BLOB_VERSION;
- blob->hdr.reserved = 0;
- blob->hdr.aiKeyAlg = CALG_RC2;
- blob->dwKeySize = rawKey.size();
- std::copy(rawKey.begin(), rawKey.end(), blobData.begin() + sizeof(PlainTextKeyBlob));
- HCRYPTKEY key;
- if (!CryptImportKey(context, vecptr(blobData), blobData.size(), 0, CRYPT_IPSEC_HMAC_KEY, &key)) {
- assert(false);
- return;
- }
-
- // Create hash
- if (!CryptCreateHash(context, CALG_HMAC, key, 0, &hash)) {
- assert(false);
- return;
- }
- ZeroMemory(&info, sizeof(info));
- info.HashAlgid = CALG_SHA1;
- }
-
- ~HMACHash() {
- CryptDestroyHash(hash);
- }
-
- virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
- return updateInternal(data);
- }
-
- virtual std::vector<unsigned char> getHash() {
- std::vector<unsigned char> result;
- DWORD hashLength = sizeof(DWORD);
- DWORD hashSize;
- CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
- result.resize(static_cast<size_t>(hashSize));
- if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
- assert(false);
- }
- result.resize(static_cast<size_t>(hashSize));
- return result;
- }
-
- private:
- template<typename ContainerType>
- Hash& updateInternal(const ContainerType& data) {
- if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) {
- assert(false);
- }
- return *this;
- }
-
- private:
- HCRYPTHASH hash;
- HMAC_INFO info;
- };
+ // Haven't tested the code below properly yet, but figured out after writing
+ // it that PLAINTEXTKEYBLOB doesn't work on XP or 2k, and the workaround is a
+ // bit too ugly to try this now. So, using our own algorithm for now. See
+ // http://support.microsoft.com/kb/228786/en-us
+
+ // MSDN describes this as PLAINTEXTKEYBLOB, but this struct doesn't exist,
+ // and seems to even conflict with the PLAINTEXTKEYBLOB constant. Redefining
+ // here.
+ struct PlainTextKeyBlob {
+ BLOBHEADER hdr;
+ DWORD dwKeySize;
+ };
+
+ class HMACHash : public Hash {
+ public:
+ template<typename T>
+ HMACHash(HCRYPTPROV context, const T& rawKey) : hash(NULL) {
+ // Import raw key
+ T blobData(sizeof(PlainTextKeyBlob) + rawKey.size());
+ PlainTextKeyBlob* blob = reinterpret_cast<PlainTextKeyBlob*>(vecptr(blobData));
+ blob->hdr.bType = PLAINTEXTKEYBLOB;
+ blob->hdr.bVersion = CUR_BLOB_VERSION;
+ blob->hdr.reserved = 0;
+ blob->hdr.aiKeyAlg = CALG_RC2;
+ blob->dwKeySize = rawKey.size();
+ std::copy(rawKey.begin(), rawKey.end(), blobData.begin() + sizeof(PlainTextKeyBlob));
+ HCRYPTKEY key;
+ if (!CryptImportKey(context, vecptr(blobData), blobData.size(), 0, CRYPT_IPSEC_HMAC_KEY, &key)) {
+ assert(false);
+ return;
+ }
+
+ // Create hash
+ if (!CryptCreateHash(context, CALG_HMAC, key, 0, &hash)) {
+ assert(false);
+ return;
+ }
+ ZeroMemory(&info, sizeof(info));
+ info.HashAlgid = CALG_SHA1;
+ }
+
+ ~HMACHash() {
+ CryptDestroyHash(hash);
+ }
+
+ virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE {
+ return updateInternal(data);
+ }
+
+ virtual std::vector<unsigned char> getHash() {
+ std::vector<unsigned char> result;
+ DWORD hashLength = sizeof(DWORD);
+ DWORD hashSize;
+ CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
+ result.resize(static_cast<size_t>(hashSize));
+ if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
+ assert(false);
+ }
+ result.resize(static_cast<size_t>(hashSize));
+ return result;
+ }
+
+ private:
+ template<typename ContainerType>
+ Hash& updateInternal(const ContainerType& data) {
+ if (!CryptHashData(hash, const_cast<BYTE*>(vecptr(data)), data.size(), 0)) {
+ assert(false);
+ }
+ return *this;
+ }
+
+ private:
+ HCRYPTHASH hash;
+ HMAC_INFO info;
+ };
#endif
- // Simple implementation.
- template<typename T>
- ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data, CryptoProvider* crypto) {
- static const int BLOCK_SIZE = 64;
-
- T paddedKey;
- if (key.size() <= BLOCK_SIZE) {
- paddedKey = key;
- }
- else {
- assign(paddedKey, crypto->getSHA1Hash(key));
- }
- paddedKey.resize(BLOCK_SIZE, 0x0);
-
- // Create the first value
- T x(paddedKey);
- for (unsigned int i = 0; i < x.size(); ++i) {
- x[i] ^= 0x36;
- }
- append(x, data);
-
- // Create the second value
- T y(paddedKey);
- for (unsigned int i = 0; i < y.size(); ++i) {
- y[i] ^= 0x5c;
- }
- append(y, crypto->getSHA1Hash(x));
- return crypto->getSHA1Hash(y);
- }
+ // Simple implementation.
+ template<typename T>
+ ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data, CryptoProvider* crypto) {
+ static const int BLOCK_SIZE = 64;
+
+ T paddedKey;
+ if (key.size() <= BLOCK_SIZE) {
+ paddedKey = key;
+ }
+ else {
+ assign(paddedKey, crypto->getSHA1Hash(key));
+ }
+ paddedKey.resize(BLOCK_SIZE, 0x0);
+
+ // Create the first value
+ T x(paddedKey);
+ for (unsigned int i = 0; i < x.size(); ++i) {
+ x[i] ^= 0x36;
+ }
+ append(x, data);
+
+ // Create the second value
+ T y(paddedKey);
+ for (unsigned int i = 0; i < y.size(); ++i) {
+ y[i] ^= 0x5c;
+ }
+ append(y, crypto->getSHA1Hash(x));
+ return crypto->getSHA1Hash(y);
+ }
}
WindowsCryptoProvider::WindowsCryptoProvider() {
- p = boost::make_shared<Private>();
- if (!CryptAcquireContext(&p->context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
- assert(false);
- }
+ p = boost::make_shared<Private>();
+ if (!CryptAcquireContext(&p->context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
+ assert(false);
+ }
}
WindowsCryptoProvider::~WindowsCryptoProvider() {
- CryptReleaseContext(p->context, 0);
+ CryptReleaseContext(p->context, 0);
}
Hash* WindowsCryptoProvider::createSHA1() {
- return new WindowsHash(p->context, CALG_SHA1);
+ return new WindowsHash(p->context, CALG_SHA1);
}
Hash* WindowsCryptoProvider::createMD5() {
- return new WindowsHash(p->context, CALG_MD5);
+ return new WindowsHash(p->context, CALG_MD5);
}
bool WindowsCryptoProvider::isMD5AllowedForCrypto() const {
- return !WindowsRegistry::isFIPSEnabled();
+ return !WindowsRegistry::isFIPSEnabled();
}
ByteArray WindowsCryptoProvider::getHMACSHA1(const SafeByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data, this);
+ return getHMACSHA1Internal(key, data, this);
}
ByteArray WindowsCryptoProvider::getHMACSHA1(const ByteArray& key, const ByteArray& data) {
- return getHMACSHA1Internal(key, data, this);
+ return getHMACSHA1Internal(key, data, this);
}
diff --git a/Swiften/Crypto/WindowsCryptoProvider.h b/Swiften/Crypto/WindowsCryptoProvider.h
index b3f6f29..4c998d2 100644
--- a/Swiften/Crypto/WindowsCryptoProvider.h
+++ b/Swiften/Crypto/WindowsCryptoProvider.h
@@ -13,19 +13,19 @@
#include <Swiften/Crypto/CryptoProvider.h>
namespace Swift {
- class WindowsCryptoProvider : public CryptoProvider, public boost::noncopyable {
- public:
- WindowsCryptoProvider();
- virtual ~WindowsCryptoProvider();
+ class WindowsCryptoProvider : public CryptoProvider, public boost::noncopyable {
+ public:
+ WindowsCryptoProvider();
+ virtual ~WindowsCryptoProvider();
- virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
- virtual Hash* createMD5() SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
- virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
+ virtual Hash* createSHA1() SWIFTEN_OVERRIDE;
+ virtual Hash* createMD5() SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE;
+ virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE;
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Disco/CapsInfoGenerator.cpp b/Swiften/Disco/CapsInfoGenerator.cpp
index 1b07c43..b4637c7 100644
--- a/Swiften/Disco/CapsInfoGenerator.cpp
+++ b/Swiften/Disco/CapsInfoGenerator.cpp
@@ -15,9 +15,9 @@
#include <Swiften/StringCodecs/Base64.h>
namespace {
- bool compareFields(Swift::FormField::ref f1, Swift::FormField::ref f2) {
- return f1->getName() < f2->getName();
- }
+ bool compareFields(Swift::FormField::ref f1, Swift::FormField::ref f2) {
+ return f1->getName() < f2->getName();
+ }
}
namespace Swift {
@@ -26,39 +26,39 @@ CapsInfoGenerator::CapsInfoGenerator(const std::string& node, CryptoProvider* cr
}
CapsInfo CapsInfoGenerator::generateCapsInfo(const DiscoInfo& discoInfo) const {
- std::string serializedCaps;
+ std::string serializedCaps;
- std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities());
- std::sort(identities.begin(), identities.end());
- foreach (const DiscoInfo::Identity& identity, identities) {
- serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<";
- }
+ std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities());
+ std::sort(identities.begin(), identities.end());
+ foreach (const DiscoInfo::Identity& 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) {
- serializedCaps += feature + "<";
- }
+ std::vector<std::string> features(discoInfo.getFeatures());
+ std::sort(features.begin(), features.end());
+ foreach (const std::string& feature, features) {
+ serializedCaps += feature + "<";
+ }
- foreach(Form::ref 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) {
- 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) {
- serializedCaps += value + "<";
- }
- }
- }
+ foreach(Form::ref 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) {
+ 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) {
+ serializedCaps += value + "<";
+ }
+ }
+ }
- std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps))));
- return CapsInfo(node_, version, "sha-1");
+ std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps))));
+ return CapsInfo(node_, version, "sha-1");
}
}
diff --git a/Swiften/Disco/CapsInfoGenerator.h b/Swiften/Disco/CapsInfoGenerator.h
index b964816..ed1b1bd 100644
--- a/Swiften/Disco/CapsInfoGenerator.h
+++ b/Swiften/Disco/CapsInfoGenerator.h
@@ -12,17 +12,17 @@
#include <Swiften/Elements/CapsInfo.h>
namespace Swift {
- class DiscoInfo;
- class CryptoProvider;
+ class DiscoInfo;
+ class CryptoProvider;
- class SWIFTEN_API CapsInfoGenerator {
- public:
- CapsInfoGenerator(const std::string& node, CryptoProvider* crypto);
+ class SWIFTEN_API CapsInfoGenerator {
+ public:
+ CapsInfoGenerator(const std::string& node, CryptoProvider* crypto);
- CapsInfo generateCapsInfo(const DiscoInfo& discoInfo) const;
+ CapsInfo generateCapsInfo(const DiscoInfo& discoInfo) const;
- private:
- std::string node_;
- CryptoProvider* crypto_;
- };
+ private:
+ std::string node_;
+ CryptoProvider* crypto_;
+ };
}
diff --git a/Swiften/Disco/CapsManager.cpp b/Swiften/Disco/CapsManager.cpp
index 5616f0a..139ee6c 100644
--- a/Swiften/Disco/CapsManager.cpp
+++ b/Swiften/Disco/CapsManager.cpp
@@ -19,66 +19,66 @@
namespace Swift {
CapsManager::CapsManager(CapsStorage* capsStorage, StanzaChannel* stanzaChannel, IQRouter* iqRouter, CryptoProvider* crypto) : iqRouter(iqRouter), crypto(crypto), capsStorage(capsStorage), warnOnInvalidHash(true) {
- stanzaChannel->onPresenceReceived.connect(boost::bind(&CapsManager::handlePresenceReceived, this, _1));
- stanzaChannel->onAvailableChanged.connect(boost::bind(&CapsManager::handleStanzaChannelAvailableChanged, this, _1));
+ stanzaChannel->onPresenceReceived.connect(boost::bind(&CapsManager::handlePresenceReceived, this, _1));
+ stanzaChannel->onAvailableChanged.connect(boost::bind(&CapsManager::handleStanzaChannelAvailableChanged, this, _1));
}
void CapsManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) {
- boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>();
- if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) {
- return;
- }
- std::string hash = capsInfo->getVersion();
- if (capsStorage->getDiscoInfo(hash)) {
- return;
- }
- if (failingCaps.find(std::make_pair(presence->getFrom(), hash)) != failingCaps.end()) {
- return;
- }
- if (requestedDiscoInfos.find(hash) != requestedDiscoInfos.end()) {
- fallbacks[hash].insert(std::make_pair(presence->getFrom(), capsInfo->getNode()));
- return;
- }
- requestDiscoInfo(presence->getFrom(), capsInfo->getNode(), hash);
+ boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>();
+ if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) {
+ return;
+ }
+ std::string hash = capsInfo->getVersion();
+ if (capsStorage->getDiscoInfo(hash)) {
+ return;
+ }
+ if (failingCaps.find(std::make_pair(presence->getFrom(), hash)) != failingCaps.end()) {
+ return;
+ }
+ if (requestedDiscoInfos.find(hash) != requestedDiscoInfos.end()) {
+ fallbacks[hash].insert(std::make_pair(presence->getFrom(), capsInfo->getNode()));
+ return;
+ }
+ requestDiscoInfo(presence->getFrom(), capsInfo->getNode(), hash);
}
void CapsManager::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- failingCaps.clear();
- fallbacks.clear();
- requestedDiscoInfos.clear();
- }
+ if (available) {
+ failingCaps.clear();
+ fallbacks.clear();
+ requestedDiscoInfos.clear();
+ }
}
void CapsManager::handleDiscoInfoReceived(const JID& from, const std::string& hash, DiscoInfo::ref discoInfo, ErrorPayload::ref error) {
- requestedDiscoInfos.erase(hash);
- if (error || !discoInfo || CapsInfoGenerator("", crypto).generateCapsInfo(*discoInfo.get()).getVersion() != hash) {
- if (warnOnInvalidHash && !error && discoInfo) {
- std::cerr << "Warning: Caps from " << from.toString() << " do not verify" << std::endl;
- }
- failingCaps.insert(std::make_pair(from, hash));
- std::map<std::string, std::set< std::pair<JID, std::string> > >::iterator i = fallbacks.find(hash);
- if (i != fallbacks.end() && !i->second.empty()) {
- std::pair<JID,std::string> fallbackAndNode = *i->second.begin();
- i->second.erase(i->second.begin());
- requestDiscoInfo(fallbackAndNode.first, fallbackAndNode.second, hash);
- }
- return;
- }
- fallbacks.erase(hash);
- capsStorage->setDiscoInfo(hash, discoInfo);
- onCapsAvailable(hash);
+ requestedDiscoInfos.erase(hash);
+ if (error || !discoInfo || CapsInfoGenerator("", crypto).generateCapsInfo(*discoInfo.get()).getVersion() != hash) {
+ if (warnOnInvalidHash && !error && discoInfo) {
+ std::cerr << "Warning: Caps from " << from.toString() << " do not verify" << std::endl;
+ }
+ failingCaps.insert(std::make_pair(from, hash));
+ std::map<std::string, std::set< std::pair<JID, std::string> > >::iterator i = fallbacks.find(hash);
+ if (i != fallbacks.end() && !i->second.empty()) {
+ std::pair<JID,std::string> fallbackAndNode = *i->second.begin();
+ i->second.erase(i->second.begin());
+ requestDiscoInfo(fallbackAndNode.first, fallbackAndNode.second, hash);
+ }
+ return;
+ }
+ fallbacks.erase(hash);
+ capsStorage->setDiscoInfo(hash, discoInfo);
+ onCapsAvailable(hash);
}
void CapsManager::requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash) {
- GetDiscoInfoRequest::ref request = GetDiscoInfoRequest::create(jid, node + "#" + hash, iqRouter);
- request->onResponse.connect(boost::bind(&CapsManager::handleDiscoInfoReceived, this, jid, hash, _1, _2));
- requestedDiscoInfos.insert(hash);
- request->send();
+ GetDiscoInfoRequest::ref request = GetDiscoInfoRequest::create(jid, node + "#" + hash, iqRouter);
+ request->onResponse.connect(boost::bind(&CapsManager::handleDiscoInfoReceived, this, jid, hash, _1, _2));
+ requestedDiscoInfos.insert(hash);
+ request->send();
}
DiscoInfo::ref CapsManager::getCaps(const std::string& hash) const {
- return capsStorage->getDiscoInfo(hash);
+ return capsStorage->getDiscoInfo(hash);
}
diff --git a/Swiften/Disco/CapsManager.h b/Swiften/Disco/CapsManager.h
index 77e736d..c96db13 100644
--- a/Swiften/Disco/CapsManager.h
+++ b/Swiften/Disco/CapsManager.h
@@ -18,36 +18,36 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- class StanzaChannel;
- class IQRouter;
- class JID;
- class CapsStorage;
- class CryptoProvider;
-
- class SWIFTEN_API CapsManager : public CapsProvider, public boost::bsignals::trackable {
- public:
- CapsManager(CapsStorage*, StanzaChannel*, IQRouter*, CryptoProvider*);
-
- DiscoInfo::ref getCaps(const std::string&) const;
-
- // Mainly for testing purposes
- void setWarnOnInvalidHash(bool b) {
- warnOnInvalidHash = b;
- }
-
- private:
- void handlePresenceReceived(boost::shared_ptr<Presence>);
- void handleStanzaChannelAvailableChanged(bool);
- void handleDiscoInfoReceived(const JID&, const std::string& hash, DiscoInfo::ref, ErrorPayload::ref);
- void requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash);
-
- private:
- IQRouter* iqRouter;
- CryptoProvider* crypto;
- CapsStorage* capsStorage;
- bool warnOnInvalidHash;
- std::set<std::string> requestedDiscoInfos;
- std::set< std::pair<JID, std::string> > failingCaps;
- std::map<std::string, std::set< std::pair<JID, std::string> > > fallbacks;
- };
+ class StanzaChannel;
+ class IQRouter;
+ class JID;
+ class CapsStorage;
+ class CryptoProvider;
+
+ class SWIFTEN_API CapsManager : public CapsProvider, public boost::bsignals::trackable {
+ public:
+ CapsManager(CapsStorage*, StanzaChannel*, IQRouter*, CryptoProvider*);
+
+ DiscoInfo::ref getCaps(const std::string&) const;
+
+ // Mainly for testing purposes
+ void setWarnOnInvalidHash(bool b) {
+ warnOnInvalidHash = b;
+ }
+
+ private:
+ void handlePresenceReceived(boost::shared_ptr<Presence>);
+ void handleStanzaChannelAvailableChanged(bool);
+ void handleDiscoInfoReceived(const JID&, const std::string& hash, DiscoInfo::ref, ErrorPayload::ref);
+ void requestDiscoInfo(const JID& jid, const std::string& node, const std::string& hash);
+
+ private:
+ IQRouter* iqRouter;
+ CryptoProvider* crypto;
+ CapsStorage* capsStorage;
+ bool warnOnInvalidHash;
+ std::set<std::string> requestedDiscoInfos;
+ std::set< std::pair<JID, std::string> > failingCaps;
+ std::map<std::string, std::set< std::pair<JID, std::string> > > fallbacks;
+ };
}
diff --git a/Swiften/Disco/CapsMemoryStorage.h b/Swiften/Disco/CapsMemoryStorage.h
index e635ea1..39559ec 100644
--- a/Swiften/Disco/CapsMemoryStorage.h
+++ b/Swiften/Disco/CapsMemoryStorage.h
@@ -15,26 +15,26 @@
#include <Swiften/Disco/CapsStorage.h>
namespace Swift {
- class SWIFTEN_API CapsMemoryStorage : public CapsStorage {
- public:
- CapsMemoryStorage() {}
-
- virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const {
- CapsMap::const_iterator i = caps.find(hash);
- if (i != caps.end()) {
- return i->second;
- }
- else {
- return DiscoInfo::ref();
- }
- }
-
- virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) {
- caps[hash] = discoInfo;
- }
-
- private:
- typedef std::map<std::string, DiscoInfo::ref> CapsMap;
- CapsMap caps;
- };
+ class SWIFTEN_API CapsMemoryStorage : public CapsStorage {
+ public:
+ CapsMemoryStorage() {}
+
+ virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const {
+ CapsMap::const_iterator i = caps.find(hash);
+ if (i != caps.end()) {
+ return i->second;
+ }
+ else {
+ return DiscoInfo::ref();
+ }
+ }
+
+ virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) {
+ caps[hash] = discoInfo;
+ }
+
+ private:
+ typedef std::map<std::string, DiscoInfo::ref> CapsMap;
+ CapsMap caps;
+ };
}
diff --git a/Swiften/Disco/CapsProvider.h b/Swiften/Disco/CapsProvider.h
index 0f7e49d..9cba027 100644
--- a/Swiften/Disco/CapsProvider.h
+++ b/Swiften/Disco/CapsProvider.h
@@ -12,14 +12,14 @@
#include <Swiften/Elements/DiscoInfo.h>
namespace Swift {
-
- class SWIFTEN_API CapsProvider {
- public:
- virtual ~CapsProvider() {}
- virtual DiscoInfo::ref getCaps(const std::string&) const = 0;
+ class SWIFTEN_API CapsProvider {
+ public:
+ virtual ~CapsProvider() {}
- boost::signal<void (const std::string&)> onCapsAvailable;
- };
+ virtual DiscoInfo::ref getCaps(const std::string&) const = 0;
+
+ boost::signal<void (const std::string&)> onCapsAvailable;
+ };
}
diff --git a/Swiften/Disco/CapsStorage.h b/Swiften/Disco/CapsStorage.h
index 61c508b..5459ecf 100644
--- a/Swiften/Disco/CapsStorage.h
+++ b/Swiften/Disco/CapsStorage.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/DiscoInfo.h>
namespace Swift {
- class SWIFTEN_API CapsStorage {
- public:
- virtual ~CapsStorage();
+ class SWIFTEN_API CapsStorage {
+ public:
+ virtual ~CapsStorage();
- virtual DiscoInfo::ref getDiscoInfo(const std::string&) const = 0;
- virtual void setDiscoInfo(const std::string&, DiscoInfo::ref) = 0;
- };
+ virtual DiscoInfo::ref getDiscoInfo(const std::string&) const = 0;
+ virtual void setDiscoInfo(const std::string&, DiscoInfo::ref) = 0;
+ };
}
diff --git a/Swiften/Disco/ClientDiscoManager.cpp b/Swiften/Disco/ClientDiscoManager.cpp
index 0b6eccf..8c90d2d 100644
--- a/Swiften/Disco/ClientDiscoManager.cpp
+++ b/Swiften/Disco/ClientDiscoManager.cpp
@@ -13,31 +13,31 @@
namespace Swift {
ClientDiscoManager::ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto) : crypto(crypto) {
- discoInfoResponder = new DiscoInfoResponder(iqRouter);
- discoInfoResponder->start();
- this->presenceSender = new PayloadAddingPresenceSender(presenceSender);
+ discoInfoResponder = new DiscoInfoResponder(iqRouter);
+ discoInfoResponder->start();
+ this->presenceSender = new PayloadAddingPresenceSender(presenceSender);
}
ClientDiscoManager::~ClientDiscoManager() {
- delete presenceSender;
- discoInfoResponder->stop();
- delete discoInfoResponder;
+ delete presenceSender;
+ discoInfoResponder->stop();
+ delete discoInfoResponder;
}
void ClientDiscoManager::setCapsNode(const std::string& node) {
- capsNode = node;
+ capsNode = node;
}
void ClientDiscoManager::setDiscoInfo(const DiscoInfo& discoInfo) {
- capsInfo = CapsInfo::ref(new CapsInfo(CapsInfoGenerator(capsNode, crypto).generateCapsInfo(discoInfo)));
- discoInfoResponder->clearDiscoInfo();
- discoInfoResponder->setDiscoInfo(discoInfo);
- discoInfoResponder->setDiscoInfo(capsInfo->getNode() + "#" + capsInfo->getVersion(), discoInfo);
- presenceSender->setPayload(capsInfo);
+ capsInfo = CapsInfo::ref(new CapsInfo(CapsInfoGenerator(capsNode, crypto).generateCapsInfo(discoInfo)));
+ discoInfoResponder->clearDiscoInfo();
+ discoInfoResponder->setDiscoInfo(discoInfo);
+ discoInfoResponder->setDiscoInfo(capsInfo->getNode() + "#" + capsInfo->getVersion(), discoInfo);
+ presenceSender->setPayload(capsInfo);
}
void ClientDiscoManager::handleConnected() {
- presenceSender->reset();
+ presenceSender->reset();
}
}
diff --git a/Swiften/Disco/ClientDiscoManager.h b/Swiften/Disco/ClientDiscoManager.h
index 560c69a..fe68dd7 100644
--- a/Swiften/Disco/ClientDiscoManager.h
+++ b/Swiften/Disco/ClientDiscoManager.h
@@ -12,66 +12,66 @@
#include <Swiften/Presence/PayloadAddingPresenceSender.h>
namespace Swift {
- class IQRouter;
- class DiscoInfoResponder;
- class PayloadAddingPresenceSender;
- class PresenceSender;
- class CryptoProvider;
+ class IQRouter;
+ class DiscoInfoResponder;
+ class PayloadAddingPresenceSender;
+ class PresenceSender;
+ class CryptoProvider;
- /**
- * Class responsible for managing outgoing disco information for a client.
- *
- * The manager will respond to disco#info requests, and add entity capabilities information
- * to outgoing presence.
- *
- * To use this class, call setCapsNode() once with the caps URI of the client. After this,
- * call setDiscoInfo() with the capabilities for the client. This can be
- * called whenever the capabilities change.
- */
- class SWIFTEN_API ClientDiscoManager {
- public:
- /**
- * Constructs the manager
- *
- * \param iqRouter the router on which requests will be answered
- * \param presenceSender the presence sender to which all outgoing presence
- * (with caps information) will be sent.
- */
- ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto);
- ~ClientDiscoManager();
+ /**
+ * Class responsible for managing outgoing disco information for a client.
+ *
+ * The manager will respond to disco#info requests, and add entity capabilities information
+ * to outgoing presence.
+ *
+ * To use this class, call setCapsNode() once with the caps URI of the client. After this,
+ * call setDiscoInfo() with the capabilities for the client. This can be
+ * called whenever the capabilities change.
+ */
+ class SWIFTEN_API ClientDiscoManager {
+ public:
+ /**
+ * Constructs the manager
+ *
+ * \param iqRouter the router on which requests will be answered
+ * \param presenceSender the presence sender to which all outgoing presence
+ * (with caps information) will be sent.
+ */
+ ClientDiscoManager(IQRouter* iqRouter, PresenceSender* presenceSender, CryptoProvider* crypto);
+ ~ClientDiscoManager();
- /**
- * Needs to be called before calling setDiscoInfo().
- */
- void setCapsNode(const std::string& node);
+ /**
+ * Needs to be called before calling setDiscoInfo().
+ */
+ void setCapsNode(const std::string& node);
- /**
- * Sets the capabilities of the client.
- */
- void setDiscoInfo(const DiscoInfo& info);
+ /**
+ * Sets the capabilities of the client.
+ */
+ void setDiscoInfo(const DiscoInfo& info);
- /**
- * Returns the presence sender through which all outgoing presence
- * should be sent.
- * The manager will add the necessary caps information, and forward it to
- * the presence sender passed at construction time.
- */
- PresenceSender* getPresenceSender() const {
- return presenceSender;
- }
+ /**
+ * Returns the presence sender through which all outgoing presence
+ * should be sent.
+ * The manager will add the necessary caps information, and forward it to
+ * the presence sender passed at construction time.
+ */
+ PresenceSender* getPresenceSender() const {
+ return presenceSender;
+ }
- /**
- * Called when the client is connected.
- * This resets the presence sender, such that it assumes initial presence
- * hasn't been sent yet.
- */
- void handleConnected();
+ /**
+ * Called when the client is connected.
+ * This resets the presence sender, such that it assumes initial presence
+ * hasn't been sent yet.
+ */
+ void handleConnected();
- private:
- PayloadAddingPresenceSender* presenceSender;
- CryptoProvider* crypto;
- DiscoInfoResponder* discoInfoResponder;
- std::string capsNode;
- CapsInfo::ref capsInfo;
- };
+ private:
+ PayloadAddingPresenceSender* presenceSender;
+ CryptoProvider* crypto;
+ DiscoInfoResponder* discoInfoResponder;
+ std::string capsNode;
+ CapsInfo::ref capsInfo;
+ };
}
diff --git a/Swiften/Disco/DiscoInfoResponder.cpp b/Swiften/Disco/DiscoInfoResponder.cpp
index bb3937a..cf18f43 100644
--- a/Swiften/Disco/DiscoInfoResponder.cpp
+++ b/Swiften/Disco/DiscoInfoResponder.cpp
@@ -17,34 +17,34 @@ DiscoInfoResponder::DiscoInfoResponder(IQRouter* router) : GetResponder<DiscoInf
}
void DiscoInfoResponder::clearDiscoInfo() {
- info_ = DiscoInfo();
- nodeInfo_.clear();
+ info_ = DiscoInfo();
+ nodeInfo_.clear();
}
void DiscoInfoResponder::setDiscoInfo(const DiscoInfo& info) {
- info_ = info;
+ info_ = info;
}
void DiscoInfoResponder::setDiscoInfo(const std::string& node, const DiscoInfo& info) {
- DiscoInfo newInfo(info);
- newInfo.setNode(node);
- nodeInfo_[node] = newInfo;
+ DiscoInfo newInfo(info);
+ newInfo.setNode(node);
+ nodeInfo_[node] = newInfo;
}
bool DiscoInfoResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<DiscoInfo> info) {
- if (info->getNode().empty()) {
- sendResponse(from, id, boost::make_shared<DiscoInfo>(info_));
- }
- else {
- std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode());
- if (i != nodeInfo_.end()) {
- sendResponse(from, id, boost::make_shared<DiscoInfo>((*i).second));
- }
- else {
- sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
- }
- }
- return true;
+ if (info->getNode().empty()) {
+ sendResponse(from, id, boost::make_shared<DiscoInfo>(info_));
+ }
+ else {
+ std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode());
+ if (i != nodeInfo_.end()) {
+ sendResponse(from, id, boost::make_shared<DiscoInfo>((*i).second));
+ }
+ else {
+ sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
+ }
+ }
+ return true;
}
}
diff --git a/Swiften/Disco/DiscoInfoResponder.h b/Swiften/Disco/DiscoInfoResponder.h
index 92d337b..0781173 100644
--- a/Swiften/Disco/DiscoInfoResponder.h
+++ b/Swiften/Disco/DiscoInfoResponder.h
@@ -13,21 +13,21 @@
#include <Swiften/Queries/GetResponder.h>
namespace Swift {
- class IQRouter;
+ class IQRouter;
- class SWIFTEN_API DiscoInfoResponder : public GetResponder<DiscoInfo> {
- public:
- DiscoInfoResponder(IQRouter* router);
+ class SWIFTEN_API DiscoInfoResponder : public GetResponder<DiscoInfo> {
+ public:
+ DiscoInfoResponder(IQRouter* router);
- void clearDiscoInfo();
- void setDiscoInfo(const DiscoInfo& info);
- void setDiscoInfo(const std::string& node, const DiscoInfo& info);
+ void clearDiscoInfo();
+ void setDiscoInfo(const DiscoInfo& info);
+ void setDiscoInfo(const std::string& node, const DiscoInfo& info);
- private:
- virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload);
+ private:
+ virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload);
- private:
- DiscoInfo info_;
- std::map<std::string, DiscoInfo> nodeInfo_;
- };
+ private:
+ DiscoInfo info_;
+ std::map<std::string, DiscoInfo> nodeInfo_;
+ };
}
diff --git a/Swiften/Disco/DiscoServiceWalker.cpp b/Swiften/Disco/DiscoServiceWalker.cpp
index 5803602..19170ce 100644
--- a/Swiften/Disco/DiscoServiceWalker.cpp
+++ b/Swiften/Disco/DiscoServiceWalker.cpp
@@ -18,118 +18,118 @@ DiscoServiceWalker::DiscoServiceWalker(const JID& service, IQRouter* iqRouter, s
}
void DiscoServiceWalker::beginWalk() {
- SWIFT_LOG(debug) << "Starting walk to " << service_ << std::endl;
- assert(!active_);
- assert(servicesBeingSearched_.empty());
- active_ = true;
- walkNode(service_);
+ 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_) {
- request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
- }
- foreach (GetDiscoItemsRequest::ref request, pendingDiscoItemsRequests_) {
- request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
- }
- active_ = false;
- onWalkAborted();
- }
+ if (active_) {
+ SWIFT_LOG(debug) << "Ending walk to " << service_ << std::endl;
+ foreach (GetDiscoInfoRequest::ref request, pendingDiscoInfoRequests_) {
+ request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
+ }
+ foreach (GetDiscoItemsRequest::ref 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();
+ 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(boost::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()) {
- 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());
- }
+ /* 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()) {
+ 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(boost::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()) {
- 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());
+ /* 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()) {
+ 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);
+ 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();
- }
+ 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/Disco/DiscoServiceWalker.h b/Swiften/Disco/DiscoServiceWalker.h
index 17376b7..bd8102b 100644
--- a/Swiften/Disco/DiscoServiceWalker.h
+++ b/Swiften/Disco/DiscoServiceWalker.h
@@ -22,55 +22,55 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class IQRouter;
- /**
- * Recursively walk service discovery trees to find all services offered.
- * This stops on any disco item that's not reporting itself as a server.
- */
- class SWIFTEN_API DiscoServiceWalker {
- public:
- DiscoServiceWalker(const JID& service, IQRouter* iqRouter, size_t maxSteps = 200);
+ class IQRouter;
+ /**
+ * Recursively walk service discovery trees to find all services offered.
+ * This stops on any disco item that's not reporting itself as a server.
+ */
+ class SWIFTEN_API DiscoServiceWalker {
+ public:
+ DiscoServiceWalker(const JID& service, IQRouter* iqRouter, size_t maxSteps = 200);
- /**
- * Start the walk.
- *
- * Call this exactly once.
- */
- void beginWalk();
+ /**
+ * Start the walk.
+ *
+ * Call this exactly once.
+ */
+ void beginWalk();
- /**
- * End the walk.
- */
- void endWalk();
+ /**
+ * End the walk.
+ */
+ void endWalk();
- bool isActive() const {
- return active_;
- }
+ bool isActive() const {
+ return active_;
+ }
- /** Emitted for each service found. */
- boost::signal<void(const JID&, boost::shared_ptr<DiscoInfo>)> onServiceFound;
+ /** Emitted for each service found. */
+ boost::signal<void(const JID&, boost::shared_ptr<DiscoInfo>)> onServiceFound;
- /** Emitted when walking is aborted. */
- boost::signal<void()> onWalkAborted;
+ /** Emitted when walking is aborted. */
+ boost::signal<void()> onWalkAborted;
- /** Emitted when walking is complete.*/
- boost::signal<void()> onWalkComplete;
+ /** Emitted when walking is complete.*/
+ boost::signal<void()> onWalkComplete;
- private:
- void walkNode(const JID& jid);
- void markNodeCompleted(const JID& jid);
- void handleDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request);
- void handleDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request);
- void handleDiscoError(const JID& jid, ErrorPayload::ref error);
+ private:
+ void walkNode(const JID& jid);
+ void markNodeCompleted(const JID& jid);
+ void handleDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request);
+ void handleDiscoItemsResponse(boost::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request);
+ void handleDiscoError(const JID& jid, ErrorPayload::ref error);
- private:
- JID service_;
- IQRouter* iqRouter_;
- size_t maxSteps_;
- bool active_;
- std::set<JID> servicesBeingSearched_;
- std::set<JID> searchedServices_;
- std::set<GetDiscoInfoRequest::ref> pendingDiscoInfoRequests_;
- std::set<GetDiscoItemsRequest::ref> pendingDiscoItemsRequests_;
- };
+ private:
+ JID service_;
+ IQRouter* iqRouter_;
+ size_t maxSteps_;
+ bool active_;
+ std::set<JID> servicesBeingSearched_;
+ std::set<JID> searchedServices_;
+ std::set<GetDiscoInfoRequest::ref> pendingDiscoInfoRequests_;
+ std::set<GetDiscoItemsRequest::ref> pendingDiscoItemsRequests_;
+ };
}
diff --git a/Swiften/Disco/DummyEntityCapsProvider.cpp b/Swiften/Disco/DummyEntityCapsProvider.cpp
index 65baf7a..6e9d898 100644
--- a/Swiften/Disco/DummyEntityCapsProvider.cpp
+++ b/Swiften/Disco/DummyEntityCapsProvider.cpp
@@ -11,11 +11,11 @@
namespace Swift {
DiscoInfo::ref DummyEntityCapsProvider::getCaps(const JID& jid) const {
- std::map<JID, DiscoInfo::ref>::const_iterator i = caps.find(jid);
- if (i != caps.end()) {
- return i->second;
- }
- return DiscoInfo::ref();
+ std::map<JID, DiscoInfo::ref>::const_iterator i = caps.find(jid);
+ if (i != caps.end()) {
+ return i->second;
+ }
+ return DiscoInfo::ref();
}
}
diff --git a/Swiften/Disco/DummyEntityCapsProvider.h b/Swiften/Disco/DummyEntityCapsProvider.h
index d6b2c82..5171c91 100644
--- a/Swiften/Disco/DummyEntityCapsProvider.h
+++ b/Swiften/Disco/DummyEntityCapsProvider.h
@@ -12,13 +12,13 @@
#include <Swiften/Disco/EntityCapsProvider.h>
namespace Swift {
- class SWIFTEN_API DummyEntityCapsProvider : public EntityCapsProvider {
- public:
- DummyEntityCapsProvider() {
- }
+ class SWIFTEN_API DummyEntityCapsProvider : public EntityCapsProvider {
+ public:
+ DummyEntityCapsProvider() {
+ }
- DiscoInfo::ref getCaps(const JID& jid) const;
+ DiscoInfo::ref getCaps(const JID& jid) const;
- std::map<JID, DiscoInfo::ref> caps;
- };
+ std::map<JID, DiscoInfo::ref> caps;
+ };
}
diff --git a/Swiften/Disco/EntityCapsManager.cpp b/Swiften/Disco/EntityCapsManager.cpp
index a79033d..d30af54 100644
--- a/Swiften/Disco/EntityCapsManager.cpp
+++ b/Swiften/Disco/EntityCapsManager.cpp
@@ -14,66 +14,66 @@
namespace Swift {
EntityCapsManager::EntityCapsManager(CapsProvider* capsProvider, StanzaChannel* stanzaChannel) : capsProvider(capsProvider) {
- stanzaChannel->onPresenceReceived.connect(boost::bind(&EntityCapsManager::handlePresenceReceived, this, _1));
- stanzaChannel->onAvailableChanged.connect(boost::bind(&EntityCapsManager::handleStanzaChannelAvailableChanged, this, _1));
- capsProvider->onCapsAvailable.connect(boost::bind(&EntityCapsManager::handleCapsAvailable, this, _1));
+ stanzaChannel->onPresenceReceived.connect(boost::bind(&EntityCapsManager::handlePresenceReceived, this, _1));
+ stanzaChannel->onAvailableChanged.connect(boost::bind(&EntityCapsManager::handleStanzaChannelAvailableChanged, this, _1));
+ capsProvider->onCapsAvailable.connect(boost::bind(&EntityCapsManager::handleCapsAvailable, this, _1));
}
void EntityCapsManager::handlePresenceReceived(boost::shared_ptr<Presence> presence) {
- JID from = presence->getFrom();
- if (presence->isAvailable()) {
- boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>();
- if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) {
- return;
- }
- std::string hash = capsInfo->getVersion();
- std::map<JID, std::string>::iterator i = caps.find(from);
- if (i == caps.end() || i->second != hash) {
- caps.insert(std::make_pair(from, hash));
- DiscoInfo::ref disco = capsProvider->getCaps(hash);
- if (disco) {
- onCapsChanged(from);
- }
- else if (i != caps.end()) {
- caps.erase(i);
- onCapsChanged(from);
- }
- }
- }
- else {
- std::map<JID, std::string>::iterator i = caps.find(from);
- if (i != caps.end()) {
- caps.erase(i);
- onCapsChanged(from);
- }
- }
+ JID from = presence->getFrom();
+ if (presence->isAvailable()) {
+ boost::shared_ptr<CapsInfo> capsInfo = presence->getPayload<CapsInfo>();
+ if (!capsInfo || capsInfo->getHash() != "sha-1" || presence->getPayload<ErrorPayload>()) {
+ return;
+ }
+ std::string hash = capsInfo->getVersion();
+ std::map<JID, std::string>::iterator i = caps.find(from);
+ if (i == caps.end() || i->second != hash) {
+ caps.insert(std::make_pair(from, hash));
+ DiscoInfo::ref disco = capsProvider->getCaps(hash);
+ if (disco) {
+ onCapsChanged(from);
+ }
+ else if (i != caps.end()) {
+ caps.erase(i);
+ onCapsChanged(from);
+ }
+ }
+ }
+ else {
+ std::map<JID, std::string>::iterator i = caps.find(from);
+ if (i != caps.end()) {
+ caps.erase(i);
+ onCapsChanged(from);
+ }
+ }
}
void EntityCapsManager::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- std::map<JID, std::string> capsCopy;
- capsCopy.swap(caps);
- for (std::map<JID,std::string>::const_iterator i = capsCopy.begin(); i != capsCopy.end(); ++i) {
- onCapsChanged(i->first);
- }
- }
+ if (available) {
+ std::map<JID, std::string> capsCopy;
+ capsCopy.swap(caps);
+ for (std::map<JID,std::string>::const_iterator i = capsCopy.begin(); i != capsCopy.end(); ++i) {
+ onCapsChanged(i->first);
+ }
+ }
}
void EntityCapsManager::handleCapsAvailable(const std::string& hash) {
- // TODO: Use Boost.Bimap ?
- for (std::map<JID,std::string>::const_iterator i = caps.begin(); i != caps.end(); ++i) {
- if (i->second == hash) {
- onCapsChanged(i->first);
- }
- }
+ // TODO: Use Boost.Bimap ?
+ for (std::map<JID,std::string>::const_iterator i = caps.begin(); i != caps.end(); ++i) {
+ if (i->second == hash) {
+ onCapsChanged(i->first);
+ }
+ }
}
DiscoInfo::ref EntityCapsManager::getCaps(const JID& jid) const {
- std::map<JID, std::string>::const_iterator i = caps.find(jid);
- if (i != caps.end()) {
- return capsProvider->getCaps(i->second);
- }
- return DiscoInfo::ref();
+ std::map<JID, std::string>::const_iterator i = caps.find(jid);
+ if (i != caps.end()) {
+ return capsProvider->getCaps(i->second);
+ }
+ return DiscoInfo::ref();
}
}
diff --git a/Swiften/Disco/EntityCapsManager.h b/Swiften/Disco/EntityCapsManager.h
index 62c0002..2a5d2d7 100644
--- a/Swiften/Disco/EntityCapsManager.h
+++ b/Swiften/Disco/EntityCapsManager.h
@@ -16,31 +16,31 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- class StanzaChannel;
- class CapsProvider;
-
- /**
- * This class is responsible for gathering and providing
- * information about capabilities of entities on the network.
- * This information is provided in the form of service discovery
- * information.
- */
- class SWIFTEN_API EntityCapsManager : public EntityCapsProvider, public boost::bsignals::trackable {
- public:
- EntityCapsManager(CapsProvider*, StanzaChannel*);
-
- /**
- * Returns the service discovery information of the given JID.
- */
- DiscoInfo::ref getCaps(const JID&) const;
-
- private:
- void handlePresenceReceived(boost::shared_ptr<Presence>);
- void handleStanzaChannelAvailableChanged(bool);
- void handleCapsAvailable(const std::string&);
-
- private:
- CapsProvider* capsProvider;
- std::map<JID, std::string> caps;
- };
+ class StanzaChannel;
+ class CapsProvider;
+
+ /**
+ * This class is responsible for gathering and providing
+ * information about capabilities of entities on the network.
+ * This information is provided in the form of service discovery
+ * information.
+ */
+ class SWIFTEN_API EntityCapsManager : public EntityCapsProvider, public boost::bsignals::trackable {
+ public:
+ EntityCapsManager(CapsProvider*, StanzaChannel*);
+
+ /**
+ * Returns the service discovery information of the given JID.
+ */
+ DiscoInfo::ref getCaps(const JID&) const;
+
+ private:
+ void handlePresenceReceived(boost::shared_ptr<Presence>);
+ void handleStanzaChannelAvailableChanged(bool);
+ void handleCapsAvailable(const std::string&);
+
+ private:
+ CapsProvider* capsProvider;
+ std::map<JID, std::string> caps;
+ };
}
diff --git a/Swiften/Disco/EntityCapsProvider.h b/Swiften/Disco/EntityCapsProvider.h
index abc5758..34984ca 100644
--- a/Swiften/Disco/EntityCapsProvider.h
+++ b/Swiften/Disco/EntityCapsProvider.h
@@ -12,23 +12,23 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- /**
- * This class provides information about capabilities of entities on the network.
- * This information is provided in the form of service discovery
- * information.
- */
- class SWIFTEN_API EntityCapsProvider {
- public:
- virtual ~EntityCapsProvider();
+ /**
+ * This class provides information about capabilities of entities on the network.
+ * This information is provided in the form of service discovery
+ * information.
+ */
+ class SWIFTEN_API EntityCapsProvider {
+ public:
+ virtual ~EntityCapsProvider();
- /**
- * Returns the service discovery information of the given JID.
- */
- virtual DiscoInfo::ref getCaps(const JID&) const = 0;
+ /**
+ * Returns the service discovery information of the given JID.
+ */
+ virtual DiscoInfo::ref getCaps(const JID&) const = 0;
- /**
- * Emitted when the capabilities of a JID changes.
- */
- boost::signal<void (const JID&)> onCapsChanged;
- };
+ /**
+ * Emitted when the capabilities of a JID changes.
+ */
+ boost::signal<void (const JID&)> onCapsChanged;
+ };
}
diff --git a/Swiften/Disco/FeatureOracle.cpp b/Swiften/Disco/FeatureOracle.cpp
index 4e61aa9..1267cb0 100644
--- a/Swiften/Disco/FeatureOracle.cpp
+++ b/Swiften/Disco/FeatureOracle.cpp
@@ -24,74 +24,74 @@ FeatureOracle::FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* p
}
Tristate FeatureOracle::isFileTransferSupported(const JID& jid) {
- DiscoInfo::ref discoInfo = getDiscoResultForJID(jid);
- if (discoInfo) {
- return FileTransferManager::isSupportedBy(discoInfo) ? Yes : No;
- }
- else {
- return Maybe;
- }
+ DiscoInfo::ref discoInfo = getDiscoResultForJID(jid);
+ if (discoInfo) {
+ return FileTransferManager::isSupportedBy(discoInfo) ? Yes : No;
+ }
+ else {
+ return Maybe;
+ }
}
Tristate FeatureOracle::isMessageReceiptsSupported(const JID& jid) {
- return isFeatureSupported(jid, DiscoInfo::MessageDeliveryReceiptsFeature);
+ return isFeatureSupported(jid, DiscoInfo::MessageDeliveryReceiptsFeature);
}
Tristate FeatureOracle::isMessageCorrectionSupported(const JID& jid) {
- return isFeatureSupported(jid, DiscoInfo::MessageCorrectionFeature);
+ return isFeatureSupported(jid, DiscoInfo::MessageCorrectionFeature);
}
DiscoInfo::ref FeatureOracle::getDiscoResultForJID(const JID& jid) {
- DiscoInfo::ref discoInfo;
- if (jid.isBare()) {
- // Calculate the common subset of disco features of all available results and return that.
- std::vector<Presence::ref> availablePresences = presenceOracle_->getAllPresence(jid);
-
- bool commonFeaturesInitialized = false;
- std::vector<std::string> commonFeatures;
- foreach(Presence::ref presence, availablePresences) {
- DiscoInfo::ref presenceDiscoInfo = capsProvider_->getCaps(presence->getFrom());
- if (presenceDiscoInfo) {
- std::vector<std::string> features = presenceDiscoInfo->getFeatures();
- if (!commonFeaturesInitialized) {
- commonFeatures = features;
- commonFeaturesInitialized = true;
- }
- else {
- std::vector<std::string> featuresToRemove;
- foreach(const std::string& feature, commonFeatures) {
- if (std::find(features.begin(), features.end(), feature) == features.end()) {
- featuresToRemove.push_back(feature);
- }
- }
- foreach(const std::string& featureToRemove, featuresToRemove) {
- commonFeatures.erase(std::remove(commonFeatures.begin(), commonFeatures.end(), featureToRemove), commonFeatures.end());
- }
- }
- }
- }
- discoInfo = boost::make_shared<DiscoInfo>();
-
- foreach(const std::string& commonFeature, commonFeatures) {
- discoInfo->addFeature(commonFeature);
- }
- }
- else {
- // Return the disco result of the full JID.
- discoInfo = capsProvider_->getCaps(jid);
- }
-
- return discoInfo;
+ DiscoInfo::ref discoInfo;
+ if (jid.isBare()) {
+ // Calculate the common subset of disco features of all available results and return that.
+ std::vector<Presence::ref> availablePresences = presenceOracle_->getAllPresence(jid);
+
+ bool commonFeaturesInitialized = false;
+ std::vector<std::string> commonFeatures;
+ foreach(Presence::ref presence, availablePresences) {
+ DiscoInfo::ref presenceDiscoInfo = capsProvider_->getCaps(presence->getFrom());
+ if (presenceDiscoInfo) {
+ std::vector<std::string> features = presenceDiscoInfo->getFeatures();
+ if (!commonFeaturesInitialized) {
+ commonFeatures = features;
+ commonFeaturesInitialized = true;
+ }
+ else {
+ std::vector<std::string> featuresToRemove;
+ foreach(const std::string& feature, commonFeatures) {
+ if (std::find(features.begin(), features.end(), feature) == features.end()) {
+ featuresToRemove.push_back(feature);
+ }
+ }
+ foreach(const std::string& featureToRemove, featuresToRemove) {
+ commonFeatures.erase(std::remove(commonFeatures.begin(), commonFeatures.end(), featureToRemove), commonFeatures.end());
+ }
+ }
+ }
+ }
+ discoInfo = boost::make_shared<DiscoInfo>();
+
+ foreach(const std::string& commonFeature, commonFeatures) {
+ discoInfo->addFeature(commonFeature);
+ }
+ }
+ else {
+ // Return the disco result of the full JID.
+ discoInfo = capsProvider_->getCaps(jid);
+ }
+
+ return discoInfo;
}
Tristate FeatureOracle::isFeatureSupported(const JID& jid, const std::string& feature) {
- DiscoInfo::ref discoInfo = getDiscoResultForJID(jid);
- if (discoInfo) {
- return discoInfo->hasFeature(feature) ? Yes : No;
- }
- else {
- return Maybe;
- }
+ DiscoInfo::ref discoInfo = getDiscoResultForJID(jid);
+ if (discoInfo) {
+ return discoInfo->hasFeature(feature) ? Yes : No;
+ }
+ else {
+ return Maybe;
+ }
}
}
diff --git a/Swiften/Disco/FeatureOracle.h b/Swiften/Disco/FeatureOracle.h
index d579e5a..d434e86 100644
--- a/Swiften/Disco/FeatureOracle.h
+++ b/Swiften/Disco/FeatureOracle.h
@@ -20,27 +20,27 @@ class PresenceOracle;
* @brief The FeatureOracle class enables direct feature support lookup for client features supported by Swiften.
*/
class SWIFTEN_API FeatureOracle {
- public:
- FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* presenceOracle);
-
- public:
- Tristate isFileTransferSupported(const JID& jid);
- Tristate isMessageReceiptsSupported(const JID& jid);
- Tristate isMessageCorrectionSupported(const JID& jid);
-
- private:
- /**
- * @brief getDiscoResultForJID returns a shared reference to a DiscoInfo representing features supported by the jid.
- * @param jid The JID to return the DiscoInfo::ref for.
- * @return DiscoResult::ref
- */
- DiscoInfo::ref getDiscoResultForJID(const JID& jid);
-
- Tristate isFeatureSupported(const JID& jid, const std::string& feature);
-
- private:
- EntityCapsProvider* capsProvider_;
- PresenceOracle* presenceOracle_;
+ public:
+ FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* presenceOracle);
+
+ public:
+ Tristate isFileTransferSupported(const JID& jid);
+ Tristate isMessageReceiptsSupported(const JID& jid);
+ Tristate isMessageCorrectionSupported(const JID& jid);
+
+ private:
+ /**
+ * @brief getDiscoResultForJID returns a shared reference to a DiscoInfo representing features supported by the jid.
+ * @param jid The JID to return the DiscoInfo::ref for.
+ * @return DiscoResult::ref
+ */
+ DiscoInfo::ref getDiscoResultForJID(const JID& jid);
+
+ Tristate isFeatureSupported(const JID& jid, const std::string& feature);
+
+ private:
+ EntityCapsProvider* capsProvider_;
+ PresenceOracle* presenceOracle_;
};
}
diff --git a/Swiften/Disco/GetDiscoInfoRequest.h b/Swiften/Disco/GetDiscoInfoRequest.h
index 81b212c..ccbd3e2 100644
--- a/Swiften/Disco/GetDiscoInfoRequest.h
+++ b/Swiften/Disco/GetDiscoInfoRequest.h
@@ -13,26 +13,26 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetDiscoInfoRequest : public GenericRequest<DiscoInfo> {
- public:
- typedef boost::shared_ptr<GetDiscoInfoRequest> ref;
-
- static ref create(const JID& jid, IQRouter* router) {
- return ref(new GetDiscoInfoRequest(jid, router));
- }
-
- static ref create(const JID& jid, const std::string& node, IQRouter* router) {
- return ref(new GetDiscoInfoRequest(jid, node, router));
- }
-
- private:
- GetDiscoInfoRequest(const JID& jid, IQRouter* router) :
- GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
- }
-
- GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) :
- GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
- getPayloadGeneric()->setNode(node);
- }
- };
+ class SWIFTEN_API GetDiscoInfoRequest : public GenericRequest<DiscoInfo> {
+ public:
+ typedef boost::shared_ptr<GetDiscoInfoRequest> ref;
+
+ static ref create(const JID& jid, IQRouter* router) {
+ return ref(new GetDiscoInfoRequest(jid, router));
+ }
+
+ static ref create(const JID& jid, const std::string& node, IQRouter* router) {
+ return ref(new GetDiscoInfoRequest(jid, node, router));
+ }
+
+ private:
+ GetDiscoInfoRequest(const JID& jid, IQRouter* router) :
+ GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
+ }
+
+ GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) :
+ GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
+ getPayloadGeneric()->setNode(node);
+ }
+ };
}
diff --git a/Swiften/Disco/GetDiscoItemsRequest.h b/Swiften/Disco/GetDiscoItemsRequest.h
index 0a96f96..7f1adc6 100644
--- a/Swiften/Disco/GetDiscoItemsRequest.h
+++ b/Swiften/Disco/GetDiscoItemsRequest.h
@@ -13,26 +13,26 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetDiscoItemsRequest : public GenericRequest<DiscoItems> {
- public:
- typedef boost::shared_ptr<GetDiscoItemsRequest> ref;
-
- static ref create(const JID& jid, IQRouter* router) {
- return ref(new GetDiscoItemsRequest(jid, router));
- }
-
- static ref create(const JID& jid, const std::string& node, IQRouter* router) {
- return ref(new GetDiscoItemsRequest(jid, node, router));
- }
-
- private:
- GetDiscoItemsRequest(const JID& jid, IQRouter* router) :
- GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
- }
-
- GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) :
- GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
- getPayloadGeneric()->setNode(node);
- }
- };
+ class SWIFTEN_API GetDiscoItemsRequest : public GenericRequest<DiscoItems> {
+ public:
+ typedef boost::shared_ptr<GetDiscoItemsRequest> ref;
+
+ static ref create(const JID& jid, IQRouter* router) {
+ return ref(new GetDiscoItemsRequest(jid, router));
+ }
+
+ static ref create(const JID& jid, const std::string& node, IQRouter* router) {
+ return ref(new GetDiscoItemsRequest(jid, node, router));
+ }
+
+ private:
+ GetDiscoItemsRequest(const JID& jid, IQRouter* router) :
+ GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
+ }
+
+ GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) :
+ GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
+ getPayloadGeneric()->setNode(node);
+ }
+ };
}
diff --git a/Swiften/Disco/JIDDiscoInfoResponder.cpp b/Swiften/Disco/JIDDiscoInfoResponder.cpp
index 8803b6b..7bec992 100644
--- a/Swiften/Disco/JIDDiscoInfoResponder.cpp
+++ b/Swiften/Disco/JIDDiscoInfoResponder.cpp
@@ -17,41 +17,41 @@ JIDDiscoInfoResponder::JIDDiscoInfoResponder(IQRouter* router) : GetResponder<Di
}
void JIDDiscoInfoResponder::clearDiscoInfo(const JID& jid) {
- info.erase(jid);
+ info.erase(jid);
}
void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const DiscoInfo& discoInfo) {
- JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
- i->second.discoInfo = discoInfo;
+ JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
+ i->second.discoInfo = discoInfo;
}
void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& discoInfo) {
- JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
- DiscoInfo newInfo(discoInfo);
- newInfo.setNode(node);
- i->second.nodeDiscoInfo[node] = newInfo;
+ JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
+ DiscoInfo newInfo(discoInfo);
+ newInfo.setNode(node);
+ i->second.nodeDiscoInfo[node] = newInfo;
}
bool JIDDiscoInfoResponder::handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> discoInfo) {
- JIDDiscoInfoMap::const_iterator i = info.find(to);
- if (i != info.end()) {
- if (discoInfo->getNode().empty()) {
- sendResponse(from, to, id, boost::make_shared<DiscoInfo>(i->second.discoInfo));
- }
- else {
- std::map<std::string,DiscoInfo>::const_iterator j = i->second.nodeDiscoInfo.find(discoInfo->getNode());
- if (j != i->second.nodeDiscoInfo.end()) {
- sendResponse(from, to, id, boost::make_shared<DiscoInfo>(j->second));
- }
- else {
- sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
- }
- }
- }
- else {
- sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
- }
- return true;
+ JIDDiscoInfoMap::const_iterator i = info.find(to);
+ if (i != info.end()) {
+ if (discoInfo->getNode().empty()) {
+ sendResponse(from, to, id, boost::make_shared<DiscoInfo>(i->second.discoInfo));
+ }
+ else {
+ std::map<std::string,DiscoInfo>::const_iterator j = i->second.nodeDiscoInfo.find(discoInfo->getNode());
+ if (j != i->second.nodeDiscoInfo.end()) {
+ sendResponse(from, to, id, boost::make_shared<DiscoInfo>(j->second));
+ }
+ else {
+ sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
+ }
+ }
+ }
+ else {
+ sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
+ }
+ return true;
}
}
diff --git a/Swiften/Disco/JIDDiscoInfoResponder.h b/Swiften/Disco/JIDDiscoInfoResponder.h
index 1323b2d..e2fbb5b7 100644
--- a/Swiften/Disco/JIDDiscoInfoResponder.h
+++ b/Swiften/Disco/JIDDiscoInfoResponder.h
@@ -14,25 +14,25 @@
#include <Swiften/Queries/GetResponder.h>
namespace Swift {
- class IQRouter;
-
- class SWIFTEN_API JIDDiscoInfoResponder : public GetResponder<DiscoInfo> {
- public:
- JIDDiscoInfoResponder(IQRouter* router);
-
- void clearDiscoInfo(const JID& jid);
- void setDiscoInfo(const JID& jid, const DiscoInfo& info);
- void setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& info);
-
- private:
- virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload);
-
- private:
- struct JIDDiscoInfo {
- DiscoInfo discoInfo;
- std::map<std::string, DiscoInfo> nodeDiscoInfo;
- };
- typedef std::map<JID, JIDDiscoInfo> JIDDiscoInfoMap;
- JIDDiscoInfoMap info;
- };
+ class IQRouter;
+
+ class SWIFTEN_API JIDDiscoInfoResponder : public GetResponder<DiscoInfo> {
+ public:
+ JIDDiscoInfoResponder(IQRouter* router);
+
+ void clearDiscoInfo(const JID& jid);
+ void setDiscoInfo(const JID& jid, const DiscoInfo& info);
+ void setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& info);
+
+ private:
+ virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> payload);
+
+ private:
+ struct JIDDiscoInfo {
+ DiscoInfo discoInfo;
+ std::map<std::string, DiscoInfo> nodeDiscoInfo;
+ };
+ typedef std::map<JID, JIDDiscoInfo> JIDDiscoInfoMap;
+ JIDDiscoInfoMap info;
+ };
}
diff --git a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
index 857d6ff..58c9531 100644
--- a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
+++ b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
@@ -15,72 +15,72 @@
using namespace Swift;
class CapsInfoGeneratorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CapsInfoGeneratorTest);
- CPPUNIT_TEST(testGenerate_XEP0115SimpleExample);
- CPPUNIT_TEST(testGenerate_XEP0115ComplexExample);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(CapsInfoGeneratorTest);
+ CPPUNIT_TEST(testGenerate_XEP0115SimpleExample);
+ CPPUNIT_TEST(testGenerate_XEP0115ComplexExample);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
- void testGenerate_XEP0115SimpleExample() {
- DiscoInfo discoInfo;
- discoInfo.addIdentity(DiscoInfo::Identity("Exodus 0.9.1", "client", "pc"));
- discoInfo.addFeature("http://jabber.org/protocol/disco#items");
- discoInfo.addFeature("http://jabber.org/protocol/caps");
- discoInfo.addFeature("http://jabber.org/protocol/disco#info");
- discoInfo.addFeature("http://jabber.org/protocol/muc");
+ void testGenerate_XEP0115SimpleExample() {
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity("Exodus 0.9.1", "client", "pc"));
+ discoInfo.addFeature("http://jabber.org/protocol/disco#items");
+ discoInfo.addFeature("http://jabber.org/protocol/caps");
+ discoInfo.addFeature("http://jabber.org/protocol/disco#info");
+ discoInfo.addFeature("http://jabber.org/protocol/muc");
- CapsInfoGenerator testling("http://code.google.com/p/exodus", crypto.get());
- CapsInfo result = testling.generateCapsInfo(discoInfo);
+ CapsInfoGenerator testling("http://code.google.com/p/exodus", crypto.get());
+ CapsInfo result = testling.generateCapsInfo(discoInfo);
- CPPUNIT_ASSERT_EQUAL(std::string("http://code.google.com/p/exodus"), result.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), result.getHash());
- CPPUNIT_ASSERT_EQUAL(std::string("QgayPKawpkPSDYmwT/WM94uAlu0="), result.getVersion());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("http://code.google.com/p/exodus"), result.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), result.getHash());
+ CPPUNIT_ASSERT_EQUAL(std::string("QgayPKawpkPSDYmwT/WM94uAlu0="), result.getVersion());
+ }
- void testGenerate_XEP0115ComplexExample() {
- DiscoInfo discoInfo;
- discoInfo.addIdentity(DiscoInfo::Identity("Psi 0.11", "client", "pc", "en"));
- discoInfo.addIdentity(DiscoInfo::Identity("\xce\xa8 0.11", "client", "pc", "el"));
- discoInfo.addFeature("http://jabber.org/protocol/disco#items");
- discoInfo.addFeature("http://jabber.org/protocol/caps");
- discoInfo.addFeature("http://jabber.org/protocol/disco#info");
- discoInfo.addFeature("http://jabber.org/protocol/muc");
+ void testGenerate_XEP0115ComplexExample() {
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity("Psi 0.11", "client", "pc", "en"));
+ discoInfo.addIdentity(DiscoInfo::Identity("\xce\xa8 0.11", "client", "pc", "el"));
+ discoInfo.addFeature("http://jabber.org/protocol/disco#items");
+ discoInfo.addFeature("http://jabber.org/protocol/caps");
+ discoInfo.addFeature("http://jabber.org/protocol/disco#info");
+ discoInfo.addFeature("http://jabber.org/protocol/muc");
- Form::ref extension(new Form(Form::ResultType));
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "urn:xmpp:dataforms:softwareinfo");
- field->setName("FORM_TYPE");
- extension->addField(field);
- field = boost::make_shared<FormField>(FormField::ListMultiType);
- field->addValue("ipv6");
- field->addValue("ipv4");
- field->setName("ip_version");
- extension->addField(field);
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Psi");
- field->setName("software");
- extension->addField(field);
- field = boost::make_shared<FormField>(FormField::TextSingleType, "0.11");
- field->setName("software_version");
- extension->addField(field);
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Mac");
- field->setName("os");
- extension->addField(field);
- field = boost::make_shared<FormField>(FormField::TextSingleType, "10.5.1");
- field->setName("os_version");
- extension->addField(field);
- discoInfo.addExtension(extension);
+ Form::ref extension(new Form(Form::ResultType));
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "urn:xmpp:dataforms:softwareinfo");
+ field->setName("FORM_TYPE");
+ extension->addField(field);
+ field = boost::make_shared<FormField>(FormField::ListMultiType);
+ field->addValue("ipv6");
+ field->addValue("ipv4");
+ field->setName("ip_version");
+ extension->addField(field);
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Psi");
+ field->setName("software");
+ extension->addField(field);
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "0.11");
+ field->setName("software_version");
+ extension->addField(field);
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Mac");
+ field->setName("os");
+ extension->addField(field);
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "10.5.1");
+ field->setName("os_version");
+ extension->addField(field);
+ discoInfo.addExtension(extension);
- CapsInfoGenerator testling("http://psi-im.org", crypto.get());
- CapsInfo result = testling.generateCapsInfo(discoInfo);
+ CapsInfoGenerator testling("http://psi-im.org", crypto.get());
+ CapsInfo result = testling.generateCapsInfo(discoInfo);
- CPPUNIT_ASSERT_EQUAL(std::string("q07IKJEyjvHSyhy//CH0CxmKi8w="), result.getVersion());
- }
-
- private:
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_ASSERT_EQUAL(std::string("q07IKJEyjvHSyhy//CH0CxmKi8w="), result.getVersion());
+ }
+
+ private:
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CapsInfoGeneratorTest);
diff --git a/Swiften/Disco/UnitTest/CapsManagerTest.cpp b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
index 50f369c..fe7ee7e 100644
--- a/Swiften/Disco/UnitTest/CapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
@@ -24,269 +24,269 @@
using namespace Swift;
class CapsManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CapsManagerTest);
- CPPUNIT_TEST(testReceiveNewHashRequestsDisco);
- CPPUNIT_TEST(testReceiveSameHashDoesNotRequestDisco);
- CPPUNIT_TEST(testReceiveLegacyCapsDoesNotRequestDisco);
- CPPUNIT_TEST(testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
- CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco);
- CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco);
- CPPUNIT_TEST(testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
- CPPUNIT_TEST(testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco);
- CPPUNIT_TEST(testReceiveSuccesfulDiscoStoresCaps);
- CPPUNIT_TEST(testReceiveIncorrectVerificationDiscoDoesNotStoreCaps);
- CPPUNIT_TEST(testReceiveFailingDiscoFallsBack);
- CPPUNIT_TEST(testReceiveNoDiscoFallsBack);
- CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack);
- CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco);
- CPPUNIT_TEST(testReconnectResetsFallback);
- CPPUNIT_TEST(testReconnectResetsRequests);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- stanzaChannel = new DummyStanzaChannel();
- iqRouter = new IQRouter(stanzaChannel);
- storage = new CapsMemoryStorage();
- user1 = JID("user1@bar.com/bla");
- discoInfo1 = boost::make_shared<DiscoInfo>();
- discoInfo1->addFeature("http://swift.im/feature1");
- capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
- capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
- user2 = JID("user2@foo.com/baz");
- discoInfo2 = boost::make_shared<DiscoInfo>();
- discoInfo2->addFeature("http://swift.im/feature2");
- capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
- user3 = JID("user3@foo.com/baz");
- legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
- }
-
- void tearDown() {
- delete storage;
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testReceiveNewHashRequestsDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
- boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(discoInfo);
- CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode());
- }
-
- void testReceiveSameHashDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReceiveLegacyCapsDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, legacyCapsInfo);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendDiscoInfoResult(discoInfo1);
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReceiveSameHashFromSameUserAfterIncorrectVerificationDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendDiscoInfoResult(discoInfo2);
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user2, capsInfo1);
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get));
- }
-
- void testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendDiscoInfoResult(discoInfo2);
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user2, capsInfo1);
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get));
- }
-
- void testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
-
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo2);
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
- }
-
- void testReceiveSuccesfulDiscoStoresCaps() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendDiscoInfoResult(discoInfo1);
-
- boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
- CPPUNIT_ASSERT(discoInfo);
- CPPUNIT_ASSERT(discoInfo->hasFeature("http://swift.im/feature1"));
- }
-
- void testReceiveIncorrectVerificationDiscoDoesNotStoreCaps() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendDiscoInfoResult(discoInfo2);
-
- boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
- CPPUNIT_ASSERT(!discoInfo);
- }
-
- void testReceiveFailingDiscoFallsBack() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendPresenceWithCaps(user2, capsInfo1alt);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get));
- boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(discoInfo);
- CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
- }
-
- void testReceiveNoDiscoFallsBack() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendPresenceWithCaps(user2, capsInfo1alt);
- stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), boost::shared_ptr<DiscoInfo>()));
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get));
- boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(discoInfo);
- CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
- }
-
- void testReceiveFailingFallbackDiscoFallsBack() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendPresenceWithCaps(user2, capsInfo1alt);
- sendPresenceWithCaps(user3, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[1]->getTo(), stanzaChannel->sentStanzas[1]->getID()));
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(2, user3, IQ::Get));
- }
-
- void testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- stanzaChannel->sentStanzas.clear();
-
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
- }
-
- void testReconnectResetsFallback() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- sendPresenceWithCaps(user2, capsInfo1alt);
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- stanzaChannel->sentStanzas.clear();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testReconnectResetsRequests() {
- boost::shared_ptr<CapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
- stanzaChannel->sentStanzas.clear();
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
- }
-
- private:
- boost::shared_ptr<CapsManager> createManager() {
- boost::shared_ptr<CapsManager> manager(new CapsManager(storage, stanzaChannel, iqRouter, crypto.get()));
- manager->setWarnOnInvalidHash(false);
- //manager->onCapsChanged.connect(boost::bind(&CapsManagerTest::handleCapsChanged, this, _1));
- return manager;
- }
-
- void handleCapsChanged(const JID& jid) {
- changes.push_back(jid);
- }
-
- void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setFrom(jid);
- presence->addPayload(caps);
- stanzaChannel->onPresenceReceived(presence);
- }
-
- void sendDiscoInfoResult(boost::shared_ptr<DiscoInfo> discoInfo) {
- stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), discoInfo));
- }
-
- private:
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- CapsStorage* storage;
- std::vector<JID> changes;
- JID user1;
- boost::shared_ptr<DiscoInfo> discoInfo1;
- boost::shared_ptr<CapsInfo> capsInfo1;
- boost::shared_ptr<CapsInfo> capsInfo1alt;
- JID user2;
- boost::shared_ptr<DiscoInfo> discoInfo2;
- boost::shared_ptr<CapsInfo> capsInfo2;
- boost::shared_ptr<CapsInfo> legacyCapsInfo;
- JID user3;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(CapsManagerTest);
+ CPPUNIT_TEST(testReceiveNewHashRequestsDisco);
+ CPPUNIT_TEST(testReceiveSameHashDoesNotRequestDisco);
+ CPPUNIT_TEST(testReceiveLegacyCapsDoesNotRequestDisco);
+ CPPUNIT_TEST(testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
+ CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco);
+ CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco);
+ CPPUNIT_TEST(testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
+ CPPUNIT_TEST(testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco);
+ CPPUNIT_TEST(testReceiveSuccesfulDiscoStoresCaps);
+ CPPUNIT_TEST(testReceiveIncorrectVerificationDiscoDoesNotStoreCaps);
+ CPPUNIT_TEST(testReceiveFailingDiscoFallsBack);
+ CPPUNIT_TEST(testReceiveNoDiscoFallsBack);
+ CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack);
+ CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco);
+ CPPUNIT_TEST(testReconnectResetsFallback);
+ CPPUNIT_TEST(testReconnectResetsRequests);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ storage = new CapsMemoryStorage();
+ user1 = JID("user1@bar.com/bla");
+ discoInfo1 = boost::make_shared<DiscoInfo>();
+ discoInfo1->addFeature("http://swift.im/feature1");
+ capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ user2 = JID("user2@foo.com/baz");
+ discoInfo2 = boost::make_shared<DiscoInfo>();
+ discoInfo2->addFeature("http://swift.im/feature2");
+ capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
+ user3 = JID("user3@foo.com/baz");
+ legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
+ }
+
+ void tearDown() {
+ delete storage;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testReceiveNewHashRequestsDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
+ boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveSameHashDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveLegacyCapsDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, legacyCapsInfo);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo1);
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveSameHashFromSameUserAfterIncorrectVerificationDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo2);
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user2, capsInfo1);
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get));
+ }
+
+ void testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo2);
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user2, capsInfo1);
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user2, IQ::Get));
+ }
+
+ void testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
+
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo2);
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
+ }
+
+ void testReceiveSuccesfulDiscoStoresCaps() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo1);
+
+ boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT(discoInfo->hasFeature("http://swift.im/feature1"));
+ }
+
+ void testReceiveIncorrectVerificationDiscoDoesNotStoreCaps() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo2);
+
+ boost::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
+ CPPUNIT_ASSERT(!discoInfo);
+ }
+
+ void testReceiveFailingDiscoFallsBack() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendPresenceWithCaps(user2, capsInfo1alt);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get));
+ boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveNoDiscoFallsBack() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendPresenceWithCaps(user2, capsInfo1alt);
+ stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), boost::shared_ptr<DiscoInfo>()));
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get));
+ boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveFailingFallbackDiscoFallsBack() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendPresenceWithCaps(user2, capsInfo1alt);
+ sendPresenceWithCaps(user3, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[1]->getTo(), stanzaChannel->sentStanzas[1]->getID()));
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(2, user3, IQ::Get));
+ }
+
+ void testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ stanzaChannel->sentStanzas.clear();
+
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
+ }
+
+ void testReconnectResetsFallback() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendPresenceWithCaps(user2, capsInfo1alt);
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ stanzaChannel->sentStanzas.clear();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReconnectResetsRequests() {
+ boost::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ stanzaChannel->sentStanzas.clear();
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
+ }
+
+ private:
+ boost::shared_ptr<CapsManager> createManager() {
+ boost::shared_ptr<CapsManager> manager(new CapsManager(storage, stanzaChannel, iqRouter, crypto.get()));
+ manager->setWarnOnInvalidHash(false);
+ //manager->onCapsChanged.connect(boost::bind(&CapsManagerTest::handleCapsChanged, this, _1));
+ return manager;
+ }
+
+ void handleCapsChanged(const JID& jid) {
+ changes.push_back(jid);
+ }
+
+ void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(caps);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendDiscoInfoResult(boost::shared_ptr<DiscoInfo> discoInfo) {
+ stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), discoInfo));
+ }
+
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ CapsStorage* storage;
+ std::vector<JID> changes;
+ JID user1;
+ boost::shared_ptr<DiscoInfo> discoInfo1;
+ boost::shared_ptr<CapsInfo> capsInfo1;
+ boost::shared_ptr<CapsInfo> capsInfo1alt;
+ JID user2;
+ boost::shared_ptr<DiscoInfo> discoInfo2;
+ boost::shared_ptr<CapsInfo> capsInfo2;
+ boost::shared_ptr<CapsInfo> legacyCapsInfo;
+ JID user3;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CapsManagerTest);
diff --git a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
index 2bd50a3..907029e 100644
--- a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
+++ b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
@@ -16,82 +16,82 @@
using namespace Swift;
class DiscoInfoResponderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DiscoInfoResponderTest);
- CPPUNIT_TEST(testHandleRequest_GetToplevelInfo);
- CPPUNIT_TEST(testHandleRequest_GetNodeInfo);
- CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- channel_ = new DummyIQChannel();
- router_ = new IQRouter(channel_);
- }
-
- void tearDown() {
- delete router_;
- delete channel_;
- }
-
- void testHandleRequest_GetToplevelInfo() {
- DiscoInfoResponder testling(router_);
- testling.start();
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(discoInfo);
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode());
- CPPUNIT_ASSERT(payload->hasFeature("foo"));
-
- testling.stop();
- }
-
- void testHandleRequest_GetNodeInfo() {
- DiscoInfoResponder testling(router_);
- testling.start();
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(discoInfo);
- DiscoInfo discoInfoBar;
- discoInfoBar.addFeature("bar");
- testling.setDiscoInfo("bar-node", discoInfoBar);
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- query->setNode("bar-node");
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode());
- CPPUNIT_ASSERT(payload->hasFeature("bar"));
-
- testling.stop();
- }
-
- void testHandleRequest_GetInvalidNodeInfo() {
- DiscoInfoResponder testling(router_);
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- query->setNode("bar-node");
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
- testling.start();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
- CPPUNIT_ASSERT(payload);
-
- testling.stop();
- }
-
- private:
- IQRouter* router_;
- DummyIQChannel* channel_;
+ CPPUNIT_TEST_SUITE(DiscoInfoResponderTest);
+ CPPUNIT_TEST(testHandleRequest_GetToplevelInfo);
+ CPPUNIT_TEST(testHandleRequest_GetNodeInfo);
+ CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ }
+
+ void tearDown() {
+ delete router_;
+ delete channel_;
+ }
+
+ void testHandleRequest_GetToplevelInfo() {
+ DiscoInfoResponder testling(router_);
+ testling.start();
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(discoInfo);
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode());
+ CPPUNIT_ASSERT(payload->hasFeature("foo"));
+
+ testling.stop();
+ }
+
+ void testHandleRequest_GetNodeInfo() {
+ DiscoInfoResponder testling(router_);
+ testling.start();
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(discoInfo);
+ DiscoInfo discoInfoBar;
+ discoInfoBar.addFeature("bar");
+ testling.setDiscoInfo("bar-node", discoInfoBar);
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ query->setNode("bar-node");
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode());
+ CPPUNIT_ASSERT(payload->hasFeature("bar"));
+
+ testling.stop();
+ }
+
+ void testHandleRequest_GetInvalidNodeInfo() {
+ DiscoInfoResponder testling(router_);
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ query->setNode("bar-node");
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com"), "id-1", query));
+ testling.start();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
+ CPPUNIT_ASSERT(payload);
+
+ testling.stop();
+ }
+
+ private:
+ IQRouter* router_;
+ DummyIQChannel* channel_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DiscoInfoResponderTest);
diff --git a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
index 0a52dec..4062753 100644
--- a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
@@ -22,174 +22,174 @@
using namespace Swift;
class EntityCapsManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(EntityCapsManagerTest);
- CPPUNIT_TEST(testReceiveKnownHash);
- CPPUNIT_TEST(testReceiveKnownHashTwiceDoesNotTriggerChange);
- CPPUNIT_TEST(testReceiveUnknownHashDoesNotTriggerChange);
- CPPUNIT_TEST(testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps);
- CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps);
- CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps);
- CPPUNIT_TEST(testHashAvailable);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
-
- stanzaChannel = new DummyStanzaChannel();
- capsProvider = new DummyCapsProvider();
-
- user1 = JID("user1@bar.com/bla");
- discoInfo1 = boost::make_shared<DiscoInfo>();
- discoInfo1->addFeature("http://swift.im/feature1");
- capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
- capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
- user2 = JID("user2@foo.com/baz");
- discoInfo2 = boost::make_shared<DiscoInfo>();
- discoInfo2->addFeature("http://swift.im/feature2");
- capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
- user3 = JID("user3@foo.com/baz");
- legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
- }
-
- void tearDown() {
- delete capsProvider;
- delete stanzaChannel;
- }
-
- void testReceiveKnownHash() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1));
- }
-
- void testReceiveKnownHashTwiceDoesNotTriggerChange() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- sendPresenceWithCaps(user1, capsInfo1);
- changes.clear();
-
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testReceiveUnknownHashDoesNotTriggerChange() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testHashAvailable() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- sendPresenceWithCaps(user1, capsInfo1);
-
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- capsProvider->onCapsAvailable(capsInfo1->getVersion());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1));
- }
-
- void testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- sendPresenceWithCaps(user1, capsInfo1);
- changes.clear();
- sendPresenceWithCaps(user1, capsInfo2);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- CPPUNIT_ASSERT(!testling->getCaps(user1));
- }
-
- void testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- sendPresenceWithCaps(user1, capsInfo1);
- changes.clear();
- sendUnavailablePresence(user1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- CPPUNIT_ASSERT(!testling->getCaps(user1));
- }
-
- void testReconnectTriggersChangeAndClearsCaps() {
- boost::shared_ptr<EntityCapsManager> testling = createManager();
- capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
- capsProvider->caps[capsInfo2->getVersion()] = discoInfo2;
- sendPresenceWithCaps(user1, capsInfo1);
- sendPresenceWithCaps(user2, capsInfo2);
- changes.clear();
- stanzaChannel->setAvailable(false);
- stanzaChannel->setAvailable(true);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
- CPPUNIT_ASSERT(!testling->getCaps(user1));
- CPPUNIT_ASSERT_EQUAL(user2, changes[1]);
- CPPUNIT_ASSERT(!testling->getCaps(user2));
- }
-
- private:
- boost::shared_ptr<EntityCapsManager> createManager() {
- boost::shared_ptr<EntityCapsManager> manager(new EntityCapsManager(capsProvider, stanzaChannel));
- manager->onCapsChanged.connect(boost::bind(&EntityCapsManagerTest::handleCapsChanged, this, _1));
- return manager;
- }
-
- void handleCapsChanged(const JID& jid) {
- changes.push_back(jid);
- }
-
- void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setFrom(jid);
- presence->addPayload(caps);
- stanzaChannel->onPresenceReceived(presence);
- }
-
- void sendUnavailablePresence(const JID& jid) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setFrom(jid);
- presence->setType(Presence::Unavailable);
- stanzaChannel->onPresenceReceived(presence);
- }
-
- private:
- struct DummyCapsProvider : public CapsProvider {
- virtual DiscoInfo::ref getCaps(const std::string& hash) const {
- std::map<std::string, DiscoInfo::ref>::const_iterator i = caps.find(hash);
- if (i != caps.end()) {
- return i->second;
- }
- return DiscoInfo::ref();
- }
-
- std::map<std::string, DiscoInfo::ref> caps;
- };
-
- private:
- DummyStanzaChannel* stanzaChannel;
- DummyCapsProvider* capsProvider;
- JID user1;
- boost::shared_ptr<DiscoInfo> discoInfo1;
- boost::shared_ptr<CapsInfo> capsInfo1;
- boost::shared_ptr<CapsInfo> capsInfo1alt;
- JID user2;
- boost::shared_ptr<DiscoInfo> discoInfo2;
- boost::shared_ptr<CapsInfo> capsInfo2;
- boost::shared_ptr<CapsInfo> legacyCapsInfo;
- JID user3;
- std::vector<JID> changes;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(EntityCapsManagerTest);
+ CPPUNIT_TEST(testReceiveKnownHash);
+ CPPUNIT_TEST(testReceiveKnownHashTwiceDoesNotTriggerChange);
+ CPPUNIT_TEST(testReceiveUnknownHashDoesNotTriggerChange);
+ CPPUNIT_TEST(testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps);
+ CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps);
+ CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps);
+ CPPUNIT_TEST(testHashAvailable);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+
+ stanzaChannel = new DummyStanzaChannel();
+ capsProvider = new DummyCapsProvider();
+
+ user1 = JID("user1@bar.com/bla");
+ discoInfo1 = boost::make_shared<DiscoInfo>();
+ discoInfo1->addFeature("http://swift.im/feature1");
+ capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ user2 = JID("user2@foo.com/baz");
+ discoInfo2 = boost::make_shared<DiscoInfo>();
+ discoInfo2->addFeature("http://swift.im/feature2");
+ capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
+ user3 = JID("user3@foo.com/baz");
+ legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
+ }
+
+ void tearDown() {
+ delete capsProvider;
+ delete stanzaChannel;
+ }
+
+ void testReceiveKnownHash() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1));
+ }
+
+ void testReceiveKnownHashTwiceDoesNotTriggerChange() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ sendPresenceWithCaps(user1, capsInfo1);
+ changes.clear();
+
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testReceiveUnknownHashDoesNotTriggerChange() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testHashAvailable() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ capsProvider->onCapsAvailable(capsInfo1->getVersion());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1));
+ }
+
+ void testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ sendPresenceWithCaps(user1, capsInfo1);
+ changes.clear();
+ sendPresenceWithCaps(user1, capsInfo2);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ CPPUNIT_ASSERT(!testling->getCaps(user1));
+ }
+
+ void testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ sendPresenceWithCaps(user1, capsInfo1);
+ changes.clear();
+ sendUnavailablePresence(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ CPPUNIT_ASSERT(!testling->getCaps(user1));
+ }
+
+ void testReconnectTriggersChangeAndClearsCaps() {
+ boost::shared_ptr<EntityCapsManager> testling = createManager();
+ capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
+ capsProvider->caps[capsInfo2->getVersion()] = discoInfo2;
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendPresenceWithCaps(user2, capsInfo2);
+ changes.clear();
+ stanzaChannel->setAvailable(false);
+ stanzaChannel->setAvailable(true);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ CPPUNIT_ASSERT(!testling->getCaps(user1));
+ CPPUNIT_ASSERT_EQUAL(user2, changes[1]);
+ CPPUNIT_ASSERT(!testling->getCaps(user2));
+ }
+
+ private:
+ boost::shared_ptr<EntityCapsManager> createManager() {
+ boost::shared_ptr<EntityCapsManager> manager(new EntityCapsManager(capsProvider, stanzaChannel));
+ manager->onCapsChanged.connect(boost::bind(&EntityCapsManagerTest::handleCapsChanged, this, _1));
+ return manager;
+ }
+
+ void handleCapsChanged(const JID& jid) {
+ changes.push_back(jid);
+ }
+
+ void sendPresenceWithCaps(const JID& jid, boost::shared_ptr<CapsInfo> caps) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(caps);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendUnavailablePresence(const JID& jid) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->setType(Presence::Unavailable);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ private:
+ struct DummyCapsProvider : public CapsProvider {
+ virtual DiscoInfo::ref getCaps(const std::string& hash) const {
+ std::map<std::string, DiscoInfo::ref>::const_iterator i = caps.find(hash);
+ if (i != caps.end()) {
+ return i->second;
+ }
+ return DiscoInfo::ref();
+ }
+
+ std::map<std::string, DiscoInfo::ref> caps;
+ };
+
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ DummyCapsProvider* capsProvider;
+ JID user1;
+ boost::shared_ptr<DiscoInfo> discoInfo1;
+ boost::shared_ptr<CapsInfo> capsInfo1;
+ boost::shared_ptr<CapsInfo> capsInfo1alt;
+ JID user2;
+ boost::shared_ptr<DiscoInfo> discoInfo2;
+ boost::shared_ptr<CapsInfo> capsInfo2;
+ boost::shared_ptr<CapsInfo> legacyCapsInfo;
+ JID user3;
+ std::vector<JID> changes;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(EntityCapsManagerTest);
diff --git a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
index 613b049..3c1a057 100644
--- a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
+++ b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
@@ -16,104 +16,104 @@
using namespace Swift;
class JIDDiscoInfoResponderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(JIDDiscoInfoResponderTest);
- CPPUNIT_TEST(testHandleRequest_GetToplevelInfo);
- CPPUNIT_TEST(testHandleRequest_GetNodeInfo);
- CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo);
- CPPUNIT_TEST(testHandleRequest_GetUnknownJID);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- channel_ = new DummyIQChannel();
- router_ = new IQRouter(channel_);
- }
-
- void tearDown() {
- delete router_;
- delete channel_;
- }
-
- void testHandleRequest_GetToplevelInfo() {
- JIDDiscoInfoResponder testling(router_);
- testling.start();
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode());
- CPPUNIT_ASSERT(payload->hasFeature("foo"));
-
- testling.stop();
- }
-
- void testHandleRequest_GetNodeInfo() {
- JIDDiscoInfoResponder testling(router_);
- testling.start();
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
- DiscoInfo discoInfoBar;
- discoInfoBar.addFeature("bar");
- testling.setDiscoInfo(JID("foo@bar.com/baz"), "bar-node", discoInfoBar);
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- query->setNode("bar-node");
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode());
- CPPUNIT_ASSERT(payload->hasFeature("bar"));
-
- testling.stop();
- }
-
- void testHandleRequest_GetInvalidNodeInfo() {
- JIDDiscoInfoResponder testling(router_);
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
- testling.start();
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- query->setNode("bar-node");
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
- CPPUNIT_ASSERT(payload);
-
- testling.stop();
- }
-
- void testHandleRequest_GetUnknownJID() {
- JIDDiscoInfoResponder testling(router_);
- DiscoInfo discoInfo;
- discoInfo.addFeature("foo");
- testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
- testling.start();
-
- boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
- channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/fum"), "id-1", query));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
- CPPUNIT_ASSERT(payload);
-
- testling.stop();
- }
-
- private:
- IQRouter* router_;
- DummyIQChannel* channel_;
+ CPPUNIT_TEST_SUITE(JIDDiscoInfoResponderTest);
+ CPPUNIT_TEST(testHandleRequest_GetToplevelInfo);
+ CPPUNIT_TEST(testHandleRequest_GetNodeInfo);
+ CPPUNIT_TEST(testHandleRequest_GetInvalidNodeInfo);
+ CPPUNIT_TEST(testHandleRequest_GetUnknownJID);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ }
+
+ void tearDown() {
+ delete router_;
+ delete channel_;
+ }
+
+ void testHandleRequest_GetToplevelInfo() {
+ JIDDiscoInfoResponder testling(router_);
+ testling.start();
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), payload->getNode());
+ CPPUNIT_ASSERT(payload->hasFeature("foo"));
+
+ testling.stop();
+ }
+
+ void testHandleRequest_GetNodeInfo() {
+ JIDDiscoInfoResponder testling(router_);
+ testling.start();
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
+ DiscoInfo discoInfoBar;
+ discoInfoBar.addFeature("bar");
+ testling.setDiscoInfo(JID("foo@bar.com/baz"), "bar-node", discoInfoBar);
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ query->setNode("bar-node");
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<DiscoInfo> payload(channel_->iqs_[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar-node"), payload->getNode());
+ CPPUNIT_ASSERT(payload->hasFeature("bar"));
+
+ testling.stop();
+ }
+
+ void testHandleRequest_GetInvalidNodeInfo() {
+ JIDDiscoInfoResponder testling(router_);
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
+ testling.start();
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ query->setNode("bar-node");
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/baz"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
+ CPPUNIT_ASSERT(payload);
+
+ testling.stop();
+ }
+
+ void testHandleRequest_GetUnknownJID() {
+ JIDDiscoInfoResponder testling(router_);
+ DiscoInfo discoInfo;
+ discoInfo.addFeature("foo");
+ testling.setDiscoInfo(JID("foo@bar.com/baz"), discoInfo);
+ testling.start();
+
+ boost::shared_ptr<DiscoInfo> query(new DiscoInfo());
+ channel_->onIQReceived(IQ::createRequest(IQ::Get, JID("foo@bar.com/fum"), "id-1", query));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ boost::shared_ptr<ErrorPayload> payload(channel_->iqs_[0]->getPayload<ErrorPayload>());
+ CPPUNIT_ASSERT(payload);
+
+ testling.stop();
+ }
+
+ private:
+ IQRouter* router_;
+ DummyIQChannel* channel_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(JIDDiscoInfoResponderTest);
diff --git a/Swiften/Elements/AuthChallenge.h b/Swiften/Elements/AuthChallenge.h
index 61a72ec..0c43980 100644
--- a/Swiften/Elements/AuthChallenge.h
+++ b/Swiften/Elements/AuthChallenge.h
@@ -14,23 +14,23 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API AuthChallenge : public ToplevelElement {
- public:
- AuthChallenge() {
- }
+ class SWIFTEN_API AuthChallenge : public ToplevelElement {
+ public:
+ AuthChallenge() {
+ }
- AuthChallenge(const std::vector<unsigned char>& value) : value(value) {
- }
+ AuthChallenge(const std::vector<unsigned char>& value) : value(value) {
+ }
- const boost::optional< std::vector<unsigned char> >& getValue() const {
- return value;
- }
+ const boost::optional< std::vector<unsigned char> >& getValue() const {
+ return value;
+ }
- void setValue(const std::vector<unsigned char>& value) {
- this->value = boost::optional<std::vector<unsigned char> >(value);
- }
+ void setValue(const std::vector<unsigned char>& value) {
+ this->value = boost::optional<std::vector<unsigned char> >(value);
+ }
- private:
- boost::optional< std::vector<unsigned char> > value;
- };
+ private:
+ boost::optional< std::vector<unsigned char> > value;
+ };
}
diff --git a/Swiften/Elements/AuthFailure.h b/Swiften/Elements/AuthFailure.h
index e722d04..8f6702c 100644
--- a/Swiften/Elements/AuthFailure.h
+++ b/Swiften/Elements/AuthFailure.h
@@ -12,10 +12,10 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API AuthFailure : public ToplevelElement {
- public:
- typedef boost::shared_ptr<AuthFailure> ref;
+ class SWIFTEN_API AuthFailure : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<AuthFailure> ref;
- AuthFailure() {}
- };
+ AuthFailure() {}
+ };
}
diff --git a/Swiften/Elements/AuthRequest.h b/Swiften/Elements/AuthRequest.h
index 8043d1a..33b25b4 100644
--- a/Swiften/Elements/AuthRequest.h
+++ b/Swiften/Elements/AuthRequest.h
@@ -16,37 +16,37 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API AuthRequest : public ToplevelElement {
- public:
- AuthRequest(const std::string& mechanism = "") : mechanism_(mechanism) {
- }
-
- AuthRequest(const std::string& mechanism, const SafeByteArray& message) :
- mechanism_(mechanism), message_(message) {
- }
-
- AuthRequest(const std::string& mechanism, const boost::optional<SafeByteArray>& message) :
- mechanism_(mechanism), message_(message) {
- }
-
- const boost::optional<SafeByteArray>& getMessage() const {
- return message_;
- }
-
- void setMessage(const SafeByteArray& message) {
- message_ = boost::optional<SafeByteArray>(message);
- }
-
- const std::string& getMechanism() const {
- return mechanism_;
- }
-
- void setMechanism(const std::string& mechanism) {
- mechanism_ = mechanism;
- }
-
- private:
- std::string mechanism_;
- boost::optional<SafeByteArray> message_;
- };
+ class SWIFTEN_API AuthRequest : public ToplevelElement {
+ public:
+ AuthRequest(const std::string& mechanism = "") : mechanism_(mechanism) {
+ }
+
+ AuthRequest(const std::string& mechanism, const SafeByteArray& message) :
+ mechanism_(mechanism), message_(message) {
+ }
+
+ AuthRequest(const std::string& mechanism, const boost::optional<SafeByteArray>& message) :
+ mechanism_(mechanism), message_(message) {
+ }
+
+ const boost::optional<SafeByteArray>& getMessage() const {
+ return message_;
+ }
+
+ void setMessage(const SafeByteArray& message) {
+ message_ = boost::optional<SafeByteArray>(message);
+ }
+
+ const std::string& getMechanism() const {
+ return mechanism_;
+ }
+
+ void setMechanism(const std::string& mechanism) {
+ mechanism_ = mechanism;
+ }
+
+ private:
+ std::string mechanism_;
+ boost::optional<SafeByteArray> message_;
+ };
}
diff --git a/Swiften/Elements/AuthResponse.h b/Swiften/Elements/AuthResponse.h
index a6ba96f..a88e8d0 100644
--- a/Swiften/Elements/AuthResponse.h
+++ b/Swiften/Elements/AuthResponse.h
@@ -15,26 +15,26 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API AuthResponse : public ToplevelElement {
- public:
- AuthResponse() {
- }
+ class SWIFTEN_API AuthResponse : public ToplevelElement {
+ public:
+ AuthResponse() {
+ }
- AuthResponse(const SafeByteArray& value) : value(value) {
- }
+ AuthResponse(const SafeByteArray& value) : value(value) {
+ }
- AuthResponse(const boost::optional<SafeByteArray>& value) : value(value) {
- }
+ AuthResponse(const boost::optional<SafeByteArray>& value) : value(value) {
+ }
- const boost::optional<SafeByteArray>& getValue() const {
- return value;
- }
+ const boost::optional<SafeByteArray>& getValue() const {
+ return value;
+ }
- void setValue(const SafeByteArray& value) {
- this->value = boost::optional<SafeByteArray>(value);
- }
+ void setValue(const SafeByteArray& value) {
+ this->value = boost::optional<SafeByteArray>(value);
+ }
- private:
- boost::optional<SafeByteArray> value;
- };
+ private:
+ boost::optional<SafeByteArray> value;
+ };
}
diff --git a/Swiften/Elements/AuthSuccess.h b/Swiften/Elements/AuthSuccess.h
index d649574..860702c 100644
--- a/Swiften/Elements/AuthSuccess.h
+++ b/Swiften/Elements/AuthSuccess.h
@@ -14,19 +14,19 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API AuthSuccess : public ToplevelElement {
- public:
- AuthSuccess() {}
+ class SWIFTEN_API AuthSuccess : public ToplevelElement {
+ public:
+ AuthSuccess() {}
- const boost::optional<std::vector<unsigned char> >& getValue() const {
- return value;
- }
+ const boost::optional<std::vector<unsigned char> >& getValue() const {
+ return value;
+ }
- void setValue(const std::vector<unsigned char>& value) {
- this->value = boost::optional<std::vector<unsigned char> >(value);
- }
+ void setValue(const std::vector<unsigned char>& value) {
+ this->value = boost::optional<std::vector<unsigned char> >(value);
+ }
- private:
- boost::optional<std::vector<unsigned char> > value;
- };
+ private:
+ boost::optional<std::vector<unsigned char> > value;
+ };
}
diff --git a/Swiften/Elements/BlockListPayload.h b/Swiften/Elements/BlockListPayload.h
index 94f5150..acc9df4 100644
--- a/Swiften/Elements/BlockListPayload.h
+++ b/Swiften/Elements/BlockListPayload.h
@@ -13,20 +13,20 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API BlockListPayload : public Payload {
- public:
- BlockListPayload(const std::vector<JID>& items = std::vector<JID>()) : items(items) {
- }
+ class SWIFTEN_API BlockListPayload : public Payload {
+ public:
+ BlockListPayload(const std::vector<JID>& items = std::vector<JID>()) : items(items) {
+ }
- void addItem(const JID& item) {
- items.push_back(item);
- }
+ void addItem(const JID& item) {
+ items.push_back(item);
+ }
- const std::vector<JID>& getItems() const {
- return items;
- }
+ const std::vector<JID>& getItems() const {
+ return items;
+ }
- private:
- std::vector<JID> items;
- };
+ private:
+ std::vector<JID> items;
+ };
}
diff --git a/Swiften/Elements/BlockPayload.h b/Swiften/Elements/BlockPayload.h
index 7fae9d2..df8d150 100644
--- a/Swiften/Elements/BlockPayload.h
+++ b/Swiften/Elements/BlockPayload.h
@@ -13,20 +13,20 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API BlockPayload : public Payload {
- public:
- BlockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) {
- }
+ class SWIFTEN_API BlockPayload : public Payload {
+ public:
+ BlockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) {
+ }
- void addItem(const JID& jid) {
- items.push_back(jid);
- }
+ void addItem(const JID& jid) {
+ items.push_back(jid);
+ }
- const std::vector<JID>& getItems() const {
- return items;
- }
+ const std::vector<JID>& getItems() const {
+ return items;
+ }
- private:
- std::vector<JID> items;
- };
+ private:
+ std::vector<JID> items;
+ };
}
diff --git a/Swiften/Elements/Body.h b/Swiften/Elements/Body.h
index fc7016f..8761d5a 100644
--- a/Swiften/Elements/Body.h
+++ b/Swiften/Elements/Body.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Body : public Payload {
- public:
- Body(const std::string& text = "") : text_(text) {
- }
+ class SWIFTEN_API Body : public Payload {
+ public:
+ Body(const std::string& text = "") : text_(text) {
+ }
- void setText(const std::string& text) {
- text_ = text;
- }
+ void setText(const std::string& text) {
+ text_ = text;
+ }
- const std::string& getText() const {
- return text_;
- }
+ const std::string& getText() const {
+ return text_;
+ }
- private:
- std::string text_;
- };
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Elements/Bytestreams.h b/Swiften/Elements/Bytestreams.h
index 5d2ca30..dc6ec78 100644
--- a/Swiften/Elements/Bytestreams.h
+++ b/Swiften/Elements/Bytestreams.h
@@ -17,47 +17,47 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API Bytestreams : public Payload {
- public:
- typedef boost::shared_ptr<Bytestreams> ref;
+ class SWIFTEN_API Bytestreams : public Payload {
+ public:
+ typedef boost::shared_ptr<Bytestreams> ref;
- struct StreamHost {
- StreamHost(const std::string& host = "", const JID& jid = JID(), int port = -1) : host(host), jid(jid), port(port) {}
+ struct StreamHost {
+ StreamHost(const std::string& host = "", const JID& jid = JID(), int port = -1) : host(host), jid(jid), port(port) {}
- std::string host;
- JID jid;
- int port;
- };
+ std::string host;
+ JID jid;
+ int port;
+ };
- Bytestreams() {}
+ Bytestreams() {}
- const std::string& getStreamID() const {
- return id;
- }
+ const std::string& getStreamID() const {
+ return id;
+ }
- void setStreamID(const std::string& id) {
- this->id = id;
- }
+ void setStreamID(const std::string& id) {
+ this->id = id;
+ }
- const boost::optional<JID>& getUsedStreamHost() const {
- return usedStreamHost;
- }
+ const boost::optional<JID>& getUsedStreamHost() const {
+ return usedStreamHost;
+ }
- void setUsedStreamHost(const JID& host) {
- usedStreamHost = host;
- }
+ void setUsedStreamHost(const JID& host) {
+ usedStreamHost = host;
+ }
- const std::vector<StreamHost>& getStreamHosts() const {
- return streamHosts;
- }
+ const std::vector<StreamHost>& getStreamHosts() const {
+ return streamHosts;
+ }
- void addStreamHost(const StreamHost& streamHost) {
- streamHosts.push_back(streamHost);
- }
+ void addStreamHost(const StreamHost& streamHost) {
+ streamHosts.push_back(streamHost);
+ }
- private:
- std::string id;
- boost::optional<JID> usedStreamHost;
- std::vector<StreamHost> streamHosts;
- };
+ private:
+ std::string id;
+ boost::optional<JID> usedStreamHost;
+ std::vector<StreamHost> streamHosts;
+ };
}
diff --git a/Swiften/Elements/CapsInfo.h b/Swiften/Elements/CapsInfo.h
index fc92b10..875ede4 100644
--- a/Swiften/Elements/CapsInfo.h
+++ b/Swiften/Elements/CapsInfo.h
@@ -14,48 +14,48 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CapsInfo : public Payload {
- public:
- typedef boost::shared_ptr<CapsInfo> ref;
-
- CapsInfo(const std::string& node = "", const std::string& version = "", const std::string& hash = "sha-1") : node_(node), version_(version), hash_(hash) {}
-
- bool operator==(const CapsInfo& o) const {
- return o.node_ == node_ && o.version_ == version_ && o.hash_ == hash_;
- }
-
- bool operator<(const CapsInfo& o) const {
- if (o.node_ == node_) {
- if (o.version_ == version_) {
- return hash_ < o.hash_;
- }
- else {
- return version_ < o.version_;
- }
- }
- else {
- return node_ < o.node_;
- }
- }
-
- const std::string& getNode() const { return node_; }
- void setNode(const std::string& node) {
- node_ = node;
- }
-
- const std::string& getVersion() const { return version_; }
- void setVersion(const std::string& version) {
- version_ = version;
- }
-
- const std::string& getHash() const { return hash_; }
- void setHash(const std::string& hash) {
- hash_ = hash;
- }
-
- private:
- std::string node_;
- std::string version_;
- std::string hash_;
- };
+ class SWIFTEN_API CapsInfo : public Payload {
+ public:
+ typedef boost::shared_ptr<CapsInfo> ref;
+
+ CapsInfo(const std::string& node = "", const std::string& version = "", const std::string& hash = "sha-1") : node_(node), version_(version), hash_(hash) {}
+
+ bool operator==(const CapsInfo& o) const {
+ return o.node_ == node_ && o.version_ == version_ && o.hash_ == hash_;
+ }
+
+ bool operator<(const CapsInfo& o) const {
+ if (o.node_ == node_) {
+ if (o.version_ == version_) {
+ return hash_ < o.hash_;
+ }
+ else {
+ return version_ < o.version_;
+ }
+ }
+ else {
+ return node_ < o.node_;
+ }
+ }
+
+ const std::string& getNode() const { return node_; }
+ void setNode(const std::string& node) {
+ node_ = node;
+ }
+
+ const std::string& getVersion() const { return version_; }
+ void setVersion(const std::string& version) {
+ version_ = version;
+ }
+
+ const std::string& getHash() const { return hash_; }
+ void setHash(const std::string& hash) {
+ hash_ = hash;
+ }
+
+ private:
+ std::string node_;
+ std::string version_;
+ std::string hash_;
+ };
}
diff --git a/Swiften/Elements/CarbonsDisable.cpp b/Swiften/Elements/CarbonsDisable.cpp
index b5d80ca..848fa92 100644
--- a/Swiften/Elements/CarbonsDisable.cpp
+++ b/Swiften/Elements/CarbonsDisable.cpp
@@ -7,6 +7,6 @@
#include <Swiften/Elements/CarbonsDisable.h>
namespace Swift {
- CarbonsDisable::~CarbonsDisable() {
- }
+ CarbonsDisable::~CarbonsDisable() {
+ }
}
diff --git a/Swiften/Elements/CarbonsDisable.h b/Swiften/Elements/CarbonsDisable.h
index e31526d..f6c9a38 100644
--- a/Swiften/Elements/CarbonsDisable.h
+++ b/Swiften/Elements/CarbonsDisable.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CarbonsDisable : public Payload {
- public:
- typedef boost::shared_ptr<CarbonsDisable> ref;
+ class SWIFTEN_API CarbonsDisable : public Payload {
+ public:
+ typedef boost::shared_ptr<CarbonsDisable> ref;
- public:
- virtual ~CarbonsDisable();
- };
+ public:
+ virtual ~CarbonsDisable();
+ };
}
diff --git a/Swiften/Elements/CarbonsEnable.cpp b/Swiften/Elements/CarbonsEnable.cpp
index 7d38be1..c927cfb 100644
--- a/Swiften/Elements/CarbonsEnable.cpp
+++ b/Swiften/Elements/CarbonsEnable.cpp
@@ -7,6 +7,6 @@
#include <Swiften/Elements/CarbonsEnable.h>
namespace Swift {
- CarbonsEnable::~CarbonsEnable() {
- }
+ CarbonsEnable::~CarbonsEnable() {
+ }
}
diff --git a/Swiften/Elements/CarbonsEnable.h b/Swiften/Elements/CarbonsEnable.h
index b100e8d..1cb64ad 100644
--- a/Swiften/Elements/CarbonsEnable.h
+++ b/Swiften/Elements/CarbonsEnable.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CarbonsEnable : public Payload {
- public:
- typedef boost::shared_ptr<CarbonsEnable> ref;
+ class SWIFTEN_API CarbonsEnable : public Payload {
+ public:
+ typedef boost::shared_ptr<CarbonsEnable> ref;
- public:
- virtual ~CarbonsEnable();
- };
+ public:
+ virtual ~CarbonsEnable();
+ };
}
diff --git a/Swiften/Elements/CarbonsPrivate.cpp b/Swiften/Elements/CarbonsPrivate.cpp
index a0c6369..4ebcd31 100644
--- a/Swiften/Elements/CarbonsPrivate.cpp
+++ b/Swiften/Elements/CarbonsPrivate.cpp
@@ -7,6 +7,6 @@
#include <Swiften/Elements/CarbonsPrivate.h>
namespace Swift {
- CarbonsPrivate::~CarbonsPrivate() {
- }
+ CarbonsPrivate::~CarbonsPrivate() {
+ }
}
diff --git a/Swiften/Elements/CarbonsPrivate.h b/Swiften/Elements/CarbonsPrivate.h
index e363b5c..fdd3944 100644
--- a/Swiften/Elements/CarbonsPrivate.h
+++ b/Swiften/Elements/CarbonsPrivate.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CarbonsPrivate : public Payload {
- public:
- typedef boost::shared_ptr<CarbonsPrivate> ref;
+ class SWIFTEN_API CarbonsPrivate : public Payload {
+ public:
+ typedef boost::shared_ptr<CarbonsPrivate> ref;
- public:
- virtual ~CarbonsPrivate();
- };
+ public:
+ virtual ~CarbonsPrivate();
+ };
}
diff --git a/Swiften/Elements/CarbonsReceived.cpp b/Swiften/Elements/CarbonsReceived.cpp
index d906f8e..1c0a72b 100644
--- a/Swiften/Elements/CarbonsReceived.cpp
+++ b/Swiften/Elements/CarbonsReceived.cpp
@@ -7,15 +7,15 @@
#include <Swiften/Elements/CarbonsReceived.h>
namespace Swift {
- CarbonsReceived::~CarbonsReceived() {
+ CarbonsReceived::~CarbonsReceived() {
- }
+ }
- void CarbonsReceived::setForwarded(boost::shared_ptr<Forwarded> forwarded) {
- forwarded_ = forwarded;
- }
+ void CarbonsReceived::setForwarded(boost::shared_ptr<Forwarded> forwarded) {
+ forwarded_ = forwarded;
+ }
- boost::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const {
- return forwarded_;
- }
+ boost::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const {
+ return forwarded_;
+ }
}
diff --git a/Swiften/Elements/CarbonsReceived.h b/Swiften/Elements/CarbonsReceived.h
index b057893..82ccff9 100644
--- a/Swiften/Elements/CarbonsReceived.h
+++ b/Swiften/Elements/CarbonsReceived.h
@@ -13,16 +13,16 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CarbonsReceived : public Payload {
- public:
- typedef boost::shared_ptr<CarbonsReceived> ref;
+ class SWIFTEN_API CarbonsReceived : public Payload {
+ public:
+ typedef boost::shared_ptr<CarbonsReceived> ref;
- public:
- virtual ~CarbonsReceived();
- void setForwarded(boost::shared_ptr<Forwarded> forwarded);
- boost::shared_ptr<Forwarded> getForwarded() const;
+ public:
+ virtual ~CarbonsReceived();
+ void setForwarded(boost::shared_ptr<Forwarded> forwarded);
+ boost::shared_ptr<Forwarded> getForwarded() const;
- private:
- boost::shared_ptr<Forwarded> forwarded_;
- };
+ private:
+ boost::shared_ptr<Forwarded> forwarded_;
+ };
}
diff --git a/Swiften/Elements/CarbonsSent.cpp b/Swiften/Elements/CarbonsSent.cpp
index 08b2e13..c2380c6 100644
--- a/Swiften/Elements/CarbonsSent.cpp
+++ b/Swiften/Elements/CarbonsSent.cpp
@@ -7,15 +7,15 @@
#include <Swiften/Elements/CarbonsSent.h>
namespace Swift {
- CarbonsSent::~CarbonsSent() {
-
- }
+ CarbonsSent::~CarbonsSent() {
- void CarbonsSent::setForwarded(boost::shared_ptr<Forwarded> forwarded) {
- forwarded_ = forwarded;
- }
+ }
- boost::shared_ptr<Forwarded> CarbonsSent::getForwarded() const {
- return forwarded_;
- }
+ void CarbonsSent::setForwarded(boost::shared_ptr<Forwarded> forwarded) {
+ forwarded_ = forwarded;
+ }
+
+ boost::shared_ptr<Forwarded> CarbonsSent::getForwarded() const {
+ return forwarded_;
+ }
}
diff --git a/Swiften/Elements/CarbonsSent.h b/Swiften/Elements/CarbonsSent.h
index f6b2b53..d025a0d 100644
--- a/Swiften/Elements/CarbonsSent.h
+++ b/Swiften/Elements/CarbonsSent.h
@@ -13,16 +13,16 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API CarbonsSent : public Payload {
- public:
- typedef boost::shared_ptr<CarbonsSent> ref;
+ class SWIFTEN_API CarbonsSent : public Payload {
+ public:
+ typedef boost::shared_ptr<CarbonsSent> ref;
- public:
- virtual ~CarbonsSent();
- void setForwarded(boost::shared_ptr<Forwarded> forwarded);
- boost::shared_ptr<Forwarded> getForwarded() const;
+ public:
+ virtual ~CarbonsSent();
+ void setForwarded(boost::shared_ptr<Forwarded> forwarded);
+ boost::shared_ptr<Forwarded> getForwarded() const;
- private:
- boost::shared_ptr<Forwarded> forwarded_;
- };
+ private:
+ boost::shared_ptr<Forwarded> forwarded_;
+ };
}
diff --git a/Swiften/Elements/ChatState.h b/Swiften/Elements/ChatState.h
index 5f0bb9b..c1ae68e 100644
--- a/Swiften/Elements/ChatState.h
+++ b/Swiften/Elements/ChatState.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API ChatState : public Payload {
- public:
- typedef boost::shared_ptr<ChatState> ref;
+ class SWIFTEN_API ChatState : public Payload {
+ public:
+ typedef boost::shared_ptr<ChatState> ref;
- public:
- enum ChatStateType {Active, Composing, Paused, Inactive, Gone};
- ChatState(ChatStateType state = Active) {
- state_ = state;
- }
+ public:
+ enum ChatStateType {Active, Composing, Paused, Inactive, Gone};
+ ChatState(ChatStateType state = Active) {
+ state_ = state;
+ }
- ChatStateType getChatState() const { return state_; }
- void setChatState(ChatStateType state) {state_ = state;}
+ ChatStateType getChatState() const { return state_; }
+ void setChatState(ChatStateType state) {state_ = state;}
- private:
- ChatStateType state_;
- };
+ private:
+ ChatStateType state_;
+ };
}
diff --git a/Swiften/Elements/Command.h b/Swiften/Elements/Command.h
index e628c36..fff3d6b 100644
--- a/Swiften/Elements/Command.h
+++ b/Swiften/Elements/Command.h
@@ -15,69 +15,69 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- /**
- * Ad-Hoc Command (XEP-0050).
- */
- class SWIFTEN_API Command : public Payload {
- public:
- typedef boost::shared_ptr<Command> ref;
-
- enum Status {Executing, Completed, Canceled, NoStatus};
- enum Action {Cancel, Execute, Complete, Prev, Next, NoAction};
-
- struct Note {
- enum Type {Info, Warn, Error};
-
- Note(std::string note, Type type) : note(note), type(type) {}
-
- std::string note;
- Type type;
- };
-
- public:
- Command(const std::string& node, const std::string& sessionID, Status status) { constructor(node, sessionID, NoAction, status);}
- Command(const std::string& node = "", const std::string& sessionID = "", Action action = Execute) { constructor(node, sessionID, action, NoStatus); }
-
- const std::string& getNode() const { return node_; }
- void setNode(const std::string& node) { node_ = node; }
-
- const std::string& getSessionID() const { return sessionID_; }
- void setSessionID(const std::string& id) { sessionID_ = id; }
-
- Action getAction() const { return action_; }
- void setAction(Action action) { action_ = action; }
-
- void setExecuteAction(Action action) { executeAction_ = action; }
- Action getExecuteAction() const { return executeAction_; }
-
- Status getStatus() const { return status_; }
- void setStatus(Status status) { status_ = status; }
-
- void addAvailableAction(Action action) { availableActions_.push_back(action); }
- const std::vector<Action>& getAvailableActions() const { return availableActions_; }
- void addNote(const Note& note) { notes_.push_back(note); }
- const std::vector<Note>& getNotes() const { return notes_; }
-
- Form::ref getForm() const { return form_; }
- void setForm(Form::ref payload) { form_ = payload; }
-
- private:
- void constructor(const std::string& node, const std::string& sessionID, Action action, Status status) {
- node_ = node;
- sessionID_ = sessionID;
- action_ = action;
- status_ = status;
- executeAction_ = NoAction;
- }
-
- private:
- std::string node_;
- std::string sessionID_;
- Action action_;
- Status status_;
- Action executeAction_;
- std::vector<Action> availableActions_;
- std::vector<Note> notes_;
- Form::ref form_;
- };
+ /**
+ * Ad-Hoc Command (XEP-0050).
+ */
+ class SWIFTEN_API Command : public Payload {
+ public:
+ typedef boost::shared_ptr<Command> ref;
+
+ enum Status {Executing, Completed, Canceled, NoStatus};
+ enum Action {Cancel, Execute, Complete, Prev, Next, NoAction};
+
+ struct Note {
+ enum Type {Info, Warn, Error};
+
+ Note(std::string note, Type type) : note(note), type(type) {}
+
+ std::string note;
+ Type type;
+ };
+
+ public:
+ Command(const std::string& node, const std::string& sessionID, Status status) { constructor(node, sessionID, NoAction, status);}
+ Command(const std::string& node = "", const std::string& sessionID = "", Action action = Execute) { constructor(node, sessionID, action, NoStatus); }
+
+ const std::string& getNode() const { return node_; }
+ void setNode(const std::string& node) { node_ = node; }
+
+ const std::string& getSessionID() const { return sessionID_; }
+ void setSessionID(const std::string& id) { sessionID_ = id; }
+
+ Action getAction() const { return action_; }
+ void setAction(Action action) { action_ = action; }
+
+ void setExecuteAction(Action action) { executeAction_ = action; }
+ Action getExecuteAction() const { return executeAction_; }
+
+ Status getStatus() const { return status_; }
+ void setStatus(Status status) { status_ = status; }
+
+ void addAvailableAction(Action action) { availableActions_.push_back(action); }
+ const std::vector<Action>& getAvailableActions() const { return availableActions_; }
+ void addNote(const Note& note) { notes_.push_back(note); }
+ const std::vector<Note>& getNotes() const { return notes_; }
+
+ Form::ref getForm() const { return form_; }
+ void setForm(Form::ref payload) { form_ = payload; }
+
+ private:
+ void constructor(const std::string& node, const std::string& sessionID, Action action, Status status) {
+ node_ = node;
+ sessionID_ = sessionID;
+ action_ = action;
+ status_ = status;
+ executeAction_ = NoAction;
+ }
+
+ private:
+ std::string node_;
+ std::string sessionID_;
+ Action action_;
+ Status status_;
+ Action executeAction_;
+ std::vector<Action> availableActions_;
+ std::vector<Note> notes_;
+ Form::ref form_;
+ };
}
diff --git a/Swiften/Elements/ComponentHandshake.h b/Swiften/Elements/ComponentHandshake.h
index 8efd618..e8afc18 100644
--- a/Swiften/Elements/ComponentHandshake.h
+++ b/Swiften/Elements/ComponentHandshake.h
@@ -14,22 +14,22 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API ComponentHandshake : public ToplevelElement {
- public:
- typedef boost::shared_ptr<ComponentHandshake> ref;
+ class SWIFTEN_API ComponentHandshake : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<ComponentHandshake> ref;
- ComponentHandshake(const std::string& data = "") : data(data) {
- }
+ ComponentHandshake(const std::string& data = "") : data(data) {
+ }
- void setData(const std::string& d) {
- data = d;
- }
+ void setData(const std::string& d) {
+ data = d;
+ }
- const std::string& getData() const {
- return data;
- }
+ const std::string& getData() const {
+ return data;
+ }
- private:
- std::string data;
- };
+ private:
+ std::string data;
+ };
}
diff --git a/Swiften/Elements/CompressFailure.h b/Swiften/Elements/CompressFailure.h
index a32ba27..8cdd268 100644
--- a/Swiften/Elements/CompressFailure.h
+++ b/Swiften/Elements/CompressFailure.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API CompressFailure : public ToplevelElement {
- public:
- CompressFailure() {}
- };
+ class SWIFTEN_API CompressFailure : public ToplevelElement {
+ public:
+ CompressFailure() {}
+ };
}
diff --git a/Swiften/Elements/CompressRequest.h b/Swiften/Elements/CompressRequest.h
index 1c3fb39..7e813b9 100644
--- a/Swiften/Elements/CompressRequest.h
+++ b/Swiften/Elements/CompressRequest.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API CompressRequest : public ToplevelElement
- {
- public:
- CompressRequest(const std::string& method = "") : method_(method) {}
+ class SWIFTEN_API CompressRequest : public ToplevelElement
+ {
+ public:
+ CompressRequest(const std::string& method = "") : method_(method) {}
- const std::string& getMethod() const {
- return method_;
- }
+ const std::string& getMethod() const {
+ return method_;
+ }
- void setMethod(const std::string& method) {
- method_ = method;
- }
+ void setMethod(const std::string& method) {
+ method_ = method;
+ }
- private:
- std::string method_;
- };
+ private:
+ std::string method_;
+ };
}
diff --git a/Swiften/Elements/Compressed.h b/Swiften/Elements/Compressed.h
index bcfcacc..a2e236f 100644
--- a/Swiften/Elements/Compressed.h
+++ b/Swiften/Elements/Compressed.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API Compressed : public ToplevelElement {
- public:
- Compressed() {}
- };
+ class SWIFTEN_API Compressed : public ToplevelElement {
+ public:
+ Compressed() {}
+ };
}
diff --git a/Swiften/Elements/ContainerPayload.h b/Swiften/Elements/ContainerPayload.h
index 30e7541..7435f34 100644
--- a/Swiften/Elements/ContainerPayload.h
+++ b/Swiften/Elements/ContainerPayload.h
@@ -15,21 +15,21 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API ContainerPayload : public Payload {
- public:
- ContainerPayload() {}
- ContainerPayload(boost::shared_ptr<T> payload) : payload(payload) {}
-
- void setPayload(boost::shared_ptr<T> payload) {
- this->payload = payload;
- }
-
- boost::shared_ptr<T> getPayload() const {
- return payload;
- }
-
- private:
- boost::shared_ptr<T> payload;
- };
+ template<typename T>
+ class SWIFTEN_API ContainerPayload : public Payload {
+ public:
+ ContainerPayload() {}
+ ContainerPayload(boost::shared_ptr<T> payload) : payload(payload) {}
+
+ void setPayload(boost::shared_ptr<T> payload) {
+ this->payload = payload;
+ }
+
+ boost::shared_ptr<T> getPayload() const {
+ return payload;
+ }
+
+ private:
+ boost::shared_ptr<T> payload;
+ };
}
diff --git a/Swiften/Elements/Delay.h b/Swiften/Elements/Delay.h
index 2cfb1d0..b154dea 100644
--- a/Swiften/Elements/Delay.h
+++ b/Swiften/Elements/Delay.h
@@ -14,19 +14,19 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API Delay : public Payload {
- public:
- Delay() {}
- Delay(const boost::posix_time::ptime& time, const JID& from = JID()) : time_(time), from_(from) {}
+ class SWIFTEN_API Delay : public Payload {
+ public:
+ Delay() {}
+ Delay(const boost::posix_time::ptime& time, const JID& from = JID()) : time_(time), from_(from) {}
- const boost::posix_time::ptime& getStamp() const {return time_;}
- void setStamp(const boost::posix_time::ptime& time) {time_ = time;}
+ const boost::posix_time::ptime& getStamp() const {return time_;}
+ void setStamp(const boost::posix_time::ptime& time) {time_ = time;}
- const boost::optional<JID>& getFrom() const {return from_;}
- void setFrom(const JID& from) {from_ = from;}
+ const boost::optional<JID>& getFrom() const {return from_;}
+ void setFrom(const JID& from) {from_ = from;}
- private:
- boost::posix_time::ptime time_;
- boost::optional<JID> from_;
- };
+ private:
+ boost::posix_time::ptime time_;
+ boost::optional<JID> from_;
+ };
}
diff --git a/Swiften/Elements/DeliveryReceipt.h b/Swiften/Elements/DeliveryReceipt.h
index eac5280..a4936a5 100644
--- a/Swiften/Elements/DeliveryReceipt.h
+++ b/Swiften/Elements/DeliveryReceipt.h
@@ -20,24 +20,24 @@
namespace Swift {
class SWIFTEN_API DeliveryReceipt : public Payload {
- public:
- typedef boost::shared_ptr<DeliveryReceipt> ref;
+ public:
+ typedef boost::shared_ptr<DeliveryReceipt> ref;
- public:
- DeliveryReceipt() {}
+ public:
+ DeliveryReceipt() {}
- DeliveryReceipt(const std::string& msgId) : receivedID_(msgId) {}
+ DeliveryReceipt(const std::string& msgId) : receivedID_(msgId) {}
- void setReceivedID(const std::string& msgId) {
- receivedID_ = msgId;
- }
+ void setReceivedID(const std::string& msgId) {
+ receivedID_ = msgId;
+ }
- std::string getReceivedID() const {
- return receivedID_;
- }
+ std::string getReceivedID() const {
+ return receivedID_;
+ }
- private:
- std::string receivedID_;
+ private:
+ std::string receivedID_;
};
}
diff --git a/Swiften/Elements/DeliveryReceiptRequest.h b/Swiften/Elements/DeliveryReceiptRequest.h
index 1f03c5a..58086df 100644
--- a/Swiften/Elements/DeliveryReceiptRequest.h
+++ b/Swiften/Elements/DeliveryReceiptRequest.h
@@ -18,11 +18,11 @@
namespace Swift {
class SWIFTEN_API DeliveryReceiptRequest : public Payload {
- public:
- typedef boost::shared_ptr<DeliveryReceiptRequest> ref;
+ public:
+ typedef boost::shared_ptr<DeliveryReceiptRequest> ref;
- public:
- DeliveryReceiptRequest() {}
+ public:
+ DeliveryReceiptRequest() {}
};
}
diff --git a/Swiften/Elements/DiscoInfo.cpp b/Swiften/Elements/DiscoInfo.cpp
index 84f5ed3..29676b5 100644
--- a/Swiften/Elements/DiscoInfo.cpp
+++ b/Swiften/Elements/DiscoInfo.cpp
@@ -26,26 +26,26 @@ const std::string DiscoInfo::WhiteboardFeature = std::string("http://swift.im/wh
const std::string DiscoInfo::BlockingCommandFeature = std::string("urn:xmpp:blocking");
bool DiscoInfo::Identity::operator<(const Identity& other) const {
- if (category_ == other.category_) {
- if (type_ == other.type_) {
- if (lang_ == other.lang_) {
- return name_ < other.name_;
- }
- else {
- return lang_ < other.lang_;
- }
- }
- else {
- return type_ < other.type_;
- }
- }
- else {
- return category_ < other.category_;
- }
+ if (category_ == other.category_) {
+ if (type_ == other.type_) {
+ if (lang_ == other.lang_) {
+ return name_ < other.name_;
+ }
+ else {
+ return lang_ < other.lang_;
+ }
+ }
+ else {
+ return type_ < other.type_;
+ }
+ }
+ else {
+ return category_ < other.category_;
+ }
}
bool DiscoInfo::hasFeature(const std::string& feature) const {
- return std::find(features_.begin(), features_.end(), feature) != features_.end();
+ return std::find(features_.begin(), features_.end(), feature) != features_.end();
}
}
diff --git a/Swiften/Elements/DiscoInfo.h b/Swiften/Elements/DiscoInfo.h
index 01a49bd..d6ca6b8 100644
--- a/Swiften/Elements/DiscoInfo.h
+++ b/Swiften/Elements/DiscoInfo.h
@@ -14,100 +14,100 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- /**
- * disco#info from XEP-0030
- */
- class SWIFTEN_API DiscoInfo : public Payload {
- public:
- typedef boost::shared_ptr<DiscoInfo> ref;
-
- static const std::string ChatStatesFeature;
- static const std::string SecurityLabelsFeature;
- static const std::string SecurityLabelsCatalogFeature;
- static const std::string JabberSearchFeature;
- static const std::string CommandsFeature;
- static const std::string MessageCorrectionFeature;
- static const std::string JingleFeature;
- static const std::string JingleFTFeature;
- static const std::string JingleTransportsIBBFeature;
- static const std::string JingleTransportsS5BFeature;
- static const std::string Bytestream;
- static const std::string MessageDeliveryReceiptsFeature;
- static const std::string WhiteboardFeature;
- static const std::string BlockingCommandFeature;
-
- class Identity {
- public:
- Identity(const std::string& name, const std::string& category = "client", const std::string& type = "pc", const std::string& lang = "") : name_(name), category_(category), type_(type), lang_(lang) {
- }
-
- const std::string& getCategory() const {
- return category_;
- }
-
- const std::string& getType() const {
- return type_;
- }
-
- const std::string& getLanguage() const {
- return lang_;
- }
-
- const std::string& getName() const {
- return name_;
- }
-
- // Sorted according to XEP-115 rules
- bool operator<(const Identity& other) const;
-
- private:
- std::string name_;
- std::string category_;
- std::string type_;
- std::string lang_;
- };
-
- DiscoInfo() {
- }
-
- const std::string& getNode() const {
- return node_;
- }
-
- void setNode(const std::string& node) {
- node_ = node;
- }
-
- const std::vector<Identity>& getIdentities() const {
- return identities_;
- }
-
- void addIdentity(const Identity& identity) {
- identities_.push_back(identity);
- }
-
- const std::vector<std::string>& getFeatures() const {
- return features_;
- }
-
- void addFeature(const std::string& feature) {
- features_.push_back(feature);
- }
-
- bool hasFeature(const std::string& feature) const;
-
- void addExtension(Form::ref form) {
- extensions_.push_back(form);
- }
-
- const std::vector<Form::ref>& getExtensions() const {
- return extensions_;
- }
-
- private:
- std::string node_;
- std::vector<Identity> identities_;
- std::vector<std::string> features_;
- std::vector<Form::ref> extensions_;
- };
+ /**
+ * disco#info from XEP-0030
+ */
+ class SWIFTEN_API DiscoInfo : public Payload {
+ public:
+ typedef boost::shared_ptr<DiscoInfo> ref;
+
+ static const std::string ChatStatesFeature;
+ static const std::string SecurityLabelsFeature;
+ static const std::string SecurityLabelsCatalogFeature;
+ static const std::string JabberSearchFeature;
+ static const std::string CommandsFeature;
+ static const std::string MessageCorrectionFeature;
+ static const std::string JingleFeature;
+ static const std::string JingleFTFeature;
+ static const std::string JingleTransportsIBBFeature;
+ static const std::string JingleTransportsS5BFeature;
+ static const std::string Bytestream;
+ static const std::string MessageDeliveryReceiptsFeature;
+ static const std::string WhiteboardFeature;
+ static const std::string BlockingCommandFeature;
+
+ class Identity {
+ public:
+ Identity(const std::string& name, const std::string& category = "client", const std::string& type = "pc", const std::string& lang = "") : name_(name), category_(category), type_(type), lang_(lang) {
+ }
+
+ const std::string& getCategory() const {
+ return category_;
+ }
+
+ const std::string& getType() const {
+ return type_;
+ }
+
+ const std::string& getLanguage() const {
+ return lang_;
+ }
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ // Sorted according to XEP-115 rules
+ bool operator<(const Identity& other) const;
+
+ private:
+ std::string name_;
+ std::string category_;
+ std::string type_;
+ std::string lang_;
+ };
+
+ DiscoInfo() {
+ }
+
+ const std::string& getNode() const {
+ return node_;
+ }
+
+ void setNode(const std::string& node) {
+ node_ = node;
+ }
+
+ const std::vector<Identity>& getIdentities() const {
+ return identities_;
+ }
+
+ void addIdentity(const Identity& identity) {
+ identities_.push_back(identity);
+ }
+
+ const std::vector<std::string>& getFeatures() const {
+ return features_;
+ }
+
+ void addFeature(const std::string& feature) {
+ features_.push_back(feature);
+ }
+
+ bool hasFeature(const std::string& feature) const;
+
+ void addExtension(Form::ref form) {
+ extensions_.push_back(form);
+ }
+
+ const std::vector<Form::ref>& getExtensions() const {
+ return extensions_;
+ }
+
+ private:
+ std::string node_;
+ std::vector<Identity> identities_;
+ std::vector<std::string> features_;
+ std::vector<Form::ref> extensions_;
+ };
}
diff --git a/Swiften/Elements/DiscoItems.h b/Swiften/Elements/DiscoItems.h
index 4672444..9c06b8d 100644
--- a/Swiften/Elements/DiscoItems.h
+++ b/Swiften/Elements/DiscoItems.h
@@ -14,58 +14,58 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- /**
- * Service discovery disco#items from XEP-0030.
- */
- class SWIFTEN_API DiscoItems : public Payload {
- public:
- /**
- * A single result item.
- */
- class Item {
- public:
- Item(const std::string& name, const JID& jid, const std::string& node="") : name_(name), jid_(jid), node_(node) {
- }
+ /**
+ * Service discovery disco#items from XEP-0030.
+ */
+ class SWIFTEN_API DiscoItems : public Payload {
+ public:
+ /**
+ * A single result item.
+ */
+ class Item {
+ public:
+ Item(const std::string& name, const JID& jid, const std::string& node="") : name_(name), jid_(jid), node_(node) {
+ }
- const std::string& getName() const {
- return name_;
- }
+ const std::string& getName() const {
+ return name_;
+ }
- const std::string& getNode() const {
- return node_;
- }
+ const std::string& getNode() const {
+ return node_;
+ }
- const JID& getJID() const {
- return jid_;
- }
+ const JID& getJID() const {
+ return jid_;
+ }
- private:
- std::string name_;
- JID jid_;
- std::string node_;
- };
+ private:
+ std::string name_;
+ JID jid_;
+ std::string node_;
+ };
- DiscoItems() {
- }
+ DiscoItems() {
+ }
- const std::string& getNode() const {
- return node_;
- }
+ const std::string& getNode() const {
+ return node_;
+ }
- void setNode(const std::string& node) {
- node_ = node;
- }
+ void setNode(const std::string& node) {
+ node_ = node;
+ }
- const std::vector<Item>& getItems() const {
- return items_;
- }
+ const std::vector<Item>& getItems() const {
+ return items_;
+ }
- void addItem(const Item& item) {
- items_.push_back(item);
- }
+ void addItem(const Item& item) {
+ items_.push_back(item);
+ }
- private:
- std::string node_;
- std::vector<Item> items_;
- };
+ private:
+ std::string node_;
+ std::vector<Item> items_;
+ };
}
diff --git a/Swiften/Elements/Element.h b/Swiften/Elements/Element.h
index 3cd5f94..b036a29 100644
--- a/Swiften/Elements/Element.h
+++ b/Swiften/Elements/Element.h
@@ -9,12 +9,12 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API Element {
- public:
- Element() {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Element)
- virtual ~Element();
+ class SWIFTEN_API Element {
+ public:
+ Element() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Element)
+ virtual ~Element();
- SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Element)
- };
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Element)
+ };
}
diff --git a/Swiften/Elements/EnableStreamManagement.h b/Swiften/Elements/EnableStreamManagement.h
index c16a290..bf867e2 100644
--- a/Swiften/Elements/EnableStreamManagement.h
+++ b/Swiften/Elements/EnableStreamManagement.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API EnableStreamManagement : public ToplevelElement {
- public:
- EnableStreamManagement() {}
- };
+ class SWIFTEN_API EnableStreamManagement : public ToplevelElement {
+ public:
+ EnableStreamManagement() {}
+ };
}
diff --git a/Swiften/Elements/ErrorPayload.h b/Swiften/Elements/ErrorPayload.h
index d2556f9..800ff22 100644
--- a/Swiften/Elements/ErrorPayload.h
+++ b/Swiften/Elements/ErrorPayload.h
@@ -14,75 +14,75 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API ErrorPayload : public Payload {
- public:
- typedef boost::shared_ptr<ErrorPayload> ref;
-
- enum Type { Cancel, Continue, Modify, Auth, Wait };
-
- enum Condition {
- BadRequest,
- Conflict,
- FeatureNotImplemented,
- Forbidden,
- Gone,
- InternalServerError,
- ItemNotFound,
- JIDMalformed,
- NotAcceptable,
- NotAllowed,
- NotAuthorized,
- PaymentRequired,
- RecipientUnavailable,
- Redirect,
- RegistrationRequired,
- RemoteServerNotFound,
- RemoteServerTimeout,
- ResourceConstraint,
- ServiceUnavailable,
- SubscriptionRequired,
- UndefinedCondition,
- UnexpectedRequest
- };
-
- ErrorPayload(Condition condition = UndefinedCondition, Type type = Cancel, const std::string& text = std::string()) : type_(type), condition_(condition), text_(text) { }
-
- Type getType() const {
- return type_;
- }
-
- void setType(Type type) {
- type_ = type;
- }
-
- Condition getCondition() const {
- return condition_;
- }
-
- void setCondition(Condition condition) {
- condition_ = condition;
- }
-
- void setText(const std::string& text) {
- text_ = text;
- }
-
- const std::string& getText() const {
- return text_;
- }
-
- void setPayload(boost::shared_ptr<Payload> payload) {
- payload_ = payload;
- }
-
- boost::shared_ptr<Payload> getPayload() const {
- return payload_;
- }
-
- private:
- Type type_;
- Condition condition_;
- std::string text_;
- boost::shared_ptr<Payload> payload_;
- };
+ class SWIFTEN_API ErrorPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<ErrorPayload> ref;
+
+ enum Type { Cancel, Continue, Modify, Auth, Wait };
+
+ enum Condition {
+ BadRequest,
+ Conflict,
+ FeatureNotImplemented,
+ Forbidden,
+ Gone,
+ InternalServerError,
+ ItemNotFound,
+ JIDMalformed,
+ NotAcceptable,
+ NotAllowed,
+ NotAuthorized,
+ PaymentRequired,
+ RecipientUnavailable,
+ Redirect,
+ RegistrationRequired,
+ RemoteServerNotFound,
+ RemoteServerTimeout,
+ ResourceConstraint,
+ ServiceUnavailable,
+ SubscriptionRequired,
+ UndefinedCondition,
+ UnexpectedRequest
+ };
+
+ ErrorPayload(Condition condition = UndefinedCondition, Type type = Cancel, const std::string& text = std::string()) : type_(type), condition_(condition), text_(text) { }
+
+ Type getType() const {
+ return type_;
+ }
+
+ void setType(Type type) {
+ type_ = type;
+ }
+
+ Condition getCondition() const {
+ return condition_;
+ }
+
+ void setCondition(Condition condition) {
+ condition_ = condition;
+ }
+
+ void setText(const std::string& text) {
+ text_ = text;
+ }
+
+ const std::string& getText() const {
+ return text_;
+ }
+
+ void setPayload(boost::shared_ptr<Payload> payload) {
+ payload_ = payload;
+ }
+
+ boost::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ private:
+ Type type_;
+ Condition condition_;
+ std::string text_;
+ boost::shared_ptr<Payload> payload_;
+ };
}
diff --git a/Swiften/Elements/Form.cpp b/Swiften/Elements/Form.cpp
index d6de8ff..f8414b2 100644
--- a/Swiften/Elements/Form.cpp
+++ b/Swiften/Elements/Form.cpp
@@ -11,56 +11,56 @@
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 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_) {
- if (field->getName() == name) {
- return field;
- }
- }
- return FormField::ref();
+ foreach(FormField::ref field, fields_) {
+ if (field->getName() == name) {
+ return field;
+ }
+ }
+ return FormField::ref();
}
void Form::addReportedField(FormField::ref field) {
- reportedFields_.push_back(field);
+ reportedFields_.push_back(field);
}
const std::vector<FormField::ref>& Form::getReportedFields() const {
- return reportedFields_;
+ return reportedFields_;
}
void Form::addItem(const Form::FormItem& item) {
- items_.push_back(item);
+ items_.push_back(item);
}
const std::vector<Form::FormItem>& Form::getItems() const {
- return items_;
+ return items_;
}
void Form::clearEmptyTextFields() {
- std::vector<FormField::ref> populatedFields;
- foreach (FormField::ref 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;
+ std::vector<FormField::ref> populatedFields;
+ foreach (FormField::ref 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/Form.h b/Swiften/Elements/Form.h
index 31faf25..ebdb161 100644
--- a/Swiften/Elements/Form.h
+++ b/Swiften/Elements/Form.h
@@ -17,107 +17,107 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- /**
- * XEP-0004 Data form.
- * For the relevant Fields, the parsers and serialisers protect the API user against
- * the strange multi-value instead of newline thing by transforming them.
- */
- class SWIFTEN_API Form : public Payload {
- public:
- typedef boost::shared_ptr<Form> ref;
- typedef std::vector<FormField::ref> FormItem;
-
- enum Type { FormType, SubmitType, CancelType, ResultType };
-
- public:
- Form(Type type = FormType) : type_(type) {}
-
- void addPage(boost::shared_ptr<FormPage> page) {
- assert(page);
- pages_.push_back(page);
- }
-
- const std::vector<boost::shared_ptr<FormPage> >& getPages() const {
- return pages_;
- }
-
- void addField(boost::shared_ptr<FormField> field) {
- assert(field);
- fields_.push_back(field);
- }
-
- const std::vector<boost::shared_ptr<FormField> >& getFields() const {
- return fields_;
- }
-
- void clearFields() {
- fields_.clear();
- }
-
- void addTextElement(boost::shared_ptr<FormText> text) {
- assert(text);
- textElements_.push_back(text);
- }
-
- const std::vector<boost::shared_ptr<FormText> >& getTextElements() const {
- return textElements_;
- }
-
- void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) {
- assert(reportedRef);
- reportedRefs_.push_back(reportedRef);
- }
-
- const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const {
- return reportedRefs_;
- }
-
- void setTitle(const std::string& title) {
- title_ = title;
- }
-
- const std::string& getTitle() const {
- return title_;
- }
-
- void setInstructions(const std::string& instructions) {
- instructions_ = instructions;
- }
-
- const std::string& getInstructions() const {
- return instructions_;
- }
-
- Type getType() const {
- return type_;
- }
-
- void setType(Type type) {
- type_ = type;
- }
-
- std::string getFormType() const;
- FormField::ref getField(const std::string& name) const;
- void addItem(const FormItem& item);
- const std::vector<FormItem>& getItems() const;
- void clearItems() { items_.clear(); }
-
- void clearEmptyTextFields();
-
- void addReportedField(FormField::ref field);
- const std::vector<FormField::ref> & getReportedFields() const;
- void clearReportedFields() { reportedFields_.clear(); }
-
- private:
- std::vector<boost::shared_ptr<FormReportedRef> >reportedRefs_;
- std::vector<boost::shared_ptr<FormText> > textElements_;
- std::vector<boost::shared_ptr<FormPage> > pages_;
- std::vector<boost::shared_ptr<FormField> > fields_;
- std::vector<boost::shared_ptr<FormField> > reportedFields_;
- std::vector<FormItem> items_;
- boost::shared_ptr<FormReportedRef> reportedRef_;
- std::string title_;
- std::string instructions_;
- Type type_;
- };
+ /**
+ * XEP-0004 Data form.
+ * For the relevant Fields, the parsers and serialisers protect the API user against
+ * the strange multi-value instead of newline thing by transforming them.
+ */
+ class SWIFTEN_API Form : public Payload {
+ public:
+ typedef boost::shared_ptr<Form> ref;
+ typedef std::vector<FormField::ref> FormItem;
+
+ enum Type { FormType, SubmitType, CancelType, ResultType };
+
+ public:
+ Form(Type type = FormType) : type_(type) {}
+
+ void addPage(boost::shared_ptr<FormPage> page) {
+ assert(page);
+ pages_.push_back(page);
+ }
+
+ const std::vector<boost::shared_ptr<FormPage> >& getPages() const {
+ return pages_;
+ }
+
+ void addField(boost::shared_ptr<FormField> field) {
+ assert(field);
+ fields_.push_back(field);
+ }
+
+ const std::vector<boost::shared_ptr<FormField> >& getFields() const {
+ return fields_;
+ }
+
+ void clearFields() {
+ fields_.clear();
+ }
+
+ void addTextElement(boost::shared_ptr<FormText> text) {
+ assert(text);
+ textElements_.push_back(text);
+ }
+
+ const std::vector<boost::shared_ptr<FormText> >& getTextElements() const {
+ return textElements_;
+ }
+
+ void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) {
+ assert(reportedRef);
+ reportedRefs_.push_back(reportedRef);
+ }
+
+ const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const {
+ return reportedRefs_;
+ }
+
+ void setTitle(const std::string& title) {
+ title_ = title;
+ }
+
+ const std::string& getTitle() const {
+ return title_;
+ }
+
+ void setInstructions(const std::string& instructions) {
+ instructions_ = instructions;
+ }
+
+ const std::string& getInstructions() const {
+ return instructions_;
+ }
+
+ Type getType() const {
+ return type_;
+ }
+
+ void setType(Type type) {
+ type_ = type;
+ }
+
+ std::string getFormType() const;
+ FormField::ref getField(const std::string& name) const;
+ void addItem(const FormItem& item);
+ const std::vector<FormItem>& getItems() const;
+ void clearItems() { items_.clear(); }
+
+ void clearEmptyTextFields();
+
+ void addReportedField(FormField::ref field);
+ const std::vector<FormField::ref> & getReportedFields() const;
+ void clearReportedFields() { reportedFields_.clear(); }
+
+ private:
+ std::vector<boost::shared_ptr<FormReportedRef> >reportedRefs_;
+ std::vector<boost::shared_ptr<FormText> > textElements_;
+ std::vector<boost::shared_ptr<FormPage> > pages_;
+ std::vector<boost::shared_ptr<FormField> > fields_;
+ std::vector<boost::shared_ptr<FormField> > reportedFields_;
+ std::vector<FormItem> items_;
+ boost::shared_ptr<FormReportedRef> reportedRef_;
+ std::string title_;
+ std::string instructions_;
+ Type type_;
+ };
}
diff --git a/Swiften/Elements/FormField.cpp b/Swiften/Elements/FormField.cpp
index f8ebbca..d4bc9f4 100644
--- a/Swiften/Elements/FormField.cpp
+++ b/Swiften/Elements/FormField.cpp
@@ -16,17 +16,17 @@ FormField::~FormField() {
}
std::string FormField::getTextMultiValue() const {
- assert(type == TextMultiType || type == UnknownType);
- return boost::algorithm::join(values, "\n");
+ assert(type == TextMultiType || type == UnknownType);
+ return boost::algorithm::join(values, "\n");
}
void FormField::setTextMultiValue(const std::string& value) {
- assert(type == TextMultiType || type == UnknownType);
- values.clear();
- boost::split(values, value, boost::is_any_of("\n"));
+ assert(type == TextMultiType || type == UnknownType);
+ values.clear();
+ boost::split(values, value, boost::is_any_of("\n"));
}
void FormField::setBoolValue(bool b) {
- values.clear();
- values.push_back(b ? "1" : "0");
+ values.clear();
+ values.push_back(b ? "1" : "0");
}
diff --git a/Swiften/Elements/FormField.h b/Swiften/Elements/FormField.h
index d84dbb6..e62dec4 100644
--- a/Swiften/Elements/FormField.h
+++ b/Swiften/Elements/FormField.h
@@ -15,126 +15,126 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API FormField {
- public:
- typedef boost::shared_ptr<FormField> ref;
-
- enum Type {
- UnknownType,
- BooleanType,
- FixedType,
- HiddenType,
- ListSingleType,
- TextMultiType,
- TextPrivateType,
- TextSingleType,
- JIDSingleType,
- JIDMultiType,
- ListMultiType
- };
-
- FormField(Type type = UnknownType) : type(type), required(false) {}
- FormField(Type type, const std::string& value) : type(type), required(false) {
- addValue(value);
- }
- virtual ~FormField();
-
- struct Option {
- Option(const std::string& label, const std::string& value) : label(label), value(value) {}
- std::string label;
- std::string value;
- };
-
- void setName(const std::string& name) { this->name = name; }
- const std::string& getName() const { return name; }
-
- void setLabel(const std::string& label) { this->label = label; }
- const std::string& getLabel() const { return label; }
-
- void setDescription(const std::string& description) { this->description = description; }
- const std::string& getDescription() const { return description; }
-
- void setRequired(bool required) { this->required = required; }
- bool getRequired() const { return required; }
-
- void addOption(const Option& option) {
- options.push_back(option);
- }
-
- const std::vector<Option>& getOptions() const {
- return options;
- }
-
- void clearOptions() {
- options.clear();
- }
-
- const std::vector<std::string>& getValues() const {
- return values;
- }
-
- void addValue(const std::string& value) {
- values.push_back(value);
- }
-
- Type getType() const {
- return type;
- }
-
- void setType(Type type) {
- this->type = type;
- }
-
- // Type specific
-
- bool getBoolValue() const {
- assert(type == BooleanType || type == UnknownType);
- if (values.empty()) {
- return false;
- }
- return values[0] == "true" || values[0] == "1";
- }
-
- void setBoolValue(bool b);
-
- JID getJIDSingleValue() const {
- assert(type == JIDSingleType || type == UnknownType);
- return values.empty() ? JID() : JID(values[0]);
- }
-
- JID getJIDMultiValue(size_t index) const {
- assert(type == JIDMultiType || type == UnknownType);
- return values.empty() ? JID() : JID(values[index]);
- }
-
- std::string getTextPrivateValue() const {
- assert(type == TextPrivateType || type == UnknownType);
- return values.empty() ? "" : values[0];
- }
-
- std::string getFixedValue() const {
- assert(type == FixedType || type == UnknownType);
- return values.empty() ? "" : values[0];
- }
-
- std::string getTextSingleValue() const {
- assert(type == TextSingleType || type == UnknownType);
- return values.empty() ? "" : values[0];
- }
-
- std::string getTextMultiValue() const;
- void setTextMultiValue(const std::string& value);
-
- protected:
-
- private:
- Type type;
- std::string name;
- std::string label;
- std::string description;
- bool required;
- std::vector<Option> options;
- std::vector<std::string> values;
- };
+ class SWIFTEN_API FormField {
+ public:
+ typedef boost::shared_ptr<FormField> ref;
+
+ enum Type {
+ UnknownType,
+ BooleanType,
+ FixedType,
+ HiddenType,
+ ListSingleType,
+ TextMultiType,
+ TextPrivateType,
+ TextSingleType,
+ JIDSingleType,
+ JIDMultiType,
+ ListMultiType
+ };
+
+ FormField(Type type = UnknownType) : type(type), required(false) {}
+ FormField(Type type, const std::string& value) : type(type), required(false) {
+ addValue(value);
+ }
+ virtual ~FormField();
+
+ struct Option {
+ Option(const std::string& label, const std::string& value) : label(label), value(value) {}
+ std::string label;
+ std::string value;
+ };
+
+ void setName(const std::string& name) { this->name = name; }
+ const std::string& getName() const { return name; }
+
+ void setLabel(const std::string& label) { this->label = label; }
+ const std::string& getLabel() const { return label; }
+
+ void setDescription(const std::string& description) { this->description = description; }
+ const std::string& getDescription() const { return description; }
+
+ void setRequired(bool required) { this->required = required; }
+ bool getRequired() const { return required; }
+
+ void addOption(const Option& option) {
+ options.push_back(option);
+ }
+
+ const std::vector<Option>& getOptions() const {
+ return options;
+ }
+
+ void clearOptions() {
+ options.clear();
+ }
+
+ const std::vector<std::string>& getValues() const {
+ return values;
+ }
+
+ void addValue(const std::string& value) {
+ values.push_back(value);
+ }
+
+ Type getType() const {
+ return type;
+ }
+
+ void setType(Type type) {
+ this->type = type;
+ }
+
+ // Type specific
+
+ bool getBoolValue() const {
+ assert(type == BooleanType || type == UnknownType);
+ if (values.empty()) {
+ return false;
+ }
+ return values[0] == "true" || values[0] == "1";
+ }
+
+ void setBoolValue(bool b);
+
+ JID getJIDSingleValue() const {
+ assert(type == JIDSingleType || type == UnknownType);
+ return values.empty() ? JID() : JID(values[0]);
+ }
+
+ JID getJIDMultiValue(size_t index) const {
+ assert(type == JIDMultiType || type == UnknownType);
+ return values.empty() ? JID() : JID(values[index]);
+ }
+
+ std::string getTextPrivateValue() const {
+ assert(type == TextPrivateType || type == UnknownType);
+ return values.empty() ? "" : values[0];
+ }
+
+ std::string getFixedValue() const {
+ assert(type == FixedType || type == UnknownType);
+ return values.empty() ? "" : values[0];
+ }
+
+ std::string getTextSingleValue() const {
+ assert(type == TextSingleType || type == UnknownType);
+ return values.empty() ? "" : values[0];
+ }
+
+ std::string getTextMultiValue() const;
+ void setTextMultiValue(const std::string& value);
+
+ protected:
+
+ private:
+ Type type;
+ std::string name;
+ std::string label;
+ std::string description;
+ bool required;
+ std::vector<Option> options;
+ std::vector<std::string> values;
+ };
}
diff --git a/Swiften/Elements/FormPage.cpp b/Swiften/Elements/FormPage.cpp
index db7979f..a4e1616 100644
--- a/Swiften/Elements/FormPage.cpp
+++ b/Swiften/Elements/FormPage.cpp
@@ -14,51 +14,51 @@ FormPage::~FormPage() {
}
void FormPage::setLabel(const std::string& label) {
- label_ = label;
+ label_ = label;
}
const std::string& FormPage::getLabel() const {
- return label_;
+ return label_;
}
void FormPage::addChildSection(boost::shared_ptr<FormSection> section) {
- childSections_.push_back(section);
+ childSections_.push_back(section);
}
const std::vector<boost::shared_ptr<FormSection> >& FormPage::getChildSections() const {
- return childSections_;
+ return childSections_;
}
void FormPage::addTextElement(boost::shared_ptr<FormText> textElement) {
- textElements_.push_back(textElement);
+ textElements_.push_back(textElement);
}
const std::vector<boost::shared_ptr<FormText> >& FormPage::getTextElements() const {
- return textElements_;
+ return textElements_;
}
void FormPage::addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) {
- reportedRefs_.push_back(reportedRef);
+ reportedRefs_.push_back(reportedRef);
}
const std::vector<boost::shared_ptr<FormReportedRef> >& FormPage::getReportedRefs() const {
- return reportedRefs_;
+ return reportedRefs_;
}
void FormPage::addField(boost::shared_ptr<FormField> field) {
- fields_.push_back(field);
+ fields_.push_back(field);
}
const std::vector<boost::shared_ptr<FormField> >& FormPage::getFields() const {
- return fields_;
+ return fields_;
}
void FormPage::addFieldRef(std::string ref) {
- fieldRefs_.push_back(ref);
+ fieldRefs_.push_back(ref);
}
const std::vector<std::string> FormPage::getFieldRefs() const {
- return fieldRefs_;
+ return fieldRefs_;
}
}
diff --git a/Swiften/Elements/FormPage.h b/Swiften/Elements/FormPage.h
index 35bf63b..f7a4a9a 100644
--- a/Swiften/Elements/FormPage.h
+++ b/Swiften/Elements/FormPage.h
@@ -18,30 +18,30 @@
namespace Swift {
- class SWIFTEN_API FormPage {
- public:
- typedef boost::shared_ptr<FormPage> page;
- FormPage ();
- ~FormPage();
- void setLabel(const std::string& label);
- const std::string& getLabel() const;
- void addChildSection(boost::shared_ptr<FormSection> section);
- const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const;
- void addTextElement(boost::shared_ptr<FormText> textElement);
- const std::vector<boost::shared_ptr<FormText> >& getTextElements() const;
- void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef);
- const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const;
- void addField(boost::shared_ptr<FormField> field);
- const std::vector<boost::shared_ptr<FormField> >& getFields() const;
- void addFieldRef(std::string ref);
- const std::vector<std::string> getFieldRefs() const;
+ class SWIFTEN_API FormPage {
+ public:
+ typedef boost::shared_ptr<FormPage> page;
+ FormPage ();
+ ~FormPage();
+ void setLabel(const std::string& label);
+ const std::string& getLabel() const;
+ void addChildSection(boost::shared_ptr<FormSection> section);
+ const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const;
+ void addTextElement(boost::shared_ptr<FormText> textElement);
+ const std::vector<boost::shared_ptr<FormText> >& getTextElements() const;
+ void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef);
+ const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const;
+ void addField(boost::shared_ptr<FormField> field);
+ const std::vector<boost::shared_ptr<FormField> >& getFields() const;
+ void addFieldRef(std::string ref);
+ const std::vector<std::string> getFieldRefs() const;
- private:
- std::string label_;
- std::vector<boost::shared_ptr<FormText> > textElements_;
- std::vector<boost::shared_ptr<FormSection> > childSections_;
- std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_;
- std::vector<boost::shared_ptr<FormField> > fields_;
- std::vector<std::string> fieldRefs_;
- };
+ private:
+ std::string label_;
+ std::vector<boost::shared_ptr<FormText> > textElements_;
+ std::vector<boost::shared_ptr<FormSection> > childSections_;
+ std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_;
+ std::vector<boost::shared_ptr<FormField> > fields_;
+ std::vector<std::string> fieldRefs_;
+ };
}
diff --git a/Swiften/Elements/FormReportedRef.h b/Swiften/Elements/FormReportedRef.h
index 03a89d1..a972f10 100644
--- a/Swiften/Elements/FormReportedRef.h
+++ b/Swiften/Elements/FormReportedRef.h
@@ -11,9 +11,9 @@
namespace Swift {
- class SWIFTEN_API FormReportedRef {
+ class SWIFTEN_API FormReportedRef {
- public:
- typedef boost::shared_ptr<FormReportedRef> ref;
- };
+ public:
+ typedef boost::shared_ptr<FormReportedRef> ref;
+ };
}
diff --git a/Swiften/Elements/FormSection.cpp b/Swiften/Elements/FormSection.cpp
index 7b254df..2fe1954 100644
--- a/Swiften/Elements/FormSection.cpp
+++ b/Swiften/Elements/FormSection.cpp
@@ -14,51 +14,51 @@ FormSection::~FormSection() {
}
void FormSection::setLabel(const std::string& label) {
- label_ = label;
+ label_ = label;
}
const std::string& FormSection::getLabel() const {
- return label_;
+ return label_;
}
void FormSection::addTextElement(boost::shared_ptr<FormText> textElement) {
- textElements_.push_back(textElement);
+ textElements_.push_back(textElement);
}
const std::vector<boost::shared_ptr<FormText> >& FormSection::getTextElements() const {
- return textElements_;
+ return textElements_;
}
void FormSection::addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef) {
- reportedRefs_.push_back(reportedRef);
+ reportedRefs_.push_back(reportedRef);
}
const std::vector<boost::shared_ptr<FormReportedRef> >& FormSection::getReportedRefs() const {
- return reportedRefs_;
+ return reportedRefs_;
}
void FormSection::addChildSection(boost::shared_ptr<FormSection> childSection) {
- childSections_.push_back(childSection);
+ childSections_.push_back(childSection);
}
const std::vector<boost::shared_ptr<FormSection> >& FormSection::getChildSections() const {
- return childSections_;
+ return childSections_;
}
void FormSection::addField(boost::shared_ptr<FormField> field) {
- fields_.push_back(field);
+ fields_.push_back(field);
}
const std::vector<boost::shared_ptr<FormField> >& FormSection::getFields() const {
- return fields_;
+ return fields_;
}
void FormSection::addFieldRef(std::string ref) {
- fieldRefs_.push_back(ref);
+ fieldRefs_.push_back(ref);
}
const std::vector<std::string> FormSection::getFieldRefs() const {
- return fieldRefs_;
+ return fieldRefs_;
}
}
diff --git a/Swiften/Elements/FormSection.h b/Swiften/Elements/FormSection.h
index 523d507..69638c4 100644
--- a/Swiften/Elements/FormSection.h
+++ b/Swiften/Elements/FormSection.h
@@ -17,30 +17,30 @@
namespace Swift {
- class SWIFTEN_API FormSection {
- public:
- typedef boost::shared_ptr<FormSection> section;
- FormSection();
- ~FormSection();
- void setLabel(const std::string& label);
- const std::string& getLabel() const;
- void addTextElement(boost::shared_ptr<FormText> textElement);
- const std::vector<boost::shared_ptr<FormText> >& getTextElements() const;
- void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef);
- const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const;
- void addChildSection(boost::shared_ptr<FormSection> childSection);
- const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const;
- void addField(boost::shared_ptr<FormField> field);
- const std::vector<boost::shared_ptr<FormField> >& getFields() const;
- void addFieldRef(std::string ref);
- const std::vector<std::string> getFieldRefs() const;
+ class SWIFTEN_API FormSection {
+ public:
+ typedef boost::shared_ptr<FormSection> section;
+ FormSection();
+ ~FormSection();
+ void setLabel(const std::string& label);
+ const std::string& getLabel() const;
+ void addTextElement(boost::shared_ptr<FormText> textElement);
+ const std::vector<boost::shared_ptr<FormText> >& getTextElements() const;
+ void addReportedRef(boost::shared_ptr<FormReportedRef> reportedRef);
+ const std::vector<boost::shared_ptr<FormReportedRef> >& getReportedRefs() const;
+ void addChildSection(boost::shared_ptr<FormSection> childSection);
+ const std::vector<boost::shared_ptr<FormSection> >& getChildSections() const;
+ void addField(boost::shared_ptr<FormField> field);
+ const std::vector<boost::shared_ptr<FormField> >& getFields() const;
+ void addFieldRef(std::string ref);
+ const std::vector<std::string> getFieldRefs() const;
- private:
- std::string label_;
- std::vector<boost::shared_ptr<FormText> > textElements_;
- std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_;
- std::vector<boost::shared_ptr<FormSection> > childSections_;
- std::vector<boost::shared_ptr<FormField> > fields_;
- std::vector<std::string> fieldRefs_;
- };
+ private:
+ std::string label_;
+ std::vector<boost::shared_ptr<FormText> > textElements_;
+ std::vector<boost::shared_ptr<FormReportedRef> > reportedRefs_;
+ std::vector<boost::shared_ptr<FormSection> > childSections_;
+ std::vector<boost::shared_ptr<FormField> > fields_;
+ std::vector<std::string> fieldRefs_;
+ };
}
diff --git a/Swiften/Elements/FormText.cpp b/Swiften/Elements/FormText.cpp
index cbbfbe4..2180e13 100644
--- a/Swiften/Elements/FormText.cpp
+++ b/Swiften/Elements/FormText.cpp
@@ -14,11 +14,11 @@ FormText::~FormText() {
}
void FormText::setTextString(const std::string& text) {
- text_ = text;
+ text_ = text;
}
const std::string& FormText::getTextString() const {
- return text_;
+ return text_;
}
}
diff --git a/Swiften/Elements/FormText.h b/Swiften/Elements/FormText.h
index 5df1a25..1d95a3a 100644
--- a/Swiften/Elements/FormText.h
+++ b/Swiften/Elements/FormText.h
@@ -13,16 +13,16 @@
namespace Swift {
- class SWIFTEN_API FormText{
+ class SWIFTEN_API FormText{
- public:
- typedef boost::shared_ptr<FormText> text;
- FormText();
- virtual ~FormText();
- void setTextString(const std::string& text);
- const std::string& getTextString() const;
+ public:
+ typedef boost::shared_ptr<FormText> text;
+ FormText();
+ virtual ~FormText();
+ void setTextString(const std::string& text);
+ const std::string& getTextString() const;
- private:
- std::string text_;
- };
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Elements/Forwarded.h b/Swiften/Elements/Forwarded.h
index b39f5a5..8401fe1 100644
--- a/Swiften/Elements/Forwarded.h
+++ b/Swiften/Elements/Forwarded.h
@@ -13,21 +13,21 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class Delay;
- class Stanza;
+ class Delay;
+ class Stanza;
- class SWIFTEN_API Forwarded : public Payload {
- public:
- virtual ~Forwarded();
+ class SWIFTEN_API Forwarded : public Payload {
+ public:
+ virtual ~Forwarded();
- void setDelay(boost::shared_ptr<Delay> delay) { delay_ = delay; }
- const boost::shared_ptr<Delay>& getDelay() const { return delay_; }
+ void setDelay(boost::shared_ptr<Delay> delay) { delay_ = delay; }
+ const boost::shared_ptr<Delay>& getDelay() const { return delay_; }
- void setStanza(boost::shared_ptr<Stanza> stanza) { stanza_ = stanza; }
- const boost::shared_ptr<Stanza>& getStanza() const { return stanza_; }
+ void setStanza(boost::shared_ptr<Stanza> stanza) { stanza_ = stanza; }
+ const boost::shared_ptr<Stanza>& getStanza() const { return stanza_; }
- private:
- boost::shared_ptr<Delay> delay_;
- boost::shared_ptr<Stanza> stanza_;
- };
+ private:
+ boost::shared_ptr<Delay> delay_;
+ boost::shared_ptr<Stanza> stanza_;
+ };
}
diff --git a/Swiften/Elements/HashElement.h b/Swiften/Elements/HashElement.h
index cc5a0e4..bbe4d1c 100644
--- a/Swiften/Elements/HashElement.h
+++ b/Swiften/Elements/HashElement.h
@@ -12,34 +12,34 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- /*
- * @brief This class represents a XEP-0300 <hash/> element.
- */
- class SWIFTEN_API HashElement {
- public:
- HashElement(const std::string& algorithm, const ByteArray& hash) : algorithm_(algorithm), hash_(hash) {
- }
-
- void setHashValue(const std::string& algorithm, const ByteArray& hash) {
- algorithm_ = algorithm;
- hash_ = hash;
- }
-
- const std::string& getAlgorithm() const {
- return algorithm_;
- }
-
- const ByteArray& getHashValue() const {
- return hash_;
- }
-
- bool operator==(const HashElement& rhs) const {
- return (algorithm_ == rhs.algorithm_) && (hash_ == rhs.hash_);
- }
-
-
- private:
- std::string algorithm_;
- ByteArray hash_;
- };
+ /*
+ * @brief This class represents a XEP-0300 <hash/> element.
+ */
+ class SWIFTEN_API HashElement {
+ public:
+ HashElement(const std::string& algorithm, const ByteArray& hash) : algorithm_(algorithm), hash_(hash) {
+ }
+
+ void setHashValue(const std::string& algorithm, const ByteArray& hash) {
+ algorithm_ = algorithm;
+ hash_ = hash;
+ }
+
+ const std::string& getAlgorithm() const {
+ return algorithm_;
+ }
+
+ const ByteArray& getHashValue() const {
+ return hash_;
+ }
+
+ bool operator==(const HashElement& rhs) const {
+ return (algorithm_ == rhs.algorithm_) && (hash_ == rhs.hash_);
+ }
+
+
+ private:
+ std::string algorithm_;
+ ByteArray hash_;
+ };
}
diff --git a/Swiften/Elements/IBB.h b/Swiften/Elements/IBB.h
index a06e3bc..97a46bb 100644
--- a/Swiften/Elements/IBB.h
+++ b/Swiften/Elements/IBB.h
@@ -16,94 +16,94 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API IBB : public Payload {
- public:
- typedef boost::shared_ptr<IBB> ref;
-
- enum Action {
- Open,
- Close,
- Data
- };
- enum StanzaType {
- IQStanza,
- MessageStanza
- };
-
- IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(-1), sequenceNumber(-1) {
- }
-
- static IBB::ref createIBBOpen(const std::string& streamID, int blockSize) {
- IBB::ref result = boost::make_shared<IBB>(Open, streamID);
- result->setBlockSize(blockSize);
- return result;
- }
-
- static IBB::ref createIBBData(const std::string& streamID, int sequenceNumber, const std::vector<unsigned char>& data) {
- IBB::ref result = boost::make_shared<IBB>(Data, streamID);
- result->setSequenceNumber(sequenceNumber);
- result->setData(data);
- return result;
- }
-
- static IBB::ref createIBBClose(const std::string& streamID) {
- return boost::make_shared<IBB>(Close, streamID);
- }
-
- void setAction(Action action) {
- this->action = action;
- }
-
- Action getAction() const {
- return action;
- }
-
- void setStanzaType(StanzaType stanzaType) {
- this->stanzaType = stanzaType;
- }
-
- StanzaType getStanzaType() const {
- return stanzaType;
- }
-
- void setStreamID(const std::string& id) {
- streamID = id;
- }
-
- const std::string& getStreamID() const {
- return streamID;
- }
-
- const std::vector<unsigned char>& getData() const {
- return data;
- }
-
- void setData(const std::vector<unsigned char>& data) {
- this->data = data;
- }
-
- int getBlockSize() const {
- return blockSize;
- }
-
- void setBlockSize(int blockSize) {
- this->blockSize = blockSize;
- }
-
- int getSequenceNumber() const {
- return sequenceNumber;
- }
-
- void setSequenceNumber(int i) {
- sequenceNumber = i;
- }
-
- private:
- Action action;
- std::string streamID;
- std::vector<unsigned char> data;
- StanzaType stanzaType;
- int blockSize;
- int sequenceNumber;
- };
+ class SWIFTEN_API IBB : public Payload {
+ public:
+ typedef boost::shared_ptr<IBB> ref;
+
+ enum Action {
+ Open,
+ Close,
+ Data
+ };
+ enum StanzaType {
+ IQStanza,
+ MessageStanza
+ };
+
+ IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(-1), sequenceNumber(-1) {
+ }
+
+ static IBB::ref createIBBOpen(const std::string& streamID, int blockSize) {
+ IBB::ref result = boost::make_shared<IBB>(Open, streamID);
+ result->setBlockSize(blockSize);
+ return result;
+ }
+
+ static IBB::ref createIBBData(const std::string& streamID, int sequenceNumber, const std::vector<unsigned char>& data) {
+ IBB::ref result = boost::make_shared<IBB>(Data, streamID);
+ result->setSequenceNumber(sequenceNumber);
+ result->setData(data);
+ return result;
+ }
+
+ static IBB::ref createIBBClose(const std::string& streamID) {
+ return boost::make_shared<IBB>(Close, streamID);
+ }
+
+ void setAction(Action action) {
+ this->action = action;
+ }
+
+ Action getAction() const {
+ return action;
+ }
+
+ void setStanzaType(StanzaType stanzaType) {
+ this->stanzaType = stanzaType;
+ }
+
+ StanzaType getStanzaType() const {
+ return stanzaType;
+ }
+
+ void setStreamID(const std::string& id) {
+ streamID = id;
+ }
+
+ const std::string& getStreamID() const {
+ return streamID;
+ }
+
+ const std::vector<unsigned char>& getData() const {
+ return data;
+ }
+
+ void setData(const std::vector<unsigned char>& data) {
+ this->data = data;
+ }
+
+ int getBlockSize() const {
+ return blockSize;
+ }
+
+ void setBlockSize(int blockSize) {
+ this->blockSize = blockSize;
+ }
+
+ int getSequenceNumber() const {
+ return sequenceNumber;
+ }
+
+ void setSequenceNumber(int i) {
+ sequenceNumber = i;
+ }
+
+ private:
+ Action action;
+ std::string streamID;
+ std::vector<unsigned char> data;
+ StanzaType stanzaType;
+ int blockSize;
+ int sequenceNumber;
+ };
}
diff --git a/Swiften/Elements/IQ.cpp b/Swiften/Elements/IQ.cpp
index 343a205..cd1498e 100644
--- a/Swiften/Elements/IQ.cpp
+++ b/Swiften/Elements/IQ.cpp
@@ -11,58 +11,58 @@
namespace Swift {
boost::shared_ptr<IQ> IQ::createRequest(
- Type type, const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) {
- boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(type);
- if (to.isValid()) {
- iq->setTo(to);
- }
- iq->setID(id);
- if (payload) {
- iq->addPayload(payload);
- }
- return iq;
+ Type type, const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) {
+ boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(type);
+ if (to.isValid()) {
+ iq->setTo(to);
+ }
+ iq->setID(id);
+ if (payload) {
+ iq->addPayload(payload);
+ }
+ return iq;
}
boost::shared_ptr<IQ> IQ::createResult(const JID& to, const std::string& id, boost::shared_ptr<Payload> payload) {
- boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result);
- iq->setTo(to);
- iq->setID(id);
- if (payload) {
- iq->addPayload(payload);
- }
- return iq;
+ boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result);
+ iq->setTo(to);
+ iq->setID(id);
+ if (payload) {
+ iq->addPayload(payload);
+ }
+ return iq;
}
boost::shared_ptr<IQ> IQ::createResult(const JID& to, const JID& from, const std::string& id, boost::shared_ptr<Payload> payload) {
- boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result);
- iq->setTo(to);
- iq->setFrom(from);
- iq->setID(id);
- if (payload) {
- iq->addPayload(payload);
- }
- return iq;
+ boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(Result);
+ iq->setTo(to);
+ iq->setFrom(from);
+ iq->setID(id);
+ if (payload) {
+ iq->addPayload(payload);
+ }
+ return iq;
}
boost::shared_ptr<IQ> IQ::createError(const JID& to, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, boost::shared_ptr<Payload> payload) {
- boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error);
- iq->setTo(to);
- iq->setID(id);
- boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type);
- errorPayload->setPayload(payload);
- iq->addPayload(errorPayload);
- return iq;
+ boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error);
+ iq->setTo(to);
+ iq->setID(id);
+ boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type);
+ errorPayload->setPayload(payload);
+ iq->addPayload(errorPayload);
+ return iq;
}
boost::shared_ptr<IQ> IQ::createError(const JID& to, const JID& from, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, boost::shared_ptr<Payload> payload) {
- boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error);
- iq->setTo(to);
- iq->setFrom(from);
- iq->setID(id);
- boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type);
- errorPayload->setPayload(payload);
- iq->addPayload(errorPayload);
- return iq;
+ boost::shared_ptr<IQ> iq = boost::make_shared<IQ>(IQ::Error);
+ iq->setTo(to);
+ iq->setFrom(from);
+ iq->setID(id);
+ boost::shared_ptr<ErrorPayload> errorPayload = boost::make_shared<Swift::ErrorPayload>(condition, type);
+ errorPayload->setPayload(payload);
+ iq->addPayload(errorPayload);
+ return iq;
}
}
diff --git a/Swiften/Elements/IQ.h b/Swiften/Elements/IQ.h
index b77dd03..275c00e 100644
--- a/Swiften/Elements/IQ.h
+++ b/Swiften/Elements/IQ.h
@@ -13,46 +13,46 @@
#include <Swiften/Elements/Stanza.h>
namespace Swift {
- class SWIFTEN_API IQ : public Stanza {
- public:
- typedef boost::shared_ptr<IQ> ref;
-
- enum Type { Get, Set, Result, Error };
-
- IQ(Type type = Get) : type_(type) { }
-
- Type getType() const { return type_; }
- void setType(Type type) { type_ = type; }
-
- static boost::shared_ptr<IQ> createRequest(
- Type type,
- const JID& to,
- const std::string& id,
- boost::shared_ptr<Payload> payload);
- static boost::shared_ptr<IQ> createResult(
- const JID& to,
- const std::string& id,
- boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
- static boost::shared_ptr<IQ> createResult(
- const JID& to,
- const JID& from,
- const std::string& id,
- boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
- static boost::shared_ptr<IQ> createError(
- const JID& to,
- const std::string& id,
- ErrorPayload::Condition condition = ErrorPayload::BadRequest,
- ErrorPayload::Type type = ErrorPayload::Cancel,
- boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
- static boost::shared_ptr<IQ> createError(
- const JID& to,
- const JID& from,
- const std::string& id,
- ErrorPayload::Condition condition = ErrorPayload::BadRequest,
- ErrorPayload::Type type = ErrorPayload::Cancel,
- boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
-
- private:
- Type type_;
- };
+ class SWIFTEN_API IQ : public Stanza {
+ public:
+ typedef boost::shared_ptr<IQ> ref;
+
+ enum Type { Get, Set, Result, Error };
+
+ IQ(Type type = Get) : type_(type) { }
+
+ Type getType() const { return type_; }
+ void setType(Type type) { type_ = type; }
+
+ static boost::shared_ptr<IQ> createRequest(
+ Type type,
+ const JID& to,
+ const std::string& id,
+ boost::shared_ptr<Payload> payload);
+ static boost::shared_ptr<IQ> createResult(
+ const JID& to,
+ const std::string& id,
+ boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
+ static boost::shared_ptr<IQ> createResult(
+ const JID& to,
+ const JID& from,
+ const std::string& id,
+ boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
+ static boost::shared_ptr<IQ> createError(
+ const JID& to,
+ const std::string& id,
+ ErrorPayload::Condition condition = ErrorPayload::BadRequest,
+ ErrorPayload::Type type = ErrorPayload::Cancel,
+ boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
+ static boost::shared_ptr<IQ> createError(
+ const JID& to,
+ const JID& from,
+ const std::string& id,
+ ErrorPayload::Condition condition = ErrorPayload::BadRequest,
+ ErrorPayload::Type type = ErrorPayload::Cancel,
+ boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>());
+
+ private:
+ Type type_;
+ };
}
diff --git a/Swiften/Elements/Idle.h b/Swiften/Elements/Idle.h
index ec170fb..07ecc74 100644
--- a/Swiften/Elements/Idle.h
+++ b/Swiften/Elements/Idle.h
@@ -20,25 +20,25 @@
namespace Swift {
- class SWIFTEN_API Idle : public Payload {
- public:
- typedef boost::shared_ptr<Idle> ref;
-
- public:
- Idle() {}
- Idle(boost::posix_time::ptime since) : since_(since) {
- }
-
- void setSince(boost::posix_time::ptime since) {
- since_ = since;
- }
-
- boost::posix_time::ptime getSince() const {
- return since_;
- }
-
- private:
- boost::posix_time::ptime since_;
- };
+ class SWIFTEN_API Idle : public Payload {
+ public:
+ typedef boost::shared_ptr<Idle> ref;
+
+ public:
+ Idle() {}
+ Idle(boost::posix_time::ptime since) : since_(since) {
+ }
+
+ void setSince(boost::posix_time::ptime since) {
+ since_ = since;
+ }
+
+ boost::posix_time::ptime getSince() const {
+ return since_;
+ }
+
+ private:
+ boost::posix_time::ptime since_;
+ };
}
diff --git a/Swiften/Elements/InBandRegistrationPayload.h b/Swiften/Elements/InBandRegistrationPayload.h
index ef40c8f..a282df8 100644
--- a/Swiften/Elements/InBandRegistrationPayload.h
+++ b/Swiften/Elements/InBandRegistrationPayload.h
@@ -16,196 +16,196 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API InBandRegistrationPayload : public Payload {
- public:
- typedef boost::shared_ptr<InBandRegistrationPayload> ref;
+ class SWIFTEN_API InBandRegistrationPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<InBandRegistrationPayload> ref;
- InBandRegistrationPayload() : registered(false), remove(false) {}
+ InBandRegistrationPayload() : registered(false), remove(false) {}
- Form::ref getForm() const { return form; }
- void setForm(Form::ref f) { form = f; }
+ Form::ref getForm() const { return form; }
+ void setForm(Form::ref f) { form = f; }
- bool isRegistered() const {
- return registered;
- }
+ bool isRegistered() const {
+ return registered;
+ }
- void setRegistered(bool b) {
- registered = b;
- }
+ void setRegistered(bool b) {
+ registered = b;
+ }
- bool isRemove() const {
- return remove;
- }
+ bool isRemove() const {
+ return remove;
+ }
- void setRemove(bool b) {
- remove = b;
- }
+ void setRemove(bool b) {
+ remove = b;
+ }
- const boost::optional<std::string>& getInstructions() const {
- return instructions;
- }
+ const boost::optional<std::string>& getInstructions() const {
+ return instructions;
+ }
- const boost::optional<std::string>& getUsername() const {
- return username;
- }
+ const boost::optional<std::string>& getUsername() const {
+ return username;
+ }
- const boost::optional<std::string>& getNick() const {
- return nick;
- }
+ const boost::optional<std::string>& getNick() const {
+ return nick;
+ }
- const boost::optional<std::string>& getPassword() const {
- return password;
- }
+ const boost::optional<std::string>& getPassword() const {
+ return password;
+ }
- const boost::optional<std::string>& getName() const {
- return name;
- }
+ const boost::optional<std::string>& getName() const {
+ return name;
+ }
- const boost::optional<std::string>& getFirst() const {
- return first;
- }
+ const boost::optional<std::string>& getFirst() const {
+ return first;
+ }
- const boost::optional<std::string>& getLast() const {
- return last;
- }
+ const boost::optional<std::string>& getLast() const {
+ return last;
+ }
- const boost::optional<std::string>& getEMail() const {
- return email;
- }
+ const boost::optional<std::string>& getEMail() const {
+ return email;
+ }
- const boost::optional<std::string>& getAddress() const {
- return address;
- }
+ const boost::optional<std::string>& getAddress() const {
+ return address;
+ }
- const boost::optional<std::string>& getCity() const {
- return city;
- }
+ const boost::optional<std::string>& getCity() const {
+ return city;
+ }
- const boost::optional<std::string>& getState() const {
- return state;
- }
+ const boost::optional<std::string>& getState() const {
+ return state;
+ }
- const boost::optional<std::string>& getZip() const {
- return zip;
- }
+ const boost::optional<std::string>& getZip() const {
+ return zip;
+ }
- const boost::optional<std::string>& getPhone() const {
- return phone;
- }
-
- const boost::optional<std::string>& getURL() const {
- return url;
- }
-
- const boost::optional<std::string>& getDate() const {
- return date;
- }
-
- const boost::optional<std::string>& getMisc() const {
- return misc;
- }
-
- const boost::optional<std::string>& getText() const {
- return text;
- }
-
- const boost::optional<std::string>& getKey() const {
- return key;
- }
-
- void setInstructions(const std::string& v) {
- this->instructions = v;
- }
-
- void setUsername(const std::string& v) {
- this->username = v;
- }
-
- void setNick(const std::string& v) {
- this->nick = v;
- }
-
- void setPassword(const std::string& v) {
- this->password = v;
- }
-
- void setName(const std::string& v) {
- this->name = v;
- }
-
- void setFirst(const std::string& v) {
- this->first = v;
- }
-
- void setLast(const std::string& v) {
- this->last = v;
- }
-
- void setEMail(const std::string& v) {
- this->email = v;
- }
-
- void setAddress(const std::string& v) {
- this->address = v;
- }
-
- void setCity(const std::string& v) {
- this->city = v;
- }
-
- void setState(const std::string& v) {
- this->state = v;
- }
-
- void setZip(const std::string& v) {
- this->zip = v;
- }
-
- void setPhone(const std::string& v) {
- this->phone = v;
- }
-
- void setURL(const std::string& v) {
- this->url = v;
- }
-
- void setDate(const std::string& v) {
- this->date = v;
- }
-
- void setMisc(const std::string& v) {
- this->misc = v;
- }
-
- void setText(const std::string& v) {
- this->text = v;
- }
-
- void setKey(const std::string& v) {
- this->key = v;
- }
-
- private:
- Form::ref form;
- bool registered;
- bool remove;
- boost::optional<std::string> instructions;
- boost::optional<std::string> username;
- boost::optional<std::string> nick;
- boost::optional<std::string> password;
- boost::optional<std::string> name;
- boost::optional<std::string> first;
- boost::optional<std::string> last;
- boost::optional<std::string> email;
- boost::optional<std::string> address;
- boost::optional<std::string> city;
- boost::optional<std::string> state;
- boost::optional<std::string> zip;
- boost::optional<std::string> phone;
- boost::optional<std::string> url;
- boost::optional<std::string> date;
- boost::optional<std::string> misc;
- boost::optional<std::string> text;
- boost::optional<std::string> key;
- };
+ const boost::optional<std::string>& getPhone() const {
+ return phone;
+ }
+
+ const boost::optional<std::string>& getURL() const {
+ return url;
+ }
+
+ const boost::optional<std::string>& getDate() const {
+ return date;
+ }
+
+ const boost::optional<std::string>& getMisc() const {
+ return misc;
+ }
+
+ const boost::optional<std::string>& getText() const {
+ return text;
+ }
+
+ const boost::optional<std::string>& getKey() const {
+ return key;
+ }
+
+ void setInstructions(const std::string& v) {
+ this->instructions = v;
+ }
+
+ void setUsername(const std::string& v) {
+ this->username = v;
+ }
+
+ void setNick(const std::string& v) {
+ this->nick = v;
+ }
+
+ void setPassword(const std::string& v) {
+ this->password = v;
+ }
+
+ void setName(const std::string& v) {
+ this->name = v;
+ }
+
+ void setFirst(const std::string& v) {
+ this->first = v;
+ }
+
+ void setLast(const std::string& v) {
+ this->last = v;
+ }
+
+ void setEMail(const std::string& v) {
+ this->email = v;
+ }
+
+ void setAddress(const std::string& v) {
+ this->address = v;
+ }
+
+ void setCity(const std::string& v) {
+ this->city = v;
+ }
+
+ void setState(const std::string& v) {
+ this->state = v;
+ }
+
+ void setZip(const std::string& v) {
+ this->zip = v;
+ }
+
+ void setPhone(const std::string& v) {
+ this->phone = v;
+ }
+
+ void setURL(const std::string& v) {
+ this->url = v;
+ }
+
+ void setDate(const std::string& v) {
+ this->date = v;
+ }
+
+ void setMisc(const std::string& v) {
+ this->misc = v;
+ }
+
+ void setText(const std::string& v) {
+ this->text = v;
+ }
+
+ void setKey(const std::string& v) {
+ this->key = v;
+ }
+
+ private:
+ Form::ref form;
+ bool registered;
+ bool remove;
+ boost::optional<std::string> instructions;
+ boost::optional<std::string> username;
+ boost::optional<std::string> nick;
+ boost::optional<std::string> password;
+ boost::optional<std::string> name;
+ boost::optional<std::string> first;
+ boost::optional<std::string> last;
+ boost::optional<std::string> email;
+ boost::optional<std::string> address;
+ boost::optional<std::string> city;
+ boost::optional<std::string> state;
+ boost::optional<std::string> zip;
+ boost::optional<std::string> phone;
+ boost::optional<std::string> url;
+ boost::optional<std::string> date;
+ boost::optional<std::string> misc;
+ boost::optional<std::string> text;
+ boost::optional<std::string> key;
+ };
}
diff --git a/Swiften/Elements/IsodeIQDelegation.h b/Swiften/Elements/IsodeIQDelegation.h
index 7bd618c..12fd9bd 100644
--- a/Swiften/Elements/IsodeIQDelegation.h
+++ b/Swiften/Elements/IsodeIQDelegation.h
@@ -14,23 +14,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API IsodeIQDelegation : public Payload {
- public:
-
- IsodeIQDelegation();
-
- virtual ~IsodeIQDelegation();
+ class SWIFTEN_API IsodeIQDelegation : public Payload {
+ public:
- boost::shared_ptr<Forwarded> getForward() const {
- return forward;
- }
+ IsodeIQDelegation();
- void setForward(boost::shared_ptr<Forwarded> value) {
- this->forward = value ;
- }
+ virtual ~IsodeIQDelegation();
+ boost::shared_ptr<Forwarded> getForward() const {
+ return forward;
+ }
- private:
- boost::shared_ptr<Forwarded> forward;
- };
+ void setForward(boost::shared_ptr<Forwarded> value) {
+ this->forward = value ;
+ }
+
+
+ private:
+ boost::shared_ptr<Forwarded> forward;
+ };
}
diff --git a/Swiften/Elements/JingleContentPayload.h b/Swiften/Elements/JingleContentPayload.h
index 5ec2e33..46751fd 100644
--- a/Swiften/Elements/JingleContentPayload.h
+++ b/Swiften/Elements/JingleContentPayload.h
@@ -18,85 +18,85 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API JingleContentPayload : public Payload {
- public:
- typedef boost::shared_ptr<JingleContentPayload> ref;
-
- enum Creator {
- UnknownCreator,
- InitiatorCreator,
- ResponderCreator
- };
-
- JingleContentPayload() : creator(UnknownCreator) {
- }
-
- /*enum Senders {
- NoSenders,
- InitiatorSender,
- ResponderSender,
- BothSenders,
- };*/
-
- Creator getCreator() const {
- return creator;
- }
-
- void setCreator(Creator creator) {
- this->creator = creator;
- }
-
- const std::string& getName() const {
- return name;
- }
-
- void setName(const std::string& name) {
- this->name = name;
- }
-
- const std::vector<JingleDescription::ref>& getDescriptions() const {
- return descriptions;
- }
-
- void addDescription(JingleDescription::ref description) {
- descriptions.push_back(description);
- }
-
- const std::vector<boost::shared_ptr<JingleTransportPayload> >& getTransports() const {
- return transports;
- }
-
- void addTransport(boost::shared_ptr<JingleTransportPayload> transport) {
- transports.push_back(transport);
- }
-
- template<typename T>
- boost::shared_ptr<T> getDescription() const {
- for (size_t i = 0; i < descriptions.size(); ++i) {
- boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(descriptions[i]));
- if (result) {
- return result;
- }
- }
- return boost::shared_ptr<T>();
- }
-
- template<typename T>
- boost::shared_ptr<T> getTransport() const {
- for (size_t i = 0; i < transports.size(); ++i) {
- boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(transports[i]));
- if (result) {
- return result;
- }
- }
- return boost::shared_ptr<T>();
- }
-
- private:
- Creator creator;
- std::string name;
- //Senders senders;
- std::vector<JingleDescription::ref> descriptions;
- std::vector<boost::shared_ptr<JingleTransportPayload> > transports;
- };
+ class SWIFTEN_API JingleContentPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<JingleContentPayload> ref;
+
+ enum Creator {
+ UnknownCreator,
+ InitiatorCreator,
+ ResponderCreator
+ };
+
+ JingleContentPayload() : creator(UnknownCreator) {
+ }
+
+ /*enum Senders {
+ NoSenders,
+ InitiatorSender,
+ ResponderSender,
+ BothSenders,
+ };*/
+
+ Creator getCreator() const {
+ return creator;
+ }
+
+ void setCreator(Creator creator) {
+ this->creator = creator;
+ }
+
+ const std::string& getName() const {
+ return name;
+ }
+
+ void setName(const std::string& name) {
+ this->name = name;
+ }
+
+ const std::vector<JingleDescription::ref>& getDescriptions() const {
+ return descriptions;
+ }
+
+ void addDescription(JingleDescription::ref description) {
+ descriptions.push_back(description);
+ }
+
+ const std::vector<boost::shared_ptr<JingleTransportPayload> >& getTransports() const {
+ return transports;
+ }
+
+ void addTransport(boost::shared_ptr<JingleTransportPayload> transport) {
+ transports.push_back(transport);
+ }
+
+ template<typename T>
+ boost::shared_ptr<T> getDescription() const {
+ for (size_t i = 0; i < descriptions.size(); ++i) {
+ boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(descriptions[i]));
+ if (result) {
+ return result;
+ }
+ }
+ return boost::shared_ptr<T>();
+ }
+
+ template<typename T>
+ boost::shared_ptr<T> getTransport() const {
+ for (size_t i = 0; i < transports.size(); ++i) {
+ boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(transports[i]));
+ if (result) {
+ return result;
+ }
+ }
+ return boost::shared_ptr<T>();
+ }
+
+ private:
+ Creator creator;
+ std::string name;
+ //Senders senders;
+ std::vector<JingleDescription::ref> descriptions;
+ std::vector<boost::shared_ptr<JingleTransportPayload> > transports;
+ };
}
diff --git a/Swiften/Elements/JingleDescription.h b/Swiften/Elements/JingleDescription.h
index 7577383..b52291e 100644
--- a/Swiften/Elements/JingleDescription.h
+++ b/Swiften/Elements/JingleDescription.h
@@ -12,8 +12,8 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API JingleDescription : public Payload {
- public:
- typedef boost::shared_ptr<JingleDescription> ref;
- };
+ class SWIFTEN_API JingleDescription : public Payload {
+ public:
+ typedef boost::shared_ptr<JingleDescription> ref;
+ };
}
diff --git a/Swiften/Elements/JingleFileTransferDescription.h b/Swiften/Elements/JingleFileTransferDescription.h
index e37f2c6..4389bb2 100644
--- a/Swiften/Elements/JingleFileTransferDescription.h
+++ b/Swiften/Elements/JingleFileTransferDescription.h
@@ -15,19 +15,19 @@
#include <Swiften/Elements/JingleFileTransferFileInfo.h>
namespace Swift {
- class SWIFTEN_API JingleFileTransferDescription : public JingleDescription {
- public:
- typedef boost::shared_ptr<JingleFileTransferDescription> ref;
+ class SWIFTEN_API JingleFileTransferDescription : public JingleDescription {
+ public:
+ typedef boost::shared_ptr<JingleFileTransferDescription> ref;
- void setFileInfo(const JingleFileTransferFileInfo& fileInfo) {
- fileInfo_ = fileInfo;
- }
+ void setFileInfo(const JingleFileTransferFileInfo& fileInfo) {
+ fileInfo_ = fileInfo;
+ }
- const JingleFileTransferFileInfo& getFileInfo() {
- return fileInfo_;
- }
+ const JingleFileTransferFileInfo& getFileInfo() {
+ return fileInfo_;
+ }
- private:
- JingleFileTransferFileInfo fileInfo_;
- };
+ private:
+ JingleFileTransferFileInfo fileInfo_;
+ };
}
diff --git a/Swiften/Elements/JingleFileTransferFileInfo.h b/Swiften/Elements/JingleFileTransferFileInfo.h
index 40640c8..cc592c4 100644
--- a/Swiften/Elements/JingleFileTransferFileInfo.h
+++ b/Swiften/Elements/JingleFileTransferFileInfo.h
@@ -20,102 +20,102 @@
namespace Swift {
- /**
- * @brief This class represents the file info used in XEP-0234.
- */
- class SWIFTEN_API JingleFileTransferFileInfo : public Payload {
- typedef boost::shared_ptr<JingleFileTransferFileInfo> ref;
-
- public:
- JingleFileTransferFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, const boost::posix_time::ptime &date = boost::posix_time::ptime()) :
- name_(name), description_(description), size_(size), date_(date), supportsRangeRequests_(false), rangeOffset_(0) {
- }
-
- public:
- typedef std::map<std::string, ByteArray> HashElementMap;
-
- public:
- void setName(const std::string& name) {
- name_ = name;;
- }
-
- const std::string& getName() const {
- return name_;
- }
-
- void setDescription(const std::string& description) {
- description_ = description;
- }
-
- const std::string& getDescription() const {
- return description_;
- }
-
- void setMediaType(const std::string& mediaType) {
- mediaType_ = mediaType;
- }
-
- const std::string& getMediaType() const {
- return mediaType_;
- }
-
- void setSize(const boost::uintmax_t size) {
- size_ = size;
- }
-
- boost::uintmax_t getSize() const {
- return size_;
- }
-
- void setDate(const boost::posix_time::ptime& date) {
- date_ = date;
- }
-
- const boost::posix_time::ptime& getDate() const {
- return date_;
- }
-
- void setSupportsRangeRequests(const bool supportsIt) {
- supportsRangeRequests_ = supportsIt;
- }
-
- bool getSupportsRangeRequests() const {
- return supportsRangeRequests_;
- }
-
- void setRangeOffset(const boost::uintmax_t offset) {
- supportsRangeRequests_ = true;
- rangeOffset_ = offset;
- }
-
- boost::uintmax_t getRangeOffset() const {
- return rangeOffset_;
- }
-
- void addHash(const HashElement& hash) {
- hashes_[hash.getAlgorithm()] = hash.getHashValue();
- }
-
- const std::map<std::string, ByteArray>& getHashes() const {
- return hashes_;
- }
-
- boost::optional<ByteArray> getHash(const std::string& algorithm) const {
- boost::optional<ByteArray> ret;
- if (hashes_.find(algorithm) != hashes_.end()) {
- ret = boost::optional<ByteArray>(hashes_.find(algorithm)->second);
- }
- return ret;
- }
-
- private:
- std::string name_;
- std::string description_;
- std::string mediaType_;
- boost::uintmax_t size_;
- boost::posix_time::ptime date_;
- bool supportsRangeRequests_;
- boost::uintmax_t rangeOffset_;
- HashElementMap hashes_;
- };
+ /**
+ * @brief This class represents the file info used in XEP-0234.
+ */
+ class SWIFTEN_API JingleFileTransferFileInfo : public Payload {
+ typedef boost::shared_ptr<JingleFileTransferFileInfo> ref;
+
+ public:
+ JingleFileTransferFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0, const boost::posix_time::ptime &date = boost::posix_time::ptime()) :
+ name_(name), description_(description), size_(size), date_(date), supportsRangeRequests_(false), rangeOffset_(0) {
+ }
+
+ public:
+ typedef std::map<std::string, ByteArray> HashElementMap;
+
+ public:
+ void setName(const std::string& name) {
+ name_ = name;;
+ }
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ void setDescription(const std::string& description) {
+ description_ = description;
+ }
+
+ const std::string& getDescription() const {
+ return description_;
+ }
+
+ void setMediaType(const std::string& mediaType) {
+ mediaType_ = mediaType;
+ }
+
+ const std::string& getMediaType() const {
+ return mediaType_;
+ }
+
+ void setSize(const boost::uintmax_t size) {
+ size_ = size;
+ }
+
+ boost::uintmax_t getSize() const {
+ return size_;
+ }
+
+ void setDate(const boost::posix_time::ptime& date) {
+ date_ = date;
+ }
+
+ const boost::posix_time::ptime& getDate() const {
+ return date_;
+ }
+
+ void setSupportsRangeRequests(const bool supportsIt) {
+ supportsRangeRequests_ = supportsIt;
+ }
+
+ bool getSupportsRangeRequests() const {
+ return supportsRangeRequests_;
+ }
+
+ void setRangeOffset(const boost::uintmax_t offset) {
+ supportsRangeRequests_ = true;
+ rangeOffset_ = offset;
+ }
+
+ boost::uintmax_t getRangeOffset() const {
+ return rangeOffset_;
+ }
+
+ void addHash(const HashElement& hash) {
+ hashes_[hash.getAlgorithm()] = hash.getHashValue();
+ }
+
+ const std::map<std::string, ByteArray>& getHashes() const {
+ return hashes_;
+ }
+
+ boost::optional<ByteArray> getHash(const std::string& algorithm) const {
+ boost::optional<ByteArray> ret;
+ if (hashes_.find(algorithm) != hashes_.end()) {
+ ret = boost::optional<ByteArray>(hashes_.find(algorithm)->second);
+ }
+ return ret;
+ }
+
+ private:
+ std::string name_;
+ std::string description_;
+ std::string mediaType_;
+ boost::uintmax_t size_;
+ boost::posix_time::ptime date_;
+ bool supportsRangeRequests_;
+ boost::uintmax_t rangeOffset_;
+ HashElementMap hashes_;
+ };
}
diff --git a/Swiften/Elements/JingleFileTransferHash.h b/Swiften/Elements/JingleFileTransferHash.h
index 7c56fe8..42fc23c 100644
--- a/Swiften/Elements/JingleFileTransferHash.h
+++ b/Swiften/Elements/JingleFileTransferHash.h
@@ -25,18 +25,18 @@ namespace Swift {
class SWIFTEN_API JingleFileTransferHash : public Payload {
public:
- typedef boost::shared_ptr<JingleFileTransferHash> ref;
+ typedef boost::shared_ptr<JingleFileTransferHash> ref;
- void setFileInfo(const JingleFileTransferFileInfo& fileInfo) {
- fileInfo_ = fileInfo;
- }
+ void setFileInfo(const JingleFileTransferFileInfo& fileInfo) {
+ fileInfo_ = fileInfo;
+ }
- JingleFileTransferFileInfo& getFileInfo() {
- return fileInfo_;
- }
+ JingleFileTransferFileInfo& getFileInfo() {
+ return fileInfo_;
+ }
private:
- JingleFileTransferFileInfo fileInfo_;
+ JingleFileTransferFileInfo fileInfo_;
};
-
+
}
diff --git a/Swiften/Elements/JingleIBBTransportPayload.h b/Swiften/Elements/JingleIBBTransportPayload.h
index efadf0b..6626f51 100644
--- a/Swiften/Elements/JingleIBBTransportPayload.h
+++ b/Swiften/Elements/JingleIBBTransportPayload.h
@@ -15,36 +15,36 @@
#include <Swiften/Elements/JingleTransportPayload.h>
namespace Swift {
- class SWIFTEN_API JingleIBBTransportPayload : public JingleTransportPayload {
- public:
- typedef boost::shared_ptr<JingleIBBTransportPayload> ref;
-
- enum StanzaType {
- IQStanza,
- MessageStanza
- };
-
- JingleIBBTransportPayload() : stanzaType(IQStanza) {
- }
-
- void setStanzaType(StanzaType stanzaType) {
- this->stanzaType = stanzaType;
- }
-
- StanzaType getStanzaType() const {
- return stanzaType;
- }
-
- boost::optional<unsigned int> getBlockSize() const {
- return blockSize;
- }
-
- void setBlockSize(unsigned int blockSize) {
- this->blockSize = blockSize;
- }
-
- private:
- boost::optional<unsigned int> blockSize;
- StanzaType stanzaType;
- };
+ class SWIFTEN_API JingleIBBTransportPayload : public JingleTransportPayload {
+ public:
+ typedef boost::shared_ptr<JingleIBBTransportPayload> ref;
+
+ enum StanzaType {
+ IQStanza,
+ MessageStanza
+ };
+
+ JingleIBBTransportPayload() : stanzaType(IQStanza) {
+ }
+
+ void setStanzaType(StanzaType stanzaType) {
+ this->stanzaType = stanzaType;
+ }
+
+ StanzaType getStanzaType() const {
+ return stanzaType;
+ }
+
+ boost::optional<unsigned int> getBlockSize() const {
+ return blockSize;
+ }
+
+ void setBlockSize(unsigned int blockSize) {
+ this->blockSize = blockSize;
+ }
+
+ private:
+ boost::optional<unsigned int> blockSize;
+ StanzaType stanzaType;
+ };
}
diff --git a/Swiften/Elements/JinglePayload.h b/Swiften/Elements/JinglePayload.h
index 359e3ca..a862c41 100644
--- a/Swiften/Elements/JinglePayload.h
+++ b/Swiften/Elements/JinglePayload.h
@@ -18,150 +18,150 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API JinglePayload : public Payload {
- public:
- typedef boost::shared_ptr<JinglePayload> ref;
- struct Reason : public Payload {
- enum Type {
- UnknownType,
- AlternativeSession,
- Busy,
- Cancel,
- ConnectivityError,
- Decline,
- Expired,
- FailedApplication,
- FailedTransport,
- GeneralError,
- Gone,
- IncompatibleParameters,
- MediaError,
- SecurityError,
- Success,
- Timeout,
- UnsupportedApplications,
- UnsupportedTransports
- };
- Reason() : type(UnknownType), text("") {}
- Reason(Type type, const std::string& text = "") : type(type), text(text) {}
- Type type;
- std::string text;
- };
-
- enum Action {
- UnknownAction,
- ContentAccept,
- ContentAdd,
- ContentModify,
- ContentReject,
- ContentRemove,
- DescriptionInfo,
- SecurityInfo,
- SessionAccept,
- SessionInfo,
- SessionInitiate,
- SessionTerminate,
- TransportAccept,
- TransportInfo,
- TransportReject,
- TransportReplace
- };
- JinglePayload() : action(SessionTerminate), sessionID("") {
- }
-
- JinglePayload(Action action, const std::string& sessionID) : action(action), sessionID(sessionID) {
-
- }
-
- void setAction(Action action) {
- this->action = action;
- }
-
- Action getAction() const {
- return action;
- }
-
- void setInitiator(const JID& initiator) {
- this->initiator = initiator;
- }
-
- const JID& getInitiator() const {
- return initiator;
- }
-
- void setResponder(const JID& responder) {
- this->responder = responder;
- }
-
- const JID& getResponder() const {
- return responder;
- }
-
- void setSessionID(const std::string& id) {
- sessionID = id;
- }
-
- const std::string& getSessionID() const {
- return sessionID;
- }
-
- void addContent(JingleContentPayload::ref content) {
- this->payloads.push_back(content);
- }
-
- void addPayload(boost::shared_ptr<Payload> payload) {
- this->payloads.push_back(payload);
- }
-
- const std::vector<JingleContentPayload::ref> getContents() const {
- return getPayloads<JingleContentPayload>();
- }
-
- const std::vector<boost::shared_ptr<Payload> > getPayloads() const {
- return payloads;
- }
-
- template<typename T>
- const std::vector<boost::shared_ptr<T> > getPayloads() const {
- std::vector<boost::shared_ptr<T> > matched_payloads;
- for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
- boost::shared_ptr<T> result = boost::dynamic_pointer_cast<T>(*i);
- if (result) {
- matched_payloads.push_back(result);
- }
- }
-
- return matched_payloads;
-
- }
-
- template<typename T>
- const boost::shared_ptr<T> getPayload() const {
- boost::shared_ptr<T> result;
- for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
- result = boost::dynamic_pointer_cast<T>(*i);
- if (result) {
- return result;
- }
- }
-
- return result;
- }
-
- void setReason(const Reason& reason) {
- this->reason = reason;
- }
-
- const boost::optional<Reason>& getReason() const {
- return reason;
- }
-
- private:
- Action action;
- JID initiator;
- JID responder;
- std::string sessionID;
- std::vector<boost::shared_ptr<Payload> > payloads;
- boost::optional<Reason> reason;
- };
+ class SWIFTEN_API JinglePayload : public Payload {
+ public:
+ typedef boost::shared_ptr<JinglePayload> ref;
+ struct Reason : public Payload {
+ enum Type {
+ UnknownType,
+ AlternativeSession,
+ Busy,
+ Cancel,
+ ConnectivityError,
+ Decline,
+ Expired,
+ FailedApplication,
+ FailedTransport,
+ GeneralError,
+ Gone,
+ IncompatibleParameters,
+ MediaError,
+ SecurityError,
+ Success,
+ Timeout,
+ UnsupportedApplications,
+ UnsupportedTransports
+ };
+ Reason() : type(UnknownType), text("") {}
+ Reason(Type type, const std::string& text = "") : type(type), text(text) {}
+ Type type;
+ std::string text;
+ };
+
+ enum Action {
+ UnknownAction,
+ ContentAccept,
+ ContentAdd,
+ ContentModify,
+ ContentReject,
+ ContentRemove,
+ DescriptionInfo,
+ SecurityInfo,
+ SessionAccept,
+ SessionInfo,
+ SessionInitiate,
+ SessionTerminate,
+ TransportAccept,
+ TransportInfo,
+ TransportReject,
+ TransportReplace
+ };
+ JinglePayload() : action(SessionTerminate), sessionID("") {
+ }
+
+ JinglePayload(Action action, const std::string& sessionID) : action(action), sessionID(sessionID) {
+
+ }
+
+ void setAction(Action action) {
+ this->action = action;
+ }
+
+ Action getAction() const {
+ return action;
+ }
+
+ void setInitiator(const JID& initiator) {
+ this->initiator = initiator;
+ }
+
+ const JID& getInitiator() const {
+ return initiator;
+ }
+
+ void setResponder(const JID& responder) {
+ this->responder = responder;
+ }
+
+ const JID& getResponder() const {
+ return responder;
+ }
+
+ void setSessionID(const std::string& id) {
+ sessionID = id;
+ }
+
+ const std::string& getSessionID() const {
+ return sessionID;
+ }
+
+ void addContent(JingleContentPayload::ref content) {
+ this->payloads.push_back(content);
+ }
+
+ void addPayload(boost::shared_ptr<Payload> payload) {
+ this->payloads.push_back(payload);
+ }
+
+ const std::vector<JingleContentPayload::ref> getContents() const {
+ return getPayloads<JingleContentPayload>();
+ }
+
+ const std::vector<boost::shared_ptr<Payload> > getPayloads() const {
+ return payloads;
+ }
+
+ template<typename T>
+ const std::vector<boost::shared_ptr<T> > getPayloads() const {
+ std::vector<boost::shared_ptr<T> > matched_payloads;
+ for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
+ boost::shared_ptr<T> result = boost::dynamic_pointer_cast<T>(*i);
+ if (result) {
+ matched_payloads.push_back(result);
+ }
+ }
+
+ return matched_payloads;
+
+ }
+
+ template<typename T>
+ const boost::shared_ptr<T> getPayload() const {
+ boost::shared_ptr<T> result;
+ for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
+ result = boost::dynamic_pointer_cast<T>(*i);
+ if (result) {
+ return result;
+ }
+ }
+
+ return result;
+ }
+
+ void setReason(const Reason& reason) {
+ this->reason = reason;
+ }
+
+ const boost::optional<Reason>& getReason() const {
+ return reason;
+ }
+
+ private:
+ Action action;
+ JID initiator;
+ JID responder;
+ std::string sessionID;
+ std::vector<boost::shared_ptr<Payload> > payloads;
+ boost::optional<Reason> reason;
+ };
}
diff --git a/Swiften/Elements/JingleS5BTransportPayload.h b/Swiften/Elements/JingleS5BTransportPayload.h
index 4b0e7d4..bb542f0 100644
--- a/Swiften/Elements/JingleS5BTransportPayload.h
+++ b/Swiften/Elements/JingleS5BTransportPayload.h
@@ -16,106 +16,106 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API JingleS5BTransportPayload : public JingleTransportPayload {
- public:
- enum Mode {
- TCPMode, // default case
- UDPMode
- };
-
- struct Candidate {
- enum Type {
- DirectType, // default case
- AssistedType,
- TunnelType,
- ProxyType
- };
-
- Candidate() : priority(0), type(DirectType) {}
-
- std::string cid;
- JID jid;
- HostAddressPort hostPort;
- int priority;
- Type type;
- };
-
- struct CompareCandidate {
- bool operator() (const JingleS5BTransportPayload::Candidate& c1, const JingleS5BTransportPayload::Candidate& c2) const {
- if (c1.priority < c2.priority) return true;
- return false;
- }
- };
-
- public:
- JingleS5BTransportPayload() : mode(TCPMode), candidateError(false), proxyError(false) {}
-
- Mode getMode() const {
- return mode;
- }
-
- void setMode(Mode mode) {
- this->mode = mode;
- }
-
- const std::vector<Candidate>& getCandidates() const {
- return candidates;
- }
-
- void addCandidate(const Candidate& candidate) {
- candidates.push_back(candidate);
- }
-
- void setCandidateUsed(const std::string& cid) {
- candidateUsedCID = cid;
- }
-
- const std::string& getCandidateUsed() const {
- return candidateUsedCID;
- }
-
- void setActivated(const std::string& cid) {
- activatedCID = cid;
- }
-
- const std::string& getActivated() const {
- return activatedCID;
- }
-
- void setDstAddr(const std::string& addr) {
- dstAddr = addr;
- }
-
- const std::string& getDstAddr() const {
- return dstAddr;
- }
-
- void setCandidateError(bool hasError) {
- candidateError = hasError;
- }
-
- bool hasCandidateError() const {
- return candidateError;
- }
-
- void setProxyError(bool hasError) {
- proxyError = hasError;
- }
-
- bool hasProxyError() const {
- return proxyError;
- }
- public:
- typedef boost::shared_ptr<JingleS5BTransportPayload> ref;
-
- private:
- Mode mode;
- std::vector<Candidate> candidates;
-
- std::string candidateUsedCID;
- std::string activatedCID;
- std::string dstAddr;
- bool candidateError;
- bool proxyError;
- };
+ class SWIFTEN_API JingleS5BTransportPayload : public JingleTransportPayload {
+ public:
+ enum Mode {
+ TCPMode, // default case
+ UDPMode
+ };
+
+ struct Candidate {
+ enum Type {
+ DirectType, // default case
+ AssistedType,
+ TunnelType,
+ ProxyType
+ };
+
+ Candidate() : priority(0), type(DirectType) {}
+
+ std::string cid;
+ JID jid;
+ HostAddressPort hostPort;
+ int priority;
+ Type type;
+ };
+
+ struct CompareCandidate {
+ bool operator() (const JingleS5BTransportPayload::Candidate& c1, const JingleS5BTransportPayload::Candidate& c2) const {
+ if (c1.priority < c2.priority) return true;
+ return false;
+ }
+ };
+
+ public:
+ JingleS5BTransportPayload() : mode(TCPMode), candidateError(false), proxyError(false) {}
+
+ Mode getMode() const {
+ return mode;
+ }
+
+ void setMode(Mode mode) {
+ this->mode = mode;
+ }
+
+ const std::vector<Candidate>& getCandidates() const {
+ return candidates;
+ }
+
+ void addCandidate(const Candidate& candidate) {
+ candidates.push_back(candidate);
+ }
+
+ void setCandidateUsed(const std::string& cid) {
+ candidateUsedCID = cid;
+ }
+
+ const std::string& getCandidateUsed() const {
+ return candidateUsedCID;
+ }
+
+ void setActivated(const std::string& cid) {
+ activatedCID = cid;
+ }
+
+ const std::string& getActivated() const {
+ return activatedCID;
+ }
+
+ void setDstAddr(const std::string& addr) {
+ dstAddr = addr;
+ }
+
+ const std::string& getDstAddr() const {
+ return dstAddr;
+ }
+
+ void setCandidateError(bool hasError) {
+ candidateError = hasError;
+ }
+
+ bool hasCandidateError() const {
+ return candidateError;
+ }
+
+ void setProxyError(bool hasError) {
+ proxyError = hasError;
+ }
+
+ bool hasProxyError() const {
+ return proxyError;
+ }
+ public:
+ typedef boost::shared_ptr<JingleS5BTransportPayload> ref;
+
+ private:
+ Mode mode;
+ std::vector<Candidate> candidates;
+
+ std::string candidateUsedCID;
+ std::string activatedCID;
+ std::string dstAddr;
+ bool candidateError;
+ bool proxyError;
+ };
}
diff --git a/Swiften/Elements/JingleTransportPayload.h b/Swiften/Elements/JingleTransportPayload.h
index 70f3d25..12a08cd 100644
--- a/Swiften/Elements/JingleTransportPayload.h
+++ b/Swiften/Elements/JingleTransportPayload.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API JingleTransportPayload : public Payload {
- public:
- void setSessionID(const std::string& id) {
- sessionID = id;
- }
+ class SWIFTEN_API JingleTransportPayload : public Payload {
+ public:
+ void setSessionID(const std::string& id) {
+ sessionID = id;
+ }
- const std::string& getSessionID() const {
- return sessionID;
- }
+ const std::string& getSessionID() const {
+ return sessionID;
+ }
- public:
- typedef boost::shared_ptr<JingleTransportPayload> ref;
+ public:
+ typedef boost::shared_ptr<JingleTransportPayload> ref;
- private:
- std::string sessionID;
- };
+ private:
+ std::string sessionID;
+ };
}
diff --git a/Swiften/Elements/Last.h b/Swiften/Elements/Last.h
index 68cf7a7..869dab4 100644
--- a/Swiften/Elements/Last.h
+++ b/Swiften/Elements/Last.h
@@ -10,14 +10,14 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Last : public Payload {
- public:
- Last(int seconds = 0) : seconds_(seconds) {}
+ class SWIFTEN_API Last : public Payload {
+ public:
+ Last(int seconds = 0) : seconds_(seconds) {}
- int getSeconds() const {return seconds_;}
- void setSeconds(int seconds) {seconds_ = seconds;}
+ int getSeconds() const {return seconds_;}
+ void setSeconds(int seconds) {seconds_ = seconds;}
- private:
- int seconds_;
- };
+ private:
+ int seconds_;
+ };
}
diff --git a/Swiften/Elements/MAMFin.h b/Swiften/Elements/MAMFin.h
index 96e410e..dd1f7bf 100644
--- a/Swiften/Elements/MAMFin.h
+++ b/Swiften/Elements/MAMFin.h
@@ -16,48 +16,48 @@
#include <Swiften/Elements/ResultSet.h>
namespace Swift {
- class SWIFTEN_API MAMFin : public Payload {
- public:
- MAMFin() : isComplete_(false), isStable_(true) {}
- virtual ~MAMFin();
-
- void setComplete(const bool isComplete) {
- isComplete_ = isComplete;
- }
-
- bool isComplete() const {
- return isComplete_;
- }
-
- void setStable(const bool isStable) {
- isStable_ = isStable;
- }
-
- bool isStable() const {
- return isStable_;
- }
-
- void setResultSet(boost::shared_ptr<ResultSet> resultSet) {
- resultSet_ = resultSet;
- }
-
- boost::shared_ptr<ResultSet> getResultSet() const {
- return resultSet_;
- }
-
- void setQueryID(const std::string& queryID) {
- queryID_ = queryID;
- }
-
- const boost::optional<std::string>& getQueryID() const {
- return queryID_;
- }
-
-
- private:
- bool isComplete_;
- bool isStable_;
- boost::shared_ptr<ResultSet> resultSet_;
- boost::optional<std::string> queryID_;
- };
+ class SWIFTEN_API MAMFin : public Payload {
+ public:
+ MAMFin() : isComplete_(false), isStable_(true) {}
+ virtual ~MAMFin();
+
+ void setComplete(const bool isComplete) {
+ isComplete_ = isComplete;
+ }
+
+ bool isComplete() const {
+ return isComplete_;
+ }
+
+ void setStable(const bool isStable) {
+ isStable_ = isStable;
+ }
+
+ bool isStable() const {
+ return isStable_;
+ }
+
+ void setResultSet(boost::shared_ptr<ResultSet> resultSet) {
+ resultSet_ = resultSet;
+ }
+
+ boost::shared_ptr<ResultSet> getResultSet() const {
+ return resultSet_;
+ }
+
+ void setQueryID(const std::string& queryID) {
+ queryID_ = queryID;
+ }
+
+ const boost::optional<std::string>& getQueryID() const {
+ return queryID_;
+ }
+
+
+ private:
+ bool isComplete_;
+ bool isStable_;
+ boost::shared_ptr<ResultSet> resultSet_;
+ boost::optional<std::string> queryID_;
+ };
}
diff --git a/Swiften/Elements/MAMQuery.h b/Swiften/Elements/MAMQuery.h
index 2a795dc..253fa0c 100644
--- a/Swiften/Elements/MAMQuery.h
+++ b/Swiften/Elements/MAMQuery.h
@@ -17,26 +17,26 @@
#include <Swiften/Elements/ResultSet.h>
namespace Swift {
- class SWIFTEN_API MAMQuery : public Payload {
- public:
- virtual ~MAMQuery();
+ class SWIFTEN_API MAMQuery : public Payload {
+ public:
+ virtual ~MAMQuery();
- void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; }
- const boost::optional<std::string>& getQueryID() const { return queryID_; }
+ void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; }
+ const boost::optional<std::string>& getQueryID() const { return queryID_; }
- void setNode(const boost::optional<std::string>& node) { node_ = node; }
- const boost::optional<std::string>& getNode() const { return node_; }
+ void setNode(const boost::optional<std::string>& node) { node_ = node; }
+ const boost::optional<std::string>& getNode() const { return node_; }
- void setForm(boost::shared_ptr<Form> form) { form_ = form; }
- const boost::shared_ptr<Form>& getForm() const { return form_; }
+ void setForm(boost::shared_ptr<Form> form) { form_ = form; }
+ const boost::shared_ptr<Form>& getForm() const { return form_; }
- void setResultSet(boost::shared_ptr<ResultSet> resultSet) { resultSet_ = resultSet; }
- const boost::shared_ptr<ResultSet>& getResultSet() const { return resultSet_; }
+ void setResultSet(boost::shared_ptr<ResultSet> resultSet) { resultSet_ = resultSet; }
+ const boost::shared_ptr<ResultSet>& getResultSet() const { return resultSet_; }
- private:
- boost::optional<std::string> queryID_;
- boost::optional<std::string> node_;
- boost::shared_ptr<Form> form_;
- boost::shared_ptr<ResultSet> resultSet_;
- };
+ private:
+ boost::optional<std::string> queryID_;
+ boost::optional<std::string> node_;
+ boost::shared_ptr<Form> form_;
+ boost::shared_ptr<ResultSet> resultSet_;
+ };
}
diff --git a/Swiften/Elements/MAMResult.h b/Swiften/Elements/MAMResult.h
index de69fba..88ec8f0 100644
--- a/Swiften/Elements/MAMResult.h
+++ b/Swiften/Elements/MAMResult.h
@@ -15,18 +15,18 @@
#include <Swiften/Elements/Forwarded.h>
namespace Swift {
- class SWIFTEN_API MAMResult : public ContainerPayload<Forwarded> {
- public:
- virtual ~MAMResult();
+ class SWIFTEN_API MAMResult : public ContainerPayload<Forwarded> {
+ public:
+ virtual ~MAMResult();
- void setID(const std::string& id) { id_ = id; }
- const std::string& getID() const { return id_; }
+ void setID(const std::string& id) { id_ = id; }
+ const std::string& getID() const { return id_; }
- void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; }
- const boost::optional<std::string>& getQueryID() const { return queryID_; }
+ void setQueryID(const boost::optional<std::string>& queryID) { queryID_ = queryID; }
+ const boost::optional<std::string>& getQueryID() const { return queryID_; }
- private:
- std::string id_;
- boost::optional<std::string> queryID_;
- };
+ private:
+ std::string id_;
+ boost::optional<std::string> queryID_;
+ };
}
diff --git a/Swiften/Elements/MUCAdminPayload.h b/Swiften/Elements/MUCAdminPayload.h
index f16111d..c9b01d9 100644
--- a/Swiften/Elements/MUCAdminPayload.h
+++ b/Swiften/Elements/MUCAdminPayload.h
@@ -19,19 +19,19 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCAdminPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCAdminPayload> ref;
+ class SWIFTEN_API MUCAdminPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCAdminPayload> ref;
- MUCAdminPayload() {
- }
+ MUCAdminPayload() {
+ }
- void addItem(const MUCItem& item) {items_.push_back(item);}
+ void addItem(const MUCItem& item) {items_.push_back(item);}
- const std::vector<MUCItem>& getItems() const {return items_;}
+ const std::vector<MUCItem>& getItems() const {return items_;}
- private:
- std::vector<MUCItem> items_;
- };
+ private:
+ std::vector<MUCItem> items_;
+ };
}
diff --git a/Swiften/Elements/MUCDestroyPayload.h b/Swiften/Elements/MUCDestroyPayload.h
index b68f97c..80eb83e 100644
--- a/Swiften/Elements/MUCDestroyPayload.h
+++ b/Swiften/Elements/MUCDestroyPayload.h
@@ -13,31 +13,31 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCDestroyPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCDestroyPayload> ref;
+ class SWIFTEN_API MUCDestroyPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCDestroyPayload> ref;
- MUCDestroyPayload() {
- }
+ MUCDestroyPayload() {
+ }
- void setNewVenue(const JID& jid) {
- newVenue_ = jid;
- }
+ void setNewVenue(const JID& jid) {
+ newVenue_ = jid;
+ }
- const JID& getNewVenue() const {
- return newVenue_;
- }
+ const JID& getNewVenue() const {
+ return newVenue_;
+ }
- void setReason(const std::string& reason) {
- reason_ = reason;
- }
+ void setReason(const std::string& reason) {
+ reason_ = reason;
+ }
- const std::string& getReason() const {
- return reason_;
- }
+ const std::string& getReason() const {
+ return reason_;
+ }
- private:
- JID newVenue_;
- std::string reason_;
- };
+ private:
+ JID newVenue_;
+ std::string reason_;
+ };
}
diff --git a/Swiften/Elements/MUCInvitationPayload.h b/Swiften/Elements/MUCInvitationPayload.h
index fd92a83..508a8ec 100644
--- a/Swiften/Elements/MUCInvitationPayload.h
+++ b/Swiften/Elements/MUCInvitationPayload.h
@@ -13,66 +13,66 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCInvitationPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCInvitationPayload> ref;
- MUCInvitationPayload() : continuation_(false), impromptu_(false) {
- }
-
- void setIsContinuation(bool b) {
- continuation_ = b;
- }
-
- bool getIsContinuation() const {
- return continuation_;
- }
-
- void setIsImpromptu(bool b) {
- impromptu_ = b;
- }
-
- bool getIsImpromptu() const {
- return impromptu_;
- }
-
- void setJID(const JID& jid) {
- jid_ = jid;
- }
-
- const JID& getJID() const {
- return jid_;
- }
-
- void setPassword(const std::string& password) {
- password_ = password;
- }
-
- const std::string& getPassword() const {
- return password_;
- }
-
- void setReason(const std::string& text) {
- reason_ = text;
- }
-
- const std::string& getReason() const {
- return reason_;
- }
-
- void setThread(const std::string& thread) {
- thread_ = thread;
- }
-
- const std::string& getThread() const {
- return thread_;
- }
-
- private:
- bool continuation_;
- bool impromptu_;
- JID jid_;
- std::string password_;
- std::string reason_;
- std::string thread_;
- };
+ class SWIFTEN_API MUCInvitationPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCInvitationPayload> ref;
+ MUCInvitationPayload() : continuation_(false), impromptu_(false) {
+ }
+
+ void setIsContinuation(bool b) {
+ continuation_ = b;
+ }
+
+ bool getIsContinuation() const {
+ return continuation_;
+ }
+
+ void setIsImpromptu(bool b) {
+ impromptu_ = b;
+ }
+
+ bool getIsImpromptu() const {
+ return impromptu_;
+ }
+
+ void setJID(const JID& jid) {
+ jid_ = jid;
+ }
+
+ const JID& getJID() const {
+ return jid_;
+ }
+
+ void setPassword(const std::string& password) {
+ password_ = password;
+ }
+
+ const std::string& getPassword() const {
+ return password_;
+ }
+
+ void setReason(const std::string& text) {
+ reason_ = text;
+ }
+
+ const std::string& getReason() const {
+ return reason_;
+ }
+
+ void setThread(const std::string& thread) {
+ thread_ = thread;
+ }
+
+ const std::string& getThread() const {
+ return thread_;
+ }
+
+ private:
+ bool continuation_;
+ bool impromptu_;
+ JID jid_;
+ std::string password_;
+ std::string reason_;
+ std::string thread_;
+ };
}
diff --git a/Swiften/Elements/MUCItem.h b/Swiften/Elements/MUCItem.h
index 40f4572..9ea6d77 100644
--- a/Swiften/Elements/MUCItem.h
+++ b/Swiften/Elements/MUCItem.h
@@ -10,12 +10,12 @@
#include <Swiften/JID/JID.h>
namespace Swift {
struct MUCItem {
- MUCItem() {}
- boost::optional<JID> realJID;
- boost::optional<std::string> nick;
- boost::optional<MUCOccupant::Affiliation> affiliation;
- boost::optional<MUCOccupant::Role> role;
- boost::optional<JID> actor;
- boost::optional<std::string> reason;
+ MUCItem() {}
+ boost::optional<JID> realJID;
+ boost::optional<std::string> nick;
+ boost::optional<MUCOccupant::Affiliation> affiliation;
+ boost::optional<MUCOccupant::Role> role;
+ boost::optional<JID> actor;
+ boost::optional<std::string> reason;
};
}
diff --git a/Swiften/Elements/MUCOccupant.cpp b/Swiften/Elements/MUCOccupant.cpp
index c2d2f3d..edd6eb6 100644
--- a/Swiften/Elements/MUCOccupant.cpp
+++ b/Swiften/Elements/MUCOccupant.cpp
@@ -19,28 +19,28 @@ MUCOccupant::MUCOccupant(const MUCOccupant& other) : nick_(other.getNick()), rol
}
std::string MUCOccupant::getNick() const {
- return nick_;
+ return nick_;
}
MUCOccupant::Role MUCOccupant::getRole() const {
- return role_;
+ return role_;
}
MUCOccupant::Affiliation MUCOccupant::getAffiliation() const {
- return affiliation_;
+ return affiliation_;
}
void MUCOccupant::setRealJID(const JID& realJID) {
- realJID_ = realJID;
+ realJID_ = realJID;
}
void MUCOccupant::setNick(const std::string& nick) {
- nick_ = nick;
+ nick_ = nick;
}
boost::optional<JID> MUCOccupant::getRealJID() const {
- return realJID_;
+ return realJID_;
}
}
diff --git a/Swiften/Elements/MUCOccupant.h b/Swiften/Elements/MUCOccupant.h
index 0eb9169..eb7df2c 100644
--- a/Swiften/Elements/MUCOccupant.h
+++ b/Swiften/Elements/MUCOccupant.h
@@ -14,30 +14,30 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class Client;
-
- class SWIFTEN_API MUCOccupant {
- public:
- enum Role {Moderator, Participant, Visitor, NoRole};
- enum Affiliation {Owner, Admin, Member, Outcast, NoAffiliation};
-
- MUCOccupant(const std::string &nick, Role role, Affiliation affiliation);
- MUCOccupant(const MUCOccupant& other);
- ~MUCOccupant();
-
- std::string getNick() const;
- Role getRole() const;
- Affiliation getAffiliation() const;
- boost::optional<JID> getRealJID() const;
- void setRealJID(const JID& jid);
- void setNick(const std::string& nick);
-
- private:
- std::string nick_;
- Role role_;
- Affiliation affiliation_;
- boost::optional<JID> realJID_;
- /* If you add a field, remember to update the const copy constructor */
- };
+ class Client;
+
+ class SWIFTEN_API MUCOccupant {
+ public:
+ enum Role {Moderator, Participant, Visitor, NoRole};
+ enum Affiliation {Owner, Admin, Member, Outcast, NoAffiliation};
+
+ MUCOccupant(const std::string &nick, Role role, Affiliation affiliation);
+ MUCOccupant(const MUCOccupant& other);
+ ~MUCOccupant();
+
+ std::string getNick() const;
+ Role getRole() const;
+ Affiliation getAffiliation() const;
+ boost::optional<JID> getRealJID() const;
+ void setRealJID(const JID& jid);
+ void setNick(const std::string& nick);
+
+ private:
+ std::string nick_;
+ Role role_;
+ Affiliation affiliation_;
+ boost::optional<JID> realJID_;
+ /* If you add a field, remember to update the const copy constructor */
+ };
}
diff --git a/Swiften/Elements/MUCOwnerPayload.h b/Swiften/Elements/MUCOwnerPayload.h
index 890b031..f75f677 100644
--- a/Swiften/Elements/MUCOwnerPayload.h
+++ b/Swiften/Elements/MUCOwnerPayload.h
@@ -13,26 +13,26 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API MUCOwnerPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCOwnerPayload> ref;
+ class SWIFTEN_API MUCOwnerPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCOwnerPayload> ref;
- MUCOwnerPayload() {
- }
+ MUCOwnerPayload() {
+ }
- boost::shared_ptr<Payload> getPayload() const {
- return payload;
- }
+ boost::shared_ptr<Payload> getPayload() const {
+ return payload;
+ }
- void setPayload(boost::shared_ptr<Payload> p) {
- payload = p;
- }
+ void setPayload(boost::shared_ptr<Payload> p) {
+ payload = p;
+ }
- Form::ref getForm() {
- return boost::dynamic_pointer_cast<Form>(payload);
- }
+ Form::ref getForm() {
+ return boost::dynamic_pointer_cast<Form>(payload);
+ }
- private:
- boost::shared_ptr<Payload> payload;
- };
+ private:
+ boost::shared_ptr<Payload> payload;
+ };
}
diff --git a/Swiften/Elements/MUCPayload.h b/Swiften/Elements/MUCPayload.h
index af70f48..8588ca2 100644
--- a/Swiften/Elements/MUCPayload.h
+++ b/Swiften/Elements/MUCPayload.h
@@ -16,61 +16,61 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCPayload> ref;
-
- MUCPayload() {
- maxChars_ = -1;
- maxStanzas_ = -1;
- seconds_ = -1;
- }
-
- void setMaxChars(int maxChars) {
- maxChars_ = maxChars;
- }
-
- void setMaxStanzas(int maxStanzas) {
- maxStanzas_ = maxStanzas;
- }
-
- void setSeconds(int seconds) {
- seconds_ = seconds;
- }
-
- void setSince(boost::posix_time::ptime since) {
- since_ = since;
- }
-
- void setPassword(const std::string& password) {
- password_ = password;
- }
-
- int getMaxChars() const{
- return maxChars_;
- }
-
- int getMaxStanzas() const{
- return maxStanzas_;
- }
-
- int getSeconds() const {
- return seconds_;
- }
-
- const boost::optional<std::string>& getPassword() const {
- return password_;
- }
-
- const boost::posix_time::ptime& getSince() const {
- return since_;
- }
-
- private:
- int maxChars_;
- int maxStanzas_;
- int seconds_;
- boost::posix_time::ptime since_;
- boost::optional<std::string> password_;
- };
+ class SWIFTEN_API MUCPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCPayload> ref;
+
+ MUCPayload() {
+ maxChars_ = -1;
+ maxStanzas_ = -1;
+ seconds_ = -1;
+ }
+
+ void setMaxChars(int maxChars) {
+ maxChars_ = maxChars;
+ }
+
+ void setMaxStanzas(int maxStanzas) {
+ maxStanzas_ = maxStanzas;
+ }
+
+ void setSeconds(int seconds) {
+ seconds_ = seconds;
+ }
+
+ void setSince(boost::posix_time::ptime since) {
+ since_ = since;
+ }
+
+ void setPassword(const std::string& password) {
+ password_ = password;
+ }
+
+ int getMaxChars() const{
+ return maxChars_;
+ }
+
+ int getMaxStanzas() const{
+ return maxStanzas_;
+ }
+
+ int getSeconds() const {
+ return seconds_;
+ }
+
+ const boost::optional<std::string>& getPassword() const {
+ return password_;
+ }
+
+ const boost::posix_time::ptime& getSince() const {
+ return since_;
+ }
+
+ private:
+ int maxChars_;
+ int maxStanzas_;
+ int seconds_;
+ boost::posix_time::ptime since_;
+ boost::optional<std::string> password_;
+ };
}
diff --git a/Swiften/Elements/MUCUserPayload.h b/Swiften/Elements/MUCUserPayload.h
index 6d2de30..e83c2d0 100644
--- a/Swiften/Elements/MUCUserPayload.h
+++ b/Swiften/Elements/MUCUserPayload.h
@@ -19,79 +19,79 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCUserPayload : public Payload {
- public:
- typedef boost::shared_ptr<MUCUserPayload> ref;
+ class SWIFTEN_API MUCUserPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<MUCUserPayload> ref;
- struct StatusCode {
- StatusCode() : code(0) {}
- StatusCode(int code) : code(code) {}
- int code;
- };
+ struct StatusCode {
+ StatusCode() : code(0) {}
+ StatusCode(int code) : code(code) {}
+ int code;
+ };
- //struct Password {
+ //struct Password {
- //}
+ //}
- // struct History {
+ // struct History {
- // }
+ // }
- /**
- * reason is optional.
- * from and to are mutually exclusive.
- * From is used for MUC sending to invited client. To is used sending to MUC from inviting client.
- * from is the JID the MUC claims the invite is from.
- * to is the JID to send the invite to.
- */
- struct Invite {
- std::string reason;
- JID from;
- JID to;
- };
+ /**
+ * reason is optional.
+ * from and to are mutually exclusive.
+ * From is used for MUC sending to invited client. To is used sending to MUC from inviting client.
+ * from is the JID the MUC claims the invite is from.
+ * to is the JID to send the invite to.
+ */
+ struct Invite {
+ std::string reason;
+ JID from;
+ JID to;
+ };
- MUCUserPayload() {
- }
+ MUCUserPayload() {
+ }
- void addItem(const MUCItem& item) {items_.push_back(item);}
-
- void addStatusCode(StatusCode code) {statusCodes_.push_back(code);}
+ void addItem(const MUCItem& item) {items_.push_back(item);}
- const std::vector<MUCItem>& getItems() const {return items_;}
+ void addStatusCode(StatusCode code) {statusCodes_.push_back(code);}
- const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;}
+ const std::vector<MUCItem>& getItems() const {return items_;}
- boost::shared_ptr<Payload> getPayload() const {
- return payload_;
- }
+ const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;}
- void setPayload(boost::shared_ptr<Payload> p) {
- payload_ = p;
- }
+ boost::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
- const boost::optional<std::string>& getPassword() const {
- return password_;
- }
+ void setPayload(boost::shared_ptr<Payload> p) {
+ payload_ = p;
+ }
- void setPassword(const std::string& password) {
- password_ = password;
- }
+ const boost::optional<std::string>& getPassword() const {
+ return password_;
+ }
+ void setPassword(const std::string& password) {
+ password_ = password;
+ }
- const boost::optional<Invite>& getInvite() const {
- return invite_;
- }
- void setInvite(const Invite& invite) {
- invite_ = invite;
- }
+ const boost::optional<Invite>& getInvite() const {
+ return invite_;
+ }
+ void setInvite(const Invite& invite) {
+ invite_ = invite;
+ }
- private:
- std::vector<MUCItem> items_;
- std::vector<StatusCode> statusCodes_;
- boost::shared_ptr<Payload> payload_;
- boost::optional<std::string> password_;
- boost::optional<Invite> invite_;
- };
+
+ private:
+ std::vector<MUCItem> items_;
+ std::vector<StatusCode> statusCodes_;
+ boost::shared_ptr<Payload> payload_;
+ boost::optional<std::string> password_;
+ boost::optional<Invite> invite_;
+ };
}
diff --git a/Swiften/Elements/Message.h b/Swiften/Elements/Message.h
index 0f0d380..c55e04b 100644
--- a/Swiften/Elements/Message.h
+++ b/Swiften/Elements/Message.h
@@ -20,63 +20,63 @@
#include <Swiften/Elements/Subject.h>
namespace Swift {
- class SWIFTEN_API Message : public Stanza {
- public:
- typedef boost::shared_ptr<Message> ref;
-
- enum Type { Normal, Chat, Error, Groupchat, Headline };
-
- Message() : type_(Chat) { }
-
- std::string getSubject() const {
- boost::shared_ptr<Subject> subject(getPayload<Subject>());
- if (subject) {
- return subject->getText();
- }
- return "";
- }
-
- void setSubject(const std::string& subject) {
- updatePayload(boost::make_shared<Subject>(subject));
- }
-
- // Explicitly convert to bool. In C++11, it would be cleaner to
- // compare to nullptr.
- bool hasSubject() {
- return static_cast<bool>(getPayload<Subject>());
- }
-
- boost::optional<std::string> getBody() const {
- boost::shared_ptr<Body> body(getPayload<Body>());
- boost::optional<std::string> bodyData;
- if (body) {
- bodyData = body->getText();
- }
- return bodyData;
- }
-
- void setBody(const std::string& body) {
- setBody(boost::optional<std::string>(body));
- }
-
- void setBody(const boost::optional<std::string>& body) {
- if (body) {
- updatePayload(boost::make_shared<Body>(body.get()));
- }
- else {
- removePayloadOfSameType(boost::make_shared<Body>());
- }
- }
-
- bool isError() {
- boost::shared_ptr<Swift::ErrorPayload> error(getPayload<Swift::ErrorPayload>());
- return getType() == Message::Error || error;
- }
-
- Type getType() const { return type_; }
- void setType(Type type) { type_ = type; }
-
- private:
- Type type_;
- };
+ class SWIFTEN_API Message : public Stanza {
+ public:
+ typedef boost::shared_ptr<Message> ref;
+
+ enum Type { Normal, Chat, Error, Groupchat, Headline };
+
+ Message() : type_(Chat) { }
+
+ std::string getSubject() const {
+ boost::shared_ptr<Subject> subject(getPayload<Subject>());
+ if (subject) {
+ return subject->getText();
+ }
+ return "";
+ }
+
+ void setSubject(const std::string& subject) {
+ updatePayload(boost::make_shared<Subject>(subject));
+ }
+
+ // Explicitly convert to bool. In C++11, it would be cleaner to
+ // compare to nullptr.
+ bool hasSubject() {
+ return static_cast<bool>(getPayload<Subject>());
+ }
+
+ boost::optional<std::string> getBody() const {
+ boost::shared_ptr<Body> body(getPayload<Body>());
+ boost::optional<std::string> bodyData;
+ if (body) {
+ bodyData = body->getText();
+ }
+ return bodyData;
+ }
+
+ void setBody(const std::string& body) {
+ setBody(boost::optional<std::string>(body));
+ }
+
+ void setBody(const boost::optional<std::string>& body) {
+ if (body) {
+ updatePayload(boost::make_shared<Body>(body.get()));
+ }
+ else {
+ removePayloadOfSameType(boost::make_shared<Body>());
+ }
+ }
+
+ bool isError() {
+ boost::shared_ptr<Swift::ErrorPayload> error(getPayload<Swift::ErrorPayload>());
+ return getType() == Message::Error || error;
+ }
+
+ Type getType() const { return type_; }
+ void setType(Type type) { type_ = type; }
+
+ private:
+ Type type_;
+ };
}
diff --git a/Swiften/Elements/Nickname.h b/Swiften/Elements/Nickname.h
index 7a9e7b5..123c156 100644
--- a/Swiften/Elements/Nickname.h
+++ b/Swiften/Elements/Nickname.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Nickname : public Payload {
- public:
- Nickname(const std::string& nickname = "") : nickname(nickname) {
- }
+ class SWIFTEN_API Nickname : public Payload {
+ public:
+ Nickname(const std::string& nickname = "") : nickname(nickname) {
+ }
- void setNickname(const std::string& nickname) {
- this->nickname = nickname;
- }
+ void setNickname(const std::string& nickname) {
+ this->nickname = nickname;
+ }
- const std::string& getNickname() const {
- return nickname;
- }
+ const std::string& getNickname() const {
+ return nickname;
+ }
- private:
- std::string nickname;
- };
+ private:
+ std::string nickname;
+ };
}
diff --git a/Swiften/Elements/Payload.h b/Swiften/Elements/Payload.h
index dfa74b2..e31afa9 100644
--- a/Swiften/Elements/Payload.h
+++ b/Swiften/Elements/Payload.h
@@ -12,14 +12,14 @@
#include <Swiften/Elements/Element.h>
namespace Swift {
- class SWIFTEN_API Payload : public Element {
- public:
- typedef boost::shared_ptr<Payload> ref;
- public:
- Payload() {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Payload)
- virtual ~Payload();
+ class SWIFTEN_API Payload : public Element {
+ public:
+ typedef boost::shared_ptr<Payload> ref;
+ public:
+ Payload() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Payload)
+ virtual ~Payload();
- SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Payload)
- };
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Payload)
+ };
}
diff --git a/Swiften/Elements/Presence.cpp b/Swiften/Elements/Presence.cpp
index cf1f0d8..344efc1 100644
--- a/Swiften/Elements/Presence.cpp
+++ b/Swiften/Elements/Presence.cpp
@@ -15,31 +15,31 @@ Presence::Presence() : type_(Available) /*, showType_(Online)*/ {
}
Presence::Presence(const std::string& status) : type_(Available) {
- setStatus(status);
+ setStatus(status);
}
Presence::~Presence() {
}
int Presence::getPriority() const {
- boost::shared_ptr<Priority> priority(getPayload<Priority>());
- return (priority ? priority->getPriority() : 0);
+ boost::shared_ptr<Priority> priority(getPayload<Priority>());
+ return (priority ? priority->getPriority() : 0);
}
void Presence::setPriority(int priority) {
- updatePayload(boost::make_shared<Priority>(priority));
+ updatePayload(boost::make_shared<Priority>(priority));
}
-std::string Presence::getStatus() const {
- boost::shared_ptr<Status> status(getPayload<Status>());
- if (status) {
- return status->getText();
- }
- return "";
+std::string Presence::getStatus() const {
+ boost::shared_ptr<Status> status(getPayload<Status>());
+ if (status) {
+ return status->getText();
+ }
+ return "";
}
-void Presence::setStatus(const std::string& status) {
- updatePayload(boost::make_shared<Status>(status));
+void Presence::setStatus(const std::string& status) {
+ updatePayload(boost::make_shared<Status>(status));
}
}
diff --git a/Swiften/Elements/Presence.h b/Swiften/Elements/Presence.h
index 6327761..0b6ee5f 100644
--- a/Swiften/Elements/Presence.h
+++ b/Swiften/Elements/Presence.h
@@ -13,59 +13,59 @@
#include <Swiften/Elements/StatusShow.h>
namespace Swift {
- class SWIFTEN_API Presence : public Stanza {
- public:
- typedef boost::shared_ptr<Presence> ref;
+ class SWIFTEN_API Presence : public Stanza {
+ public:
+ typedef boost::shared_ptr<Presence> ref;
- enum Type { Available, Error, Probe, Subscribe, Subscribed, Unavailable, Unsubscribe, Unsubscribed };
+ enum Type { Available, Error, Probe, Subscribe, Subscribed, Unavailable, Unsubscribe, Unsubscribed };
- Presence();
- Presence(const std::string& status);
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Presence)
- virtual ~Presence();
+ Presence();
+ Presence(const std::string& status);
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Presence)
+ virtual ~Presence();
- static ref create() {
- return boost::make_shared<Presence>();
- }
+ static ref create() {
+ return boost::make_shared<Presence>();
+ }
- static ref create(const std::string& status) {
- return boost::make_shared<Presence>(status);
- }
+ static ref create(const std::string& status) {
+ return boost::make_shared<Presence>(status);
+ }
- static ref create(Presence::ref presence) {
- return boost::make_shared<Presence>(*presence);
- }
+ static ref create(Presence::ref presence) {
+ return boost::make_shared<Presence>(*presence);
+ }
- Type getType() const { return type_; }
- void setType(Type type) { type_ = type; }
+ Type getType() const { return type_; }
+ void setType(Type type) { type_ = type; }
- StatusShow::Type getShow() const {
- boost::shared_ptr<StatusShow> show(getPayload<StatusShow>());
- if (show) {
- return show->getType();
- }
- return type_ == Available ? StatusShow::Online : StatusShow::None;
- }
+ StatusShow::Type getShow() const {
+ boost::shared_ptr<StatusShow> show(getPayload<StatusShow>());
+ if (show) {
+ return show->getType();
+ }
+ return type_ == Available ? StatusShow::Online : StatusShow::None;
+ }
- void setShow(const StatusShow::Type &show) {
- updatePayload(boost::make_shared<StatusShow>(show));
- }
+ void setShow(const StatusShow::Type &show) {
+ updatePayload(boost::make_shared<StatusShow>(show));
+ }
- std::string getStatus() const;
- void setStatus(const std::string& status);
+ std::string getStatus() const;
+ void setStatus(const std::string& status);
- int getPriority() const;
- void setPriority(int priority);
+ int getPriority() const;
+ void setPriority(int priority);
- boost::shared_ptr<Presence> clone() const {
- return boost::make_shared<Presence>(*this);
- }
+ boost::shared_ptr<Presence> clone() const {
+ return boost::make_shared<Presence>(*this);
+ }
- bool isAvailable() const {
- return type_ == Available;
- }
+ bool isAvailable() const {
+ return type_ == Available;
+ }
- private:
- Presence::Type type_;
- };
+ private:
+ Presence::Type type_;
+ };
}
diff --git a/Swiften/Elements/Priority.h b/Swiften/Elements/Priority.h
index 6de42b4..56e493c 100644
--- a/Swiften/Elements/Priority.h
+++ b/Swiften/Elements/Priority.h
@@ -10,20 +10,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Priority : public Payload {
- public:
- Priority(int priority = 0) : priority_(priority) {
- }
+ class SWIFTEN_API Priority : public Payload {
+ public:
+ Priority(int priority = 0) : priority_(priority) {
+ }
- void setPriority(int priority) {
- priority_ = priority;
- }
+ void setPriority(int priority) {
+ priority_ = priority;
+ }
- int getPriority() const {
- return priority_;
- }
+ int getPriority() const {
+ return priority_;
+ }
- private:
- int priority_;
- };
+ private:
+ int priority_;
+ };
}
diff --git a/Swiften/Elements/PrivateStorage.h b/Swiften/Elements/PrivateStorage.h
index 15455b8..e1f97d5 100644
--- a/Swiften/Elements/PrivateStorage.h
+++ b/Swiften/Elements/PrivateStorage.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PrivateStorage : public Payload {
- public:
- PrivateStorage(boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()) : payload(payload) {
- }
+ class SWIFTEN_API PrivateStorage : public Payload {
+ public:
+ PrivateStorage(boost::shared_ptr<Payload> payload = boost::shared_ptr<Payload>()) : payload(payload) {
+ }
- boost::shared_ptr<Payload> getPayload() const {
- return payload;
- }
+ boost::shared_ptr<Payload> getPayload() const {
+ return payload;
+ }
- void setPayload(boost::shared_ptr<Payload> p) {
- payload = p;
- }
+ void setPayload(boost::shared_ptr<Payload> p) {
+ payload = p;
+ }
- private:
- boost::shared_ptr<Payload> payload;
- };
+ private:
+ boost::shared_ptr<Payload> payload;
+ };
}
diff --git a/Swiften/Elements/ProtocolHeader.h b/Swiften/Elements/ProtocolHeader.h
index a38f806..4ae545a 100644
--- a/Swiften/Elements/ProtocolHeader.h
+++ b/Swiften/Elements/ProtocolHeader.h
@@ -11,34 +11,34 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API ProtocolHeader {
- public:
- ProtocolHeader() : version("1.0") {}
-
- const std::string& getTo() const { return to; }
- void setTo(const std::string& a) {
- to = a;
- }
-
- const std::string& getFrom() const { return from; }
- void setFrom(const std::string& a) {
- from = a;
- }
-
- const std::string& getVersion() const { return version; }
- void setVersion(const std::string& a) {
- version = a;
- }
-
- const std::string& getID() const { return id; }
- void setID(const std::string& a) {
- id = a;
- }
-
- private:
- std::string to;
- std::string from;
- std::string id;
- std::string version;
- };
+ class SWIFTEN_API ProtocolHeader {
+ public:
+ ProtocolHeader() : version("1.0") {}
+
+ const std::string& getTo() const { return to; }
+ void setTo(const std::string& a) {
+ to = a;
+ }
+
+ const std::string& getFrom() const { return from; }
+ void setFrom(const std::string& a) {
+ from = a;
+ }
+
+ const std::string& getVersion() const { return version; }
+ void setVersion(const std::string& a) {
+ version = a;
+ }
+
+ const std::string& getID() const { return id; }
+ void setID(const std::string& a) {
+ id = a;
+ }
+
+ private:
+ std::string to;
+ std::string from;
+ std::string id;
+ std::string version;
+ };
}
diff --git a/Swiften/Elements/PubSub.h b/Swiften/Elements/PubSub.h
index fb75c80..d62c54e 100644
--- a/Swiften/Elements/PubSub.h
+++ b/Swiften/Elements/PubSub.h
@@ -12,9 +12,9 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSub : public ContainerPayload<PubSubPayload> {
- public:
- PubSub();
- virtual ~PubSub();
- };
+ class SWIFTEN_API PubSub : public ContainerPayload<PubSubPayload> {
+ public:
+ PubSub();
+ virtual ~PubSub();
+ };
}
diff --git a/Swiften/Elements/PubSubAffiliation.h b/Swiften/Elements/PubSubAffiliation.h
index 61198ff..b19e84b 100644
--- a/Swiften/Elements/PubSubAffiliation.h
+++ b/Swiften/Elements/PubSubAffiliation.h
@@ -13,40 +13,40 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubAffiliation : public Payload {
- public:
- enum Type {
- None,
- Member,
- Outcast,
- Owner,
- Publisher,
- PublishOnly
- };
-
- PubSubAffiliation();
- PubSubAffiliation(const std::string& node) : node(node), type(None) {}
- virtual ~PubSubAffiliation();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- Type getType() const {
- return type;
- }
-
- void setType(Type value) {
- this->type = value ;
- }
-
-
- private:
- std::string node;
- Type type;
- };
+ class SWIFTEN_API PubSubAffiliation : public Payload {
+ public:
+ enum Type {
+ None,
+ Member,
+ Outcast,
+ Owner,
+ Publisher,
+ PublishOnly
+ };
+
+ PubSubAffiliation();
+ PubSubAffiliation(const std::string& node) : node(node), type(None) {}
+ virtual ~PubSubAffiliation();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ Type getType() const {
+ return type;
+ }
+
+ void setType(Type value) {
+ this->type = value ;
+ }
+
+
+ private:
+ std::string node;
+ Type type;
+ };
}
diff --git a/Swiften/Elements/PubSubAffiliations.h b/Swiften/Elements/PubSubAffiliations.h
index e8f0382..9f66056 100644
--- a/Swiften/Elements/PubSubAffiliations.h
+++ b/Swiften/Elements/PubSubAffiliations.h
@@ -19,36 +19,36 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubAffiliations : public PubSubPayload {
- public:
-
- PubSubAffiliations();
-
- virtual ~PubSubAffiliations();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubAffiliation> >& getAffiliations() const {
- return affiliations;
- }
-
- void setAffiliations(const std::vector< boost::shared_ptr<PubSubAffiliation> >& value) {
- this->affiliations = value ;
- }
-
- void addAffiliation(boost::shared_ptr<PubSubAffiliation> value) {
- this->affiliations.push_back(value);
- }
-
-
- private:
- boost::optional< std::string > node;
- std::vector< boost::shared_ptr<PubSubAffiliation> > affiliations;
- };
+ class SWIFTEN_API PubSubAffiliations : public PubSubPayload {
+ public:
+
+ PubSubAffiliations();
+
+ virtual ~PubSubAffiliations();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubAffiliation> >& getAffiliations() const {
+ return affiliations;
+ }
+
+ void setAffiliations(const std::vector< boost::shared_ptr<PubSubAffiliation> >& value) {
+ this->affiliations = value ;
+ }
+
+ void addAffiliation(boost::shared_ptr<PubSubAffiliation> value) {
+ this->affiliations.push_back(value);
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::vector< boost::shared_ptr<PubSubAffiliation> > affiliations;
+ };
}
diff --git a/Swiften/Elements/PubSubConfigure.h b/Swiften/Elements/PubSubConfigure.h
index 4cd219c..e8f3cbc 100644
--- a/Swiften/Elements/PubSubConfigure.h
+++ b/Swiften/Elements/PubSubConfigure.h
@@ -14,23 +14,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubConfigure : public Payload {
- public:
-
- PubSubConfigure();
-
- virtual ~PubSubConfigure();
+ class SWIFTEN_API PubSubConfigure : public Payload {
+ public:
- boost::shared_ptr<Form> getData() const {
- return data;
- }
+ PubSubConfigure();
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
+ virtual ~PubSubConfigure();
+ boost::shared_ptr<Form> getData() const {
+ return data;
+ }
- private:
- boost::shared_ptr<Form> data;
- };
+ void setData(boost::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ boost::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubCreate.h b/Swiften/Elements/PubSubCreate.h
index f535a89..b2226c4 100644
--- a/Swiften/Elements/PubSubCreate.h
+++ b/Swiften/Elements/PubSubCreate.h
@@ -17,32 +17,32 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubCreate : public PubSubPayload {
- public:
-
- PubSubCreate();
- PubSubCreate(const std::string& node) : node(node) {}
- virtual ~PubSubCreate();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<PubSubConfigure> getConfigure() const {
- return configure;
- }
-
- void setConfigure(boost::shared_ptr<PubSubConfigure> value) {
- this->configure = value ;
- }
-
-
- private:
- std::string node;
- boost::shared_ptr<PubSubConfigure> configure;
- };
+ class SWIFTEN_API PubSubCreate : public PubSubPayload {
+ public:
+
+ PubSubCreate();
+ PubSubCreate(const std::string& node) : node(node) {}
+ virtual ~PubSubCreate();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<PubSubConfigure> getConfigure() const {
+ return configure;
+ }
+
+ void setConfigure(boost::shared_ptr<PubSubConfigure> value) {
+ this->configure = value ;
+ }
+
+
+ private:
+ std::string node;
+ boost::shared_ptr<PubSubConfigure> configure;
+ };
}
diff --git a/Swiften/Elements/PubSubDefault.h b/Swiften/Elements/PubSubDefault.h
index f4e7595..08482b4 100644
--- a/Swiften/Elements/PubSubDefault.h
+++ b/Swiften/Elements/PubSubDefault.h
@@ -16,37 +16,37 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubDefault : public PubSubPayload {
- public:
- enum Type {
- None,
- Collection,
- Leaf
- };
-
- PubSubDefault();
-
- virtual ~PubSubDefault();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- Type getType() const {
- return type;
- }
-
- void setType(Type value) {
- this->type = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- Type type;
- };
+ class SWIFTEN_API PubSubDefault : public PubSubPayload {
+ public:
+ enum Type {
+ None,
+ Collection,
+ Leaf
+ };
+
+ PubSubDefault();
+
+ virtual ~PubSubDefault();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ Type getType() const {
+ return type;
+ }
+
+ void setType(Type value) {
+ this->type = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ Type type;
+ };
}
diff --git a/Swiften/Elements/PubSubError.h b/Swiften/Elements/PubSubError.h
index 8fc957c..2d4452a 100644
--- a/Swiften/Elements/PubSubError.h
+++ b/Swiften/Elements/PubSubError.h
@@ -9,103 +9,103 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubError : public Payload {
- public:
- enum Type {
- UnknownType = 0,
- ClosedNode,
- ConfigurationRequired,
- InvalidJID,
- InvalidOptions,
- InvalidPayload,
- InvalidSubscriptionID,
- ItemForbidden,
- ItemRequired,
- JIDRequired,
- MaximumItemsExceeded,
- MaximumNodesExceeded,
- NodeIDRequired,
- NotInRosterGroup,
- NotSubscribed,
- PayloadTooBig,
- PayloadRequired,
- PendingSubscription,
- PresenceSubscriptionRequired,
- SubscriptionIDRequired,
- TooManySubscriptions,
- Unsupported,
- UnsupportedAccessModel
- };
+ class SWIFTEN_API PubSubError : public Payload {
+ public:
+ enum Type {
+ UnknownType = 0,
+ ClosedNode,
+ ConfigurationRequired,
+ InvalidJID,
+ InvalidOptions,
+ InvalidPayload,
+ InvalidSubscriptionID,
+ ItemForbidden,
+ ItemRequired,
+ JIDRequired,
+ MaximumItemsExceeded,
+ MaximumNodesExceeded,
+ NodeIDRequired,
+ NotInRosterGroup,
+ NotSubscribed,
+ PayloadTooBig,
+ PayloadRequired,
+ PendingSubscription,
+ PresenceSubscriptionRequired,
+ SubscriptionIDRequired,
+ TooManySubscriptions,
+ Unsupported,
+ UnsupportedAccessModel
+ };
- enum UnsupportedFeatureType {
- UnknownUnsupportedFeatureType = 0,
- AccessAuthorize,
- AccessOpen,
- AccessPresence,
- AccessRoster,
- AccessWhitelist,
- AutoCreate,
- AutoSubscribe,
- Collections,
- ConfigNode,
- CreateAndConfigure,
- CreateNodes,
- DeleteItems,
- DeleteNodes,
- FilteredNotifications,
- GetPending,
- InstantNodes,
- ItemIDs,
- LastPublished,
- LeasedSubscription,
- ManageSubscriptions,
- MemberAffiliation,
- MetaData,
- ModifyAffiliations,
- MultiCollection,
- MultiSubscribe,
- OutcastAffiliation,
- PersistentItems,
- PresenceNotifications,
- PresenceSubscribe,
- Publish,
- PublishOptions,
- PublishOnlyAffiliation,
- PublisherAffiliation,
- PurgeNodes,
- RetractItems,
- RetrieveAffiliations,
- RetrieveDefault,
- RetrieveItems,
- RetrieveSubscriptions,
- Subscribe,
- SubscriptionOptions,
- SubscriptionNotifications
- };
+ enum UnsupportedFeatureType {
+ UnknownUnsupportedFeatureType = 0,
+ AccessAuthorize,
+ AccessOpen,
+ AccessPresence,
+ AccessRoster,
+ AccessWhitelist,
+ AutoCreate,
+ AutoSubscribe,
+ Collections,
+ ConfigNode,
+ CreateAndConfigure,
+ CreateNodes,
+ DeleteItems,
+ DeleteNodes,
+ FilteredNotifications,
+ GetPending,
+ InstantNodes,
+ ItemIDs,
+ LastPublished,
+ LeasedSubscription,
+ ManageSubscriptions,
+ MemberAffiliation,
+ MetaData,
+ ModifyAffiliations,
+ MultiCollection,
+ MultiSubscribe,
+ OutcastAffiliation,
+ PersistentItems,
+ PresenceNotifications,
+ PresenceSubscribe,
+ Publish,
+ PublishOptions,
+ PublishOnlyAffiliation,
+ PublisherAffiliation,
+ PurgeNodes,
+ RetractItems,
+ RetrieveAffiliations,
+ RetrieveDefault,
+ RetrieveItems,
+ RetrieveSubscriptions,
+ Subscribe,
+ SubscriptionOptions,
+ SubscriptionNotifications
+ };
- PubSubError(Type type = UnknownType) : type(type), unsupportedType(UnknownUnsupportedFeatureType) {
- }
+ PubSubError(Type type = UnknownType) : type(type), unsupportedType(UnknownUnsupportedFeatureType) {
+ }
- virtual ~PubSubError();
+ virtual ~PubSubError();
- Type getType() const {
- return type;
- }
+ Type getType() const {
+ return type;
+ }
- void setType(Type type) {
- this->type = type;
- }
+ void setType(Type type) {
+ this->type = type;
+ }
- UnsupportedFeatureType getUnsupportedFeatureType() const {
- return unsupportedType;
- }
+ UnsupportedFeatureType getUnsupportedFeatureType() const {
+ return unsupportedType;
+ }
- void setUnsupportedFeatureType(UnsupportedFeatureType unsupportedType) {
- this->unsupportedType = unsupportedType;
- }
+ void setUnsupportedFeatureType(UnsupportedFeatureType unsupportedType) {
+ this->unsupportedType = unsupportedType;
+ }
- private:
- Type type;
- UnsupportedFeatureType unsupportedType;
- };
+ private:
+ Type type;
+ UnsupportedFeatureType unsupportedType;
+ };
}
diff --git a/Swiften/Elements/PubSubEvent.h b/Swiften/Elements/PubSubEvent.h
index 2029945..85d9bed 100644
--- a/Swiften/Elements/PubSubEvent.h
+++ b/Swiften/Elements/PubSubEvent.h
@@ -15,9 +15,9 @@
#include <Swiften/Elements/PubSubEventPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubEvent : public ContainerPayload<PubSubEventPayload> {
- public:
- PubSubEvent();
- virtual ~PubSubEvent();
- };
+ class SWIFTEN_API PubSubEvent : public ContainerPayload<PubSubEventPayload> {
+ public:
+ PubSubEvent();
+ virtual ~PubSubEvent();
+ };
}
diff --git a/Swiften/Elements/PubSubEventAssociate.h b/Swiften/Elements/PubSubEventAssociate.h
index 73cd3b9..5d963a0 100644
--- a/Swiften/Elements/PubSubEventAssociate.h
+++ b/Swiften/Elements/PubSubEventAssociate.h
@@ -13,23 +13,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventAssociate : public Payload {
- public:
-
- PubSubEventAssociate();
-
- virtual ~PubSubEventAssociate();
+ class SWIFTEN_API PubSubEventAssociate : public Payload {
+ public:
- const std::string& getNode() const {
- return node;
- }
+ PubSubEventAssociate();
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ virtual ~PubSubEventAssociate();
+ const std::string& getNode() const {
+ return node;
+ }
- private:
- std::string node;
- };
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventCollection.h b/Swiften/Elements/PubSubEventCollection.h
index 5910c9f..390fa58 100644
--- a/Swiften/Elements/PubSubEventCollection.h
+++ b/Swiften/Elements/PubSubEventCollection.h
@@ -19,41 +19,41 @@
#include <Swiften/Elements/PubSubEventPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventCollection : public PubSubEventPayload {
- public:
-
- PubSubEventCollection();
-
- virtual ~PubSubEventCollection();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<PubSubEventDisassociate> getDisassociate() const {
- return disassociate;
- }
-
- void setDisassociate(boost::shared_ptr<PubSubEventDisassociate> value) {
- this->disassociate = value ;
- }
-
- boost::shared_ptr<PubSubEventAssociate> getAssociate() const {
- return associate;
- }
-
- void setAssociate(boost::shared_ptr<PubSubEventAssociate> value) {
- this->associate = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- boost::shared_ptr<PubSubEventDisassociate> disassociate;
- boost::shared_ptr<PubSubEventAssociate> associate;
- };
+ class SWIFTEN_API PubSubEventCollection : public PubSubEventPayload {
+ public:
+
+ PubSubEventCollection();
+
+ virtual ~PubSubEventCollection();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<PubSubEventDisassociate> getDisassociate() const {
+ return disassociate;
+ }
+
+ void setDisassociate(boost::shared_ptr<PubSubEventDisassociate> value) {
+ this->disassociate = value ;
+ }
+
+ boost::shared_ptr<PubSubEventAssociate> getAssociate() const {
+ return associate;
+ }
+
+ void setAssociate(boost::shared_ptr<PubSubEventAssociate> value) {
+ this->associate = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ boost::shared_ptr<PubSubEventDisassociate> disassociate;
+ boost::shared_ptr<PubSubEventAssociate> associate;
+ };
}
diff --git a/Swiften/Elements/PubSubEventConfiguration.h b/Swiften/Elements/PubSubEventConfiguration.h
index da42fcb..14639ab 100644
--- a/Swiften/Elements/PubSubEventConfiguration.h
+++ b/Swiften/Elements/PubSubEventConfiguration.h
@@ -17,32 +17,32 @@
#include <Swiften/Elements/PubSubEventPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventConfiguration : public PubSubEventPayload {
- public:
-
- PubSubEventConfiguration();
-
- virtual ~PubSubEventConfiguration();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<Form> getData() const {
- return data;
- }
-
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
-
-
- private:
- std::string node;
- boost::shared_ptr<Form> data;
- };
+ class SWIFTEN_API PubSubEventConfiguration : public PubSubEventPayload {
+ public:
+
+ PubSubEventConfiguration();
+
+ virtual ~PubSubEventConfiguration();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(boost::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ std::string node;
+ boost::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubEventDelete.h b/Swiften/Elements/PubSubEventDelete.h
index 1a2c74f..a778276 100644
--- a/Swiften/Elements/PubSubEventDelete.h
+++ b/Swiften/Elements/PubSubEventDelete.h
@@ -17,32 +17,32 @@
#include <Swiften/Elements/PubSubEventRedirect.h>
namespace Swift {
- class SWIFTEN_API PubSubEventDelete : public PubSubEventPayload {
- public:
-
- PubSubEventDelete();
-
- virtual ~PubSubEventDelete();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<PubSubEventRedirect> getRedirects() const {
- return redirects;
- }
-
- void setRedirects(boost::shared_ptr<PubSubEventRedirect> value) {
- this->redirects = value ;
- }
-
-
- private:
- std::string node;
- boost::shared_ptr<PubSubEventRedirect> redirects;
- };
+ class SWIFTEN_API PubSubEventDelete : public PubSubEventPayload {
+ public:
+
+ PubSubEventDelete();
+
+ virtual ~PubSubEventDelete();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<PubSubEventRedirect> getRedirects() const {
+ return redirects;
+ }
+
+ void setRedirects(boost::shared_ptr<PubSubEventRedirect> value) {
+ this->redirects = value ;
+ }
+
+
+ private:
+ std::string node;
+ boost::shared_ptr<PubSubEventRedirect> redirects;
+ };
}
diff --git a/Swiften/Elements/PubSubEventDisassociate.h b/Swiften/Elements/PubSubEventDisassociate.h
index d4c3452..826b1f4 100644
--- a/Swiften/Elements/PubSubEventDisassociate.h
+++ b/Swiften/Elements/PubSubEventDisassociate.h
@@ -13,23 +13,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventDisassociate : public Payload {
- public:
-
- PubSubEventDisassociate();
-
- virtual ~PubSubEventDisassociate();
+ class SWIFTEN_API PubSubEventDisassociate : public Payload {
+ public:
- const std::string& getNode() const {
- return node;
- }
+ PubSubEventDisassociate();
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ virtual ~PubSubEventDisassociate();
+ const std::string& getNode() const {
+ return node;
+ }
- private:
- std::string node;
- };
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventItem.h b/Swiften/Elements/PubSubEventItem.h
index 3b4f930..bbadab9 100644
--- a/Swiften/Elements/PubSubEventItem.h
+++ b/Swiften/Elements/PubSubEventItem.h
@@ -17,54 +17,54 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventItem : public Payload {
- public:
-
- PubSubEventItem();
-
- virtual ~PubSubEventItem();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const boost::optional< std::string >& getPublisher() const {
- return publisher;
- }
-
- void setPublisher(const boost::optional< std::string >& value) {
- this->publisher = value ;
- }
-
- const std::vector< boost::shared_ptr<Payload> >& getData() const {
- return data;
- }
-
- void setData(const std::vector< boost::shared_ptr<Payload> >& value) {
- this->data = value ;
- }
-
- void addData(boost::shared_ptr<Payload> value) {
- this->data.push_back(value);
- }
-
- const boost::optional< std::string >& getID() const {
- return id;
- }
-
- void setID(const boost::optional< std::string >& value) {
- this->id = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- boost::optional< std::string > publisher;
- std::vector< boost::shared_ptr<Payload> > data;
- boost::optional< std::string > id;
- };
+ class SWIFTEN_API PubSubEventItem : public Payload {
+ public:
+
+ PubSubEventItem();
+
+ virtual ~PubSubEventItem();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const boost::optional< std::string >& getPublisher() const {
+ return publisher;
+ }
+
+ void setPublisher(const boost::optional< std::string >& value) {
+ this->publisher = value ;
+ }
+
+ const std::vector< boost::shared_ptr<Payload> >& getData() const {
+ return data;
+ }
+
+ void setData(const std::vector< boost::shared_ptr<Payload> >& value) {
+ this->data = value ;
+ }
+
+ void addData(boost::shared_ptr<Payload> value) {
+ this->data.push_back(value);
+ }
+
+ const boost::optional< std::string >& getID() const {
+ return id;
+ }
+
+ void setID(const boost::optional< std::string >& value) {
+ this->id = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ boost::optional< std::string > publisher;
+ std::vector< boost::shared_ptr<Payload> > data;
+ boost::optional< std::string > id;
+ };
}
diff --git a/Swiften/Elements/PubSubEventItems.h b/Swiften/Elements/PubSubEventItems.h
index c3be21a..9d1e09b 100644
--- a/Swiften/Elements/PubSubEventItems.h
+++ b/Swiften/Elements/PubSubEventItems.h
@@ -19,49 +19,49 @@
#include <Swiften/Elements/PubSubEventRetract.h>
namespace Swift {
- class SWIFTEN_API PubSubEventItems : public PubSubEventPayload {
- public:
-
- PubSubEventItems();
-
- virtual ~PubSubEventItems();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubEventItem> >& getItems() const {
- return items;
- }
-
- void setItems(const std::vector< boost::shared_ptr<PubSubEventItem> >& value) {
- this->items = value ;
- }
-
- void addItem(boost::shared_ptr<PubSubEventItem> value) {
- this->items.push_back(value);
- }
-
- const std::vector< boost::shared_ptr<PubSubEventRetract> >& getRetracts() const {
- return retracts;
- }
-
- void setRetracts(const std::vector< boost::shared_ptr<PubSubEventRetract> >& value) {
- this->retracts = value ;
- }
-
- void addRetract(boost::shared_ptr<PubSubEventRetract> value) {
- this->retracts.push_back(value);
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubEventItem> > items;
- std::vector< boost::shared_ptr<PubSubEventRetract> > retracts;
- };
+ class SWIFTEN_API PubSubEventItems : public PubSubEventPayload {
+ public:
+
+ PubSubEventItems();
+
+ virtual ~PubSubEventItems();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubEventItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< boost::shared_ptr<PubSubEventItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(boost::shared_ptr<PubSubEventItem> value) {
+ this->items.push_back(value);
+ }
+
+ const std::vector< boost::shared_ptr<PubSubEventRetract> >& getRetracts() const {
+ return retracts;
+ }
+
+ void setRetracts(const std::vector< boost::shared_ptr<PubSubEventRetract> >& value) {
+ this->retracts = value ;
+ }
+
+ void addRetract(boost::shared_ptr<PubSubEventRetract> value) {
+ this->retracts.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubEventItem> > items;
+ std::vector< boost::shared_ptr<PubSubEventRetract> > retracts;
+ };
}
diff --git a/Swiften/Elements/PubSubEventPayload.h b/Swiften/Elements/PubSubEventPayload.h
index f1e3890..f4abc06 100644
--- a/Swiften/Elements/PubSubEventPayload.h
+++ b/Swiften/Elements/PubSubEventPayload.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventPayload : public Payload {
- public:
- virtual ~PubSubEventPayload();
- };
+ class SWIFTEN_API PubSubEventPayload : public Payload {
+ public:
+ virtual ~PubSubEventPayload();
+ };
}
diff --git a/Swiften/Elements/PubSubEventPurge.h b/Swiften/Elements/PubSubEventPurge.h
index a19a8a2..743cc25 100644
--- a/Swiften/Elements/PubSubEventPurge.h
+++ b/Swiften/Elements/PubSubEventPurge.h
@@ -14,23 +14,23 @@
#include <Swiften/Elements/PubSubEventPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload {
- public:
-
- PubSubEventPurge();
-
- virtual ~PubSubEventPurge();
+ class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload {
+ public:
- const std::string& getNode() const {
- return node;
- }
+ PubSubEventPurge();
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ virtual ~PubSubEventPurge();
+ const std::string& getNode() const {
+ return node;
+ }
- private:
- std::string node;
- };
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventRedirect.h b/Swiften/Elements/PubSubEventRedirect.h
index 13dc865..e0e351f 100644
--- a/Swiften/Elements/PubSubEventRedirect.h
+++ b/Swiften/Elements/PubSubEventRedirect.h
@@ -13,23 +13,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventRedirect : public Payload {
- public:
-
- PubSubEventRedirect();
-
- virtual ~PubSubEventRedirect();
+ class SWIFTEN_API PubSubEventRedirect : public Payload {
+ public:
- const std::string& getURI() const {
- return uri;
- }
+ PubSubEventRedirect();
- void setURI(const std::string& value) {
- this->uri = value ;
- }
+ virtual ~PubSubEventRedirect();
+ const std::string& getURI() const {
+ return uri;
+ }
- private:
- std::string uri;
- };
+ void setURI(const std::string& value) {
+ this->uri = value ;
+ }
+
+
+ private:
+ std::string uri;
+ };
}
diff --git a/Swiften/Elements/PubSubEventRetract.h b/Swiften/Elements/PubSubEventRetract.h
index 6681061..b0aea96 100644
--- a/Swiften/Elements/PubSubEventRetract.h
+++ b/Swiften/Elements/PubSubEventRetract.h
@@ -13,23 +13,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventRetract : public Payload {
- public:
-
- PubSubEventRetract();
-
- virtual ~PubSubEventRetract();
+ class SWIFTEN_API PubSubEventRetract : public Payload {
+ public:
- const std::string& getID() const {
- return id;
- }
+ PubSubEventRetract();
- void setID(const std::string& value) {
- this->id = value ;
- }
+ virtual ~PubSubEventRetract();
+ const std::string& getID() const {
+ return id;
+ }
- private:
- std::string id;
- };
+ void setID(const std::string& value) {
+ this->id = value ;
+ }
+
+
+ private:
+ std::string id;
+ };
}
diff --git a/Swiften/Elements/PubSubEventSubscription.h b/Swiften/Elements/PubSubEventSubscription.h
index 6416d21..0b8297c 100644
--- a/Swiften/Elements/PubSubEventSubscription.h
+++ b/Swiften/Elements/PubSubEventSubscription.h
@@ -18,65 +18,65 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubEventSubscription : public PubSubEventPayload {
- public:
- enum SubscriptionType {
- None,
- Pending,
- Subscribed,
- Unconfigured
- };
-
- PubSubEventSubscription();
-
- virtual ~PubSubEventSubscription();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- SubscriptionType getSubscription() const {
- return subscription;
- }
-
- void setSubscription(SubscriptionType value) {
- this->subscription = value ;
- }
-
- const boost::optional< std::string >& getSubscriptionID() const {
- return subscriptionID;
- }
-
- void setSubscriptionID(const boost::optional< std::string >& value) {
- this->subscriptionID = value ;
- }
-
- const boost::posix_time::ptime& getExpiry() const {
- return expiry;
- }
-
- void setExpiry(const boost::posix_time::ptime& value) {
- this->expiry = value ;
- }
-
-
- private:
- std::string node;
- JID jid;
- SubscriptionType subscription;
- boost::optional< std::string > subscriptionID;
- boost::posix_time::ptime expiry;
- };
+ class SWIFTEN_API PubSubEventSubscription : public PubSubEventPayload {
+ public:
+ enum SubscriptionType {
+ None,
+ Pending,
+ Subscribed,
+ Unconfigured
+ };
+
+ PubSubEventSubscription();
+
+ virtual ~PubSubEventSubscription();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ SubscriptionType getSubscription() const {
+ return subscription;
+ }
+
+ void setSubscription(SubscriptionType value) {
+ this->subscription = value ;
+ }
+
+ const boost::optional< std::string >& getSubscriptionID() const {
+ return subscriptionID;
+ }
+
+ void setSubscriptionID(const boost::optional< std::string >& value) {
+ this->subscriptionID = value ;
+ }
+
+ const boost::posix_time::ptime& getExpiry() const {
+ return expiry;
+ }
+
+ void setExpiry(const boost::posix_time::ptime& value) {
+ this->expiry = value ;
+ }
+
+
+ private:
+ std::string node;
+ JID jid;
+ SubscriptionType subscription;
+ boost::optional< std::string > subscriptionID;
+ boost::posix_time::ptime expiry;
+ };
}
diff --git a/Swiften/Elements/PubSubItem.h b/Swiften/Elements/PubSubItem.h
index 63b374b..5a16edc 100644
--- a/Swiften/Elements/PubSubItem.h
+++ b/Swiften/Elements/PubSubItem.h
@@ -16,36 +16,36 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubItem : public Payload {
- public:
-
- PubSubItem();
-
- virtual ~PubSubItem();
-
- const std::vector< boost::shared_ptr<Payload> >& getData() const {
- return data;
- }
-
- void setData(const std::vector< boost::shared_ptr<Payload> >& value) {
- this->data = value ;
- }
-
- void addData(boost::shared_ptr<Payload> value) {
- this->data.push_back(value);
- }
-
- const std::string& getID() const {
- return id;
- }
-
- void setID(const std::string& value) {
- this->id = value ;
- }
-
-
- private:
- std::vector< boost::shared_ptr<Payload> > data;
- std::string id;
- };
+ class SWIFTEN_API PubSubItem : public Payload {
+ public:
+
+ PubSubItem();
+
+ virtual ~PubSubItem();
+
+ const std::vector< boost::shared_ptr<Payload> >& getData() const {
+ return data;
+ }
+
+ void setData(const std::vector< boost::shared_ptr<Payload> >& value) {
+ this->data = value ;
+ }
+
+ void addData(boost::shared_ptr<Payload> value) {
+ this->data.push_back(value);
+ }
+
+ const std::string& getID() const {
+ return id;
+ }
+
+ void setID(const std::string& value) {
+ this->id = value ;
+ }
+
+
+ private:
+ std::vector< boost::shared_ptr<Payload> > data;
+ std::string id;
+ };
}
diff --git a/Swiften/Elements/PubSubItems.h b/Swiften/Elements/PubSubItems.h
index 7665ca4..b7d8fcc 100644
--- a/Swiften/Elements/PubSubItems.h
+++ b/Swiften/Elements/PubSubItems.h
@@ -19,54 +19,54 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubItems : public PubSubPayload {
- public:
-
- PubSubItems();
- PubSubItems(const std::string& node) : node(node) {}
- virtual ~PubSubItems();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
- return items;
- }
-
- void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
- this->items = value ;
- }
-
- void addItem(boost::shared_ptr<PubSubItem> value) {
- this->items.push_back(value);
- }
-
- const boost::optional< unsigned int >& getMaximumItems() const {
- return maximumItems;
- }
-
- void setMaximumItems(const boost::optional< unsigned int >& value) {
- this->maximumItems = value ;
- }
-
- const boost::optional< std::string >& getSubscriptionID() const {
- return subscriptionID;
- }
-
- void setSubscriptionID(const boost::optional< std::string >& value) {
- this->subscriptionID = value ;
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubItem> > items;
- boost::optional< unsigned int > maximumItems;
- boost::optional< std::string > subscriptionID;
- };
+ class SWIFTEN_API PubSubItems : public PubSubPayload {
+ public:
+
+ PubSubItems();
+ PubSubItems(const std::string& node) : node(node) {}
+ virtual ~PubSubItems();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(boost::shared_ptr<PubSubItem> value) {
+ this->items.push_back(value);
+ }
+
+ const boost::optional< unsigned int >& getMaximumItems() const {
+ return maximumItems;
+ }
+
+ void setMaximumItems(const boost::optional< unsigned int >& value) {
+ this->maximumItems = value ;
+ }
+
+ const boost::optional< std::string >& getSubscriptionID() const {
+ return subscriptionID;
+ }
+
+ void setSubscriptionID(const boost::optional< std::string >& value) {
+ this->subscriptionID = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubItem> > items;
+ boost::optional< unsigned int > maximumItems;
+ boost::optional< std::string > subscriptionID;
+ };
}
diff --git a/Swiften/Elements/PubSubOptions.h b/Swiften/Elements/PubSubOptions.h
index 9a953fe..fffc175 100644
--- a/Swiften/Elements/PubSubOptions.h
+++ b/Swiften/Elements/PubSubOptions.h
@@ -19,50 +19,50 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubOptions : public PubSubPayload {
- public:
-
- PubSubOptions();
-
- virtual ~PubSubOptions();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- boost::shared_ptr<Form> getData() const {
- return data;
- }
-
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
-
- const boost::optional< std::string >& getSubscriptionID() const {
- return subscriptionID;
- }
-
- void setSubscriptionID(const boost::optional< std::string >& value) {
- this->subscriptionID = value ;
- }
-
-
- private:
- std::string node;
- JID jid;
- boost::shared_ptr<Form> data;
- boost::optional< std::string > subscriptionID;
- };
+ class SWIFTEN_API PubSubOptions : public PubSubPayload {
+ public:
+
+ PubSubOptions();
+
+ virtual ~PubSubOptions();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ boost::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(boost::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+ const boost::optional< std::string >& getSubscriptionID() const {
+ return subscriptionID;
+ }
+
+ void setSubscriptionID(const boost::optional< std::string >& value) {
+ this->subscriptionID = value ;
+ }
+
+
+ private:
+ std::string node;
+ JID jid;
+ boost::shared_ptr<Form> data;
+ boost::optional< std::string > subscriptionID;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerAffiliation.h b/Swiften/Elements/PubSubOwnerAffiliation.h
index d064873..a8c1d91 100644
--- a/Swiften/Elements/PubSubOwnerAffiliation.h
+++ b/Swiften/Elements/PubSubOwnerAffiliation.h
@@ -12,40 +12,40 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerAffiliation : public Payload {
- public:
- enum Type {
- None,
- Member,
- Outcast,
- Owner,
- Publisher,
- PublishOnly
- };
-
- PubSubOwnerAffiliation();
-
- virtual ~PubSubOwnerAffiliation();
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- Type getType() const {
- return type;
- }
-
- void setType(Type value) {
- this->type = value ;
- }
-
-
- private:
- JID jid;
- Type type;
- };
+ class SWIFTEN_API PubSubOwnerAffiliation : public Payload {
+ public:
+ enum Type {
+ None,
+ Member,
+ Outcast,
+ Owner,
+ Publisher,
+ PublishOnly
+ };
+
+ PubSubOwnerAffiliation();
+
+ virtual ~PubSubOwnerAffiliation();
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ Type getType() const {
+ return type;
+ }
+
+ void setType(Type value) {
+ this->type = value ;
+ }
+
+
+ private:
+ JID jid;
+ Type type;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerAffiliations.h b/Swiften/Elements/PubSubOwnerAffiliations.h
index 23739a7..5005b01 100644
--- a/Swiften/Elements/PubSubOwnerAffiliations.h
+++ b/Swiften/Elements/PubSubOwnerAffiliations.h
@@ -18,36 +18,36 @@
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerAffiliations : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerAffiliations();
-
- virtual ~PubSubOwnerAffiliations();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& getAffiliations() const {
- return affiliations;
- }
-
- void setAffiliations(const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& value) {
- this->affiliations = value ;
- }
-
- void addAffiliation(boost::shared_ptr<PubSubOwnerAffiliation> value) {
- this->affiliations.push_back(value);
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubOwnerAffiliation> > affiliations;
- };
+ class SWIFTEN_API PubSubOwnerAffiliations : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerAffiliations();
+
+ virtual ~PubSubOwnerAffiliations();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& getAffiliations() const {
+ return affiliations;
+ }
+
+ void setAffiliations(const std::vector< boost::shared_ptr<PubSubOwnerAffiliation> >& value) {
+ this->affiliations = value ;
+ }
+
+ void addAffiliation(boost::shared_ptr<PubSubOwnerAffiliation> value) {
+ this->affiliations.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubOwnerAffiliation> > affiliations;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerConfigure.h b/Swiften/Elements/PubSubOwnerConfigure.h
index d29342d..086095c 100644
--- a/Swiften/Elements/PubSubOwnerConfigure.h
+++ b/Swiften/Elements/PubSubOwnerConfigure.h
@@ -18,32 +18,32 @@
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerConfigure : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerConfigure();
- PubSubOwnerConfigure(const std::string& node) : node(node) {}
- virtual ~PubSubOwnerConfigure();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<Form> getData() const {
- return data;
- }
-
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- boost::shared_ptr<Form> data;
- };
+ class SWIFTEN_API PubSubOwnerConfigure : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerConfigure();
+ PubSubOwnerConfigure(const std::string& node) : node(node) {}
+ virtual ~PubSubOwnerConfigure();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(boost::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ boost::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerDefault.h b/Swiften/Elements/PubSubOwnerDefault.h
index 17717db..a0b82f7 100644
--- a/Swiften/Elements/PubSubOwnerDefault.h
+++ b/Swiften/Elements/PubSubOwnerDefault.h
@@ -15,23 +15,23 @@
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerDefault();
-
- virtual ~PubSubOwnerDefault();
+ class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload {
+ public:
- boost::shared_ptr<Form> getData() const {
- return data;
- }
+ PubSubOwnerDefault();
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
+ virtual ~PubSubOwnerDefault();
+ boost::shared_ptr<Form> getData() const {
+ return data;
+ }
- private:
- boost::shared_ptr<Form> data;
- };
+ void setData(boost::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ boost::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerDelete.h b/Swiften/Elements/PubSubOwnerDelete.h
index b4f60a2..7f908a1 100644
--- a/Swiften/Elements/PubSubOwnerDelete.h
+++ b/Swiften/Elements/PubSubOwnerDelete.h
@@ -17,32 +17,32 @@
#include <Swiften/Elements/PubSubOwnerRedirect.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerDelete : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerDelete();
- PubSubOwnerDelete(const std::string& node) : node(node) {}
- virtual ~PubSubOwnerDelete();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- boost::shared_ptr<PubSubOwnerRedirect> getRedirect() const {
- return redirect;
- }
-
- void setRedirect(boost::shared_ptr<PubSubOwnerRedirect> value) {
- this->redirect = value ;
- }
-
-
- private:
- std::string node;
- boost::shared_ptr<PubSubOwnerRedirect> redirect;
- };
+ class SWIFTEN_API PubSubOwnerDelete : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerDelete();
+ PubSubOwnerDelete(const std::string& node) : node(node) {}
+ virtual ~PubSubOwnerDelete();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ boost::shared_ptr<PubSubOwnerRedirect> getRedirect() const {
+ return redirect;
+ }
+
+ void setRedirect(boost::shared_ptr<PubSubOwnerRedirect> value) {
+ this->redirect = value ;
+ }
+
+
+ private:
+ std::string node;
+ boost::shared_ptr<PubSubOwnerRedirect> redirect;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerPayload.h b/Swiften/Elements/PubSubOwnerPayload.h
index 3a90d8e..8381a17 100644
--- a/Swiften/Elements/PubSubOwnerPayload.h
+++ b/Swiften/Elements/PubSubOwnerPayload.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerPayload : public Payload {
- public:
- virtual ~PubSubOwnerPayload();
- };
+ class SWIFTEN_API PubSubOwnerPayload : public Payload {
+ public:
+ virtual ~PubSubOwnerPayload();
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerPubSub.h b/Swiften/Elements/PubSubOwnerPubSub.h
index 50a4370..f3474cf 100644
--- a/Swiften/Elements/PubSubOwnerPubSub.h
+++ b/Swiften/Elements/PubSubOwnerPubSub.h
@@ -12,9 +12,9 @@
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerPubSub : public ContainerPayload<PubSubOwnerPayload> {
- public:
- PubSubOwnerPubSub();
- virtual ~PubSubOwnerPubSub();
- };
+ class SWIFTEN_API PubSubOwnerPubSub : public ContainerPayload<PubSubOwnerPayload> {
+ public:
+ PubSubOwnerPubSub();
+ virtual ~PubSubOwnerPubSub();
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerPurge.h b/Swiften/Elements/PubSubOwnerPurge.h
index 2b1b64f..aca48e1 100644
--- a/Swiften/Elements/PubSubOwnerPurge.h
+++ b/Swiften/Elements/PubSubOwnerPurge.h
@@ -14,23 +14,23 @@
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerPurge();
-
- virtual ~PubSubOwnerPurge();
+ class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload {
+ public:
- const std::string& getNode() const {
- return node;
- }
+ PubSubOwnerPurge();
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ virtual ~PubSubOwnerPurge();
+ const std::string& getNode() const {
+ return node;
+ }
- private:
- std::string node;
- };
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerRedirect.h b/Swiften/Elements/PubSubOwnerRedirect.h
index 7659889..c481f98 100644
--- a/Swiften/Elements/PubSubOwnerRedirect.h
+++ b/Swiften/Elements/PubSubOwnerRedirect.h
@@ -13,23 +13,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerRedirect : public Payload {
- public:
-
- PubSubOwnerRedirect();
-
- virtual ~PubSubOwnerRedirect();
+ class SWIFTEN_API PubSubOwnerRedirect : public Payload {
+ public:
- const std::string& getURI() const {
- return uri;
- }
+ PubSubOwnerRedirect();
- void setURI(const std::string& value) {
- this->uri = value ;
- }
+ virtual ~PubSubOwnerRedirect();
+ const std::string& getURI() const {
+ return uri;
+ }
- private:
- std::string uri;
- };
+ void setURI(const std::string& value) {
+ this->uri = value ;
+ }
+
+
+ private:
+ std::string uri;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerSubscription.h b/Swiften/Elements/PubSubOwnerSubscription.h
index 2b8964d..6a3fcc1 100644
--- a/Swiften/Elements/PubSubOwnerSubscription.h
+++ b/Swiften/Elements/PubSubOwnerSubscription.h
@@ -12,38 +12,38 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerSubscription : public Payload {
- public:
- enum SubscriptionType {
- None,
- Pending,
- Subscribed,
- Unconfigured
- };
-
- PubSubOwnerSubscription();
-
- virtual ~PubSubOwnerSubscription();
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- SubscriptionType getSubscription() const {
- return subscription;
- }
-
- void setSubscription(SubscriptionType value) {
- this->subscription = value ;
- }
-
-
- private:
- JID jid;
- SubscriptionType subscription;
- };
+ class SWIFTEN_API PubSubOwnerSubscription : public Payload {
+ public:
+ enum SubscriptionType {
+ None,
+ Pending,
+ Subscribed,
+ Unconfigured
+ };
+
+ PubSubOwnerSubscription();
+
+ virtual ~PubSubOwnerSubscription();
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ SubscriptionType getSubscription() const {
+ return subscription;
+ }
+
+ void setSubscription(SubscriptionType value) {
+ this->subscription = value ;
+ }
+
+
+ private:
+ JID jid;
+ SubscriptionType subscription;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerSubscriptions.h b/Swiften/Elements/PubSubOwnerSubscriptions.h
index caa5da8..44c31b8 100644
--- a/Swiften/Elements/PubSubOwnerSubscriptions.h
+++ b/Swiften/Elements/PubSubOwnerSubscriptions.h
@@ -18,36 +18,36 @@
#include <Swiften/Elements/PubSubOwnerSubscription.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerSubscriptions : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerSubscriptions();
-
- virtual ~PubSubOwnerSubscriptions();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& getSubscriptions() const {
- return subscriptions;
- }
-
- void setSubscriptions(const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& value) {
- this->subscriptions = value ;
- }
-
- void addSubscription(boost::shared_ptr<PubSubOwnerSubscription> value) {
- this->subscriptions.push_back(value);
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubOwnerSubscription> > subscriptions;
- };
+ class SWIFTEN_API PubSubOwnerSubscriptions : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerSubscriptions();
+
+ virtual ~PubSubOwnerSubscriptions();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& getSubscriptions() const {
+ return subscriptions;
+ }
+
+ void setSubscriptions(const std::vector< boost::shared_ptr<PubSubOwnerSubscription> >& value) {
+ this->subscriptions = value ;
+ }
+
+ void addSubscription(boost::shared_ptr<PubSubOwnerSubscription> value) {
+ this->subscriptions.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubOwnerSubscription> > subscriptions;
+ };
}
diff --git a/Swiften/Elements/PubSubPayload.h b/Swiften/Elements/PubSubPayload.h
index c0fb905..7fc1882 100644
--- a/Swiften/Elements/PubSubPayload.h
+++ b/Swiften/Elements/PubSubPayload.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubPayload : public Payload {
- public:
- virtual ~PubSubPayload();
- };
+ class SWIFTEN_API PubSubPayload : public Payload {
+ public:
+ virtual ~PubSubPayload();
+ };
}
diff --git a/Swiften/Elements/PubSubPublish.h b/Swiften/Elements/PubSubPublish.h
index 11a3ab2..a6fca8d 100644
--- a/Swiften/Elements/PubSubPublish.h
+++ b/Swiften/Elements/PubSubPublish.h
@@ -18,36 +18,36 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubPublish : public PubSubPayload {
- public:
-
- PubSubPublish();
-
- virtual ~PubSubPublish();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
- return items;
- }
-
- void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
- this->items = value ;
- }
-
- void addItem(boost::shared_ptr<PubSubItem> value) {
- this->items.push_back(value);
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubItem> > items;
- };
+ class SWIFTEN_API PubSubPublish : public PubSubPayload {
+ public:
+
+ PubSubPublish();
+
+ virtual ~PubSubPublish();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(boost::shared_ptr<PubSubItem> value) {
+ this->items.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubItem> > items;
+ };
}
diff --git a/Swiften/Elements/PubSubRetract.h b/Swiften/Elements/PubSubRetract.h
index 3863bef..60ceb28 100644
--- a/Swiften/Elements/PubSubRetract.h
+++ b/Swiften/Elements/PubSubRetract.h
@@ -18,45 +18,45 @@
#include <Swiften/Elements/PubSubPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubRetract : public PubSubPayload {
- public:
-
- PubSubRetract();
-
- virtual ~PubSubRetract();
-
- const std::string& getNode() const {
- return node;
- }
-
- void setNode(const std::string& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
- return items;
- }
-
- void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
- this->items = value ;
- }
-
- void addItem(boost::shared_ptr<PubSubItem> value) {
- this->items.push_back(value);
- }
-
- bool isNotify() const {
- return notify;
- }
-
- void setNotify(bool value) {
- this->notify = value ;
- }
-
-
- private:
- std::string node;
- std::vector< boost::shared_ptr<PubSubItem> > items;
- bool notify;
- };
+ class SWIFTEN_API PubSubRetract : public PubSubPayload {
+ public:
+
+ PubSubRetract();
+
+ virtual ~PubSubRetract();
+
+ const std::string& getNode() const {
+ return node;
+ }
+
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< boost::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(boost::shared_ptr<PubSubItem> value) {
+ this->items.push_back(value);
+ }
+
+ bool isNotify() const {
+ return notify;
+ }
+
+ void setNotify(bool value) {
+ this->notify = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::vector< boost::shared_ptr<PubSubItem> > items;
+ bool notify;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscribe.h b/Swiften/Elements/PubSubSubscribe.h
index fe4ecd3..8c57a21 100644
--- a/Swiften/Elements/PubSubSubscribe.h
+++ b/Swiften/Elements/PubSubSubscribe.h
@@ -19,41 +19,41 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubSubscribe : public PubSubPayload {
- public:
-
- PubSubSubscribe();
-
- virtual ~PubSubSubscribe();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- boost::shared_ptr<PubSubOptions> getOptions() const {
- return options;
- }
-
- void setOptions(boost::shared_ptr<PubSubOptions> value) {
- this->options = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- JID jid;
- boost::shared_ptr<PubSubOptions> options;
- };
+ class SWIFTEN_API PubSubSubscribe : public PubSubPayload {
+ public:
+
+ PubSubSubscribe();
+
+ virtual ~PubSubSubscribe();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ boost::shared_ptr<PubSubOptions> getOptions() const {
+ return options;
+ }
+
+ void setOptions(boost::shared_ptr<PubSubOptions> value) {
+ this->options = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ JID jid;
+ boost::shared_ptr<PubSubOptions> options;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscribeOptions.h b/Swiften/Elements/PubSubSubscribeOptions.h
index 4b168c7..c837787 100644
--- a/Swiften/Elements/PubSubSubscribeOptions.h
+++ b/Swiften/Elements/PubSubSubscribeOptions.h
@@ -11,23 +11,23 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubSubscribeOptions : public Payload {
- public:
-
- PubSubSubscribeOptions();
-
- virtual ~PubSubSubscribeOptions();
+ class SWIFTEN_API PubSubSubscribeOptions : public Payload {
+ public:
- bool isRequired() const {
- return required;
- }
+ PubSubSubscribeOptions();
- void setRequired(bool value) {
- this->required = value ;
- }
+ virtual ~PubSubSubscribeOptions();
+ bool isRequired() const {
+ return required;
+ }
- private:
- bool required;
- };
+ void setRequired(bool value) {
+ this->required = value ;
+ }
+
+
+ private:
+ bool required;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscription.h b/Swiften/Elements/PubSubSubscription.h
index bd27a83..5bb1194 100644
--- a/Swiften/Elements/PubSubSubscription.h
+++ b/Swiften/Elements/PubSubSubscription.h
@@ -19,65 +19,65 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubSubscription : public PubSubPayload {
- public:
- enum SubscriptionType {
- None,
- Pending,
- Subscribed,
- Unconfigured
- };
-
- PubSubSubscription();
-
- virtual ~PubSubSubscription();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const boost::optional< std::string >& getSubscriptionID() const {
- return subscriptionID;
- }
-
- void setSubscriptionID(const boost::optional< std::string >& value) {
- this->subscriptionID = value ;
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- boost::shared_ptr<PubSubSubscribeOptions> getOptions() const {
- return options;
- }
-
- void setOptions(boost::shared_ptr<PubSubSubscribeOptions> value) {
- this->options = value ;
- }
-
- SubscriptionType getSubscription() const {
- return subscription;
- }
-
- void setSubscription(SubscriptionType value) {
- this->subscription = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- boost::optional< std::string > subscriptionID;
- JID jid;
- boost::shared_ptr<PubSubSubscribeOptions> options;
- SubscriptionType subscription;
- };
+ class SWIFTEN_API PubSubSubscription : public PubSubPayload {
+ public:
+ enum SubscriptionType {
+ None,
+ Pending,
+ Subscribed,
+ Unconfigured
+ };
+
+ PubSubSubscription();
+
+ virtual ~PubSubSubscription();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const boost::optional< std::string >& getSubscriptionID() const {
+ return subscriptionID;
+ }
+
+ void setSubscriptionID(const boost::optional< std::string >& value) {
+ this->subscriptionID = value ;
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ boost::shared_ptr<PubSubSubscribeOptions> getOptions() const {
+ return options;
+ }
+
+ void setOptions(boost::shared_ptr<PubSubSubscribeOptions> value) {
+ this->options = value ;
+ }
+
+ SubscriptionType getSubscription() const {
+ return subscription;
+ }
+
+ void setSubscription(SubscriptionType value) {
+ this->subscription = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ boost::optional< std::string > subscriptionID;
+ JID jid;
+ boost::shared_ptr<PubSubSubscribeOptions> options;
+ SubscriptionType subscription;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscriptions.h b/Swiften/Elements/PubSubSubscriptions.h
index ae08471..63fc402 100644
--- a/Swiften/Elements/PubSubSubscriptions.h
+++ b/Swiften/Elements/PubSubSubscriptions.h
@@ -19,36 +19,36 @@
#include <Swiften/Elements/PubSubSubscription.h>
namespace Swift {
- class SWIFTEN_API PubSubSubscriptions : public PubSubPayload {
- public:
-
- PubSubSubscriptions();
- PubSubSubscriptions(const std::string& node) : node(node) {}
- virtual ~PubSubSubscriptions();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const std::vector< boost::shared_ptr<PubSubSubscription> >& getSubscriptions() const {
- return subscriptions;
- }
-
- void setSubscriptions(const std::vector< boost::shared_ptr<PubSubSubscription> >& value) {
- this->subscriptions = value ;
- }
-
- void addSubscription(boost::shared_ptr<PubSubSubscription> value) {
- this->subscriptions.push_back(value);
- }
-
-
- private:
- boost::optional< std::string > node;
- std::vector< boost::shared_ptr<PubSubSubscription> > subscriptions;
- };
+ class SWIFTEN_API PubSubSubscriptions : public PubSubPayload {
+ public:
+
+ PubSubSubscriptions();
+ PubSubSubscriptions(const std::string& node) : node(node) {}
+ virtual ~PubSubSubscriptions();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const std::vector< boost::shared_ptr<PubSubSubscription> >& getSubscriptions() const {
+ return subscriptions;
+ }
+
+ void setSubscriptions(const std::vector< boost::shared_ptr<PubSubSubscription> >& value) {
+ this->subscriptions = value ;
+ }
+
+ void addSubscription(boost::shared_ptr<PubSubSubscription> value) {
+ this->subscriptions.push_back(value);
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::vector< boost::shared_ptr<PubSubSubscription> > subscriptions;
+ };
}
diff --git a/Swiften/Elements/PubSubUnsubscribe.h b/Swiften/Elements/PubSubUnsubscribe.h
index 4ea44b0..305af9a 100644
--- a/Swiften/Elements/PubSubUnsubscribe.h
+++ b/Swiften/Elements/PubSubUnsubscribe.h
@@ -17,41 +17,41 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API PubSubUnsubscribe : public PubSubPayload {
- public:
-
- PubSubUnsubscribe();
-
- virtual ~PubSubUnsubscribe();
-
- const boost::optional< std::string >& getNode() const {
- return node;
- }
-
- void setNode(const boost::optional< std::string >& value) {
- this->node = value ;
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- void setJID(const JID& value) {
- this->jid = value ;
- }
-
- const boost::optional< std::string >& getSubscriptionID() const {
- return subscriptionID;
- }
-
- void setSubscriptionID(const boost::optional< std::string >& value) {
- this->subscriptionID = value ;
- }
-
-
- private:
- boost::optional< std::string > node;
- JID jid;
- boost::optional< std::string > subscriptionID;
- };
+ class SWIFTEN_API PubSubUnsubscribe : public PubSubPayload {
+ public:
+
+ PubSubUnsubscribe();
+
+ virtual ~PubSubUnsubscribe();
+
+ const boost::optional< std::string >& getNode() const {
+ return node;
+ }
+
+ void setNode(const boost::optional< std::string >& value) {
+ this->node = value ;
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ void setJID(const JID& value) {
+ this->jid = value ;
+ }
+
+ const boost::optional< std::string >& getSubscriptionID() const {
+ return subscriptionID;
+ }
+
+ void setSubscriptionID(const boost::optional< std::string >& value) {
+ this->subscriptionID = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ JID jid;
+ boost::optional< std::string > subscriptionID;
+ };
}
diff --git a/Swiften/Elements/RawXMLPayload.h b/Swiften/Elements/RawXMLPayload.h
index d1b104d..65901bc 100644
--- a/Swiften/Elements/RawXMLPayload.h
+++ b/Swiften/Elements/RawXMLPayload.h
@@ -12,19 +12,19 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API RawXMLPayload : public Payload {
- public:
- RawXMLPayload(const std::string& data = "") : rawXML_(data) {}
+ class SWIFTEN_API RawXMLPayload : public Payload {
+ public:
+ RawXMLPayload(const std::string& data = "") : rawXML_(data) {}
- void setRawXML(const std::string& data) {
- rawXML_ = data;
- }
+ void setRawXML(const std::string& data) {
+ rawXML_ = data;
+ }
- const std::string& getRawXML() const {
- return rawXML_;
- }
+ const std::string& getRawXML() const {
+ return rawXML_;
+ }
- private:
- std::string rawXML_;
- };
+ private:
+ std::string rawXML_;
+ };
}
diff --git a/Swiften/Elements/Replace.h b/Swiften/Elements/Replace.h
index 1152040..b64777f 100644
--- a/Swiften/Elements/Replace.h
+++ b/Swiften/Elements/Replace.h
@@ -20,17 +20,17 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Replace : public Payload {
- public:
- typedef boost::shared_ptr<Replace> ref;
- Replace(const std::string& id = std::string()) : replaceID_(id) {}
- const std::string& getID() const {
- return replaceID_;
- }
- void setID(const std::string& id) {
- replaceID_ = id;
- }
- private:
- std::string replaceID_;
- };
+ class SWIFTEN_API Replace : public Payload {
+ public:
+ typedef boost::shared_ptr<Replace> ref;
+ Replace(const std::string& id = std::string()) : replaceID_(id) {}
+ const std::string& getID() const {
+ return replaceID_;
+ }
+ void setID(const std::string& id) {
+ replaceID_ = id;
+ }
+ private:
+ std::string replaceID_;
+ };
}
diff --git a/Swiften/Elements/ResourceBind.h b/Swiften/Elements/ResourceBind.h
index 01d7e8b..fd6d4c7 100644
--- a/Swiften/Elements/ResourceBind.h
+++ b/Swiften/Elements/ResourceBind.h
@@ -8,33 +8,33 @@
#include <string>
-#include <Swiften/Base/API.h>
+#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API ResourceBind : public Payload {
- public:
- ResourceBind() {}
-
- void setJID(const JID& jid) {
- jid_ = jid;
- }
-
- const JID& getJID() const {
- return jid_;
- }
-
- void setResource(const std::string& resource) {
- resource_ = resource;
- }
-
- const std::string& getResource() const {
- return resource_;
- }
-
- private:
- JID jid_;
- std::string resource_;
- };
+ class SWIFTEN_API ResourceBind : public Payload {
+ public:
+ ResourceBind() {}
+
+ void setJID(const JID& jid) {
+ jid_ = jid;
+ }
+
+ const JID& getJID() const {
+ return jid_;
+ }
+
+ void setResource(const std::string& resource) {
+ resource_ = resource;
+ }
+
+ const std::string& getResource() const {
+ return resource_;
+ }
+
+ private:
+ JID jid_;
+ std::string resource_;
+ };
}
diff --git a/Swiften/Elements/ResultSet.h b/Swiften/Elements/ResultSet.h
index dc3692f..44995d1 100644
--- a/Swiften/Elements/ResultSet.h
+++ b/Swiften/Elements/ResultSet.h
@@ -12,43 +12,43 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API ResultSet : public Payload {
- public:
- virtual ~ResultSet();
+ class SWIFTEN_API ResultSet : public Payload {
+ public:
+ virtual ~ResultSet();
- void setMaxItems(const boost::optional<int>& maxItems) { maxItems_ = maxItems; }
- const boost::optional<int>& getMaxItems() const { return maxItems_; }
+ void setMaxItems(const boost::optional<int>& maxItems) { maxItems_ = maxItems; }
+ const boost::optional<int>& getMaxItems() const { return maxItems_; }
- void setCount(const boost::optional<int>& count) { count_ = count; }
- const boost::optional<int>& getCount() const { return count_; }
+ void setCount(const boost::optional<int>& count) { count_ = count; }
+ const boost::optional<int>& getCount() const { return count_; }
- void setIndex(const boost::optional<int>& index) { index_ = index; }
- const boost::optional<int>& getIndex() const { return index_; }
+ void setIndex(const boost::optional<int>& index) { index_ = index; }
+ const boost::optional<int>& getIndex() const { return index_; }
- void setFirstIDIndex(const boost::optional<int>& firstIndex) { firstIndex_ = firstIndex; }
- const boost::optional<int>& getFirstIDIndex() const { return firstIndex_; }
+ void setFirstIDIndex(const boost::optional<int>& firstIndex) { firstIndex_ = firstIndex; }
+ const boost::optional<int>& getFirstIDIndex() const { return firstIndex_; }
- void setFirstID(const boost::optional<std::string>& firstID) { firstID_ = firstID; }
- const boost::optional<std::string>& getFirstID() const { return firstID_; }
+ void setFirstID(const boost::optional<std::string>& firstID) { firstID_ = firstID; }
+ const boost::optional<std::string>& getFirstID() const { return firstID_; }
- void setLastID(const boost::optional<std::string>& lastID) { lastID_ = lastID; }
- const boost::optional<std::string>& getLastID() const { return lastID_; }
+ void setLastID(const boost::optional<std::string>& lastID) { lastID_ = lastID; }
+ const boost::optional<std::string>& getLastID() const { return lastID_; }
- void setBefore(const boost::optional<std::string>& before) { before_ = before; }
- const boost::optional<std::string>& getBefore() const { return before_; }
+ void setBefore(const boost::optional<std::string>& before) { before_ = before; }
+ const boost::optional<std::string>& getBefore() const { return before_; }
- void setAfter(const boost::optional<std::string>& after) { after_ = after; }
- const boost::optional<std::string>& getAfter() const { return after_; }
+ void setAfter(const boost::optional<std::string>& after) { after_ = after; }
+ const boost::optional<std::string>& getAfter() const { return after_; }
- private:
- boost::optional<int> maxItems_;
- boost::optional<int> count_;
- boost::optional<int> index_;
- boost::optional<int> firstIndex_;
- boost::optional<std::string> firstID_;
- boost::optional<std::string> lastID_;
- boost::optional<std::string> before_;
- boost::optional<std::string> after_;
- };
+ private:
+ boost::optional<int> maxItems_;
+ boost::optional<int> count_;
+ boost::optional<int> index_;
+ boost::optional<int> firstIndex_;
+ boost::optional<std::string> firstID_;
+ boost::optional<std::string> lastID_;
+ boost::optional<std::string> before_;
+ boost::optional<std::string> after_;
+ };
}
diff --git a/Swiften/Elements/RosterItemExchangePayload.h b/Swiften/Elements/RosterItemExchangePayload.h
index b1d9fe2..5090aff 100644
--- a/Swiften/Elements/RosterItemExchangePayload.h
+++ b/Swiften/Elements/RosterItemExchangePayload.h
@@ -22,73 +22,73 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API RosterItemExchangePayload : public Payload {
- public:
- typedef boost::shared_ptr<RosterItemExchangePayload> ref;
+ class SWIFTEN_API RosterItemExchangePayload : public Payload {
+ public:
+ typedef boost::shared_ptr<RosterItemExchangePayload> ref;
- class SWIFTEN_API Item {
- public:
- enum Action { Add, Modify, Delete };
+ class SWIFTEN_API Item {
+ public:
+ enum Action { Add, Modify, Delete };
- Item(Action action = Add);
+ Item(Action action = Add);
- Action getAction() const {
- return action;
- }
+ Action getAction() const {
+ return action;
+ }
- void setAction(Action action) {
- this->action = action;
- }
+ void setAction(Action action) {
+ this->action = action;
+ }
- const JID& getJID() const {
- return jid;
- }
+ const JID& getJID() const {
+ return jid;
+ }
- void setJID(const JID& jid) {
- this->jid = jid;
- }
+ void setJID(const JID& jid) {
+ this->jid = jid;
+ }
- const std::string& getName() const {
- return name;
- }
+ const std::string& getName() const {
+ return name;
+ }
- void setName(const std::string& name) {
- this->name = name;
- }
+ void setName(const std::string& name) {
+ this->name = name;
+ }
- const std::vector<std::string>& getGroups() const {
- return groups;
- }
+ const std::vector<std::string>& getGroups() const {
+ return groups;
+ }
- void setGroups(const std::vector<std::string> &groups) {
- this->groups = groups;
- }
+ void setGroups(const std::vector<std::string> &groups) {
+ this->groups = groups;
+ }
- void addGroup(const std::string& group) {
- groups.push_back(group);
- }
+ void addGroup(const std::string& group) {
+ groups.push_back(group);
+ }
- private:
- Action action;
- JID jid;
- std::string name;
- std::vector<std::string> groups;
- };
+ private:
+ Action action;
+ JID jid;
+ std::string name;
+ std::vector<std::string> groups;
+ };
- typedef std::vector<RosterItemExchangePayload::Item> RosterItemExchangePayloadItems;
+ typedef std::vector<RosterItemExchangePayload::Item> RosterItemExchangePayloadItems;
- public:
- RosterItemExchangePayload();
+ public:
+ RosterItemExchangePayload();
- void addItem(const RosterItemExchangePayload::Item& item) {
- items_.push_back(item);
- }
+ void addItem(const RosterItemExchangePayload::Item& item) {
+ items_.push_back(item);
+ }
- const RosterItemExchangePayloadItems& getItems() const {
- return items_;
- }
+ const RosterItemExchangePayloadItems& getItems() const {
+ return items_;
+ }
- private:
- RosterItemExchangePayloadItems items_;
- };
+ private:
+ RosterItemExchangePayloadItems items_;
+ };
}
diff --git a/Swiften/Elements/RosterItemPayload.h b/Swiften/Elements/RosterItemPayload.h
index 6fb6ebe..ea19fa5 100644
--- a/Swiften/Elements/RosterItemPayload.h
+++ b/Swiften/Elements/RosterItemPayload.h
@@ -13,40 +13,40 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API RosterItemPayload {
- public:
- enum Subscription { None, To, From, Both, Remove };
-
- RosterItemPayload() : subscription_(None), ask_(false) {}
- RosterItemPayload(const JID& jid, const std::string& name, Subscription subscription, const std::vector<std::string>& groups = std::vector<std::string>()) : jid_(jid), name_(name), subscription_(subscription), groups_(groups), ask_(false) { }
-
- void setJID(const JID& jid) { jid_ = jid; }
- const JID& getJID() const { return jid_; }
-
- void setName(const std::string& name) { name_ = name; }
- const std::string& getName() const { return name_; }
-
- void setSubscription(Subscription subscription) { subscription_ = subscription; }
- const Subscription& getSubscription() const { return subscription_; }
-
- void addGroup(const std::string& group) { groups_.push_back(group); }
- void setGroups(const std::vector<std::string>& groups) { groups_ = groups; }
- const std::vector<std::string>& getGroups() const { return groups_; }
-
- void setSubscriptionRequested() { ask_ = true; }
- bool getSubscriptionRequested() const { return ask_; }
-
- const std::string& getUnknownContent() const { return unknownContent_; }
- void addUnknownContent(const std::string& c) {
- unknownContent_ += c;
- }
-
- private:
- JID jid_;
- std::string name_;
- Subscription subscription_;
- std::vector<std::string> groups_;
- bool ask_;
- std::string unknownContent_;
- };
+ class SWIFTEN_API RosterItemPayload {
+ public:
+ enum Subscription { None, To, From, Both, Remove };
+
+ RosterItemPayload() : subscription_(None), ask_(false) {}
+ RosterItemPayload(const JID& jid, const std::string& name, Subscription subscription, const std::vector<std::string>& groups = std::vector<std::string>()) : jid_(jid), name_(name), subscription_(subscription), groups_(groups), ask_(false) { }
+
+ void setJID(const JID& jid) { jid_ = jid; }
+ const JID& getJID() const { return jid_; }
+
+ void setName(const std::string& name) { name_ = name; }
+ const std::string& getName() const { return name_; }
+
+ void setSubscription(Subscription subscription) { subscription_ = subscription; }
+ const Subscription& getSubscription() const { return subscription_; }
+
+ void addGroup(const std::string& group) { groups_.push_back(group); }
+ void setGroups(const std::vector<std::string>& groups) { groups_ = groups; }
+ const std::vector<std::string>& getGroups() const { return groups_; }
+
+ void setSubscriptionRequested() { ask_ = true; }
+ bool getSubscriptionRequested() const { return ask_; }
+
+ const std::string& getUnknownContent() const { return unknownContent_; }
+ void addUnknownContent(const std::string& c) {
+ unknownContent_ += c;
+ }
+
+ private:
+ JID jid_;
+ std::string name_;
+ Subscription subscription_;
+ std::vector<std::string> groups_;
+ bool ask_;
+ std::string unknownContent_;
+ };
}
diff --git a/Swiften/Elements/RosterPayload.cpp b/Swiften/Elements/RosterPayload.cpp
index d9bdc9a..b4be7d1 100644
--- a/Swiften/Elements/RosterPayload.cpp
+++ b/Swiften/Elements/RosterPayload.cpp
@@ -11,14 +11,14 @@
namespace Swift {
boost::optional<RosterItemPayload> RosterPayload::getItem(const JID& jid) const {
- foreach(const RosterItemPayload& 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>();
+ foreach(const RosterItemPayload& 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/RosterPayload.h b/Swiften/Elements/RosterPayload.h
index e205ce9..35e81cd 100644
--- a/Swiften/Elements/RosterPayload.h
+++ b/Swiften/Elements/RosterPayload.h
@@ -16,34 +16,34 @@
#include <Swiften/Elements/RosterItemPayload.h>
namespace Swift {
- class SWIFTEN_API RosterPayload : public Payload {
- public:
- typedef boost::shared_ptr<RosterPayload> ref;
- typedef std::vector<RosterItemPayload> RosterItemPayloads;
+ class SWIFTEN_API RosterPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<RosterPayload> ref;
+ typedef std::vector<RosterItemPayload> RosterItemPayloads;
- public:
- RosterPayload() {}
+ public:
+ RosterPayload() {}
- boost::optional<RosterItemPayload> getItem(const JID& jid) const;
+ boost::optional<RosterItemPayload> getItem(const JID& jid) const;
- void addItem(const RosterItemPayload& item) {
- items_.push_back(item);
- }
+ void addItem(const RosterItemPayload& item) {
+ items_.push_back(item);
+ }
- const RosterItemPayloads& getItems() const {
- return items_;
- }
+ const RosterItemPayloads& getItems() const {
+ return items_;
+ }
- const boost::optional<std::string>& getVersion() const {
- return version_;
- }
+ const boost::optional<std::string>& getVersion() const {
+ return version_;
+ }
- void setVersion(const std::string& version) {
- version_ = version;
- }
+ void setVersion(const std::string& version) {
+ version_ = version;
+ }
- private:
- RosterItemPayloads items_;
- boost::optional<std::string> version_;
- };
+ private:
+ RosterItemPayloads items_;
+ boost::optional<std::string> version_;
+ };
}
diff --git a/Swiften/Elements/S5BProxyRequest.h b/Swiften/Elements/S5BProxyRequest.h
index 2732f18..cbc7d5b 100644
--- a/Swiften/Elements/S5BProxyRequest.h
+++ b/Swiften/Elements/S5BProxyRequest.h
@@ -25,45 +25,45 @@ namespace Swift {
class SWIFTEN_API S5BProxyRequest : public Payload {
public:
- typedef boost::shared_ptr<S5BProxyRequest> ref;
+ typedef boost::shared_ptr<S5BProxyRequest> ref;
public:
- struct StreamHost {
- std::string host;
- int port;
- JID jid;
- };
+ struct StreamHost {
+ std::string host;
+ int port;
+ JID jid;
+ };
public:
- const boost::optional<StreamHost>& getStreamHost() const {
- return streamHost;
- }
+ const boost::optional<StreamHost>& getStreamHost() const {
+ return streamHost;
+ }
- void setStreamHost(const StreamHost& streamHost) {
- this->streamHost = boost::optional<StreamHost>(streamHost);
- }
+ void setStreamHost(const StreamHost& streamHost) {
+ this->streamHost = boost::optional<StreamHost>(streamHost);
+ }
- const std::string& getSID() const {
- return sid;
- }
+ const std::string& getSID() const {
+ return sid;
+ }
- void setSID(const std::string& sid) {
- this->sid = sid;
- }
+ void setSID(const std::string& sid) {
+ this->sid = sid;
+ }
- const boost::optional<JID>& getActivate() const {
- return activate;
- }
+ const boost::optional<JID>& getActivate() const {
+ return activate;
+ }
- void setActivate(const JID& activate) {
- this->activate = activate;
- }
+ void setActivate(const JID& activate) {
+ this->activate = activate;
+ }
private:
- boost::optional<StreamHost> streamHost;
+ boost::optional<StreamHost> streamHost;
- std::string sid;
- boost::optional<JID> activate;
+ std::string sid;
+ boost::optional<JID> activate;
};
}
diff --git a/Swiften/Elements/SearchPayload.h b/Swiften/Elements/SearchPayload.h
index 2ca6888..6784291 100644
--- a/Swiften/Elements/SearchPayload.h
+++ b/Swiften/Elements/SearchPayload.h
@@ -16,81 +16,81 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- /**
- * XEP-0055 search payload.
- */
- class SWIFTEN_API SearchPayload : public Payload {
- public:
- typedef boost::shared_ptr<SearchPayload> ref;
-
- struct Item {
- std::string first;
- std::string last;
- std::string nick;
- std::string email;
- JID jid;
- };
-
- SearchPayload() {}
-
- Form::ref getForm() const { return form; }
- void setForm(Form::ref f) { form = f; }
-
- const boost::optional<std::string>& getInstructions() const {
- return instructions;
- }
-
- const boost::optional<std::string>& getNick() const {
- return nick;
- }
-
- const boost::optional<std::string>& getFirst() const {
- return first;
- }
-
- const boost::optional<std::string>& getLast() const {
- return last;
- }
-
- const boost::optional<std::string>& getEMail() const {
- return email;
- }
-
- void setInstructions(const std::string& v) {
- this->instructions = v;
- }
-
- void setNick(const std::string& v) {
- this->nick = v;
- }
-
- void setFirst(const std::string& v) {
- this->first = v;
- }
-
- void setLast(const std::string& v) {
- this->last = v;
- }
-
- void setEMail(const std::string& v) {
- this->email = v;
- }
-
- const std::vector<Item>& getItems() const {
- return items;
- }
-
- void addItem(const Item& item) {
- items.push_back(item);
- }
-
- private:
- Form::ref form;
- boost::optional<std::string> instructions;
- boost::optional<std::string> nick;
- boost::optional<std::string> first;
- boost::optional<std::string> last;
- boost::optional<std::string> email;
- std::vector<Item> items;
- };
+ /**
+ * XEP-0055 search payload.
+ */
+ class SWIFTEN_API SearchPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<SearchPayload> ref;
+
+ struct Item {
+ std::string first;
+ std::string last;
+ std::string nick;
+ std::string email;
+ JID jid;
+ };
+
+ SearchPayload() {}
+
+ Form::ref getForm() const { return form; }
+ void setForm(Form::ref f) { form = f; }
+
+ const boost::optional<std::string>& getInstructions() const {
+ return instructions;
+ }
+
+ const boost::optional<std::string>& getNick() const {
+ return nick;
+ }
+
+ const boost::optional<std::string>& getFirst() const {
+ return first;
+ }
+
+ const boost::optional<std::string>& getLast() const {
+ return last;
+ }
+
+ const boost::optional<std::string>& getEMail() const {
+ return email;
+ }
+
+ void setInstructions(const std::string& v) {
+ this->instructions = v;
+ }
+
+ void setNick(const std::string& v) {
+ this->nick = v;
+ }
+
+ void setFirst(const std::string& v) {
+ this->first = v;
+ }
+
+ void setLast(const std::string& v) {
+ this->last = v;
+ }
+
+ void setEMail(const std::string& v) {
+ this->email = v;
+ }
+
+ const std::vector<Item>& getItems() const {
+ return items;
+ }
+
+ void addItem(const Item& item) {
+ items.push_back(item);
+ }
+
+ private:
+ Form::ref form;
+ boost::optional<std::string> instructions;
+ boost::optional<std::string> nick;
+ boost::optional<std::string> first;
+ boost::optional<std::string> last;
+ boost::optional<std::string> email;
+ std::vector<Item> items;
+ };
}
diff --git a/Swiften/Elements/SecurityLabel.h b/Swiften/Elements/SecurityLabel.h
index b018620..748c65e 100644
--- a/Swiften/Elements/SecurityLabel.h
+++ b/Swiften/Elements/SecurityLabel.h
@@ -14,63 +14,63 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API SecurityLabel : public Payload {
- public:
-
- SecurityLabel();
-
- virtual ~SecurityLabel();
-
- const std::vector< std::string >& getEquivalentLabels() const {
- return equivalentLabels;
- }
-
- void setEquivalentLabels(const std::vector< std::string >& value) {
- this->equivalentLabels = value ;
- }
-
- void addEquivalentLabel(const std::string& value) {
- this->equivalentLabels.push_back(value);
- }
-
- const std::string& getForegroundColor() const {
- return foregroundColor;
- }
-
- void setForegroundColor(const std::string& value) {
- this->foregroundColor = value ;
- }
-
- const std::string& getDisplayMarking() const {
- return displayMarking;
- }
-
- void setDisplayMarking(const std::string& value) {
- this->displayMarking = value ;
- }
-
- const std::string& getBackgroundColor() const {
- return backgroundColor;
- }
-
- void setBackgroundColor(const std::string& value) {
- this->backgroundColor = value ;
- }
-
- const std::string& getLabel() const {
- return label;
- }
-
- void setLabel(const std::string& value) {
- this->label = value ;
- }
-
-
- private:
- std::vector< std::string > equivalentLabels;
- std::string foregroundColor;
- std::string displayMarking;
- std::string backgroundColor;
- std::string label;
- };
+ class SWIFTEN_API SecurityLabel : public Payload {
+ public:
+
+ SecurityLabel();
+
+ virtual ~SecurityLabel();
+
+ const std::vector< std::string >& getEquivalentLabels() const {
+ return equivalentLabels;
+ }
+
+ void setEquivalentLabels(const std::vector< std::string >& value) {
+ this->equivalentLabels = value ;
+ }
+
+ void addEquivalentLabel(const std::string& value) {
+ this->equivalentLabels.push_back(value);
+ }
+
+ const std::string& getForegroundColor() const {
+ return foregroundColor;
+ }
+
+ void setForegroundColor(const std::string& value) {
+ this->foregroundColor = value ;
+ }
+
+ const std::string& getDisplayMarking() const {
+ return displayMarking;
+ }
+
+ void setDisplayMarking(const std::string& value) {
+ this->displayMarking = value ;
+ }
+
+ const std::string& getBackgroundColor() const {
+ return backgroundColor;
+ }
+
+ void setBackgroundColor(const std::string& value) {
+ this->backgroundColor = value ;
+ }
+
+ const std::string& getLabel() const {
+ return label;
+ }
+
+ void setLabel(const std::string& value) {
+ this->label = value ;
+ }
+
+
+ private:
+ std::vector< std::string > equivalentLabels;
+ std::string foregroundColor;
+ std::string displayMarking;
+ std::string backgroundColor;
+ std::string label;
+ };
}
diff --git a/Swiften/Elements/SecurityLabelsCatalog.h b/Swiften/Elements/SecurityLabelsCatalog.h
index cdcfca3..8e6db64 100644
--- a/Swiften/Elements/SecurityLabelsCatalog.h
+++ b/Swiften/Elements/SecurityLabelsCatalog.h
@@ -17,74 +17,74 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API SecurityLabelsCatalog : public Payload {
- public:
- typedef boost::shared_ptr<SecurityLabelsCatalog> ref;
- class Item {
- public:
- Item() : default_(false) {}
- boost::shared_ptr<SecurityLabel> getLabel() const {
- return label_;
- }
-
- void setLabel(boost::shared_ptr<SecurityLabel> label) {
- label_ = label;
- }
-
- const std::string& getSelector() const { return selector_; }
-
- void setSelector(const std::string& selector) {
- selector_ = selector;
- }
-
- bool getIsDefault() const { return default_; }
-
- void setIsDefault(bool isDefault) {
- default_ = isDefault;
- }
- private:
- boost::shared_ptr<SecurityLabel> label_;
- std::string selector_;
- bool default_;
- };
- SecurityLabelsCatalog(const JID& to = JID()) : to_(to) {}
-
- const std::vector<Item>& getItems() const {
- return items_;
- }
-
- void addItem(const Item& item) {
- items_.push_back(item);
- }
-
- const JID& getTo() const {
- return to_;
- }
-
- void setTo(const JID& to) {
- to_ = to;
- }
-
- const std::string& getName() const {
- return name_;
- }
-
- void setName(const std::string& name) {
- name_ = name;
- }
-
- const std::string& getDescription() const {
- return description_;
- }
-
- void setDescription(const std::string& description) {
- description_ = description;
- }
-
- private:
- JID to_;
- std::string name_;
- std::string description_;
- std::vector<Item> items_;
- };
+ class SWIFTEN_API SecurityLabelsCatalog : public Payload {
+ public:
+ typedef boost::shared_ptr<SecurityLabelsCatalog> ref;
+ class Item {
+ public:
+ Item() : default_(false) {}
+ boost::shared_ptr<SecurityLabel> getLabel() const {
+ return label_;
+ }
+
+ void setLabel(boost::shared_ptr<SecurityLabel> label) {
+ label_ = label;
+ }
+
+ const std::string& getSelector() const { return selector_; }
+
+ void setSelector(const std::string& selector) {
+ selector_ = selector;
+ }
+
+ bool getIsDefault() const { return default_; }
+
+ void setIsDefault(bool isDefault) {
+ default_ = isDefault;
+ }
+ private:
+ boost::shared_ptr<SecurityLabel> label_;
+ std::string selector_;
+ bool default_;
+ };
+ SecurityLabelsCatalog(const JID& to = JID()) : to_(to) {}
+
+ const std::vector<Item>& getItems() const {
+ return items_;
+ }
+
+ void addItem(const Item& item) {
+ items_.push_back(item);
+ }
+
+ const JID& getTo() const {
+ return to_;
+ }
+
+ void setTo(const JID& to) {
+ to_ = to;
+ }
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ void setName(const std::string& name) {
+ name_ = name;
+ }
+
+ const std::string& getDescription() const {
+ return description_;
+ }
+
+ void setDescription(const std::string& description) {
+ description_ = description;
+ }
+
+ private:
+ JID to_;
+ std::string name_;
+ std::string description_;
+ std::vector<Item> items_;
+ };
}
diff --git a/Swiften/Elements/SoftwareVersion.h b/Swiften/Elements/SoftwareVersion.h
index f906223..57318b9 100644
--- a/Swiften/Elements/SoftwareVersion.h
+++ b/Swiften/Elements/SoftwareVersion.h
@@ -14,43 +14,43 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API SoftwareVersion : public Payload {
- public:
- typedef boost::shared_ptr<SoftwareVersion> ref;
-
- SoftwareVersion(
- const std::string& name = "",
- const std::string& version = "",
- const std::string& os = "") :
- name_(name), version_(version), os_(os) {}
-
- const std::string& getName() const {
- return name_;
- }
-
- void setName(const std::string& name) {
- name_ = name;
- }
-
- const std::string& getVersion() const {
- return version_;
- }
-
- void setVersion(const std::string& version) {
- version_ = version;
- }
-
- const std::string& getOS() const {
- return os_;
- }
-
- void setOS(const std::string& os) {
- os_ = os;
- }
-
- private:
- std::string name_;
- std::string version_;
- std::string os_;
- };
+ class SWIFTEN_API SoftwareVersion : public Payload {
+ public:
+ typedef boost::shared_ptr<SoftwareVersion> ref;
+
+ SoftwareVersion(
+ const std::string& name = "",
+ const std::string& version = "",
+ const std::string& os = "") :
+ name_(name), version_(version), os_(os) {}
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ void setName(const std::string& name) {
+ name_ = name;
+ }
+
+ const std::string& getVersion() const {
+ return version_;
+ }
+
+ void setVersion(const std::string& version) {
+ version_ = version;
+ }
+
+ const std::string& getOS() const {
+ return os_;
+ }
+
+ void setOS(const std::string& os) {
+ os_ = os;
+ }
+
+ private:
+ std::string name_;
+ std::string version_;
+ std::string os_;
+ };
}
diff --git a/Swiften/Elements/Stanza.cpp b/Swiften/Elements/Stanza.cpp
index f385e1c..617be4e 100644
--- a/Swiften/Elements/Stanza.cpp
+++ b/Swiften/Elements/Stanza.cpp
@@ -17,53 +17,53 @@ namespace Swift {
Stanza::Stanza() {
}
-
+
Stanza::~Stanza() {
- payloads_.clear();
+ payloads_.clear();
}
void Stanza::updatePayload(boost::shared_ptr<Payload> payload) {
- foreach (boost::shared_ptr<Payload>& i, payloads_) {
- if (typeid(*i.get()) == typeid(*payload.get())) {
- i = payload;
- return;
- }
- }
- addPayload(payload);
+ foreach (boost::shared_ptr<Payload>& i, payloads_) {
+ if (typeid(*i.get()) == typeid(*payload.get())) {
+ i = payload;
+ return;
+ }
+ }
+ addPayload(payload);
}
static bool sameType(boost::shared_ptr<Payload> a, boost::shared_ptr<Payload> b) {
- return typeid(*a.get()) == typeid(*b.get());
+ return typeid(*a.get()) == typeid(*b.get());
}
void Stanza::removePayloadOfSameType(boost::shared_ptr<Payload> payload) {
- payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(),
- boost::bind<bool>(&sameType, payload, _1)),
- payloads_.end());
+ payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(),
+ boost::bind<bool>(&sameType, payload, _1)),
+ payloads_.end());
}
boost::shared_ptr<Payload> Stanza::getPayloadOfSameType(boost::shared_ptr<Payload> payload) const {
- foreach (const boost::shared_ptr<Payload>& i, payloads_) {
- if (typeid(*i.get()) == typeid(*payload.get())) {
- return i;
- }
- }
- return boost::shared_ptr<Payload>();
+ foreach (const boost::shared_ptr<Payload>& i, payloads_) {
+ if (typeid(*i.get()) == typeid(*payload.get())) {
+ return i;
+ }
+ }
+ return boost::shared_ptr<Payload>();
}
boost::optional<boost::posix_time::ptime> Stanza::getTimestamp() const {
- boost::shared_ptr<Delay> delay = getPayload<Delay>();
- return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>();
+ boost::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< boost::shared_ptr<Delay> > delays = getPayloads<Delay>();
- for (size_t i = 0; i < delays.size(); ++i) {
- if (delays[i]->getFrom() == jid) {
- return delays[i]->getStamp();
- }
- }
- return getTimestamp();
+ std::vector< boost::shared_ptr<Delay> > delays = getPayloads<Delay>();
+ for (size_t i = 0; i < delays.size(); ++i) {
+ if (delays[i]->getFrom() == jid) {
+ return delays[i]->getStamp();
+ }
+ }
+ return getTimestamp();
}
diff --git a/Swiften/Elements/Stanza.h b/Swiften/Elements/Stanza.h
index 8da6280..765aca8 100644
--- a/Swiften/Elements/Stanza.h
+++ b/Swiften/Elements/Stanza.h
@@ -18,79 +18,79 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class Payload;
-
- class SWIFTEN_API Stanza : public ToplevelElement {
- public:
- typedef boost::shared_ptr<Stanza> ref;
-
- protected:
- Stanza();
-
- public:
- virtual ~Stanza();
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Stanza)
-
- template<typename T>
- boost::shared_ptr<T> getPayload() const {
- for (size_t i = 0; i < payloads_.size(); ++i) {
- boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i]));
- if (result) {
- return result;
- }
- }
- return boost::shared_ptr<T>();
- }
-
- template<typename T>
- std::vector< boost::shared_ptr<T> > getPayloads() const {
- std::vector< boost::shared_ptr<T> > results;
- for (size_t i = 0; i < payloads_.size(); ++i) {
- boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i]));
- if (result) {
- results.push_back(result);
- }
- }
- return results;
- }
-
-
- const std::vector< boost::shared_ptr<Payload> >& getPayloads() const {
- return payloads_;
- }
-
- void addPayload(boost::shared_ptr<Payload> payload) {
- payloads_.push_back(payload);
- }
-
- template<typename InputIterator>
- void addPayloads(InputIterator begin, InputIterator end) {
- payloads_.insert(payloads_.end(), begin, end);
- }
-
- void updatePayload(boost::shared_ptr<Payload> payload);
-
- void removePayloadOfSameType(boost::shared_ptr<Payload>);
- boost::shared_ptr<Payload> getPayloadOfSameType(boost::shared_ptr<Payload>) const;
-
- const JID& getFrom() const { return from_; }
- void setFrom(const JID& from) { from_ = from; }
-
- const JID& getTo() const { return to_; }
- void setTo(const JID& to) { to_ = to; }
-
- const std::string& getID() const { return id_; }
- void setID(const std::string& id) { id_ = id; }
-
- boost::optional<boost::posix_time::ptime> getTimestamp() const;
-
- // Falls back to any timestamp if no specific timestamp for the given JID is found.
- boost::optional<boost::posix_time::ptime> getTimestampFrom(const JID& jid) const;
-
- private:
- std::string id_;
- JID from_;
- JID to_;
- std::vector< boost::shared_ptr<Payload> > payloads_;
- };
+ class Payload;
+
+ class SWIFTEN_API Stanza : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<Stanza> ref;
+
+ protected:
+ Stanza();
+
+ public:
+ virtual ~Stanza();
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Stanza)
+
+ template<typename T>
+ boost::shared_ptr<T> getPayload() const {
+ for (size_t i = 0; i < payloads_.size(); ++i) {
+ boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i]));
+ if (result) {
+ return result;
+ }
+ }
+ return boost::shared_ptr<T>();
+ }
+
+ template<typename T>
+ std::vector< boost::shared_ptr<T> > getPayloads() const {
+ std::vector< boost::shared_ptr<T> > results;
+ for (size_t i = 0; i < payloads_.size(); ++i) {
+ boost::shared_ptr<T> result(boost::dynamic_pointer_cast<T>(payloads_[i]));
+ if (result) {
+ results.push_back(result);
+ }
+ }
+ return results;
+ }
+
+
+ const std::vector< boost::shared_ptr<Payload> >& getPayloads() const {
+ return payloads_;
+ }
+
+ void addPayload(boost::shared_ptr<Payload> payload) {
+ payloads_.push_back(payload);
+ }
+
+ template<typename InputIterator>
+ void addPayloads(InputIterator begin, InputIterator end) {
+ payloads_.insert(payloads_.end(), begin, end);
+ }
+
+ void updatePayload(boost::shared_ptr<Payload> payload);
+
+ void removePayloadOfSameType(boost::shared_ptr<Payload>);
+ boost::shared_ptr<Payload> getPayloadOfSameType(boost::shared_ptr<Payload>) const;
+
+ const JID& getFrom() const { return from_; }
+ void setFrom(const JID& from) { from_ = from; }
+
+ const JID& getTo() const { return to_; }
+ void setTo(const JID& to) { to_ = to; }
+
+ const std::string& getID() const { return id_; }
+ void setID(const std::string& id) { id_ = id; }
+
+ boost::optional<boost::posix_time::ptime> getTimestamp() const;
+
+ // Falls back to any timestamp if no specific timestamp for the given JID is found.
+ boost::optional<boost::posix_time::ptime> getTimestampFrom(const JID& jid) const;
+
+ private:
+ std::string id_;
+ JID from_;
+ JID to_;
+ std::vector< boost::shared_ptr<Payload> > payloads_;
+ };
}
diff --git a/Swiften/Elements/StanzaAck.cpp b/Swiften/Elements/StanzaAck.cpp
index 2dbff41..bd0b78d 100644
--- a/Swiften/Elements/StanzaAck.cpp
+++ b/Swiften/Elements/StanzaAck.cpp
@@ -14,6 +14,6 @@ StanzaAck::~StanzaAck() {
}
void StanzaAck::setHandledStanzasCount(int i) {
- handledStanzasCount = boost::numeric_cast<unsigned int>(i);
- valid = true;
+ handledStanzasCount = boost::numeric_cast<unsigned int>(i);
+ valid = true;
}
diff --git a/Swiften/Elements/StanzaAck.h b/Swiften/Elements/StanzaAck.h
index d976802..45680c0 100644
--- a/Swiften/Elements/StanzaAck.h
+++ b/Swiften/Elements/StanzaAck.h
@@ -12,26 +12,26 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StanzaAck : public ToplevelElement {
- public:
- typedef boost::shared_ptr<StanzaAck> ref;
+ class SWIFTEN_API StanzaAck : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<StanzaAck> ref;
- StanzaAck() : valid(false), handledStanzasCount(0) {}
- StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {}
- virtual ~StanzaAck();
+ StanzaAck() : valid(false), handledStanzasCount(0) {}
+ StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {}
+ virtual ~StanzaAck();
- unsigned int getHandledStanzasCount() const {
- return handledStanzasCount;
- }
+ unsigned int getHandledStanzasCount() const {
+ return handledStanzasCount;
+ }
- void setHandledStanzasCount(int i);
+ void setHandledStanzasCount(int i);
- bool isValid() const {
- return valid;
- }
+ bool isValid() const {
+ return valid;
+ }
- private:
- bool valid;
- unsigned int handledStanzasCount;
- };
+ private:
+ bool valid;
+ unsigned int handledStanzasCount;
+ };
}
diff --git a/Swiften/Elements/StanzaAckRequest.h b/Swiften/Elements/StanzaAckRequest.h
index dc3bf32..e9b95b5 100644
--- a/Swiften/Elements/StanzaAckRequest.h
+++ b/Swiften/Elements/StanzaAckRequest.h
@@ -10,6 +10,6 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StanzaAckRequest : public ToplevelElement {
- };
+ class SWIFTEN_API StanzaAckRequest : public ToplevelElement {
+ };
}
diff --git a/Swiften/Elements/StartSession.h b/Swiften/Elements/StartSession.h
index ea934da..a40865e 100644
--- a/Swiften/Elements/StartSession.h
+++ b/Swiften/Elements/StartSession.h
@@ -12,8 +12,8 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API StartSession : public Payload {
- public:
- StartSession() {}
- };
+ class SWIFTEN_API StartSession : public Payload {
+ public:
+ StartSession() {}
+ };
}
diff --git a/Swiften/Elements/StartTLSFailure.h b/Swiften/Elements/StartTLSFailure.h
index 1477962..5867e3f 100644
--- a/Swiften/Elements/StartTLSFailure.h
+++ b/Swiften/Elements/StartTLSFailure.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StartTLSFailure : public ToplevelElement {
- public:
- StartTLSFailure() {}
- };
+ class SWIFTEN_API StartTLSFailure : public ToplevelElement {
+ public:
+ StartTLSFailure() {}
+ };
}
diff --git a/Swiften/Elements/StartTLSRequest.h b/Swiften/Elements/StartTLSRequest.h
index 648eef7..f47a21d 100644
--- a/Swiften/Elements/StartTLSRequest.h
+++ b/Swiften/Elements/StartTLSRequest.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StartTLSRequest : public ToplevelElement {
- public:
- StartTLSRequest() {}
- };
+ class SWIFTEN_API StartTLSRequest : public ToplevelElement {
+ public:
+ StartTLSRequest() {}
+ };
}
diff --git a/Swiften/Elements/Status.h b/Swiften/Elements/Status.h
index 58e17d6..2fd2eff 100644
--- a/Swiften/Elements/Status.h
+++ b/Swiften/Elements/Status.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Status : public Payload {
- public:
- Status(const std::string& text = "") : text_(text) {
- }
+ class SWIFTEN_API Status : public Payload {
+ public:
+ Status(const std::string& text = "") : text_(text) {
+ }
- void setText(const std::string& text) {
- text_ = text;
- }
+ void setText(const std::string& text) {
+ text_ = text;
+ }
- const std::string& getText() const {
- return text_;
- }
+ const std::string& getText() const {
+ return text_;
+ }
- private:
- std::string text_;
- };
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Elements/StatusShow.h b/Swiften/Elements/StatusShow.h
index 84be286..b339fa1 100644
--- a/Swiften/Elements/StatusShow.h
+++ b/Swiften/Elements/StatusShow.h
@@ -12,38 +12,38 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API StatusShow : public Payload {
- public:
- enum Type { Online, Away, FFC, XA, DND, None };
-
- StatusShow(const Type& type = Online);
-
- void setType(const Type& type) {
- type_ = type;
- }
-
- const Type& getType() const {
- return type_;
- }
-
- /**
- * Can be used for rough ordering of Types.
- * Greater magnitude = more available.
- */
- static int typeToAvailabilityOrdering(Type type) {
- switch (type) {
- case Online: return 4;
- case FFC: return 5;
- case Away: return 2;
- case XA: return 1;
- case DND: return 3;
- case None: return 0;
- }
- assert(false);
- return 0;
- }
-
- private:
- Type type_;
- };
+ class SWIFTEN_API StatusShow : public Payload {
+ public:
+ enum Type { Online, Away, FFC, XA, DND, None };
+
+ StatusShow(const Type& type = Online);
+
+ void setType(const Type& type) {
+ type_ = type;
+ }
+
+ const Type& getType() const {
+ return type_;
+ }
+
+ /**
+ * Can be used for rough ordering of Types.
+ * Greater magnitude = more available.
+ */
+ static int typeToAvailabilityOrdering(Type type) {
+ switch (type) {
+ case Online: return 4;
+ case FFC: return 5;
+ case Away: return 2;
+ case XA: return 1;
+ case DND: return 3;
+ case None: return 0;
+ }
+ assert(false);
+ return 0;
+ }
+
+ private:
+ Type type_;
+ };
}
diff --git a/Swiften/Elements/Storage.h b/Swiften/Elements/Storage.h
index 7de303d..87cfb39 100644
--- a/Swiften/Elements/Storage.h
+++ b/Swiften/Elements/Storage.h
@@ -17,51 +17,51 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API Storage : public Payload {
- public:
- struct Room {
- Room() : autoJoin(false) {}
-
- std::string name;
- JID jid;
- bool autoJoin;
- std::string nick;
- boost::optional<std::string> password;
- };
-
- struct URL {
- URL() {}
-
- std::string name;
- std::string url;
- };
-
- Storage() {
- }
-
-
- void clearRooms() {
- rooms.clear();
- }
-
- const std::vector<Room>& getRooms() const {
- return rooms;
- }
-
- void addRoom(const Room& room) {
- rooms.push_back(room);
- }
-
- const std::vector<URL>& getURLs() const {
- return urls;
- }
-
- void addURL(const URL& url) {
- urls.push_back(url);
- }
-
- private:
- std::vector<Room> rooms;
- std::vector<URL> urls;
- };
+ class SWIFTEN_API Storage : public Payload {
+ public:
+ struct Room {
+ Room() : autoJoin(false) {}
+
+ std::string name;
+ JID jid;
+ bool autoJoin;
+ std::string nick;
+ boost::optional<std::string> password;
+ };
+
+ struct URL {
+ URL() {}
+
+ std::string name;
+ std::string url;
+ };
+
+ Storage() {
+ }
+
+
+ void clearRooms() {
+ rooms.clear();
+ }
+
+ const std::vector<Room>& getRooms() const {
+ return rooms;
+ }
+
+ void addRoom(const Room& room) {
+ rooms.push_back(room);
+ }
+
+ const std::vector<URL>& getURLs() const {
+ return urls;
+ }
+
+ void addURL(const URL& url) {
+ urls.push_back(url);
+ }
+
+ private:
+ std::vector<Room> rooms;
+ std::vector<URL> urls;
+ };
}
diff --git a/Swiften/Elements/StreamError.h b/Swiften/Elements/StreamError.h
index e7e7309..ce57134 100644
--- a/Swiften/Elements/StreamError.h
+++ b/Swiften/Elements/StreamError.h
@@ -14,58 +14,58 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamError : public ToplevelElement {
- public:
- typedef boost::shared_ptr<StreamError> ref;
+ class SWIFTEN_API StreamError : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<StreamError> ref;
- enum Type {
- BadFormat,
- BadNamespacePrefix,
- Conflict,
- ConnectionTimeout,
- HostGone,
- HostUnknown,
- ImproperAddressing,
- InternalServerError,
- InvalidFrom,
- InvalidID,
- InvalidNamespace,
- InvalidXML,
- NotAuthorized,
- NotWellFormed,
- PolicyViolation,
- RemoteConnectionFailed,
- Reset,
- ResourceConstraint,
- RestrictedXML,
- SeeOtherHost,
- SystemShutdown,
- UndefinedCondition,
- UnsupportedEncoding,
- UnsupportedStanzaType,
- UnsupportedVersion
- };
+ enum Type {
+ BadFormat,
+ BadNamespacePrefix,
+ Conflict,
+ ConnectionTimeout,
+ HostGone,
+ HostUnknown,
+ ImproperAddressing,
+ InternalServerError,
+ InvalidFrom,
+ InvalidID,
+ InvalidNamespace,
+ InvalidXML,
+ NotAuthorized,
+ NotWellFormed,
+ PolicyViolation,
+ RemoteConnectionFailed,
+ Reset,
+ ResourceConstraint,
+ RestrictedXML,
+ SeeOtherHost,
+ SystemShutdown,
+ UndefinedCondition,
+ UnsupportedEncoding,
+ UnsupportedStanzaType,
+ UnsupportedVersion
+ };
- StreamError(Type type = UndefinedCondition, const std::string& text = std::string()) : type_(type), text_(text) { }
+ StreamError(Type type = UndefinedCondition, const std::string& text = std::string()) : type_(type), text_(text) { }
- Type getType() const {
- return type_;
- }
+ Type getType() const {
+ return type_;
+ }
- void setType(Type type) {
- type_ = type;
- }
+ void setType(Type type) {
+ type_ = type;
+ }
- void setText(const std::string& text) {
- text_ = text;
- }
+ void setText(const std::string& text) {
+ text_ = text;
+ }
- const std::string& getText() const {
- return text_;
- }
+ const std::string& getText() const {
+ return text_;
+ }
- private:
- Type type_;
- std::string text_;
- };
+ private:
+ Type type_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Elements/StreamFeatures.cpp b/Swiften/Elements/StreamFeatures.cpp
index 0acc417..77bafac 100644
--- a/Swiften/Elements/StreamFeatures.cpp
+++ b/Swiften/Elements/StreamFeatures.cpp
@@ -11,11 +11,11 @@
namespace Swift {
bool StreamFeatures::hasCompressionMethod(const std::string& mechanism) const {
- return std::find(compressionMethods_.begin(), compressionMethods_.end(), mechanism) != compressionMethods_.end();
+ return std::find(compressionMethods_.begin(), compressionMethods_.end(), mechanism) != compressionMethods_.end();
}
bool StreamFeatures::hasAuthenticationMechanism(const std::string& mechanism) const {
- return std::find(authenticationMechanisms_.begin(), authenticationMechanisms_.end(), mechanism) != authenticationMechanisms_.end();
+ return std::find(authenticationMechanisms_.begin(), authenticationMechanisms_.end(), mechanism) != authenticationMechanisms_.end();
}
}
diff --git a/Swiften/Elements/StreamFeatures.h b/Swiften/Elements/StreamFeatures.h
index 7a9d936..1d07a16 100644
--- a/Swiften/Elements/StreamFeatures.h
+++ b/Swiften/Elements/StreamFeatures.h
@@ -16,92 +16,92 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamFeatures : public ToplevelElement {
- public:
- typedef boost::shared_ptr<StreamFeatures> ref;
-
- StreamFeatures() : hasStartTLS_(false), hasResourceBind_(false), hasSession_(false), hasStreamManagement_(false), hasRosterVersioning_(false) {}
-
- void setHasStartTLS() {
- hasStartTLS_ = true;
- }
-
- bool hasStartTLS() const {
- return hasStartTLS_;
- }
-
- void setHasSession() {
- hasSession_ = true;
- }
-
- bool hasSession() const {
- return hasSession_;
- }
-
- void setHasResourceBind() {
- hasResourceBind_ = true;
- }
-
- bool hasResourceBind() const {
- return hasResourceBind_;
- }
-
- const std::vector<std::string>& getCompressionMethods() const {
- return compressionMethods_;
- }
-
- void addCompressionMethod(const std::string& mechanism) {
- compressionMethods_.push_back(mechanism);
- }
-
- bool hasCompressionMethod(const std::string& mechanism) const;
-
- const std::vector<std::string>& getAuthenticationMechanisms() const {
- return authenticationMechanisms_;
- }
-
- void addAuthenticationMechanism(const std::string& mechanism) {
- authenticationMechanisms_.push_back(mechanism);
- }
-
- bool hasAuthenticationMechanism(const std::string& mechanism) const;
-
- bool hasAuthenticationMechanisms() const {
- return !authenticationMechanisms_.empty();
- }
-
- const boost::optional<std::string> getAuthenticationHostname() const {
- return authenticationHostname_;
- }
-
- void setAuthenticationHostname(const boost::optional<std::string> authenticationHostname) {
- authenticationHostname_ = authenticationHostname;
- }
-
- bool hasStreamManagement() const {
- return hasStreamManagement_;
- }
-
- void setHasStreamManagement() {
- hasStreamManagement_ = true;
- }
-
- bool hasRosterVersioning() const {
- return hasRosterVersioning_;
- }
-
- void setHasRosterVersioning() {
- hasRosterVersioning_ = true;
- }
-
- private:
- bool hasStartTLS_;
- std::vector<std::string> compressionMethods_;
- std::vector<std::string> authenticationMechanisms_;
- bool hasResourceBind_;
- bool hasSession_;
- bool hasStreamManagement_;
- bool hasRosterVersioning_;
- boost::optional<std::string> authenticationHostname_;
- };
+ class SWIFTEN_API StreamFeatures : public ToplevelElement {
+ public:
+ typedef boost::shared_ptr<StreamFeatures> ref;
+
+ StreamFeatures() : hasStartTLS_(false), hasResourceBind_(false), hasSession_(false), hasStreamManagement_(false), hasRosterVersioning_(false) {}
+
+ void setHasStartTLS() {
+ hasStartTLS_ = true;
+ }
+
+ bool hasStartTLS() const {
+ return hasStartTLS_;
+ }
+
+ void setHasSession() {
+ hasSession_ = true;
+ }
+
+ bool hasSession() const {
+ return hasSession_;
+ }
+
+ void setHasResourceBind() {
+ hasResourceBind_ = true;
+ }
+
+ bool hasResourceBind() const {
+ return hasResourceBind_;
+ }
+
+ const std::vector<std::string>& getCompressionMethods() const {
+ return compressionMethods_;
+ }
+
+ void addCompressionMethod(const std::string& mechanism) {
+ compressionMethods_.push_back(mechanism);
+ }
+
+ bool hasCompressionMethod(const std::string& mechanism) const;
+
+ const std::vector<std::string>& getAuthenticationMechanisms() const {
+ return authenticationMechanisms_;
+ }
+
+ void addAuthenticationMechanism(const std::string& mechanism) {
+ authenticationMechanisms_.push_back(mechanism);
+ }
+
+ bool hasAuthenticationMechanism(const std::string& mechanism) const;
+
+ bool hasAuthenticationMechanisms() const {
+ return !authenticationMechanisms_.empty();
+ }
+
+ const boost::optional<std::string> getAuthenticationHostname() const {
+ return authenticationHostname_;
+ }
+
+ void setAuthenticationHostname(const boost::optional<std::string> authenticationHostname) {
+ authenticationHostname_ = authenticationHostname;
+ }
+
+ bool hasStreamManagement() const {
+ return hasStreamManagement_;
+ }
+
+ void setHasStreamManagement() {
+ hasStreamManagement_ = true;
+ }
+
+ bool hasRosterVersioning() const {
+ return hasRosterVersioning_;
+ }
+
+ void setHasRosterVersioning() {
+ hasRosterVersioning_ = true;
+ }
+
+ private:
+ bool hasStartTLS_;
+ std::vector<std::string> compressionMethods_;
+ std::vector<std::string> authenticationMechanisms_;
+ bool hasResourceBind_;
+ bool hasSession_;
+ bool hasStreamManagement_;
+ bool hasRosterVersioning_;
+ boost::optional<std::string> authenticationHostname_;
+ };
}
diff --git a/Swiften/Elements/StreamInitiation.h b/Swiften/Elements/StreamInitiation.h
index b56fadc..cd37974 100644
--- a/Swiften/Elements/StreamInitiation.h
+++ b/Swiften/Elements/StreamInitiation.h
@@ -17,57 +17,57 @@
#include <Swiften/Elements/StreamInitiationFileInfo.h>
namespace Swift {
- class SWIFTEN_API StreamInitiation : public Payload {
- public:
- typedef boost::shared_ptr<StreamInitiation> ref;
-
- StreamInitiation() : isFileTransfer(true) {}
-
- const std::string& getID() const {
- return id;
- }
-
- void setID(const std::string& id) {
- this->id = id;
- }
-
- const boost::optional<StreamInitiationFileInfo>& getFileInfo() const {
- return fileInfo;
- }
-
- void setFileInfo(const StreamInitiationFileInfo& info) {
- fileInfo = info;
- }
-
- const std::vector<std::string>& getProvidedMethods() const {
- return providedMethods;
- }
-
- void addProvidedMethod(const std::string& method) {
- providedMethods.push_back(method);
- }
-
- void setRequestedMethod(const std::string& method) {
- requestedMethod = method;
- }
-
- const std::string& getRequestedMethod() const {
- return requestedMethod;
- }
-
- bool getIsFileTransfer() const {
- return isFileTransfer;
- }
-
- void setIsFileTransfer(bool b) {
- isFileTransfer = b;
- }
-
- private:
- bool isFileTransfer;
- std::string id;
- boost::optional<StreamInitiationFileInfo> fileInfo;
- std::vector<std::string> providedMethods;
- std::string requestedMethod;
- };
+ class SWIFTEN_API StreamInitiation : public Payload {
+ public:
+ typedef boost::shared_ptr<StreamInitiation> ref;
+
+ StreamInitiation() : isFileTransfer(true) {}
+
+ const std::string& getID() const {
+ return id;
+ }
+
+ void setID(const std::string& id) {
+ this->id = id;
+ }
+
+ const boost::optional<StreamInitiationFileInfo>& getFileInfo() const {
+ return fileInfo;
+ }
+
+ void setFileInfo(const StreamInitiationFileInfo& info) {
+ fileInfo = info;
+ }
+
+ const std::vector<std::string>& getProvidedMethods() const {
+ return providedMethods;
+ }
+
+ void addProvidedMethod(const std::string& method) {
+ providedMethods.push_back(method);
+ }
+
+ void setRequestedMethod(const std::string& method) {
+ requestedMethod = method;
+ }
+
+ const std::string& getRequestedMethod() const {
+ return requestedMethod;
+ }
+
+ bool getIsFileTransfer() const {
+ return isFileTransfer;
+ }
+
+ void setIsFileTransfer(bool b) {
+ isFileTransfer = b;
+ }
+
+ private:
+ bool isFileTransfer;
+ std::string id;
+ boost::optional<StreamInitiationFileInfo> fileInfo;
+ std::vector<std::string> providedMethods;
+ std::string requestedMethod;
+ };
}
diff --git a/Swiften/Elements/StreamInitiationFileInfo.h b/Swiften/Elements/StreamInitiationFileInfo.h
index 9c40d60..11bd4c5 100644
--- a/Swiften/Elements/StreamInitiationFileInfo.h
+++ b/Swiften/Elements/StreamInitiationFileInfo.h
@@ -18,87 +18,87 @@ namespace Swift {
class SWIFTEN_API StreamInitiationFileInfo : public Payload {
public:
- typedef boost::shared_ptr<StreamInitiationFileInfo> ref;
-
+ typedef boost::shared_ptr<StreamInitiationFileInfo> ref;
+
public:
- StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0,
- const std::string& hash = "", const boost::posix_time::ptime &date = boost::posix_time::ptime(), const std::string& algo="md5") :
- name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {}
-
- void setName(const std::string& name) {
- this->name = name;;
- }
-
- const std::string& getName() const {
- return this->name;
- }
-
- void setDescription(const std::string& description) {
- this->description = description;
- }
-
- const std::string& getDescription() const {
- return this->description;
- }
-
- void setSize(const unsigned long long size) {
- this->size = size;
- }
-
- unsigned long long getSize() const {
- return this->size;
- }
-
- void setHash(const std::string& hash) {
- this->hash = hash;
- }
-
- const std::string& getHash() const {
- return this->hash;
- }
-
- void setDate(const boost::posix_time::ptime& date) {
- this->date = date;
- }
-
- const boost::posix_time::ptime& getDate() const {
- return this->date;
- }
-
- void setAlgo(const std::string& algo) {
- this->algo = algo;
- }
-
- const std::string& getAlgo() const {
- return this->algo;
- }
-
- void setSupportsRangeRequests(const bool supportsIt) {
- supportsRangeRequests = supportsIt;
- }
-
- bool getSupportsRangeRequests() const {
- return supportsRangeRequests;
- }
-
- void setRangeOffset(unsigned long long offset) {
- supportsRangeRequests = true;
- rangeOffset = offset;
- }
-
- unsigned long long getRangeOffset() const {
- return rangeOffset;
- }
+ StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", unsigned long long size = 0,
+ const std::string& hash = "", const boost::posix_time::ptime &date = boost::posix_time::ptime(), const std::string& algo="md5") :
+ name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {}
+
+ void setName(const std::string& name) {
+ this->name = name;;
+ }
+
+ const std::string& getName() const {
+ return this->name;
+ }
+
+ void setDescription(const std::string& description) {
+ this->description = description;
+ }
+
+ const std::string& getDescription() const {
+ return this->description;
+ }
+
+ void setSize(const unsigned long long size) {
+ this->size = size;
+ }
+
+ unsigned long long getSize() const {
+ return this->size;
+ }
+
+ void setHash(const std::string& hash) {
+ this->hash = hash;
+ }
+
+ const std::string& getHash() const {
+ return this->hash;
+ }
+
+ void setDate(const boost::posix_time::ptime& date) {
+ this->date = date;
+ }
+
+ const boost::posix_time::ptime& getDate() const {
+ return this->date;
+ }
+
+ void setAlgo(const std::string& algo) {
+ this->algo = algo;
+ }
+
+ const std::string& getAlgo() const {
+ return this->algo;
+ }
+
+ void setSupportsRangeRequests(const bool supportsIt) {
+ supportsRangeRequests = supportsIt;
+ }
+
+ bool getSupportsRangeRequests() const {
+ return supportsRangeRequests;
+ }
+
+ void setRangeOffset(unsigned long long offset) {
+ supportsRangeRequests = true;
+ rangeOffset = offset;
+ }
+
+ unsigned long long getRangeOffset() const {
+ return rangeOffset;
+ }
private:
- std::string name;
- std::string description;
- unsigned long long size;
- std::string hash;
- boost::posix_time::ptime date;
- std::string algo;
- bool supportsRangeRequests;
- unsigned long long rangeOffset;
+ std::string name;
+ std::string description;
+ unsigned long long size;
+ std::string hash;
+ boost::posix_time::ptime date;
+ std::string algo;
+ bool supportsRangeRequests;
+ unsigned long long rangeOffset;
};
}
diff --git a/Swiften/Elements/StreamManagementEnabled.h b/Swiften/Elements/StreamManagementEnabled.h
index eaae189..7cb640d 100644
--- a/Swiften/Elements/StreamManagementEnabled.h
+++ b/Swiften/Elements/StreamManagementEnabled.h
@@ -12,29 +12,29 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamManagementEnabled : public ToplevelElement {
- public:
- StreamManagementEnabled();
- ~StreamManagementEnabled();
-
- void setResumeSupported() {
- resumeSupported = true;
- }
-
- bool getResumeSupported() const {
- return resumeSupported;
- }
-
- void setResumeID(const std::string& id) {
- resumeID = id;
- }
-
- const std::string& getResumeID() const {
- return resumeID;
- }
-
- private:
- bool resumeSupported;
- std::string resumeID;
- };
+ class SWIFTEN_API StreamManagementEnabled : public ToplevelElement {
+ public:
+ StreamManagementEnabled();
+ ~StreamManagementEnabled();
+
+ void setResumeSupported() {
+ resumeSupported = true;
+ }
+
+ bool getResumeSupported() const {
+ return resumeSupported;
+ }
+
+ void setResumeID(const std::string& id) {
+ resumeID = id;
+ }
+
+ const std::string& getResumeID() const {
+ return resumeID;
+ }
+
+ private:
+ bool resumeSupported;
+ std::string resumeID;
+ };
}
diff --git a/Swiften/Elements/StreamManagementFailed.h b/Swiften/Elements/StreamManagementFailed.h
index 70781d7..062d9bd 100644
--- a/Swiften/Elements/StreamManagementFailed.h
+++ b/Swiften/Elements/StreamManagementFailed.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamManagementFailed : public ToplevelElement {
- public:
- StreamManagementFailed() {}
- };
+ class SWIFTEN_API StreamManagementFailed : public ToplevelElement {
+ public:
+ StreamManagementFailed() {}
+ };
}
diff --git a/Swiften/Elements/StreamResume.h b/Swiften/Elements/StreamResume.h
index 6876ead..0ded077 100644
--- a/Swiften/Elements/StreamResume.h
+++ b/Swiften/Elements/StreamResume.h
@@ -14,29 +14,29 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamResume : public ToplevelElement {
- public:
- StreamResume();
- ~StreamResume();
-
- void setResumeID(const std::string& id) {
- resumeID = id;
- }
-
- const std::string& getResumeID() const {
- return resumeID;
- }
-
- const boost::optional<unsigned int> getHandledStanzasCount() const {
- return handledStanzasCount;
- }
-
- void setHandledStanzasCount(unsigned int i) {
- handledStanzasCount = i;
- }
-
- private:
- std::string resumeID;
- boost::optional<unsigned int> handledStanzasCount;
- };
+ class SWIFTEN_API StreamResume : public ToplevelElement {
+ public:
+ StreamResume();
+ ~StreamResume();
+
+ void setResumeID(const std::string& id) {
+ resumeID = id;
+ }
+
+ const std::string& getResumeID() const {
+ return resumeID;
+ }
+
+ const boost::optional<unsigned int> getHandledStanzasCount() const {
+ return handledStanzasCount;
+ }
+
+ void setHandledStanzasCount(unsigned int i) {
+ handledStanzasCount = i;
+ }
+
+ private:
+ std::string resumeID;
+ boost::optional<unsigned int> handledStanzasCount;
+ };
}
diff --git a/Swiften/Elements/StreamResumed.h b/Swiften/Elements/StreamResumed.h
index 88779cc..e1c80d9 100644
--- a/Swiften/Elements/StreamResumed.h
+++ b/Swiften/Elements/StreamResumed.h
@@ -14,29 +14,29 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API StreamResumed : public ToplevelElement {
- public:
- StreamResumed();
- ~StreamResumed();
-
- void setResumeID(const std::string& id) {
- resumeID = id;
- }
-
- const std::string& getResumeID() const {
- return resumeID;
- }
-
- const boost::optional<unsigned int> getHandledStanzasCount() const {
- return handledStanzasCount;
- }
-
- void setHandledStanzasCount(unsigned int i) {
- handledStanzasCount = i;
- }
-
- private:
- std::string resumeID;
- boost::optional<unsigned int> handledStanzasCount;
- };
+ class SWIFTEN_API StreamResumed : public ToplevelElement {
+ public:
+ StreamResumed();
+ ~StreamResumed();
+
+ void setResumeID(const std::string& id) {
+ resumeID = id;
+ }
+
+ const std::string& getResumeID() const {
+ return resumeID;
+ }
+
+ const boost::optional<unsigned int> getHandledStanzasCount() const {
+ return handledStanzasCount;
+ }
+
+ void setHandledStanzasCount(unsigned int i) {
+ handledStanzasCount = i;
+ }
+
+ private:
+ std::string resumeID;
+ boost::optional<unsigned int> handledStanzasCount;
+ };
}
diff --git a/Swiften/Elements/StreamType.h b/Swiften/Elements/StreamType.h
index 0cd4133..d6b820e 100644
--- a/Swiften/Elements/StreamType.h
+++ b/Swiften/Elements/StreamType.h
@@ -7,9 +7,9 @@
#pragma once
namespace Swift {
- enum StreamType {
- ClientStreamType,
- ServerStreamType,
- ComponentStreamType
- };
+ enum StreamType {
+ ClientStreamType,
+ ServerStreamType,
+ ComponentStreamType
+ };
}
diff --git a/Swiften/Elements/Subject.h b/Swiften/Elements/Subject.h
index 982ce3b..4f9444a 100644
--- a/Swiften/Elements/Subject.h
+++ b/Swiften/Elements/Subject.h
@@ -12,20 +12,20 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Subject : public Payload {
- public:
- Subject(const std::string& text = "") : text_(text) {
- }
+ class SWIFTEN_API Subject : public Payload {
+ public:
+ Subject(const std::string& text = "") : text_(text) {
+ }
- void setText(const std::string& text) {
- text_ = text;
- }
+ void setText(const std::string& text) {
+ text_ = text;
+ }
- const std::string& getText() const {
- return text_;
- }
+ const std::string& getText() const {
+ return text_;
+ }
- private:
- std::string text_;
- };
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Elements/TLSProceed.h b/Swiften/Elements/TLSProceed.h
index 4e05511..3cd5360 100644
--- a/Swiften/Elements/TLSProceed.h
+++ b/Swiften/Elements/TLSProceed.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API TLSProceed : public ToplevelElement {
- public:
- TLSProceed() {}
- };
+ class SWIFTEN_API TLSProceed : public ToplevelElement {
+ public:
+ TLSProceed() {}
+ };
}
diff --git a/Swiften/Elements/Thread.cpp b/Swiften/Elements/Thread.cpp
index dfd9029..5ac371b 100644
--- a/Swiften/Elements/Thread.cpp
+++ b/Swiften/Elements/Thread.cpp
@@ -8,27 +8,27 @@
namespace Swift {
- Thread::Thread(const std::string& text, const std::string& parent) : text_(text), parent_(parent) {
-
- }
+ Thread::Thread(const std::string& text, const std::string& parent) : text_(text), parent_(parent) {
- Thread::~Thread() {
+ }
- }
+ Thread::~Thread() {
- void Thread::setText(const std::string& text) {
- text_ = text;
- }
+ }
- const std::string& Thread::getText() const {
- return text_;
- }
+ void Thread::setText(const std::string& text) {
+ text_ = text;
+ }
- void Thread::setParent(const std::string& parent) {
- parent_ = parent;
- }
+ const std::string& Thread::getText() const {
+ return text_;
+ }
- const std::string& Thread::getParent() const {
- return parent_;
- }
+ void Thread::setParent(const std::string& parent) {
+ parent_ = parent;
+ }
+
+ const std::string& Thread::getParent() const {
+ return parent_;
+ }
}
diff --git a/Swiften/Elements/Thread.h b/Swiften/Elements/Thread.h
index 8207851..e736e7f 100644
--- a/Swiften/Elements/Thread.h
+++ b/Swiften/Elements/Thread.h
@@ -12,17 +12,17 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Thread : public Payload {
- public:
- Thread(const std::string& text = "", const std::string& parent = "");
- virtual ~Thread();
- void setText(const std::string& text);
- const std::string& getText() const;
- void setParent(const std::string& parent);
- const std::string& getParent() const;
+ class SWIFTEN_API Thread : public Payload {
+ public:
+ Thread(const std::string& text = "", const std::string& parent = "");
+ virtual ~Thread();
+ void setText(const std::string& text);
+ const std::string& getText() const;
+ void setParent(const std::string& parent);
+ const std::string& getParent() const;
- private:
- std::string text_;
- std::string parent_;
- };
+ private:
+ std::string text_;
+ std::string parent_;
+ };
}
diff --git a/Swiften/Elements/ToplevelElement.h b/Swiften/Elements/ToplevelElement.h
index a9cc09c..55e055a 100644
--- a/Swiften/Elements/ToplevelElement.h
+++ b/Swiften/Elements/ToplevelElement.h
@@ -10,10 +10,10 @@
#include <Swiften/Elements/Element.h>
namespace Swift {
- class SWIFTEN_API ToplevelElement : public Element {
- public:
- ToplevelElement() {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(ToplevelElement)
- virtual ~ToplevelElement();
- };
+ class SWIFTEN_API ToplevelElement : public Element {
+ public:
+ ToplevelElement() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(ToplevelElement)
+ virtual ~ToplevelElement();
+ };
}
diff --git a/Swiften/Elements/UnblockPayload.h b/Swiften/Elements/UnblockPayload.h
index ddb42d8..7d6574d 100644
--- a/Swiften/Elements/UnblockPayload.h
+++ b/Swiften/Elements/UnblockPayload.h
@@ -13,20 +13,20 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API UnblockPayload : public Payload {
- public:
- UnblockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) {
- }
+ class SWIFTEN_API UnblockPayload : public Payload {
+ public:
+ UnblockPayload(const std::vector<JID>& jids = std::vector<JID>()) : items(jids) {
+ }
- void addItem(const JID& item) {
- items.push_back(item);
- }
+ void addItem(const JID& item) {
+ items.push_back(item);
+ }
- const std::vector<JID>& getItems() const {
- return items;
- }
+ const std::vector<JID>& getItems() const {
+ return items;
+ }
- private:
- std::vector<JID> items;
- };
+ private:
+ std::vector<JID> items;
+ };
}
diff --git a/Swiften/Elements/UnitTest/FormTest.cpp b/Swiften/Elements/UnitTest/FormTest.cpp
index ea680f9..9255fa8 100644
--- a/Swiften/Elements/UnitTest/FormTest.cpp
+++ b/Swiften/Elements/UnitTest/FormTest.cpp
@@ -15,44 +15,44 @@
using namespace Swift;
class FormTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FormTest);
- CPPUNIT_TEST(testGetFormType);
- CPPUNIT_TEST(testGetFormType_InvalidFormType);
- CPPUNIT_TEST(testGetFormType_NoFormType);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(FormTest);
+ CPPUNIT_TEST(testGetFormType);
+ CPPUNIT_TEST(testGetFormType_InvalidFormType);
+ CPPUNIT_TEST(testGetFormType_NoFormType);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetFormType() {
- Form form;
+ public:
+ void testGetFormType() {
+ Form form;
- form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo"));
+ form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo"));
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot");
- field->setName("FORM_TYPE");
- form.addField(field);
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot");
+ field->setName("FORM_TYPE");
+ form.addField(field);
- form.addField(boost::make_shared<FormField>(FormField::FixedType, "Bar"));
+ form.addField(boost::make_shared<FormField>(FormField::FixedType, "Bar"));
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), form.getFormType());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), form.getFormType());
+ }
- void testGetFormType_InvalidFormType() {
- Form form;
+ void testGetFormType_InvalidFormType() {
+ Form form;
- FormField::ref field = boost::make_shared<FormField>(FormField::FixedType, "jabber:bot");
- field->setName("FORM_TYPE");
- form.addField(field);
+ FormField::ref field = boost::make_shared<FormField>(FormField::FixedType, "jabber:bot");
+ field->setName("FORM_TYPE");
+ form.addField(field);
- CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType());
+ }
- void testGetFormType_NoFormType() {
- Form form;
+ void testGetFormType_NoFormType() {
+ Form form;
- form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo"));
+ form.addField(boost::make_shared<FormField>(FormField::FixedType, "Foo"));
- CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), form.getFormType());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(FormTest);
diff --git a/Swiften/Elements/UnitTest/IQTest.cpp b/Swiften/Elements/UnitTest/IQTest.cpp
index 7cc78c6..a88e2d6 100644
--- a/Swiften/Elements/UnitTest/IQTest.cpp
+++ b/Swiften/Elements/UnitTest/IQTest.cpp
@@ -16,43 +16,43 @@ using namespace Swift;
class IQTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(IQTest);
- CPPUNIT_TEST(testCreateResult);
- CPPUNIT_TEST(testCreateResult_WithoutPayload);
- CPPUNIT_TEST(testCreateError);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- IQTest() {}
-
- void testCreateResult() {
- boost::shared_ptr<Payload> payload(new SoftwareVersion("myclient"));
- boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid", payload));
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
- CPPUNIT_ASSERT(iq->getPayload<SoftwareVersion>());
- CPPUNIT_ASSERT(payload == iq->getPayload<SoftwareVersion>());
- }
-
- void testCreateResult_WithoutPayload() {
- boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid"));
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
- CPPUNIT_ASSERT(!iq->getPayload<SoftwareVersion>());
- }
-
- void testCreateError() {
- boost::shared_ptr<IQ> iq(IQ::createError(JID("foo@bar/fum"), "myid", ErrorPayload::BadRequest, ErrorPayload::Modify));
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
- boost::shared_ptr<ErrorPayload> error(iq->getPayload<ErrorPayload>());
- CPPUNIT_ASSERT(error);
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, error->getCondition());
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, error->getType());
- }
+ CPPUNIT_TEST_SUITE(IQTest);
+ CPPUNIT_TEST(testCreateResult);
+ CPPUNIT_TEST(testCreateResult_WithoutPayload);
+ CPPUNIT_TEST(testCreateError);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ IQTest() {}
+
+ void testCreateResult() {
+ boost::shared_ptr<Payload> payload(new SoftwareVersion("myclient"));
+ boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid", payload));
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
+ CPPUNIT_ASSERT(iq->getPayload<SoftwareVersion>());
+ CPPUNIT_ASSERT(payload == iq->getPayload<SoftwareVersion>());
+ }
+
+ void testCreateResult_WithoutPayload() {
+ boost::shared_ptr<IQ> iq(IQ::createResult(JID("foo@bar/fum"), "myid"));
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
+ CPPUNIT_ASSERT(!iq->getPayload<SoftwareVersion>());
+ }
+
+ void testCreateError() {
+ boost::shared_ptr<IQ> iq(IQ::createError(JID("foo@bar/fum"), "myid", ErrorPayload::BadRequest, ErrorPayload::Modify));
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar/fum"), iq->getTo());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), iq->getID());
+ boost::shared_ptr<ErrorPayload> error(iq->getPayload<ErrorPayload>());
+ CPPUNIT_ASSERT(error);
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, error->getCondition());
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, error->getType());
+ }
};
diff --git a/Swiften/Elements/UnitTest/StanzaTest.cpp b/Swiften/Elements/UnitTest/StanzaTest.cpp
index de5779c..13c038c 100644
--- a/Swiften/Elements/UnitTest/StanzaTest.cpp
+++ b/Swiften/Elements/UnitTest/StanzaTest.cpp
@@ -19,214 +19,214 @@ using namespace Swift;
class StanzaTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StanzaTest);
- CPPUNIT_TEST(testConstructor_Copy);
- CPPUNIT_TEST(testGetPayload);
- CPPUNIT_TEST(testGetPayloads);
- CPPUNIT_TEST(testGetPayload_NoSuchPayload);
- CPPUNIT_TEST(testDestructor);
- CPPUNIT_TEST(testDestructor_Copy);
- CPPUNIT_TEST(testUpdatePayload_ExistingPayload);
- CPPUNIT_TEST(testUpdatePayload_NewPayload);
- CPPUNIT_TEST(testGetPayloadOfSameType);
- CPPUNIT_TEST(testGetPayloadOfSameType_NoSuchPayload);
- CPPUNIT_TEST(testGetTimestamp);
- CPPUNIT_TEST(testGetTimestamp_TimestampWithFrom);
- CPPUNIT_TEST(testGetTimestamp_NoDelay);
- CPPUNIT_TEST(testGetTimestampFrom);
- CPPUNIT_TEST(testGetTimestampFrom_Fallsback);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- class MyPayload1 : public Payload {
- public:
- MyPayload1() {}
- };
-
- class MyPayload2 : public Payload {
- public:
- MyPayload2(const std::string& s = "") : text_(s) {}
-
- std::string text_;
- };
-
- class MyPayload3 : public Payload {
- public:
- MyPayload3() {}
- };
-
- class DestroyingPayload : public Payload {
- public:
- DestroyingPayload(bool* alive) : alive_(alive) {
- }
-
- ~DestroyingPayload() {
- (*alive_) = false;
- }
-
- private:
- bool* alive_;
- };
-
- void testConstructor_Copy() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload2>());
- Message copy(m);
-
- CPPUNIT_ASSERT(copy.getPayload<MyPayload1>());
- CPPUNIT_ASSERT(copy.getPayload<MyPayload2>());
- }
-
- void testDestructor() {
- bool payloadAlive = true;
- {
- Message m;
- m.addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
- }
-
- CPPUNIT_ASSERT(!payloadAlive);
- }
-
- void testDestructor_Copy() {
- bool payloadAlive = true;
- Message* m1 = new Message();
- m1->addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
- Message* m2 = new Message(*m1);
-
- delete m1;
- CPPUNIT_ASSERT(payloadAlive);
-
- delete m2;
- CPPUNIT_ASSERT(!payloadAlive);
- }
-
- void testGetPayload() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload2>());
- m.addPayload(boost::make_shared<MyPayload3>());
-
- boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
- CPPUNIT_ASSERT(p);
- }
-
- void testGetPayload_NoSuchPayload() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload3>());
-
- boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
- CPPUNIT_ASSERT(!p);
- }
-
- void testGetPayloads() {
- Message m;
- boost::shared_ptr<MyPayload2> payload1(new MyPayload2());
- boost::shared_ptr<MyPayload2> payload2(new MyPayload2());
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(payload1);
- m.addPayload(boost::make_shared<MyPayload3>());
- m.addPayload(payload2);
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), m.getPayloads<MyPayload2>().size());
- CPPUNIT_ASSERT_EQUAL(payload1, m.getPayloads<MyPayload2>()[0]);
- CPPUNIT_ASSERT_EQUAL(payload2, m.getPayloads<MyPayload2>()[1]);
- }
-
-
- void testUpdatePayload_ExistingPayload() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload2>("foo"));
- m.addPayload(boost::make_shared<MyPayload3>());
-
- m.updatePayload(boost::make_shared<MyPayload2>("bar"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
- boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
- }
-
- void testUpdatePayload_NewPayload() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload3>());
-
- m.updatePayload(boost::make_shared<MyPayload2>("bar"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
- boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
- }
-
- void testGetPayloadOfSameType() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload2>("foo"));
- m.addPayload(boost::make_shared<MyPayload3>());
-
- boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar"))));
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_);
- }
-
- void testGetPayloadOfSameType_NoSuchPayload() {
- Message m;
- m.addPayload(boost::make_shared<MyPayload1>());
- m.addPayload(boost::make_shared<MyPayload3>());
-
- CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar")));
- }
-
- void testGetTimestamp() {
- Message m;
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1)));
-
- boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
-
- CPPUNIT_ASSERT(timestamp);
- CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
- }
-
- void testGetTimestamp_TimestampWithFrom() {
- Message m;
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo@bar.com")));
-
- boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
-
- CPPUNIT_ASSERT(timestamp);
- CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
- }
-
- void testGetTimestamp_NoDelay() {
- Message m;
- CPPUNIT_ASSERT(!m.getTimestamp());
- }
-
- void testGetTimestampFrom() {
- Message m;
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(0)));
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com")));
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
-
- boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
-
- CPPUNIT_ASSERT(timestamp);
- CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:02"), boost::posix_time::to_simple_string(*timestamp));
- }
-
- void testGetTimestampFrom_Fallsback() {
- Message m;
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
- m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
-
- boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
-
- CPPUNIT_ASSERT(timestamp);
- CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
- }
+ CPPUNIT_TEST_SUITE(StanzaTest);
+ CPPUNIT_TEST(testConstructor_Copy);
+ CPPUNIT_TEST(testGetPayload);
+ CPPUNIT_TEST(testGetPayloads);
+ CPPUNIT_TEST(testGetPayload_NoSuchPayload);
+ CPPUNIT_TEST(testDestructor);
+ CPPUNIT_TEST(testDestructor_Copy);
+ CPPUNIT_TEST(testUpdatePayload_ExistingPayload);
+ CPPUNIT_TEST(testUpdatePayload_NewPayload);
+ CPPUNIT_TEST(testGetPayloadOfSameType);
+ CPPUNIT_TEST(testGetPayloadOfSameType_NoSuchPayload);
+ CPPUNIT_TEST(testGetTimestamp);
+ CPPUNIT_TEST(testGetTimestamp_TimestampWithFrom);
+ CPPUNIT_TEST(testGetTimestamp_NoDelay);
+ CPPUNIT_TEST(testGetTimestampFrom);
+ CPPUNIT_TEST(testGetTimestampFrom_Fallsback);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ class MyPayload1 : public Payload {
+ public:
+ MyPayload1() {}
+ };
+
+ class MyPayload2 : public Payload {
+ public:
+ MyPayload2(const std::string& s = "") : text_(s) {}
+
+ std::string text_;
+ };
+
+ class MyPayload3 : public Payload {
+ public:
+ MyPayload3() {}
+ };
+
+ class DestroyingPayload : public Payload {
+ public:
+ DestroyingPayload(bool* alive) : alive_(alive) {
+ }
+
+ ~DestroyingPayload() {
+ (*alive_) = false;
+ }
+
+ private:
+ bool* alive_;
+ };
+
+ void testConstructor_Copy() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>());
+ Message copy(m);
+
+ CPPUNIT_ASSERT(copy.getPayload<MyPayload1>());
+ CPPUNIT_ASSERT(copy.getPayload<MyPayload2>());
+ }
+
+ void testDestructor() {
+ bool payloadAlive = true;
+ {
+ Message m;
+ m.addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
+ }
+
+ CPPUNIT_ASSERT(!payloadAlive);
+ }
+
+ void testDestructor_Copy() {
+ bool payloadAlive = true;
+ Message* m1 = new Message();
+ m1->addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
+ Message* m2 = new Message(*m1);
+
+ delete m1;
+ CPPUNIT_ASSERT(payloadAlive);
+
+ delete m2;
+ CPPUNIT_ASSERT(!payloadAlive);
+ }
+
+ void testGetPayload() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>());
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT(p);
+ }
+
+ void testGetPayload_NoSuchPayload() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT(!p);
+ }
+
+ void testGetPayloads() {
+ Message m;
+ boost::shared_ptr<MyPayload2> payload1(new MyPayload2());
+ boost::shared_ptr<MyPayload2> payload2(new MyPayload2());
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(payload1);
+ m.addPayload(boost::make_shared<MyPayload3>());
+ m.addPayload(payload2);
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), m.getPayloads<MyPayload2>().size());
+ CPPUNIT_ASSERT_EQUAL(payload1, m.getPayloads<MyPayload2>()[0]);
+ CPPUNIT_ASSERT_EQUAL(payload2, m.getPayloads<MyPayload2>()[1]);
+ }
+
+
+ void testUpdatePayload_ExistingPayload() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>("foo"));
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ m.updatePayload(boost::make_shared<MyPayload2>("bar"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
+ boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
+ }
+
+ void testUpdatePayload_NewPayload() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ m.updatePayload(boost::make_shared<MyPayload2>("bar"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
+ boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
+ }
+
+ void testGetPayloadOfSameType() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>("foo"));
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar"))));
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_);
+ }
+
+ void testGetPayloadOfSameType_NoSuchPayload() {
+ Message m;
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
+
+ CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar")));
+ }
+
+ void testGetTimestamp() {
+ Message m;
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1)));
+
+ boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
+
+ CPPUNIT_ASSERT(timestamp);
+ CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
+ }
+
+ void testGetTimestamp_TimestampWithFrom() {
+ Message m;
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo@bar.com")));
+
+ boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
+
+ CPPUNIT_ASSERT(timestamp);
+ CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
+ }
+
+ void testGetTimestamp_NoDelay() {
+ Message m;
+ CPPUNIT_ASSERT(!m.getTimestamp());
+ }
+
+ void testGetTimestampFrom() {
+ Message m;
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(0)));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
+
+ boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
+
+ CPPUNIT_ASSERT(timestamp);
+ CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:02"), boost::posix_time::to_simple_string(*timestamp));
+ }
+
+ void testGetTimestampFrom_Fallsback() {
+ Message m;
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
+
+ boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
+
+ CPPUNIT_ASSERT(timestamp);
+ CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StanzaTest);
diff --git a/Swiften/Elements/UnknownElement.h b/Swiften/Elements/UnknownElement.h
index 1d71e6b..b6f8021 100644
--- a/Swiften/Elements/UnknownElement.h
+++ b/Swiften/Elements/UnknownElement.h
@@ -10,8 +10,8 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class SWIFTEN_API UnknownElement : public ToplevelElement {
- public:
- UnknownElement() {}
- };
+ class SWIFTEN_API UnknownElement : public ToplevelElement {
+ public:
+ UnknownElement() {}
+ };
}
diff --git a/Swiften/Elements/UserLocation.h b/Swiften/Elements/UserLocation.h
index 1a9dba3..7d07d6a 100644
--- a/Swiften/Elements/UserLocation.h
+++ b/Swiften/Elements/UserLocation.h
@@ -16,212 +16,212 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API UserLocation : public Payload {
- public:
-
- UserLocation();
-
- virtual ~UserLocation();
+ class SWIFTEN_API UserLocation : public Payload {
+ public:
- const boost::optional< std::string >& getArea() const {
- return area;
- }
+ UserLocation();
- void setArea(const boost::optional< std::string >& value) {
- this->area = value ;
- }
+ virtual ~UserLocation();
- const boost::optional< float >& getAltitude() const {
- return altitude;
- }
+ const boost::optional< std::string >& getArea() const {
+ return area;
+ }
- void setAltitude(const boost::optional< float >& value) {
- this->altitude = value ;
- }
+ void setArea(const boost::optional< std::string >& value) {
+ this->area = value ;
+ }
- const boost::optional< std::string >& getLocality() const {
- return locality;
- }
+ const boost::optional< float >& getAltitude() const {
+ return altitude;
+ }
- void setLocality(const boost::optional< std::string >& value) {
- this->locality = value ;
- }
+ void setAltitude(const boost::optional< float >& value) {
+ this->altitude = value ;
+ }
- const boost::optional< float >& getLatitude() const {
- return latitude;
- }
+ const boost::optional< std::string >& getLocality() const {
+ return locality;
+ }
- void setLatitude(const boost::optional< float >& value) {
- this->latitude = value ;
- }
+ void setLocality(const boost::optional< std::string >& value) {
+ this->locality = value ;
+ }
- const boost::optional< float >& getAccuracy() const {
- return accuracy;
- }
+ const boost::optional< float >& getLatitude() const {
+ return latitude;
+ }
- void setAccuracy(const boost::optional< float >& value) {
- this->accuracy = value ;
- }
+ void setLatitude(const boost::optional< float >& value) {
+ this->latitude = value ;
+ }
- const boost::optional< std::string >& getDescription() const {
- return description;
- }
+ const boost::optional< float >& getAccuracy() const {
+ return accuracy;
+ }
- void setDescription(const boost::optional< std::string >& value) {
- this->description = value ;
- }
+ void setAccuracy(const boost::optional< float >& value) {
+ this->accuracy = value ;
+ }
- const boost::optional< std::string >& getCountryCode() const {
- return countryCode;
- }
+ const boost::optional< std::string >& getDescription() const {
+ return description;
+ }
- void setCountryCode(const boost::optional< std::string >& value) {
- this->countryCode = value ;
- }
+ void setDescription(const boost::optional< std::string >& value) {
+ this->description = value ;
+ }
- const boost::optional< boost::posix_time::ptime >& getTimestamp() const {
- return timestamp;
- }
+ const boost::optional< std::string >& getCountryCode() const {
+ return countryCode;
+ }
- void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) {
- this->timestamp = value ;
- }
+ void setCountryCode(const boost::optional< std::string >& value) {
+ this->countryCode = value ;
+ }
- const boost::optional< std::string >& getFloor() const {
- return floor;
- }
+ const boost::optional< boost::posix_time::ptime >& getTimestamp() const {
+ return timestamp;
+ }
- void setFloor(const boost::optional< std::string >& value) {
- this->floor = value ;
- }
+ void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) {
+ this->timestamp = value ;
+ }
- const boost::optional< std::string >& getBuilding() const {
- return building;
- }
+ const boost::optional< std::string >& getFloor() const {
+ return floor;
+ }
- void setBuilding(const boost::optional< std::string >& value) {
- this->building = value ;
- }
+ void setFloor(const boost::optional< std::string >& value) {
+ this->floor = value ;
+ }
- const boost::optional< std::string >& getRoom() const {
- return room;
- }
-
- void setRoom(const boost::optional< std::string >& value) {
- this->room = value ;
- }
-
- const boost::optional< std::string >& getCountry() const {
- return country;
- }
-
- void setCountry(const boost::optional< std::string >& value) {
- this->country = value ;
- }
-
- const boost::optional< std::string >& getRegion() const {
- return region;
- }
-
- void setRegion(const boost::optional< std::string >& value) {
- this->region = value ;
- }
-
- const boost::optional< std::string >& getURI() const {
- return uri;
- }
-
- void setURI(const boost::optional< std::string >& value) {
- this->uri = value ;
- }
-
- const boost::optional< float >& getLongitude() const {
- return longitude;
- }
-
- void setLongitude(const boost::optional< float >& value) {
- this->longitude = value ;
- }
-
- const boost::optional< float >& getError() const {
- return error;
- }
-
- void setError(const boost::optional< float >& value) {
- this->error = value ;
- }
-
- const boost::optional< std::string >& getPostalCode() const {
- return postalCode;
- }
-
- void setPostalCode(const boost::optional< std::string >& value) {
- this->postalCode = value ;
- }
-
- const boost::optional< float >& getBearing() const {
- return bearing;
- }
-
- void setBearing(const boost::optional< float >& value) {
- this->bearing = value ;
- }
-
- const boost::optional< std::string >& getText() const {
- return text;
- }
-
- void setText(const boost::optional< std::string >& value) {
- this->text = value ;
- }
-
- const boost::optional< std::string >& getDatum() const {
- return datum;
- }
-
- void setDatum(const boost::optional< std::string >& value) {
- this->datum = value ;
- }
-
- const boost::optional< std::string >& getStreet() const {
- return street;
- }
-
- void setStreet(const boost::optional< std::string >& value) {
- this->street = value ;
- }
-
- const boost::optional< float >& getSpeed() const {
- return speed;
- }
-
- void setSpeed(const boost::optional< float >& value) {
- this->speed = value ;
- }
-
-
- private:
- boost::optional< std::string > area;
- boost::optional< float > altitude;
- boost::optional< std::string > locality;
- boost::optional< float > latitude;
- boost::optional< float > accuracy;
- boost::optional< std::string > description;
- boost::optional< std::string > countryCode;
- boost::optional< boost::posix_time::ptime > timestamp;
- boost::optional< std::string > floor;
- boost::optional< std::string > building;
- boost::optional< std::string > room;
- boost::optional< std::string > country;
- boost::optional< std::string > region;
- boost::optional< std::string > uri;
- boost::optional< float > longitude;
- boost::optional< float > error;
- boost::optional< std::string > postalCode;
- boost::optional< float > bearing;
- boost::optional< std::string > text;
- boost::optional< std::string > datum;
- boost::optional< std::string > street;
- boost::optional< float > speed;
- };
+ const boost::optional< std::string >& getBuilding() const {
+ return building;
+ }
+
+ void setBuilding(const boost::optional< std::string >& value) {
+ this->building = value ;
+ }
+
+ const boost::optional< std::string >& getRoom() const {
+ return room;
+ }
+
+ void setRoom(const boost::optional< std::string >& value) {
+ this->room = value ;
+ }
+
+ const boost::optional< std::string >& getCountry() const {
+ return country;
+ }
+
+ void setCountry(const boost::optional< std::string >& value) {
+ this->country = value ;
+ }
+
+ const boost::optional< std::string >& getRegion() const {
+ return region;
+ }
+
+ void setRegion(const boost::optional< std::string >& value) {
+ this->region = value ;
+ }
+
+ const boost::optional< std::string >& getURI() const {
+ return uri;
+ }
+
+ void setURI(const boost::optional< std::string >& value) {
+ this->uri = value ;
+ }
+
+ const boost::optional< float >& getLongitude() const {
+ return longitude;
+ }
+
+ void setLongitude(const boost::optional< float >& value) {
+ this->longitude = value ;
+ }
+
+ const boost::optional< float >& getError() const {
+ return error;
+ }
+
+ void setError(const boost::optional< float >& value) {
+ this->error = value ;
+ }
+
+ const boost::optional< std::string >& getPostalCode() const {
+ return postalCode;
+ }
+
+ void setPostalCode(const boost::optional< std::string >& value) {
+ this->postalCode = value ;
+ }
+
+ const boost::optional< float >& getBearing() const {
+ return bearing;
+ }
+
+ void setBearing(const boost::optional< float >& value) {
+ this->bearing = value ;
+ }
+
+ const boost::optional< std::string >& getText() const {
+ return text;
+ }
+
+ void setText(const boost::optional< std::string >& value) {
+ this->text = value ;
+ }
+
+ const boost::optional< std::string >& getDatum() const {
+ return datum;
+ }
+
+ void setDatum(const boost::optional< std::string >& value) {
+ this->datum = value ;
+ }
+
+ const boost::optional< std::string >& getStreet() const {
+ return street;
+ }
+
+ void setStreet(const boost::optional< std::string >& value) {
+ this->street = value ;
+ }
+
+ const boost::optional< float >& getSpeed() const {
+ return speed;
+ }
+
+ void setSpeed(const boost::optional< float >& value) {
+ this->speed = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > area;
+ boost::optional< float > altitude;
+ boost::optional< std::string > locality;
+ boost::optional< float > latitude;
+ boost::optional< float > accuracy;
+ boost::optional< std::string > description;
+ boost::optional< std::string > countryCode;
+ boost::optional< boost::posix_time::ptime > timestamp;
+ boost::optional< std::string > floor;
+ boost::optional< std::string > building;
+ boost::optional< std::string > room;
+ boost::optional< std::string > country;
+ boost::optional< std::string > region;
+ boost::optional< std::string > uri;
+ boost::optional< float > longitude;
+ boost::optional< float > error;
+ boost::optional< std::string > postalCode;
+ boost::optional< float > bearing;
+ boost::optional< std::string > text;
+ boost::optional< std::string > datum;
+ boost::optional< std::string > street;
+ boost::optional< float > speed;
+ };
}
diff --git a/Swiften/Elements/UserTune.h b/Swiften/Elements/UserTune.h
index c500832..7def9b9 100644
--- a/Swiften/Elements/UserTune.h
+++ b/Swiften/Elements/UserTune.h
@@ -15,77 +15,77 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API UserTune : public Payload {
- public:
-
- UserTune();
-
- virtual ~UserTune();
-
- const boost::optional< unsigned int >& getRating() const {
- return rating;
- }
-
- void setRating(const boost::optional< unsigned int >& value) {
- this->rating = value ;
- }
-
- const boost::optional< std::string >& getTitle() const {
- return title;
- }
-
- void setTitle(const boost::optional< std::string >& value) {
- this->title = value ;
- }
-
- const boost::optional< std::string >& getTrack() const {
- return track;
- }
-
- void setTrack(const boost::optional< std::string >& value) {
- this->track = value ;
- }
-
- const boost::optional< std::string >& getArtist() const {
- return artist;
- }
-
- void setArtist(const boost::optional< std::string >& value) {
- this->artist = value ;
- }
-
- const boost::optional< std::string >& getURI() const {
- return uri;
- }
-
- void setURI(const boost::optional< std::string >& value) {
- this->uri = value ;
- }
-
- const boost::optional< std::string >& getSource() const {
- return source;
- }
-
- void setSource(const boost::optional< std::string >& value) {
- this->source = value ;
- }
-
- const boost::optional< unsigned int >& getLength() const {
- return length;
- }
-
- void setLength(const boost::optional< unsigned int >& value) {
- this->length = value ;
- }
-
-
- private:
- boost::optional< unsigned int > rating;
- boost::optional< std::string > title;
- boost::optional< std::string > track;
- boost::optional< std::string > artist;
- boost::optional< std::string > uri;
- boost::optional< std::string > source;
- boost::optional< unsigned int > length;
- };
+ class SWIFTEN_API UserTune : public Payload {
+ public:
+
+ UserTune();
+
+ virtual ~UserTune();
+
+ const boost::optional< unsigned int >& getRating() const {
+ return rating;
+ }
+
+ void setRating(const boost::optional< unsigned int >& value) {
+ this->rating = value ;
+ }
+
+ const boost::optional< std::string >& getTitle() const {
+ return title;
+ }
+
+ void setTitle(const boost::optional< std::string >& value) {
+ this->title = value ;
+ }
+
+ const boost::optional< std::string >& getTrack() const {
+ return track;
+ }
+
+ void setTrack(const boost::optional< std::string >& value) {
+ this->track = value ;
+ }
+
+ const boost::optional< std::string >& getArtist() const {
+ return artist;
+ }
+
+ void setArtist(const boost::optional< std::string >& value) {
+ this->artist = value ;
+ }
+
+ const boost::optional< std::string >& getURI() const {
+ return uri;
+ }
+
+ void setURI(const boost::optional< std::string >& value) {
+ this->uri = value ;
+ }
+
+ const boost::optional< std::string >& getSource() const {
+ return source;
+ }
+
+ void setSource(const boost::optional< std::string >& value) {
+ this->source = value ;
+ }
+
+ const boost::optional< unsigned int >& getLength() const {
+ return length;
+ }
+
+ void setLength(const boost::optional< unsigned int >& value) {
+ this->length = value ;
+ }
+
+
+ private:
+ boost::optional< unsigned int > rating;
+ boost::optional< std::string > title;
+ boost::optional< std::string > track;
+ boost::optional< std::string > artist;
+ boost::optional< std::string > uri;
+ boost::optional< std::string > source;
+ boost::optional< unsigned int > length;
+ };
}
diff --git a/Swiften/Elements/VCard.cpp b/Swiften/Elements/VCard.cpp
index ffa90e7..f541d06 100644
--- a/Swiften/Elements/VCard.cpp
+++ b/Swiften/Elements/VCard.cpp
@@ -11,15 +11,15 @@
namespace Swift {
VCard::EMailAddress VCard::getPreferredEMailAddress() const {
- foreach(const EMailAddress& address, emailAddresses_) {
- if (address.isPreferred) {
- return address;
- }
- }
- if (!emailAddresses_.empty()) {
- return emailAddresses_[0];
- }
- return EMailAddress();
+ foreach(const EMailAddress& address, emailAddresses_) {
+ if (address.isPreferred) {
+ return address;
+ }
+ }
+ if (!emailAddresses_.empty()) {
+ return emailAddresses_[0];
+ }
+ return EMailAddress();
}
diff --git a/Swiften/Elements/VCard.h b/Swiften/Elements/VCard.h
index ba9c39c..94cd029 100644
--- a/Swiften/Elements/VCard.h
+++ b/Swiften/Elements/VCard.h
@@ -17,287 +17,287 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API VCard : public Payload {
- public:
- typedef boost::shared_ptr<VCard> ref;
-
- struct EMailAddress {
- EMailAddress() : isHome(false), isWork(false), isInternet(false), isPreferred(false), isX400(false) {
- }
-
- bool isHome;
- bool isWork;
- bool isInternet;
- bool isPreferred;
- bool isX400;
- std::string address;
- };
-
- struct Telephone {
- Telephone() : isHome(false), isWork(false), isVoice(false), isFax(false), isPager(false), isMSG(false), isCell(false),
- isVideo(false), isBBS(false), isModem(false), isISDN(false), isPCS(false), isPreferred(false) {
- }
-
- bool isHome;
- bool isWork;
- bool isVoice;
- bool isFax;
- bool isPager;
- bool isMSG;
- bool isCell;
- bool isVideo;
- bool isBBS;
- bool isModem;
- bool isISDN;
- bool isPCS;
- bool isPreferred;
- std::string number;
- };
-
- enum DeliveryType {
- DomesticDelivery,
- InternationalDelivery,
- None
- };
-
- struct Address {
- Address() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) {
- }
-
- bool isHome;
- bool isWork;
- bool isPostal;
- bool isParcel;
- DeliveryType deliveryType;
- bool isPreferred;
-
- std::string poBox;
- std::string addressExtension;
- std::string street;
- std::string locality;
- std::string region;
- std::string postalCode;
- std::string country;
- };
-
- struct AddressLabel {
- AddressLabel() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) {
- }
-
- bool isHome;
- bool isWork;
- bool isPostal;
- bool isParcel;
- DeliveryType deliveryType;
- bool isPreferred;
- std::vector<std::string> lines;
- };
-
- struct Organization {
- std::string name;
- std::vector<std::string> units;
- };
-
- VCard() {}
-
- void setVersion(const std::string& version) { version_ = version; }
- const std::string& getVersion() const { return version_; }
-
- void setFullName(const std::string& fullName) { fullName_ = fullName; }
- const std::string& getFullName() const { return fullName_; }
-
- void setFamilyName(const std::string& familyName) { familyName_ = familyName; }
- const std::string& getFamilyName() const { return familyName_; }
-
- void setGivenName(const std::string& givenName) { givenName_ = givenName; }
- const std::string& getGivenName() const { return givenName_; }
-
- void setMiddleName(const std::string& middleName) { middleName_ = middleName; }
- const std::string& getMiddleName() const { return middleName_; }
-
- void setPrefix(const std::string& prefix) { prefix_ = prefix; }
- const std::string& getPrefix() const { return prefix_; }
-
- void setSuffix(const std::string& suffix) { suffix_ = suffix; }
- const std::string& getSuffix() const { return suffix_; }
-
-
- //void setEMailAddress(const std::string& email) { email_ = email; }
- //const std::string& getEMailAddress() const { return email_; }
-
- void setNickname(const std::string& nick) { nick_ = nick; }
- const std::string& getNickname() const { return nick_; }
-
- void setPhoto(const ByteArray& photo) { photo_ = photo; }
- const ByteArray& getPhoto() const { return photo_; }
-
- void setPhotoType(const std::string& photoType) { photoType_ = photoType; }
- const std::string& getPhotoType() const { return photoType_; }
-
- const std::string& getUnknownContent() const { return unknownContent_; }
- void addUnknownContent(const std::string& c) {
- unknownContent_ += c;
- }
-
- const std::vector<EMailAddress>& getEMailAddresses() const {
- return emailAddresses_;
- }
-
- void addEMailAddress(const EMailAddress& email) {
- emailAddresses_.push_back(email);
- }
-
- void clearEMailAddresses() {
- emailAddresses_.clear();
- }
+ class SWIFTEN_API VCard : public Payload {
+ public:
+ typedef boost::shared_ptr<VCard> ref;
+
+ struct EMailAddress {
+ EMailAddress() : isHome(false), isWork(false), isInternet(false), isPreferred(false), isX400(false) {
+ }
+
+ bool isHome;
+ bool isWork;
+ bool isInternet;
+ bool isPreferred;
+ bool isX400;
+ std::string address;
+ };
+
+ struct Telephone {
+ Telephone() : isHome(false), isWork(false), isVoice(false), isFax(false), isPager(false), isMSG(false), isCell(false),
+ isVideo(false), isBBS(false), isModem(false), isISDN(false), isPCS(false), isPreferred(false) {
+ }
+
+ bool isHome;
+ bool isWork;
+ bool isVoice;
+ bool isFax;
+ bool isPager;
+ bool isMSG;
+ bool isCell;
+ bool isVideo;
+ bool isBBS;
+ bool isModem;
+ bool isISDN;
+ bool isPCS;
+ bool isPreferred;
+ std::string number;
+ };
+
+ enum DeliveryType {
+ DomesticDelivery,
+ InternationalDelivery,
+ None
+ };
+
+ struct Address {
+ Address() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) {
+ }
+
+ bool isHome;
+ bool isWork;
+ bool isPostal;
+ bool isParcel;
+ DeliveryType deliveryType;
+ bool isPreferred;
+
+ std::string poBox;
+ std::string addressExtension;
+ std::string street;
+ std::string locality;
+ std::string region;
+ std::string postalCode;
+ std::string country;
+ };
+
+ struct AddressLabel {
+ AddressLabel() : isHome(false), isWork(false), isPostal(false), isParcel(false), deliveryType(None), isPreferred(false) {
+ }
+
+ bool isHome;
+ bool isWork;
+ bool isPostal;
+ bool isParcel;
+ DeliveryType deliveryType;
+ bool isPreferred;
+ std::vector<std::string> lines;
+ };
+
+ struct Organization {
+ std::string name;
+ std::vector<std::string> units;
+ };
+
+ VCard() {}
+
+ void setVersion(const std::string& version) { version_ = version; }
+ const std::string& getVersion() const { return version_; }
+
+ void setFullName(const std::string& fullName) { fullName_ = fullName; }
+ const std::string& getFullName() const { return fullName_; }
+
+ void setFamilyName(const std::string& familyName) { familyName_ = familyName; }
+ const std::string& getFamilyName() const { return familyName_; }
+
+ void setGivenName(const std::string& givenName) { givenName_ = givenName; }
+ const std::string& getGivenName() const { return givenName_; }
+
+ void setMiddleName(const std::string& middleName) { middleName_ = middleName; }
+ const std::string& getMiddleName() const { return middleName_; }
+
+ void setPrefix(const std::string& prefix) { prefix_ = prefix; }
+ const std::string& getPrefix() const { return prefix_; }
+
+ void setSuffix(const std::string& suffix) { suffix_ = suffix; }
+ const std::string& getSuffix() const { return suffix_; }
+
+
+ //void setEMailAddress(const std::string& email) { email_ = email; }
+ //const std::string& getEMailAddress() const { return email_; }
+
+ void setNickname(const std::string& nick) { nick_ = nick; }
+ const std::string& getNickname() const { return nick_; }
+
+ void setPhoto(const ByteArray& photo) { photo_ = photo; }
+ const ByteArray& getPhoto() const { return photo_; }
+
+ void setPhotoType(const std::string& photoType) { photoType_ = photoType; }
+ const std::string& getPhotoType() const { return photoType_; }
+
+ const std::string& getUnknownContent() const { return unknownContent_; }
+ void addUnknownContent(const std::string& c) {
+ unknownContent_ += c;
+ }
+
+ const std::vector<EMailAddress>& getEMailAddresses() const {
+ return emailAddresses_;
+ }
+
+ void addEMailAddress(const EMailAddress& email) {
+ emailAddresses_.push_back(email);
+ }
+
+ void clearEMailAddresses() {
+ emailAddresses_.clear();
+ }
- EMailAddress getPreferredEMailAddress() const;
+ EMailAddress getPreferredEMailAddress() const;
- void setBirthday(const boost::posix_time::ptime& birthday) {
- birthday_ = birthday;
- }
+ void setBirthday(const boost::posix_time::ptime& birthday) {
+ birthday_ = birthday;
+ }
- const boost::posix_time::ptime& getBirthday() const {
- return birthday_;
- }
+ const boost::posix_time::ptime& getBirthday() const {
+ return birthday_;
+ }
- const std::vector<Telephone>& getTelephones() const {
- return telephones_;
- }
+ const std::vector<Telephone>& getTelephones() const {
+ return telephones_;
+ }
- void addTelephone(const Telephone& phone) {
- telephones_.push_back(phone);
- }
+ void addTelephone(const Telephone& phone) {
+ telephones_.push_back(phone);
+ }
- void clearTelephones() {
- telephones_.clear();
- }
+ void clearTelephones() {
+ telephones_.clear();
+ }
- const std::vector<Address>& getAddresses() const {
- return addresses_;
- }
+ const std::vector<Address>& getAddresses() const {
+ return addresses_;
+ }
- void addAddress(const Address& address) {
- addresses_.push_back(address);
- }
+ void addAddress(const Address& address) {
+ addresses_.push_back(address);
+ }
- void clearAddresses() {
- addresses_.clear();
- }
-
- const std::vector<AddressLabel>& getAddressLabels() const {
- return addressLabels_;
- }
-
- void addAddressLabel(const AddressLabel& addressLabel) {
- addressLabels_.push_back(addressLabel);
- }
-
- void clearAddressLabels() {
- addressLabels_.clear();
- }
-
- const std::vector<JID>& getJIDs() const {
- return jids_;
- }
-
- void addJID(const JID& jid) {
- jids_.push_back(jid);
- }
-
- void clearJIDs() {
- jids_.clear();
- }
-
- const std::string& getDescription() const {
- return description_;
- }
-
- void setDescription(const std::string& description) {
- this->description_ = description;
- }
-
- const std::vector<Organization>& getOrganizations() const {
- return organizations_;
- }
-
- void addOrganization(const Organization& organization) {
- organizations_.push_back(organization);
- }
-
- void clearOrganizations() {
- organizations_.clear();
- }
-
- const std::vector<std::string>& getTitles() const {
- return titles_;
- }
-
- void addTitle(const std::string& title) {
- titles_.push_back(title);
- }
-
- void clearTitles() {
- titles_.clear();
- }
-
- const std::vector<std::string>& getRoles() const {
- return roles_;
- }
-
- void addRole(const std::string& role) {
- roles_.push_back(role);
- }
-
- void clearRoles() {
- roles_.clear();
- }
-
- const std::vector<std::string>& getURLs() const {
- return urls_;
- }
-
- void addURL(const std::string& url) {
- urls_.push_back(url);
- }
-
- void clearURLs() {
- urls_.clear();
- }
-
- bool isEmpty() const {
- bool empty = version_.empty() && fullName_.empty() && familyName_.empty() && givenName_.empty() && middleName_.empty() && prefix_.empty() && suffix_.empty();
- empty &= photo_.empty() && photoType_.empty() && nick_.empty();
- empty &= birthday_.is_not_a_date_time();
- empty &= unknownContent_.empty();
- empty &= emailAddresses_.empty() && telephones_.empty() && addresses_.empty() && addressLabels_.empty() && jids_.empty();
- empty &= description_.empty() && organizations_.empty() && titles_.empty() && roles_.empty() && urls_.empty();
- return empty;
- }
-
- private:
- std::string version_;
- std::string fullName_;
- std::string familyName_;
- std::string givenName_;
- std::string middleName_;
- std::string prefix_;
- std::string suffix_;
- //std::string email_;
- ByteArray photo_;
- std::string photoType_;
- std::string nick_;
- boost::posix_time::ptime birthday_;
- std::string unknownContent_;
- std::vector<EMailAddress> emailAddresses_;
- std::vector<Telephone> telephones_;
- std::vector<Address> addresses_;
- std::vector<AddressLabel> addressLabels_;
- std::vector<JID> jids_;
- std::string description_;
- std::vector<Organization> organizations_;
- std::vector<std::string> titles_;
- std::vector<std::string> roles_;
- std::vector<std::string> urls_;
- };
+ void clearAddresses() {
+ addresses_.clear();
+ }
+
+ const std::vector<AddressLabel>& getAddressLabels() const {
+ return addressLabels_;
+ }
+
+ void addAddressLabel(const AddressLabel& addressLabel) {
+ addressLabels_.push_back(addressLabel);
+ }
+
+ void clearAddressLabels() {
+ addressLabels_.clear();
+ }
+
+ const std::vector<JID>& getJIDs() const {
+ return jids_;
+ }
+
+ void addJID(const JID& jid) {
+ jids_.push_back(jid);
+ }
+
+ void clearJIDs() {
+ jids_.clear();
+ }
+
+ const std::string& getDescription() const {
+ return description_;
+ }
+
+ void setDescription(const std::string& description) {
+ this->description_ = description;
+ }
+
+ const std::vector<Organization>& getOrganizations() const {
+ return organizations_;
+ }
+
+ void addOrganization(const Organization& organization) {
+ organizations_.push_back(organization);
+ }
+
+ void clearOrganizations() {
+ organizations_.clear();
+ }
+
+ const std::vector<std::string>& getTitles() const {
+ return titles_;
+ }
+
+ void addTitle(const std::string& title) {
+ titles_.push_back(title);
+ }
+
+ void clearTitles() {
+ titles_.clear();
+ }
+
+ const std::vector<std::string>& getRoles() const {
+ return roles_;
+ }
+
+ void addRole(const std::string& role) {
+ roles_.push_back(role);
+ }
+
+ void clearRoles() {
+ roles_.clear();
+ }
+
+ const std::vector<std::string>& getURLs() const {
+ return urls_;
+ }
+
+ void addURL(const std::string& url) {
+ urls_.push_back(url);
+ }
+
+ void clearURLs() {
+ urls_.clear();
+ }
+
+ bool isEmpty() const {
+ bool empty = version_.empty() && fullName_.empty() && familyName_.empty() && givenName_.empty() && middleName_.empty() && prefix_.empty() && suffix_.empty();
+ empty &= photo_.empty() && photoType_.empty() && nick_.empty();
+ empty &= birthday_.is_not_a_date_time();
+ empty &= unknownContent_.empty();
+ empty &= emailAddresses_.empty() && telephones_.empty() && addresses_.empty() && addressLabels_.empty() && jids_.empty();
+ empty &= description_.empty() && organizations_.empty() && titles_.empty() && roles_.empty() && urls_.empty();
+ return empty;
+ }
+
+ private:
+ std::string version_;
+ std::string fullName_;
+ std::string familyName_;
+ std::string givenName_;
+ std::string middleName_;
+ std::string prefix_;
+ std::string suffix_;
+ //std::string email_;
+ ByteArray photo_;
+ std::string photoType_;
+ std::string nick_;
+ boost::posix_time::ptime birthday_;
+ std::string unknownContent_;
+ std::vector<EMailAddress> emailAddresses_;
+ std::vector<Telephone> telephones_;
+ std::vector<Address> addresses_;
+ std::vector<AddressLabel> addressLabels_;
+ std::vector<JID> jids_;
+ std::string description_;
+ std::vector<Organization> organizations_;
+ std::vector<std::string> titles_;
+ std::vector<std::string> roles_;
+ std::vector<std::string> urls_;
+ };
}
diff --git a/Swiften/Elements/VCardUpdate.h b/Swiften/Elements/VCardUpdate.h
index ded26c9..e3b5377 100644
--- a/Swiften/Elements/VCardUpdate.h
+++ b/Swiften/Elements/VCardUpdate.h
@@ -12,14 +12,14 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API VCardUpdate : public Payload {
- public:
- VCardUpdate(const std::string& photoHash = "") : photoHash_(photoHash) {}
+ class SWIFTEN_API VCardUpdate : public Payload {
+ public:
+ VCardUpdate(const std::string& photoHash = "") : photoHash_(photoHash) {}
- void setPhotoHash(const std::string& photoHash) { photoHash_ = photoHash; }
- const std::string& getPhotoHash() const { return photoHash_; }
+ void setPhotoHash(const std::string& photoHash) { photoHash_ = photoHash; }
+ const std::string& getPhotoHash() const { return photoHash_; }
- private:
- std::string photoHash_;
- };
+ private:
+ std::string photoHash_;
+ };
}
diff --git a/Swiften/Elements/Version.h b/Swiften/Elements/Version.h
index b14dcf0..1d734be 100644
--- a/Swiften/Elements/Version.h
+++ b/Swiften/Elements/Version.h
@@ -12,17 +12,17 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API Version : public Payload {
- public:
- Version(const std::string& name = "", const std::string& version = "", const std::string& os = "") : name_(name), version_(version), os_(os) { }
+ class SWIFTEN_API Version : public Payload {
+ public:
+ Version(const std::string& name = "", const std::string& version = "", const std::string& os = "") : name_(name), version_(version), os_(os) { }
- const std::string& getName() const { return name_; }
- const std::string& getVersion() const { return version_; }
- const std::string& getOS() const { return os_; }
+ const std::string& getName() const { return name_; }
+ const std::string& getVersion() const { return version_; }
+ const std::string& getOS() const { return os_; }
- private:
- std::string name_;
- std::string version_;
- std::string os_;
- };
+ private:
+ std::string name_;
+ std::string version_;
+ std::string os_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardColor.cpp b/Swiften/Elements/Whiteboard/WhiteboardColor.cpp
index dcd6ad7..6bf7e03 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardColor.cpp
+++ b/Swiften/Elements/Whiteboard/WhiteboardColor.cpp
@@ -20,44 +20,44 @@
#include <Swiften/Base/String.h>
namespace Swift {
- WhiteboardColor::WhiteboardColor() : red_(0), green_(0), blue_(0), alpha_(255) {
- }
-
- WhiteboardColor::WhiteboardColor(int red, int green, int blue, int alpha) : red_(red), green_(green), blue_(blue), alpha_(alpha) {
- }
-
- WhiteboardColor::WhiteboardColor(const std::string& hex) : alpha_(255) {
- int value = String::convertHexStringToInt(hex.substr(1));
- red_ = (value >> 16)&0xFF;
- green_ = (value >> 8)&0xFF;
- blue_ = value&0xFF;
- }
-
- std::string WhiteboardColor::toHex() const {
- std::string value = String::convertIntToHexString((red_ << 16) + (green_ << 8) + blue_);
- while (value.size() < 6) {
- value.insert(0, "0");
- }
- return "#"+value;
- }
-
- int WhiteboardColor::getRed() const {
- return red_;
- }
-
- int WhiteboardColor::getGreen() const {
- return green_;
- }
-
- int WhiteboardColor::getBlue() const {
- return blue_;
- }
-
- int WhiteboardColor::getAlpha() const {
- return alpha_;
- }
-
- void WhiteboardColor::setAlpha(int alpha) {
- alpha_ = alpha;
- }
+ WhiteboardColor::WhiteboardColor() : red_(0), green_(0), blue_(0), alpha_(255) {
+ }
+
+ WhiteboardColor::WhiteboardColor(int red, int green, int blue, int alpha) : red_(red), green_(green), blue_(blue), alpha_(alpha) {
+ }
+
+ WhiteboardColor::WhiteboardColor(const std::string& hex) : alpha_(255) {
+ int value = String::convertHexStringToInt(hex.substr(1));
+ red_ = (value >> 16)&0xFF;
+ green_ = (value >> 8)&0xFF;
+ blue_ = value&0xFF;
+ }
+
+ std::string WhiteboardColor::toHex() const {
+ std::string value = String::convertIntToHexString((red_ << 16) + (green_ << 8) + blue_);
+ while (value.size() < 6) {
+ value.insert(0, "0");
+ }
+ return "#"+value;
+ }
+
+ int WhiteboardColor::getRed() const {
+ return red_;
+ }
+
+ int WhiteboardColor::getGreen() const {
+ return green_;
+ }
+
+ int WhiteboardColor::getBlue() const {
+ return blue_;
+ }
+
+ int WhiteboardColor::getAlpha() const {
+ return alpha_;
+ }
+
+ void WhiteboardColor::setAlpha(int alpha) {
+ alpha_ = alpha;
+ }
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardColor.h b/Swiften/Elements/Whiteboard/WhiteboardColor.h
index 3b3d93c..6402efd 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardColor.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardColor.h
@@ -11,20 +11,20 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API WhiteboardColor {
- public:
- WhiteboardColor();
- WhiteboardColor(int red, int green, int blue, int alpha = 255);
- WhiteboardColor(const std::string& hex);
- std::string toHex() const;
- int getRed() const;
- int getGreen() const;
- int getBlue() const;
- int getAlpha() const;
- void setAlpha(int alpha);
+ class SWIFTEN_API WhiteboardColor {
+ public:
+ WhiteboardColor();
+ WhiteboardColor(int red, int green, int blue, int alpha = 255);
+ WhiteboardColor(const std::string& hex);
+ std::string toHex() const;
+ int getRed() const;
+ int getGreen() const;
+ int getBlue() const;
+ int getAlpha() const;
+ void setAlpha(int alpha);
- private:
- int red_, green_, blue_;
- int alpha_;
- };
+ private:
+ int red_, green_, blue_;
+ int alpha_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h b/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h
index d11fd8c..afecd0c 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h
@@ -17,19 +17,19 @@
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardDeleteOperation : public WhiteboardOperation {
- public:
- typedef boost::shared_ptr<WhiteboardDeleteOperation> ref;
- public:
- std::string getElementID() const {
- return elementID_;
- }
+ class SWIFTEN_API WhiteboardDeleteOperation : public WhiteboardOperation {
+ public:
+ typedef boost::shared_ptr<WhiteboardDeleteOperation> ref;
+ public:
+ std::string getElementID() const {
+ return elementID_;
+ }
- void setElementID(const std::string& elementID) {
- elementID_ = elementID;
- }
+ void setElementID(const std::string& elementID) {
+ elementID_ = elementID;
+ }
- private:
- std::string elementID_;
- };
+ private:
+ std::string elementID_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardElement.h b/Swiften/Elements/Whiteboard/WhiteboardElement.h
index b01f31d..a4d1207 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardElement.h
@@ -17,23 +17,23 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h>
namespace Swift {
- class WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardElement> ref;
+ class WhiteboardElement {
+ public:
+ typedef boost::shared_ptr<WhiteboardElement> ref;
- public:
- virtual ~WhiteboardElement() {}
- virtual void accept(WhiteboardElementVisitor& visitor) = 0;
+ public:
+ virtual ~WhiteboardElement() {}
+ virtual void accept(WhiteboardElementVisitor& visitor) = 0;
- const std::string& getID() const {
- return id_;
- }
+ const std::string& getID() const {
+ return id_;
+ }
- void setID(const std::string& id) {
- id_ = id;
- }
+ void setID(const std::string& id) {
+ id_ = id;
+ }
- private:
- std::string id_;
- };
+ private:
+ std::string id_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h b/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h
index 413d6cf..090af56 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h
@@ -7,21 +7,21 @@
#pragma once
namespace Swift {
- class WhiteboardLineElement;
- class WhiteboardFreehandPathElement;
- class WhiteboardRectElement;
- class WhiteboardPolygonElement;
- class WhiteboardTextElement;
- class WhiteboardEllipseElement;
+ class WhiteboardLineElement;
+ class WhiteboardFreehandPathElement;
+ class WhiteboardRectElement;
+ class WhiteboardPolygonElement;
+ class WhiteboardTextElement;
+ class WhiteboardEllipseElement;
- class WhiteboardElementVisitor {
- public:
- virtual ~WhiteboardElementVisitor() {}
- virtual void visit(WhiteboardLineElement& /*element*/) = 0;
- virtual void visit(WhiteboardFreehandPathElement& /*element*/) = 0;
- virtual void visit(WhiteboardRectElement& /*element*/) = 0;
- virtual void visit(WhiteboardPolygonElement& /*element*/) = 0;
- virtual void visit(WhiteboardTextElement& /*element*/) = 0;
- virtual void visit(WhiteboardEllipseElement& /*element*/) = 0;
- };
+ class WhiteboardElementVisitor {
+ public:
+ virtual ~WhiteboardElementVisitor() {}
+ virtual void visit(WhiteboardLineElement& /*element*/) = 0;
+ virtual void visit(WhiteboardFreehandPathElement& /*element*/) = 0;
+ virtual void visit(WhiteboardRectElement& /*element*/) = 0;
+ virtual void visit(WhiteboardPolygonElement& /*element*/) = 0;
+ virtual void visit(WhiteboardTextElement& /*element*/) = 0;
+ virtual void visit(WhiteboardEllipseElement& /*element*/) = 0;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h b/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h
index 040c8a3..15b50e4 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h
@@ -17,65 +17,65 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardEllipseElement : public WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardEllipseElement> ref;
- public:
- WhiteboardEllipseElement(int cx, int cy, int rx, int ry) {
- cx_ = cx;
- cy_ = cy;
- rx_ = rx;
- ry_ = ry;
- }
-
- int getCX() const {
- return cx_;
- }
-
- int getCY() const {
- return cy_;
- }
-
- int getRX() const {
- return rx_;
- }
-
- int getRY() const {
- return ry_;
- }
-
- const WhiteboardColor& getPenColor() const {
- return penColor_;
- }
-
- void setPenColor(const WhiteboardColor& color) {
- penColor_ = color;
- }
-
- const WhiteboardColor& getBrushColor() const {
- return brushColor_;
- }
-
- void setBrushColor(const WhiteboardColor& color) {
- brushColor_ = color;
- }
-
- int getPenWidth() const {
- return penWidth_;
- }
-
- void setPenWidth(const int penWidth) {
- penWidth_ = penWidth;
- }
-
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
-
- private:
- int cx_, cy_, rx_, ry_;
- WhiteboardColor penColor_;
- WhiteboardColor brushColor_;
- int penWidth_;
- };
+ class SWIFTEN_API WhiteboardEllipseElement : public WhiteboardElement {
+ public:
+ typedef boost::shared_ptr<WhiteboardEllipseElement> ref;
+ public:
+ WhiteboardEllipseElement(int cx, int cy, int rx, int ry) {
+ cx_ = cx;
+ cy_ = cy;
+ rx_ = rx;
+ ry_ = ry;
+ }
+
+ int getCX() const {
+ return cx_;
+ }
+
+ int getCY() const {
+ return cy_;
+ }
+
+ int getRX() const {
+ return rx_;
+ }
+
+ int getRY() const {
+ return ry_;
+ }
+
+ const WhiteboardColor& getPenColor() const {
+ return penColor_;
+ }
+
+ void setPenColor(const WhiteboardColor& color) {
+ penColor_ = color;
+ }
+
+ const WhiteboardColor& getBrushColor() const {
+ return brushColor_;
+ }
+
+ void setBrushColor(const WhiteboardColor& color) {
+ brushColor_ = color;
+ }
+
+ int getPenWidth() const {
+ return penWidth_;
+ }
+
+ void setPenWidth(const int penWidth) {
+ penWidth_ = penWidth;
+ }
+
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
+
+ private:
+ int cx_, cy_, rx_, ry_;
+ WhiteboardColor penColor_;
+ WhiteboardColor brushColor_;
+ int penWidth_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
index 5164ae9..7522b7b 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
@@ -20,45 +20,45 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardFreehandPathElement : public WhiteboardElement {
- typedef std::pair<int, int> Point;
- public:
- typedef boost::shared_ptr<WhiteboardFreehandPathElement> ref;
- public:
- WhiteboardFreehandPathElement() {
- }
+ class SWIFTEN_API WhiteboardFreehandPathElement : public WhiteboardElement {
+ typedef std::pair<int, int> Point;
+ public:
+ typedef boost::shared_ptr<WhiteboardFreehandPathElement> ref;
+ public:
+ WhiteboardFreehandPathElement() {
+ }
- void setPoints(const std::vector<Point>& points) {
- points_ = points;
- }
+ void setPoints(const std::vector<Point>& points) {
+ points_ = points;
+ }
- const std::vector<Point>& getPoints() const {
- return points_;
- }
+ const std::vector<Point>& getPoints() const {
+ return points_;
+ }
- const WhiteboardColor& getColor() const {
- return color_;
- }
+ const WhiteboardColor& getColor() const {
+ return color_;
+ }
- void setColor(const WhiteboardColor& color) {
- color_ = color;
- }
+ void setColor(const WhiteboardColor& color) {
+ color_ = color;
+ }
- int getPenWidth() const {
- return penWidth_;
- }
+ int getPenWidth() const {
+ return penWidth_;
+ }
- void setPenWidth(const int penWidth) {
- penWidth_ = penWidth;
- }
+ void setPenWidth(const int penWidth) {
+ penWidth_ = penWidth;
+ }
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
- private:
- std::vector<Point> points_;
- WhiteboardColor color_;
- int penWidth_;
- };
+ private:
+ std::vector<Point> points_;
+ WhiteboardColor color_;
+ int penWidth_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
index bbeaa12..855e502 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
@@ -17,19 +17,19 @@
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardInsertOperation : public WhiteboardOperation {
- public:
- typedef boost::shared_ptr<WhiteboardInsertOperation> ref;
- public:
- WhiteboardElement::ref getElement() const {
- return element_;
- }
+ class SWIFTEN_API WhiteboardInsertOperation : public WhiteboardOperation {
+ public:
+ typedef boost::shared_ptr<WhiteboardInsertOperation> ref;
+ public:
+ WhiteboardElement::ref getElement() const {
+ return element_;
+ }
- void setElement(WhiteboardElement::ref element) {
- element_ = element;
- }
+ void setElement(WhiteboardElement::ref element) {
+ element_ = element;
+ }
- private:
- WhiteboardElement::ref element_;
- };
+ private:
+ WhiteboardElement::ref element_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardLineElement.h b/Swiften/Elements/Whiteboard/WhiteboardLineElement.h
index dae207a..7fb8a77 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardLineElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardLineElement.h
@@ -18,56 +18,56 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardLineElement : public WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardLineElement> ref;
- public:
- WhiteboardLineElement(int x1, int y1, int x2, int y2) : penWidth_(1) {
- x1_ = x1;
- y1_ = y1;
- x2_ = x2;
- y2_ = y2;
- }
+ class SWIFTEN_API WhiteboardLineElement : public WhiteboardElement {
+ public:
+ typedef boost::shared_ptr<WhiteboardLineElement> ref;
+ public:
+ WhiteboardLineElement(int x1, int y1, int x2, int y2) : penWidth_(1) {
+ x1_ = x1;
+ y1_ = y1;
+ x2_ = x2;
+ y2_ = y2;
+ }
- int x1() const {
- return x1_;
- }
+ int x1() const {
+ return x1_;
+ }
- int y1() const {
- return y1_;
- }
+ int y1() const {
+ return y1_;
+ }
- int x2() const {
- return x2_;
- }
+ int x2() const {
+ return x2_;
+ }
- int y2() const {
- return y2_;
- }
+ int y2() const {
+ return y2_;
+ }
- const WhiteboardColor& getColor() const {
- return color_;
- }
+ const WhiteboardColor& getColor() const {
+ return color_;
+ }
- void setColor(const WhiteboardColor& color) {
- color_ = color;
- }
+ void setColor(const WhiteboardColor& color) {
+ color_ = color;
+ }
- int getPenWidth() const {
- return penWidth_;
- }
+ int getPenWidth() const {
+ return penWidth_;
+ }
- void setPenWidth(const int penWidth) {
- penWidth_ = penWidth;
- }
+ void setPenWidth(const int penWidth) {
+ penWidth_ = penWidth;
+ }
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
- private:
- int x1_, y1_, x2_, y2_;
- WhiteboardColor color_;
- int penWidth_;
- };
+ private:
+ int x1_, y1_, x2_, y2_;
+ WhiteboardColor color_;
+ int penWidth_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardOperation.h b/Swiften/Elements/Whiteboard/WhiteboardOperation.h
index 79083a0..b657bd9 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardOperation.h
@@ -19,41 +19,41 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class WhiteboardOperation {
- public:
- typedef boost::shared_ptr<WhiteboardOperation> ref;
- public:
- WhiteboardOperation() {}
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(WhiteboardOperation)
- virtual ~WhiteboardOperation(){}
-
- std::string getID() const {
- return id_;
- }
-
- void setID(const std::string& id) {
- id_ = id;
- }
-
- std::string getParentID() const {
- return parentID_;
- }
-
- void setParentID(const std::string& parentID) {
- parentID_ = parentID;
- }
-
- int getPos() const {
- return pos_;
- }
-
- void setPos(int pos) {
- pos_ = pos;
- }
-
- private:
- std::string id_;
- std::string parentID_;
- int pos_;
- };
+ class WhiteboardOperation {
+ public:
+ typedef boost::shared_ptr<WhiteboardOperation> ref;
+ public:
+ WhiteboardOperation() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(WhiteboardOperation)
+ virtual ~WhiteboardOperation(){}
+
+ std::string getID() const {
+ return id_;
+ }
+
+ void setID(const std::string& id) {
+ id_ = id;
+ }
+
+ std::string getParentID() const {
+ return parentID_;
+ }
+
+ void setParentID(const std::string& parentID) {
+ parentID_ = parentID;
+ }
+
+ int getPos() const {
+ return pos_;
+ }
+
+ void setPos(int pos) {
+ pos_ = pos;
+ }
+
+ private:
+ std::string id_;
+ std::string parentID_;
+ int pos_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
index 38bc3e1..bd0b674 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
@@ -19,54 +19,54 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardPolygonElement : public WhiteboardElement {
- typedef std::pair<int, int> Point;
- public:
- typedef boost::shared_ptr<WhiteboardPolygonElement> ref;
- public:
- WhiteboardPolygonElement() {
- }
+ class SWIFTEN_API WhiteboardPolygonElement : public WhiteboardElement {
+ typedef std::pair<int, int> Point;
+ public:
+ typedef boost::shared_ptr<WhiteboardPolygonElement> ref;
+ public:
+ WhiteboardPolygonElement() {
+ }
- const std::vector<Point>& getPoints() const {
- return points_;
- }
+ const std::vector<Point>& getPoints() const {
+ return points_;
+ }
- void setPoints(const std::vector<Point>& points) {
- points_ = points;
- }
+ void setPoints(const std::vector<Point>& points) {
+ points_ = points;
+ }
- const WhiteboardColor& getPenColor() const {
- return penColor_;
- }
+ const WhiteboardColor& getPenColor() const {
+ return penColor_;
+ }
- void setPenColor(const WhiteboardColor& color) {
- penColor_ = color;
- }
+ void setPenColor(const WhiteboardColor& color) {
+ penColor_ = color;
+ }
- const WhiteboardColor& getBrushColor() const {
- return brushColor_;
- }
+ const WhiteboardColor& getBrushColor() const {
+ return brushColor_;
+ }
- void setBrushColor(const WhiteboardColor& color) {
- brushColor_ = color;
- }
+ void setBrushColor(const WhiteboardColor& color) {
+ brushColor_ = color;
+ }
- int getPenWidth() const {
- return penWidth_;
- }
+ int getPenWidth() const {
+ return penWidth_;
+ }
- void setPenWidth(const int penWidth) {
- penWidth_ = penWidth;
- }
+ void setPenWidth(const int penWidth) {
+ penWidth_ = penWidth;
+ }
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
- private:
- std::vector<Point> points_;
- WhiteboardColor penColor_;
- WhiteboardColor brushColor_;
- int penWidth_;
- };
+ private:
+ std::vector<Point> points_;
+ WhiteboardColor penColor_;
+ WhiteboardColor brushColor_;
+ int penWidth_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
index 7d47ba0..c681e97 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
@@ -17,65 +17,65 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardRectElement : public WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardRectElement> ref;
- public:
- WhiteboardRectElement(int x, int y, int width, int height) : penWidth_(1) {
- x_ = x;
- y_ = y;
- width_ = width;
- height_ = height;
- }
-
- int getX() const {
- return x_;
- }
-
- int getY() const {
- return y_;
- }
-
- int getWidth() const {
- return width_;
- }
-
- int getHeight() const {
- return height_;
- }
-
- const WhiteboardColor& getPenColor() const {
- return penColor_;
- }
-
- void setPenColor(const WhiteboardColor& color) {
- penColor_ = color;
- }
-
- const WhiteboardColor& getBrushColor() const {
- return brushColor_;
- }
-
- void setBrushColor(const WhiteboardColor& color) {
- brushColor_ = color;
- }
-
- int getPenWidth() const {
- return penWidth_;
- }
-
- void setPenWidth(const int penWidth) {
- penWidth_ = penWidth;
- }
-
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
-
- private:
- int x_, y_, width_, height_;
- WhiteboardColor penColor_;
- WhiteboardColor brushColor_;
- int penWidth_;
- };
+ class SWIFTEN_API WhiteboardRectElement : public WhiteboardElement {
+ public:
+ typedef boost::shared_ptr<WhiteboardRectElement> ref;
+ public:
+ WhiteboardRectElement(int x, int y, int width, int height) : penWidth_(1) {
+ x_ = x;
+ y_ = y;
+ width_ = width;
+ height_ = height;
+ }
+
+ int getX() const {
+ return x_;
+ }
+
+ int getY() const {
+ return y_;
+ }
+
+ int getWidth() const {
+ return width_;
+ }
+
+ int getHeight() const {
+ return height_;
+ }
+
+ const WhiteboardColor& getPenColor() const {
+ return penColor_;
+ }
+
+ void setPenColor(const WhiteboardColor& color) {
+ penColor_ = color;
+ }
+
+ const WhiteboardColor& getBrushColor() const {
+ return brushColor_;
+ }
+
+ void setBrushColor(const WhiteboardColor& color) {
+ brushColor_ = color;
+ }
+
+ int getPenWidth() const {
+ return penWidth_;
+ }
+
+ void setPenWidth(const int penWidth) {
+ penWidth_ = penWidth;
+ }
+
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
+
+ private:
+ int x_, y_, width_, height_;
+ WhiteboardColor penColor_;
+ WhiteboardColor brushColor_;
+ int penWidth_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardTextElement.h b/Swiften/Elements/Whiteboard/WhiteboardTextElement.h
index 37ae2c5..df00bea 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardTextElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardTextElement.h
@@ -17,55 +17,55 @@
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardTextElement : public WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardTextElement> ref;
- public:
- WhiteboardTextElement(int x, int y) {
- x_ = x;
- y_ = y;
- }
+ class SWIFTEN_API WhiteboardTextElement : public WhiteboardElement {
+ public:
+ typedef boost::shared_ptr<WhiteboardTextElement> ref;
+ public:
+ WhiteboardTextElement(int x, int y) {
+ x_ = x;
+ y_ = y;
+ }
- void setText(const std::string text) {
- text_ = text;
- }
+ void setText(const std::string text) {
+ text_ = text;
+ }
- const std::string& getText() const {
- return text_;
- }
+ const std::string& getText() const {
+ return text_;
+ }
- int getX() const {
- return x_;
- }
+ int getX() const {
+ return x_;
+ }
- int getY() const {
- return y_;
- }
+ int getY() const {
+ return y_;
+ }
- const WhiteboardColor& getColor() const {
- return color_;
- }
+ const WhiteboardColor& getColor() const {
+ return color_;
+ }
- void setColor(const WhiteboardColor& color) {
- color_ = color;
- }
+ void setColor(const WhiteboardColor& color) {
+ color_ = color;
+ }
- int getSize() const {
- return size_;
- }
+ int getSize() const {
+ return size_;
+ }
- void setSize(const int size) {
- size_ = size;
- }
+ void setSize(const int size) {
+ size_ = size;
+ }
- void accept(WhiteboardElementVisitor& visitor) {
- visitor.visit(*this);
- }
+ void accept(WhiteboardElementVisitor& visitor) {
+ visitor.visit(*this);
+ }
- private:
- int x_, y_;
- int size_;
- std::string text_;
- WhiteboardColor color_;
- };
+ private:
+ int x_, y_;
+ int size_;
+ std::string text_;
+ WhiteboardColor color_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
index fe88fe7..5147999 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
@@ -17,28 +17,28 @@
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardUpdateOperation : public WhiteboardOperation {
- public:
- typedef boost::shared_ptr<WhiteboardUpdateOperation> ref;
- public:
- WhiteboardElement::ref getElement() const {
- return element_;
- }
-
- void setElement(WhiteboardElement::ref element) {
- element_ = element;
- }
-
- int getNewPos() const {
- return newPos_;
- }
-
- void setNewPos(int newPos) {
- newPos_ = newPos;
- }
-
- private:
- WhiteboardElement::ref element_;
- int newPos_;
- };
+ class SWIFTEN_API WhiteboardUpdateOperation : public WhiteboardOperation {
+ public:
+ typedef boost::shared_ptr<WhiteboardUpdateOperation> ref;
+ public:
+ WhiteboardElement::ref getElement() const {
+ return element_;
+ }
+
+ void setElement(WhiteboardElement::ref element) {
+ element_ = element;
+ }
+
+ int getNewPos() const {
+ return newPos_;
+ }
+
+ void setNewPos(int newPos) {
+ newPos_ = newPos;
+ }
+
+ private:
+ WhiteboardElement::ref element_;
+ int newPos_;
+ };
}
diff --git a/Swiften/Elements/WhiteboardPayload.h b/Swiften/Elements/WhiteboardPayload.h
index 3fcaa33..42e1375 100644
--- a/Swiften/Elements/WhiteboardPayload.h
+++ b/Swiften/Elements/WhiteboardPayload.h
@@ -20,52 +20,52 @@
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardPayload : public Payload {
- public:
- typedef boost::shared_ptr<WhiteboardPayload> ref;
-
- public:
- enum Type {UnknownType, Data, SessionRequest, SessionAccept, SessionTerminate};
-
- WhiteboardPayload(Type type = WhiteboardPayload::Data) : type_(type) {
- }
-
- void setData(const std::string &data) {
- data_ = data;
- }
-
- std::string getData() const {
- return data_;
- }
-
- Type getType() const {
- return type_;
- }
-
- void setType(Type type) {
- type_ = type;
- }
-
- WhiteboardElement::ref getElement() const {
- return element_;
- }
-
- void setElement(WhiteboardElement::ref element) {
- element_ = element;
- }
-
- WhiteboardOperation::ref getOperation() const {
- return operation_;
- }
-
- void setOperation(WhiteboardOperation::ref operation) {
- operation_ = operation;
- }
-
- private:
- std::string data_;
- Type type_;
- WhiteboardElement::ref element_;
- WhiteboardOperation::ref operation_;
- };
+ class SWIFTEN_API WhiteboardPayload : public Payload {
+ public:
+ typedef boost::shared_ptr<WhiteboardPayload> ref;
+
+ public:
+ enum Type {UnknownType, Data, SessionRequest, SessionAccept, SessionTerminate};
+
+ WhiteboardPayload(Type type = WhiteboardPayload::Data) : type_(type) {
+ }
+
+ void setData(const std::string &data) {
+ data_ = data;
+ }
+
+ std::string getData() const {
+ return data_;
+ }
+
+ Type getType() const {
+ return type_;
+ }
+
+ void setType(Type type) {
+ type_ = type;
+ }
+
+ WhiteboardElement::ref getElement() const {
+ return element_;
+ }
+
+ void setElement(WhiteboardElement::ref element) {
+ element_ = element;
+ }
+
+ WhiteboardOperation::ref getOperation() const {
+ return operation_;
+ }
+
+ void setOperation(WhiteboardOperation::ref operation) {
+ operation_ = operation;
+ }
+
+ private:
+ std::string data_;
+ Type type_;
+ WhiteboardElement::ref element_;
+ WhiteboardOperation::ref operation_;
+ };
}
diff --git a/Swiften/Entity/Entity.cpp b/Swiften/Entity/Entity.cpp
index af6f636..0875fb1 100644
--- a/Swiften/Entity/Entity.cpp
+++ b/Swiften/Entity/Entity.cpp
@@ -12,38 +12,38 @@
namespace Swift {
Entity::Entity() {
- payloadParserFactories = new FullPayloadParserFactoryCollection();
- payloadSerializers = new FullPayloadSerializerCollection();
+ payloadParserFactories = new FullPayloadParserFactoryCollection();
+ payloadSerializers = new FullPayloadSerializerCollection();
}
Entity::~Entity() {
- delete payloadSerializers;
- delete payloadParserFactories;
+ delete payloadSerializers;
+ delete payloadParserFactories;
}
void Entity::addPayloadParserFactory(PayloadParserFactory* payloadParserFactory) {
- payloadParserFactories->addFactory(payloadParserFactory);
+ payloadParserFactories->addFactory(payloadParserFactory);
}
void Entity::removePayloadParserFactory(PayloadParserFactory* payloadParserFactory) {
- payloadParserFactories->removeFactory(payloadParserFactory);
+ payloadParserFactories->removeFactory(payloadParserFactory);
}
void Entity::addPayloadSerializer(PayloadSerializer* payloadSerializer) {
- payloadSerializers->addSerializer(payloadSerializer);
+ payloadSerializers->addSerializer(payloadSerializer);
}
void Entity::removePayloadSerializer(PayloadSerializer* payloadSerializer) {
- payloadSerializers->removeSerializer(payloadSerializer);
+ payloadSerializers->removeSerializer(payloadSerializer);
}
PayloadParserFactoryCollection* Entity::getPayloadParserFactories() {
- return payloadParserFactories;
+ return payloadParserFactories;
}
PayloadSerializerCollection* Entity::getPayloadSerializers() {
- return payloadSerializers;
+ return payloadSerializers;
}
}
diff --git a/Swiften/Entity/Entity.h b/Swiften/Entity/Entity.h
index d563c5e..a44c145 100644
--- a/Swiften/Entity/Entity.h
+++ b/Swiften/Entity/Entity.h
@@ -9,33 +9,33 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class PayloadParserFactory;
- class PayloadSerializer;
- class FullPayloadParserFactoryCollection;
- class FullPayloadSerializerCollection;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
-
- /**
- * The base class for XMPP entities (Clients, Components).
- */
- class SWIFTEN_API Entity {
- public:
- Entity();
- virtual ~Entity();
-
- void addPayloadParserFactory(PayloadParserFactory* payloadParserFactory);
- void removePayloadParserFactory(PayloadParserFactory* payloadParserFactory);
-
- void addPayloadSerializer(PayloadSerializer* payloadSerializer);
- void removePayloadSerializer(PayloadSerializer* payloadSerializer);
-
- protected:
- PayloadParserFactoryCollection* getPayloadParserFactories();
- PayloadSerializerCollection* getPayloadSerializers();
-
- private:
- FullPayloadParserFactoryCollection* payloadParserFactories;
- FullPayloadSerializerCollection* payloadSerializers;
- };
+ class PayloadParserFactory;
+ class PayloadSerializer;
+ class FullPayloadParserFactoryCollection;
+ class FullPayloadSerializerCollection;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+
+ /**
+ * The base class for XMPP entities (Clients, Components).
+ */
+ class SWIFTEN_API Entity {
+ public:
+ Entity();
+ virtual ~Entity();
+
+ void addPayloadParserFactory(PayloadParserFactory* payloadParserFactory);
+ void removePayloadParserFactory(PayloadParserFactory* payloadParserFactory);
+
+ void addPayloadSerializer(PayloadSerializer* payloadSerializer);
+ void removePayloadSerializer(PayloadSerializer* payloadSerializer);
+
+ protected:
+ PayloadParserFactoryCollection* getPayloadParserFactories();
+ PayloadSerializerCollection* getPayloadSerializers();
+
+ private:
+ FullPayloadParserFactoryCollection* payloadParserFactories;
+ FullPayloadSerializerCollection* payloadSerializers;
+ };
}
diff --git a/Swiften/Entity/GenericPayloadPersister.h b/Swiften/Entity/GenericPayloadPersister.h
index 6f07c3b..19afc61 100644
--- a/Swiften/Entity/GenericPayloadPersister.h
+++ b/Swiften/Entity/GenericPayloadPersister.h
@@ -11,27 +11,27 @@
#include <Swiften/Parser/GenericPayloadParserFactory.h>
namespace Swift {
- template<typename PAYLOAD, typename PARSER, typename SERIALIZER>
- class SWIFTEN_API GenericPayloadPersister : public PayloadPersister {
- public:
- GenericPayloadPersister() {
- }
+ template<typename PAYLOAD, typename PARSER, typename SERIALIZER>
+ class SWIFTEN_API GenericPayloadPersister : public PayloadPersister {
+ public:
+ GenericPayloadPersister() {
+ }
- public:
- boost::shared_ptr<PAYLOAD> loadPayloadGeneric(const boost::filesystem::path& path) {
- return boost::dynamic_pointer_cast<PAYLOAD>(loadPayload(path));
- }
+ public:
+ boost::shared_ptr<PAYLOAD> loadPayloadGeneric(const boost::filesystem::path& path) {
+ return boost::dynamic_pointer_cast<PAYLOAD>(loadPayload(path));
+ }
- protected:
- virtual const PayloadSerializer* getSerializer() const {
- return &serializer;
- }
+ protected:
+ virtual const PayloadSerializer* getSerializer() const {
+ return &serializer;
+ }
- virtual PayloadParser* createParser() const {
- return new PARSER();
- }
+ virtual PayloadParser* createParser() const {
+ return new PARSER();
+ }
- private:
- SERIALIZER serializer;
- };
+ private:
+ SERIALIZER serializer;
+ };
}
diff --git a/Swiften/Entity/PayloadPersister.cpp b/Swiften/Entity/PayloadPersister.cpp
index 2ad8e09..7147615 100644
--- a/Swiften/Entity/PayloadPersister.cpp
+++ b/Swiften/Entity/PayloadPersister.cpp
@@ -26,32 +26,32 @@ PayloadPersister::~PayloadPersister() {
}
void PayloadPersister::savePayload(boost::shared_ptr<Payload> payload, const boost::filesystem::path& path) {
- try {
- if (!boost::filesystem::exists(path.parent_path())) {
- boost::filesystem::create_directories(path.parent_path());
- }
- boost::filesystem::ofstream file(path);
- file << getSerializer()->serialize(payload);
- file.close();
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
+ try {
+ if (!boost::filesystem::exists(path.parent_path())) {
+ boost::filesystem::create_directories(path.parent_path());
+ }
+ boost::filesystem::ofstream file(path);
+ file << getSerializer()->serialize(payload);
+ file.close();
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
}
boost::shared_ptr<Payload> PayloadPersister::loadPayload(const boost::filesystem::path& path) {
- try {
- if (boost::filesystem::exists(path)) {
- ByteArray data;
- readByteArrayFromFile(data, path);
- boost::shared_ptr<PayloadParser> parser(createParser());
- PayloadParserTester tester(parser.get());
- tester.parse(byteArrayToString(data));
- return parser->getPayload();
- }
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- return boost::shared_ptr<Payload>();
+ try {
+ if (boost::filesystem::exists(path)) {
+ ByteArray data;
+ readByteArrayFromFile(data, path);
+ boost::shared_ptr<PayloadParser> parser(createParser());
+ PayloadParserTester tester(parser.get());
+ tester.parse(byteArrayToString(data));
+ return parser->getPayload();
+ }
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ std::cerr << "ERROR: " << e.what() << std::endl;
+ }
+ return boost::shared_ptr<Payload>();
}
diff --git a/Swiften/Entity/PayloadPersister.h b/Swiften/Entity/PayloadPersister.h
index 44f400f..9102f4b 100644
--- a/Swiften/Entity/PayloadPersister.h
+++ b/Swiften/Entity/PayloadPersister.h
@@ -12,21 +12,21 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class Payload;
- class PayloadSerializer;
- class PayloadParser;
+ class Payload;
+ class PayloadSerializer;
+ class PayloadParser;
- class SWIFTEN_API PayloadPersister {
- public:
- PayloadPersister();
- virtual ~PayloadPersister();
+ class SWIFTEN_API PayloadPersister {
+ public:
+ PayloadPersister();
+ virtual ~PayloadPersister();
- void savePayload(boost::shared_ptr<Payload>, const boost::filesystem::path&);
- boost::shared_ptr<Payload> loadPayload(const boost::filesystem::path&);
+ void savePayload(boost::shared_ptr<Payload>, const boost::filesystem::path&);
+ boost::shared_ptr<Payload> loadPayload(const boost::filesystem::path&);
- protected:
+ protected:
- virtual const PayloadSerializer* getSerializer() const = 0;
- virtual PayloadParser* createParser() const = 0;
- };
+ virtual const PayloadSerializer* getSerializer() const = 0;
+ virtual PayloadParser* createParser() const = 0;
+ };
}
diff --git a/Swiften/EventLoop/BoostASIOEventLoop.cpp b/Swiften/EventLoop/BoostASIOEventLoop.cpp
index 1574434..a9d1440 100644
--- a/Swiften/EventLoop/BoostASIOEventLoop.cpp
+++ b/Swiften/EventLoop/BoostASIOEventLoop.cpp
@@ -19,19 +19,19 @@ BoostASIOEventLoop::~BoostASIOEventLoop() {
}
void BoostASIOEventLoop::handleASIOEvent() {
- {
- boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_);
- isEventInASIOEventLoop_ = false;
- }
- handleNextEvents();
+ {
+ boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_);
+ isEventInASIOEventLoop_ = false;
+ }
+ handleNextEvents();
}
void BoostASIOEventLoop::eventPosted() {
- boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_);
- if (!isEventInASIOEventLoop_) {
- isEventInASIOEventLoop_ = true;
- ioService_->post(boost::bind(&BoostASIOEventLoop::handleASIOEvent, this));
- }
+ boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_);
+ if (!isEventInASIOEventLoop_) {
+ isEventInASIOEventLoop_ = true;
+ ioService_->post(boost::bind(&BoostASIOEventLoop::handleASIOEvent, this));
+ }
}
}
diff --git a/Swiften/EventLoop/BoostASIOEventLoop.h b/Swiften/EventLoop/BoostASIOEventLoop.h
index a093199..c39aaf5 100644
--- a/Swiften/EventLoop/BoostASIOEventLoop.h
+++ b/Swiften/EventLoop/BoostASIOEventLoop.h
@@ -15,20 +15,20 @@
#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class SWIFTEN_API BoostASIOEventLoop : public EventLoop {
- public:
- BoostASIOEventLoop(boost::shared_ptr<boost::asio::io_service> ioService);
- virtual ~BoostASIOEventLoop();
+ class SWIFTEN_API BoostASIOEventLoop : public EventLoop {
+ public:
+ BoostASIOEventLoop(boost::shared_ptr<boost::asio::io_service> ioService);
+ virtual ~BoostASIOEventLoop();
- protected:
- void handleASIOEvent();
+ protected:
+ void handleASIOEvent();
- virtual void eventPosted();
+ virtual void eventPosted();
- private:
- boost::shared_ptr<boost::asio::io_service> ioService_;
+ private:
+ boost::shared_ptr<boost::asio::io_service> ioService_;
- bool isEventInASIOEventLoop_;
- boost::recursive_mutex isEventInASIOEventLoopMutex_;
- };
+ bool isEventInASIOEventLoop_;
+ boost::recursive_mutex isEventInASIOEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/Cocoa/CocoaEvent.h b/Swiften/EventLoop/Cocoa/CocoaEvent.h
index 1e2c6f6..945056e 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEvent.h
+++ b/Swiften/EventLoop/Cocoa/CocoaEvent.h
@@ -13,7 +13,7 @@
#undef check
namespace Swift {
- class CocoaEventLoop;
+ class CocoaEventLoop;
}
// Using deprecated declaration of instance vars in interface, because this
@@ -22,7 +22,7 @@ namespace Swift {
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
@interface CocoaEvent : NSObject {
- Swift::CocoaEventLoop* eventLoop;
+ Swift::CocoaEventLoop* eventLoop;
}
#pragma clang diagnostic pop
diff --git a/Swiften/EventLoop/Cocoa/CocoaEvent.mm b/Swiften/EventLoop/Cocoa/CocoaEvent.mm
index 8615b48..fc9695b 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEvent.mm
+++ b/Swiften/EventLoop/Cocoa/CocoaEvent.mm
@@ -11,19 +11,19 @@
@implementation CocoaEvent
- (id) init:(Swift::CocoaEventLoop*) el {
- self = [super init];
- if (self != nil) {
- eventLoop = el;
- }
- return self;
+ self = [super init];
+ if (self != nil) {
+ eventLoop = el;
+ }
+ return self;
}
- (void) process {
- eventLoop->handleNextCocoaEvent();
+ eventLoop->handleNextCocoaEvent();
}
- (void) dealloc {
- [super dealloc];
+ [super dealloc];
}
@end
diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.h b/Swiften/EventLoop/Cocoa/CocoaEventLoop.h
index aad6b0a..bbe8390 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.h
+++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.h
@@ -11,18 +11,18 @@
#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class CocoaEventLoop : public EventLoop {
- public:
- CocoaEventLoop();
- virtual ~CocoaEventLoop();
+ class CocoaEventLoop : public EventLoop {
+ public:
+ CocoaEventLoop();
+ virtual ~CocoaEventLoop();
- void handleNextCocoaEvent();
-
- protected:
- virtual void eventPosted();
+ void handleNextCocoaEvent();
- private:
- bool isEventInCocoaEventLoop_;
- boost::recursive_mutex isEventInCocoaEventLoopMutex_;
- };
+ protected:
+ virtual void eventPosted();
+
+ private:
+ bool isEventInCocoaEventLoop_;
+ boost::recursive_mutex isEventInCocoaEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
index 2d7c613..de7c1de 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
+++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
@@ -19,25 +19,25 @@ CocoaEventLoop::~CocoaEventLoop() {
}
void CocoaEventLoop::handleNextCocoaEvent() {
- {
- boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_);
- isEventInCocoaEventLoop_ = false;
- }
- handleNextEvents();
+ {
+ boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_);
+ isEventInCocoaEventLoop_ = false;
+ }
+ handleNextEvents();
}
void CocoaEventLoop::eventPosted() {
- boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_);
- if (!isEventInCocoaEventLoop_) {
- isEventInCocoaEventLoop_ = true;
-
- CocoaEvent* cocoaEvent = [[CocoaEvent alloc] init: this];
- [cocoaEvent
- performSelectorOnMainThread:@selector(process)
- withObject: nil
- waitUntilDone: NO];
- [cocoaEvent release];
- }
+ boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_);
+ if (!isEventInCocoaEventLoop_) {
+ isEventInCocoaEventLoop_ = true;
+
+ CocoaEvent* cocoaEvent = [[CocoaEvent alloc] init: this];
+ [cocoaEvent
+ performSelectorOnMainThread:@selector(process)
+ withObject: nil
+ waitUntilDone: NO];
+ [cocoaEvent release];
+ }
}
}
diff --git a/Swiften/EventLoop/DummyEventLoop.cpp b/Swiften/EventLoop/DummyEventLoop.cpp
index 45e9af7..6eb730a 100644
--- a/Swiften/EventLoop/DummyEventLoop.cpp
+++ b/Swiften/EventLoop/DummyEventLoop.cpp
@@ -14,26 +14,26 @@ DummyEventLoop::DummyEventLoop() : hasEvents_(false) {
}
DummyEventLoop::~DummyEventLoop() {
- if (hasEvents()) {
- std::cerr << "DummyEventLoop: Unhandled events at destruction time" << std::endl;
- }
+ if (hasEvents()) {
+ std::cerr << "DummyEventLoop: Unhandled events at destruction time" << std::endl;
+ }
}
void DummyEventLoop::processEvents() {
- while(hasEvents()) {
- hasEvents_ = false;
- handleNextEvents();
- }
+ while(hasEvents()) {
+ hasEvents_ = false;
+ handleNextEvents();
+ }
}
bool DummyEventLoop::hasEvents() {
- boost::lock_guard<boost::mutex> lock(hasEventsMutex_);
- return hasEvents_;
+ boost::lock_guard<boost::mutex> lock(hasEventsMutex_);
+ return hasEvents_;
}
void DummyEventLoop::eventPosted() {
- boost::lock_guard<boost::mutex> lock(hasEventsMutex_);
- hasEvents_ = true;
+ boost::lock_guard<boost::mutex> lock(hasEventsMutex_);
+ hasEvents_ = true;
}
}
diff --git a/Swiften/EventLoop/DummyEventLoop.h b/Swiften/EventLoop/DummyEventLoop.h
index b41cd09..b78c1a6 100644
--- a/Swiften/EventLoop/DummyEventLoop.h
+++ b/Swiften/EventLoop/DummyEventLoop.h
@@ -15,19 +15,19 @@
#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class SWIFTEN_API DummyEventLoop : public EventLoop {
- public:
- DummyEventLoop();
- virtual ~DummyEventLoop();
+ class SWIFTEN_API DummyEventLoop : public EventLoop {
+ public:
+ DummyEventLoop();
+ virtual ~DummyEventLoop();
- void processEvents();
+ void processEvents();
- bool hasEvents();
+ bool hasEvents();
- virtual void eventPosted();
+ virtual void eventPosted();
- private:
- bool hasEvents_;
- boost::mutex hasEventsMutex_;
- };
+ private:
+ bool hasEvents_;
+ boost::mutex hasEventsMutex_;
+ };
}
diff --git a/Swiften/EventLoop/Event.cpp b/Swiften/EventLoop/Event.cpp
index f3ea228..15d7146 100644
--- a/Swiften/EventLoop/Event.cpp
+++ b/Swiften/EventLoop/Event.cpp
@@ -10,13 +10,13 @@
#include <typeinfo>
std::ostream& operator<<(std::ostream& os, const Swift::Event& e) {
- os << "Event(" << e.id << ",";
- if (e.owner) {
- os << typeid(*e.owner.get()).name();
- }
- else {
- os << "null";
- }
- os << ")";
- return os;
+ os << "Event(" << e.id << ",";
+ if (e.owner) {
+ os << typeid(*e.owner.get()).name();
+ }
+ else {
+ os << "null";
+ }
+ os << ")";
+ return os;
}
diff --git a/Swiften/EventLoop/Event.h b/Swiften/EventLoop/Event.h
index 4585eb3..eecd896 100644
--- a/Swiften/EventLoop/Event.h
+++ b/Swiften/EventLoop/Event.h
@@ -12,19 +12,19 @@
#include <Swiften/EventLoop/EventOwner.h>
namespace Swift {
- class Event {
- public:
- Event(boost::shared_ptr<EventOwner> owner, const boost::function<void()>& callback) : id(~0U), owner(owner), callback(callback) {
- }
+ class Event {
+ public:
+ Event(boost::shared_ptr<EventOwner> owner, const boost::function<void()>& callback) : id(~0U), owner(owner), callback(callback) {
+ }
- bool operator==(const Event& o) const {
- return o.id == id;
- }
+ bool operator==(const Event& o) const {
+ return o.id == id;
+ }
- unsigned int id;
- boost::shared_ptr<EventOwner> owner;
- boost::function<void()> callback;
- };
+ unsigned int id;
+ boost::shared_ptr<EventOwner> owner;
+ boost::function<void()> callback;
+ };
}
std::ostream& operator<<(std::ostream& os, const Swift::Event& e);
diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp
index 8e7add5..2434277 100644
--- a/Swiften/EventLoop/EventLoop.cpp
+++ b/Swiften/EventLoop/EventLoop.cpp
@@ -23,16 +23,16 @@ 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;
- }
+ 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) {
@@ -42,59 +42,59 @@ 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;
- boost::recursive_mutex::scoped_lock lock(removeEventsMutex_);
- {
- std::vector<Event> nextEvents;
- {
- boost::recursive_mutex::scoped_lock 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) {
- invokeCallback(event);
- }
- }
- }
- handlingEvents_ = false;
- }
-
- if (callEventPosted) {
- eventPosted();
- }
+ 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;
+ boost::recursive_mutex::scoped_lock lock(removeEventsMutex_);
+ {
+ std::vector<Event> nextEvents;
+ {
+ boost::recursive_mutex::scoped_lock 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) {
+ invokeCallback(event);
+ }
+ }
+ }
+ handlingEvents_ = false;
+ }
+
+ if (callEventPosted) {
+ eventPosted();
+ }
}
void EventLoop::postEvent(boost::function<void ()> callback, boost::shared_ptr<EventOwner> owner) {
- Event event(owner, callback);
- bool callEventPosted = false;
- {
- boost::recursive_mutex::scoped_lock lock(eventsMutex_);
-
- callEventPosted = events_.empty();
-
- event.id = nextEventID_;
- nextEventID_++;
- events_.push_back(event);
- }
- if (callEventPosted) {
- eventPosted();
- }
+ Event event(owner, callback);
+ bool callEventPosted = false;
+ {
+ boost::recursive_mutex::scoped_lock lock(eventsMutex_);
+
+ callEventPosted = events_.empty();
+
+ event.id = nextEventID_;
+ nextEventID_++;
+ events_.push_back(event);
+ }
+ if (callEventPosted) {
+ eventPosted();
+ }
}
void EventLoop::removeEventsFromOwner(boost::shared_ptr<EventOwner> owner) {
- boost::recursive_mutex::scoped_lock removeLock(removeEventsMutex_);
- boost::recursive_mutex::scoped_lock lock(eventsMutex_);
- events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner);
+ boost::recursive_mutex::scoped_lock removeLock(removeEventsMutex_);
+ boost::recursive_mutex::scoped_lock lock(eventsMutex_);
+ events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner);
}
}
diff --git a/Swiften/EventLoop/EventLoop.h b/Swiften/EventLoop/EventLoop.h
index 2687501..84a3e9d 100644
--- a/Swiften/EventLoop/EventLoop.h
+++ b/Swiften/EventLoop/EventLoop.h
@@ -15,57 +15,57 @@
#include <Swiften/EventLoop/Event.h>
namespace Swift {
- class EventOwner;
+ class EventOwner;
- /**
- * The \ref EventLoop class provides the abstract interface for implementing event loops to use with Swiften.
- *
- * Events are added to the event queue using the \ref postEvent method and can be removed from the queue using
- * the \ref removeEventsFromOwner method.
- */
- class SWIFTEN_API EventLoop {
- public:
- EventLoop();
- virtual ~EventLoop();
+ /**
+ * The \ref EventLoop class provides the abstract interface for implementing event loops to use with Swiften.
+ *
+ * Events are added to the event queue using the \ref postEvent method and can be removed from the queue using
+ * the \ref removeEventsFromOwner method.
+ */
+ class SWIFTEN_API EventLoop {
+ public:
+ EventLoop();
+ virtual ~EventLoop();
- /**
- * The \ref postEvent method allows events to be added to the event queue of the \ref EventLoop.
- * An optional \ref EventOwner can be passed, allowing later removal of events that have not yet been
- * executed using the \ref removeEventsFromOwner method.
- */
- void postEvent(boost::function<void ()> event, boost::shared_ptr<EventOwner> owner = boost::shared_ptr<EventOwner>());
+ /**
+ * The \ref postEvent method allows events to be added to the event queue of the \ref EventLoop.
+ * An optional \ref EventOwner can be passed, allowing later removal of events that have not yet been
+ * executed using the \ref removeEventsFromOwner method.
+ */
+ void postEvent(boost::function<void ()> event, boost::shared_ptr<EventOwner> owner = boost::shared_ptr<EventOwner>());
- /**
- * The \ref removeEventsFromOwner method removes all events from the specified \ref owner from the
- * event queue.
- */
- void removeEventsFromOwner(boost::shared_ptr<EventOwner> owner);
+ /**
+ * The \ref removeEventsFromOwner method removes all events from the specified \ref owner from the
+ * event queue.
+ */
+ void removeEventsFromOwner(boost::shared_ptr<EventOwner> owner);
- protected:
- /**
- * The \ref handleNextEvents method is called by an implementation of the abstract \ref EventLoop class
- * at any point after the virtual \ref eventPosted method has been called.
- * This method does not block, except for short-time synchronization.
- * It can process multiple events before it reutrns.
- * If called recursively, the event queue is not further processed. Instead, \ref eventPosted
- * is called to notify the implementing event loop of the non-empty event queue.
- * It is recommended to not call \ref handleNextEvents inside an event posted to the event loop
- * as this can lead to an infinite loop.
- */
- void handleNextEvents();
+ protected:
+ /**
+ * The \ref handleNextEvents method is called by an implementation of the abstract \ref EventLoop class
+ * at any point after the virtual \ref eventPosted method has been called.
+ * This method does not block, except for short-time synchronization.
+ * It can process multiple events before it reutrns.
+ * If called recursively, the event queue is not further processed. Instead, \ref eventPosted
+ * is called to notify the implementing event loop of the non-empty event queue.
+ * It is recommended to not call \ref handleNextEvents inside an event posted to the event loop
+ * as this can lead to an infinite loop.
+ */
+ void handleNextEvents();
- /**
- * The \ref eventPosted virtual method serves as notification for when events are still available in the queue.
- * It is called after the first event is posted to an empty queue or after an event has been handled in
- * \ref handleNextEvents and there are still remaining events in the queue.
- */
- virtual void eventPosted() = 0;
+ /**
+ * The \ref eventPosted virtual method serves as notification for when events are still available in the queue.
+ * It is called after the first event is posted to an empty queue or after an event has been handled in
+ * \ref handleNextEvents and there are still remaining events in the queue.
+ */
+ virtual void eventPosted() = 0;
- private:
- unsigned int nextEventID_;
- std::list<Event> events_;
- bool handlingEvents_;
- boost::recursive_mutex eventsMutex_;
- boost::recursive_mutex removeEventsMutex_;
- };
+ private:
+ unsigned int nextEventID_;
+ std::list<Event> events_;
+ bool handlingEvents_;
+ boost::recursive_mutex eventsMutex_;
+ boost::recursive_mutex removeEventsMutex_;
+ };
}
diff --git a/Swiften/EventLoop/EventOwner.h b/Swiften/EventLoop/EventOwner.h
index a62a778..cd4a80b 100644
--- a/Swiften/EventLoop/EventOwner.h
+++ b/Swiften/EventLoop/EventOwner.h
@@ -9,8 +9,8 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API EventOwner {
- public:
- virtual ~EventOwner();
- };
+ class SWIFTEN_API EventOwner {
+ public:
+ virtual ~EventOwner();
+ };
}
diff --git a/Swiften/EventLoop/Qt/QtEventLoop.h b/Swiften/EventLoop/Qt/QtEventLoop.h
index 123b6e8..3f5e93c 100644
--- a/Swiften/EventLoop/Qt/QtEventLoop.h
+++ b/Swiften/EventLoop/Qt/QtEventLoop.h
@@ -15,45 +15,45 @@
#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class QtEventLoop : public QObject, public EventLoop {
- public:
- QtEventLoop() : isEventInQtEventLoop_(false) {}
- virtual ~QtEventLoop() {
- QCoreApplication::removePostedEvents(this);
- }
-
- protected:
- virtual void eventPosted() {
- boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_);
- if (!isEventInQtEventLoop_) {
- isEventInQtEventLoop_ = true;
- QCoreApplication::postEvent(this, new Event());
- }
- }
-
- virtual bool event(QEvent* qevent) {
- Event* event = dynamic_cast<Event*>(qevent);
- if (event) {
- {
- boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_);
- isEventInQtEventLoop_ = false;
- }
- handleNextEvents();
- //event->deleteLater(); FIXME: Leak?
- return true;
- }
-
- return false;
- }
-
- private:
- struct Event : public QEvent {
- Event() :
- QEvent(QEvent::User) {
- }
- };
-
- bool isEventInQtEventLoop_;
- boost::recursive_mutex isEventInQtEventLoopMutex_;
- };
+ class QtEventLoop : public QObject, public EventLoop {
+ public:
+ QtEventLoop() : isEventInQtEventLoop_(false) {}
+ virtual ~QtEventLoop() {
+ QCoreApplication::removePostedEvents(this);
+ }
+
+ protected:
+ virtual void eventPosted() {
+ boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_);
+ if (!isEventInQtEventLoop_) {
+ isEventInQtEventLoop_ = true;
+ QCoreApplication::postEvent(this, new Event());
+ }
+ }
+
+ virtual bool event(QEvent* qevent) {
+ Event* event = dynamic_cast<Event*>(qevent);
+ if (event) {
+ {
+ boost::recursive_mutex::scoped_lock lock(isEventInQtEventLoopMutex_);
+ isEventInQtEventLoop_ = false;
+ }
+ handleNextEvents();
+ //event->deleteLater(); FIXME: Leak?
+ return true;
+ }
+
+ return false;
+ }
+
+ private:
+ struct Event : public QEvent {
+ Event() :
+ QEvent(QEvent::User) {
+ }
+ };
+
+ bool isEventInQtEventLoop_;
+ boost::recursive_mutex isEventInQtEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp
index 59e799f..37fecd9 100644
--- a/Swiften/EventLoop/SimpleEventLoop.cpp
+++ b/Swiften/EventLoop/SimpleEventLoop.cpp
@@ -19,40 +19,40 @@ SimpleEventLoop::~SimpleEventLoop() {
}
void SimpleEventLoop::doRun(bool breakAfterEvents) {
- while (isRunning_) {
- {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- while (!eventAvailable_) {
- eventAvailableCondition_.wait(lock);
- }
-
- eventAvailable_ = false;
- }
- runOnce();
- if (breakAfterEvents) {
- return;
- }
- }
+ while (isRunning_) {
+ {
+ boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
+ while (!eventAvailable_) {
+ eventAvailableCondition_.wait(lock);
+ }
+
+ eventAvailable_ = false;
+ }
+ runOnce();
+ if (breakAfterEvents) {
+ return;
+ }
+ }
}
void SimpleEventLoop::runOnce() {
- handleNextEvents();
+ handleNextEvents();
}
void SimpleEventLoop::stop() {
- postEvent(boost::bind(&SimpleEventLoop::doStop, this));
+ postEvent(boost::bind(&SimpleEventLoop::doStop, this));
}
void SimpleEventLoop::doStop() {
- isRunning_ = false;
+ isRunning_ = false;
}
void SimpleEventLoop::eventPosted() {
- {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- eventAvailable_ = true;
- }
- eventAvailableCondition_.notify_one();
+ {
+ boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = true;
+ }
+ eventAvailableCondition_.notify_one();
}
diff --git a/Swiften/EventLoop/SimpleEventLoop.h b/Swiften/EventLoop/SimpleEventLoop.h
index 6374a8a..98b3554 100644
--- a/Swiften/EventLoop/SimpleEventLoop.h
+++ b/Swiften/EventLoop/SimpleEventLoop.h
@@ -13,35 +13,35 @@
#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class SWIFTEN_API SimpleEventLoop : public EventLoop {
- public:
- SimpleEventLoop();
- virtual ~SimpleEventLoop();
+ class SWIFTEN_API SimpleEventLoop : public EventLoop {
+ public:
+ SimpleEventLoop();
+ virtual ~SimpleEventLoop();
- void run() {
- doRun(false);
- }
+ void run() {
+ doRun(false);
+ }
- void runUntilEvents() {
- doRun(true);
- }
+ void runUntilEvents() {
+ doRun(true);
+ }
- void runOnce();
+ void runOnce();
- void stop();
-
- protected:
- virtual void eventPosted();
+ void stop();
- private:
- void doRun(bool breakAfterEvents);
- void doStop();
+ protected:
+ virtual void eventPosted();
- private:
- bool isRunning_;
+ private:
+ void doRun(bool breakAfterEvents);
+ void doStop();
- bool eventAvailable_;
- boost::mutex eventAvailableMutex_;
- boost::condition_variable eventAvailableCondition_;
- };
+ private:
+ bool isRunning_;
+
+ bool eventAvailable_;
+ boost::mutex eventAvailableMutex_;
+ boost::condition_variable eventAvailableCondition_;
+ };
}
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.cpp b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
index c94b085..093b913 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.cpp
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
@@ -20,7 +20,7 @@
namespace Swift {
-SingleThreadedEventLoop::SingleThreadedEventLoop()
+SingleThreadedEventLoop::SingleThreadedEventLoop()
: shouldShutDown_(false), eventAvailable_(false)
{
}
@@ -30,33 +30,33 @@ SingleThreadedEventLoop::~SingleThreadedEventLoop() {
}
void SingleThreadedEventLoop::waitForEvents() {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- while (!eventAvailable_ && !shouldShutDown_) {
- eventAvailableCondition_.wait(lock);
- }
+ boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
+ while (!eventAvailable_ && !shouldShutDown_) {
+ eventAvailableCondition_.wait(lock);
+ }
- if (shouldShutDown_)
- throw EventLoopCanceledException();
+ if (shouldShutDown_)
+ throw EventLoopCanceledException();
}
void SingleThreadedEventLoop::handleEvents() {
- {
- boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
- eventAvailable_ = false;
- }
- handleNextEvents();
+ {
+ boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = false;
+ }
+ handleNextEvents();
}
void SingleThreadedEventLoop::stop() {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- shouldShutDown_ = true;
- eventAvailableCondition_.notify_one();
+ boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
+ shouldShutDown_ = true;
+ eventAvailableCondition_.notify_one();
}
void SingleThreadedEventLoop::eventPosted() {
- boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
- eventAvailable_ = true;
- eventAvailableCondition_.notify_one();
+ boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = true;
+ eventAvailableCondition_.notify_one();
}
} // namespace Swift
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.h b/Swiften/EventLoop/SingleThreadedEventLoop.h
index 39f3fe3..eb897bf 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.h
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.h
@@ -29,39 +29,39 @@
// The SingleThreadedEventLoop class implements an event loop that can be used from such applications.
//
// USAGE:
-//
-// Spawn a new thread in the desired framework and call SingleThreadedEventLoop::waitForEvents(). The method
+//
+// Spawn a new thread in the desired framework and call SingleThreadedEventLoop::waitForEvents(). The method
// blocks until a new event has arrived at which time it'll return, or until the wait is canceled
-// at which time it throws EventLoopCanceledException.
+// at which time it throws EventLoopCanceledException.
//
// When a new event has arrived and SingleThreadedEventLoop::waitForEvents() returns, the caller should then
-// call SingleThreadedEventLoop::handleEvents() on the main GUI thread. For WPF applications, for instance,
+// call SingleThreadedEventLoop::handleEvents() on the main GUI thread. For WPF applications, for instance,
// the Dispatcher class can be used to execute the call on the GUI thread.
//
namespace Swift {
- class SingleThreadedEventLoop : public EventLoop {
- public:
- class EventLoopCanceledException : public std::exception { };
+ class SingleThreadedEventLoop : public EventLoop {
+ public:
+ class EventLoopCanceledException : public std::exception { };
+
+ public:
+ SingleThreadedEventLoop();
+ virtual ~SingleThreadedEventLoop();
- public:
- SingleThreadedEventLoop();
- virtual ~SingleThreadedEventLoop();
+ // Blocks while waiting for new events and returns when new events are available.
+ // Throws EventLoopCanceledException when the wait is canceled.
+ void waitForEvents();
+ void handleEvents();
+ void stop();
- // Blocks while waiting for new events and returns when new events are available.
- // Throws EventLoopCanceledException when the wait is canceled.
- void waitForEvents();
- void handleEvents();
- void stop();
+ protected:
+ virtual void eventPosted();
- protected:
- virtual void eventPosted();
-
- private:
- bool shouldShutDown_;
+ private:
+ bool shouldShutDown_;
- bool eventAvailable_;
- boost::mutex eventAvailableMutex_;
- boost::condition_variable eventAvailableCondition_;
- };
+ bool eventAvailable_;
+ boost::mutex eventAvailableMutex_;
+ boost::condition_variable eventAvailableCondition_;
+ };
}
diff --git a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
index d1274e1..1028b7e 100644
--- a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
+++ b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
@@ -18,74 +18,74 @@
using namespace Swift;
class EventLoopTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(EventLoopTest);
- CPPUNIT_TEST(testPost);
- CPPUNIT_TEST(testRemove);
- CPPUNIT_TEST(testHandleEvent_Recursive);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- events_.clear();
- }
-
- void testPost() {
- SimpleEventLoop testling;
-
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1));
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2));
- testling.stop();
- testling.run();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
- CPPUNIT_ASSERT_EQUAL(1, events_[0]);
- CPPUNIT_ASSERT_EQUAL(2, events_[1]);
- }
-
- void testRemove() {
- SimpleEventLoop testling;
- boost::shared_ptr<MyEventOwner> eventOwner1(new MyEventOwner());
- boost::shared_ptr<MyEventOwner> eventOwner2(new MyEventOwner());
-
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner1);
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2), eventOwner2);
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 3), eventOwner1);
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 4), eventOwner2);
- testling.removeEventsFromOwner(eventOwner2);
- testling.stop();
- testling.run();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
- CPPUNIT_ASSERT_EQUAL(1, events_[0]);
- CPPUNIT_ASSERT_EQUAL(3, events_[1]);
- }
-
- void testHandleEvent_Recursive() {
- DummyEventLoop testling;
- boost::shared_ptr<MyEventOwner> eventOwner(new MyEventOwner());
-
- testling.postEvent(boost::bind(&EventLoopTest::runEventLoop, this, &testling, eventOwner), eventOwner);
- testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 0), eventOwner);
- testling.processEvents();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
- CPPUNIT_ASSERT_EQUAL(0, events_[0]);
- CPPUNIT_ASSERT_EQUAL(1, events_[1]);
- }
-
- private:
- struct MyEventOwner : public EventOwner {};
- void logEvent(int i) {
- events_.push_back(i);
- }
- void runEventLoop(DummyEventLoop* loop, boost::shared_ptr<MyEventOwner> eventOwner) {
- loop->processEvents();
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(events_.size()));
- loop->postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner);
- }
-
- private:
- std::vector<int> events_;
+ CPPUNIT_TEST_SUITE(EventLoopTest);
+ CPPUNIT_TEST(testPost);
+ CPPUNIT_TEST(testRemove);
+ CPPUNIT_TEST(testHandleEvent_Recursive);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ events_.clear();
+ }
+
+ void testPost() {
+ SimpleEventLoop testling;
+
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1));
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2));
+ testling.stop();
+ testling.run();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
+ CPPUNIT_ASSERT_EQUAL(1, events_[0]);
+ CPPUNIT_ASSERT_EQUAL(2, events_[1]);
+ }
+
+ void testRemove() {
+ SimpleEventLoop testling;
+ boost::shared_ptr<MyEventOwner> eventOwner1(new MyEventOwner());
+ boost::shared_ptr<MyEventOwner> eventOwner2(new MyEventOwner());
+
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner1);
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 2), eventOwner2);
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 3), eventOwner1);
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 4), eventOwner2);
+ testling.removeEventsFromOwner(eventOwner2);
+ testling.stop();
+ testling.run();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
+ CPPUNIT_ASSERT_EQUAL(1, events_[0]);
+ CPPUNIT_ASSERT_EQUAL(3, events_[1]);
+ }
+
+ void testHandleEvent_Recursive() {
+ DummyEventLoop testling;
+ boost::shared_ptr<MyEventOwner> eventOwner(new MyEventOwner());
+
+ testling.postEvent(boost::bind(&EventLoopTest::runEventLoop, this, &testling, eventOwner), eventOwner);
+ testling.postEvent(boost::bind(&EventLoopTest::logEvent, this, 0), eventOwner);
+ testling.processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(events_.size()));
+ CPPUNIT_ASSERT_EQUAL(0, events_[0]);
+ CPPUNIT_ASSERT_EQUAL(1, events_[1]);
+ }
+
+ private:
+ struct MyEventOwner : public EventOwner {};
+ void logEvent(int i) {
+ events_.push_back(i);
+ }
+ void runEventLoop(DummyEventLoop* loop, boost::shared_ptr<MyEventOwner> eventOwner) {
+ loop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(events_.size()));
+ loop->postEvent(boost::bind(&EventLoopTest::logEvent, this, 1), eventOwner);
+ }
+
+ private:
+ std::vector<int> events_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(EventLoopTest);
diff --git a/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp b/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp
index 1748953..167fe45 100644
--- a/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp
+++ b/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp
@@ -16,53 +16,53 @@
using namespace Swift;
class SimpleEventLoopTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SimpleEventLoopTest);
- // FIXME: Temporarily disabling run, because it generates a "vector
- // iterator not incrementable" on XP
- //CPPUNIT_TEST(testRun);
- CPPUNIT_TEST(testPostFromMainThread);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SimpleEventLoopTest);
+ // FIXME: Temporarily disabling run, because it generates a "vector
+ // iterator not incrementable" on XP
+ //CPPUNIT_TEST(testRun);
+ CPPUNIT_TEST(testPostFromMainThread);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- counter_ = 0;
- }
+ public:
+ void setUp() {
+ counter_ = 0;
+ }
- void testRun() {
- SimpleEventLoop testling;
- boost::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling));
- testling.run();
+ void testRun() {
+ SimpleEventLoop testling;
+ boost::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling));
+ testling.run();
- CPPUNIT_ASSERT_EQUAL(10, counter_);
- }
+ CPPUNIT_ASSERT_EQUAL(10, counter_);
+ }
- void testPostFromMainThread() {
- SimpleEventLoop testling;
- testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling));
- testling.run();
+ void testPostFromMainThread() {
+ SimpleEventLoop testling;
+ testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling));
+ testling.run();
- CPPUNIT_ASSERT_EQUAL(1, counter_);
- }
+ CPPUNIT_ASSERT_EQUAL(1, counter_);
+ }
- private:
- void runIncrementingThread(SimpleEventLoop* loop) {
- for (unsigned int i = 0; i < 10; ++i) {
- Swift::sleep(1);
- loop->postEvent(boost::bind(&SimpleEventLoopTest::incrementCounter, this));
- }
- loop->stop();
- }
+ private:
+ void runIncrementingThread(SimpleEventLoop* loop) {
+ for (unsigned int i = 0; i < 10; ++i) {
+ Swift::sleep(1);
+ loop->postEvent(boost::bind(&SimpleEventLoopTest::incrementCounter, this));
+ }
+ loop->stop();
+ }
- void incrementCounter() {
- counter_++;
- }
+ void incrementCounter() {
+ counter_++;
+ }
- void incrementCounterAndStop(SimpleEventLoop* loop) {
- counter_++;
- loop->stop();
- }
+ void incrementCounterAndStop(SimpleEventLoop* loop) {
+ counter_++;
+ loop->stop();
+ }
- int counter_;
+ int counter_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SimpleEventLoopTest);
diff --git a/Swiften/Examples/BenchTool/BenchTool.cpp b/Swiften/Examples/BenchTool/BenchTool.cpp
index 49ecd92..f7337b9 100644
--- a/Swiften/Examples/BenchTool/BenchTool.cpp
+++ b/Swiften/Examples/BenchTool/BenchTool.cpp
@@ -28,40 +28,40 @@ static int numberOfInstances = 100;
static void handleConnected() {
- numberOfConnectedClients++;
- std::cout << "Connected " << numberOfConnectedClients << std::endl;
+ numberOfConnectedClients++;
+ std::cout << "Connected " << numberOfConnectedClients << std::endl;
}
int main(int, char**) {
- char* jid = getenv("SWIFT_BENCHTOOL_JID");
- if (!jid) {
- std::cerr << "Please set the SWIFT_BENCHTOOL_JID environment variable" << std::endl;
- return -1;
- }
- char* pass = getenv("SWIFT_BENCHTOOL_PASS");
- if (!pass) {
- std::cerr << "Please set the SWIFT_BENCHTOOL_PASS environment variable" << std::endl;
- return -1;
- }
+ char* jid = getenv("SWIFT_BENCHTOOL_JID");
+ if (!jid) {
+ std::cerr << "Please set the SWIFT_BENCHTOOL_JID environment variable" << std::endl;
+ return -1;
+ }
+ char* pass = getenv("SWIFT_BENCHTOOL_PASS");
+ if (!pass) {
+ std::cerr << "Please set the SWIFT_BENCHTOOL_PASS environment variable" << std::endl;
+ return -1;
+ }
- BlindCertificateTrustChecker trustChecker;
- std::vector<CoreClient*> clients;
- for (int i = 0; i < numberOfInstances; ++i) {
- CoreClient* client = new Swift::CoreClient(JID(jid), createSafeByteArray(std::string(pass)), &networkFactories);
- client->setCertificateTrustChecker(&trustChecker);
- client->onConnected.connect(&handleConnected);
- clients.push_back(client);
- }
-
- for (size_t i = 0; i < clients.size(); ++i) {
- clients[i]->connect();
- }
+ BlindCertificateTrustChecker trustChecker;
+ std::vector<CoreClient*> clients;
+ for (int i = 0; i < numberOfInstances; ++i) {
+ CoreClient* client = new Swift::CoreClient(JID(jid), createSafeByteArray(std::string(pass)), &networkFactories);
+ client->setCertificateTrustChecker(&trustChecker);
+ client->onConnected.connect(&handleConnected);
+ clients.push_back(client);
+ }
- eventLoop.run();
+ for (size_t i = 0; i < clients.size(); ++i) {
+ clients[i]->connect();
+ }
- for (size_t i = 0; i < clients.size(); ++i) {
- delete clients[i];
- }
+ eventLoop.run();
- return 0;
+ for (size_t i = 0; i < clients.size(); ++i) {
+ delete clients[i];
+ }
+
+ return 0;
}
diff --git a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
index 8d1da38..50f857c 100644
--- a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
+++ b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
@@ -31,72 +31,72 @@ static int exitCode = CANNOT_CONNECT;
static boost::bsignals::connection errorConnection;
static void handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> /*info*/, ErrorPayload::ref error) {
- if (!error) {
- errorConnection.disconnect();
- client->disconnect();
- eventLoop.stop();
- exitCode = OK;
- } else {
- errorConnection.disconnect();
- exitCode = DISCO_ERROR;
- }
+ if (!error) {
+ errorConnection.disconnect();
+ client->disconnect();
+ eventLoop.stop();
+ exitCode = OK;
+ } else {
+ errorConnection.disconnect();
+ exitCode = DISCO_ERROR;
+ }
}
static void handleConnected() {
- exitCode = NO_RESPONSE;
- GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(), client->getIQRouter());
- discoInfoRequest->onResponse.connect(&handleServerDiscoInfoResponse);
- discoInfoRequest->send();
+ exitCode = NO_RESPONSE;
+ GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(), client->getIQRouter());
+ discoInfoRequest->onResponse.connect(&handleServerDiscoInfoResponse);
+ discoInfoRequest->send();
}
static void handleDisconnected(const boost::optional<ClientError>&) {
- exitCode = CANNOT_AUTH;
- eventLoop.stop();
+ exitCode = CANNOT_AUTH;
+ eventLoop.stop();
}
int main(int argc, char* argv[]) {
- if (argc < 4 || argc > 5) {
- std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>] <password> <timeout_seconds>" << std::endl;
- return -1;
- }
-
- int argi = 1;
-
- std::string jid = argv[argi++];
- std::string connectHost = "";
- if (argc == 5) {
- connectHost = argv[argi++];
- }
-
- client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories);
- char* timeoutChar = argv[argi++];
- int timeout = atoi(timeoutChar);
- timeout = (timeout ? timeout : 30) * 1000;
- ClientXMLTracer* tracer = new ClientXMLTracer(client);
- client->onConnected.connect(&handleConnected);
- errorConnection = client->onDisconnected.connect(&handleDisconnected);
- std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: "; ;
- if (!connectHost.empty()) {
- std::cout << connectHost << std::endl;
- ClientOptions options;
- options.manualHostname = connectHost;
- client->connect(options);
- } else {
- std::cout << " Default" << std::endl;
- client->connect();
- }
-
- {
- Timer::ref timer = networkFactories.getTimerFactory()->createTimer(timeout);
- timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
- timer->start();
-
- eventLoop.run();
- }
-
- delete tracer;
- delete client;
- return exitCode;
+ if (argc < 4 || argc > 5) {
+ std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>] <password> <timeout_seconds>" << std::endl;
+ return -1;
+ }
+
+ int argi = 1;
+
+ std::string jid = argv[argi++];
+ std::string connectHost = "";
+ if (argc == 5) {
+ connectHost = argv[argi++];
+ }
+
+ client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories);
+ char* timeoutChar = argv[argi++];
+ int timeout = atoi(timeoutChar);
+ timeout = (timeout ? timeout : 30) * 1000;
+ ClientXMLTracer* tracer = new ClientXMLTracer(client);
+ client->onConnected.connect(&handleConnected);
+ errorConnection = client->onDisconnected.connect(&handleDisconnected);
+ std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: "; ;
+ if (!connectHost.empty()) {
+ std::cout << connectHost << std::endl;
+ ClientOptions options;
+ options.manualHostname = connectHost;
+ client->connect(options);
+ } else {
+ std::cout << " Default" << std::endl;
+ client->connect();
+ }
+
+ {
+ Timer::ref timer = networkFactories.getTimerFactory()->createTimer(timeout);
+ timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
+ timer->start();
+
+ eventLoop.run();
+ }
+
+ delete tracer;
+ delete client;
+ return exitCode;
}
diff --git a/Swiften/Examples/LinkLocalTool/main.cpp b/Swiften/Examples/LinkLocalTool/main.cpp
index dabce57..37804fb 100644
--- a/Swiften/Examples/LinkLocalTool/main.cpp
+++ b/Swiften/Examples/LinkLocalTool/main.cpp
@@ -17,33 +17,33 @@
using namespace Swift;
int main(int argc, char* argv[]) {
- if (argc < 2) {
- std::cerr << "Invalid parameters" << std::endl;
- return -1;
- }
-
- SimpleEventLoop eventLoop;
- PlatformDNSSDQuerierFactory factory(&eventLoop);
- boost::shared_ptr<DNSSDQuerier> querier = factory.createQuerier();
- querier->start();
-
- if (std::string(argv[1]) == "browse") {
- boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery();
- browseQuery->startBrowsing();
- eventLoop.run();
- browseQuery->stopBrowsing();
- }
- else if (std::string(argv[1]) == "resolve-service") {
- if (argc < 5) {
- std::cerr << "Invalid parameters" << std::endl;
- return -1;
- }
- boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(DNSSDServiceID(argv[2], argv[3], argv[4]));
- resolveQuery->start();
- eventLoop.run();
- std::cerr << "Done running" << std::endl;
- resolveQuery->stop();
- }
-
- querier->stop();
+ if (argc < 2) {
+ std::cerr << "Invalid parameters" << std::endl;
+ return -1;
+ }
+
+ SimpleEventLoop eventLoop;
+ PlatformDNSSDQuerierFactory factory(&eventLoop);
+ boost::shared_ptr<DNSSDQuerier> querier = factory.createQuerier();
+ querier->start();
+
+ if (std::string(argv[1]) == "browse") {
+ boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery();
+ browseQuery->startBrowsing();
+ eventLoop.run();
+ browseQuery->stopBrowsing();
+ }
+ else if (std::string(argv[1]) == "resolve-service") {
+ if (argc < 5) {
+ std::cerr << "Invalid parameters" << std::endl;
+ return -1;
+ }
+ boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(DNSSDServiceID(argv[2], argv[3], argv[4]));
+ resolveQuery->start();
+ eventLoop.run();
+ std::cerr << "Done running" << std::endl;
+ resolveQuery->stop();
+ }
+
+ querier->stop();
}
diff --git a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
index 216d16d..1aaebac 100644
--- a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
+++ b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
@@ -33,88 +33,88 @@ static JID mucJID;
static JID roomJID;
static void joinMUC() {
- cout << "Joining " << roomJID.toString() << endl;
+ cout << "Joining " << roomJID.toString() << endl;
- muc = client->getMUCManager()->createMUC(roomJID);
- muc->joinAs("SwiftExample");
+ muc = client->getMUCManager()->createMUC(roomJID);
+ muc->joinAs("SwiftExample");
}
static void handleRoomsItemsResponse(boost::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()) {
- roomCount++;
- cout << "\t" << roomCount << ". " << item.getJID().getNode() << " - " << item.getName() << std::endl;
- if (roomCount == 1) {
- roomJID = item.getJID();
- }
- }
- cout << endl;
- joinMUC();
+ 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()) {
+ 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
+ cout << "Connected." << endl;
+ // search for MUC rooms
- GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(mucJID, client->getIQRouter());
- discoItemsRequest->onResponse.connect(&handleRoomsItemsResponse);
+ GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(mucJID, client->getIQRouter());
+ discoItemsRequest->onResponse.connect(&handleRoomsItemsResponse);
- cout << "Request list of rooms." << endl;
- discoItemsRequest->send();
+ cout << "Request list of rooms." << endl;
+ discoItemsRequest->send();
}
static void handleDisconnected(const boost::optional<ClientError>&) {
- cout << "Disconnected." << endl;
+ cout << "Disconnected." << endl;
}
static void handleIncomingMessage(boost::shared_ptr<Message> message) {
- if (message->getFrom().toBare() == roomJID) {
- cout << "[ " << roomJID << " ] " << message->getFrom().getResource() << ": " << message->getBody().get_value_or("") << endl;
- }
+ if (message->getFrom().toBare() == roomJID) {
+ cout << "[ " << roomJID << " ] " << message->getFrom().getResource() << ": " << message->getBody().get_value_or("") << endl;
+ }
}
/*
* Usage: ./MUCListAndJoin <jid> <password> <muc_domain>
*/
int main(int argc, char* argv[]) {
- int ret = 0;
-
- if (argc != 4) {
- cout << "Usage: ./" << argv[0] << " <jid> <password> <muc_domain>" << endl;
- ret = -1;
- }
- else {
- mucJID = JID(argv[3]);
- client = boost::make_shared<Client>(JID(argv[1]), string(argv[2]), &networkFactories);
- client->setAlwaysTrustCertificates();
-
- // Enable the following line for detailed XML logging
- // ClientXMLTracer* tracer = new ClientXMLTracer(client.get());
-
- client->onConnected.connect(&handleConnected);
- client->onDisconnected.connect(&handleDisconnected);
- client->onMessageReceived.connect(&handleIncomingMessage);
-
- cout << "Connecting..." << flush;
- client->connect();
- {
- Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
- timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
-
- Timer::ref disconnectTimer = networkFactories.getTimerFactory()->createTimer(25000);
- disconnectTimer->onTick.connect(boost::bind(&Client::disconnect, client.get()));
-
- timer->start();
- disconnectTimer->start();
-
- eventLoop.run();
- }
- }
- return ret;
+ int ret = 0;
+
+ if (argc != 4) {
+ cout << "Usage: ./" << argv[0] << " <jid> <password> <muc_domain>" << endl;
+ ret = -1;
+ }
+ else {
+ mucJID = JID(argv[3]);
+ client = boost::make_shared<Client>(JID(argv[1]), string(argv[2]), &networkFactories);
+ client->setAlwaysTrustCertificates();
+
+ // Enable the following line for detailed XML logging
+ // ClientXMLTracer* tracer = new ClientXMLTracer(client.get());
+
+ client->onConnected.connect(&handleConnected);
+ client->onDisconnected.connect(&handleDisconnected);
+ client->onMessageReceived.connect(&handleIncomingMessage);
+
+ cout << "Connecting..." << flush;
+ client->connect();
+ {
+ Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
+ timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
+
+ Timer::ref disconnectTimer = networkFactories.getTimerFactory()->createTimer(25000);
+ disconnectTimer->onTick.connect(boost::bind(&Client::disconnect, client.get()));
+
+ timer->start();
+ disconnectTimer->start();
+
+ eventLoop.run();
+ }
+ }
+ return ret;
}
diff --git a/Swiften/Examples/NetworkTool/main.cpp b/Swiften/Examples/NetworkTool/main.cpp
index c3f95e8..0cedfa7 100644
--- a/Swiften/Examples/NetworkTool/main.cpp
+++ b/Swiften/Examples/NetworkTool/main.cpp
@@ -20,67 +20,67 @@ using namespace Swift;
static SimpleEventLoop eventLoop;
static void handleGetPublicIPRequestResponse(const boost::optional<HostAddress>& result) {
- if (result) {
- std::cerr << "Result: " << result->toString() << std::endl;;
- }
- else {
- std::cerr << "No result" << std::endl;
- }
- eventLoop.stop();
+ if (result) {
+ std::cerr << "Result: " << result->toString() << std::endl;;
+ }
+ else {
+ std::cerr << "No result" << std::endl;
+ }
+ eventLoop.stop();
}
static void handleGetForwardPortRequestResponse(const boost::optional<NATPortMapping>& result) {
- if (result) {
- std::cerr << "Result: " << result->getPublicPort() << " -> " << result->getLocalPort() << std::endl;;
- }
- else {
- std::cerr << "No result" << std::endl;
- }
- eventLoop.stop();
+ if (result) {
+ std::cerr << "Result: " << result->getPublicPort() << " -> " << result->getLocalPort() << std::endl;;
+ }
+ else {
+ std::cerr << "No result" << std::endl;
+ }
+ eventLoop.stop();
}
static void handleRemovePortForwardingRequestResponse(const boost::optional<bool> result) {
- if (result && result.get()) {
- std::cerr << "Result: OK" << std::endl;
- }
- else {
- std::cerr << "Result: ERROR" << std::endl;
- }
- eventLoop.stop();
+ if (result && result.get()) {
+ std::cerr << "Result: OK" << std::endl;
+ }
+ else {
+ std::cerr << "Result: ERROR" << std::endl;
+ }
+ eventLoop.stop();
}
int main(int argc, char* argv[]) {
- if (argc < 2) {
- std::cerr << "Invalid parameters" << std::endl;
- return -1;
- }
+ if (argc < 2) {
+ std::cerr << "Invalid parameters" << std::endl;
+ return -1;
+ }
- PlatformNATTraversalWorker natTraverser(&eventLoop);
- if (std::string(argv[1]) == "get-public-ip") {
- boost::shared_ptr<NATTraversalGetPublicIPRequest> query = natTraverser.createGetPublicIPRequest();
- query->onResult.connect(boost::bind(&handleGetPublicIPRequestResponse, _1));
- query->start();
- eventLoop.run();
- }
- else if (std::string(argv[1]) == "add-port-forward") {
- if (argc < 4) {
- std::cerr << "Invalid parameters" << std::endl;
- }
- boost::shared_ptr<NATTraversalForwardPortRequest> query = natTraverser.createForwardPortRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3]));
- query->onResult.connect(boost::bind(&handleGetForwardPortRequestResponse, _1));
- query->start();
- eventLoop.run();
- }
- else if (std::string(argv[1]) == "remove-port-forward") {
- if (argc < 4) {
- std::cerr << "Invalid parameters" << std::endl;
- }
- boost::shared_ptr<NATTraversalRemovePortForwardingRequest> query = natTraverser.createRemovePortForwardingRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3]));
- query->onResult.connect(boost::bind(&handleRemovePortForwardingRequestResponse, _1));
- query->start();
- eventLoop.run();
- }
- else if (std::string(argv[1]) == "get-local-ip") {
- std::cout << PlatformNetworkEnvironment().getLocalAddress().toString() << std::endl;
- }
+ PlatformNATTraversalWorker natTraverser(&eventLoop);
+ if (std::string(argv[1]) == "get-public-ip") {
+ boost::shared_ptr<NATTraversalGetPublicIPRequest> query = natTraverser.createGetPublicIPRequest();
+ query->onResult.connect(boost::bind(&handleGetPublicIPRequestResponse, _1));
+ query->start();
+ eventLoop.run();
+ }
+ else if (std::string(argv[1]) == "add-port-forward") {
+ if (argc < 4) {
+ std::cerr << "Invalid parameters" << std::endl;
+ }
+ boost::shared_ptr<NATTraversalForwardPortRequest> query = natTraverser.createForwardPortRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3]));
+ query->onResult.connect(boost::bind(&handleGetForwardPortRequestResponse, _1));
+ query->start();
+ eventLoop.run();
+ }
+ else if (std::string(argv[1]) == "remove-port-forward") {
+ if (argc < 4) {
+ std::cerr << "Invalid parameters" << std::endl;
+ }
+ boost::shared_ptr<NATTraversalRemovePortForwardingRequest> query = natTraverser.createRemovePortForwardingRequest(boost::lexical_cast<int>(argv[2]), boost::lexical_cast<int>(argv[3]));
+ query->onResult.connect(boost::bind(&handleRemovePortForwardingRequestResponse, _1));
+ query->start();
+ eventLoop.run();
+ }
+ else if (std::string(argv[1]) == "get-local-ip") {
+ std::cout << PlatformNetworkEnvironment().getLocalAddress().toString() << std::endl;
+ }
}
diff --git a/Swiften/Examples/ParserTester/ParserTester.cpp b/Swiften/Examples/ParserTester/ParserTester.cpp
index 25963a6..af79ece 100644
--- a/Swiften/Examples/ParserTester/ParserTester.cpp
+++ b/Swiften/Examples/ParserTester/ParserTester.cpp
@@ -18,44 +18,44 @@
using namespace Swift;
class MyXMPPParserClient : public XMPPParserClient {
- public:
- virtual void handleStreamStart(const ProtocolHeader&) {
- std::cout << "-> Stream start" << std::endl;
- }
- virtual void handleElement(boost::shared_ptr<ToplevelElement> element) {
- std::cout << "-> Element " << typeid(*element.get()).name() << std::endl;
- }
- virtual void handleStreamEnd() {
- std::cout << "-> Stream end" << std::endl;
- }
+ public:
+ virtual void handleStreamStart(const ProtocolHeader&) {
+ std::cout << "-> Stream start" << std::endl;
+ }
+ virtual void handleElement(boost::shared_ptr<ToplevelElement> element) {
+ std::cout << "-> Element " << typeid(*element.get()).name() << std::endl;
+ }
+ virtual void handleStreamEnd() {
+ std::cout << "-> Stream end" << std::endl;
+ }
};
int main(int argc, char* argv[]) {
- if (argc != 2) {
- std::cerr << "Usage: " << argv[0] << " file" << std::endl;
- return 0;
- }
- FullPayloadParserFactoryCollection factories;
- MyXMPPParserClient parserClient;
- PlatformXMLParserFactory xmlParserFactory;
- XMPPParser parser(&parserClient, &factories, &xmlParserFactory);
- ParserTester<XMLParserClient> tester(&parser);
+ if (argc != 2) {
+ std::cerr << "Usage: " << argv[0] << " file" << std::endl;
+ return 0;
+ }
+ FullPayloadParserFactoryCollection factories;
+ MyXMPPParserClient parserClient;
+ PlatformXMLParserFactory xmlParserFactory;
+ XMPPParser parser(&parserClient, &factories, &xmlParserFactory);
+ ParserTester<XMLParserClient> tester(&parser);
- std::string line;
- std::ifstream myfile (argv[1]);
- if (myfile.is_open()) {
- while (!myfile.eof()) {
- getline (myfile,line);
- std::cout << "Parsing: " << line << std::endl;
- if (!tester.parse(line)) {
- std::cerr << "PARSE ERROR" << std::endl;
- return -1;
- }
- }
- myfile.close();
- }
- else {
- std::cerr << "Unable to open file " << argv[1] << std::endl;
- }
- return 0;
+ std::string line;
+ std::ifstream myfile (argv[1]);
+ if (myfile.is_open()) {
+ while (!myfile.eof()) {
+ getline (myfile,line);
+ std::cout << "Parsing: " << line << std::endl;
+ if (!tester.parse(line)) {
+ std::cerr << "PARSE ERROR" << std::endl;
+ return -1;
+ }
+ }
+ myfile.close();
+ }
+ else {
+ std::cerr << "Unable to open file " << argv[1] << std::endl;
+ }
+ return 0;
}
diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp
index bfda44f..c6e75e8 100644
--- a/Swiften/Examples/SendFile/ReceiveFile.cpp
+++ b/Swiften/Examples/SendFile/ReceiveFile.cpp
@@ -36,101 +36,101 @@ 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) {
- //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);
- boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>("out");
- transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out));
- transfer->accept(out);
- }
-
- void handleDisconnected(const boost::optional<ClientError>&) {
- std::cerr << "Error!" << std::endl;
- exit(-1);
- }
-
- void handleFileTransferFinished(
- const boost::optional<FileTransferError>& error,
- boost::shared_ptr<FileWriteBytestream> out) {
- std::cout << "File transfer finished" << std::endl;
- out->close();
- if (error) {
- exit(-1);
- }
- else {
- exit(0);
- }
- }
-
- void exit(int code) {
- exitCode = code;
- stop();
- eventLoop.stop();
- }
-
- private:
- JID jid;
- std::string password;
- Client* client;
- ClientXMLTracer* tracer;
- std::vector<IncomingFileTransfer::ref> incomingFileTransfers;
+ 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) {
+ //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);
+ boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>("out");
+ transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out));
+ transfer->accept(out);
+ }
+
+ void handleDisconnected(const boost::optional<ClientError>&) {
+ std::cerr << "Error!" << std::endl;
+ exit(-1);
+ }
+
+ void handleFileTransferFinished(
+ const boost::optional<FileTransferError>& error,
+ boost::shared_ptr<FileWriteBytestream> out) {
+ std::cout << "File transfer finished" << std::endl;
+ out->close();
+ if (error) {
+ exit(-1);
+ }
+ else {
+ exit(0);
+ }
+ }
+
+ void exit(int code) {
+ exitCode = code;
+ stop();
+ eventLoop.stop();
+ }
+
+ private:
+ JID jid;
+ std::string password;
+ Client* client;
+ ClientXMLTracer* tracer;
+ std::vector<IncomingFileTransfer::ref> incomingFileTransfers;
};
int main(int argc, char* argv[]) {
- if (argc != 3) {
- std::cerr << "Usage: " << argv[0] << " <jid> <password>" << std::endl;
- return -1;
- }
+ if (argc != 3) {
+ std::cerr << "Usage: " << argv[0] << " <jid> <password>" << std::endl;
+ return -1;
+ }
- JID jid(argv[1]);
- FileReceiver fileReceiver(jid, std::string(argv[2]));
- fileReceiver.start();
+ JID jid(argv[1]);
+ FileReceiver fileReceiver(jid, std::string(argv[2]));
+ fileReceiver.start();
- eventLoop.run();
+ eventLoop.run();
- return exitCode;
+ return exitCode;
}
diff --git a/Swiften/Examples/SendFile/SendFile.cpp b/Swiften/Examples/SendFile/SendFile.cpp
index 5f2403a..bed6512 100644
--- a/Swiften/Examples/SendFile/SendFile.cpp
+++ b/Swiften/Examples/SendFile/SendFile.cpp
@@ -38,110 +38,110 @@ static BoostNetworkFactories networkFactories(&eventLoop);
static int exitCode = 2;
class FileSender {
- public:
- FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file) : jid(jid), password(password), recipient(recipient), file(file), tracer(NULL) {
- client = new Swift::Client(jid, password, &networkFactories);
- client->onConnected.connect(boost::bind(&FileSender::handleConnected, this));
- client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1));
- //tracer = new ClientXMLTracer(client);
- client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1));
- }
-
- ~FileSender() {
- delete tracer;
- client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1));
- client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this));
- delete client;
- }
-
- void start() {
- client->connect();
- }
-
- private:
- void handleConnected() {
- std::cout << "Connected. Awaiting presence from receipient." << std::endl;
- client->sendPresence(Presence::create());
- }
-
- void handleCapsChanged(JID jid) {
- if (jid.toBare() == recipient) {
- // create ReadBytestream from file
- boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file);
-
- outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream);
-
- if (outgoingFileTransfer) {
- outgoingFileTransfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1));
- std::cout << "Starting file-transfer to " << recipient.toString() << "." << std::endl;
- outgoingFileTransfer->start();
- // TODO: getting notified about FT status and end
- } else {
- std::cout << recipient << " doesn't support any kind of file transfer!" << std::endl;
- client->disconnect();
- }
- }
- }
-
- void handleDisconnected(const boost::optional<ClientError>& err) {
- if (err) {
- std::cout << "Disconnected due to error ( " << err.get().getType() << " )." << std::endl;
- exit(-1);
- }
- else {
- std::cout << "Successfully disconnected." << std::endl;
- }
- }
-
- void handleFileTransferFinished(const boost::optional<FileTransferError>& error) {
- std::cout << "File transfer finished." << std::endl;
- outgoingFileTransfer.reset();
- if (error) {
- client->disconnect();
- exit(-1);
- }
- else {
- client->disconnect();
- exit(0);
- }
- }
-
- void exit(int code) {
- exitCode = code;
- eventLoop.stop();
- }
-
- private:
- BoostConnectionServer::ref connectionServer;
- OutgoingFileTransfer::ref outgoingFileTransfer;
- JID jid;
- std::string password;
- JID recipient;
- boost::filesystem::path file;
- Client* client;
- ClientXMLTracer* tracer;
+ public:
+ FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file) : jid(jid), password(password), recipient(recipient), file(file), tracer(NULL) {
+ client = new Swift::Client(jid, password, &networkFactories);
+ client->onConnected.connect(boost::bind(&FileSender::handleConnected, this));
+ client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1));
+ //tracer = new ClientXMLTracer(client);
+ client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1));
+ }
+
+ ~FileSender() {
+ delete tracer;
+ client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1));
+ client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this));
+ delete client;
+ }
+
+ void start() {
+ client->connect();
+ }
+
+ private:
+ void handleConnected() {
+ std::cout << "Connected. Awaiting presence from receipient." << std::endl;
+ client->sendPresence(Presence::create());
+ }
+
+ void handleCapsChanged(JID jid) {
+ if (jid.toBare() == recipient) {
+ // create ReadBytestream from file
+ boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file);
+
+ outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream);
+
+ if (outgoingFileTransfer) {
+ outgoingFileTransfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1));
+ std::cout << "Starting file-transfer to " << recipient.toString() << "." << std::endl;
+ outgoingFileTransfer->start();
+ // TODO: getting notified about FT status and end
+ } else {
+ std::cout << recipient << " doesn't support any kind of file transfer!" << std::endl;
+ client->disconnect();
+ }
+ }
+ }
+
+ void handleDisconnected(const boost::optional<ClientError>& err) {
+ if (err) {
+ std::cout << "Disconnected due to error ( " << err.get().getType() << " )." << std::endl;
+ exit(-1);
+ }
+ else {
+ std::cout << "Successfully disconnected." << std::endl;
+ }
+ }
+
+ void handleFileTransferFinished(const boost::optional<FileTransferError>& error) {
+ std::cout << "File transfer finished." << std::endl;
+ outgoingFileTransfer.reset();
+ if (error) {
+ client->disconnect();
+ exit(-1);
+ }
+ else {
+ client->disconnect();
+ exit(0);
+ }
+ }
+
+ void exit(int code) {
+ exitCode = code;
+ eventLoop.stop();
+ }
+
+ private:
+ BoostConnectionServer::ref connectionServer;
+ OutgoingFileTransfer::ref outgoingFileTransfer;
+ JID jid;
+ std::string password;
+ JID recipient;
+ boost::filesystem::path file;
+ Client* client;
+ ClientXMLTracer* tracer;
};
int main(int argc, char* argv[]) {
- if (argc != 5) {
- std::cerr << "Usage: " << argv[0] << " <jid> <password> <recipient> <file>" << std::endl;
- return -1;
- }
-
- //Log::setLogLevel(Log::debug);
-
- JID sender(argv[1]);
- JID recipient(argv[3]);
- FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4]));
- fileSender.start();
- {
- Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
- timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
- timer->start();
-
- eventLoop.run();
- }
-
- return exitCode;
+ if (argc != 5) {
+ std::cerr << "Usage: " << argv[0] << " <jid> <password> <recipient> <file>" << std::endl;
+ return -1;
+ }
+
+ //Log::setLogLevel(Log::debug);
+
+ JID sender(argv[1]);
+ JID recipient(argv[3]);
+ FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4]));
+ fileSender.start();
+ {
+ Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
+ timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
+ timer->start();
+
+ eventLoop.run();
+ }
+
+ return exitCode;
}
diff --git a/Swiften/Examples/SendMessage/SendMessage.cpp b/Swiften/Examples/SendMessage/SendMessage.cpp
index 5f13903..973cda5 100644
--- a/Swiften/Examples/SendMessage/SendMessage.cpp
+++ b/Swiften/Examples/SendMessage/SendMessage.cpp
@@ -30,62 +30,62 @@ static boost::bsignals::connection errorConnection;
static void handleConnected() {
- boost::shared_ptr<Message> message(new Message());
- message->setBody(messageBody);
- message->setTo(recipient);
- client->sendMessage(message);
- exitCode = 0;
- errorConnection.disconnect();
- client->disconnect();
- eventLoop.stop();
+ boost::shared_ptr<Message> message(new Message());
+ message->setBody(messageBody);
+ message->setTo(recipient);
+ client->sendMessage(message);
+ exitCode = 0;
+ errorConnection.disconnect();
+ client->disconnect();
+ eventLoop.stop();
}
static void handleDisconnected(const boost::optional<ClientError>&) {
- std::cerr << "Error!" << std::endl;
- exitCode = 1;
- eventLoop.stop();
+ std::cerr << "Error!" << std::endl;
+ exitCode = 1;
+ eventLoop.stop();
}
int main(int argc, char* argv[]) {
- if (argc < 5 || argc > 6) {
- std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>]<password> <recipient> <message>" << std::endl;
- return -1;
- }
-
- int argi = 1;
-
- std::string jid = argv[argi++];
- std::string connectHost = "";
- if (argc == 6) {
- connectHost = argv[argi++];
- }
-
- client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories);
- client->setAlwaysTrustCertificates();
-
- recipient = JID(argv[argi++]);
- messageBody = std::string(argv[argi++]);
-
- ClientXMLTracer* tracer = new ClientXMLTracer(client);
- client->onConnected.connect(&handleConnected);
- errorConnection = client->onDisconnected.connect(&handleDisconnected);
- if (!connectHost.empty()) {
- ClientOptions options;
- options.manualHostname = connectHost;
- client->connect(options);
- } else {
- client->connect();
- }
-
- {
- Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
- timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
- timer->start();
-
- eventLoop.run();
- }
-
- delete tracer;
- delete client;
- return exitCode;
+ if (argc < 5 || argc > 6) {
+ std::cerr << "Usage: " << argv[0] << " <jid> [<connect_host>]<password> <recipient> <message>" << std::endl;
+ return -1;
+ }
+
+ int argi = 1;
+
+ std::string jid = argv[argi++];
+ std::string connectHost = "";
+ if (argc == 6) {
+ connectHost = argv[argi++];
+ }
+
+ client = new Swift::Client(JID(jid), std::string(argv[argi++]), &networkFactories);
+ client->setAlwaysTrustCertificates();
+
+ recipient = JID(argv[argi++]);
+ messageBody = std::string(argv[argi++]);
+
+ ClientXMLTracer* tracer = new ClientXMLTracer(client);
+ client->onConnected.connect(&handleConnected);
+ errorConnection = client->onDisconnected.connect(&handleDisconnected);
+ if (!connectHost.empty()) {
+ ClientOptions options;
+ options.manualHostname = connectHost;
+ client->connect(options);
+ } else {
+ client->connect();
+ }
+
+ {
+ Timer::ref timer = networkFactories.getTimerFactory()->createTimer(30000);
+ timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
+ timer->start();
+
+ eventLoop.run();
+ }
+
+ delete tracer;
+ delete client;
+ return exitCode;
}
diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp
index d1b0db3..c1fadee 100644
--- a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp
+++ b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp
@@ -14,20 +14,20 @@
using namespace Swift;
boost::shared_ptr<ByteArray> ByteArrayReadBytestream::read(size_t size) {
- size_t readSize = size;
- if (position + readSize > data.size()) {
- readSize = data.size() - position;
- }
- boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>(
- data.begin() + boost::numeric_cast<long long>(position),
- data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize));
+ size_t readSize = size;
+ if (position + readSize > data.size()) {
+ readSize = data.size() - position;
+ }
+ boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>(
+ data.begin() + boost::numeric_cast<long long>(position),
+ data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize));
- onRead(*result);
- position += readSize;
- return result;
+ onRead(*result);
+ position += readSize;
+ return result;
}
void ByteArrayReadBytestream::addData(const std::vector<unsigned char>& moreData) {
- append(data, moreData);
- onDataAvailable();
+ append(data, moreData);
+ onDataAvailable();
}
diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.h b/Swiften/FileTransfer/ByteArrayReadBytestream.h
index eefa80a..a711acb 100644
--- a/Swiften/FileTransfer/ByteArrayReadBytestream.h
+++ b/Swiften/FileTransfer/ByteArrayReadBytestream.h
@@ -13,26 +13,26 @@
#include <Swiften/FileTransfer/ReadBytestream.h>
namespace Swift {
- class SWIFTEN_API ByteArrayReadBytestream : public ReadBytestream {
- public:
- ByteArrayReadBytestream(const std::vector<unsigned char>& data) : data(data), position(0), dataComplete(true) {
- }
+ class SWIFTEN_API ByteArrayReadBytestream : public ReadBytestream {
+ public:
+ ByteArrayReadBytestream(const std::vector<unsigned char>& data) : data(data), position(0), dataComplete(true) {
+ }
- virtual boost::shared_ptr<ByteArray> read(size_t size);
+ virtual boost::shared_ptr<ByteArray> read(size_t size);
- virtual bool isFinished() const {
- return position >= data.size() && dataComplete;
- }
+ virtual bool isFinished() const {
+ return position >= data.size() && dataComplete;
+ }
- virtual void setDataComplete(bool b) {
- dataComplete = b;
- }
+ virtual void setDataComplete(bool b) {
+ dataComplete = b;
+ }
- void addData(const std::vector<unsigned char>& moreData);
+ void addData(const std::vector<unsigned char>& moreData);
- private:
- std::vector<unsigned char> data;
- size_t position;
- bool dataComplete;
- };
+ private:
+ std::vector<unsigned char> data;
+ size_t position;
+ bool dataComplete;
+ };
}
diff --git a/Swiften/FileTransfer/ByteArrayWriteBytestream.h b/Swiften/FileTransfer/ByteArrayWriteBytestream.h
index 08c4d4b..ec9d101 100644
--- a/Swiften/FileTransfer/ByteArrayWriteBytestream.h
+++ b/Swiften/FileTransfer/ByteArrayWriteBytestream.h
@@ -10,22 +10,22 @@
#include <Swiften/FileTransfer/WriteBytestream.h>
namespace Swift {
- class SWIFTEN_API ByteArrayWriteBytestream : public WriteBytestream {
- public:
- ByteArrayWriteBytestream() {
- }
+ class SWIFTEN_API ByteArrayWriteBytestream : public WriteBytestream {
+ public:
+ ByteArrayWriteBytestream() {
+ }
- virtual bool write(const std::vector<unsigned char>& bytes) {
- data.insert(data.end(), bytes.begin(), bytes.end());
- onWrite(bytes);
- return true;
- }
+ virtual bool write(const std::vector<unsigned char>& bytes) {
+ data.insert(data.end(), bytes.begin(), bytes.end());
+ onWrite(bytes);
+ return true;
+ }
- const std::vector<unsigned char>& getData() const {
- return data;
- }
+ const std::vector<unsigned char>& getData() const {
+ return data;
+ }
- private:
- std::vector<unsigned char> data;
- };
+ private:
+ std::vector<unsigned char> data;
+ };
}
diff --git a/Swiften/FileTransfer/BytestreamException.h b/Swiften/FileTransfer/BytestreamException.h
index 202315e..02d1e98 100644
--- a/Swiften/FileTransfer/BytestreamException.h
+++ b/Swiften/FileTransfer/BytestreamException.h
@@ -11,9 +11,9 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API BytestreamException : public std::exception {
- public:
- BytestreamException() {
- }
- };
+ class SWIFTEN_API BytestreamException : public std::exception {
+ public:
+ BytestreamException() {
+ }
+ };
}
diff --git a/Swiften/FileTransfer/BytestreamsRequest.h b/Swiften/FileTransfer/BytestreamsRequest.h
index 447f743..7fa3660 100644
--- a/Swiften/FileTransfer/BytestreamsRequest.h
+++ b/Swiften/FileTransfer/BytestreamsRequest.h
@@ -13,23 +13,23 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API BytestreamsRequest : public GenericRequest<Bytestreams> {
- public:
- typedef boost::shared_ptr<BytestreamsRequest> ref;
+ class SWIFTEN_API BytestreamsRequest : public GenericRequest<Bytestreams> {
+ public:
+ typedef boost::shared_ptr<BytestreamsRequest> ref;
- static ref create(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) {
- return ref(new BytestreamsRequest(jid, payload, router));
- }
+ static ref create(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) {
+ return ref(new BytestreamsRequest(jid, payload, router));
+ }
- static ref create(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) {
- return ref(new BytestreamsRequest(from, to, payload, router));
- }
+ static ref create(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) {
+ return ref(new BytestreamsRequest(from, to, payload, router));
+ }
- private:
- BytestreamsRequest(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, jid, payload, router) {
- }
+ private:
+ BytestreamsRequest(const JID& jid, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, jid, payload, router) {
+ }
- BytestreamsRequest(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, from, to, payload, router) {
- }
- };
+ BytestreamsRequest(const JID& from, const JID& to, boost::shared_ptr<Bytestreams> payload, IQRouter* router) : GenericRequest<Bytestreams>(IQ::Set, from, to, payload, router) {
+ }
+ };
}
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
index 1e68bc6..b54f1c1 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
@@ -33,268 +33,268 @@
using namespace Swift;
DefaultFileTransferTransporter::DefaultFileTransferTransporter(
- const JID& initiator,
- const JID& responder,
- Role role,
- SOCKS5BytestreamRegistry* s5bRegistry,
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- IDGenerator* idGenerator,
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- CryptoProvider* crypto,
- IQRouter* router,
- const FileTransferOptions& options) :
- initiator(initiator),
- responder(responder),
- role(role),
- s5bRegistry(s5bRegistry),
- s5bServerManager(s5bServerManager),
- s5bProxy(s5bProxy),
- crypto(crypto),
- router(router) {
-
- localCandidateGenerator = new LocalJingleTransportCandidateGenerator(
- s5bServerManager,
- s5bProxy,
- role == Initiator ? initiator : responder,
- idGenerator,
- options);
- localCandidateGenerator->onLocalTransportCandidatesGenerated.connect(
- boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1));
-
- remoteCandidateSelector = new RemoteJingleTransportCandidateSelector(
- connectionFactory,
- timerFactory,
- options);
- remoteCandidateSelector->onCandidateSelectFinished.connect(
- boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2));
+ const JID& initiator,
+ const JID& responder,
+ Role role,
+ SOCKS5BytestreamRegistry* s5bRegistry,
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ IDGenerator* idGenerator,
+ ConnectionFactory* connectionFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* crypto,
+ IQRouter* router,
+ const FileTransferOptions& options) :
+ initiator(initiator),
+ responder(responder),
+ role(role),
+ s5bRegistry(s5bRegistry),
+ s5bServerManager(s5bServerManager),
+ s5bProxy(s5bProxy),
+ crypto(crypto),
+ router(router) {
+
+ localCandidateGenerator = new LocalJingleTransportCandidateGenerator(
+ s5bServerManager,
+ s5bProxy,
+ role == Initiator ? initiator : responder,
+ idGenerator,
+ options);
+ localCandidateGenerator->onLocalTransportCandidatesGenerated.connect(
+ boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1));
+
+ remoteCandidateSelector = new RemoteJingleTransportCandidateSelector(
+ connectionFactory,
+ timerFactory,
+ options);
+ remoteCandidateSelector->onCandidateSelectFinished.connect(
+ boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2));
}
DefaultFileTransferTransporter::~DefaultFileTransferTransporter() {
- DefaultFileTransferTransporter::stopGeneratingLocalCandidates();
- remoteCandidateSelector->onCandidateSelectFinished.disconnect(
- boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2));
- delete remoteCandidateSelector;
-
- localCandidateGenerator->onLocalTransportCandidatesGenerated.disconnect(
- boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1));
- delete localCandidateGenerator;
+ DefaultFileTransferTransporter::stopGeneratingLocalCandidates();
+ remoteCandidateSelector->onCandidateSelectFinished.disconnect(
+ boost::bind(&DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished, this, _1, _2));
+ delete remoteCandidateSelector;
+
+ localCandidateGenerator->onLocalTransportCandidatesGenerated.disconnect(
+ boost::bind(&DefaultFileTransferTransporter::handleLocalCandidatesGenerated, this, _1));
+ delete localCandidateGenerator;
}
void DefaultFileTransferTransporter::initialize() {
- s5bSessionID = s5bRegistry->generateSessionID();
+ s5bSessionID = s5bRegistry->generateSessionID();
}
void DefaultFileTransferTransporter::initialize(const std::string& s5bSessionID) {
- this->s5bSessionID = s5bSessionID;
+ this->s5bSessionID = s5bSessionID;
}
void DefaultFileTransferTransporter::startGeneratingLocalCandidates() {
- localCandidateGenerator->start();
+ localCandidateGenerator->start();
}
void DefaultFileTransferTransporter::stopGeneratingLocalCandidates() {
- localCandidateGenerator->stop();
+ localCandidateGenerator->stop();
}
-
+
void DefaultFileTransferTransporter::handleLocalCandidatesGenerated(
- const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
- s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), true);
- s5bProxy->connectToProxies(getSOCKS5DstAddr());
- onLocalCandidatesGenerated(s5bSessionID, candidates, getSOCKS5DstAddr());
+ const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
+ s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), true);
+ s5bProxy->connectToProxies(getSOCKS5DstAddr());
+ onLocalCandidatesGenerated(s5bSessionID, candidates, getSOCKS5DstAddr());
}
void DefaultFileTransferTransporter::handleRemoteCandidateSelectFinished(
- const boost::optional<JingleS5BTransportPayload::Candidate>& candidate,
- boost::shared_ptr<SOCKS5BytestreamClientSession> session) {
- remoteS5BClientSession = session;
- onRemoteCandidateSelectFinished(s5bSessionID, candidate);
+ const boost::optional<JingleS5BTransportPayload::Candidate>& candidate,
+ boost::shared_ptr<SOCKS5BytestreamClientSession> session) {
+ remoteS5BClientSession = session;
+ onRemoteCandidateSelectFinished(s5bSessionID, candidate);
}
void DefaultFileTransferTransporter::addRemoteCandidates(
- const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) {
- remoteCandidateSelector->setSOCKS5DstAddr(dstAddr.empty() ? getRemoteCandidateSOCKS5DstAddr() : dstAddr);
- remoteCandidateSelector->addCandidates(candidates);
+ const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) {
+ remoteCandidateSelector->setSOCKS5DstAddr(dstAddr.empty() ? getRemoteCandidateSOCKS5DstAddr() : dstAddr);
+ remoteCandidateSelector->addCandidates(candidates);
}
void DefaultFileTransferTransporter::startTryingRemoteCandidates() {
- remoteCandidateSelector->startSelectingCandidate();
+ remoteCandidateSelector->startSelectingCandidate();
}
void DefaultFileTransferTransporter::stopTryingRemoteCandidates() {
- remoteCandidateSelector->stopSelectingCandidate();
+ remoteCandidateSelector->stopSelectingCandidate();
}
void DefaultFileTransferTransporter::handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error) {
- onProxyActivated(sessionID, error);
+ onProxyActivated(sessionID, error);
}
void DefaultFileTransferTransporter::startActivatingProxy(const JID& proxyServiceJID) {
- // activate proxy
- SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << "." << std::endl;
- S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>();
- proxyRequest->setSID(s5bSessionID);
- proxyRequest->setActivate(role == Initiator ? responder : initiator);
-
- boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxyServiceJID, proxyRequest, router);
- request->onResponse.connect(boost::bind(&DefaultFileTransferTransporter::handleActivateProxySessionResult, this, s5bSessionID, _2));
- request->send();
+ // activate proxy
+ SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << "." << std::endl;
+ S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>();
+ proxyRequest->setSID(s5bSessionID);
+ proxyRequest->setActivate(role == Initiator ? responder : initiator);
+
+ boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxyServiceJID, proxyRequest, router);
+ request->onResponse.connect(boost::bind(&DefaultFileTransferTransporter::handleActivateProxySessionResult, this, s5bSessionID, _2));
+ request->send();
}
void DefaultFileTransferTransporter::stopActivatingProxy() {
- // TODO
- assert(false);
+ // TODO
+ assert(false);
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBSendSession(
- const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) {
- if (s5bServerManager->getServer()) {
- closeLocalSession();
- }
- closeRemoteSession();
- boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>(
- sessionID, initiator, responder, stream, router);
- ibbSession->setBlockSize(blockSize);
- return boost::make_shared<IBBSendTransportSession>(ibbSession);
+ const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) {
+ if (s5bServerManager->getServer()) {
+ closeLocalSession();
+ }
+ closeRemoteSession();
+ boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>(
+ sessionID, initiator, responder, stream, router);
+ ibbSession->setBlockSize(blockSize);
+ return boost::make_shared<IBBSendTransportSession>(ibbSession);
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBReceiveSession(
- const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) {
- if (s5bServerManager->getServer()) {
- closeLocalSession();
- }
- closeRemoteSession();
- boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>(
- sessionID, initiator, responder, size, stream, router);
- return boost::make_shared<IBBReceiveTransportSession>(ibbSession);
+ const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) {
+ if (s5bServerManager->getServer()) {
+ closeLocalSession();
+ }
+ closeRemoteSession();
+ boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>(
+ sessionID, initiator, responder, size, stream, router);
+ return boost::make_shared<IBBReceiveTransportSession>(ibbSession);
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession(
- boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- closeLocalSession();
- return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(
- remoteS5BClientSession, stream);
+ boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ closeLocalSession();
+ return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(
+ remoteS5BClientSession, stream);
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession(
- boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- closeLocalSession();
- return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(
- remoteS5BClientSession, stream);
+ boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ closeLocalSession();
+ return boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(
+ remoteS5BClientSession, stream);
}
boost::shared_ptr<SOCKS5BytestreamServerSession> DefaultFileTransferTransporter::getServerSession() {
- s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
- std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions =
- s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
- while (serverSessions.size() > 1) {
- boost::shared_ptr<SOCKS5BytestreamServerSession> session = serverSessions.back();
- serverSessions.pop_back();
- session->stop();
- }
- return !serverSessions.empty() ? serverSessions.front() : boost::shared_ptr<SOCKS5BytestreamServerSession>();
+ s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
+ std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions =
+ s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
+ while (serverSessions.size() > 1) {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> session = serverSessions.back();
+ serverSessions.pop_back();
+ session->stop();
+ }
+ return !serverSessions.empty() ? serverSessions.front() : boost::shared_ptr<SOCKS5BytestreamServerSession>();
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession(
- boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
- closeRemoteSession();
- boost::shared_ptr<TransportSession> transportSession;
- if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
- SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
- assert(proxySession);
- transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
- }
-
- if (!transportSession) {
- boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
- if (serverSession) {
- transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
- }
- }
-
- if (!transportSession) {
- transportSession = boost::make_shared<FailingTransportSession>();
- }
- return transportSession;
+ boost::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
+ closeRemoteSession();
+ boost::shared_ptr<TransportSession> transportSession;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
+ assert(proxySession);
+ transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
+ }
+
+ if (!transportSession) {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
+ if (serverSession) {
+ transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
+ }
+ }
+
+ if (!transportSession) {
+ transportSession = boost::make_shared<FailingTransportSession>();
+ }
+ return transportSession;
}
boost::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession(
- boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
- closeRemoteSession();
- boost::shared_ptr<TransportSession> transportSession;
- if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
- SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
- assert(proxySession);
- transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
- }
-
- if (!transportSession) {
- boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
- if (serverSession) {
- transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
- }
- }
-
- if (!transportSession) {
- transportSession = boost::make_shared<FailingTransportSession>();
- }
- return transportSession;
+ boost::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
+ closeRemoteSession();
+ boost::shared_ptr<TransportSession> transportSession;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
+ assert(proxySession);
+ transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
+ }
+
+ if (!transportSession) {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
+ if (serverSession) {
+ transportSession = boost::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
+ }
+ }
+
+ if (!transportSession) {
+ transportSession = boost::make_shared<FailingTransportSession>();
+ }
+ return transportSession;
}
std::string DefaultFileTransferTransporter::getSOCKS5DstAddr() const {
- std::string result;
- if (role == Initiator) {
- result = getInitiatorCandidateSOCKS5DstAddr();
- SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result << std::endl;
- }
- else {
- result = getResponderCandidateSOCKS5DstAddr();
- SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result << std::endl;
- }
- return result;
+ std::string result;
+ if (role == Initiator) {
+ result = getInitiatorCandidateSOCKS5DstAddr();
+ SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result << std::endl;
+ }
+ else {
+ result = getResponderCandidateSOCKS5DstAddr();
+ SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result << std::endl;
+ }
+ return result;
}
std::string DefaultFileTransferTransporter::getInitiatorCandidateSOCKS5DstAddr() const {
- return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + initiator.toString() + responder.toString())));
+ 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())));
+ return Hexify::hexify(crypto->getSHA1Hash(createSafeByteArray(s5bSessionID + responder.toString() + initiator.toString())));
}
std::string DefaultFileTransferTransporter::getRemoteCandidateSOCKS5DstAddr() const {
- if (role == Initiator) {
- return getResponderCandidateSOCKS5DstAddr();
- }
- else {
- return getInitiatorCandidateSOCKS5DstAddr();
- }
+ if (role == Initiator) {
+ return getResponderCandidateSOCKS5DstAddr();
+ }
+ else {
+ return getInitiatorCandidateSOCKS5DstAddr();
+ }
}
std::string DefaultFileTransferTransporter::getLocalCandidateSOCKS5DstAddr() const {
- if (role == Responder) {
- return getResponderCandidateSOCKS5DstAddr();
- }
- else {
- return getInitiatorCandidateSOCKS5DstAddr();
- }
+ if (role == Responder) {
+ return getResponderCandidateSOCKS5DstAddr();
+ }
+ else {
+ return getInitiatorCandidateSOCKS5DstAddr();
+ }
}
void DefaultFileTransferTransporter::closeLocalSession() {
- s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
- if (s5bServerManager->getServer()) {
- std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
- foreach(boost::shared_ptr<SOCKS5BytestreamServerSession> session, serverSessions) {
- session->stop();
- }
- }
+ s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
+ if (s5bServerManager->getServer()) {
+ std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
+ foreach(boost::shared_ptr<SOCKS5BytestreamServerSession> session, serverSessions) {
+ session->stop();
+ }
+ }
}
void DefaultFileTransferTransporter::closeRemoteSession() {
- if (remoteS5BClientSession) {
- remoteS5BClientSession->stop();
- remoteS5BClientSession.reset();
- }
+ if (remoteS5BClientSession) {
+ remoteS5BClientSession->stop();
+ remoteS5BClientSession.reset();
+ }
}
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.h b/Swiften/FileTransfer/DefaultFileTransferTransporter.h
index 026b834..7ec6a12 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.h
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.h
@@ -12,101 +12,101 @@
#include <Swiften/FileTransfer/FileTransferTransporter.h>
namespace Swift {
- class LocalJingleTransportCandidateGenerator;
- class RemoteJingleTransportCandidateSelector;
- class SOCKS5BytestreamRegistry;
- class SOCKS5BytestreamServerManager;
- class SOCKS5BytestreamProxiesManager;
- class SOCKS5BytestreamClientSession;
- class SOCKS5BytestreamServerSession;
- class IDGenerator;
- class IQRouter;
- class ReadBytestream;
- class WriteBytestream;
- class ConnectionFactory;
- class TimerFactory;
- class CryptoProvider;
- class FileTransferOptions;
+ class LocalJingleTransportCandidateGenerator;
+ class RemoteJingleTransportCandidateSelector;
+ class SOCKS5BytestreamRegistry;
+ class SOCKS5BytestreamServerManager;
+ class SOCKS5BytestreamProxiesManager;
+ class SOCKS5BytestreamClientSession;
+ class SOCKS5BytestreamServerSession;
+ class IDGenerator;
+ class IQRouter;
+ class ReadBytestream;
+ class WriteBytestream;
+ class ConnectionFactory;
+ class TimerFactory;
+ class CryptoProvider;
+ class FileTransferOptions;
- class SWIFTEN_API DefaultFileTransferTransporter : public FileTransferTransporter {
- public:
- enum Role {
- Initiator,
- Responder
- };
+ class SWIFTEN_API DefaultFileTransferTransporter : public FileTransferTransporter {
+ public:
+ enum Role {
+ Initiator,
+ Responder
+ };
- DefaultFileTransferTransporter(
- const JID& initiator,
- const JID& responder,
- Role role,
- SOCKS5BytestreamRegistry*,
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- IDGenerator* idGenerator,
- ConnectionFactory*,
- TimerFactory*,
- CryptoProvider*,
- IQRouter*,
- const FileTransferOptions&);
- virtual ~DefaultFileTransferTransporter();
+ DefaultFileTransferTransporter(
+ const JID& initiator,
+ const JID& responder,
+ Role role,
+ SOCKS5BytestreamRegistry*,
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ IDGenerator* idGenerator,
+ ConnectionFactory*,
+ TimerFactory*,
+ CryptoProvider*,
+ IQRouter*,
+ const FileTransferOptions&);
+ virtual ~DefaultFileTransferTransporter();
-
- virtual void initialize();
- virtual void initialize(const std::string& s5bSessionID);
- virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
- virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
+ virtual void initialize();
+ virtual void initialize(const std::string& s5bSessionID);
- virtual void addRemoteCandidates(
- const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE;
- virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE;
- virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE;
+ virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
+ virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
- virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE;
- virtual void stopActivatingProxy() SWIFTEN_OVERRIDE;
+ virtual void addRemoteCandidates(
+ const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE;
+ virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createIBBSendSession(
- const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(
- const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE;
+ virtual void stopActivatingProxy() SWIFTEN_OVERRIDE;
- private:
- void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&);
- void handleRemoteCandidateSelectFinished(
- const boost::optional<JingleS5BTransportPayload::Candidate>&,
- boost::shared_ptr<SOCKS5BytestreamClientSession>);
- void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error);
- void closeLocalSession();
- void closeRemoteSession();
- boost::shared_ptr<SOCKS5BytestreamServerSession> getServerSession();
+ virtual boost::shared_ptr<TransportSession> createIBBSendSession(
+ const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(
+ const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
- std::string getSOCKS5DstAddr() const;
- std::string getInitiatorCandidateSOCKS5DstAddr() const;
- std::string getResponderCandidateSOCKS5DstAddr() const;
- std::string getRemoteCandidateSOCKS5DstAddr() const;
- std::string getLocalCandidateSOCKS5DstAddr() const;
+ private:
+ void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&);
+ void handleRemoteCandidateSelectFinished(
+ const boost::optional<JingleS5BTransportPayload::Candidate>&,
+ boost::shared_ptr<SOCKS5BytestreamClientSession>);
+ void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error);
+ void closeLocalSession();
+ void closeRemoteSession();
+ boost::shared_ptr<SOCKS5BytestreamServerSession> getServerSession();
- private:
- JID initiator;
- JID responder;
- Role role;
- SOCKS5BytestreamRegistry* s5bRegistry;
- SOCKS5BytestreamServerManager* s5bServerManager;
- SOCKS5BytestreamProxiesManager* s5bProxy;
- CryptoProvider* crypto;
- IQRouter* router;
- LocalJingleTransportCandidateGenerator* localCandidateGenerator;
- RemoteJingleTransportCandidateSelector* remoteCandidateSelector;
- std::string s5bSessionID;
- boost::shared_ptr<SOCKS5BytestreamClientSession> remoteS5BClientSession;
- };
+ std::string getSOCKS5DstAddr() const;
+ std::string getInitiatorCandidateSOCKS5DstAddr() const;
+ std::string getResponderCandidateSOCKS5DstAddr() const;
+ std::string getRemoteCandidateSOCKS5DstAddr() const;
+ std::string getLocalCandidateSOCKS5DstAddr() const;
+
+ private:
+ JID initiator;
+ JID responder;
+ Role role;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamServerManager* s5bServerManager;
+ SOCKS5BytestreamProxiesManager* s5bProxy;
+ CryptoProvider* crypto;
+ IQRouter* router;
+ LocalJingleTransportCandidateGenerator* localCandidateGenerator;
+ RemoteJingleTransportCandidateSelector* remoteCandidateSelector;
+ std::string s5bSessionID;
+ boost::shared_ptr<SOCKS5BytestreamClientSession> remoteS5BClientSession;
+ };
}
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp
index ffa0a12..3af2cad 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp
@@ -11,22 +11,22 @@
using namespace Swift;
DefaultFileTransferTransporterFactory::DefaultFileTransferTransporterFactory(
- SOCKS5BytestreamRegistry* s5bRegistry,
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxiesManager,
- IDGenerator* idGenerator,
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- CryptoProvider* cryptoProvider,
- IQRouter* iqRouter) :
- s5bRegistry(s5bRegistry),
- s5bServerManager(s5bServerManager),
- s5bProxiesManager(s5bProxiesManager),
- idGenerator(idGenerator),
- connectionFactory(connectionFactory),
- timerFactory(timerFactory),
- cryptoProvider(cryptoProvider),
- iqRouter(iqRouter)
+ SOCKS5BytestreamRegistry* s5bRegistry,
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxiesManager,
+ IDGenerator* idGenerator,
+ ConnectionFactory* connectionFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* cryptoProvider,
+ IQRouter* iqRouter) :
+ s5bRegistry(s5bRegistry),
+ s5bServerManager(s5bServerManager),
+ s5bProxiesManager(s5bProxiesManager),
+ idGenerator(idGenerator),
+ connectionFactory(connectionFactory),
+ timerFactory(timerFactory),
+ cryptoProvider(cryptoProvider),
+ iqRouter(iqRouter)
{
}
@@ -34,39 +34,39 @@ DefaultFileTransferTransporterFactory::~DefaultFileTransferTransporterFactory()
}
FileTransferTransporter* DefaultFileTransferTransporterFactory::createInitiatorTransporter(
- const JID& initiator, const JID& responder, const FileTransferOptions& options) {
- DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter(
- initiator,
- responder,
- DefaultFileTransferTransporter::Initiator,
- s5bRegistry,
- s5bServerManager,
- s5bProxiesManager,
- idGenerator,
- connectionFactory,
- timerFactory,
- cryptoProvider,
- iqRouter,
- options);
- transporter->initialize();
- return transporter;
+ const JID& initiator, const JID& responder, const FileTransferOptions& options) {
+ DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter(
+ initiator,
+ responder,
+ DefaultFileTransferTransporter::Initiator,
+ s5bRegistry,
+ s5bServerManager,
+ s5bProxiesManager,
+ idGenerator,
+ connectionFactory,
+ timerFactory,
+ cryptoProvider,
+ iqRouter,
+ options);
+ transporter->initialize();
+ return transporter;
}
FileTransferTransporter* DefaultFileTransferTransporterFactory::createResponderTransporter(
- const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions& options) {
- DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter(
- initiator,
- responder,
- DefaultFileTransferTransporter::Responder,
- s5bRegistry,
- s5bServerManager,
- s5bProxiesManager,
- idGenerator,
- connectionFactory,
- timerFactory,
- cryptoProvider,
- iqRouter,
- options);
- transporter->initialize(s5bSessionID);
- return transporter;
+ const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions& options) {
+ DefaultFileTransferTransporter* transporter = new DefaultFileTransferTransporter(
+ initiator,
+ responder,
+ DefaultFileTransferTransporter::Responder,
+ s5bRegistry,
+ s5bServerManager,
+ s5bProxiesManager,
+ idGenerator,
+ connectionFactory,
+ timerFactory,
+ cryptoProvider,
+ iqRouter,
+ options);
+ transporter->initialize(s5bSessionID);
+ return transporter;
}
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h
index 33ed05e..3cc3455 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h
@@ -11,41 +11,41 @@
#include <Swiften/FileTransfer/FileTransferTransporterFactory.h>
namespace Swift {
- class SOCKS5BytestreamRegistry;
- class SOCKS5BytestreamServerManager;
- class SOCKS5BytestreamProxiesManager;
- class IDGenerator;
- class ConnectionFactory;
- class TimerFactory;
- class CryptoProvider;
- class IQRouter;
+ class SOCKS5BytestreamRegistry;
+ class SOCKS5BytestreamServerManager;
+ class SOCKS5BytestreamProxiesManager;
+ class IDGenerator;
+ class ConnectionFactory;
+ class TimerFactory;
+ class CryptoProvider;
+ class IQRouter;
- class SWIFTEN_API DefaultFileTransferTransporterFactory : public FileTransferTransporterFactory {
- public:
- DefaultFileTransferTransporterFactory(
- SOCKS5BytestreamRegistry*,
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- IDGenerator* idGenerator,
- ConnectionFactory*,
- TimerFactory*,
- CryptoProvider*,
- IQRouter*);
- virtual ~DefaultFileTransferTransporterFactory();
+ class SWIFTEN_API DefaultFileTransferTransporterFactory : public FileTransferTransporterFactory {
+ public:
+ DefaultFileTransferTransporterFactory(
+ SOCKS5BytestreamRegistry*,
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ IDGenerator* idGenerator,
+ ConnectionFactory*,
+ TimerFactory*,
+ CryptoProvider*,
+ IQRouter*);
+ virtual ~DefaultFileTransferTransporterFactory();
- virtual FileTransferTransporter* createInitiatorTransporter(
- const JID& initiator, const JID& responder, const FileTransferOptions&) SWIFTEN_OVERRIDE;
- virtual FileTransferTransporter* createResponderTransporter(
- const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) SWIFTEN_OVERRIDE;
+ virtual FileTransferTransporter* createInitiatorTransporter(
+ const JID& initiator, const JID& responder, const FileTransferOptions&) SWIFTEN_OVERRIDE;
+ virtual FileTransferTransporter* createResponderTransporter(
+ const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) SWIFTEN_OVERRIDE;
- private:
- SOCKS5BytestreamRegistry* s5bRegistry;
- SOCKS5BytestreamServerManager* s5bServerManager;
- SOCKS5BytestreamProxiesManager* s5bProxiesManager;
- IDGenerator* idGenerator;
- ConnectionFactory* connectionFactory;
- TimerFactory* timerFactory;
- CryptoProvider* cryptoProvider;
- IQRouter* iqRouter;
- };
+ private:
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamServerManager* s5bServerManager;
+ SOCKS5BytestreamProxiesManager* s5bProxiesManager;
+ IDGenerator* idGenerator;
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+ CryptoProvider* cryptoProvider;
+ IQRouter* iqRouter;
+ };
}
diff --git a/Swiften/FileTransfer/FailingTransportSession.h b/Swiften/FileTransfer/FailingTransportSession.h
index c197052..f0f21eb 100644
--- a/Swiften/FileTransfer/FailingTransportSession.h
+++ b/Swiften/FileTransfer/FailingTransportSession.h
@@ -12,17 +12,17 @@
namespace Swift {
class SWIFTEN_API FailingTransportSession : public TransportSession {
- public:
- virtual ~FailingTransportSession() {
- }
+ public:
+ virtual ~FailingTransportSession() {
+ }
- virtual void start() SWIFTEN_OVERRIDE {
- assert(false);
- onFinished(FileTransferError(FileTransferError::PeerError));
- }
+ virtual void start() SWIFTEN_OVERRIDE {
+ assert(false);
+ onFinished(FileTransferError(FileTransferError::PeerError));
+ }
- virtual void stop() SWIFTEN_OVERRIDE {
- }
+ virtual void stop() SWIFTEN_OVERRIDE {
+ }
};
}
diff --git a/Swiften/FileTransfer/FileReadBytestream.cpp b/Swiften/FileTransfer/FileReadBytestream.cpp
index 4700a9c..7b7127a 100644
--- a/Swiften/FileTransfer/FileReadBytestream.cpp
+++ b/Swiften/FileTransfer/FileReadBytestream.cpp
@@ -20,28 +20,28 @@ FileReadBytestream::FileReadBytestream(const boost::filesystem::path& file) : fi
}
FileReadBytestream::~FileReadBytestream() {
- if (stream) {
- stream->close();
- delete stream;
- stream = NULL;
- }
+ if (stream) {
+ stream->close();
+ delete stream;
+ stream = NULL;
+ }
}
boost::shared_ptr<ByteArray> FileReadBytestream::read(size_t size) {
- if (!stream) {
- stream = new boost::filesystem::ifstream(file, std::ios_base::in|std::ios_base::binary);
- }
- boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>();
- result->resize(size);
- assert(stream->good());
- stream->read(reinterpret_cast<char*>(vecptr(*result)), boost::numeric_cast<std::streamsize>(size));
- result->resize(boost::numeric_cast<size_t>(stream->gcount()));
- onRead(*result);
- return result;
+ if (!stream) {
+ stream = new boost::filesystem::ifstream(file, std::ios_base::in|std::ios_base::binary);
+ }
+ boost::shared_ptr<ByteArray> result = boost::make_shared<ByteArray>();
+ result->resize(size);
+ assert(stream->good());
+ stream->read(reinterpret_cast<char*>(vecptr(*result)), boost::numeric_cast<std::streamsize>(size));
+ result->resize(boost::numeric_cast<size_t>(stream->gcount()));
+ onRead(*result);
+ return result;
}
bool FileReadBytestream::isFinished() const {
- return stream && !stream->good();
+ return stream && !stream->good();
}
}
diff --git a/Swiften/FileTransfer/FileReadBytestream.h b/Swiften/FileTransfer/FileReadBytestream.h
index 5ea197e..24cfbae 100644
--- a/Swiften/FileTransfer/FileReadBytestream.h
+++ b/Swiften/FileTransfer/FileReadBytestream.h
@@ -13,16 +13,16 @@
#include <Swiften/FileTransfer/ReadBytestream.h>
namespace Swift {
- class SWIFTEN_API FileReadBytestream : public ReadBytestream {
- public:
- FileReadBytestream(const boost::filesystem::path& file);
- virtual ~FileReadBytestream();
+ class SWIFTEN_API FileReadBytestream : public ReadBytestream {
+ public:
+ FileReadBytestream(const boost::filesystem::path& file);
+ virtual ~FileReadBytestream();
- virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size);
- virtual bool isFinished() const;
+ virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size);
+ virtual bool isFinished() const;
- private:
- boost::filesystem::path file;
- boost::filesystem::ifstream* stream;
- };
+ private:
+ boost::filesystem::path file;
+ boost::filesystem::ifstream* stream;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransfer.cpp b/Swiften/FileTransfer/FileTransfer.cpp
index 4782d39..32c9f53 100644
--- a/Swiften/FileTransfer/FileTransfer.cpp
+++ b/Swiften/FileTransfer/FileTransfer.cpp
@@ -15,12 +15,12 @@ FileTransfer::~FileTransfer() {
}
void FileTransfer::setState(const State& state) {
- state_ = state;
- onStateChanged(state);
+ state_ = state;
+ onStateChanged(state);
}
void FileTransfer::setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description) {
- filename_ = name;
- fileSizeInBytes_ = size;
- description_ = description;
+ filename_ = name;
+ fileSizeInBytes_ = size;
+ description_ = description;
}
diff --git a/Swiften/FileTransfer/FileTransfer.h b/Swiften/FileTransfer/FileTransfer.h
index ab8e806..b585ab9 100644
--- a/Swiften/FileTransfer/FileTransfer.h
+++ b/Swiften/FileTransfer/FileTransfer.h
@@ -21,68 +21,68 @@
#include <Swiften/FileTransfer/FileTransferError.h>
namespace Swift {
- /**
- * The FileTransfer class provides a general interface for file-transfer
- * implmenetations. Currently, only Jingle File Transfer based on XEP-0234 is
- * implementated in the \ref OutgoingJingleFileTransfer and
- * \ref IncomingJingleFileTransfer classes.
- */
- class SWIFTEN_API FileTransfer {
- public:
- struct State {
- enum Type {
- Initial,
- WaitingForStart,
- Negotiating,
- WaitingForAccept,
- Transferring,
- Canceled,
- Failed,
- Finished
- };
-
- State(Type type, const std::string& message = "") : type(type), message(message) {}
-
- Type type;
- std::string message;
- };
- typedef boost::shared_ptr<FileTransfer> ref;
-
- public:
- FileTransfer();
- virtual ~FileTransfer();
-
- virtual void cancel() = 0;
-
- const std::string& getFileName() const {
- return filename_;
- }
-
- boost::uintmax_t getFileSizeInBytes() const {
- return fileSizeInBytes_;
- }
-
- const State& getState() const {
- return state_;
- }
-
- const std::string& getDescription() const {
- return description_;
- }
-
- public:
- boost::signal<void (size_t /* proccessedBytes */)> onProcessedBytes;
- boost::signal<void (const State&)> onStateChanged;
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
-
- protected:
- void setState(const State& state);
- void setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description);
-
- private:
- boost::uintmax_t fileSizeInBytes_;
- std::string filename_;
- std::string description_;
- State state_;
- };
+ /**
+ * The FileTransfer class provides a general interface for file-transfer
+ * implmenetations. Currently, only Jingle File Transfer based on XEP-0234 is
+ * implementated in the \ref OutgoingJingleFileTransfer and
+ * \ref IncomingJingleFileTransfer classes.
+ */
+ class SWIFTEN_API FileTransfer {
+ public:
+ struct State {
+ enum Type {
+ Initial,
+ WaitingForStart,
+ Negotiating,
+ WaitingForAccept,
+ Transferring,
+ Canceled,
+ Failed,
+ Finished
+ };
+
+ State(Type type, const std::string& message = "") : type(type), message(message) {}
+
+ Type type;
+ std::string message;
+ };
+ typedef boost::shared_ptr<FileTransfer> ref;
+
+ public:
+ FileTransfer();
+ virtual ~FileTransfer();
+
+ virtual void cancel() = 0;
+
+ const std::string& getFileName() const {
+ return filename_;
+ }
+
+ boost::uintmax_t getFileSizeInBytes() const {
+ return fileSizeInBytes_;
+ }
+
+ const State& getState() const {
+ return state_;
+ }
+
+ const std::string& getDescription() const {
+ return description_;
+ }
+
+ public:
+ boost::signal<void (size_t /* proccessedBytes */)> onProcessedBytes;
+ boost::signal<void (const State&)> onStateChanged;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+
+ protected:
+ void setState(const State& state);
+ void setFileInfo(const std::string& name, boost::uintmax_t size, const std::string& description);
+
+ private:
+ boost::uintmax_t fileSizeInBytes_;
+ std::string filename_;
+ std::string description_;
+ State state_;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferError.h b/Swiften/FileTransfer/FileTransferError.h
index eff8ca9..e94ee7a 100644
--- a/Swiften/FileTransfer/FileTransferError.h
+++ b/Swiften/FileTransfer/FileTransferError.h
@@ -9,23 +9,23 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API FileTransferError {
- public:
- enum Type {
- UnknownError,
- PeerError,
- ReadError,
- WriteError,
- ClosedError
- };
+ class SWIFTEN_API FileTransferError {
+ public:
+ enum Type {
+ UnknownError,
+ PeerError,
+ ReadError,
+ WriteError,
+ ClosedError
+ };
- FileTransferError(Type type = UnknownError) : type(type) {}
+ FileTransferError(Type type = UnknownError) : type(type) {}
- Type getType() const {
- return type;
- }
+ Type getType() const {
+ return type;
+ }
- private:
- Type type;
- };
+ private:
+ Type type;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferManager.cpp b/Swiften/FileTransfer/FileTransferManager.cpp
index 0c7d894..94f4ab7 100644
--- a/Swiften/FileTransfer/FileTransferManager.cpp
+++ b/Swiften/FileTransfer/FileTransferManager.cpp
@@ -12,12 +12,12 @@ FileTransferManager::~FileTransferManager() {
}
bool FileTransferManager::isSupportedBy(const DiscoInfo::ref info) {
- if (info) {
- return info->hasFeature(DiscoInfo::JingleFeature)
- && info->hasFeature(DiscoInfo::JingleFTFeature)
- && (info->hasFeature(DiscoInfo::JingleTransportsIBBFeature) || info->hasFeature(DiscoInfo::JingleTransportsS5BFeature));
- }
- return false;
+ if (info) {
+ return info->hasFeature(DiscoInfo::JingleFeature)
+ && info->hasFeature(DiscoInfo::JingleFTFeature)
+ && (info->hasFeature(DiscoInfo::JingleTransportsIBBFeature) || info->hasFeature(DiscoInfo::JingleTransportsS5BFeature));
+ }
+ return false;
}
}
diff --git a/Swiften/FileTransfer/FileTransferManager.h b/Swiften/FileTransfer/FileTransferManager.h
index ec568e8..be2902a 100644
--- a/Swiften/FileTransfer/FileTransferManager.h
+++ b/Swiften/FileTransfer/FileTransferManager.h
@@ -26,29 +26,29 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class ReadBytestream;
-
- class SWIFTEN_API FileTransferManager {
- public:
- virtual ~FileTransferManager();
-
- virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID& to,
- const boost::filesystem::path& filepath,
- const std::string& description,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions& = FileTransferOptions()) = 0;
- virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID& to,
- const std::string& filename,
- const std::string& description,
- const boost::uintmax_t sizeInBytes,
- const boost::posix_time::ptime& lastModified,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions& = FileTransferOptions()) = 0;
-
- static bool isSupportedBy(const DiscoInfo::ref info);
-
- boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
- };
+ class ReadBytestream;
+
+ class SWIFTEN_API FileTransferManager {
+ public:
+ virtual ~FileTransferManager();
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID& to,
+ const boost::filesystem::path& filepath,
+ const std::string& description,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions& = FileTransferOptions()) = 0;
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID& to,
+ const std::string& filename,
+ const std::string& description,
+ const boost::uintmax_t sizeInBytes,
+ const boost::posix_time::ptime& lastModified,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions& = FileTransferOptions()) = 0;
+
+ static bool isSupportedBy(const DiscoInfo::ref info);
+
+ boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
index 2bd6a04..80993ef 100644
--- a/Swiften/FileTransfer/FileTransferManagerImpl.cpp
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
@@ -40,147 +40,147 @@
namespace Swift {
FileTransferManagerImpl::FileTransferManagerImpl(
- const JID& ownJID,
- JingleSessionManager* jingleSessionManager,
- IQRouter* router,
- EntityCapsProvider* capsProvider,
- PresenceOracle* presOracle,
- ConnectionFactory* connectionFactory,
- ConnectionServerFactory* connectionServerFactory,
- TimerFactory* timerFactory,
- DomainNameResolver* domainNameResolver,
- NetworkEnvironment* networkEnvironment,
- NATTraverser* natTraverser,
- CryptoProvider* crypto) :
- iqRouter(router),
- capsProvider(capsProvider),
- presenceOracle(presOracle) {
- bytestreamRegistry = new SOCKS5BytestreamRegistry();
- s5bServerManager = new SOCKS5BytestreamServerManager(
- bytestreamRegistry, connectionServerFactory, networkEnvironment, natTraverser);
- bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, domainNameResolver, iqRouter, JID(ownJID.getDomain()));
-
- transporterFactory = new DefaultFileTransferTransporterFactory(
- bytestreamRegistry,
- s5bServerManager,
- bytestreamProxy,
- &idGenerator,
- connectionFactory,
- timerFactory,
- crypto,
- iqRouter);
- outgoingFTManager = new OutgoingFileTransferManager(
- jingleSessionManager,
- iqRouter,
- transporterFactory,
- timerFactory,
- crypto);
- incomingFTManager = new IncomingFileTransferManager(
- jingleSessionManager,
- transporterFactory,
- timerFactory,
- crypto);
- incomingFTManager->onIncomingFileTransfer.connect(onIncomingFileTransfer);
+ const JID& ownJID,
+ JingleSessionManager* jingleSessionManager,
+ IQRouter* router,
+ EntityCapsProvider* capsProvider,
+ PresenceOracle* presOracle,
+ ConnectionFactory* connectionFactory,
+ ConnectionServerFactory* connectionServerFactory,
+ TimerFactory* timerFactory,
+ DomainNameResolver* domainNameResolver,
+ NetworkEnvironment* networkEnvironment,
+ NATTraverser* natTraverser,
+ CryptoProvider* crypto) :
+ iqRouter(router),
+ capsProvider(capsProvider),
+ presenceOracle(presOracle) {
+ bytestreamRegistry = new SOCKS5BytestreamRegistry();
+ s5bServerManager = new SOCKS5BytestreamServerManager(
+ bytestreamRegistry, connectionServerFactory, networkEnvironment, natTraverser);
+ bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, domainNameResolver, iqRouter, JID(ownJID.getDomain()));
+
+ transporterFactory = new DefaultFileTransferTransporterFactory(
+ bytestreamRegistry,
+ s5bServerManager,
+ bytestreamProxy,
+ &idGenerator,
+ connectionFactory,
+ timerFactory,
+ crypto,
+ iqRouter);
+ outgoingFTManager = new OutgoingFileTransferManager(
+ jingleSessionManager,
+ iqRouter,
+ transporterFactory,
+ timerFactory,
+ crypto);
+ incomingFTManager = new IncomingFileTransferManager(
+ jingleSessionManager,
+ transporterFactory,
+ timerFactory,
+ crypto);
+ incomingFTManager->onIncomingFileTransfer.connect(onIncomingFileTransfer);
}
FileTransferManagerImpl::~FileTransferManagerImpl() {
- delete incomingFTManager;
- delete outgoingFTManager;
- delete transporterFactory;
- delete bytestreamProxy;
- delete s5bServerManager;
- delete bytestreamRegistry;
+ delete incomingFTManager;
+ delete outgoingFTManager;
+ delete transporterFactory;
+ delete bytestreamProxy;
+ delete s5bServerManager;
+ delete bytestreamRegistry;
}
void FileTransferManagerImpl::start() {
}
void FileTransferManagerImpl::stop() {
- s5bServerManager->stop();
+ s5bServerManager->stop();
}
boost::optional<JID> FileTransferManagerImpl::highestPriorityJIDSupportingFileTransfer(const JID& bareJID) {
- JID fullReceipientJID;
- int priority = INT_MIN;
-
- //getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Isode Limited. @ 11:11
- std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID);
-
- //iterate over them
- foreach(Presence::ref pres, presences) {
- if (pres->getPriority() > priority) {
- // look up caps from the jid
- DiscoInfo::ref info = capsProvider->getCaps(pres->getFrom());
- if (isSupportedBy(info)) {
- priority = pres->getPriority();
- fullReceipientJID = pres->getFrom();
- }
- }
- }
-
- return fullReceipientJID.isValid() ? boost::optional<JID>(fullReceipientJID) : boost::optional<JID>();
+ JID fullReceipientJID;
+ int priority = INT_MIN;
+
+ //getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Isode Limited. @ 11:11
+ std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID);
+
+ //iterate over them
+ foreach(Presence::ref pres, presences) {
+ if (pres->getPriority() > priority) {
+ // look up caps from the jid
+ DiscoInfo::ref info = capsProvider->getCaps(pres->getFrom());
+ if (isSupportedBy(info)) {
+ priority = pres->getPriority();
+ fullReceipientJID = pres->getFrom();
+ }
+ }
+ }
+
+ return fullReceipientJID.isValid() ? boost::optional<JID>(fullReceipientJID) : boost::optional<JID>();
}
OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer(
- const JID& to,
- const boost::filesystem::path& filepath,
- const std::string& description,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions& config) {
+ const JID& to,
+ const boost::filesystem::path& filepath,
+ const std::string& description,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions& config) {
#if BOOST_FILESYSTEM_VERSION == 2 // TODO: Delete this when boost 1.44 becomes a minimum requirement, and we no longer need v2
- std::string filename = filepath.filename();
+ std::string filename = filepath.filename();
#else
- std::string filename = pathToString(filepath.filename());
+ std::string filename = pathToString(filepath.filename());
#endif
- boost::uintmax_t sizeInBytes = boost::filesystem::file_size(filepath);
- boost::posix_time::ptime lastModified = boost::posix_time::from_time_t(boost::filesystem::last_write_time(filepath));
- return createOutgoingFileTransfer(to, filename, description, sizeInBytes, lastModified, bytestream, config);
+ boost::uintmax_t sizeInBytes = boost::filesystem::file_size(filepath);
+ boost::posix_time::ptime lastModified = boost::posix_time::from_time_t(boost::filesystem::last_write_time(filepath));
+ return createOutgoingFileTransfer(to, filename, description, sizeInBytes, lastModified, bytestream, config);
}
OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer(
- const JID& to,
- const std::string& filename,
- const std::string& description,
- const boost::uintmax_t sizeInBytes,
- const boost::posix_time::ptime& lastModified,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions& config) {
- JingleFileTransferFileInfo fileInfo;
- fileInfo.setDate(lastModified);
- fileInfo.setSize(sizeInBytes);
- fileInfo.setName(filename);
- fileInfo.setDescription(description);
-
- JID receipient = to;
-
- if(receipient.isBare()) {
- boost::optional<JID> fullJID = highestPriorityJIDSupportingFileTransfer(receipient);
- if (fullJID.is_initialized()) {
- receipient = fullJID.get();
- } else {
- return OutgoingFileTransfer::ref();
- }
- }
-
- assert(!iqRouter->getJID().isBare());
-
- DiscoInfo::ref capabilities = capsProvider->getCaps(receipient);
-
- FileTransferOptions options = config;
- if (capabilities) {
- if (!capabilities->hasFeature(DiscoInfo::JingleTransportsS5BFeature)) {
- options = options.withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false);
- }
- if (!capabilities->hasFeature(DiscoInfo::JingleTransportsIBBFeature)) {
- options = options.withInBandAllowed(false);
- }
- }
- else {
- SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString() << std::endl;
- }
-
- return outgoingFTManager->createOutgoingFileTransfer(iqRouter->getJID(), receipient, bytestream, fileInfo, options);
+ const JID& to,
+ const std::string& filename,
+ const std::string& description,
+ const boost::uintmax_t sizeInBytes,
+ const boost::posix_time::ptime& lastModified,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions& config) {
+ JingleFileTransferFileInfo fileInfo;
+ fileInfo.setDate(lastModified);
+ fileInfo.setSize(sizeInBytes);
+ fileInfo.setName(filename);
+ fileInfo.setDescription(description);
+
+ JID receipient = to;
+
+ if(receipient.isBare()) {
+ boost::optional<JID> fullJID = highestPriorityJIDSupportingFileTransfer(receipient);
+ if (fullJID.is_initialized()) {
+ receipient = fullJID.get();
+ } else {
+ return OutgoingFileTransfer::ref();
+ }
+ }
+
+ assert(!iqRouter->getJID().isBare());
+
+ DiscoInfo::ref capabilities = capsProvider->getCaps(receipient);
+
+ FileTransferOptions options = config;
+ if (capabilities) {
+ if (!capabilities->hasFeature(DiscoInfo::JingleTransportsS5BFeature)) {
+ options = options.withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false);
+ }
+ if (!capabilities->hasFeature(DiscoInfo::JingleTransportsIBBFeature)) {
+ options = options.withInBandAllowed(false);
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString() << std::endl;
+ }
+
+ return outgoingFTManager->createOutgoingFileTransfer(iqRouter->getJID(), receipient, bytestream, fileInfo, options);
}
}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.h b/Swiften/FileTransfer/FileTransferManagerImpl.h
index 49490c8..a939ace 100644
--- a/Swiften/FileTransfer/FileTransferManagerImpl.h
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.h
@@ -30,74 +30,74 @@
#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
namespace Swift {
- class ConnectionFactory;
- class ConnectionServerFactory;
- class CryptoProvider;
- class DomainNameResolver;
- class EntityCapsProvider;
- class FileTransferTransporterFactory;
- class IQRouter;
- class IncomingFileTransferManager;
- class JID;
- class JingleSessionManager;
- class NATTraverser;
- class NetworkEnvironment;
- class OutgoingFileTransferManager;
- class PresenceOracle;
- class ReadBytestream;
- class SOCKS5BytestreamProxiesManager;
- class SOCKS5BytestreamRegistry;
- class SOCKS5BytestreamServerManager;
- class TimerFactory;
+ class ConnectionFactory;
+ class ConnectionServerFactory;
+ class CryptoProvider;
+ class DomainNameResolver;
+ class EntityCapsProvider;
+ class FileTransferTransporterFactory;
+ class IQRouter;
+ class IncomingFileTransferManager;
+ class JID;
+ class JingleSessionManager;
+ class NATTraverser;
+ class NetworkEnvironment;
+ class OutgoingFileTransferManager;
+ class PresenceOracle;
+ class ReadBytestream;
+ class SOCKS5BytestreamProxiesManager;
+ class SOCKS5BytestreamRegistry;
+ class SOCKS5BytestreamServerManager;
+ class TimerFactory;
- class SWIFTEN_API FileTransferManagerImpl : public FileTransferManager {
- public:
- FileTransferManagerImpl(
- const JID& ownFullJID,
- JingleSessionManager* jingleSessionManager,
- IQRouter* router,
- EntityCapsProvider* capsProvider,
- PresenceOracle* presOracle,
- ConnectionFactory* connectionFactory,
- ConnectionServerFactory* connectionServerFactory,
- TimerFactory* timerFactory,
- DomainNameResolver* domainNameResolver,
- NetworkEnvironment* networkEnvironment,
- NATTraverser* natTraverser,
- CryptoProvider* crypto);
- virtual ~FileTransferManagerImpl();
-
- OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID& to,
- const boost::filesystem::path& filepath,
- const std::string& description,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions&) SWIFTEN_OVERRIDE;
- OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID& to,
- const std::string& filename,
- const std::string& description,
- const boost::uintmax_t sizeInBytes,
- const boost::posix_time::ptime& lastModified,
- boost::shared_ptr<ReadBytestream> bytestream,
- const FileTransferOptions&) SWIFTEN_OVERRIDE;
+ class SWIFTEN_API FileTransferManagerImpl : public FileTransferManager {
+ public:
+ FileTransferManagerImpl(
+ const JID& ownFullJID,
+ JingleSessionManager* jingleSessionManager,
+ IQRouter* router,
+ EntityCapsProvider* capsProvider,
+ PresenceOracle* presOracle,
+ ConnectionFactory* connectionFactory,
+ ConnectionServerFactory* connectionServerFactory,
+ TimerFactory* timerFactory,
+ DomainNameResolver* domainNameResolver,
+ NetworkEnvironment* networkEnvironment,
+ NATTraverser* natTraverser,
+ CryptoProvider* crypto);
+ virtual ~FileTransferManagerImpl();
- void start();
- void stop();
-
- private:
- boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID);
-
- private:
- OutgoingFileTransferManager* outgoingFTManager;
- IncomingFileTransferManager* incomingFTManager;
- FileTransferTransporterFactory* transporterFactory;
- IQRouter* iqRouter;
- EntityCapsProvider* capsProvider;
- PresenceOracle* presenceOracle;
- IDGenerator idGenerator;
- SOCKS5BytestreamRegistry* bytestreamRegistry;
- SOCKS5BytestreamProxiesManager* bytestreamProxy;
- SOCKS5BytestreamServerManager* s5bServerManager;
- };
+ OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID& to,
+ const boost::filesystem::path& filepath,
+ const std::string& description,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions&) SWIFTEN_OVERRIDE;
+ OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID& to,
+ const std::string& filename,
+ const std::string& description,
+ const boost::uintmax_t sizeInBytes,
+ const boost::posix_time::ptime& lastModified,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions&) SWIFTEN_OVERRIDE;
+
+ void start();
+ void stop();
+
+ private:
+ boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID);
+
+ private:
+ OutgoingFileTransferManager* outgoingFTManager;
+ IncomingFileTransferManager* incomingFTManager;
+ FileTransferTransporterFactory* transporterFactory;
+ IQRouter* iqRouter;
+ EntityCapsProvider* capsProvider;
+ PresenceOracle* presenceOracle;
+ IDGenerator idGenerator;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ SOCKS5BytestreamProxiesManager* bytestreamProxy;
+ SOCKS5BytestreamServerManager* s5bServerManager;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferOptions.h b/Swiften/FileTransfer/FileTransferOptions.h
index 77c6a8b..2bc4ee1 100644
--- a/Swiften/FileTransfer/FileTransferOptions.h
+++ b/Swiften/FileTransfer/FileTransferOptions.h
@@ -10,57 +10,57 @@
#include <Swiften/Base/Override.h>
namespace Swift {
- class SWIFTEN_API FileTransferOptions {
- public:
- FileTransferOptions() : allowInBand_(true), allowAssisted_(true), allowProxied_(true), allowDirect_(true) {
- }
- SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(FileTransferOptions)
- ~FileTransferOptions();
+ class SWIFTEN_API FileTransferOptions {
+ public:
+ FileTransferOptions() : allowInBand_(true), allowAssisted_(true), allowProxied_(true), allowDirect_(true) {
+ }
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(FileTransferOptions)
+ ~FileTransferOptions();
- FileTransferOptions& withInBandAllowed(bool b) {
- allowInBand_ = b;
- return *this;
- }
+ FileTransferOptions& withInBandAllowed(bool b) {
+ allowInBand_ = b;
+ return *this;
+ }
- bool isInBandAllowed() const {
- return allowInBand_;
- }
+ bool isInBandAllowed() const {
+ return allowInBand_;
+ }
- FileTransferOptions& withAssistedAllowed(bool b) {
- allowAssisted_ = b;
- return *this;
- }
+ FileTransferOptions& withAssistedAllowed(bool b) {
+ allowAssisted_ = b;
+ return *this;
+ }
- bool isAssistedAllowed() const {
- return allowAssisted_;
- }
+ bool isAssistedAllowed() const {
+ return allowAssisted_;
+ }
- FileTransferOptions& withProxiedAllowed(bool b) {
- allowProxied_ = b;
- return *this;
- }
+ FileTransferOptions& withProxiedAllowed(bool b) {
+ allowProxied_ = b;
+ return *this;
+ }
- bool isProxiedAllowed() const {
- return allowProxied_;
- }
+ bool isProxiedAllowed() const {
+ return allowProxied_;
+ }
- FileTransferOptions& withDirectAllowed(bool b) {
- allowDirect_ = b;
- return *this;
- }
+ FileTransferOptions& withDirectAllowed(bool b) {
+ allowDirect_ = b;
+ return *this;
+ }
- bool isDirectAllowed() const {
- return allowDirect_;
- }
+ bool isDirectAllowed() const {
+ return allowDirect_;
+ }
- SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(FileTransferOptions)
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(FileTransferOptions)
- private:
- bool allowInBand_;
- bool allowAssisted_;
- bool allowProxied_;
- bool allowDirect_;
- };
+ private:
+ bool allowInBand_;
+ bool allowAssisted_;
+ bool allowProxied_;
+ bool allowDirect_;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferTransporter.h b/Swiften/FileTransfer/FileTransferTransporter.h
index fe401f0..dc12b0e 100644
--- a/Swiften/FileTransfer/FileTransferTransporter.h
+++ b/Swiften/FileTransfer/FileTransferTransporter.h
@@ -15,46 +15,46 @@
#include <Swiften/Elements/JingleS5BTransportPayload.h>
namespace Swift {
- class TransportSession;
- class ErrorPayload;
- class ReadBytestream;
- class WriteBytestream;
-
- /**
- * @brief The FileTransferTransporter class is an abstract factory definition
- * to generate SOCKS5 bytestream transports or IBB bytestreams for use in file
- * transfers.
- */
- class SWIFTEN_API FileTransferTransporter {
- public:
- virtual ~FileTransferTransporter();
-
- virtual void startGeneratingLocalCandidates() = 0;
- virtual void stopGeneratingLocalCandidates() = 0;
-
- virtual void addRemoteCandidates(
- const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) = 0;
- virtual void startTryingRemoteCandidates() = 0;
- virtual void stopTryingRemoteCandidates() = 0;
-
- virtual void startActivatingProxy(const JID& proxy) = 0;
- virtual void stopActivatingProxy() = 0;
-
- virtual boost::shared_ptr<TransportSession> createIBBSendSession(
- const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) = 0;
- virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(
- const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) = 0;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
-
- boost::signal<void (const std::string& /* sessionID */, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& /* dstAddr */)> onLocalCandidatesGenerated;
- boost::signal<void (const std::string& /* sessionID */, const boost::optional<JingleS5BTransportPayload::Candidate>&)> onRemoteCandidateSelectFinished;
- boost::signal<void (const std::string& /* sessionID */, boost::shared_ptr<ErrorPayload>)> onProxyActivated;
- };
+ class TransportSession;
+ class ErrorPayload;
+ class ReadBytestream;
+ class WriteBytestream;
+
+ /**
+ * @brief The FileTransferTransporter class is an abstract factory definition
+ * to generate SOCKS5 bytestream transports or IBB bytestreams for use in file
+ * transfers.
+ */
+ class SWIFTEN_API FileTransferTransporter {
+ public:
+ virtual ~FileTransferTransporter();
+
+ virtual void startGeneratingLocalCandidates() = 0;
+ virtual void stopGeneratingLocalCandidates() = 0;
+
+ virtual void addRemoteCandidates(
+ const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) = 0;
+ virtual void startTryingRemoteCandidates() = 0;
+ virtual void stopTryingRemoteCandidates() = 0;
+
+ virtual void startActivatingProxy(const JID& proxy) = 0;
+ virtual void stopActivatingProxy() = 0;
+
+ virtual boost::shared_ptr<TransportSession> createIBBSendSession(
+ const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream>) = 0;
+ virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(
+ const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream>) = 0;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+
+ boost::signal<void (const std::string& /* sessionID */, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& /* dstAddr */)> onLocalCandidatesGenerated;
+ boost::signal<void (const std::string& /* sessionID */, const boost::optional<JingleS5BTransportPayload::Candidate>&)> onRemoteCandidateSelectFinished;
+ boost::signal<void (const std::string& /* sessionID */, boost::shared_ptr<ErrorPayload>)> onProxyActivated;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferTransporterFactory.h b/Swiften/FileTransfer/FileTransferTransporterFactory.h
index a1af4af..4adf32e 100644
--- a/Swiften/FileTransfer/FileTransferTransporterFactory.h
+++ b/Swiften/FileTransfer/FileTransferTransporterFactory.h
@@ -11,22 +11,22 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class JID;
- class FileTransferTransporter;
- class FileTransferOptions;
+ class JID;
+ class FileTransferTransporter;
+ class FileTransferOptions;
- class SWIFTEN_API FileTransferTransporterFactory {
- public:
- virtual ~FileTransferTransporterFactory();
+ class SWIFTEN_API FileTransferTransporterFactory {
+ public:
+ virtual ~FileTransferTransporterFactory();
- virtual FileTransferTransporter* createInitiatorTransporter(
- const JID& initiator,
- const JID& responder,
- const FileTransferOptions& options) = 0;
- virtual FileTransferTransporter* createResponderTransporter(
- const JID& initiator,
- const JID& responder,
- const std::string& s5bSessionID,
- const FileTransferOptions& options) = 0;
- };
+ virtual FileTransferTransporter* createInitiatorTransporter(
+ const JID& initiator,
+ const JID& responder,
+ const FileTransferOptions& options) = 0;
+ virtual FileTransferTransporter* createResponderTransporter(
+ const JID& initiator,
+ const JID& responder,
+ const std::string& s5bSessionID,
+ const FileTransferOptions& options) = 0;
+ };
}
diff --git a/Swiften/FileTransfer/FileWriteBytestream.cpp b/Swiften/FileTransfer/FileWriteBytestream.cpp
index c39d63a..b07f444 100644
--- a/Swiften/FileTransfer/FileWriteBytestream.cpp
+++ b/Swiften/FileTransfer/FileWriteBytestream.cpp
@@ -17,36 +17,36 @@ FileWriteBytestream::FileWriteBytestream(const boost::filesystem::path& file) :
}
FileWriteBytestream::~FileWriteBytestream() {
- if (stream) {
- stream->close();
- delete stream;
- stream = NULL;
- }
+ if (stream) {
+ stream->close();
+ delete stream;
+ stream = NULL;
+ }
}
bool FileWriteBytestream::write(const std::vector<unsigned char>& data) {
- if (data.empty()) {
- return true;
- }
- if (!stream) {
- stream = new boost::filesystem::ofstream(file, std::ios_base::out|std::ios_base::binary);
- }
- if (stream->good()) {
- stream->write(reinterpret_cast<const char*>(&data[0]), boost::numeric_cast<std::streamsize>(data.size()));
- if (stream->good()) {
- onWrite(data);
- return true;
- }
- }
- return false;
+ if (data.empty()) {
+ return true;
+ }
+ if (!stream) {
+ stream = new boost::filesystem::ofstream(file, std::ios_base::out|std::ios_base::binary);
+ }
+ if (stream->good()) {
+ stream->write(reinterpret_cast<const char*>(&data[0]), boost::numeric_cast<std::streamsize>(data.size()));
+ if (stream->good()) {
+ onWrite(data);
+ return true;
+ }
+ }
+ return false;
}
void FileWriteBytestream::close() {
- if (stream) {
- stream->close();
- delete stream;
- stream = NULL;
- }
+ if (stream) {
+ stream->close();
+ delete stream;
+ stream = NULL;
+ }
}
}
diff --git a/Swiften/FileTransfer/FileWriteBytestream.h b/Swiften/FileTransfer/FileWriteBytestream.h
index 02e1b46..c563789 100644
--- a/Swiften/FileTransfer/FileWriteBytestream.h
+++ b/Swiften/FileTransfer/FileWriteBytestream.h
@@ -13,16 +13,16 @@
#include <Swiften/FileTransfer/WriteBytestream.h>
namespace Swift {
- class SWIFTEN_API FileWriteBytestream : public WriteBytestream {
- public:
- FileWriteBytestream(const boost::filesystem::path& file);
- virtual ~FileWriteBytestream();
+ class SWIFTEN_API FileWriteBytestream : public WriteBytestream {
+ public:
+ FileWriteBytestream(const boost::filesystem::path& file);
+ virtual ~FileWriteBytestream();
- virtual bool write(const std::vector<unsigned char>&);
- void close();
+ virtual bool write(const std::vector<unsigned char>&);
+ void close();
- private:
- boost::filesystem::path file;
- boost::filesystem::ofstream* stream;
- };
+ private:
+ boost::filesystem::path file;
+ boost::filesystem::ofstream* stream;
+ };
}
diff --git a/Swiften/FileTransfer/IBBReceiveSession.cpp b/Swiften/FileTransfer/IBBReceiveSession.cpp
index cce263b..5a29ccb 100644
--- a/Swiften/FileTransfer/IBBReceiveSession.cpp
+++ b/Swiften/FileTransfer/IBBReceiveSession.cpp
@@ -19,100 +19,100 @@
namespace Swift {
class IBBReceiveSession::IBBResponder : public SetResponder<IBB> {
- public:
- IBBResponder(IBBReceiveSession* session, IQRouter* router) : SetResponder<IBB>(router), session(session), sequenceNumber(0), receivedSize(0) {
- setFinal(false);
- }
+ public:
+ IBBResponder(IBBReceiveSession* session, IQRouter* router) : SetResponder<IBB>(router), session(session), sequenceNumber(0), receivedSize(0) {
+ setFinal(false);
+ }
- virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) {
- if (from == session->from && ibb->getStreamID() == session->id) {
- if (ibb->getAction() == IBB::Data) {
- if (sequenceNumber == ibb->getSequenceNumber()) {
- session->bytestream->write(ibb->getData());
- receivedSize += ibb->getData().size();
- sequenceNumber++;
- sendResponse(from, id, IBB::ref());
- if (receivedSize >= session->size) {
- if (receivedSize > session->size) {
- SWIFT_LOG(warning) << "Received more data than expected";
- }
- session->finish(boost::optional<FileTransferError>());
- }
- }
- else {
- SWIFT_LOG(warning) << "Received data out of order";
- sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
- session->finish(FileTransferError(FileTransferError::ClosedError));
- }
- }
- else if (ibb->getAction() == IBB::Open) {
- SWIFT_LOG(debug) << "IBB open received";
- sendResponse(from, id, IBB::ref());
- }
- else if (ibb->getAction() == IBB::Close) {
- SWIFT_LOG(debug) << "IBB close received";
- sendResponse(from, id, IBB::ref());
- session->finish(FileTransferError(FileTransferError::ClosedError));
- }
- return true;
- }
- SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id;
- return false;
- }
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) {
+ if (from == session->from && ibb->getStreamID() == session->id) {
+ if (ibb->getAction() == IBB::Data) {
+ if (sequenceNumber == ibb->getSequenceNumber()) {
+ session->bytestream->write(ibb->getData());
+ receivedSize += ibb->getData().size();
+ sequenceNumber++;
+ sendResponse(from, id, IBB::ref());
+ if (receivedSize >= session->size) {
+ if (receivedSize > session->size) {
+ SWIFT_LOG(warning) << "Received more data than expected";
+ }
+ session->finish(boost::optional<FileTransferError>());
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "Received data out of order";
+ sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
+ session->finish(FileTransferError(FileTransferError::ClosedError));
+ }
+ }
+ else if (ibb->getAction() == IBB::Open) {
+ SWIFT_LOG(debug) << "IBB open received";
+ sendResponse(from, id, IBB::ref());
+ }
+ else if (ibb->getAction() == IBB::Close) {
+ SWIFT_LOG(debug) << "IBB close received";
+ sendResponse(from, id, IBB::ref());
+ session->finish(FileTransferError(FileTransferError::ClosedError));
+ }
+ return true;
+ }
+ SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id;
+ return false;
+ }
- private:
- IBBReceiveSession* session;
- int sequenceNumber;
- unsigned long long receivedSize;
+ private:
+ IBBReceiveSession* session;
+ int sequenceNumber;
+ unsigned long long receivedSize;
};
IBBReceiveSession::IBBReceiveSession(
- const std::string& id,
- const JID& from,
- const JID& to,
- unsigned long long size,
- boost::shared_ptr<WriteBytestream> bytestream,
- IQRouter* router) :
- id(id),
- from(from),
- to(to),
- size(size),
- bytestream(bytestream),
- router(router),
- active(false) {
- assert(!id.empty());
- assert(from.isValid());
- responder = new IBBResponder(this, router);
+ const std::string& id,
+ const JID& from,
+ const JID& to,
+ unsigned long long size,
+ boost::shared_ptr<WriteBytestream> bytestream,
+ IQRouter* router) :
+ id(id),
+ from(from),
+ to(to),
+ size(size),
+ bytestream(bytestream),
+ router(router),
+ active(false) {
+ assert(!id.empty());
+ assert(from.isValid());
+ responder = new IBBResponder(this, router);
}
IBBReceiveSession::~IBBReceiveSession() {
- if (active) {
- SWIFT_LOG(warning) << "Session still active";
- }
- delete responder;
+ if (active) {
+ SWIFT_LOG(warning) << "Session still active";
+ }
+ delete responder;
}
void IBBReceiveSession::start() {
- SWIFT_LOG(debug) << "receive session started";
- active = true;
- responder->start();
+ SWIFT_LOG(debug) << "receive session started";
+ active = true;
+ responder->start();
}
void IBBReceiveSession::stop() {
- SWIFT_LOG(debug) << "receive session stopped";
- responder->stop();
- if (active) {
- if (router->isAvailable()) {
- IBBRequest::create(to, from, IBB::createIBBClose(id), router)->send();
- }
- finish(boost::optional<FileTransferError>());
- }
+ SWIFT_LOG(debug) << "receive session stopped";
+ responder->stop();
+ if (active) {
+ if (router->isAvailable()) {
+ IBBRequest::create(to, from, IBB::createIBBClose(id), router)->send();
+ }
+ finish(boost::optional<FileTransferError>());
+ }
}
void IBBReceiveSession::finish(boost::optional<FileTransferError> error) {
- active = false;
- onFinished(error);
+ active = false;
+ onFinished(error);
}
}
diff --git a/Swiften/FileTransfer/IBBReceiveSession.h b/Swiften/FileTransfer/IBBReceiveSession.h
index c6f7211..3eec96e 100644
--- a/Swiften/FileTransfer/IBBReceiveSession.h
+++ b/Swiften/FileTransfer/IBBReceiveSession.h
@@ -17,47 +17,47 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class IQRouter;
-
- class SWIFTEN_API IBBReceiveSession {
- public:
- IBBReceiveSession(
- const std::string& id,
- const JID& from,
- const JID& to,
- unsigned long long size,
- boost::shared_ptr<WriteBytestream> bytestream,
- IQRouter* router);
- ~IBBReceiveSession();
-
- void start();
- void stop();
-
- const JID& getSender() const {
- return from;
- }
-
- const JID& getReceiver() const {
- return to;
- }
-
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
-
- private:
- bool handleSetRequest(const JID& from, const JID& to, const std::string& id, IBB::ref payload);
- void finish(boost::optional<FileTransferError>);
-
- private:
- class IBBResponder;
- friend class IBBResponder;
-
- std::string id;
- JID from;
- JID to;
- unsigned long long size;
- boost::shared_ptr<WriteBytestream> bytestream;
- IQRouter* router;
- IBBResponder* responder;
- bool active;
- };
+ class IQRouter;
+
+ class SWIFTEN_API IBBReceiveSession {
+ public:
+ IBBReceiveSession(
+ const std::string& id,
+ const JID& from,
+ const JID& to,
+ unsigned long long size,
+ boost::shared_ptr<WriteBytestream> bytestream,
+ IQRouter* router);
+ ~IBBReceiveSession();
+
+ void start();
+ void stop();
+
+ const JID& getSender() const {
+ return from;
+ }
+
+ const JID& getReceiver() const {
+ return to;
+ }
+
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+
+ private:
+ bool handleSetRequest(const JID& from, const JID& to, const std::string& id, IBB::ref payload);
+ void finish(boost::optional<FileTransferError>);
+
+ private:
+ class IBBResponder;
+ friend class IBBResponder;
+
+ std::string id;
+ JID from;
+ JID to;
+ unsigned long long size;
+ boost::shared_ptr<WriteBytestream> bytestream;
+ IQRouter* router;
+ IBBResponder* responder;
+ bool active;
+ };
}
diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
index ba56728..2e19b75 100644
--- a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
+++ b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
@@ -11,18 +11,18 @@
namespace Swift {
IBBReceiveTransportSession::IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session) : session(session) {
- finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
+ finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
}
IBBReceiveTransportSession::~IBBReceiveTransportSession() {
}
void IBBReceiveTransportSession::start() {
- session->start();
+ session->start();
}
void IBBReceiveTransportSession::stop() {
- session->stop();
+ session->stop();
}
}
diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.h b/Swiften/FileTransfer/IBBReceiveTransportSession.h
index 8a7c620..f66731b 100644
--- a/Swiften/FileTransfer/IBBReceiveTransportSession.h
+++ b/Swiften/FileTransfer/IBBReceiveTransportSession.h
@@ -14,17 +14,17 @@
namespace Swift {
class SWIFTEN_API IBBReceiveTransportSession : public TransportSession {
- public:
- IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session);
- virtual ~IBBReceiveTransportSession();
+ public:
+ IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session);
+ virtual ~IBBReceiveTransportSession();
- virtual void start() SWIFTEN_OVERRIDE;
- virtual void stop() SWIFTEN_OVERRIDE;
+ virtual void start() SWIFTEN_OVERRIDE;
+ virtual void stop() SWIFTEN_OVERRIDE;
- private:
- boost::shared_ptr<IBBReceiveSession> session;
- boost::bsignals::scoped_connection finishedConnection;
- boost::bsignals::scoped_connection bytesSentConnection;
+ private:
+ boost::shared_ptr<IBBReceiveSession> session;
+ boost::bsignals::scoped_connection finishedConnection;
+ boost::bsignals::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/IBBRequest.h b/Swiften/FileTransfer/IBBRequest.h
index dc63b90..165dd21 100644
--- a/Swiften/FileTransfer/IBBRequest.h
+++ b/Swiften/FileTransfer/IBBRequest.h
@@ -11,16 +11,16 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API IBBRequest : public GenericRequest<IBB> {
- public:
- typedef boost::shared_ptr<IBBRequest> ref;
+ class SWIFTEN_API IBBRequest : public GenericRequest<IBB> {
+ public:
+ typedef boost::shared_ptr<IBBRequest> ref;
- static ref create(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) {
- return ref(new IBBRequest(from, to, payload, router));
- }
+ static ref create(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) {
+ return ref(new IBBRequest(from, to, payload, router));
+ }
- private:
- IBBRequest(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) : GenericRequest<IBB>(IQ::Set, from, to, payload, router) {
- }
- };
+ private:
+ IBBRequest(const JID& from, const JID& to, boost::shared_ptr<IBB> payload, IQRouter* router) : GenericRequest<IBB>(IQ::Set, from, to, payload, router) {
+ }
+ };
}
diff --git a/Swiften/FileTransfer/IBBSendSession.cpp b/Swiften/FileTransfer/IBBSendSession.cpp
index 9f41532..10a36a9 100644
--- a/Swiften/FileTransfer/IBBSendSession.cpp
+++ b/Swiften/FileTransfer/IBBSendSession.cpp
@@ -17,92 +17,92 @@
namespace Swift {
IBBSendSession::IBBSendSession(
- const std::string& id,
- const JID& from,
- const JID& to,
- boost::shared_ptr<ReadBytestream> bytestream,
- IQRouter* router) :
- id(id),
- from(from),
- to(to),
- bytestream(bytestream),
- router(router),
- blockSize(4096),
- sequenceNumber(0),
- active(false),
- waitingForData(false) {
- bytestream->onDataAvailable.connect(boost::bind(&IBBSendSession::handleDataAvailable, this));
+ const std::string& id,
+ const JID& from,
+ const JID& to,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ IQRouter* router) :
+ id(id),
+ from(from),
+ to(to),
+ bytestream(bytestream),
+ router(router),
+ blockSize(4096),
+ sequenceNumber(0),
+ active(false),
+ waitingForData(false) {
+ bytestream->onDataAvailable.connect(boost::bind(&IBBSendSession::handleDataAvailable, this));
}
IBBSendSession::~IBBSendSession() {
- bytestream->onDataAvailable.disconnect(boost::bind(&IBBSendSession::handleDataAvailable, this));
+ bytestream->onDataAvailable.disconnect(boost::bind(&IBBSendSession::handleDataAvailable, this));
}
void IBBSendSession::start() {
- IBBRequest::ref request = IBBRequest::create(
- from, to, IBB::createIBBOpen(id, boost::numeric_cast<int>(blockSize)), router);
- request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
- active = true;
- request->send();
- currentRequest = request;
+ IBBRequest::ref request = IBBRequest::create(
+ from, to, IBB::createIBBOpen(id, boost::numeric_cast<int>(blockSize)), router);
+ request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
+ active = true;
+ request->send();
+ currentRequest = request;
}
void IBBSendSession::stop() {
- if (active && router->isAvailable()) {
- IBBRequest::create(from, to, IBB::createIBBClose(id), router)->send();
- }
- if (currentRequest) {
- currentRequest->onResponse.disconnect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
- }
- finish(boost::optional<FileTransferError>());
+ if (active && router->isAvailable()) {
+ IBBRequest::create(from, to, IBB::createIBBClose(id), router)->send();
+ }
+ if (currentRequest) {
+ currentRequest->onResponse.disconnect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
+ }
+ finish(boost::optional<FileTransferError>());
}
void IBBSendSession::handleIBBResponse(IBB::ref, ErrorPayload::ref error) {
- currentRequest.reset();
+ currentRequest.reset();
- if (!error && active) {
- if (!bytestream->isFinished()) {
- sendMoreData();
- }
- else {
- finish(boost::optional<FileTransferError>());
- }
- }
- else {
- finish(FileTransferError(FileTransferError::PeerError));
- }
+ if (!error && active) {
+ if (!bytestream->isFinished()) {
+ sendMoreData();
+ }
+ else {
+ finish(boost::optional<FileTransferError>());
+ }
+ }
+ else {
+ finish(FileTransferError(FileTransferError::PeerError));
+ }
}
void IBBSendSession::sendMoreData() {
- try {
- boost::shared_ptr<ByteArray> data = bytestream->read(blockSize);
- if (!data->empty()) {
- waitingForData = false;
- IBBRequest::ref request = IBBRequest::create(from, to, IBB::createIBBData(id, sequenceNumber, *data), router);
- sequenceNumber++;
- request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
- request->send();
- currentRequest = request;
- onBytesSent(data->size());
- }
- else {
- waitingForData = true;
- }
- }
- catch (const BytestreamException&) {
- finish(FileTransferError(FileTransferError::ReadError));
- }
+ try {
+ boost::shared_ptr<ByteArray> data = bytestream->read(blockSize);
+ if (!data->empty()) {
+ waitingForData = false;
+ IBBRequest::ref request = IBBRequest::create(from, to, IBB::createIBBData(id, sequenceNumber, *data), router);
+ sequenceNumber++;
+ request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
+ request->send();
+ currentRequest = request;
+ onBytesSent(data->size());
+ }
+ else {
+ waitingForData = true;
+ }
+ }
+ catch (const BytestreamException&) {
+ finish(FileTransferError(FileTransferError::ReadError));
+ }
}
void IBBSendSession::finish(boost::optional<FileTransferError> error) {
- active = false;
- onFinished(error);
+ active = false;
+ onFinished(error);
}
void IBBSendSession::handleDataAvailable() {
- if (waitingForData) {
- sendMoreData();
- }
+ if (waitingForData) {
+ sendMoreData();
+ }
}
}
diff --git a/Swiften/FileTransfer/IBBSendSession.h b/Swiften/FileTransfer/IBBSendSession.h
index af8cc12..e62ef79 100644
--- a/Swiften/FileTransfer/IBBSendSession.h
+++ b/Swiften/FileTransfer/IBBSendSession.h
@@ -18,53 +18,53 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class IQRouter;
- class IBBRequest;
+ class IQRouter;
+ class IBBRequest;
- class SWIFTEN_API IBBSendSession {
- public:
- IBBSendSession(
- const std::string& id,
- const JID& from,
- const JID& to,
- boost::shared_ptr<ReadBytestream> bytestream,
- IQRouter* router);
- ~IBBSendSession();
+ class SWIFTEN_API IBBSendSession {
+ public:
+ IBBSendSession(
+ const std::string& id,
+ const JID& from,
+ const JID& to,
+ boost::shared_ptr<ReadBytestream> bytestream,
+ IQRouter* router);
+ ~IBBSendSession();
- void start();
- void stop();
+ void start();
+ void stop();
- const JID& getSender() const {
- return from;
- }
+ const JID& getSender() const {
+ return from;
+ }
- const JID& getReceiver() const {
- return to;
- }
+ const JID& getReceiver() const {
+ return to;
+ }
- void setBlockSize(unsigned int blockSize) {
- this->blockSize = blockSize;
- }
+ void setBlockSize(unsigned int blockSize) {
+ this->blockSize = blockSize;
+ }
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
- boost::signal<void (size_t)> onBytesSent;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signal<void (size_t)> onBytesSent;
- private:
- void handleIBBResponse(IBB::ref, ErrorPayload::ref);
- void finish(boost::optional<FileTransferError>);
- void sendMoreData();
- void handleDataAvailable();
+ private:
+ void handleIBBResponse(IBB::ref, ErrorPayload::ref);
+ void finish(boost::optional<FileTransferError>);
+ void sendMoreData();
+ void handleDataAvailable();
- private:
- std::string id;
- JID from;
- JID to;
- boost::shared_ptr<ReadBytestream> bytestream;
- IQRouter* router;
- unsigned int blockSize;
- int sequenceNumber;
- bool active;
- bool waitingForData;
- boost::shared_ptr<IBBRequest> currentRequest;
- };
+ private:
+ std::string id;
+ JID from;
+ JID to;
+ boost::shared_ptr<ReadBytestream> bytestream;
+ IQRouter* router;
+ unsigned int blockSize;
+ int sequenceNumber;
+ bool active;
+ bool waitingForData;
+ boost::shared_ptr<IBBRequest> currentRequest;
+ };
}
diff --git a/Swiften/FileTransfer/IBBSendTransportSession.cpp b/Swiften/FileTransfer/IBBSendTransportSession.cpp
index a023dde..fd2d8e6 100644
--- a/Swiften/FileTransfer/IBBSendTransportSession.cpp
+++ b/Swiften/FileTransfer/IBBSendTransportSession.cpp
@@ -11,19 +11,19 @@
namespace Swift {
IBBSendTransportSession::IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session) : session(session) {
- finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
- bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1));
+ finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
+ bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1));
}
IBBSendTransportSession::~IBBSendTransportSession() {
}
void IBBSendTransportSession::start() {
- session->start();
+ session->start();
}
void IBBSendTransportSession::stop() {
- session->stop();
+ session->stop();
}
}
diff --git a/Swiften/FileTransfer/IBBSendTransportSession.h b/Swiften/FileTransfer/IBBSendTransportSession.h
index 20700b4..812c42e 100644
--- a/Swiften/FileTransfer/IBBSendTransportSession.h
+++ b/Swiften/FileTransfer/IBBSendTransportSession.h
@@ -14,17 +14,17 @@
namespace Swift {
class SWIFTEN_API IBBSendTransportSession : public TransportSession {
- public:
- IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session);
- virtual ~IBBSendTransportSession();
+ public:
+ IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session);
+ virtual ~IBBSendTransportSession();
- virtual void start() SWIFTEN_OVERRIDE;
- virtual void stop() SWIFTEN_OVERRIDE;
+ virtual void start() SWIFTEN_OVERRIDE;
+ virtual void stop() SWIFTEN_OVERRIDE;
- private:
- boost::shared_ptr<IBBSendSession> session;
- boost::bsignals::scoped_connection finishedConnection;
- boost::bsignals::scoped_connection bytesSentConnection;
+ private:
+ boost::shared_ptr<IBBSendSession> session;
+ boost::bsignals::scoped_connection finishedConnection;
+ boost::bsignals::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/IncomingFileTransfer.h b/Swiften/FileTransfer/IncomingFileTransfer.h
index 16905b8..4cb18e8 100644
--- a/Swiften/FileTransfer/IncomingFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingFileTransfer.h
@@ -14,24 +14,24 @@
#include <Swiften/FileTransfer/FileTransferOptions.h>
namespace Swift {
- class WriteBytestream;
- class JID;
-
- /**
- * @brief The IncomingFileTransfer abstract class is the general interface in Swiften
- * for incoming file transfers.
- */
- class SWIFTEN_API IncomingFileTransfer : public FileTransfer {
- public:
- typedef boost::shared_ptr<IncomingFileTransfer> ref;
-
- virtual ~IncomingFileTransfer();
-
- virtual void accept(
- boost::shared_ptr<WriteBytestream>,
- const FileTransferOptions& = FileTransferOptions()) = 0;
-
- virtual const JID& getSender() const = 0;
- virtual const JID& getRecipient() const = 0;
- };
+ class WriteBytestream;
+ class JID;
+
+ /**
+ * @brief The IncomingFileTransfer abstract class is the general interface in Swiften
+ * for incoming file transfers.
+ */
+ class SWIFTEN_API IncomingFileTransfer : public FileTransfer {
+ public:
+ typedef boost::shared_ptr<IncomingFileTransfer> ref;
+
+ virtual ~IncomingFileTransfer();
+
+ virtual void accept(
+ boost::shared_ptr<WriteBytestream>,
+ const FileTransferOptions& = FileTransferOptions()) = 0;
+
+ virtual const JID& getSender() const = 0;
+ virtual const JID& getRecipient() const = 0;
+ };
}
diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.cpp b/Swiften/FileTransfer/IncomingFileTransferManager.cpp
index f5b95ec..b0b4d49 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.cpp
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.cpp
@@ -20,46 +20,46 @@
namespace Swift {
IncomingFileTransferManager::IncomingFileTransferManager(
- JingleSessionManager* jingleSessionManager,
- FileTransferTransporterFactory* transporterFactory,
- TimerFactory* timerFactory,
- CryptoProvider* crypto) :
- jingleSessionManager(jingleSessionManager),
- transporterFactory(transporterFactory),
- timerFactory(timerFactory),
- crypto(crypto) {
- jingleSessionManager->addIncomingSessionHandler(this);
+ JingleSessionManager* jingleSessionManager,
+ FileTransferTransporterFactory* transporterFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* crypto) :
+ jingleSessionManager(jingleSessionManager),
+ transporterFactory(transporterFactory),
+ timerFactory(timerFactory),
+ crypto(crypto) {
+ jingleSessionManager->addIncomingSessionHandler(this);
}
IncomingFileTransferManager::~IncomingFileTransferManager() {
- jingleSessionManager->removeIncomingSessionHandler(this);
+ jingleSessionManager->removeIncomingSessionHandler(this);
}
bool IncomingFileTransferManager::handleIncomingJingleSession(
- JingleSession::ref session,
- const std::vector<JingleContentPayload::ref>& contents,
- const JID& recipient) {
- if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) {
- if (content->getTransport<JingleS5BTransportPayload>() || content->getTransport<JingleIBBTransportPayload>()) {
- JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>();
- if (description) {
- IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>(
- recipient, session, content, transporterFactory, timerFactory, crypto);
- onIncomingFileTransfer(transfer);
- }
- else {
- SWIFT_LOG(warning) << "Received a file-transfer request with no file description.";
- session->sendTerminate(JinglePayload::Reason::FailedApplication);
- }
- }
- else {
- session->sendTerminate(JinglePayload::Reason::UnsupportedTransports);
- }
- return true;
- }
- else {
- return false;
- }
+ JingleSession::ref session,
+ const std::vector<JingleContentPayload::ref>& contents,
+ const JID& recipient) {
+ if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) {
+ if (content->getTransport<JingleS5BTransportPayload>() || content->getTransport<JingleIBBTransportPayload>()) {
+ JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>();
+ if (description) {
+ IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>(
+ recipient, session, content, transporterFactory, timerFactory, crypto);
+ onIncomingFileTransfer(transfer);
+ }
+ else {
+ SWIFT_LOG(warning) << "Received a file-transfer request with no file description.";
+ session->sendTerminate(JinglePayload::Reason::FailedApplication);
+ }
+ }
+ else {
+ session->sendTerminate(JinglePayload::Reason::UnsupportedTransports);
+ }
+ return true;
+ }
+ else {
+ return false;
+ }
}
diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.h b/Swiften/FileTransfer/IncomingFileTransferManager.h
index 285ff3f..7a34b2a 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.h
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.h
@@ -14,32 +14,32 @@
#include <Swiften/Jingle/IncomingJingleSessionHandler.h>
namespace Swift {
- class JingleSessionManager;
- class FileTransferTransporterFactory;
- class TimerFactory;
- class CryptoProvider;
-
- class SWIFTEN_API IncomingFileTransferManager : public IncomingJingleSessionHandler {
- public:
- IncomingFileTransferManager(
- JingleSessionManager* jingleSessionManager,
- FileTransferTransporterFactory* transporterFactory,
- TimerFactory* timerFactory,
- CryptoProvider* crypto);
- virtual ~IncomingFileTransferManager();
-
- boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
-
- private:
- bool handleIncomingJingleSession(
- JingleSession::ref session,
- const std::vector<JingleContentPayload::ref>& contents,
- const JID& recipient);
-
- private:
- JingleSessionManager* jingleSessionManager;
- FileTransferTransporterFactory* transporterFactory;
- TimerFactory* timerFactory;
- CryptoProvider* crypto;
- };
+ class JingleSessionManager;
+ class FileTransferTransporterFactory;
+ class TimerFactory;
+ class CryptoProvider;
+
+ class SWIFTEN_API IncomingFileTransferManager : public IncomingJingleSessionHandler {
+ public:
+ IncomingFileTransferManager(
+ JingleSessionManager* jingleSessionManager,
+ FileTransferTransporterFactory* transporterFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* crypto);
+ virtual ~IncomingFileTransferManager();
+
+ boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
+
+ private:
+ bool handleIncomingJingleSession(
+ JingleSession::ref session,
+ const std::vector<JingleContentPayload::ref>& contents,
+ const JID& recipient);
+
+ private:
+ JingleSessionManager* jingleSessionManager;
+ FileTransferTransporterFactory* transporterFactory;
+ TimerFactory* timerFactory;
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
index db17620..40f952e 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
@@ -33,388 +33,388 @@ 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),
- receivedBytes(0),
- hashCalculator(NULL) {
- description = initialContent->getDescription<JingleFileTransferDescription>();
- assert(description);
- JingleFileTransferFileInfo fileInfo = description->getFileInfo();
- setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription());
- hashes = fileInfo.getHashes();
-
- waitOnHashTimer = timerFactory->createTimer(5000);
- waitOnHashTimerTickedConnection = waitOnHashTimer->onTick.connect(
- boost::bind(&IncomingJingleFileTransfer::handleWaitOnHashTimerTicked, this));
+ 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),
+ receivedBytes(0),
+ hashCalculator(NULL) {
+ description = initialContent->getDescription<JingleFileTransferDescription>();
+ assert(description);
+ JingleFileTransferFileInfo fileInfo = description->getFileInfo();
+ setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription());
+ hashes = fileInfo.getHashes();
+
+ waitOnHashTimer = timerFactory->createTimer(5000);
+ waitOnHashTimerTickedConnection = waitOnHashTimer->onTick.connect(
+ boost::bind(&IncomingJingleFileTransfer::handleWaitOnHashTimerTicked, this));
}
IncomingJingleFileTransfer::~IncomingJingleFileTransfer() {
- if (waitOnHashTimer) {
- waitOnHashTimer->stop();
- }
+ if (waitOnHashTimer) {
+ waitOnHashTimer->stop();
+ }
- delete hashCalculator;
- hashCalculator = NULL;
+ delete hashCalculator;
+ hashCalculator = NULL;
}
void IncomingJingleFileTransfer::accept(
- boost::shared_ptr<WriteBytestream> stream,
- const FileTransferOptions& options) {
- SWIFT_LOG(debug) << std::endl;
- if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- assert(!this->stream);
- this->stream = stream;
- this->options = options;
-
- assert(!hashCalculator);
-
- hashCalculator = new IncrementalBytestreamHashCalculator(
- hashes.find("md5") != hashes.end(), hashes.find("sha-1") != hashes.end(), crypto);
-
- writeStreamDataReceivedConnection = stream->onWrite.connect(
- boost::bind(&IncomingJingleFileTransfer::handleWriteStreamDataReceived, this, _1));
-
- JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>();
- JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>();
- if (s5bTransport) {
- SWIFT_LOG(debug) << "Got S5B transport as initial payload." << std::endl;
- setTransporter(transporterFactory->createResponderTransporter(
- getInitiator(), getResponder(), s5bTransport->getSessionID(), options));
- transporter->addRemoteCandidates(s5bTransport->getCandidates(), s5bTransport->getDstAddr());
- setState(GeneratingInitialLocalCandidates);
- transporter->startGeneratingLocalCandidates();
- }
- else if (ibbTransport && options.isInBandAllowed()) {
- SWIFT_LOG(debug) << "Got IBB transport as initial payload." << std::endl;
- setTransporter(transporterFactory->createResponderTransporter(
- getInitiator(), getResponder(), ibbTransport->getSessionID(), options));
-
- startTransferring(transporter->createIBBReceiveSession(
- ibbTransport->getSessionID(),
- 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));
- }
+ boost::shared_ptr<WriteBytestream> stream,
+ const FileTransferOptions& options) {
+ SWIFT_LOG(debug) << std::endl;
+ if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ assert(!this->stream);
+ this->stream = stream;
+ this->options = options;
+
+ assert(!hashCalculator);
+
+ hashCalculator = new IncrementalBytestreamHashCalculator(
+ hashes.find("md5") != hashes.end(), hashes.find("sha-1") != hashes.end(), crypto);
+
+ writeStreamDataReceivedConnection = stream->onWrite.connect(
+ boost::bind(&IncomingJingleFileTransfer::handleWriteStreamDataReceived, this, _1));
+
+ JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>();
+ JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>();
+ if (s5bTransport) {
+ SWIFT_LOG(debug) << "Got S5B transport as initial payload." << std::endl;
+ setTransporter(transporterFactory->createResponderTransporter(
+ getInitiator(), getResponder(), s5bTransport->getSessionID(), options));
+ transporter->addRemoteCandidates(s5bTransport->getCandidates(), s5bTransport->getDstAddr());
+ setState(GeneratingInitialLocalCandidates);
+ transporter->startGeneratingLocalCandidates();
+ }
+ else if (ibbTransport && options.isInBandAllowed()) {
+ SWIFT_LOG(debug) << "Got IBB transport as initial payload." << std::endl;
+ setTransporter(transporterFactory->createResponderTransporter(
+ getInitiator(), getResponder(), ibbTransport->getSessionID(), options));
+
+ startTransferring(transporter->createIBBReceiveSession(
+ ibbTransport->getSessionID(),
+ 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);
+ 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; }
+ 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);
+ fillCandidateMap(localCandidates, candidates);
- JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
- transport->setSessionID(s5bSessionID);
- transport->setMode(JingleS5BTransportPayload::TCPMode);
- transport->setDstAddr(dstAddr);
- foreach(JingleS5BTransportPayload::Candidate candidate, candidates) {
- transport->addCandidate(candidate);
- }
- session->sendAccept(getContentID(), initialContent->getDescriptions()[0], transport);
+ JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
+ transport->setSessionID(s5bSessionID);
+ transport->setMode(JingleS5BTransportPayload::TCPMode);
+ transport->setDstAddr(dstAddr);
+ foreach(JingleS5BTransportPayload::Candidate candidate, candidates) {
+ transport->addCandidate(candidate);
+ }
+ session->sendAccept(getContentID(), initialContent->getDescriptions()[0], transport);
- setState(TryingCandidates);
- transporter->startTryingRemoteCandidates();
+ 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;
- }
+ 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;
+ }
}
void IncomingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
- SWIFT_LOG(debug) << std::endl;
- if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- if (state == Finished) {
- 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));
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ if (state == Finished) {
+ 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);
- }
+ 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) {
- 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);
- }
+ if (receivedBytes == getFileSizeInBytes()) {
+ SWIFT_LOG(debug) << "All data received." << std::endl;
+ bool hashInfoAvailable = false;
+ foreach(const JingleFileTransferFileInfo::HashElementMap::value_type& 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();
+ 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) {
- SWIFT_LOG(warning) << "Incorrect state" << std::endl;
- return;
- }
-
- JingleIBBTransportPayload::ref ibbTransport;
- if (options.isInBandAllowed() && (ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
- SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl;
-
- startTransferring(transporter->createIBBReceiveSession(
- ibbTransport->getSessionID(),
- description->getFileInfo().getSize(),
- stream));
- session->sendTransportAccept(content, ibbTransport);
- }
- else {
- SWIFT_LOG(debug) << "Unknown replace transport" << std::endl;
- session->sendTransportReject(content, transport);
- }
+ const JingleContentID& content, JingleTransportPayload::ref transport) {
+ SWIFT_LOG(debug) << std::endl;
+ if (state != WaitingForFallbackOrTerminate) {
+ SWIFT_LOG(warning) << "Incorrect state" << std::endl;
+ return;
+ }
+
+ JingleIBBTransportPayload::ref ibbTransport;
+ if (options.isInBandAllowed() && (ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
+ SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl;
+
+ startTransferring(transporter->createIBBReceiveSession(
+ ibbTransport->getSessionID(),
+ description->getFileInfo().getSize(),
+ stream));
+ session->sendTransportAccept(content, ibbTransport);
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown replace transport" << std::endl;
+ session->sendTransportReject(content, transport);
+ }
}
JingleContentID IncomingJingleFileTransfer::getContentID() const {
- return JingleContentID(initialContent->getName(), initialContent->getCreator());
+ return JingleContentID(initialContent->getName(), initialContent->getCreator());
}
bool IncomingJingleFileTransfer::verifyData() {
- if (hashes.empty()) {
- SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl;
- return true;
- }
- if (hashes.find("sha-1") != hashes.end()) {
- SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash()) << std::endl;
- return hashes["sha-1"] == hashCalculator->getSHA1Hash();
- }
- else if (hashes.find("md5") != hashes.end()) {
- SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash()) << std::endl;
- return hashes["md5"] == hashCalculator->getMD5Hash();
- }
- else {
- SWIFT_LOG(debug) << "Unknown hash, skipping" << std::endl;
- return true;
- }
+ if (hashes.empty()) {
+ SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl;
+ return true;
+ }
+ if (hashes.find("sha-1") != hashes.end()) {
+ SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash()) << std::endl;
+ return hashes["sha-1"] == hashCalculator->getSHA1Hash();
+ }
+ else if (hashes.find("md5") != hashes.end()) {
+ SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash()) << std::endl;
+ return hashes["md5"] == hashCalculator->getMD5Hash();
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown hash, skipping" << std::endl;
+ return true;
+ }
}
void IncomingJingleFileTransfer::handleWaitOnHashTimerTicked() {
- SWIFT_LOG(debug) << std::endl;
- waitOnHashTimer->stop();
- terminate(JinglePayload::Reason::Success);
+ SWIFT_LOG(debug) << std::endl;
+ waitOnHashTimer->stop();
+ terminate(JinglePayload::Reason::Success);
}
const JID& IncomingJingleFileTransfer::getSender() const {
- return getInitiator();
+ return getInitiator();
}
const JID& IncomingJingleFileTransfer::getRecipient() const {
- return getResponder();
+ return getResponder();
}
void IncomingJingleFileTransfer::setState(State state) {
- SWIFT_LOG(debug) << state << std::endl;
- this->state = state;
- onStateChanged(FileTransfer::State(getExternalState(state)));
+ SWIFT_LOG(debug) << state << std::endl;
+ this->state = state;
+ onStateChanged(FileTransfer::State(getExternalState(state)));
}
void IncomingJingleFileTransfer::setFinishedState(
- FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << std::endl;
- this->state = Finished;
- onStateChanged(type);
- onFinished(error);
+ FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
+ SWIFT_LOG(debug) << std::endl;
+ this->state = Finished;
+ onStateChanged(type);
+ onFinished(error);
}
void IncomingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
- if (error && state != WaitingForHash) {
- terminate(JinglePayload::Reason::MediaError);
- }
+ if (error && state != WaitingForHash) {
+ terminate(JinglePayload::Reason::MediaError);
+ }
}
FileTransfer::State::Type IncomingJingleFileTransfer::getExternalState(State state) {
- switch (state) {
- case Initial: return FileTransfer::State::Initial;
- case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart;
- case TryingCandidates: return FileTransfer::State::Negotiating;
- case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating;
- case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating;
- case WaitingForFallbackOrTerminate: return FileTransfer::State::Negotiating;
- case Transferring: return FileTransfer::State::Transferring;
- case WaitingForHash: return FileTransfer::State::Transferring;
- case Finished: return FileTransfer::State::Finished;
- }
- assert(false);
- return FileTransfer::State::Initial;
+ switch (state) {
+ case Initial: return FileTransfer::State::Initial;
+ case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart;
+ case TryingCandidates: return FileTransfer::State::Negotiating;
+ case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating;
+ case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating;
+ case WaitingForFallbackOrTerminate: return FileTransfer::State::Negotiating;
+ case Transferring: return FileTransfer::State::Transferring;
+ case WaitingForHash: return FileTransfer::State::Transferring;
+ case Finished: return FileTransfer::State::Finished;
+ }
+ assert(false);
+ return FileTransfer::State::Initial;
}
void IncomingJingleFileTransfer::stopAll() {
- if (state != Initial) {
- writeStreamDataReceivedConnection.disconnect();
- delete hashCalculator;
- hashCalculator = NULL;
- }
- switch (state) {
- case Initial: break;
- case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break;
- case TryingCandidates: transporter->stopTryingRemoteCandidates(); break;
- case WaitingForFallbackOrTerminate: break;
- case WaitingForPeerProxyActivate: break;
- case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break;
- case WaitingForHash: // Fallthrough
- case Transferring:
- assert(transportSession);
- transferFinishedConnection.disconnect();
- transportSession->stop();
- transportSession.reset();
- break;
- case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
- }
- if (state != Initial) {
- removeTransporter();
- }
+ if (state != Initial) {
+ writeStreamDataReceivedConnection.disconnect();
+ delete hashCalculator;
+ hashCalculator = NULL;
+ }
+ switch (state) {
+ case Initial: break;
+ case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break;
+ case TryingCandidates: transporter->stopTryingRemoteCandidates(); break;
+ case WaitingForFallbackOrTerminate: break;
+ case WaitingForPeerProxyActivate: break;
+ case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break;
+ case WaitingForHash: // Fallthrough
+ case Transferring:
+ assert(transportSession);
+ transferFinishedConnection.disconnect();
+ transportSession->stop();
+ transportSession.reset();
+ break;
+ case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
+ }
+ if (state != Initial) {
+ removeTransporter();
+ }
}
bool IncomingJingleFileTransfer::hasPriorityOnCandidateTie() const {
- return false;
+ return false;
}
void IncomingJingleFileTransfer::fallback() {
- setState(WaitingForFallbackOrTerminate);
+ setState(WaitingForFallbackOrTerminate);
}
void IncomingJingleFileTransfer::startTransferViaRemoteCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug) << std::endl;
- if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
- setState(WaitingForPeerProxyActivate);
- }
- else {
- startTransferring(createRemoteCandidateSession());
- }
+ if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ setState(WaitingForPeerProxyActivate);
+ }
+ else {
+ startTransferring(createRemoteCandidateSession());
+ }
}
void IncomingJingleFileTransfer::startTransferViaLocalCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug) << std::endl;
- if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
- setState(WaitingForLocalProxyActivate);
- transporter->startActivatingProxy(theirCandidateChoice->jid);
- }
- else {
- startTransferring(createLocalCandidateSession());
- }
+ if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ setState(WaitingForLocalProxyActivate);
+ transporter->startActivatingProxy(theirCandidateChoice->jid);
+ }
+ else {
+ startTransferring(createLocalCandidateSession());
+ }
}
void IncomingJingleFileTransfer::startTransferring(boost::shared_ptr<TransportSession> transportSession) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug) << std::endl;
- this->transportSession = transportSession;
- transferFinishedConnection = transportSession->onFinished.connect(
- boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
- setState(Transferring);
- transportSession->start();
+ this->transportSession = transportSession;
+ transferFinishedConnection = transportSession->onFinished.connect(
+ boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
+ setState(Transferring);
+ transportSession->start();
}
bool IncomingJingleFileTransfer::isWaitingForPeerProxyActivate() const {
- return state == WaitingForPeerProxyActivate;
+ return state == WaitingForPeerProxyActivate;
}
bool IncomingJingleFileTransfer::isWaitingForLocalProxyActivate() const {
- return state == WaitingForLocalProxyActivate;
+ return state == WaitingForLocalProxyActivate;
}
bool IncomingJingleFileTransfer::isTryingCandidates() const {
- return state == TryingCandidates;
+ return state == TryingCandidates;
}
boost::shared_ptr<TransportSession> IncomingJingleFileTransfer::createLocalCandidateSession() {
- return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
+ return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
}
boost::shared_ptr<TransportSession> IncomingJingleFileTransfer::createRemoteCandidateSession() {
- return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
+ return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
}
void IncomingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) {
- SWIFT_LOG(debug) << reason << std::endl;
+ SWIFT_LOG(debug) << reason << std::endl;
- if (state != Finished) {
- session->sendTerminate(reason);
- }
- stopAll();
- setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason));
+ if (state != Finished) {
+ session->sendTerminate(reason);
+ }
+ stopAll();
+ setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason));
}
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.h b/Swiften/FileTransfer/IncomingJingleFileTransfer.h
index 57e2bcc..d3cc331 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.h
@@ -21,109 +21,109 @@
#include <Swiften/Jingle/JingleContentID.h>
namespace Swift {
- class JID;
- class JingleSession;
- class JingleContentPayload;
- class FileTransferTransporter;
- class FileTransferTransporterFactory;
- class TimerFactory;
- class Timer;
- class CryptoProvider;
- class IncrementalBytestreamHashCalculator;
- class JingleFileTransferDescription;
- class HashElement;
-
- /**
- * @brief The IncomingJingleFileTransfer class contains the business logic for managing incoming
- * Jingle file transfers.
- *
- * Calling IncomingJingleFileTransfer::accept will start to negotiate possible transfer
- * methods and after a working method has been decided among peers the trasnfer is started.
- */
- class SWIFTEN_API IncomingJingleFileTransfer : public IncomingFileTransfer, public JingleFileTransfer {
- public:
- typedef boost::shared_ptr<IncomingJingleFileTransfer> ref;
-
- IncomingJingleFileTransfer(
- const JID& recipient,
- boost::shared_ptr<JingleSession>,
- boost::shared_ptr<JingleContentPayload> content,
- FileTransferTransporterFactory*,
- TimerFactory*,
- CryptoProvider*);
- virtual ~IncomingJingleFileTransfer();
-
- virtual void accept(boost::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) SWIFTEN_OVERRIDE;
- virtual void cancel() SWIFTEN_OVERRIDE;
-
- private:
- enum State {
- Initial,
- GeneratingInitialLocalCandidates,
- TryingCandidates,
- WaitingForPeerProxyActivate,
- WaitingForLocalProxyActivate,
- WaitingForFallbackOrTerminate,
- Transferring,
- WaitingForHash,
- Finished
- };
-
- virtual void handleSessionTerminateReceived(
- boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE;
- virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportReplaceReceived(
- const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
-
- virtual void handleLocalTransportCandidatesGenerated(
- const std::string& s5bSessionID,
- const std::vector<JingleS5BTransportPayload::Candidate>&,
- const std::string& dstAddr) SWIFTEN_OVERRIDE;
-
- void handleWriteStreamDataReceived(const std::vector<unsigned char>& data);
- void stopActiveTransport();
- void checkCandidateSelected();
- virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE;
- void checkIfAllDataReceived();
- bool verifyData();
- void handleWaitOnHashTimerTicked();
- void handleTransferFinished(boost::optional<FileTransferError>);
-
- private:
- virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE;
- virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE;
- void checkHashAndTerminate();
- void stopAll();
- void setState(State state);
- void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error);
- const JID& getSender() const SWIFTEN_OVERRIDE;
- const JID& getRecipient() const SWIFTEN_OVERRIDE;
- static FileTransfer::State::Type getExternalState(State state);
- virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE;
- virtual void fallback() SWIFTEN_OVERRIDE;
- virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE;
- virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE;
- virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE;
- virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE;
- virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
-
-
- private:
- boost::shared_ptr<JingleContentPayload> initialContent;
- CryptoProvider* crypto;
- State state;
- boost::shared_ptr<JingleFileTransferDescription> description;
- boost::shared_ptr<WriteBytestream> stream;
- boost::uintmax_t receivedBytes;
- IncrementalBytestreamHashCalculator* hashCalculator;
- boost::shared_ptr<Timer> waitOnHashTimer;
- std::map<std::string, ByteArray> hashes;
- FileTransferOptions options;
-
- boost::bsignals::scoped_connection writeStreamDataReceivedConnection;
- boost::bsignals::scoped_connection waitOnHashTimerTickedConnection;
- boost::bsignals::connection transferFinishedConnection;
- };
+ class JID;
+ class JingleSession;
+ class JingleContentPayload;
+ class FileTransferTransporter;
+ class FileTransferTransporterFactory;
+ class TimerFactory;
+ class Timer;
+ class CryptoProvider;
+ class IncrementalBytestreamHashCalculator;
+ class JingleFileTransferDescription;
+ class HashElement;
+
+ /**
+ * @brief The IncomingJingleFileTransfer class contains the business logic for managing incoming
+ * Jingle file transfers.
+ *
+ * Calling IncomingJingleFileTransfer::accept will start to negotiate possible transfer
+ * methods and after a working method has been decided among peers the trasnfer is started.
+ */
+ class SWIFTEN_API IncomingJingleFileTransfer : public IncomingFileTransfer, public JingleFileTransfer {
+ public:
+ typedef boost::shared_ptr<IncomingJingleFileTransfer> ref;
+
+ IncomingJingleFileTransfer(
+ const JID& recipient,
+ boost::shared_ptr<JingleSession>,
+ boost::shared_ptr<JingleContentPayload> content,
+ FileTransferTransporterFactory*,
+ TimerFactory*,
+ CryptoProvider*);
+ virtual ~IncomingJingleFileTransfer();
+
+ virtual void accept(boost::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) SWIFTEN_OVERRIDE;
+ virtual void cancel() SWIFTEN_OVERRIDE;
+
+ private:
+ enum State {
+ Initial,
+ GeneratingInitialLocalCandidates,
+ TryingCandidates,
+ WaitingForPeerProxyActivate,
+ WaitingForLocalProxyActivate,
+ WaitingForFallbackOrTerminate,
+ Transferring,
+ WaitingForHash,
+ Finished
+ };
+
+ virtual void handleSessionTerminateReceived(
+ boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE;
+ virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportReplaceReceived(
+ const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+
+ virtual void handleLocalTransportCandidatesGenerated(
+ const std::string& s5bSessionID,
+ const std::vector<JingleS5BTransportPayload::Candidate>&,
+ const std::string& dstAddr) SWIFTEN_OVERRIDE;
+
+ void handleWriteStreamDataReceived(const std::vector<unsigned char>& data);
+ void stopActiveTransport();
+ void checkCandidateSelected();
+ virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE;
+ void checkIfAllDataReceived();
+ bool verifyData();
+ void handleWaitOnHashTimerTicked();
+ void handleTransferFinished(boost::optional<FileTransferError>);
+
+ private:
+ virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE;
+ virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE;
+ void checkHashAndTerminate();
+ void stopAll();
+ void setState(State state);
+ void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error);
+ const JID& getSender() const SWIFTEN_OVERRIDE;
+ const JID& getRecipient() const SWIFTEN_OVERRIDE;
+ static FileTransfer::State::Type getExternalState(State state);
+ virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE;
+ virtual void fallback() SWIFTEN_OVERRIDE;
+ virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE;
+ virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
+
+
+ private:
+ boost::shared_ptr<JingleContentPayload> initialContent;
+ CryptoProvider* crypto;
+ State state;
+ boost::shared_ptr<JingleFileTransferDescription> description;
+ boost::shared_ptr<WriteBytestream> stream;
+ boost::uintmax_t receivedBytes;
+ IncrementalBytestreamHashCalculator* hashCalculator;
+ boost::shared_ptr<Timer> waitOnHashTimer;
+ std::map<std::string, ByteArray> hashes;
+ FileTransferOptions options;
+
+ boost::bsignals::scoped_connection writeStreamDataReceivedConnection;
+ boost::bsignals::scoped_connection waitOnHashTimerTickedConnection;
+ boost::bsignals::connection transferFinishedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
index 483270c..f657192 100644
--- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
@@ -19,57 +19,57 @@
namespace Swift {
IncrementalBytestreamHashCalculator::IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto) {
- md5Hasher = doMD5 ? crypto->createMD5() : NULL;
- sha1Hasher = doSHA1 ? crypto->createSHA1() : NULL;
+ md5Hasher = doMD5 ? crypto->createMD5() : NULL;
+ sha1Hasher = doSHA1 ? crypto->createSHA1() : NULL;
}
IncrementalBytestreamHashCalculator::~IncrementalBytestreamHashCalculator() {
- delete md5Hasher;
- delete sha1Hasher;
+ delete md5Hasher;
+ delete sha1Hasher;
}
void IncrementalBytestreamHashCalculator::feedData(const ByteArray& data) {
- if (md5Hasher) {
- md5Hasher->update(data);
- }
- if (sha1Hasher) {
- sha1Hasher->update(data);
- }
+ if (md5Hasher) {
+ md5Hasher->update(data);
+ }
+ if (sha1Hasher) {
+ sha1Hasher->update(data);
+ }
}
/*
void IncrementalBytestreamHashCalculator::feedData(const SafeByteArray& data) {
- if (md5Hasher) {
- md5Hasher->update(createByteArray(data.data(), data.size()));
- }
- if (sha1Hasher) {
- sha1Hasher->update(createByteArray(data.data(), data.size()));
- }
+ if (md5Hasher) {
+ md5Hasher->update(createByteArray(data.data(), data.size()));
+ }
+ if (sha1Hasher) {
+ sha1Hasher->update(createByteArray(data.data(), data.size()));
+ }
}*/
ByteArray IncrementalBytestreamHashCalculator::getSHA1Hash() {
- assert(sha1Hasher);
- if (!sha1Hash) {
- sha1Hash = sha1Hasher->getHash();
- }
- return *sha1Hash;
+ assert(sha1Hasher);
+ if (!sha1Hash) {
+ sha1Hash = sha1Hasher->getHash();
+ }
+ return *sha1Hash;
}
ByteArray IncrementalBytestreamHashCalculator::getMD5Hash() {
- assert(md5Hasher);
- if (!md5Hash) {
- md5Hash = md5Hasher->getHash();
- }
- return *md5Hash;
+ assert(md5Hasher);
+ if (!md5Hash) {
+ md5Hash = md5Hasher->getHash();
+ }
+ return *md5Hash;
}
std::string IncrementalBytestreamHashCalculator::getSHA1String() {
- assert(sha1Hasher);
- return Hexify::hexify(getSHA1Hash());;
+ assert(sha1Hasher);
+ return Hexify::hexify(getSHA1Hash());;
}
std::string IncrementalBytestreamHashCalculator::getMD5String() {
- assert(md5Hasher);
- return Hexify::hexify(getMD5Hash());;
+ assert(md5Hasher);
+ return Hexify::hexify(getMD5Hash());;
}
}
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
index ba3c0e1..4477ec1 100644
--- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
@@ -20,28 +20,28 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class Hash;
- class CryptoProvider;
+ class Hash;
+ class CryptoProvider;
- class IncrementalBytestreamHashCalculator {
- public:
- IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto);
- ~IncrementalBytestreamHashCalculator();
+ class IncrementalBytestreamHashCalculator {
+ public:
+ IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto);
+ ~IncrementalBytestreamHashCalculator();
- void feedData(const ByteArray& data);
- //void feedData(const SafeByteArray& data);
+ void feedData(const ByteArray& data);
+ //void feedData(const SafeByteArray& data);
- ByteArray getSHA1Hash();
- ByteArray getMD5Hash();
+ ByteArray getSHA1Hash();
+ ByteArray getMD5Hash();
- std::string getSHA1String();
- std::string getMD5String();
+ std::string getSHA1String();
+ std::string getMD5String();
- private:
- Hash* md5Hasher;
- Hash* sha1Hasher;
- boost::optional<ByteArray> md5Hash;
- boost::optional<ByteArray> sha1Hash;
- };
+ private:
+ Hash* md5Hasher;
+ Hash* sha1Hasher;
+ boost::optional<ByteArray> md5Hash;
+ boost::optional<ByteArray> sha1Hash;
+ };
}
diff --git a/Swiften/FileTransfer/JingleFileTransfer.cpp b/Swiften/FileTransfer/JingleFileTransfer.cpp
index cf67a67..55296f9 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/JingleFileTransfer.cpp
@@ -19,217 +19,217 @@
using namespace Swift;
JingleFileTransfer::JingleFileTransfer(
- boost::shared_ptr<JingleSession> session,
- const JID& target,
- FileTransferTransporterFactory* transporterFactory) :
- session(session),
- target(target),
- transporterFactory(transporterFactory),
- transporter(NULL),
- ourCandidateSelectFinished(false),
- theirCandidateSelectFinished(false) {
-
- session->addListener(this);
+ boost::shared_ptr<JingleSession> session,
+ const JID& target,
+ FileTransferTransporterFactory* transporterFactory) :
+ session(session),
+ target(target),
+ transporterFactory(transporterFactory),
+ transporter(NULL),
+ ourCandidateSelectFinished(false),
+ theirCandidateSelectFinished(false) {
+
+ session->addListener(this);
}
JingleFileTransfer::~JingleFileTransfer() {
- session->removeListener(this);
+ session->removeListener(this);
}
void JingleFileTransfer::fillCandidateMap(CandidateMap& map, const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
- map.clear();
- foreach (JingleS5BTransportPayload::Candidate candidate, candidates) {
- map[candidate.cid] = candidate;
- }
+ map.clear();
+ foreach (JingleS5BTransportPayload::Candidate 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())));
+ return Hexify::hexify(crypto->getSHA1Hash(
+ createSafeByteArray(s5bSessionID + requester.toString() + target.toString())));
}
*/
const JID& JingleFileTransfer::getInitiator() const {
- return session->getInitiator();
+ return session->getInitiator();
}
const JID& JingleFileTransfer::getResponder() const {
- return target;
+ 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;
- }
+ 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;
+ }
}
boost::optional<FileTransferError> JingleFileTransfer::getFileTransferError(JinglePayload::Reason::Type reason) {
- if (reason == JinglePayload::Reason::Success) {
- return boost::optional<FileTransferError>();
- }
- else {
- return boost::optional<FileTransferError>(FileTransferError::UnknownError);
- }
+ if (reason == JinglePayload::Reason::Success) {
+ return boost::optional<FileTransferError>();
+ }
+ else {
+ return boost::optional<FileTransferError>(FileTransferError::UnknownError);
+ }
}
void JingleFileTransfer::handleRemoteTransportCandidateSelectFinished(
- const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>& candidate) {
- SWIFT_LOG(debug) << std::endl;
-
- ourCandidateChoice = candidate;
- ourCandidateSelectFinished = true;
-
- JingleS5BTransportPayload::ref s5bPayload = boost::make_shared<JingleS5BTransportPayload>();
- s5bPayload->setSessionID(s5bSessionID);
- if (candidate) {
- s5bPayload->setCandidateUsed(candidate->cid);
- }
- else {
- s5bPayload->setCandidateError(true);
- }
- candidateSelectRequestID = session->sendTransportInfo(getContentID(), s5bPayload);
-
- decideOnCandidates();
+ const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>& candidate) {
+ SWIFT_LOG(debug) << std::endl;
+
+ ourCandidateChoice = candidate;
+ ourCandidateSelectFinished = true;
+
+ JingleS5BTransportPayload::ref s5bPayload = boost::make_shared<JingleS5BTransportPayload>();
+ s5bPayload->setSessionID(s5bSessionID);
+ if (candidate) {
+ s5bPayload->setCandidateUsed(candidate->cid);
+ }
+ else {
+ s5bPayload->setCandidateError(true);
+ }
+ candidateSelectRequestID = session->sendTransportInfo(getContentID(), s5bPayload);
+
+ decideOnCandidates();
}
// decide on candidates according to http://xmpp.org/extensions/xep-0260.html#complete
void JingleFileTransfer::decideOnCandidates() {
- SWIFT_LOG(debug) << std::endl;
- if (!ourCandidateSelectFinished || !theirCandidateSelectFinished) {
- SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl;
- return;
- }
- if (!ourCandidateChoice && !theirCandidateChoice) {
- SWIFT_LOG(debug) << "No candidates succeeded." << std::endl;
- fallback();
- }
- else if (ourCandidateChoice && !theirCandidateChoice) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
- startTransferViaRemoteCandidate();
- }
- else if (theirCandidateChoice && !ourCandidateChoice) {
- SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << "." << std::endl;
- startTransferViaLocalCandidate();
- }
- else {
- SWIFT_LOG(debug) << "Choosing between candidates "
- << ourCandidateChoice->cid << "(" << ourCandidateChoice->priority << ")" << " and "
- << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")" << std::endl;
- if (ourCandidateChoice->priority > theirCandidateChoice->priority) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
- startTransferViaRemoteCandidate();
- }
- else if (ourCandidateChoice->priority < theirCandidateChoice->priority) {
- SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << "." << std::endl;
- startTransferViaLocalCandidate();
- }
- else {
- if (hasPriorityOnCandidateTie()) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << std::endl;
- startTransferViaRemoteCandidate();
- }
- else {
- SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << std::endl;
- startTransferViaLocalCandidate();
- }
- }
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (!ourCandidateSelectFinished || !theirCandidateSelectFinished) {
+ SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl;
+ return;
+ }
+ if (!ourCandidateChoice && !theirCandidateChoice) {
+ SWIFT_LOG(debug) << "No candidates succeeded." << std::endl;
+ fallback();
+ }
+ else if (ourCandidateChoice && !theirCandidateChoice) {
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
+ startTransferViaRemoteCandidate();
+ }
+ else if (theirCandidateChoice && !ourCandidateChoice) {
+ SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << "." << std::endl;
+ startTransferViaLocalCandidate();
+ }
+ else {
+ SWIFT_LOG(debug) << "Choosing between candidates "
+ << ourCandidateChoice->cid << "(" << ourCandidateChoice->priority << ")" << " and "
+ << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")" << std::endl;
+ if (ourCandidateChoice->priority > theirCandidateChoice->priority) {
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
+ startTransferViaRemoteCandidate();
+ }
+ else if (ourCandidateChoice->priority < theirCandidateChoice->priority) {
+ SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << "." << std::endl;
+ startTransferViaLocalCandidate();
+ }
+ else {
+ if (hasPriorityOnCandidateTie()) {
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << std::endl;
+ startTransferViaRemoteCandidate();
+ }
+ else {
+ SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << std::endl;
+ startTransferViaLocalCandidate();
+ }
+ }
+ }
}
void JingleFileTransfer::handleProxyActivateFinished(
- const std::string& s5bSessionID, ErrorPayload::ref error) {
- SWIFT_LOG(debug) << std::endl;
- if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- if (error) {
- SWIFT_LOG(debug) << "Error activating proxy" << std::endl;
- JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>();
- proxyError->setSessionID(s5bSessionID);
- proxyError->setProxyError(true);
- session->sendTransportInfo(getContentID(), proxyError);
- fallback();
- }
- else {
- JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>();
- proxyActivate->setSessionID(s5bSessionID);
- proxyActivate->setActivated(theirCandidateChoice->cid);
- session->sendTransportInfo(getContentID(), proxyActivate);
- startTransferring(createLocalCandidateSession());
- }
+ const std::string& s5bSessionID, ErrorPayload::ref error) {
+ SWIFT_LOG(debug) << std::endl;
+ if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ if (error) {
+ SWIFT_LOG(debug) << "Error activating proxy" << std::endl;
+ JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>();
+ proxyError->setSessionID(s5bSessionID);
+ proxyError->setProxyError(true);
+ session->sendTransportInfo(getContentID(), proxyError);
+ fallback();
+ }
+ else {
+ JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>();
+ proxyActivate->setSessionID(s5bSessionID);
+ proxyActivate->setActivated(theirCandidateChoice->cid);
+ session->sendTransportInfo(getContentID(), proxyActivate);
+ startTransferring(createLocalCandidateSession());
+ }
}
void JingleFileTransfer::handleTransportInfoReceived(
- const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) {
- SWIFT_LOG(debug) << std::endl;
-
- if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
- if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) {
- SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl;
- if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- theirCandidateSelectFinished = true;
- if (!s5bPayload->hasCandidateError()) {
- BOOST_AUTO(theirCandidate, localCandidates.find(s5bPayload->getCandidateUsed()));
- if (theirCandidate == localCandidates.end()) {
- SWIFT_LOG(warning) << "Got invalid candidate" << std::endl;
- terminate(JinglePayload::Reason::GeneralError);
- return;
- }
- theirCandidateChoice = theirCandidate->second;
- }
- decideOnCandidates();
- }
- else if (!s5bPayload->getActivated().empty()) {
- SWIFT_LOG(debug) << "Received peer activate from peer" << std::endl;
- if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- if (ourCandidateChoice->cid == s5bPayload->getActivated()) {
- startTransferring(createRemoteCandidateSession());
- }
- else {
- SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl;
- terminate(JinglePayload::Reason::GeneralError);
- }
- }
- else if (s5bPayload->hasProxyError()) {
- SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB." << std::endl;
- fallback();
- }
- else {
- SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
- }
- }
- else {
- SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
- }
+ const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) {
+ SWIFT_LOG(debug) << std::endl;
+
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
+ if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) {
+ SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl;
+ if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ theirCandidateSelectFinished = true;
+ if (!s5bPayload->hasCandidateError()) {
+ BOOST_AUTO(theirCandidate, localCandidates.find(s5bPayload->getCandidateUsed()));
+ if (theirCandidate == localCandidates.end()) {
+ SWIFT_LOG(warning) << "Got invalid candidate" << std::endl;
+ terminate(JinglePayload::Reason::GeneralError);
+ return;
+ }
+ theirCandidateChoice = theirCandidate->second;
+ }
+ decideOnCandidates();
+ }
+ else if (!s5bPayload->getActivated().empty()) {
+ SWIFT_LOG(debug) << "Received peer activate from peer" << std::endl;
+ if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ if (ourCandidateChoice->cid == s5bPayload->getActivated()) {
+ startTransferring(createRemoteCandidateSession());
+ }
+ else {
+ SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl;
+ terminate(JinglePayload::Reason::GeneralError);
+ }
+ }
+ else if (s5bPayload->hasProxyError()) {
+ SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB." << std::endl;
+ fallback();
+ }
+ else {
+ SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
+ }
+ }
+ else {
+ SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
+ }
}
void JingleFileTransfer::setTransporter(FileTransferTransporter* transporter) {
- SWIFT_LOG_ASSERT(!this->transporter, error);
- this->transporter = transporter;
- localTransportCandidatesGeneratedConnection = transporter->onLocalCandidatesGenerated.connect(
- boost::bind(&JingleFileTransfer::handleLocalTransportCandidatesGenerated, this, _1, _2, _3));
- remoteTransportCandidateSelectFinishedConnection = transporter->onRemoteCandidateSelectFinished.connect(
- boost::bind(&JingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1, _2));
- proxyActivatedConnection = transporter->onProxyActivated.connect(
- boost::bind(&JingleFileTransfer::handleProxyActivateFinished, this, _1, _2));
+ SWIFT_LOG_ASSERT(!this->transporter, error);
+ this->transporter = transporter;
+ localTransportCandidatesGeneratedConnection = transporter->onLocalCandidatesGenerated.connect(
+ boost::bind(&JingleFileTransfer::handleLocalTransportCandidatesGenerated, this, _1, _2, _3));
+ remoteTransportCandidateSelectFinishedConnection = transporter->onRemoteCandidateSelectFinished.connect(
+ boost::bind(&JingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1, _2));
+ proxyActivatedConnection = transporter->onProxyActivated.connect(
+ boost::bind(&JingleFileTransfer::handleProxyActivateFinished, this, _1, _2));
}
void JingleFileTransfer::removeTransporter() {
- if (transporter) {
- localTransportCandidatesGeneratedConnection.release();
- remoteTransportCandidateSelectFinishedConnection.release();
- proxyActivatedConnection.release();
- delete transporter;
- transporter = NULL;
- }
+ if (transporter) {
+ localTransportCandidatesGeneratedConnection.release();
+ remoteTransportCandidateSelectFinishedConnection.release();
+ proxyActivatedConnection.release();
+ delete transporter;
+ transporter = NULL;
+ }
}
diff --git a/Swiften/FileTransfer/JingleFileTransfer.h b/Swiften/FileTransfer/JingleFileTransfer.h
index 16a55c6..6862ba2 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.h
+++ b/Swiften/FileTransfer/JingleFileTransfer.h
@@ -19,78 +19,78 @@
#include <Swiften/Jingle/JingleContentID.h>
namespace Swift {
- class CryptoProvider;
- class IQRouter;
- class RemoteJingleTransportCandidateSelector;
- class LocalJingleTransportCandidateGenerator;
- class JingleSession;
- class FileTransferTransporter;
- class FileTransferTransporterFactory;
- class TransportSession;
+ class CryptoProvider;
+ class IQRouter;
+ class RemoteJingleTransportCandidateSelector;
+ class LocalJingleTransportCandidateGenerator;
+ class JingleSession;
+ class FileTransferTransporter;
+ class FileTransferTransporterFactory;
+ class TransportSession;
- class SWIFTEN_API JingleFileTransfer : public AbstractJingleSessionListener {
- public:
- JingleFileTransfer(
- boost::shared_ptr<JingleSession>,
- const JID& target,
- FileTransferTransporterFactory*);
- virtual ~JingleFileTransfer();
+ class SWIFTEN_API JingleFileTransfer : public AbstractJingleSessionListener {
+ public:
+ JingleFileTransfer(
+ boost::shared_ptr<JingleSession>,
+ const JID& target,
+ FileTransferTransporterFactory*);
+ virtual ~JingleFileTransfer();
- protected:
- virtual void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref);
- virtual void handleLocalTransportCandidatesGenerated(
- const std::string& s5bSessionID,
- const std::vector<JingleS5BTransportPayload::Candidate>&,
- const std::string& dstAddr) = 0;
- virtual void handleProxyActivateFinished(
- const std::string& s5bSessionID,
- ErrorPayload::ref error);
- virtual void decideOnCandidates();
- void handleRemoteTransportCandidateSelectFinished(
- const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>&);
- virtual JingleContentID getContentID() const = 0;
- virtual void startTransferring(boost::shared_ptr<TransportSession>) = 0;
- virtual void terminate(JinglePayload::Reason::Type reason) = 0;
- virtual void fallback() = 0;
- virtual bool hasPriorityOnCandidateTie() const = 0;
- virtual bool isWaitingForPeerProxyActivate() const = 0;
- virtual bool isWaitingForLocalProxyActivate() const = 0;
- virtual bool isTryingCandidates() const = 0;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() = 0;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() = 0;
- virtual void startTransferViaLocalCandidate() = 0;
- virtual void startTransferViaRemoteCandidate() = 0;
+ protected:
+ virtual void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void handleLocalTransportCandidatesGenerated(
+ const std::string& s5bSessionID,
+ const std::vector<JingleS5BTransportPayload::Candidate>&,
+ const std::string& dstAddr) = 0;
+ virtual void handleProxyActivateFinished(
+ const std::string& s5bSessionID,
+ ErrorPayload::ref error);
+ virtual void decideOnCandidates();
+ void handleRemoteTransportCandidateSelectFinished(
+ const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>&);
+ virtual JingleContentID getContentID() const = 0;
+ virtual void startTransferring(boost::shared_ptr<TransportSession>) = 0;
+ virtual void terminate(JinglePayload::Reason::Type reason) = 0;
+ virtual void fallback() = 0;
+ virtual bool hasPriorityOnCandidateTie() const = 0;
+ virtual bool isWaitingForPeerProxyActivate() const = 0;
+ virtual bool isWaitingForLocalProxyActivate() const = 0;
+ virtual bool isTryingCandidates() const = 0;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() = 0;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() = 0;
+ virtual void startTransferViaLocalCandidate() = 0;
+ virtual void startTransferViaRemoteCandidate() = 0;
- protected:
- typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap;
+ protected:
+ typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap;
- void setTransporter(FileTransferTransporter* transporter);
- void removeTransporter();
- void fillCandidateMap(
- CandidateMap& map,
- const std::vector<JingleS5BTransportPayload::Candidate>&);
- const JID& getInitiator() const;
- const JID& getResponder() const;
+ void setTransporter(FileTransferTransporter* transporter);
+ void removeTransporter();
+ void fillCandidateMap(
+ CandidateMap& map,
+ const std::vector<JingleS5BTransportPayload::Candidate>&);
+ const JID& getInitiator() const;
+ const JID& getResponder() const;
- static FileTransfer::State::Type getExternalFinishedState(JinglePayload::Reason::Type);
- static boost::optional<FileTransferError> getFileTransferError(JinglePayload::Reason::Type);
+ static FileTransfer::State::Type getExternalFinishedState(JinglePayload::Reason::Type);
+ static boost::optional<FileTransferError> getFileTransferError(JinglePayload::Reason::Type);
- boost::shared_ptr<JingleSession> session;
- JID target;
- FileTransferTransporterFactory* transporterFactory;
- FileTransferTransporter* transporter;
+ boost::shared_ptr<JingleSession> session;
+ JID target;
+ FileTransferTransporterFactory* transporterFactory;
+ FileTransferTransporter* transporter;
- std::string candidateSelectRequestID;
- bool ourCandidateSelectFinished;
- boost::optional<JingleS5BTransportPayload::Candidate> ourCandidateChoice;
- bool theirCandidateSelectFinished;
- boost::optional<JingleS5BTransportPayload::Candidate> theirCandidateChoice;
- CandidateMap localCandidates;
+ std::string candidateSelectRequestID;
+ bool ourCandidateSelectFinished;
+ boost::optional<JingleS5BTransportPayload::Candidate> ourCandidateChoice;
+ bool theirCandidateSelectFinished;
+ boost::optional<JingleS5BTransportPayload::Candidate> theirCandidateChoice;
+ CandidateMap localCandidates;
- boost::shared_ptr<TransportSession> transportSession;
+ boost::shared_ptr<TransportSession> transportSession;
- boost::bsignals::scoped_connection localTransportCandidatesGeneratedConnection;
- boost::bsignals::scoped_connection remoteTransportCandidateSelectFinishedConnection;
- boost::bsignals::scoped_connection proxyActivatedConnection;
- };
+ boost::bsignals::scoped_connection localTransportCandidatesGeneratedConnection;
+ boost::bsignals::scoped_connection remoteTransportCandidateSelectFinishedConnection;
+ boost::bsignals::scoped_connection proxyActivatedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
index f6e6963..3703ba1 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
@@ -31,162 +31,162 @@ static const unsigned int LOCAL_PREFERENCE = 0;
namespace Swift {
LocalJingleTransportCandidateGenerator::LocalJingleTransportCandidateGenerator(
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- const JID& ownJID,
- IDGenerator* idGenerator,
- const FileTransferOptions& options) :
- s5bServerManager(s5bServerManager),
- s5bProxy(s5bProxy),
- ownJID(ownJID),
- idGenerator(idGenerator),
- triedServerInit_(false),
- triedForwarding_(false),
- triedProxyDiscovery_(false),
- options_(options) {
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ const JID& ownJID,
+ IDGenerator* idGenerator,
+ const FileTransferOptions& options) :
+ s5bServerManager(s5bServerManager),
+ s5bProxy(s5bProxy),
+ ownJID(ownJID),
+ idGenerator(idGenerator),
+ triedServerInit_(false),
+ triedForwarding_(false),
+ triedProxyDiscovery_(false),
+ options_(options) {
}
LocalJingleTransportCandidateGenerator::~LocalJingleTransportCandidateGenerator() {
- SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning) << std::endl;
+ SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning) << std::endl;
}
void LocalJingleTransportCandidateGenerator::start() {
- assert(!s5bServerInitializeRequest);
- if (options_.isDirectAllowed() || options_.isAssistedAllowed()) {
- s5bServerResourceUser_ = s5bServerManager->aquireResourceUser();
- if (s5bServerResourceUser_->isInitialized()) {
- handleS5BServerInitialized(true);
- }
- else {
- s5bServerResourceUser_->onSuccessfulInitialized.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
- }
- } else {
- handleS5BServerInitialized(false);
- }
-
- if (options_.isProxiedAllowed()) {
- s5bProxy->onDiscoveredProxiesChanged.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
- if (s5bProxy->getOrDiscoverS5BProxies().is_initialized()) {
- handleDiscoveredProxiesChanged();
- }
- }
+ assert(!s5bServerInitializeRequest);
+ if (options_.isDirectAllowed() || options_.isAssistedAllowed()) {
+ s5bServerResourceUser_ = s5bServerManager->aquireResourceUser();
+ if (s5bServerResourceUser_->isInitialized()) {
+ handleS5BServerInitialized(true);
+ }
+ else {
+ s5bServerResourceUser_->onSuccessfulInitialized.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
+ }
+ } else {
+ handleS5BServerInitialized(false);
+ }
+
+ if (options_.isProxiedAllowed()) {
+ s5bProxy->onDiscoveredProxiesChanged.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
+ if (s5bProxy->getOrDiscoverS5BProxies().is_initialized()) {
+ handleDiscoveredProxiesChanged();
+ }
+ }
}
void LocalJingleTransportCandidateGenerator::stop() {
- s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
- if (s5bServerPortForwardingUser_) {
- s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
- s5bServerPortForwardingUser_.reset();
- }
- if (s5bServerResourceUser_) {
- s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
- s5bServerResourceUser_.reset();
- }
+ s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
+ if (s5bServerPortForwardingUser_) {
+ s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
+ s5bServerPortForwardingUser_.reset();
+ }
+ if (s5bServerResourceUser_) {
+ s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
+ s5bServerResourceUser_.reset();
+ }
}
void LocalJingleTransportCandidateGenerator::handleS5BServerInitialized(bool success) {
- if (s5bServerResourceUser_) {
- s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
- }
- triedServerInit_ = true;
- if (success) {
- if (options_.isAssistedAllowed()) {
- // try to setup port forwarding
- s5bServerPortForwardingUser_ = s5bServerManager->aquirePortForwardingUser();
- s5bServerPortForwardingUser_->onSetup.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
- if (s5bServerPortForwardingUser_->isForwardingSetup()) {
- handlePortForwardingSetup(true);
- }
- }
- }
- else {
- SWIFT_LOG(warning) << "Unable to start SOCKS5 server" << std::endl;
- if (s5bServerResourceUser_) {
- s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
- }
- s5bServerResourceUser_.reset();
- handlePortForwardingSetup(false);
- }
- checkS5BCandidatesReady();
+ if (s5bServerResourceUser_) {
+ s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
+ }
+ triedServerInit_ = true;
+ if (success) {
+ if (options_.isAssistedAllowed()) {
+ // try to setup port forwarding
+ s5bServerPortForwardingUser_ = s5bServerManager->aquirePortForwardingUser();
+ s5bServerPortForwardingUser_->onSetup.connect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
+ if (s5bServerPortForwardingUser_->isForwardingSetup()) {
+ handlePortForwardingSetup(true);
+ }
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "Unable to start SOCKS5 server" << std::endl;
+ if (s5bServerResourceUser_) {
+ s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
+ }
+ s5bServerResourceUser_.reset();
+ handlePortForwardingSetup(false);
+ }
+ checkS5BCandidatesReady();
}
void LocalJingleTransportCandidateGenerator::handlePortForwardingSetup(bool /* success */) {
- if (s5bServerPortForwardingUser_) {
- s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
- }
- triedForwarding_ = true;
- checkS5BCandidatesReady();
+ if (s5bServerPortForwardingUser_) {
+ s5bServerPortForwardingUser_->onSetup.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handlePortForwardingSetup, this, _1));
+ }
+ triedForwarding_ = true;
+ checkS5BCandidatesReady();
}
void LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged() {
- if (s5bProxy) {
- s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
- }
- triedProxyDiscovery_ = true;
- checkS5BCandidatesReady();
+ if (s5bProxy) {
+ s5bProxy->onDiscoveredProxiesChanged.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleDiscoveredProxiesChanged, this));
+ }
+ triedProxyDiscovery_ = true;
+ checkS5BCandidatesReady();
}
void LocalJingleTransportCandidateGenerator::checkS5BCandidatesReady() {
- if ((!options_.isDirectAllowed() || (options_.isDirectAllowed() && triedServerInit_)) &&
- (!options_.isProxiedAllowed() || (options_.isProxiedAllowed() && triedProxyDiscovery_)) &&
- (!options_.isAssistedAllowed() || (options_.isAssistedAllowed() && triedForwarding_))) {
- emitOnLocalTransportCandidatesGenerated();
- }
+ if ((!options_.isDirectAllowed() || (options_.isDirectAllowed() && triedServerInit_)) &&
+ (!options_.isProxiedAllowed() || (options_.isProxiedAllowed() && triedProxyDiscovery_)) &&
+ (!options_.isAssistedAllowed() || (options_.isAssistedAllowed() && triedForwarding_))) {
+ emitOnLocalTransportCandidatesGenerated();
+ }
}
void LocalJingleTransportCandidateGenerator::emitOnLocalTransportCandidatesGenerated() {
- std::vector<JingleS5BTransportPayload::Candidate> candidates;
-
- if (options_.isDirectAllowed()) {
- // get direct candidates
- std::vector<HostAddressPort> directCandidates = s5bServerManager->getHostAddressPorts();
- foreach(HostAddressPort addressPort, directCandidates) {
- if (addressPort.getAddress().getRawAddress().is_v6() &&
- addressPort.getAddress().getRawAddress().to_v6().is_link_local()) {
- continue;
- }
- JingleS5BTransportPayload::Candidate candidate;
- candidate.type = JingleS5BTransportPayload::Candidate::DirectType;
- candidate.jid = ownJID;
- candidate.hostPort = addressPort;
- candidate.priority = 65536 * 126 + LOCAL_PREFERENCE;
- candidate.cid = idGenerator->generateID();
- candidates.push_back(candidate);
- }
- }
-
- if (options_.isAssistedAllowed()) {
- // get assissted candidates
- std::vector<HostAddressPort> assisstedCandidates = s5bServerManager->getAssistedHostAddressPorts();
- foreach(HostAddressPort addressPort, assisstedCandidates) {
- JingleS5BTransportPayload::Candidate candidate;
- candidate.type = JingleS5BTransportPayload::Candidate::AssistedType;
- candidate.jid = ownJID;
- candidate.hostPort = addressPort;
- candidate.priority = 65536 * 120 + LOCAL_PREFERENCE;
- candidate.cid = idGenerator->generateID();
- candidates.push_back(candidate);
- }
- }
-
- if (options_.isProxiedAllowed() && s5bProxy->getOrDiscoverS5BProxies().is_initialized()) {
- foreach(S5BProxyRequest::ref proxy, s5bProxy->getOrDiscoverS5BProxies().get()) {
- if (proxy->getStreamHost()) { // FIXME: Added this test, because there were cases where this wasn't initialized. Investigate this. (Remko)
- JingleS5BTransportPayload::Candidate candidate;
- candidate.type = JingleS5BTransportPayload::Candidate::ProxyType;
- candidate.jid = (*proxy->getStreamHost()).jid;
- HostAddress address = (*proxy->getStreamHost()).host;
- assert(address.isValid());
- candidate.hostPort = HostAddressPort(address, (*proxy->getStreamHost()).port);
- candidate.priority = 65536 * 10 + LOCAL_PREFERENCE;
- candidate.cid = idGenerator->generateID();
- candidates.push_back(candidate);
- }
- }
- }
-
- onLocalTransportCandidatesGenerated(candidates);
+ std::vector<JingleS5BTransportPayload::Candidate> candidates;
+
+ if (options_.isDirectAllowed()) {
+ // get direct candidates
+ std::vector<HostAddressPort> directCandidates = s5bServerManager->getHostAddressPorts();
+ foreach(HostAddressPort addressPort, directCandidates) {
+ if (addressPort.getAddress().getRawAddress().is_v6() &&
+ addressPort.getAddress().getRawAddress().to_v6().is_link_local()) {
+ continue;
+ }
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::DirectType;
+ candidate.jid = ownJID;
+ candidate.hostPort = addressPort;
+ candidate.priority = 65536 * 126 + LOCAL_PREFERENCE;
+ candidate.cid = idGenerator->generateID();
+ candidates.push_back(candidate);
+ }
+ }
+
+ if (options_.isAssistedAllowed()) {
+ // get assissted candidates
+ std::vector<HostAddressPort> assisstedCandidates = s5bServerManager->getAssistedHostAddressPorts();
+ foreach(HostAddressPort addressPort, assisstedCandidates) {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::AssistedType;
+ candidate.jid = ownJID;
+ candidate.hostPort = addressPort;
+ candidate.priority = 65536 * 120 + LOCAL_PREFERENCE;
+ candidate.cid = idGenerator->generateID();
+ candidates.push_back(candidate);
+ }
+ }
+
+ if (options_.isProxiedAllowed() && s5bProxy->getOrDiscoverS5BProxies().is_initialized()) {
+ foreach(S5BProxyRequest::ref proxy, s5bProxy->getOrDiscoverS5BProxies().get()) {
+ if (proxy->getStreamHost()) { // FIXME: Added this test, because there were cases where this wasn't initialized. Investigate this. (Remko)
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::ProxyType;
+ candidate.jid = (*proxy->getStreamHost()).jid;
+ HostAddress address = (*proxy->getStreamHost()).host;
+ assert(address.isValid());
+ candidate.hostPort = HostAddressPort(address, (*proxy->getStreamHost()).port);
+ candidate.priority = 65536 * 10 + LOCAL_PREFERENCE;
+ candidate.cid = idGenerator->generateID();
+ candidates.push_back(candidate);
+ }
+ }
+ }
+
+ onLocalTransportCandidatesGenerated(candidates);
}
}
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
index d08a85e..74c6bfb 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
@@ -23,47 +23,47 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SOCKS5BytestreamServerManager;
- class SOCKS5BytestreamProxiesManager;
- class SOCKS5BytestreamServerInitializeRequest;
- class SOCKS5BytestreamServerResourceUser;
- class SOCKS5BytestreamServerPortForwardingUser;
- class JingleS5BTransportPayload;
+ class SOCKS5BytestreamServerManager;
+ class SOCKS5BytestreamProxiesManager;
+ class SOCKS5BytestreamServerInitializeRequest;
+ class SOCKS5BytestreamServerResourceUser;
+ class SOCKS5BytestreamServerPortForwardingUser;
+ class JingleS5BTransportPayload;
- class LocalJingleTransportCandidateGenerator {
- public:
- LocalJingleTransportCandidateGenerator(
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- const JID& ownJID,
- IDGenerator* idGenerator,
- const FileTransferOptions& options);
- virtual ~LocalJingleTransportCandidateGenerator();
+ class LocalJingleTransportCandidateGenerator {
+ public:
+ LocalJingleTransportCandidateGenerator(
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ const JID& ownJID,
+ IDGenerator* idGenerator,
+ const FileTransferOptions& options);
+ virtual ~LocalJingleTransportCandidateGenerator();
- virtual void start();
- virtual void stop();
+ virtual void start();
+ virtual void stop();
- boost::signal<void (const std::vector<JingleS5BTransportPayload::Candidate>&)> onLocalTransportCandidatesGenerated;
+ boost::signal<void (const std::vector<JingleS5BTransportPayload::Candidate>&)> onLocalTransportCandidatesGenerated;
- private:
- void handleS5BServerInitialized(bool success);
- void handlePortForwardingSetup(bool success);
- void handleDiscoveredProxiesChanged();
+ private:
+ void handleS5BServerInitialized(bool success);
+ void handlePortForwardingSetup(bool success);
+ void handleDiscoveredProxiesChanged();
- void checkS5BCandidatesReady();
- void emitOnLocalTransportCandidatesGenerated();
+ void checkS5BCandidatesReady();
+ void emitOnLocalTransportCandidatesGenerated();
- private:
- SOCKS5BytestreamServerManager* s5bServerManager;
- SOCKS5BytestreamProxiesManager* s5bProxy;
- JID ownJID;
- IDGenerator* idGenerator;
- boost::shared_ptr<SOCKS5BytestreamServerInitializeRequest> s5bServerInitializeRequest;
- boost::shared_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
- boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_;
- bool triedServerInit_;
- bool triedForwarding_;
- bool triedProxyDiscovery_;
- FileTransferOptions options_;
- };
+ private:
+ SOCKS5BytestreamServerManager* s5bServerManager;
+ SOCKS5BytestreamProxiesManager* s5bProxy;
+ JID ownJID;
+ IDGenerator* idGenerator;
+ boost::shared_ptr<SOCKS5BytestreamServerInitializeRequest> s5bServerInitializeRequest;
+ boost::shared_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
+ boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_;
+ bool triedServerInit_;
+ bool triedForwarding_;
+ bool triedProxyDiscovery_;
+ FileTransferOptions options_;
+ };
}
diff --git a/Swiften/FileTransfer/OutgoingFileTransfer.h b/Swiften/FileTransfer/OutgoingFileTransfer.h
index 358cc2f..e83a893 100644
--- a/Swiften/FileTransfer/OutgoingFileTransfer.h
+++ b/Swiften/FileTransfer/OutgoingFileTransfer.h
@@ -12,12 +12,12 @@
#include <Swiften/FileTransfer/FileTransfer.h>
namespace Swift {
- class SWIFTEN_API OutgoingFileTransfer : public FileTransfer {
- public:
- typedef boost::shared_ptr<OutgoingFileTransfer> ref;
- public:
- virtual ~OutgoingFileTransfer();
+ class SWIFTEN_API OutgoingFileTransfer : public FileTransfer {
+ public:
+ typedef boost::shared_ptr<OutgoingFileTransfer> ref;
+ public:
+ virtual ~OutgoingFileTransfer();
- virtual void start() = 0;
- };
+ virtual void start() = 0;
+ };
}
diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
index f34c449..f6d216e 100644
--- a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
@@ -24,42 +24,42 @@
namespace Swift {
OutgoingFileTransferManager::OutgoingFileTransferManager(
- JingleSessionManager* jingleSessionManager,
- IQRouter* router,
- FileTransferTransporterFactory* transporterFactory,
- TimerFactory* timerFactory,
- CryptoProvider* crypto) :
- jingleSessionManager(jingleSessionManager),
- iqRouter(router),
- transporterFactory(transporterFactory),
- timerFactory(timerFactory),
- crypto(crypto) {
- idGenerator = new IDGenerator();
+ JingleSessionManager* jingleSessionManager,
+ IQRouter* router,
+ FileTransferTransporterFactory* transporterFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* crypto) :
+ jingleSessionManager(jingleSessionManager),
+ iqRouter(router),
+ transporterFactory(transporterFactory),
+ timerFactory(timerFactory),
+ crypto(crypto) {
+ idGenerator = new IDGenerator();
}
OutgoingFileTransferManager::~OutgoingFileTransferManager() {
- delete idGenerator;
+ delete idGenerator;
}
boost::shared_ptr<OutgoingFileTransfer> OutgoingFileTransferManager::createOutgoingFileTransfer(
- const JID& from,
- const JID& recipient,
- boost::shared_ptr<ReadBytestream> readBytestream,
- const JingleFileTransferFileInfo& fileInfo,
- const FileTransferOptions& config) {
- JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>(
- from, recipient, idGenerator->generateID(), iqRouter);
- jingleSessionManager->registerOutgoingSession(from, jingleSession);
- return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(
- recipient,
- jingleSession,
- readBytestream,
- transporterFactory,
- timerFactory,
- idGenerator,
- fileInfo,
- config,
- crypto));
+ const JID& from,
+ const JID& recipient,
+ boost::shared_ptr<ReadBytestream> readBytestream,
+ const JingleFileTransferFileInfo& fileInfo,
+ const FileTransferOptions& config) {
+ JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>(
+ from, recipient, idGenerator->generateID(), iqRouter);
+ jingleSessionManager->registerOutgoingSession(from, jingleSession);
+ return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(
+ recipient,
+ jingleSession,
+ readBytestream,
+ transporterFactory,
+ timerFactory,
+ idGenerator,
+ fileInfo,
+ config,
+ crypto));
}
}
diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.h b/Swiften/FileTransfer/OutgoingFileTransferManager.h
index 1ad992e..3981005 100644
--- a/Swiften/FileTransfer/OutgoingFileTransferManager.h
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.h
@@ -17,41 +17,41 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class JingleSessionManager;
- class IQRouter;
- class FileTransferTransporterFactory;
- class OutgoingFileTransfer;
- class JID;
- class IDGenerator;
- class ReadBytestream;
- class JingleFileTransferFileInfo;
- class CryptoProvider;
- class FileTransferOptions;
- class TimerFactory;
-
- class SWIFTEN_API OutgoingFileTransferManager {
- public:
- OutgoingFileTransferManager(
- JingleSessionManager* jingleSessionManager,
- IQRouter* router,
- FileTransferTransporterFactory* transporterFactory,
- TimerFactory* timerFactory,
- CryptoProvider* crypto);
- ~OutgoingFileTransferManager();
-
- boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(
- const JID& from,
- const JID& to,
- boost::shared_ptr<ReadBytestream>,
- const JingleFileTransferFileInfo&,
- const FileTransferOptions&);
-
- private:
- JingleSessionManager* jingleSessionManager;
- IQRouter* iqRouter;
- FileTransferTransporterFactory* transporterFactory;
- TimerFactory* timerFactory;
- IDGenerator* idGenerator;
- CryptoProvider* crypto;
- };
+ class JingleSessionManager;
+ class IQRouter;
+ class FileTransferTransporterFactory;
+ class OutgoingFileTransfer;
+ class JID;
+ class IDGenerator;
+ class ReadBytestream;
+ class JingleFileTransferFileInfo;
+ class CryptoProvider;
+ class FileTransferOptions;
+ class TimerFactory;
+
+ class SWIFTEN_API OutgoingFileTransferManager {
+ public:
+ OutgoingFileTransferManager(
+ JingleSessionManager* jingleSessionManager,
+ IQRouter* router,
+ FileTransferTransporterFactory* transporterFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* crypto);
+ ~OutgoingFileTransferManager();
+
+ boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(
+ const JID& from,
+ const JID& to,
+ boost::shared_ptr<ReadBytestream>,
+ const JingleFileTransferFileInfo&,
+ const FileTransferOptions&);
+
+ private:
+ JingleSessionManager* jingleSessionManager;
+ IQRouter* iqRouter;
+ FileTransferTransporterFactory* transporterFactory;
+ TimerFactory* timerFactory;
+ IDGenerator* idGenerator;
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
index 2c43766..a5a84eb 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
@@ -10,7 +10,7 @@
* See the COPYING file for more information.
*/
-// TODO:
+// 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?
@@ -44,364 +44,364 @@ using namespace Swift;
static const int DEFAULT_BLOCK_SIZE = 4096;
OutgoingJingleFileTransfer::OutgoingJingleFileTransfer(
- const JID& toJID,
- JingleSession::ref session,
- boost::shared_ptr<ReadBytestream> stream,
- FileTransferTransporterFactory* transporterFactory,
- TimerFactory* timerFactory,
- IDGenerator* idGenerator,
- const JingleFileTransferFileInfo& fileInfo,
- const FileTransferOptions& options,
- CryptoProvider* crypto) :
- JingleFileTransfer(session, toJID, transporterFactory),
- idGenerator(idGenerator),
- stream(stream),
- fileInfo(fileInfo),
- options(options),
- contentID(idGenerator->generateID(), JingleContentPayload::InitiatorCreator),
- state(Initial),
- candidateAcknowledged(false) {
-
- setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription());
-
- // calculate both, MD5 and SHA-1 since we don't know which one the other side supports
- hashCalculator = new IncrementalBytestreamHashCalculator(true, true, crypto);
- stream->onRead.connect(
- boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
-
- waitForRemoteTermination = timerFactory->createTimer(5000);
- waitForRemoteTermination->onTick.connect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this));
+ const JID& toJID,
+ JingleSession::ref session,
+ boost::shared_ptr<ReadBytestream> stream,
+ FileTransferTransporterFactory* transporterFactory,
+ TimerFactory* timerFactory,
+ IDGenerator* idGenerator,
+ const JingleFileTransferFileInfo& fileInfo,
+ const FileTransferOptions& options,
+ CryptoProvider* crypto) :
+ JingleFileTransfer(session, toJID, transporterFactory),
+ idGenerator(idGenerator),
+ stream(stream),
+ fileInfo(fileInfo),
+ options(options),
+ contentID(idGenerator->generateID(), JingleContentPayload::InitiatorCreator),
+ state(Initial),
+ candidateAcknowledged(false) {
+
+ setFileInfo(fileInfo.getName(), fileInfo.getSize(), fileInfo.getDescription());
+
+ // calculate both, MD5 and SHA-1 since we don't know which one the other side supports
+ hashCalculator = new IncrementalBytestreamHashCalculator(true, true, crypto);
+ stream->onRead.connect(
+ boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+
+ waitForRemoteTermination = timerFactory->createTimer(5000);
+ waitForRemoteTermination->onTick.connect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this));
}
OutgoingJingleFileTransfer::~OutgoingJingleFileTransfer() {
- if (waitForRemoteTermination) {
- waitForRemoteTermination->onTick.disconnect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this));
- waitForRemoteTermination->stop();
- }
-
- stream->onRead.disconnect(
- boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
- delete hashCalculator;
- hashCalculator = NULL;
- removeTransporter();
+ if (waitForRemoteTermination) {
+ waitForRemoteTermination->onTick.disconnect(boost::bind(&OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout, this));
+ waitForRemoteTermination->stop();
+ }
+
+ stream->onRead.disconnect(
+ boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+ delete hashCalculator;
+ hashCalculator = NULL;
+ removeTransporter();
}
-
+
void OutgoingJingleFileTransfer::start() {
- SWIFT_LOG(debug) << std::endl;
- if (state != Initial) {
- SWIFT_LOG(warning) << "Incorrect state" << std::endl;
- return;
- }
-
- if (!options.isInBandAllowed() && !options.isDirectAllowed() && !options.isAssistedAllowed() && !options.isProxiedAllowed()) {
- // Started outgoing file transfer while not supporting transport methods.
- setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::UnknownError));
- }
- else {
- setTransporter(transporterFactory->createInitiatorTransporter(getInitiator(), getResponder(), options));
- setInternalState(GeneratingInitialLocalCandidates);
- transporter->startGeneratingLocalCandidates();
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state != Initial) {
+ SWIFT_LOG(warning) << "Incorrect state" << std::endl;
+ return;
+ }
+
+ if (!options.isInBandAllowed() && !options.isDirectAllowed() && !options.isAssistedAllowed() && !options.isProxiedAllowed()) {
+ // Started outgoing file transfer while not supporting transport methods.
+ setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::UnknownError));
+ }
+ else {
+ setTransporter(transporterFactory->createInitiatorTransporter(getInitiator(), getResponder(), options));
+ setInternalState(GeneratingInitialLocalCandidates);
+ transporter->startGeneratingLocalCandidates();
+ }
}
void OutgoingJingleFileTransfer::cancel() {
- terminate(JinglePayload::Reason::Cancel);
+ terminate(JinglePayload::Reason::Cancel);
}
void OutgoingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) {
- SWIFT_LOG(debug) << reason << std::endl;
+ SWIFT_LOG(debug) << reason << std::endl;
- if (state != Initial && state != GeneratingInitialLocalCandidates && state != Finished) {
- session->sendTerminate(reason);
- }
- stopAll();
- setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason));
+ if (state != Initial && state != GeneratingInitialLocalCandidates && state != Finished) {
+ session->sendTerminate(reason);
+ }
+ stopAll();
+ setFinishedState(getExternalFinishedState(reason), getFileTransferError(reason));
}
void OutgoingJingleFileTransfer::handleSessionAcceptReceived(
- const JingleContentID&,
- JingleDescription::ref,
- JingleTransportPayload::ref transportPayload) {
- SWIFT_LOG(debug) << std::endl;
- if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) {
- transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr());
- setInternalState(TryingCandidates);
- transporter->startTryingRemoteCandidates();
- }
- else if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload)) {
- startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
- }
- else {
- SWIFT_LOG(debug) << "Unknown transport payload. Falling back." << std::endl;
- fallback();
- }
+ const JingleContentID&,
+ JingleDescription::ref,
+ JingleTransportPayload::ref transportPayload) {
+ SWIFT_LOG(debug) << std::endl;
+ if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) {
+ transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr());
+ setInternalState(TryingCandidates);
+ transporter->startTryingRemoteCandidates();
+ }
+ else if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload)) {
+ startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown transport payload. Falling back." << std::endl;
+ fallback();
+ }
}
void OutgoingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
- SWIFT_LOG(debug) << std::endl;
- if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
-
- stopAll();
- if (state == WaitForTermination) {
- waitForRemoteTermination->stop();
- }
- if (reason && reason->type == JinglePayload::Reason::Cancel) {
- setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError));
- }
- else if (reason && reason->type == JinglePayload::Reason::Decline) {
- setFinishedState(FileTransfer::State::Canceled, boost::optional<FileTransferError>());
- }
- else if (reason && reason->type == JinglePayload::Reason::Success) {
- setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>());
- }
- else {
- setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError));
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
+
+ stopAll();
+ if (state == WaitForTermination) {
+ waitForRemoteTermination->stop();
+ }
+ if (reason && reason->type == JinglePayload::Reason::Cancel) {
+ setFinishedState(FileTransfer::State::Canceled, FileTransferError(FileTransferError::PeerError));
+ }
+ else if (reason && reason->type == JinglePayload::Reason::Decline) {
+ setFinishedState(FileTransfer::State::Canceled, boost::optional<FileTransferError>());
+ }
+ else if (reason && reason->type == JinglePayload::Reason::Success) {
+ setFinishedState(FileTransfer::State::Finished, boost::optional<FileTransferError>());
+ }
+ else {
+ setFinishedState(FileTransfer::State::Failed, FileTransferError(FileTransferError::PeerError));
+ }
}
void OutgoingJingleFileTransfer::handleTransportAcceptReceived(const JingleContentID&, JingleTransportPayload::ref transport) {
- SWIFT_LOG(debug) << std::endl;
- if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
-
- if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) {
- startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
- }
- else {
- SWIFT_LOG(debug) << "Unknown transport replacement" << std::endl;
- terminate(JinglePayload::Reason::FailedTransport);
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+
+ if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) {
+ startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown transport replacement" << std::endl;
+ terminate(JinglePayload::Reason::FailedTransport);
+ }
}
void OutgoingJingleFileTransfer::handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug) << std::endl;
- terminate(JinglePayload::Reason::UnsupportedTransports);
+ terminate(JinglePayload::Reason::UnsupportedTransports);
}
void OutgoingJingleFileTransfer::sendSessionInfoHash() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug) << std::endl;
- JingleFileTransferHash::ref hashElement = boost::make_shared<JingleFileTransferHash>();
- hashElement->getFileInfo().addHash(HashElement("sha-1", hashCalculator->getSHA1Hash()));
- hashElement->getFileInfo().addHash(HashElement("md5", hashCalculator->getMD5Hash()));
- session->sendInfo(hashElement);
+ JingleFileTransferHash::ref hashElement = boost::make_shared<JingleFileTransferHash>();
+ 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 = boost::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 = boost::make_shared<JingleIBBTransportPayload>();
- ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
- ibbTransport->setSessionID(idGenerator->generateID());
- transport = ibbTransport;
- }
- else {
- JingleS5BTransportPayload::ref s5bTransport = boost::make_shared<JingleS5BTransportPayload>();
- s5bTransport->setSessionID(s5bSessionID);
- s5bTransport->setMode(JingleS5BTransportPayload::TCPMode);
- s5bTransport->setDstAddr(dstAddr);
- foreach(JingleS5BTransportPayload::Candidate 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);
+ 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 = boost::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 = boost::make_shared<JingleIBBTransportPayload>();
+ ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
+ ibbTransport->setSessionID(idGenerator->generateID());
+ transport = ibbTransport;
+ }
+ else {
+ JingleS5BTransportPayload::ref s5bTransport = boost::make_shared<JingleS5BTransportPayload>();
+ s5bTransport->setSessionID(s5bSessionID);
+ s5bTransport->setMode(JingleS5BTransportPayload::TCPMode);
+ s5bTransport->setDstAddr(dstAddr);
+ foreach(JingleS5BTransportPayload::Candidate 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 = boost::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);
- }
+ if (options.isInBandAllowed()) {
+ SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl;
+ JingleIBBTransportPayload::ref ibbTransport = boost::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);
- }
- else {
- sendSessionInfoHash();
-
- // wait for other party to terminate session after they have verified the hash
- setInternalState(WaitForTermination);
- waitForRemoteTermination->start();
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
+
+ if (error) {
+ terminate(JinglePayload::Reason::ConnectivityError);
+ }
+ else {
+ sendSessionInfoHash();
+
+ // wait for other party to terminate session after they have verified the hash
+ setInternalState(WaitForTermination);
+ waitForRemoteTermination->start();
+ }
}
void OutgoingJingleFileTransfer::startTransferring(boost::shared_ptr<TransportSession> transportSession) {
- SWIFT_LOG(debug) << std::endl;
-
- this->transportSession = transportSession;
- processedBytesConnection = transportSession->onBytesSent.connect(
- boost::bind(boost::ref(onProcessedBytes), _1));
- transferFinishedConnection = transportSession->onFinished.connect(
- boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
- setInternalState(Transferring);
- transportSession->start();
+ SWIFT_LOG(debug) << std::endl;
+
+ this->transportSession = transportSession;
+ processedBytesConnection = transportSession->onBytesSent.connect(
+ boost::bind(boost::ref(onProcessedBytes), _1));
+ transferFinishedConnection = transportSession->onFinished.connect(
+ boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ setInternalState(Transferring);
+ transportSession->start();
}
void OutgoingJingleFileTransfer::setInternalState(State state) {
- SWIFT_LOG(debug) << state << std::endl;
- this->state = state;
- setState(FileTransfer::State(getExternalState(state)));
+ SWIFT_LOG(debug) << state << std::endl;
+ this->state = state;
+ setState(FileTransfer::State(getExternalState(state)));
}
void OutgoingJingleFileTransfer::setFinishedState(
- FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << std::endl;
- this->state = Finished;
- onStateChanged(type);
- onFinished(error);
+ FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
+ SWIFT_LOG(debug) << std::endl;
+ this->state = Finished;
+ onStateChanged(type);
+ onFinished(error);
}
FileTransfer::State::Type OutgoingJingleFileTransfer::getExternalState(State state) {
- switch (state) {
- case Initial: return FileTransfer::State::Initial;
- case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart;
- case WaitingForAccept: return FileTransfer::State::WaitingForAccept;
- case TryingCandidates: return FileTransfer::State::Negotiating;
- case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating;
- case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating;
- case WaitingForCandidateAcknowledge: return FileTransfer::State::Negotiating;
- case FallbackRequested: return FileTransfer::State::Negotiating;
- case Transferring: return FileTransfer::State::Transferring;
- case WaitForTermination: return FileTransfer::State::Transferring;
- case Finished: return FileTransfer::State::Finished;
- }
- assert(false);
- return FileTransfer::State::Initial;
+ switch (state) {
+ case Initial: return FileTransfer::State::Initial;
+ case GeneratingInitialLocalCandidates: return FileTransfer::State::WaitingForStart;
+ case WaitingForAccept: return FileTransfer::State::WaitingForAccept;
+ case TryingCandidates: return FileTransfer::State::Negotiating;
+ case WaitingForPeerProxyActivate: return FileTransfer::State::Negotiating;
+ case WaitingForLocalProxyActivate: return FileTransfer::State::Negotiating;
+ case WaitingForCandidateAcknowledge: return FileTransfer::State::Negotiating;
+ case FallbackRequested: return FileTransfer::State::Negotiating;
+ case Transferring: return FileTransfer::State::Transferring;
+ case WaitForTermination: return FileTransfer::State::Transferring;
+ case Finished: return FileTransfer::State::Finished;
+ }
+ assert(false);
+ return FileTransfer::State::Initial;
}
void OutgoingJingleFileTransfer::stopAll() {
- SWIFT_LOG(debug) << state << std::endl;
- switch (state) {
- case Initial: SWIFT_LOG(warning) << "Not yet started" << std::endl; break;
- case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break;
- case WaitingForAccept: break;
- case TryingCandidates: transporter->stopTryingRemoteCandidates(); break;
- case FallbackRequested: break;
- case WaitingForPeerProxyActivate: break;
- case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break;
- case WaitingForCandidateAcknowledge: // Fallthrough
- case Transferring:
- assert(transportSession);
- processedBytesConnection.disconnect();
- transferFinishedConnection.disconnect();
- transportSession->stop();
- transportSession.reset();
- break;
- case WaitForTermination:
- break;
- case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
- }
- if (state != Initial) {
- removeTransporter();
- }
+ SWIFT_LOG(debug) << state << std::endl;
+ switch (state) {
+ case Initial: SWIFT_LOG(warning) << "Not yet started" << std::endl; break;
+ case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break;
+ case WaitingForAccept: break;
+ case TryingCandidates: transporter->stopTryingRemoteCandidates(); break;
+ case FallbackRequested: break;
+ case WaitingForPeerProxyActivate: break;
+ case WaitingForLocalProxyActivate: transporter->stopActivatingProxy(); break;
+ case WaitingForCandidateAcknowledge: // Fallthrough
+ case Transferring:
+ assert(transportSession);
+ processedBytesConnection.disconnect();
+ transferFinishedConnection.disconnect();
+ transportSession->stop();
+ transportSession.reset();
+ break;
+ case WaitForTermination:
+ break;
+ case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
+ }
+ if (state != Initial) {
+ removeTransporter();
+ }
}
void OutgoingJingleFileTransfer::startTransferViaRemoteCandidate() {
- SWIFT_LOG(debug) << std::endl;
-
- if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
- setInternalState(WaitingForPeerProxyActivate);
- }
- else {
- transportSession = createRemoteCandidateSession();
- startTransferringIfCandidateAcknowledged();
- }
+ SWIFT_LOG(debug) << std::endl;
+
+ if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ setInternalState(WaitingForPeerProxyActivate);
+ }
+ else {
+ transportSession = createRemoteCandidateSession();
+ startTransferringIfCandidateAcknowledged();
+ }
}
void OutgoingJingleFileTransfer::startTransferViaLocalCandidate() {
- SWIFT_LOG(debug) << std::endl;
-
- if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
- setInternalState(WaitingForLocalProxyActivate);
- transporter->startActivatingProxy(theirCandidateChoice->jid);
- }
- else {
- transportSession = createLocalCandidateSession();
- startTransferringIfCandidateAcknowledged();
- }
+ SWIFT_LOG(debug) << std::endl;
+
+ if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ setInternalState(WaitingForLocalProxyActivate);
+ transporter->startActivatingProxy(theirCandidateChoice->jid);
+ }
+ else {
+ transportSession = createLocalCandidateSession();
+ startTransferringIfCandidateAcknowledged();
+ }
}
void OutgoingJingleFileTransfer::startTransferringIfCandidateAcknowledged() {
- if (candidateAcknowledged) {
- startTransferring(transportSession);
- }
- else {
- setInternalState(WaitingForCandidateAcknowledge);
- }
+ if (candidateAcknowledged) {
+ startTransferring(transportSession);
+ }
+ else {
+ setInternalState(WaitingForCandidateAcknowledge);
+ }
}
void OutgoingJingleFileTransfer::handleTransportInfoAcknowledged(const std::string& id) {
- if (id == candidateSelectRequestID) {
- candidateAcknowledged = true;
- }
- if (state == WaitingForCandidateAcknowledge) {
- startTransferring(transportSession);
- }
+ if (id == candidateSelectRequestID) {
+ candidateAcknowledged = true;
+ }
+ if (state == WaitingForCandidateAcknowledge) {
+ startTransferring(transportSession);
+ }
}
JingleContentID OutgoingJingleFileTransfer::getContentID() const {
- return contentID;
+ return contentID;
}
bool OutgoingJingleFileTransfer::hasPriorityOnCandidateTie() const {
- return true;
+ return true;
}
bool OutgoingJingleFileTransfer::isWaitingForPeerProxyActivate() const {
- return state == WaitingForPeerProxyActivate;
+ return state == WaitingForPeerProxyActivate;
}
bool OutgoingJingleFileTransfer::isWaitingForLocalProxyActivate() const {
- return state == WaitingForLocalProxyActivate;
+ return state == WaitingForLocalProxyActivate;
}
bool OutgoingJingleFileTransfer::isTryingCandidates() const {
- return state == TryingCandidates;
+ return state == TryingCandidates;
}
boost::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createLocalCandidateSession() {
- return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
+ return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
}
boost::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createRemoteCandidateSession() {
- return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
+ return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
}
void OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout() {
- assert(state == WaitForTermination);
- SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now." << std::endl;
- waitForRemoteTermination->stop();
- terminate(JinglePayload::Reason::MediaError);
+ assert(state == WaitForTermination);
+ SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now." << std::endl;
+ waitForRemoteTermination->stop();
+ terminate(JinglePayload::Reason::MediaError);
}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
index 96b465b..a8dad1e 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
@@ -25,98 +25,98 @@
#include <Swiften/Network/Timer.h>
namespace Swift {
- class CryptoProvider;
- class FileTransferTransporter;
- class FileTransferTransporterFactory;
- class IDGenerator;
- class IncrementalBytestreamHashCalculator;
- class ReadBytestream;
- class TimerFactory;
- class TransportSession;
-
- class SWIFTEN_API OutgoingJingleFileTransfer : public OutgoingFileTransfer, public JingleFileTransfer {
- public:
- OutgoingJingleFileTransfer(
- const JID& to,
- boost::shared_ptr<JingleSession>,
- boost::shared_ptr<ReadBytestream>,
- FileTransferTransporterFactory*,
- TimerFactory*,
- IDGenerator*,
- const JingleFileTransferFileInfo&,
- const FileTransferOptions&,
- CryptoProvider*);
- virtual ~OutgoingJingleFileTransfer();
-
- virtual void start() SWIFTEN_OVERRIDE;
- virtual void cancel() SWIFTEN_OVERRIDE;
-
- private:
- enum State {
- Initial,
- GeneratingInitialLocalCandidates,
- WaitingForAccept,
- TryingCandidates,
- WaitingForPeerProxyActivate,
- WaitingForLocalProxyActivate,
- WaitingForCandidateAcknowledge,
- FallbackRequested,
- Transferring,
- WaitForTermination,
- Finished
- };
-
- virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE;
- virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE;
- virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE;
- void startTransferringIfCandidateAcknowledged();
-
- virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) SWIFTEN_OVERRIDE;
- virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE;
-
- virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE;
-
- virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
-
- virtual void fallback() SWIFTEN_OVERRIDE;
- void handleTransferFinished(boost::optional<FileTransferError>);
-
- void sendSessionInfoHash();
-
- virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE;
-
- virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE;
- virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE;
- virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE;
- virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE;
-
- void handleWaitForRemoteTerminationTimeout();
-
- void stopAll();
- void setInternalState(State state);
- void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error);
-
- static FileTransfer::State::Type getExternalState(State state);
-
- private:
- IDGenerator* idGenerator;
- boost::shared_ptr<ReadBytestream> stream;
- JingleFileTransferFileInfo fileInfo;
- FileTransferOptions options;
- JingleContentID contentID;
- IncrementalBytestreamHashCalculator* hashCalculator;
- State state;
- bool candidateAcknowledged;
-
- Timer::ref waitForRemoteTermination;
-
- boost::bsignals::connection processedBytesConnection;
- boost::bsignals::connection transferFinishedConnection;
- };
+ class CryptoProvider;
+ class FileTransferTransporter;
+ class FileTransferTransporterFactory;
+ class IDGenerator;
+ class IncrementalBytestreamHashCalculator;
+ class ReadBytestream;
+ class TimerFactory;
+ class TransportSession;
+
+ class SWIFTEN_API OutgoingJingleFileTransfer : public OutgoingFileTransfer, public JingleFileTransfer {
+ public:
+ OutgoingJingleFileTransfer(
+ const JID& to,
+ boost::shared_ptr<JingleSession>,
+ boost::shared_ptr<ReadBytestream>,
+ FileTransferTransporterFactory*,
+ TimerFactory*,
+ IDGenerator*,
+ const JingleFileTransferFileInfo&,
+ const FileTransferOptions&,
+ CryptoProvider*);
+ virtual ~OutgoingJingleFileTransfer();
+
+ virtual void start() SWIFTEN_OVERRIDE;
+ virtual void cancel() SWIFTEN_OVERRIDE;
+
+ private:
+ enum State {
+ Initial,
+ GeneratingInitialLocalCandidates,
+ WaitingForAccept,
+ TryingCandidates,
+ WaitingForPeerProxyActivate,
+ WaitingForLocalProxyActivate,
+ WaitingForCandidateAcknowledge,
+ FallbackRequested,
+ Transferring,
+ WaitForTermination,
+ Finished
+ };
+
+ virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE;
+ virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportRejectReceived(const JingleContentID &, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE;
+ virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE;
+ void startTransferringIfCandidateAcknowledged();
+
+ virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) SWIFTEN_OVERRIDE;
+ virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE;
+
+ virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE;
+
+ virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
+
+ virtual void fallback() SWIFTEN_OVERRIDE;
+ void handleTransferFinished(boost::optional<FileTransferError>);
+
+ void sendSessionInfoHash();
+
+ virtual void startTransferring(boost::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE;
+
+ virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE;
+
+ void handleWaitForRemoteTerminationTimeout();
+
+ void stopAll();
+ void setInternalState(State state);
+ void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error);
+
+ static FileTransfer::State::Type getExternalState(State state);
+
+ private:
+ IDGenerator* idGenerator;
+ boost::shared_ptr<ReadBytestream> stream;
+ JingleFileTransferFileInfo fileInfo;
+ FileTransferOptions options;
+ JingleContentID contentID;
+ IncrementalBytestreamHashCalculator* hashCalculator;
+ State state;
+ bool candidateAcknowledged;
+
+ Timer::ref waitForRemoteTermination;
+
+ boost::bsignals::connection processedBytesConnection;
+ boost::bsignals::connection transferFinishedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/ReadBytestream.h b/Swiften/FileTransfer/ReadBytestream.h
index 1ba8417..e967c53 100644
--- a/Swiften/FileTransfer/ReadBytestream.h
+++ b/Swiften/FileTransfer/ReadBytestream.h
@@ -14,20 +14,20 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class SWIFTEN_API ReadBytestream {
- public:
- virtual ~ReadBytestream();
-
- /**
- * Return an empty vector if no more data is available.
- * Use onDataAvailable signal for signaling there is data available again.
- */
- virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size) = 0;
-
- virtual bool isFinished() const = 0;
-
- public:
- boost::signal<void ()> onDataAvailable;
- boost::signal<void (const std::vector<unsigned char>&)> onRead;
- };
+ class SWIFTEN_API ReadBytestream {
+ public:
+ virtual ~ReadBytestream();
+
+ /**
+ * Return an empty vector if no more data is available.
+ * Use onDataAvailable signal for signaling there is data available again.
+ */
+ virtual boost::shared_ptr< std::vector<unsigned char> > read(size_t size) = 0;
+
+ virtual bool isFinished() const = 0;
+
+ public:
+ boost::signal<void ()> onDataAvailable;
+ boost::signal<void (const std::vector<unsigned char>&)> onRead;
+ };
}
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
index 97e2706..296723e 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
@@ -25,73 +25,73 @@
using namespace Swift;
RemoteJingleTransportCandidateSelector::RemoteJingleTransportCandidateSelector(
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- const FileTransferOptions& options) :
- connectionFactory(connectionFactory),
- timerFactory(timerFactory),
- options(options) {
+ 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) {
- this->candidates.push(c);
- }
+ const std::vector<JingleS5BTransportPayload::Candidate>& candidates) {
+ foreach(JingleS5BTransportPayload::Candidate c, candidates) {
+ this->candidates.push(c);
+ }
}
void RemoteJingleTransportCandidateSelector::startSelectingCandidate() {
- tryNextCandidate();
+ tryNextCandidate();
}
void RemoteJingleTransportCandidateSelector::stopSelectingCandidate() {
- if (s5bSession) {
- sessionReadyConnection.disconnect();
- s5bSession->stop();
- }
+ 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>(), boost::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())) {
- boost::shared_ptr<Connection> connection = connectionFactory->createConnection();
- s5bSession = boost::make_shared<SOCKS5BytestreamClientSession>(
- connection, lastCandidate.hostPort, socks5DstAddr, timerFactory);
- sessionReadyConnection = s5bSession->onSessionReady.connect(
- boost::bind(&RemoteJingleTransportCandidateSelector::handleSessionReady, this, _1));
- s5bSession->start();
- }
- else {
- SWIFT_LOG(debug) << "Can't handle this type of candidate" << std::endl;
- tryNextCandidate();
- }
- }
+ if (candidates.empty()) {
+ SWIFT_LOG(debug) << "No more candidates" << std::endl;
+ onCandidateSelectFinished(
+ boost::optional<JingleS5BTransportPayload::Candidate>(), boost::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())) {
+ boost::shared_ptr<Connection> connection = connectionFactory->createConnection();
+ s5bSession = boost::make_shared<SOCKS5BytestreamClientSession>(
+ connection, lastCandidate.hostPort, socks5DstAddr, timerFactory);
+ sessionReadyConnection = s5bSession->onSessionReady.connect(
+ boost::bind(&RemoteJingleTransportCandidateSelector::handleSessionReady, this, _1));
+ s5bSession->start();
+ }
+ else {
+ SWIFT_LOG(debug) << "Can't handle this type of candidate" << std::endl;
+ tryNextCandidate();
+ }
+ }
}
void RemoteJingleTransportCandidateSelector::handleSessionReady(bool error) {
- sessionReadyConnection.disconnect();
- if (error) {
- s5bSession.reset();
- tryNextCandidate();
- }
- else {
- onCandidateSelectFinished(lastCandidate, s5bSession);
- }
+ sessionReadyConnection.disconnect();
+ if (error) {
+ s5bSession.reset();
+ tryNextCandidate();
+ }
+ else {
+ onCandidateSelectFinished(lastCandidate, s5bSession);
+ }
}
void RemoteJingleTransportCandidateSelector::setSOCKS5DstAddr(const std::string& socks5DstAddr) {
- this->socks5DstAddr = socks5DstAddr;
+ this->socks5DstAddr = socks5DstAddr;
}
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
index 0266f9d..5928754 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
@@ -27,37 +27,37 @@
#include <Swiften/Network/Connection.h>
namespace Swift {
- class ConnectionFactory;
- class TimerFactory;
-
- class RemoteJingleTransportCandidateSelector {
- public:
- RemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*, const FileTransferOptions&);
- virtual ~RemoteJingleTransportCandidateSelector();
-
- virtual void addCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&);
- virtual void setSOCKS5DstAddr(const std::string&);
- virtual void startSelectingCandidate();
- virtual void stopSelectingCandidate();
-
- boost::signal<void (const boost::optional<JingleS5BTransportPayload::Candidate>&, boost::shared_ptr<SOCKS5BytestreamClientSession>)> onCandidateSelectFinished;
-
- private:
- void tryNextCandidate();
- void handleSessionReady(bool error);
-
- private:
- ConnectionFactory* connectionFactory;
- TimerFactory* timerFactory;
-
- std::priority_queue<
- JingleS5BTransportPayload::Candidate,
- std::vector<JingleS5BTransportPayload::Candidate>,
- JingleS5BTransportPayload::CompareCandidate> candidates;
- boost::shared_ptr<SOCKS5BytestreamClientSession> s5bSession;
- boost::bsignals::connection sessionReadyConnection;
- JingleS5BTransportPayload::Candidate lastCandidate;
- std::string socks5DstAddr;
- FileTransferOptions options;
- };
+ class ConnectionFactory;
+ class TimerFactory;
+
+ class RemoteJingleTransportCandidateSelector {
+ public:
+ RemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*, const FileTransferOptions&);
+ virtual ~RemoteJingleTransportCandidateSelector();
+
+ virtual void addCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&);
+ virtual void setSOCKS5DstAddr(const std::string&);
+ virtual void startSelectingCandidate();
+ virtual void stopSelectingCandidate();
+
+ boost::signal<void (const boost::optional<JingleS5BTransportPayload::Candidate>&, boost::shared_ptr<SOCKS5BytestreamClientSession>)> onCandidateSelectFinished;
+
+ private:
+ void tryNextCandidate();
+ void handleSessionReady(bool error);
+
+ private:
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+
+ std::priority_queue<
+ JingleS5BTransportPayload::Candidate,
+ std::vector<JingleS5BTransportPayload::Candidate>,
+ JingleS5BTransportPayload::CompareCandidate> candidates;
+ boost::shared_ptr<SOCKS5BytestreamClientSession> s5bSession;
+ boost::bsignals::connection sessionReadyConnection;
+ JingleS5BTransportPayload::Candidate lastCandidate;
+ std::string socks5DstAddr;
+ FileTransferOptions options;
+ };
}
diff --git a/Swiften/FileTransfer/S5BTransportSession.h b/Swiften/FileTransfer/S5BTransportSession.h
index b3eee3c..95143bd 100644
--- a/Swiften/FileTransfer/S5BTransportSession.h
+++ b/Swiften/FileTransfer/S5BTransportSession.h
@@ -18,52 +18,52 @@ namespace Swift {
template <typename T>
class SWIFTEN_API S5BTransportSession : public TransportSession {
- public:
- S5BTransportSession(
- boost::shared_ptr<T> session,
- boost::shared_ptr<ReadBytestream> readStream) :
- session(session),
- readStream(readStream) {
- initialize();
- }
+ public:
+ S5BTransportSession(
+ boost::shared_ptr<T> session,
+ boost::shared_ptr<ReadBytestream> readStream) :
+ session(session),
+ readStream(readStream) {
+ initialize();
+ }
- S5BTransportSession(
- boost::shared_ptr<T> session,
- boost::shared_ptr<WriteBytestream> writeStream) :
- session(session),
- writeStream(writeStream) {
- initialize();
- }
+ S5BTransportSession(
+ boost::shared_ptr<T> session,
+ boost::shared_ptr<WriteBytestream> writeStream) :
+ session(session),
+ writeStream(writeStream) {
+ initialize();
+ }
- virtual ~S5BTransportSession() {
- }
+ virtual ~S5BTransportSession() {
+ }
- virtual void start() SWIFTEN_OVERRIDE {
- if (readStream) {
- session->startSending(readStream);
- }
- else {
- session->startReceiving(writeStream);
- }
- }
+ virtual void start() SWIFTEN_OVERRIDE {
+ if (readStream) {
+ session->startSending(readStream);
+ }
+ else {
+ session->startReceiving(writeStream);
+ }
+ }
- virtual void stop() SWIFTEN_OVERRIDE {
- session->stop();
- }
+ virtual void stop() SWIFTEN_OVERRIDE {
+ session->stop();
+ }
- private:
- void initialize() {
- finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
- bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1));
- }
+ private:
+ void initialize() {
+ finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
+ bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1));
+ }
- private:
- boost::shared_ptr<T> session;
- boost::shared_ptr<ReadBytestream> readStream;
- boost::shared_ptr<WriteBytestream> writeStream;
+ private:
+ boost::shared_ptr<T> session;
+ boost::shared_ptr<ReadBytestream> readStream;
+ boost::shared_ptr<WriteBytestream> writeStream;
- boost::bsignals::scoped_connection finishedConnection;
- boost::bsignals::scoped_connection bytesSentConnection;
+ boost::bsignals::scoped_connection finishedConnection;
+ boost::bsignals::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
index 1a23e29..98a0988 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
@@ -27,250 +27,250 @@
namespace Swift {
SOCKS5BytestreamClientSession::SOCKS5BytestreamClientSession(
- boost::shared_ptr<Connection> connection,
- const HostAddressPort& addressPort,
- const std::string& destination,
- TimerFactory* timerFactory) :
- connection(connection),
- addressPort(addressPort),
- destination(destination),
- state(Initial),
- chunkSize(131072) {
- weFailedTimeout = timerFactory->createTimer(3000);
- weFailedTimeout->onTick.connect(
- boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
+ boost::shared_ptr<Connection> connection,
+ const HostAddressPort& addressPort,
+ const std::string& destination,
+ TimerFactory* timerFactory) :
+ connection(connection),
+ addressPort(addressPort),
+ destination(destination),
+ state(Initial),
+ chunkSize(131072) {
+ weFailedTimeout = timerFactory->createTimer(3000);
+ weFailedTimeout->onTick.connect(
+ boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
}
SOCKS5BytestreamClientSession::~SOCKS5BytestreamClientSession() {
- weFailedTimeout->onTick.disconnect(
- boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
- weFailedTimeout->stop();
+ weFailedTimeout->onTick.disconnect(
+ boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
+ weFailedTimeout->stop();
}
void SOCKS5BytestreamClientSession::start() {
- assert(state == Initial);
- SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl;
- weFailedTimeout->start();
- connectFinishedConnection = connection->onConnectFinished.connect(
- boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1));
- connection->connect(addressPort);
+ assert(state == Initial);
+ SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ weFailedTimeout->start();
+ connectFinishedConnection = connection->onConnectFinished.connect(
+ boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1));
+ connection->connect(addressPort);
}
void SOCKS5BytestreamClientSession::stop() {
- SWIFT_LOG(debug) << std::endl;
- if (state < Ready) {
- weFailedTimeout->stop();
- }
- if (state == Finished) {
- return;
- }
- closeConnection();
- readBytestream.reset();
- state = Finished;
+ SWIFT_LOG(debug) << std::endl;
+ if (state < Ready) {
+ weFailedTimeout->stop();
+ }
+ if (state == Finished) {
+ return;
+ }
+ closeConnection();
+ readBytestream.reset();
+ state = Finished;
}
void SOCKS5BytestreamClientSession::process() {
- SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl;
- ByteArray bndAddress;
- switch(state) {
- case Initial:
- hello();
- break;
- case Hello:
- if (unprocessedData.size() > 1) {
- unsigned char version = unprocessedData[0];
- unsigned char authMethod = unprocessedData[1];
- if (version != 5 || authMethod != 0) {
- // signal failure to upper level
- finish(true);
- return;
- }
- unprocessedData.clear();
- authenticate();
- }
- break;
- case Authenticating:
- if (unprocessedData.size() < 5) {
- // need more data to start progressing
- break;
- }
- if (unprocessedData[0] != '\x05') {
- // wrong version
- // disconnect & signal failure
- finish(true);
- break;
- }
- if (unprocessedData[1] != '\x00') {
- // no success
- // disconnect & signal failure
- finish(true);
- break;
- }
- if (unprocessedData[3] != '\x03') {
- // we expect x'03' = DOMAINNAME here
- // disconnect & signal failure
- finish(true);
- break;
- }
- if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) {
- // complete domainname and port not available yet
- break;
- }
- bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]);
- if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) {
- // we expect a 0 as port
- // disconnect and fail
- finish(true);
- }
- unprocessedData.clear();
- state = Ready;
- SWIFT_LOG(debug) << "session ready" << std::endl;
- // issue ready signal so the bytestream can be used for reading or writing
- weFailedTimeout->stop();
- onSessionReady(false);
- break;
- case Ready:
- SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl;
- break;
- case Reading:
- case Writing:
- case Finished:
- SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl;
- SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl;
- unprocessedData.clear();
- //assert(false);
- }
+ SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl;
+ ByteArray bndAddress;
+ switch(state) {
+ case Initial:
+ hello();
+ break;
+ case Hello:
+ if (unprocessedData.size() > 1) {
+ unsigned char version = unprocessedData[0];
+ unsigned char authMethod = unprocessedData[1];
+ if (version != 5 || authMethod != 0) {
+ // signal failure to upper level
+ finish(true);
+ return;
+ }
+ unprocessedData.clear();
+ authenticate();
+ }
+ break;
+ case Authenticating:
+ if (unprocessedData.size() < 5) {
+ // need more data to start progressing
+ break;
+ }
+ if (unprocessedData[0] != '\x05') {
+ // wrong version
+ // disconnect & signal failure
+ finish(true);
+ break;
+ }
+ if (unprocessedData[1] != '\x00') {
+ // no success
+ // disconnect & signal failure
+ finish(true);
+ break;
+ }
+ if (unprocessedData[3] != '\x03') {
+ // we expect x'03' = DOMAINNAME here
+ // disconnect & signal failure
+ finish(true);
+ break;
+ }
+ if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) {
+ // complete domainname and port not available yet
+ break;
+ }
+ bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]);
+ if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) {
+ // we expect a 0 as port
+ // disconnect and fail
+ finish(true);
+ }
+ unprocessedData.clear();
+ state = Ready;
+ SWIFT_LOG(debug) << "session ready" << std::endl;
+ // issue ready signal so the bytestream can be used for reading or writing
+ weFailedTimeout->stop();
+ onSessionReady(false);
+ break;
+ case Ready:
+ SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl;
+ break;
+ case Reading:
+ case Writing:
+ case Finished:
+ SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl;
+ SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl;
+ unprocessedData.clear();
+ //assert(false);
+ }
}
void SOCKS5BytestreamClientSession::hello() {
- // Version 5, 1 auth method, No authentication
- const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3);
- connection->write(hello);
- state = Hello;
+ // Version 5, 1 auth method, No authentication
+ const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3);
+ connection->write(hello);
+ state = Hello;
}
void SOCKS5BytestreamClientSession::authenticate() {
- SWIFT_LOG(debug) << std::endl;
- SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4);
- SafeByteArray message = header;
- append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size())));
- authenticateAddress = createByteArray(destination);
- append(message, authenticateAddress);
- append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port
- connection->write(message);
- state = Authenticating;
+ SWIFT_LOG(debug) << std::endl;
+ SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4);
+ SafeByteArray message = header;
+ append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size())));
+ authenticateAddress = createByteArray(destination);
+ append(message, authenticateAddress);
+ append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port
+ connection->write(message);
+ state = Authenticating;
}
void SOCKS5BytestreamClientSession::startReceiving(boost::shared_ptr<WriteBytestream> writeStream) {
- if (state == Ready) {
- state = Reading;
- writeBytestream = writeStream;
- writeBytestream->write(unprocessedData);
- unprocessedData.clear();
- } else {
- SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
- }
+ if (state == Ready) {
+ state = Reading;
+ writeBytestream = writeStream;
+ writeBytestream->write(unprocessedData);
+ unprocessedData.clear();
+ } else {
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ }
}
void SOCKS5BytestreamClientSession::startSending(boost::shared_ptr<ReadBytestream> readStream) {
- if (state == Ready) {
- state = Writing;
- readBytestream = readStream;
- dataWrittenConnection = connection->onDataWritten.connect(
- boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
- sendData();
- } else {
- SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
- }
+ if (state == Ready) {
+ state = Writing;
+ readBytestream = readStream;
+ dataWrittenConnection = connection->onDataWritten.connect(
+ boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
+ sendData();
+ } else {
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ }
}
HostAddressPort SOCKS5BytestreamClientSession::getAddressPort() const {
- return addressPort;
+ return addressPort;
}
void SOCKS5BytestreamClientSession::sendData() {
- if (!readBytestream->isFinished()) {
- try {
- boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize));
- connection->write(createSafeByteArray(*dataToSend));
- onBytesSent(dataToSend->size());
- }
- catch (const BytestreamException&) {
- finish(true);
- }
- }
- else {
- finish(false);
- }
+ if (!readBytestream->isFinished()) {
+ try {
+ boost::shared_ptr<ByteArray> dataToSend = readBytestream->read(boost::numeric_cast<size_t>(chunkSize));
+ connection->write(createSafeByteArray(*dataToSend));
+ onBytesSent(dataToSend->size());
+ }
+ catch (const BytestreamException&) {
+ finish(true);
+ }
+ }
+ else {
+ finish(false);
+ }
}
void SOCKS5BytestreamClientSession::finish(bool error) {
- SWIFT_LOG(debug) << std::endl;
- if (state < Ready) {
- weFailedTimeout->stop();
- }
- closeConnection();
- readBytestream.reset();
- if (state == Initial || state == Hello || state == Authenticating) {
- onSessionReady(true);
- }
- else {
- state = Finished;
- if (error) {
- onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError));
- } else {
- onFinished(boost::optional<FileTransferError>());
- }
- }
+ SWIFT_LOG(debug) << std::endl;
+ if (state < Ready) {
+ weFailedTimeout->stop();
+ }
+ closeConnection();
+ readBytestream.reset();
+ if (state == Initial || state == Hello || state == Authenticating) {
+ onSessionReady(true);
+ }
+ else {
+ state = Finished;
+ if (error) {
+ onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError));
+ } else {
+ onFinished(boost::optional<FileTransferError>());
+ }
+ }
}
void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) {
- connectFinishedConnection.disconnect();
- if (error) {
- SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl;
- finish(true);
- } else {
- SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl;
- disconnectedConnection = connection->onDisconnected.connect(
- boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1));
- dataReadConnection = connection->onDataRead.connect(
- boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
- weFailedTimeout->stop();
- weFailedTimeout->start();
- process();
- }
+ connectFinishedConnection.disconnect();
+ if (error) {
+ SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ finish(true);
+ } else {
+ SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl;
+ disconnectedConnection = connection->onDisconnected.connect(
+ boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1));
+ dataReadConnection = connection->onDataRead.connect(
+ boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
+ weFailedTimeout->stop();
+ weFailedTimeout->start();
+ process();
+ }
}
void SOCKS5BytestreamClientSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl;
- if (state != Reading) {
- append(unprocessedData, *data);
- process();
- }
- else {
- writeBytestream->write(createByteArray(vecptr(*data), data->size()));
- //onBytesReceived(data->size());
- }
+ SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl;
+ if (state != Reading) {
+ append(unprocessedData, *data);
+ process();
+ }
+ else {
+ writeBytestream->write(createByteArray(vecptr(*data), data->size()));
+ //onBytesReceived(data->size());
+ }
}
void SOCKS5BytestreamClientSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
- SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
- if (error) {
- finish(true);
- }
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ if (error) {
+ finish(true);
+ }
}
void SOCKS5BytestreamClientSession::handleWeFailedTimeout() {
- SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl;
- finish(true);
+ SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl;
+ finish(true);
}
void SOCKS5BytestreamClientSession::closeConnection() {
- connectFinishedConnection.disconnect();
- dataWrittenConnection.disconnect();
- dataReadConnection.disconnect();
- disconnectedConnection.disconnect();
- connection->disconnect();
+ connectFinishedConnection.disconnect();
+ dataWrittenConnection.disconnect();
+ dataReadConnection.disconnect();
+ disconnectedConnection.disconnect();
+ connection->disconnect();
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
index 1c0563a..5aea7d0 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
@@ -37,75 +37,75 @@ class TimerFactory;
*/
class SWIFTEN_API SOCKS5BytestreamClientSession {
public:
- enum State {
- Initial,
- Hello,
- Authenticating,
- Ready,
- Writing,
- Reading,
- Finished
- };
+ enum State {
+ Initial,
+ Hello,
+ Authenticating,
+ Ready,
+ Writing,
+ Reading,
+ Finished
+ };
public:
- typedef boost::shared_ptr<SOCKS5BytestreamClientSession> ref;
+ typedef boost::shared_ptr<SOCKS5BytestreamClientSession> ref;
public:
- SOCKS5BytestreamClientSession(
- boost::shared_ptr<Connection> connection,
- const HostAddressPort&,
- const std::string&,
- TimerFactory*);
- ~SOCKS5BytestreamClientSession();
+ SOCKS5BytestreamClientSession(
+ boost::shared_ptr<Connection> connection,
+ const HostAddressPort&,
+ const std::string&,
+ TimerFactory*);
+ ~SOCKS5BytestreamClientSession();
- void start();
- void stop();
+ void start();
+ void stop();
- void startReceiving(boost::shared_ptr<WriteBytestream>);
- void startSending(boost::shared_ptr<ReadBytestream>);
+ void startReceiving(boost::shared_ptr<WriteBytestream>);
+ void startSending(boost::shared_ptr<ReadBytestream>);
- HostAddressPort getAddressPort() const;
+ HostAddressPort getAddressPort() const;
- boost::signal<void (bool /*error*/)> onSessionReady;
+ boost::signal<void (bool /*error*/)> onSessionReady;
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
- boost::signal<void (size_t)> onBytesSent;
- // boost::signal<void (size_t)> onBytesReceived;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signal<void (size_t)> onBytesSent;
+ // boost::signal<void (size_t)> onBytesReceived;
private:
- void process();
- void hello();
- void authenticate();
+ void process();
+ void hello();
+ void authenticate();
- void handleConnectFinished(bool error);
- void handleDataRead(boost::shared_ptr<SafeByteArray>);
- void handleDisconnected(const boost::optional<Connection::Error>&);
- void handleWeFailedTimeout();
+ void handleConnectFinished(bool error);
+ void handleDataRead(boost::shared_ptr<SafeByteArray>);
+ void handleDisconnected(const boost::optional<Connection::Error>&);
+ void handleWeFailedTimeout();
- void finish(bool error);
- void sendData();
- void closeConnection();
+ void finish(bool error);
+ void sendData();
+ void closeConnection();
private:
- boost::shared_ptr<Connection> connection;
- HostAddressPort addressPort;
- std::string destination; // hexify(SHA1(sessionID + requester + target))
+ boost::shared_ptr<Connection> connection;
+ HostAddressPort addressPort;
+ std::string destination; // hexify(SHA1(sessionID + requester + target))
- State state;
+ State state;
- ByteArray unprocessedData;
- ByteArray authenticateAddress;
+ ByteArray unprocessedData;
+ ByteArray authenticateAddress;
- int chunkSize;
- boost::shared_ptr<WriteBytestream> writeBytestream;
- boost::shared_ptr<ReadBytestream> readBytestream;
+ int chunkSize;
+ boost::shared_ptr<WriteBytestream> writeBytestream;
+ boost::shared_ptr<ReadBytestream> readBytestream;
- Timer::ref weFailedTimeout;
+ Timer::ref weFailedTimeout;
- boost::bsignals::scoped_connection connectFinishedConnection;
- boost::bsignals::scoped_connection dataWrittenConnection;
- boost::bsignals::scoped_connection dataReadConnection;
- boost::bsignals::scoped_connection disconnectedConnection;
+ boost::bsignals::scoped_connection connectFinishedConnection;
+ boost::bsignals::scoped_connection dataWrittenConnection;
+ boost::bsignals::scoped_connection dataReadConnection;
+ boost::bsignals::scoped_connection disconnectedConnection;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
index a1ef8f6..881a82d 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
@@ -32,172 +32,172 @@ SOCKS5BytestreamProxiesManager::SOCKS5BytestreamProxiesManager(ConnectionFactory
}
SOCKS5BytestreamProxiesManager::~SOCKS5BytestreamProxiesManager() {
- if (proxyFinder_) {
- proxyFinder_->stop();
- }
-
- foreach (const ProxySessionsMap::value_type& sessionsForID, proxySessions_) {
- foreach (const ProxyJIDClientSessionVector::value_type& session, sessionsForID.second) {
- session.second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionsForID.first, session.first, session.second, _1));
- session.second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionsForID.first, session.first, session.second, _1));
- }
- }
+ if (proxyFinder_) {
+ proxyFinder_->stop();
+ }
+
+ foreach (const ProxySessionsMap::value_type& sessionsForID, proxySessions_) {
+ foreach (const ProxyJIDClientSessionVector::value_type& session, sessionsForID.second) {
+ session.second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionsForID.first, session.first, session.second, _1));
+ session.second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionsForID.first, session.first, session.second, _1));
+ }
+ }
}
void SOCKS5BytestreamProxiesManager::addS5BProxy(S5BProxyRequest::ref proxy) {
- if (proxy) {
- SWIFT_LOG_ASSERT(HostAddress(proxy->getStreamHost().get().host).isValid(), warning) << std::endl;
- if (!localS5BProxies_) {
- localS5BProxies_ = std::vector<S5BProxyRequest::ref>();
- }
- localS5BProxies_->push_back(proxy);
- }
+ if (proxy) {
+ SWIFT_LOG_ASSERT(HostAddress(proxy->getStreamHost().get().host).isValid(), warning) << std::endl;
+ if (!localS5BProxies_) {
+ localS5BProxies_ = std::vector<S5BProxyRequest::ref>();
+ }
+ localS5BProxies_->push_back(proxy);
+ }
}
const boost::optional<std::vector<S5BProxyRequest::ref> >& SOCKS5BytestreamProxiesManager::getOrDiscoverS5BProxies() {
- if (!localS5BProxies_ && !proxyFinder_) {
- queryForProxies();
- }
- return localS5BProxies_;
+ if (!localS5BProxies_ && !proxyFinder_) {
+ queryForProxies();
+ }
+ return localS5BProxies_;
}
void SOCKS5BytestreamProxiesManager::connectToProxies(const std::string& sessionID) {
- SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl;
- ProxyJIDClientSessionVector clientSessions;
-
- if (localS5BProxies_) {
- foreach(S5BProxyRequest::ref proxy, localS5BProxies_.get()) {
- boost::shared_ptr<Connection> conn = connectionFactory_->createConnection();
-
- HostAddressPort addressPort = HostAddressPort(proxy->getStreamHost().get().host, proxy->getStreamHost().get().port);
- SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
- boost::shared_ptr<SOCKS5BytestreamClientSession> session = boost::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
- JID proxyJid = proxy->getStreamHost().get().jid;
- clientSessions.push_back(std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session));
- session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1));
- session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1));
- session->start();
- }
- }
-
- proxySessions_[sessionID] = clientSessions;
+ SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl;
+ ProxyJIDClientSessionVector clientSessions;
+
+ if (localS5BProxies_) {
+ foreach(S5BProxyRequest::ref proxy, localS5BProxies_.get()) {
+ boost::shared_ptr<Connection> conn = connectionFactory_->createConnection();
+
+ HostAddressPort addressPort = HostAddressPort(proxy->getStreamHost().get().host, proxy->getStreamHost().get().port);
+ SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
+ boost::shared_ptr<SOCKS5BytestreamClientSession> session = boost::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
+ JID proxyJid = proxy->getStreamHost().get().jid;
+ clientSessions.push_back(std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session));
+ session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1));
+ session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1));
+ session->start();
+ }
+ }
+
+ proxySessions_[sessionID] = clientSessions;
}
boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID) {
- // checking parameters
- if (proxySessions_.find(sessionID) == proxySessions_.end()) {
- return boost::shared_ptr<SOCKS5BytestreamClientSession>();
- }
-
- // get active session
- boost::shared_ptr<SOCKS5BytestreamClientSession> activeSession;
- for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end(); i++) {
- i->second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJID, i->second, _1));
- i->second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJID, i->second, _1));
- if (i->first == proxyJID && !activeSession) {
- activeSession = i->second;
- }
- else {
- i->second->stop();
- }
- }
-
- proxySessions_.erase(sessionID);
-
- return activeSession;
+ // checking parameters
+ if (proxySessions_.find(sessionID) == proxySessions_.end()) {
+ return boost::shared_ptr<SOCKS5BytestreamClientSession>();
+ }
+
+ // get active session
+ boost::shared_ptr<SOCKS5BytestreamClientSession> activeSession;
+ for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end(); i++) {
+ i->second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJID, i->second, _1));
+ i->second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJID, i->second, _1));
+ if (i->first == proxyJID && !activeSession) {
+ activeSession = i->second;
+ }
+ else {
+ i->second->stop();
+ }
+ }
+
+ proxySessions_.erase(sessionID);
+
+ return activeSession;
}
boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr) {
- SOCKS5BytestreamClientSession::ref connection = boost::make_shared<SOCKS5BytestreamClientSession>(connectionFactory_->createConnection(), addressPort, destAddr, timerFactory_);
- return connection;
+ SOCKS5BytestreamClientSession::ref connection = boost::make_shared<SOCKS5BytestreamClientSession>(connectionFactory_->createConnection(), addressPort, destAddr, timerFactory_);
+ return connection;
}
void SOCKS5BytestreamProxiesManager::handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts) {
- proxyFinder_->onProxiesFound.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1));
- foreach(S5BProxyRequest::ref proxy, proxyHosts) {
- if (proxy) {
- if (HostAddress(proxy->getStreamHost().get().host).isValid()) {
- addS5BProxy(proxy);
- onDiscoveredProxiesChanged();
- }
- else {
- DomainNameAddressQuery::ref resolveRequest = resolver_->createAddressQuery(proxy->getStreamHost().get().host);
- resolveRequest->onResult.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleNameLookupResult, this, _1, _2, proxy));
- resolveRequest->run();
- }
- }
- }
- proxyFinder_->stop();
- proxyFinder_.reset();
- if (proxyHosts.empty()) {
- onDiscoveredProxiesChanged();
- }
+ proxyFinder_->onProxiesFound.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1));
+ foreach(S5BProxyRequest::ref proxy, proxyHosts) {
+ if (proxy) {
+ if (HostAddress(proxy->getStreamHost().get().host).isValid()) {
+ addS5BProxy(proxy);
+ onDiscoveredProxiesChanged();
+ }
+ else {
+ DomainNameAddressQuery::ref resolveRequest = resolver_->createAddressQuery(proxy->getStreamHost().get().host);
+ resolveRequest->onResult.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleNameLookupResult, this, _1, _2, proxy));
+ resolveRequest->run();
+ }
+ }
+ }
+ proxyFinder_->stop();
+ proxyFinder_.reset();
+ if (proxyHosts.empty()) {
+ onDiscoveredProxiesChanged();
+ }
}
void SOCKS5BytestreamProxiesManager::handleNameLookupResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error, S5BProxyRequest::ref proxy) {
- if (error) {
- onDiscoveredProxiesChanged();
- }
- else {
- if (addresses.empty()) {
- SWIFT_LOG(warning) << "S5B proxy hostname does not resolve." << std::endl;
- }
- else {
- // generate proxy per returned address
- foreach (const HostAddress& address, addresses) {
- S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get();
- S5BProxyRequest::ref proxyForAddress = boost::make_shared<S5BProxyRequest>(*proxy);
- streamHost.host = address.toString();
- proxyForAddress->setStreamHost(streamHost);
- addS5BProxy(proxyForAddress);
- }
- }
- onDiscoveredProxiesChanged();
- }
+ if (error) {
+ onDiscoveredProxiesChanged();
+ }
+ else {
+ if (addresses.empty()) {
+ SWIFT_LOG(warning) << "S5B proxy hostname does not resolve." << std::endl;
+ }
+ else {
+ // generate proxy per returned address
+ foreach (const HostAddress& address, addresses) {
+ S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get();
+ S5BProxyRequest::ref proxyForAddress = boost::make_shared<S5BProxyRequest>(*proxy);
+ streamHost.host = address.toString();
+ proxyForAddress->setStreamHost(streamHost);
+ addS5BProxy(proxyForAddress);
+ }
+ }
+ onDiscoveredProxiesChanged();
+ }
}
void SOCKS5BytestreamProxiesManager::queryForProxies() {
- proxyFinder_ = boost::make_shared<SOCKS5BytestreamProxyFinder>(serviceRoot_, iqRouter_);
+ proxyFinder_ = boost::make_shared<SOCKS5BytestreamProxyFinder>(serviceRoot_, iqRouter_);
- proxyFinder_->onProxiesFound.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1));
- proxyFinder_->start();
+ proxyFinder_->onProxiesFound.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1));
+ proxyFinder_->start();
}
void SOCKS5BytestreamProxiesManager::handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error) {
- session->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this, boost::cref(sessionID), boost::cref(jid), session, _1));
- if (!error) {
- // The SOCKS5 bytestream session to the proxy succeeded; stop and remove other sessions.
- if (proxySessions_.find(sessionID) != proxySessions_.end()) {
- for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) {
- if ((i->first == jid) && (i->second != session)) {
- i->second->stop();
- i = proxySessions_[sessionID].erase(i);
- }
- else {
- i++;
- }
- }
- }
- }
+ session->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this, boost::cref(sessionID), boost::cref(jid), session, _1));
+ if (!error) {
+ // The SOCKS5 bytestream session to the proxy succeeded; stop and remove other sessions.
+ if (proxySessions_.find(sessionID) != proxySessions_.end()) {
+ for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) {
+ if ((i->first == jid) && (i->second != session)) {
+ i->second->stop();
+ i = proxySessions_[sessionID].erase(i);
+ }
+ else {
+ i++;
+ }
+ }
+ }
+ }
}
void SOCKS5BytestreamProxiesManager::handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error) {
- session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, jid, session, _1));
- if (error.is_initialized()) {
- // The SOCKS5 bytestream session to the proxy failed; remove it.
- if (proxySessions_.find(sessionID) != proxySessions_.end()) {
- for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) {
- if ((i->first == jid) && (i->second == session)) {
- i->second->stop();
- i = proxySessions_[sessionID].erase(i);
- break;
- }
- else {
- i++;
- }
- }
- }
- }
+ session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, jid, session, _1));
+ if (error.is_initialized()) {
+ // The SOCKS5 bytestream session to the proxy failed; remove it.
+ if (proxySessions_.find(sessionID) != proxySessions_.end()) {
+ for (ProxyJIDClientSessionVector::iterator i = proxySessions_[sessionID].begin(); i != proxySessions_[sessionID].end();) {
+ if ((i->first == jid) && (i->second == session)) {
+ i->second->stop();
+ i = proxySessions_[sessionID].erase(i);
+ break;
+ }
+ else {
+ i++;
+ }
+ }
+ }
+ }
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
index c7daee7..b490ffa 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
@@ -25,60 +25,60 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class TimerFactory;
- class ConnectionFactory;
- class DomainNameResolver;
- class DomainNameResolveError;
- class IQRouter;
+ class TimerFactory;
+ class ConnectionFactory;
+ class DomainNameResolver;
+ class DomainNameResolveError;
+ class IQRouter;
- /**
- * - manages list of working S5B proxies
- * - creates initial connections (for the candidates you provide)
- */
- class SWIFTEN_API SOCKS5BytestreamProxiesManager {
- public:
- SOCKS5BytestreamProxiesManager(ConnectionFactory*, TimerFactory*, DomainNameResolver*, IQRouter*, const JID&);
- ~SOCKS5BytestreamProxiesManager();
+ /**
+ * - manages list of working S5B proxies
+ * - creates initial connections (for the candidates you provide)
+ */
+ class SWIFTEN_API SOCKS5BytestreamProxiesManager {
+ public:
+ SOCKS5BytestreamProxiesManager(ConnectionFactory*, TimerFactory*, DomainNameResolver*, IQRouter*, const JID&);
+ ~SOCKS5BytestreamProxiesManager();
- void addS5BProxy(S5BProxyRequest::ref);
+ void addS5BProxy(S5BProxyRequest::ref);
- /*
- * Returns a list of external S5B proxies. If the optinal return value is not initialized a discovery process has been started and
- * onDiscoveredProxiesChanged signal will be emitted when it is finished.
- */
- const boost::optional<std::vector<S5BProxyRequest::ref> >& getOrDiscoverS5BProxies();
+ /*
+ * Returns a list of external S5B proxies. If the optinal return value is not initialized a discovery process has been started and
+ * onDiscoveredProxiesChanged signal will be emitted when it is finished.
+ */
+ const boost::optional<std::vector<S5BProxyRequest::ref> >& getOrDiscoverS5BProxies();
- void connectToProxies(const std::string& sessionID);
- boost::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID);
+ void connectToProxies(const std::string& sessionID);
+ boost::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID);
- boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr);
+ boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr);
- public:
- boost::signal<void ()> onDiscoveredProxiesChanged;
+ public:
+ boost::signal<void ()> onDiscoveredProxiesChanged;
- private:
- void handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts);
- void handleNameLookupResult(const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>, S5BProxyRequest::ref proxy);
+ private:
+ void handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts);
+ void handleNameLookupResult(const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>, S5BProxyRequest::ref proxy);
- void queryForProxies();
+ void queryForProxies();
- void handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error);
- void handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error);
+ void handleProxySessionReady(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, bool error);
+ void handleProxySessionFinished(const std::string& sessionID, const JID& jid, boost::shared_ptr<SOCKS5BytestreamClientSession> session, boost::optional<FileTransferError> error);
- private:
- ConnectionFactory* connectionFactory_;
- TimerFactory* timerFactory_;
- DomainNameResolver* resolver_;
- IQRouter* iqRouter_;
- JID serviceRoot_;
+ private:
+ ConnectionFactory* connectionFactory_;
+ TimerFactory* timerFactory_;
+ DomainNameResolver* resolver_;
+ IQRouter* iqRouter_;
+ JID serviceRoot_;
- typedef std::vector<std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> > > ProxyJIDClientSessionVector;
- typedef std::map<std::string, ProxyJIDClientSessionVector> ProxySessionsMap;
- ProxySessionsMap proxySessions_;
+ typedef std::vector<std::pair<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> > > ProxyJIDClientSessionVector;
+ typedef std::map<std::string, ProxyJIDClientSessionVector> ProxySessionsMap;
+ ProxySessionsMap proxySessions_;
- boost::shared_ptr<SOCKS5BytestreamProxyFinder> proxyFinder_;
+ boost::shared_ptr<SOCKS5BytestreamProxyFinder> proxyFinder_;
- boost::optional<std::vector<S5BProxyRequest::ref> > localS5BProxies_;
- };
+ boost::optional<std::vector<S5BProxyRequest::ref> > localS5BProxies_;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
index 78cf2e6..e6c85cf 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
@@ -30,58 +30,58 @@ SOCKS5BytestreamProxyFinder::~SOCKS5BytestreamProxyFinder() {
}
void SOCKS5BytestreamProxyFinder::start() {
- serviceWalker = boost::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();
+ serviceWalker = boost::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 boost::shared_ptr<GenericRequest<S5BProxyRequest> > S5BProxyRequestGenericRequest;
- foreach (S5BProxyRequestGenericRequest requester, pendingRequests) {
- requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
- }
+ typedef boost::shared_ptr<GenericRequest<S5BProxyRequest> > S5BProxyRequestGenericRequest;
+ foreach (S5BProxyRequestGenericRequest 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();
+ 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 = boost::make_shared<S5BProxyRequest>();
- boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::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();
+ S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>();
+ boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::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, boost::shared_ptr<DiscoInfo> discoInfo) {
- if (discoInfo->hasFeature(DiscoInfo::Bytestream)) {
- sendBytestreamQuery(jid);
- }
+ if (discoInfo->hasFeature(DiscoInfo::Bytestream)) {
+ sendBytestreamQuery(jid);
+ }
}
void SOCKS5BytestreamProxyFinder::handleWalkEnded() {
- if (pendingRequests.empty()) {
- onProxiesFound(proxyHosts);
- }
+ if (pendingRequests.empty()) {
+ onProxiesFound(proxyHosts);
+ }
}
void SOCKS5BytestreamProxyFinder::handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest> request, ErrorPayload::ref error) {
- requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
- pendingRequests.erase(requester);
- if (error) {
- SWIFT_LOG(debug) << "ERROR" << std::endl;
- } else {
- if (request) {
- SWIFT_LOG(debug) << "add request" << std::endl;
- proxyHosts.push_back(request);
- }
- }
- if (pendingRequests.empty() && !serviceWalker->isActive()) {
- onProxiesFound(proxyHosts);
- }
+ requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
+ pendingRequests.erase(requester);
+ if (error) {
+ SWIFT_LOG(debug) << "ERROR" << std::endl;
+ } else {
+ if (request) {
+ SWIFT_LOG(debug) << "add request" << std::endl;
+ proxyHosts.push_back(request);
+ }
+ }
+ if (pendingRequests.empty() && !serviceWalker->isActive()) {
+ onProxiesFound(proxyHosts);
+ }
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
index 1c24497..1047df0 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
@@ -29,28 +29,28 @@ class IQRouter;
* restrictive environments.
*/
class SWIFTEN_API SOCKS5BytestreamProxyFinder {
- public:
- SOCKS5BytestreamProxyFinder(const JID& service, IQRouter *iqRouter);
- ~SOCKS5BytestreamProxyFinder();
+ public:
+ SOCKS5BytestreamProxyFinder(const JID& service, IQRouter *iqRouter);
+ ~SOCKS5BytestreamProxyFinder();
- void start();
- void stop();
+ void start();
+ void stop();
- boost::signal<void(std::vector<boost::shared_ptr<S5BProxyRequest> >)> onProxiesFound;
+ boost::signal<void(std::vector<boost::shared_ptr<S5BProxyRequest> >)> onProxiesFound;
- private:
- void sendBytestreamQuery(const JID&);
+ private:
+ void sendBytestreamQuery(const JID&);
- void handleServiceFound(const JID&, boost::shared_ptr<DiscoInfo>);
- void handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest>, ErrorPayload::ref);
- void handleWalkEnded();
+ void handleServiceFound(const JID&, boost::shared_ptr<DiscoInfo>);
+ void handleProxyResponse(boost::shared_ptr<GenericRequest<S5BProxyRequest> > requester, boost::shared_ptr<S5BProxyRequest>, ErrorPayload::ref);
+ void handleWalkEnded();
- private:
- JID service;
- IQRouter* iqRouter;
- boost::shared_ptr<DiscoServiceWalker> serviceWalker;
- std::vector<S5BProxyRequest::ref> proxyHosts;
- std::set<boost::shared_ptr<GenericRequest<S5BProxyRequest> > > pendingRequests;
+ private:
+ JID service;
+ IQRouter* iqRouter;
+ boost::shared_ptr<DiscoServiceWalker> serviceWalker;
+ std::vector<S5BProxyRequest::ref> proxyHosts;
+ std::set<boost::shared_ptr<GenericRequest<S5BProxyRequest> > > pendingRequests;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
index 5f3756d..2f66dff 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
@@ -18,20 +18,20 @@ SOCKS5BytestreamRegistry::SOCKS5BytestreamRegistry() {
}
void SOCKS5BytestreamRegistry::setHasBytestream(const std::string& destination, bool b) {
- if (b) {
- availableBytestreams.insert(destination);
- }
- else {
- availableBytestreams.erase(destination);
- }
+ if (b) {
+ availableBytestreams.insert(destination);
+ }
+ else {
+ availableBytestreams.erase(destination);
+ }
}
bool SOCKS5BytestreamRegistry::hasBytestream(const std::string& destination) const {
- return availableBytestreams.find(destination) != availableBytestreams.end();
+ return availableBytestreams.find(destination) != availableBytestreams.end();
}
std::string SOCKS5BytestreamRegistry::generateSessionID() {
- return idGenerator.generateID();
+ return idGenerator.generateID();
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
index 0575aed..2fa67fa 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
@@ -14,22 +14,22 @@
#include <Swiften/Base/IDGenerator.h>
namespace Swift {
- class SOCKS5BytestreamServerSession;
+ class SOCKS5BytestreamServerSession;
- class SWIFTEN_API SOCKS5BytestreamRegistry {
- public:
- SOCKS5BytestreamRegistry();
+ class SWIFTEN_API SOCKS5BytestreamRegistry {
+ public:
+ SOCKS5BytestreamRegistry();
- void setHasBytestream(const std::string& destination, bool);
- bool hasBytestream(const std::string& destination) const;
+ void setHasBytestream(const std::string& destination, bool);
+ bool hasBytestream(const std::string& destination) const;
- /**
- * Generate a new session ID to use for new S5B streams.
- */
- std::string generateSessionID();
+ /**
+ * Generate a new session ID to use for new S5B streams.
+ */
+ std::string generateSessionID();
- private:
- std::set<std::string> availableBytestreams;
- IDGenerator idGenerator;
- };
+ private:
+ std::set<std::string> availableBytestreams;
+ IDGenerator idGenerator;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
index 4ec95d3..f25227a 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
@@ -18,51 +18,51 @@
namespace Swift {
SOCKS5BytestreamServer::SOCKS5BytestreamServer(
- boost::shared_ptr<ConnectionServer> connectionServer,
- SOCKS5BytestreamRegistry* registry) :
- connectionServer(connectionServer),
- registry(registry) {
+ boost::shared_ptr<ConnectionServer> connectionServer,
+ SOCKS5BytestreamRegistry* registry) :
+ connectionServer(connectionServer),
+ registry(registry) {
}
void SOCKS5BytestreamServer::start() {
- connectionServer->onNewConnection.connect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
+ connectionServer->onNewConnection.connect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
}
void SOCKS5BytestreamServer::stop() {
- connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
- foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
- session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
- session->stop();
- }
- sessions.clear();
+ connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
+ foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
+ session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
+ session->stop();
+ }
+ sessions.clear();
}
void SOCKS5BytestreamServer::handleNewConnection(boost::shared_ptr<Connection> connection) {
- boost::shared_ptr<SOCKS5BytestreamServerSession> session =
- boost::make_shared<SOCKS5BytestreamServerSession>(connection, registry);
- session->onFinished.connect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
- sessions.push_back(session);
- session->start();
+ boost::shared_ptr<SOCKS5BytestreamServerSession> session =
+ boost::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();
+ return connectionServer->getAddressPort();
}
std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > SOCKS5BytestreamServer::getSessions(
- const std::string& streamID) const {
- std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > result;
- foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
- if (session->getStreamID() == streamID) {
- result.push_back(session);
- }
- }
- return result;
+ const std::string& streamID) const {
+ std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > result;
+ foreach (boost::shared_ptr<SOCKS5BytestreamServerSession> session, sessions) {
+ if (session->getStreamID() == streamID) {
+ result.push_back(session);
+ }
+ }
+ return result;
}
void SOCKS5BytestreamServer::handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession> session) {
- sessions.erase(std::remove(sessions.begin(), sessions.end(), session), sessions.end());
- session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, 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/FileTransfer/SOCKS5BytestreamServer.h b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
index 4954f33..f9b293e 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
@@ -18,32 +18,32 @@
#include <Swiften/Network/ConnectionServer.h>
namespace Swift {
- class SOCKS5BytestreamServerSession;
- class CryptoProvider;
+ class SOCKS5BytestreamServerSession;
+ class CryptoProvider;
- class SWIFTEN_API SOCKS5BytestreamServer {
- public:
- SOCKS5BytestreamServer(
- boost::shared_ptr<ConnectionServer> connectionServer,
- SOCKS5BytestreamRegistry* registry);
+ class SWIFTEN_API SOCKS5BytestreamServer {
+ public:
+ SOCKS5BytestreamServer(
+ boost::shared_ptr<ConnectionServer> connectionServer,
+ SOCKS5BytestreamRegistry* registry);
- HostAddressPort getAddressPort() const;
+ HostAddressPort getAddressPort() const;
- void start();
- void stop();
+ void start();
+ void stop();
- std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > getSessions(const std::string& id) const;
+ std::vector< boost::shared_ptr<SOCKS5BytestreamServerSession> > getSessions(const std::string& id) const;
- private:
- void handleNewConnection(boost::shared_ptr<Connection> connection);
- void handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession>);
+ private:
+ void handleNewConnection(boost::shared_ptr<Connection> connection);
+ void handleSessionFinished(boost::shared_ptr<SOCKS5BytestreamServerSession>);
- private:
- friend class SOCKS5BytestreamServerSession;
+ private:
+ friend class SOCKS5BytestreamServerSession;
- boost::shared_ptr<ConnectionServer> connectionServer;
- SOCKS5BytestreamRegistry* registry;
- std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > sessions;
- };
+ boost::shared_ptr<ConnectionServer> connectionServer;
+ SOCKS5BytestreamRegistry* registry;
+ std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > sessions;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
index 3b1be89..2129815 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
@@ -34,223 +34,223 @@ static const int LISTEN_PORTS_BEGIN = 10000;
static const int LISTEN_PORTS_END = 11000;
SOCKS5BytestreamServerManager::SOCKS5BytestreamServerManager(
- SOCKS5BytestreamRegistry* bytestreamRegistry,
- ConnectionServerFactory* connectionServerFactory,
- NetworkEnvironment* networkEnvironment,
- NATTraverser* natTraverser) :
- bytestreamRegistry(bytestreamRegistry),
- connectionServerFactory(connectionServerFactory),
- networkEnvironment(networkEnvironment),
- natTraverser(natTraverser),
- state(Start),
- server(NULL),
- attemptedPortMapping_(false) {
+ SOCKS5BytestreamRegistry* bytestreamRegistry,
+ ConnectionServerFactory* connectionServerFactory,
+ NetworkEnvironment* networkEnvironment,
+ NATTraverser* natTraverser) :
+ bytestreamRegistry(bytestreamRegistry),
+ connectionServerFactory(connectionServerFactory),
+ networkEnvironment(networkEnvironment),
+ natTraverser(natTraverser),
+ state(Start),
+ server(NULL),
+ attemptedPortMapping_(false) {
}
SOCKS5BytestreamServerManager::~SOCKS5BytestreamServerManager() {
- SWIFT_LOG_ASSERT(!connectionServer, warning) << std::endl;
- SWIFT_LOG_ASSERT(!getPublicIPRequest, warning) << std::endl;
- SWIFT_LOG_ASSERT(!forwardPortRequest, warning) << std::endl;
- SWIFT_LOG_ASSERT(state == Start, warning) << std::endl;
- if (portMapping && !unforwardPortRequest) {
- SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now." << std::endl;
- unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort());
- unforwardPortRequest->start();
- }
+ SWIFT_LOG_ASSERT(!connectionServer, warning) << std::endl;
+ SWIFT_LOG_ASSERT(!getPublicIPRequest, warning) << std::endl;
+ SWIFT_LOG_ASSERT(!forwardPortRequest, warning) << std::endl;
+ SWIFT_LOG_ASSERT(state == Start, warning) << std::endl;
+ if (portMapping && !unforwardPortRequest) {
+ SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now." << std::endl;
+ unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort());
+ unforwardPortRequest->start();
+ }
}
boost::shared_ptr<SOCKS5BytestreamServerResourceUser> SOCKS5BytestreamServerManager::aquireResourceUser() {
- boost::shared_ptr<SOCKS5BytestreamServerResourceUser> resourceUser;
- if (s5bServerResourceUser_.expired()) {
- resourceUser = boost::make_shared<SOCKS5BytestreamServerResourceUser>(this);
- s5bServerResourceUser_ = resourceUser;
- }
- else {
- resourceUser = s5bServerResourceUser_.lock();
- }
- return resourceUser;
+ boost::shared_ptr<SOCKS5BytestreamServerResourceUser> resourceUser;
+ if (s5bServerResourceUser_.expired()) {
+ resourceUser = boost::make_shared<SOCKS5BytestreamServerResourceUser>(this);
+ s5bServerResourceUser_ = resourceUser;
+ }
+ else {
+ resourceUser = s5bServerResourceUser_.lock();
+ }
+ return resourceUser;
}
boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> SOCKS5BytestreamServerManager::aquirePortForwardingUser() {
- boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> portForwardingUser;
- if (s5bServerPortForwardingUser_.expired()) {
- portForwardingUser = boost::make_shared<SOCKS5BytestreamServerPortForwardingUser>(this);
- s5bServerPortForwardingUser_ = portForwardingUser;
- }
- else {
- portForwardingUser = s5bServerPortForwardingUser_.lock();
- }
- return portForwardingUser;
+ boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> portForwardingUser;
+ if (s5bServerPortForwardingUser_.expired()) {
+ portForwardingUser = boost::make_shared<SOCKS5BytestreamServerPortForwardingUser>(this);
+ s5bServerPortForwardingUser_ = portForwardingUser;
+ }
+ else {
+ portForwardingUser = s5bServerPortForwardingUser_.lock();
+ }
+ return portForwardingUser;
}
std::vector<HostAddressPort> SOCKS5BytestreamServerManager::getHostAddressPorts() const {
- std::vector<HostAddressPort> result;
- if (connectionServer) {
- std::vector<NetworkInterface> networkInterfaces = networkEnvironment->getNetworkInterfaces();
- foreach (const NetworkInterface& networkInterface, networkInterfaces) {
- foreach (const HostAddress& address, networkInterface.getAddresses()) {
- result.push_back(HostAddressPort(address, connectionServerPort));
- }
- }
- }
- return result;
+ std::vector<HostAddressPort> result;
+ if (connectionServer) {
+ std::vector<NetworkInterface> networkInterfaces = networkEnvironment->getNetworkInterfaces();
+ foreach (const NetworkInterface& networkInterface, networkInterfaces) {
+ foreach (const HostAddress& address, networkInterface.getAddresses()) {
+ result.push_back(HostAddressPort(address, connectionServerPort));
+ }
+ }
+ }
+ return result;
}
std::vector<HostAddressPort> SOCKS5BytestreamServerManager::getAssistedHostAddressPorts() const {
- std::vector<HostAddressPort> result;
- if (publicAddress && portMapping) {
- result.push_back(HostAddressPort(*publicAddress, portMapping->getPublicPort()));
- }
- return result;
+ std::vector<HostAddressPort> result;
+ if (publicAddress && portMapping) {
+ result.push_back(HostAddressPort(*publicAddress, portMapping->getPublicPort()));
+ }
+ return result;
}
bool SOCKS5BytestreamServerManager::isInitialized() const {
- return state == Initialized;
+ return state == Initialized;
}
void SOCKS5BytestreamServerManager::initialize() {
- if (state == Start) {
- state = Initializing;
+ if (state == Start) {
+ state = Initializing;
- // Find a port to listen on
- assert(!connectionServer);
- int port;
- for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) {
- SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl;
- connectionServer = connectionServerFactory->createConnectionServer(HostAddress("::"), port);
- boost::optional<ConnectionServer::Error> error = connectionServer->tryStart();
- if (!error) {
- break;
- }
- else if (*error != ConnectionServer::Conflict) {
- SWIFT_LOG(debug) << "Error starting server" << std::endl;
- onInitialized(false);
- return;
- }
- connectionServer.reset();
- }
- if (!connectionServer) {
- SWIFT_LOG(debug) << "Unable to find an open port" << std::endl;
- onInitialized(false);
- return;
- }
- SWIFT_LOG(debug) << "Server started succesfully" << std::endl;
- connectionServerPort = port;
+ // Find a port to listen on
+ assert(!connectionServer);
+ int port;
+ for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) {
+ SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl;
+ connectionServer = connectionServerFactory->createConnectionServer(HostAddress("::"), port);
+ boost::optional<ConnectionServer::Error> error = connectionServer->tryStart();
+ if (!error) {
+ break;
+ }
+ else if (*error != ConnectionServer::Conflict) {
+ SWIFT_LOG(debug) << "Error starting server" << std::endl;
+ onInitialized(false);
+ return;
+ }
+ connectionServer.reset();
+ }
+ if (!connectionServer) {
+ SWIFT_LOG(debug) << "Unable to find an open port" << std::endl;
+ onInitialized(false);
+ return;
+ }
+ SWIFT_LOG(debug) << "Server started succesfully" << std::endl;
+ connectionServerPort = port;
- // Start bytestream server. Should actually happen before the connectionserver is started
- // but that doesn't really matter here.
- assert(!server);
- server = new SOCKS5BytestreamServer(connectionServer, bytestreamRegistry);
- server->start();
- checkInitializeFinished();
- }
+ // Start bytestream server. Should actually happen before the connectionserver is started
+ // but that doesn't really matter here.
+ assert(!server);
+ server = new SOCKS5BytestreamServer(connectionServer, bytestreamRegistry);
+ server->start();
+ checkInitializeFinished();
+ }
}
bool SOCKS5BytestreamServerManager::isPortForwardingReady() const {
- return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest;
+ return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest;
}
void SOCKS5BytestreamServerManager::setupPortForwarding() {
- assert(server);
- attemptedPortMapping_ = true;
+ assert(server);
+ attemptedPortMapping_ = true;
- // Retrieve public addresses
- assert(!getPublicIPRequest);
- publicAddress = boost::optional<HostAddress>();
- if ((getPublicIPRequest = natTraverser->createGetPublicIPRequest())) {
- getPublicIPRequest->onResult.connect(
- boost::bind(&SOCKS5BytestreamServerManager::handleGetPublicIPResult, this, _1));
- getPublicIPRequest->start();
- }
+ // Retrieve public addresses
+ assert(!getPublicIPRequest);
+ publicAddress = boost::optional<HostAddress>();
+ if ((getPublicIPRequest = natTraverser->createGetPublicIPRequest())) {
+ getPublicIPRequest->onResult.connect(
+ boost::bind(&SOCKS5BytestreamServerManager::handleGetPublicIPResult, this, _1));
+ getPublicIPRequest->start();
+ }
- // Forward ports
- int port = server->getAddressPort().getPort();
- assert(!forwardPortRequest);
- portMapping = boost::optional<NATPortMapping>();
- if ((forwardPortRequest = natTraverser->createForwardPortRequest(port, port))) {
- forwardPortRequest->onResult.connect(
- boost::bind(&SOCKS5BytestreamServerManager::handleForwardPortResult, this, _1));
- forwardPortRequest->start();
- }
+ // Forward ports
+ int port = server->getAddressPort().getPort();
+ assert(!forwardPortRequest);
+ portMapping = boost::optional<NATPortMapping>();
+ if ((forwardPortRequest = natTraverser->createForwardPortRequest(port, port))) {
+ forwardPortRequest->onResult.connect(
+ boost::bind(&SOCKS5BytestreamServerManager::handleForwardPortResult, this, _1));
+ forwardPortRequest->start();
+ }
}
void SOCKS5BytestreamServerManager::removePortForwarding() {
- // remove port forwards
- if (portMapping) {
- unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort());
- unforwardPortRequest->onResult.connect(boost::bind(&SOCKS5BytestreamServerManager::handleUnforwardPortResult, this, _1));
- unforwardPortRequest->start();
- }
+ // remove port forwards
+ if (portMapping) {
+ unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort());
+ unforwardPortRequest->onResult.connect(boost::bind(&SOCKS5BytestreamServerManager::handleUnforwardPortResult, this, _1));
+ unforwardPortRequest->start();
+ }
}
void SOCKS5BytestreamServerManager::stop() {
- if (getPublicIPRequest) {
- getPublicIPRequest->stop();
- getPublicIPRequest.reset();
- }
- if (forwardPortRequest) {
- forwardPortRequest->stop();
- forwardPortRequest.reset();
- }
- if (unforwardPortRequest) {
- unforwardPortRequest->stop();
- unforwardPortRequest.reset();
- }
- if (server) {
- server->stop();
- delete server;
- server = NULL;
- }
- if (connectionServer) {
- connectionServer->stop();
- connectionServer.reset();
- }
+ if (getPublicIPRequest) {
+ getPublicIPRequest->stop();
+ getPublicIPRequest.reset();
+ }
+ if (forwardPortRequest) {
+ forwardPortRequest->stop();
+ forwardPortRequest.reset();
+ }
+ if (unforwardPortRequest) {
+ unforwardPortRequest->stop();
+ unforwardPortRequest.reset();
+ }
+ if (server) {
+ server->stop();
+ delete server;
+ server = NULL;
+ }
+ if (connectionServer) {
+ connectionServer->stop();
+ connectionServer.reset();
+ }
- state = Start;
+ state = Start;
}
void SOCKS5BytestreamServerManager::handleGetPublicIPResult(boost::optional<HostAddress> address) {
- if (address) {
- SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << "." << std::endl;
- }
- else {
- SWIFT_LOG(debug) << "No public IP discoverable." << std::endl;
- }
+ if (address) {
+ SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << "." << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "No public IP discoverable." << std::endl;
+ }
- publicAddress = address;
+ publicAddress = address;
- getPublicIPRequest->stop();
- getPublicIPRequest.reset();
+ getPublicIPRequest->stop();
+ getPublicIPRequest.reset();
}
void SOCKS5BytestreamServerManager::handleForwardPortResult(boost::optional<NATPortMapping> mapping) {
- if (mapping) {
- SWIFT_LOG(debug) << "Mapping port was successful." << std::endl;
- }
- else {
- SWIFT_LOG(debug) << "Mapping port has failed." << std::endl;
- }
+ if (mapping) {
+ SWIFT_LOG(debug) << "Mapping port was successful." << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "Mapping port has failed." << std::endl;
+ }
- portMapping = mapping;
- onPortForwardingSetup(mapping.is_initialized());
+ portMapping = mapping;
+ onPortForwardingSetup(mapping.is_initialized());
- forwardPortRequest->stop();
- forwardPortRequest.reset();
+ forwardPortRequest->stop();
+ forwardPortRequest.reset();
}
void SOCKS5BytestreamServerManager::handleUnforwardPortResult(boost::optional<bool> result) {
- if (result.is_initialized() && result.get()) {
- portMapping.reset();
- }
- else {
- SWIFT_LOG(warning) << "Failed to remove port forwarding." << std::endl;
- }
- attemptedPortMapping_ = false;
- unforwardPortRequest.reset();
+ if (result.is_initialized() && result.get()) {
+ portMapping.reset();
+ }
+ else {
+ SWIFT_LOG(warning) << "Failed to remove port forwarding." << std::endl;
+ }
+ attemptedPortMapping_ = false;
+ unforwardPortRequest.reset();
}
void SOCKS5BytestreamServerManager::checkInitializeFinished() {
- assert(state == Initializing);
- state = Initialized;
- onInitialized(true);
+ assert(state == Initializing);
+ state = Initialized;
+ onInitialized(true);
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h
index c49031b..ab12dfe 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h
@@ -17,79 +17,79 @@
#include <Swiften/Network/NATPortMapping.h>
namespace Swift {
- class NetworkEnvironment;
- class NATTraverser;
- class NATTraversalGetPublicIPRequest;
- class NATTraversalForwardPortRequest;
- class NATTraversalRemovePortForwardingRequest;
- class SOCKS5BytestreamRegistry;
- class ConnectionServerFactory;
- class ConnectionServer;
- class SOCKS5BytestreamServer;
- class SOCKS5BytestreamServerResourceUser;
- class SOCKS5BytestreamServerPortForwardingUser;
-
- class SWIFTEN_API SOCKS5BytestreamServerManager {
- friend class SOCKS5BytestreamServerResourceUser;
- friend class SOCKS5BytestreamServerPortForwardingUser;
-
- public:
- SOCKS5BytestreamServerManager(
- SOCKS5BytestreamRegistry* bytestreamRegistry,
- ConnectionServerFactory* connectionServerFactory,
- NetworkEnvironment* networkEnvironment,
- NATTraverser* natTraverser);
- ~SOCKS5BytestreamServerManager();
-
- boost::shared_ptr<SOCKS5BytestreamServerResourceUser> aquireResourceUser();
- boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> aquirePortForwardingUser();
-
- void stop();
-
- std::vector<HostAddressPort> getHostAddressPorts() const;
- std::vector<HostAddressPort> getAssistedHostAddressPorts() const;
-
- SOCKS5BytestreamServer* getServer() const {
- return server;
- }
-
- private:
- bool isInitialized() const;
- void initialize();
-
- bool isPortForwardingReady() const;
- void setupPortForwarding();
- void removePortForwarding();
-
- void checkInitializeFinished();
-
- void handleGetPublicIPResult(boost::optional<HostAddress> address);
- void handleForwardPortResult(boost::optional<NATPortMapping> mapping);
- void handleUnforwardPortResult(boost::optional<bool> result);
-
- boost::signal<void (bool /* success */)> onInitialized;
- boost::signal<void (bool /* success */)> onPortForwardingSetup;
-
- private:
- friend class SOCKS5BytestreamServerInitializeRequest;
- SOCKS5BytestreamRegistry* bytestreamRegistry;
- ConnectionServerFactory* connectionServerFactory;
- NetworkEnvironment* networkEnvironment;
- NATTraverser* natTraverser;
- enum { Start, Initializing, Initialized } state;
- SOCKS5BytestreamServer* server;
- boost::shared_ptr<ConnectionServer> connectionServer;
- int connectionServerPort;
-
- boost::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest;
- boost::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest;
- boost::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest;
- boost::optional<HostAddress> publicAddress;
- boost::optional<NATPortMapping> portMapping;
- bool attemptedPortMapping_;
-
- boost::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
- boost::weak_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_;
- };
+ class NetworkEnvironment;
+ class NATTraverser;
+ class NATTraversalGetPublicIPRequest;
+ class NATTraversalForwardPortRequest;
+ class NATTraversalRemovePortForwardingRequest;
+ class SOCKS5BytestreamRegistry;
+ class ConnectionServerFactory;
+ class ConnectionServer;
+ class SOCKS5BytestreamServer;
+ class SOCKS5BytestreamServerResourceUser;
+ class SOCKS5BytestreamServerPortForwardingUser;
+
+ class SWIFTEN_API SOCKS5BytestreamServerManager {
+ friend class SOCKS5BytestreamServerResourceUser;
+ friend class SOCKS5BytestreamServerPortForwardingUser;
+
+ public:
+ SOCKS5BytestreamServerManager(
+ SOCKS5BytestreamRegistry* bytestreamRegistry,
+ ConnectionServerFactory* connectionServerFactory,
+ NetworkEnvironment* networkEnvironment,
+ NATTraverser* natTraverser);
+ ~SOCKS5BytestreamServerManager();
+
+ boost::shared_ptr<SOCKS5BytestreamServerResourceUser> aquireResourceUser();
+ boost::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> aquirePortForwardingUser();
+
+ void stop();
+
+ std::vector<HostAddressPort> getHostAddressPorts() const;
+ std::vector<HostAddressPort> getAssistedHostAddressPorts() const;
+
+ SOCKS5BytestreamServer* getServer() const {
+ return server;
+ }
+
+ private:
+ bool isInitialized() const;
+ void initialize();
+
+ bool isPortForwardingReady() const;
+ void setupPortForwarding();
+ void removePortForwarding();
+
+ void checkInitializeFinished();
+
+ void handleGetPublicIPResult(boost::optional<HostAddress> address);
+ void handleForwardPortResult(boost::optional<NATPortMapping> mapping);
+ void handleUnforwardPortResult(boost::optional<bool> result);
+
+ boost::signal<void (bool /* success */)> onInitialized;
+ boost::signal<void (bool /* success */)> onPortForwardingSetup;
+
+ private:
+ friend class SOCKS5BytestreamServerInitializeRequest;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ ConnectionServerFactory* connectionServerFactory;
+ NetworkEnvironment* networkEnvironment;
+ NATTraverser* natTraverser;
+ enum { Start, Initializing, Initialized } state;
+ SOCKS5BytestreamServer* server;
+ boost::shared_ptr<ConnectionServer> connectionServer;
+ int connectionServerPort;
+
+ boost::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest;
+ boost::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest;
+ boost::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest;
+ boost::optional<HostAddress> publicAddress;
+ boost::optional<NATPortMapping> portMapping;
+ bool attemptedPortMapping_;
+
+ boost::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
+ boost::weak_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
index 2118782..fc7fe58 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
@@ -13,29 +13,29 @@
namespace Swift {
SOCKS5BytestreamServerPortForwardingUser::SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager) : s5bServerManager_(s5bServerManager) {
- // the server should be initialized, so we know what port to setup a forward for
- assert(s5bServerManager->isInitialized());
- if (s5bServerManager_->isPortForwardingReady()) {
- onSetup(!s5bServerManager_->getAssistedHostAddressPorts().empty());
- }
- else {
- onPortForwardingSetupConnection_ = s5bServerManager_->onPortForwardingSetup.connect(boost::bind(&SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup, this, _1));
- s5bServerManager_->setupPortForwarding();
- }
+ // the server should be initialized, so we know what port to setup a forward for
+ assert(s5bServerManager->isInitialized());
+ if (s5bServerManager_->isPortForwardingReady()) {
+ onSetup(!s5bServerManager_->getAssistedHostAddressPorts().empty());
+ }
+ else {
+ onPortForwardingSetupConnection_ = s5bServerManager_->onPortForwardingSetup.connect(boost::bind(&SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup, this, _1));
+ s5bServerManager_->setupPortForwarding();
+ }
}
SOCKS5BytestreamServerPortForwardingUser::~SOCKS5BytestreamServerPortForwardingUser() {
- if (s5bServerManager_->isPortForwardingReady()) {
- s5bServerManager_->removePortForwarding();
- }
+ if (s5bServerManager_->isPortForwardingReady()) {
+ s5bServerManager_->removePortForwarding();
+ }
}
bool SOCKS5BytestreamServerPortForwardingUser::isForwardingSetup() const {
- return s5bServerManager_->isPortForwardingReady();
+ return s5bServerManager_->isPortForwardingReady();
}
void SOCKS5BytestreamServerPortForwardingUser::handleServerManagerPortForwardingSetup(bool successful) {
- onSetup(successful);
+ onSetup(successful);
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h
index cd79ecc..5d1f59a 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h
@@ -14,20 +14,20 @@ namespace Swift {
class SOCKS5BytestreamServerManager;
class SWIFTEN_API SOCKS5BytestreamServerPortForwardingUser {
- public:
- SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager);
- ~SOCKS5BytestreamServerPortForwardingUser();
+ public:
+ SOCKS5BytestreamServerPortForwardingUser(SOCKS5BytestreamServerManager* s5bServerManager);
+ ~SOCKS5BytestreamServerPortForwardingUser();
- bool isForwardingSetup() const;
+ bool isForwardingSetup() const;
- boost::signal<void (bool /* success */)> onSetup;
+ boost::signal<void (bool /* success */)> onSetup;
- private:
- void handleServerManagerPortForwardingSetup(bool successful);
+ private:
+ void handleServerManagerPortForwardingSetup(bool successful);
- private:
- SOCKS5BytestreamServerManager* s5bServerManager_;
- boost::bsignals::scoped_connection onPortForwardingSetupConnection_;
+ private:
+ SOCKS5BytestreamServerManager* s5bServerManager_;
+ boost::bsignals::scoped_connection onPortForwardingSetupConnection_;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
index 41a728f..2fc2e76 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
@@ -13,23 +13,23 @@
namespace Swift {
SOCKS5BytestreamServerResourceUser::SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager) : s5bServerManager_(s5bServerManager) {
- assert(!s5bServerManager_->isInitialized());
- onInitializedConnection_ = s5bServerManager_->onInitialized.connect(boost::bind(&SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized, this, _1));
- s5bServerManager_->initialize();
+ assert(!s5bServerManager_->isInitialized());
+ onInitializedConnection_ = s5bServerManager_->onInitialized.connect(boost::bind(&SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized, this, _1));
+ s5bServerManager_->initialize();
}
SOCKS5BytestreamServerResourceUser::~SOCKS5BytestreamServerResourceUser() {
- if (s5bServerManager_->isInitialized()) {
- s5bServerManager_->stop();
- }
+ if (s5bServerManager_->isInitialized()) {
+ s5bServerManager_->stop();
+ }
}
bool SOCKS5BytestreamServerResourceUser::isInitialized() const {
- return s5bServerManager_->isInitialized();
+ return s5bServerManager_->isInitialized();
}
void SOCKS5BytestreamServerResourceUser::handleServerManagerInitialized(bool successfulInitialize) {
- onSuccessfulInitialized(successfulInitialize);
+ onSuccessfulInitialized(successfulInitialize);
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h
index 9e0d702..b369184 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h
@@ -14,20 +14,20 @@ namespace Swift {
class SOCKS5BytestreamServerManager;
class SWIFTEN_API SOCKS5BytestreamServerResourceUser {
- public:
- SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager);
- ~SOCKS5BytestreamServerResourceUser();
+ public:
+ SOCKS5BytestreamServerResourceUser(SOCKS5BytestreamServerManager* s5bServerManager);
+ ~SOCKS5BytestreamServerResourceUser();
- bool isInitialized() const;
+ bool isInitialized() const;
- boost::signal<void (bool /* success */)> onSuccessfulInitialized;
+ boost::signal<void (bool /* success */)> onSuccessfulInitialized;
- private:
- void handleServerManagerInitialized(bool successfulInitialize);
+ private:
+ void handleServerManagerInitialized(bool successfulInitialize);
- private:
- SOCKS5BytestreamServerManager* s5bServerManager_;
- boost::bsignals::scoped_connection onInitializedConnection_;
+ private:
+ SOCKS5BytestreamServerManager* s5bServerManager_;
+ boost::bsignals::scoped_connection onInitializedConnection_;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
index 0e1eb6b..e2d46f4 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
@@ -21,175 +21,175 @@
namespace Swift {
SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession(
- boost::shared_ptr<Connection> connection,
- SOCKS5BytestreamRegistry* bytestreams) :
- connection(connection),
- bytestreams(bytestreams),
- state(Initial),
- chunkSize(131072),
- waitingForData(false) {
- disconnectedConnection = connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1));
+ boost::shared_ptr<Connection> connection,
+ SOCKS5BytestreamRegistry* bytestreams) :
+ connection(connection),
+ bytestreams(bytestreams),
+ state(Initial),
+ chunkSize(131072),
+ waitingForData(false) {
+ disconnectedConnection = connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1));
}
SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() {
- if (state != Finished && state != Initial) {
- SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished" << std::endl;
- finish();
- }
+ if (state != Finished && state != Initial) {
+ SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished" << std::endl;
+ finish();
+ }
}
void SOCKS5BytestreamServerSession::start() {
- SWIFT_LOG(debug) << std::endl;
- dataReadConnection = connection->onDataRead.connect(
- boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
- state = WaitingForAuthentication;
+ SWIFT_LOG(debug) << std::endl;
+ dataReadConnection = connection->onDataRead.connect(
+ boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
+ state = WaitingForAuthentication;
}
void SOCKS5BytestreamServerSession::stop() {
- finish();
+ finish();
}
void SOCKS5BytestreamServerSession::startSending(boost::shared_ptr<ReadBytestream> stream) {
- if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
-
- readBytestream = stream;
- state = WritingData;
- dataAvailableConnection = readBytestream->onDataAvailable.connect(
- boost::bind(&SOCKS5BytestreamServerSession::handleDataAvailable, this));
- dataWrittenConnection = connection->onDataWritten.connect(
- boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
- sendData();
+ if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
+
+ readBytestream = stream;
+ state = WritingData;
+ dataAvailableConnection = readBytestream->onDataAvailable.connect(
+ boost::bind(&SOCKS5BytestreamServerSession::handleDataAvailable, this));
+ dataWrittenConnection = connection->onDataWritten.connect(
+ boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
+ sendData();
}
void SOCKS5BytestreamServerSession::startReceiving(boost::shared_ptr<WriteBytestream> stream) {
- if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
+ if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
- writeBytestream = stream;
- state = ReadingData;
- writeBytestream->write(unprocessedData);
- // onBytesReceived(unprocessedData.size());
- unprocessedData.clear();
+ writeBytestream = stream;
+ state = ReadingData;
+ writeBytestream->write(unprocessedData);
+ // onBytesReceived(unprocessedData.size());
+ unprocessedData.clear();
}
HostAddressPort SOCKS5BytestreamServerSession::getAddressPort() const {
- return connection->getLocalAddress();
+ return connection->getLocalAddress();
}
void SOCKS5BytestreamServerSession::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- if (state != ReadingData) {
- append(unprocessedData, *data);
- process();
- } else {
- if (!writeBytestream->write(createByteArray(vecptr(*data), data->size()))) {
- finish(boost::optional<FileTransferError>(FileTransferError::WriteError));
- }
- }
+ if (state != ReadingData) {
+ append(unprocessedData, *data);
+ process();
+ } else {
+ if (!writeBytestream->write(createByteArray(vecptr(*data), data->size()))) {
+ finish(boost::optional<FileTransferError>(FileTransferError::WriteError));
+ }
+ }
}
void SOCKS5BytestreamServerSession::handleDataAvailable() {
- if (waitingForData) {
- sendData();
- }
+ if (waitingForData) {
+ sendData();
+ }
}
void SOCKS5BytestreamServerSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
- SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
- finish(error ? boost::optional<FileTransferError>(FileTransferError::PeerError) : boost::optional<FileTransferError>());
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ finish(error ? boost::optional<FileTransferError>(FileTransferError::PeerError) : boost::optional<FileTransferError>());
}
void SOCKS5BytestreamServerSession::process() {
- if (state == WaitingForAuthentication) {
- if (unprocessedData.size() >= 2) {
- size_t authCount = unprocessedData[1];
- size_t i = 2;
- while (i < 2 + authCount && i < unprocessedData.size()) {
- // Skip authentication mechanism
- ++i;
- }
- if (i == 2 + authCount) {
- // Authentication message is complete
- if (i != unprocessedData.size()) {
- SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
- }
- unprocessedData.clear();
- connection->write(createSafeByteArray("\x05\x00", 2));
- state = WaitingForRequest;
- }
- }
- }
- else if (state == WaitingForRequest) {
- if (unprocessedData.size() >= 5) {
- ByteArray requestID;
- size_t i = 5;
- size_t hostnameSize = unprocessedData[4];
- while (i < 5 + hostnameSize && i < unprocessedData.size()) {
- requestID.push_back(unprocessedData[i]);
- ++i;
- }
- // Skip the port: 2 byte large, one already skipped. Add one for comparison with size
- i += 2;
- if (i <= unprocessedData.size()) {
- if (i != unprocessedData.size()) {
- SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
- }
- unprocessedData.clear();
- streamID = byteArrayToString(requestID);
- bool hasBytestream = bytestreams->hasBytestream(streamID);
- SafeByteArray result = createSafeByteArray("\x05", 1);
- result.push_back(hasBytestream ? 0x0 : 0x4);
- append(result, createByteArray("\x00\x03", 2));
- result.push_back(boost::numeric_cast<unsigned char>(requestID.size()));
- append(result, concat(requestID, createByteArray("\x00\x00", 2)));
- if (!hasBytestream) {
- SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl;
- connection->write(result);
- finish(boost::optional<FileTransferError>(FileTransferError::PeerError));
- }
- else {
- SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl;
- connection->write(result);
- state = ReadyForTransfer;
- }
- }
- }
- }
+ if (state == WaitingForAuthentication) {
+ if (unprocessedData.size() >= 2) {
+ size_t authCount = unprocessedData[1];
+ size_t i = 2;
+ while (i < 2 + authCount && i < unprocessedData.size()) {
+ // Skip authentication mechanism
+ ++i;
+ }
+ if (i == 2 + authCount) {
+ // Authentication message is complete
+ if (i != unprocessedData.size()) {
+ SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
+ }
+ unprocessedData.clear();
+ connection->write(createSafeByteArray("\x05\x00", 2));
+ state = WaitingForRequest;
+ }
+ }
+ }
+ else if (state == WaitingForRequest) {
+ if (unprocessedData.size() >= 5) {
+ ByteArray requestID;
+ size_t i = 5;
+ size_t hostnameSize = unprocessedData[4];
+ while (i < 5 + hostnameSize && i < unprocessedData.size()) {
+ requestID.push_back(unprocessedData[i]);
+ ++i;
+ }
+ // Skip the port: 2 byte large, one already skipped. Add one for comparison with size
+ i += 2;
+ if (i <= unprocessedData.size()) {
+ if (i != unprocessedData.size()) {
+ SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
+ }
+ unprocessedData.clear();
+ streamID = byteArrayToString(requestID);
+ bool hasBytestream = bytestreams->hasBytestream(streamID);
+ SafeByteArray result = createSafeByteArray("\x05", 1);
+ result.push_back(hasBytestream ? 0x0 : 0x4);
+ append(result, createByteArray("\x00\x03", 2));
+ result.push_back(boost::numeric_cast<unsigned char>(requestID.size()));
+ append(result, concat(requestID, createByteArray("\x00\x00", 2)));
+ if (!hasBytestream) {
+ SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl;
+ connection->write(result);
+ finish(boost::optional<FileTransferError>(FileTransferError::PeerError));
+ }
+ else {
+ SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl;
+ connection->write(result);
+ state = ReadyForTransfer;
+ }
+ }
+ }
+ }
}
void SOCKS5BytestreamServerSession::sendData() {
- if (!readBytestream->isFinished()) {
- try {
- SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize)));
- if (!dataToSend.empty()) {
- connection->write(dataToSend);
- onBytesSent(dataToSend.size());
- waitingForData = false;
- }
- else {
- waitingForData = true;
- }
- }
- catch (const BytestreamException&) {
- finish(boost::optional<FileTransferError>(FileTransferError::PeerError));
- }
- }
- else {
- finish();
- }
+ if (!readBytestream->isFinished()) {
+ try {
+ SafeByteArray dataToSend = createSafeByteArray(*readBytestream->read(boost::numeric_cast<size_t>(chunkSize)));
+ if (!dataToSend.empty()) {
+ connection->write(dataToSend);
+ onBytesSent(dataToSend.size());
+ waitingForData = false;
+ }
+ else {
+ waitingForData = true;
+ }
+ }
+ catch (const BytestreamException&) {
+ finish(boost::optional<FileTransferError>(FileTransferError::PeerError));
+ }
+ }
+ else {
+ finish();
+ }
}
void SOCKS5BytestreamServerSession::finish(const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << "state: " << state << std::endl;
- if (state == Finished) {
- return;
- }
-
- disconnectedConnection.disconnect();
- dataReadConnection.disconnect();
- dataWrittenConnection.disconnect();
- dataAvailableConnection.disconnect();
- readBytestream.reset();
- state = Finished;
- onFinished(error);
+ SWIFT_LOG(debug) << "state: " << state << std::endl;
+ if (state == Finished) {
+ return;
+ }
+
+ disconnectedConnection.disconnect();
+ dataReadConnection.disconnect();
+ dataWrittenConnection.disconnect();
+ dataAvailableConnection.disconnect();
+ readBytestream.reset();
+ state = Finished;
+ onFinished(error);
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
index ed5272f..a90e8c5 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
@@ -16,68 +16,68 @@
#include <Swiften/Network/Connection.h>
namespace Swift {
- class SOCKS5BytestreamRegistry;
-
- class SWIFTEN_API SOCKS5BytestreamServerSession {
- public:
- typedef boost::shared_ptr<SOCKS5BytestreamServerSession> ref;
-
- public:
- enum State {
- Initial,
- WaitingForAuthentication,
- WaitingForRequest,
- ReadyForTransfer,
- ReadingData,
- WritingData,
- Finished
- };
-
- SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* registry);
- ~SOCKS5BytestreamServerSession();
-
- void setChunkSize(int chunkSize) {
- this->chunkSize = chunkSize;
- }
-
- void start();
- void stop();
-
- void startSending(boost::shared_ptr<ReadBytestream>);
- void startReceiving(boost::shared_ptr<WriteBytestream>);
-
- HostAddressPort getAddressPort() const;
-
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
- boost::signal<void (unsigned long long)> onBytesSent;
-
- const std::string& getStreamID() const {
- return streamID;
- }
-
- private:
- void finish(const boost::optional<FileTransferError>& error = boost::optional<FileTransferError>());
- void process();
- void handleDataRead(boost::shared_ptr<SafeByteArray>);
- void handleDisconnected(const boost::optional<Connection::Error>&);
- void handleDataAvailable();
- void sendData();
-
- private:
- boost::shared_ptr<Connection> connection;
- SOCKS5BytestreamRegistry* bytestreams;
- ByteArray unprocessedData;
- State state;
- int chunkSize;
- std::string streamID;
- boost::shared_ptr<ReadBytestream> readBytestream;
- boost::shared_ptr<WriteBytestream> writeBytestream;
- bool waitingForData;
-
- boost::bsignals::connection disconnectedConnection;
- boost::bsignals::connection dataReadConnection;
- boost::bsignals::connection dataWrittenConnection;
- boost::bsignals::connection dataAvailableConnection;
-
- };
+ class SOCKS5BytestreamRegistry;
+
+ class SWIFTEN_API SOCKS5BytestreamServerSession {
+ public:
+ typedef boost::shared_ptr<SOCKS5BytestreamServerSession> ref;
+
+ public:
+ enum State {
+ Initial,
+ WaitingForAuthentication,
+ WaitingForRequest,
+ ReadyForTransfer,
+ ReadingData,
+ WritingData,
+ Finished
+ };
+
+ SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* registry);
+ ~SOCKS5BytestreamServerSession();
+
+ void setChunkSize(int chunkSize) {
+ this->chunkSize = chunkSize;
+ }
+
+ void start();
+ void stop();
+
+ void startSending(boost::shared_ptr<ReadBytestream>);
+ void startReceiving(boost::shared_ptr<WriteBytestream>);
+
+ HostAddressPort getAddressPort() const;
+
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signal<void (unsigned long long)> onBytesSent;
+
+ const std::string& getStreamID() const {
+ return streamID;
+ }
+
+ private:
+ void finish(const boost::optional<FileTransferError>& error = boost::optional<FileTransferError>());
+ void process();
+ void handleDataRead(boost::shared_ptr<SafeByteArray>);
+ void handleDisconnected(const boost::optional<Connection::Error>&);
+ void handleDataAvailable();
+ void sendData();
+
+ private:
+ boost::shared_ptr<Connection> connection;
+ SOCKS5BytestreamRegistry* bytestreams;
+ ByteArray unprocessedData;
+ State state;
+ int chunkSize;
+ std::string streamID;
+ boost::shared_ptr<ReadBytestream> readBytestream;
+ boost::shared_ptr<WriteBytestream> writeBytestream;
+ bool waitingForData;
+
+ boost::bsignals::connection disconnectedConnection;
+ boost::bsignals::connection dataReadConnection;
+ boost::bsignals::connection dataWrittenConnection;
+ boost::bsignals::connection dataAvailableConnection;
+
+ };
}
diff --git a/Swiften/FileTransfer/StreamInitiationRequest.h b/Swiften/FileTransfer/StreamInitiationRequest.h
index be70d72..c03fae6 100644
--- a/Swiften/FileTransfer/StreamInitiationRequest.h
+++ b/Swiften/FileTransfer/StreamInitiationRequest.h
@@ -11,23 +11,23 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API StreamInitiationRequest : public GenericRequest<StreamInitiation> {
- public:
- typedef boost::shared_ptr<StreamInitiationRequest> ref;
+ class SWIFTEN_API StreamInitiationRequest : public GenericRequest<StreamInitiation> {
+ public:
+ typedef boost::shared_ptr<StreamInitiationRequest> ref;
- static ref create(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) {
- return ref(new StreamInitiationRequest(jid, payload, router));
- }
+ static ref create(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) {
+ return ref(new StreamInitiationRequest(jid, payload, router));
+ }
- static ref create(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) {
- return ref(new StreamInitiationRequest(from, to, payload, router));
- }
+ static ref create(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) {
+ return ref(new StreamInitiationRequest(from, to, payload, router));
+ }
- private:
- StreamInitiationRequest(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, jid, payload, router) {
- }
+ private:
+ StreamInitiationRequest(const JID& jid, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, jid, payload, router) {
+ }
- StreamInitiationRequest(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, from, to, payload, router) {
- }
- };
+ StreamInitiationRequest(const JID& from, const JID& to, boost::shared_ptr<StreamInitiation> payload, IQRouter* router) : GenericRequest<StreamInitiation>(IQ::Set, from, to, payload, router) {
+ }
+ };
}
diff --git a/Swiften/FileTransfer/TransportSession.h b/Swiften/FileTransfer/TransportSession.h
index 9064c78..b42f0bd 100644
--- a/Swiften/FileTransfer/TransportSession.h
+++ b/Swiften/FileTransfer/TransportSession.h
@@ -12,14 +12,14 @@
#include <Swiften/FileTransfer/FileTransferError.h>
namespace Swift {
- class SWIFTEN_API TransportSession {
- public:
- virtual ~TransportSession();
+ class SWIFTEN_API TransportSession {
+ public:
+ virtual ~TransportSession();
- virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void start() = 0;
+ virtual void stop() = 0;
- boost::signal<void (size_t)> onBytesSent;
- boost::signal<void (boost::optional<FileTransferError>)> onFinished;
- };
+ boost::signal<void (size_t)> onBytesSent;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ };
}
diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
index d08b5c3..70d25a5 100644
--- a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
+++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
@@ -21,36 +21,36 @@
#include <Swiften/FileTransfer/FileTransferManager.h>
namespace Swift {
- class S5BProxyRequest;
- class FileTransferOptions;
-
- class DummyFileTransferManager : public FileTransferManager {
- public:
- DummyFileTransferManager() : FileTransferManager() {
- }
-
- virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID&,
- const boost::filesystem::path&,
- const std::string&,
- boost::shared_ptr<ReadBytestream>,
- const FileTransferOptions&) SWIFTEN_OVERRIDE {
- return OutgoingFileTransfer::ref();
- }
-
- virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
- const JID&,
- const std::string&,
- const std::string&,
- const boost::uintmax_t,
- const boost::posix_time::ptime&,
- boost::shared_ptr<ReadBytestream>,
- const FileTransferOptions&) SWIFTEN_OVERRIDE {
- return OutgoingFileTransfer::ref();
- }
-
- virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest>) {
- }
-
- };
+ class S5BProxyRequest;
+ class FileTransferOptions;
+
+ class DummyFileTransferManager : public FileTransferManager {
+ public:
+ DummyFileTransferManager() : FileTransferManager() {
+ }
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID&,
+ const boost::filesystem::path&,
+ const std::string&,
+ boost::shared_ptr<ReadBytestream>,
+ const FileTransferOptions&) SWIFTEN_OVERRIDE {
+ return OutgoingFileTransfer::ref();
+ }
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(
+ const JID&,
+ const std::string&,
+ const std::string&,
+ const boost::uintmax_t,
+ const boost::posix_time::ptime&,
+ boost::shared_ptr<ReadBytestream>,
+ const FileTransferOptions&) SWIFTEN_OVERRIDE {
+ return OutgoingFileTransfer::ref();
+ }
+
+ virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest>) {
+ }
+
+ };
}
diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h
index 00a931f..59fc40a 100644
--- a/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h
+++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h
@@ -28,175 +28,175 @@ namespace Swift {
class DummyFileTransferTransporter : public FileTransferTransporter {
public:
- enum Role {
- Initiator,
- Responder
- };
+ enum Role {
+ Initiator,
+ Responder
+ };
public:
- DummyFileTransferTransporter(
- const JID& initiator,
- const JID& responder,
- Role role,
- SOCKS5BytestreamRegistry* s5bRegistry,
- SOCKS5BytestreamServerManager* /* s5bServerManager */,
- SOCKS5BytestreamProxiesManager* /* s5bProxy */,
- IDGenerator* /* idGenerator */,
- ConnectionFactory*,
- TimerFactory*,
- CryptoProvider* cryptoProvider,
- IQRouter* iqRouter,
- const FileTransferOptions& ftOptions) : initiator_(initiator), responder_(responder), role_(role), s5bRegistry_(s5bRegistry), crypto_(cryptoProvider), iqRouter_(iqRouter), ftOptions_(ftOptions) {
-
- }
-
- void initialize() {
- s5bSessionID_ = s5bRegistry_->generateSessionID();
- }
-
- virtual void startGeneratingLocalCandidates() {
- std::vector<JingleS5BTransportPayload::Candidate> candidates;
- if (ftOptions_.isDirectAllowed()) {
- JingleS5BTransportPayload::Candidate candidate;
- candidate.cid = "123";
- candidate.priority = 1235;
- candidates.push_back(candidate);
- }
- onLocalCandidatesGenerated(s5bSessionID_, candidates, getSOCKS5DstAddr());
- }
-
- virtual void stopGeneratingLocalCandidates() {
- }
-
- virtual void addRemoteCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) {
- }
-
- virtual void startTryingRemoteCandidates() {
- onRemoteCandidateSelectFinished(s5bSessionID_, boost::optional<JingleS5BTransportPayload::Candidate>());
- }
-
- virtual void stopTryingRemoteCandidates() {
- }
-
- virtual void startActivatingProxy(const JID& /* proxy */) {
- }
-
- virtual void stopActivatingProxy() {
- }
-
- virtual boost::shared_ptr<TransportSession> createIBBSendSession(const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) {
- boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>(
- sessionID, initiator_, responder_, stream, iqRouter_);
- ibbSession->setBlockSize(blockSize);
- return boost::make_shared<IBBSendTransportSession>(ibbSession);
- }
-
- virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) {
- boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>(
- sessionID, initiator_, responder_, size, stream, iqRouter_);
- return boost::make_shared<IBBReceiveTransportSession>(ibbSession);
- }
-
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- return boost::shared_ptr<TransportSession>();
- }
-
- virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- return boost::shared_ptr<TransportSession>();
- }
-
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- return boost::shared_ptr<TransportSession>();
- }
-
- virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
- boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
- return boost::shared_ptr<TransportSession>();
- }
+ DummyFileTransferTransporter(
+ const JID& initiator,
+ const JID& responder,
+ Role role,
+ SOCKS5BytestreamRegistry* s5bRegistry,
+ SOCKS5BytestreamServerManager* /* s5bServerManager */,
+ SOCKS5BytestreamProxiesManager* /* s5bProxy */,
+ IDGenerator* /* idGenerator */,
+ ConnectionFactory*,
+ TimerFactory*,
+ CryptoProvider* cryptoProvider,
+ IQRouter* iqRouter,
+ const FileTransferOptions& ftOptions) : initiator_(initiator), responder_(responder), role_(role), s5bRegistry_(s5bRegistry), crypto_(cryptoProvider), iqRouter_(iqRouter), ftOptions_(ftOptions) {
+
+ }
+
+ void initialize() {
+ s5bSessionID_ = s5bRegistry_->generateSessionID();
+ }
+
+ virtual void startGeneratingLocalCandidates() {
+ std::vector<JingleS5BTransportPayload::Candidate> candidates;
+ if (ftOptions_.isDirectAllowed()) {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.cid = "123";
+ candidate.priority = 1235;
+ candidates.push_back(candidate);
+ }
+ onLocalCandidatesGenerated(s5bSessionID_, candidates, getSOCKS5DstAddr());
+ }
+
+ virtual void stopGeneratingLocalCandidates() {
+ }
+
+ virtual void addRemoteCandidates(const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) {
+ }
+
+ virtual void startTryingRemoteCandidates() {
+ onRemoteCandidateSelectFinished(s5bSessionID_, boost::optional<JingleS5BTransportPayload::Candidate>());
+ }
+
+ virtual void stopTryingRemoteCandidates() {
+ }
+
+ virtual void startActivatingProxy(const JID& /* proxy */) {
+ }
+
+ virtual void stopActivatingProxy() {
+ }
+
+ virtual boost::shared_ptr<TransportSession> createIBBSendSession(const std::string& sessionID, unsigned int blockSize, boost::shared_ptr<ReadBytestream> stream) {
+ boost::shared_ptr<IBBSendSession> ibbSession = boost::make_shared<IBBSendSession>(
+ sessionID, initiator_, responder_, stream, iqRouter_);
+ ibbSession->setBlockSize(blockSize);
+ return boost::make_shared<IBBSendTransportSession>(ibbSession);
+ }
+
+ virtual boost::shared_ptr<TransportSession> createIBBReceiveSession(const std::string& sessionID, unsigned long long size, boost::shared_ptr<WriteBytestream> stream) {
+ boost::shared_ptr<IBBReceiveSession> ibbSession = boost::make_shared<IBBReceiveSession>(
+ sessionID, initiator_, responder_, size, stream, iqRouter_);
+ return boost::make_shared<IBBReceiveTransportSession>(ibbSession);
+ }
+
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return boost::shared_ptr<TransportSession>();
+ }
+
+ virtual boost::shared_ptr<TransportSession> createRemoteCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return boost::shared_ptr<TransportSession>();
+ }
+
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return boost::shared_ptr<TransportSession>();
+ }
+
+ virtual boost::shared_ptr<TransportSession> createLocalCandidateSession(
+ boost::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return boost::shared_ptr<TransportSession>();
+ }
private:
- std::string getSOCKS5DstAddr() const {
- std::string result;
- if (role_ == Initiator) {
- result = getInitiatorCandidateSOCKS5DstAddr();
- }
- else {
- result = getResponderCandidateSOCKS5DstAddr();
- }
- return result;
- }
-
- std::string getInitiatorCandidateSOCKS5DstAddr() const {
- return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + initiator_.toString() + responder_.toString())));
- }
-
- std::string getResponderCandidateSOCKS5DstAddr() const {
- return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + responder_.toString() + initiator_.toString())));
- }
+ std::string getSOCKS5DstAddr() const {
+ std::string result;
+ if (role_ == Initiator) {
+ result = getInitiatorCandidateSOCKS5DstAddr();
+ }
+ else {
+ result = getResponderCandidateSOCKS5DstAddr();
+ }
+ return result;
+ }
+
+ std::string getInitiatorCandidateSOCKS5DstAddr() const {
+ return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + initiator_.toString() + responder_.toString())));
+ }
+
+ std::string getResponderCandidateSOCKS5DstAddr() const {
+ return Hexify::hexify(crypto_->getSHA1Hash(createSafeByteArray(s5bSessionID_ + responder_.toString() + initiator_.toString())));
+ }
private:
- JID initiator_;
- JID responder_;
- Role role_;
- SOCKS5BytestreamRegistry* s5bRegistry_;
- CryptoProvider* crypto_;
- std::string s5bSessionID_;
- IQRouter* iqRouter_;
- FileTransferOptions ftOptions_;
+ JID initiator_;
+ JID responder_;
+ Role role_;
+ SOCKS5BytestreamRegistry* s5bRegistry_;
+ CryptoProvider* crypto_;
+ std::string s5bSessionID_;
+ IQRouter* iqRouter_;
+ FileTransferOptions ftOptions_;
};
class DummyFileTransferTransporterFactory : public FileTransferTransporterFactory {
public:
- DummyFileTransferTransporterFactory(
- SOCKS5BytestreamRegistry* s5bRegistry,
- SOCKS5BytestreamServerManager* s5bServerManager,
- SOCKS5BytestreamProxiesManager* s5bProxy,
- IDGenerator* idGenerator,
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- CryptoProvider* cryptoProvider,
- IQRouter* iqRouter) : s5bRegistry_(s5bRegistry), s5bServerManager_(s5bServerManager), s5bProxy_(s5bProxy), idGenerator_(idGenerator), connectionFactory_(connectionFactory), timerFactory_(timerFactory), cryptoProvider_(cryptoProvider), iqRouter_(iqRouter) {
-
- }
-
- virtual ~DummyFileTransferTransporterFactory() {
- }
-
- virtual FileTransferTransporter* createInitiatorTransporter(const JID& initiator, const JID& responder, const FileTransferOptions& options) {
- DummyFileTransferTransporter* transporter = new DummyFileTransferTransporter(
- initiator,
- responder,
- DummyFileTransferTransporter::Initiator,
- s5bRegistry_,
- s5bServerManager_,
- s5bProxy_,
- idGenerator_,
- connectionFactory_,
- timerFactory_,
- cryptoProvider_,
- iqRouter_,
- options);
- transporter->initialize();
- return transporter;
- }
-
- virtual FileTransferTransporter* createResponderTransporter(const JID& /* initiator */, const JID& /* responder */, const std::string& /* s5bSessionID */, const FileTransferOptions& /* options */) {
- return NULL;
- }
+ DummyFileTransferTransporterFactory(
+ SOCKS5BytestreamRegistry* s5bRegistry,
+ SOCKS5BytestreamServerManager* s5bServerManager,
+ SOCKS5BytestreamProxiesManager* s5bProxy,
+ IDGenerator* idGenerator,
+ ConnectionFactory* connectionFactory,
+ TimerFactory* timerFactory,
+ CryptoProvider* cryptoProvider,
+ IQRouter* iqRouter) : s5bRegistry_(s5bRegistry), s5bServerManager_(s5bServerManager), s5bProxy_(s5bProxy), idGenerator_(idGenerator), connectionFactory_(connectionFactory), timerFactory_(timerFactory), cryptoProvider_(cryptoProvider), iqRouter_(iqRouter) {
+
+ }
+
+ virtual ~DummyFileTransferTransporterFactory() {
+ }
+
+ virtual FileTransferTransporter* createInitiatorTransporter(const JID& initiator, const JID& responder, const FileTransferOptions& options) {
+ DummyFileTransferTransporter* transporter = new DummyFileTransferTransporter(
+ initiator,
+ responder,
+ DummyFileTransferTransporter::Initiator,
+ s5bRegistry_,
+ s5bServerManager_,
+ s5bProxy_,
+ idGenerator_,
+ connectionFactory_,
+ timerFactory_,
+ cryptoProvider_,
+ iqRouter_,
+ options);
+ transporter->initialize();
+ return transporter;
+ }
+
+ virtual FileTransferTransporter* createResponderTransporter(const JID& /* initiator */, const JID& /* responder */, const std::string& /* s5bSessionID */, const FileTransferOptions& /* options */) {
+ return NULL;
+ }
private:
- SOCKS5BytestreamRegistry* s5bRegistry_;
- SOCKS5BytestreamServerManager* s5bServerManager_;
- SOCKS5BytestreamProxiesManager* s5bProxy_;
- IDGenerator* idGenerator_;
- ConnectionFactory* connectionFactory_;
- TimerFactory* timerFactory_;
- CryptoProvider* cryptoProvider_;
- IQRouter* iqRouter_;
+ SOCKS5BytestreamRegistry* s5bRegistry_;
+ SOCKS5BytestreamServerManager* s5bServerManager_;
+ SOCKS5BytestreamProxiesManager* s5bProxy_;
+ IDGenerator* idGenerator_;
+ ConnectionFactory* connectionFactory_;
+ TimerFactory* timerFactory_;
+ CryptoProvider* cryptoProvider_;
+ IQRouter* iqRouter_;
};
}
diff --git a/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp
index 2678758..d78f4f0 100644
--- a/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp
@@ -22,166 +22,166 @@
using namespace Swift;
class IBBReceiveSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IBBReceiveSessionTest);
- CPPUNIT_TEST(testOpen);
- CPPUNIT_TEST(testReceiveData);
- CPPUNIT_TEST(testReceiveMultipleData);
- CPPUNIT_TEST(testReceiveDataForOtherSession);
- CPPUNIT_TEST(testReceiveDataOutOfOrder);
- CPPUNIT_TEST(testReceiveLastData);
- CPPUNIT_TEST(testReceiveClose);
- CPPUNIT_TEST(testStopWhileActive);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- stanzaChannel = new DummyStanzaChannel();
- iqRouter = new IQRouter(stanzaChannel);
- finished = false;
- bytestream = boost::make_shared<ByteArrayWriteBytestream>();
- }
+ CPPUNIT_TEST_SUITE(IBBReceiveSessionTest);
+ CPPUNIT_TEST(testOpen);
+ CPPUNIT_TEST(testReceiveData);
+ CPPUNIT_TEST(testReceiveMultipleData);
+ CPPUNIT_TEST(testReceiveDataForOtherSession);
+ CPPUNIT_TEST(testReceiveDataOutOfOrder);
+ CPPUNIT_TEST(testReceiveLastData);
+ CPPUNIT_TEST(testReceiveClose);
+ CPPUNIT_TEST(testStopWhileActive);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ finished = false;
+ bytestream = boost::make_shared<ByteArrayWriteBytestream>();
+ }
- void tearDown() {
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testOpen() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ void tearDown() {
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testOpen() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
- CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(0, "id-open"));
- CPPUNIT_ASSERT(!finished);
-
- testling->stop();
- }
+ CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(0, "id-open"));
+ CPPUNIT_ASSERT(!finished);
+
+ testling->stop();
+ }
- void testReceiveData() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
-
- CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(1, "id-a"));
- CPPUNIT_ASSERT(createByteArray("abc") == bytestream->getData());
- CPPUNIT_ASSERT(!finished);
-
- testling->stop();
- }
-
- void testReceiveMultipleData() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b"));
-
- CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b"));
- CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData());
- CPPUNIT_ASSERT(!finished);
-
- testling->stop();
- }
-
- void testReceiveDataForOtherSession() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("othersession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
-
- CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(1, "id-a"));
-
- testling->stop();
- }
-
- void testReceiveDataOutOfOrder() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("def")), "foo@bar.com/baz", "id-b"));
-
- CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(2, "id-b"));
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(error);
-
- testling->stop();
- }
-
- void testReceiveLastData() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession", 6));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b"));
-
- CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b"));
- CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData());
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(!error);
-
- testling->stop();
- }
-
- void testReceiveClose() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
-
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBClose("mysession"), "foo@bar.com/baz", "id-close"));
+ void testReceiveData() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+
+ CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(1, "id-a"));
+ CPPUNIT_ASSERT(createByteArray("abc") == bytestream->getData());
+ CPPUNIT_ASSERT(!finished);
+
+ testling->stop();
+ }
+
+ void testReceiveMultipleData() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b"));
+
+ CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b"));
+ CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData());
+ CPPUNIT_ASSERT(!finished);
+
+ testling->stop();
+ }
+
+ void testReceiveDataForOtherSession() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("othersession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+
+ CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(1, "id-a"));
+
+ testling->stop();
+ }
+
+ void testReceiveDataOutOfOrder() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("def")), "foo@bar.com/baz", "id-b"));
+
+ CPPUNIT_ASSERT(stanzaChannel->isErrorAtIndex(2, "id-b"));
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(error);
+
+ testling->stop();
+ }
+
+ void testReceiveLastData() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession", 6));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 1, createByteArray("def")), "foo@bar.com/baz", "id-b"));
+
+ CPPUNIT_ASSERT(stanzaChannel->isResultAtIndex(2, "id-b"));
+ CPPUNIT_ASSERT(createByteArray("abcdef") == bytestream->getData());
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(!error);
+
+ testling->stop();
+ }
+
+ void testReceiveClose() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBClose("mysession"), "foo@bar.com/baz", "id-close"));
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(error);
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(error);
- testling->stop();
- }
+ testling->stop();
+ }
- void testStopWhileActive() {
- boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
- testling->start();
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ void testStopWhileActive() {
+ boost::shared_ptr<IBBReceiveSession> testling(createSession("foo@bar.com/baz", "mysession"));
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
- testling->stop();
+ testling->stop();
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
- IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
- CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction());
- CPPUNIT_ASSERT_EQUAL(std::string("mysession"), ibb->getStreamID());
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(!error);
- }
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
+ IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
+ CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("mysession"), ibb->getStreamID());
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(!error);
+ }
- private:
- IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
- IQ::ref request = IQ::createRequest(IQ::Set, JID("baz@fum.com/dum"), id, ibb);
- request->setFrom(from);
- return request;
- }
+ private:
+ IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
+ IQ::ref request = IQ::createRequest(IQ::Set, JID("baz@fum.com/dum"), id, ibb);
+ request->setFrom(from);
+ return request;
+ }
- IBBReceiveSession* createSession(const std::string& from, const std::string& id, size_t size = 0x1000) {
- IBBReceiveSession* session = new IBBReceiveSession(id, JID(from), JID(), size, bytestream, iqRouter);
- session->onFinished.connect(boost::bind(&IBBReceiveSessionTest::handleFinished, this, _1));
- return session;
- }
+ IBBReceiveSession* createSession(const std::string& from, const std::string& id, size_t size = 0x1000) {
+ IBBReceiveSession* session = new IBBReceiveSession(id, JID(from), JID(), size, bytestream, iqRouter);
+ session->onFinished.connect(boost::bind(&IBBReceiveSessionTest::handleFinished, this, _1));
+ return session;
+ }
- void handleFinished(boost::optional<FileTransferError> error) {
- finished = true;
- this->error = error;
- }
+ void handleFinished(boost::optional<FileTransferError> error) {
+ finished = true;
+ this->error = error;
+ }
- private:
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- bool finished;
- boost::optional<FileTransferError> error;
- boost::shared_ptr<ByteArrayWriteBytestream> bytestream;
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ bool finished;
+ boost::optional<FileTransferError> error;
+ boost::shared_ptr<ByteArrayWriteBytestream> bytestream;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IBBReceiveSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
index a1c9c4c..e417c77 100644
--- a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
@@ -20,213 +20,213 @@
using namespace Swift;
class IBBSendSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IBBSendSessionTest);
- CPPUNIT_TEST(testStart);
- CPPUNIT_TEST(testStart_ResponseStartsSending);
- CPPUNIT_TEST(testResponseContinuesSending);
- CPPUNIT_TEST(testRespondToAllFinishes);
- CPPUNIT_TEST(testErrorResponseFinishesWithError);
- CPPUNIT_TEST(testStopDuringSessionCloses);
- CPPUNIT_TEST(testStopAfterFinishedDoesNotClose);
- CPPUNIT_TEST(testDataStreamPauseStopsSendingData);
- CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData);
- CPPUNIT_TEST(testDataStreamResumeBeforePauseDoesNotSendData);
- CPPUNIT_TEST(testDataStreamResumeAfterResumeDoesNotSendData);
-
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- stanzaChannel = new DummyStanzaChannel();
- iqRouter = new IQRouter(stanzaChannel);
- bytestream = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
- finished = false;
- }
-
- void tearDown() {
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testStart() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(1234);
-
- testling->start();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set));
- IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>();
- CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction());
- CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
- }
-
- void testStart_ResponseStartsSending() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(3);
- testling->start();
-
- stanzaChannel->onIQReceived(createIBBResult());
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
- IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
- CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction());
- CPPUNIT_ASSERT(createByteArray("abc") == ibb->getData());
- CPPUNIT_ASSERT_EQUAL(0, ibb->getSequenceNumber());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
- }
-
- void testResponseContinuesSending() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
-
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(2, JID("foo@bar.com/baz"), IQ::Set));
- IBB::ref ibb = stanzaChannel->sentStanzas[2]->getPayload<IBB>();
- CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction());
- CPPUNIT_ASSERT(createByteArray("def") == ibb->getData());
- CPPUNIT_ASSERT_EQUAL(1, ibb->getSequenceNumber());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
- }
-
- void testRespondToAllFinishes() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
-
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(!error);
- }
-
- void testErrorResponseFinishesWithError() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
-
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(error);
- }
-
- void testStopDuringSessionCloses() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(3);
- testling->start();
- testling->stop();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
- IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
- CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
- CPPUNIT_ASSERT(finished);
- CPPUNIT_ASSERT(!error);
- }
-
- void testStopAfterFinishedDoesNotClose() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- testling->setBlockSize(16);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- CPPUNIT_ASSERT(finished);
-
- testling->stop();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testDataStreamPauseStopsSendingData() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- bytestream->setDataComplete(false);
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
-
- CPPUNIT_ASSERT(!finished);
- CPPUNIT_ASSERT(!error);
-
- CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testDataStreamResumeAfterPauseSendsData() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- bytestream->setDataComplete(false);
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
-
- bytestream->addData(createByteArray("xyz"));
-
- CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testDataStreamResumeBeforePauseDoesNotSendData() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- bytestream->setDataComplete(false);
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
-
- bytestream->addData(createByteArray("xyz"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testDataStreamResumeAfterResumeDoesNotSendData() {
- boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
- bytestream->setDataComplete(false);
- testling->setBlockSize(3);
- testling->start();
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
- stanzaChannel->onIQReceived(createIBBResult());
-
- bytestream->addData(createByteArray("xyz"));
- bytestream->addData(createByteArray("xuv"));
-
- CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- private:
- IQ::ref createIBBResult() {
- return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getTo(), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getID(), boost::shared_ptr<IBB>());
- }
-
- private:
- boost::shared_ptr<IBBSendSession> createSession(const std::string& to) {
- boost::shared_ptr<IBBSendSession> session(new IBBSendSession("myid", JID(), JID(to), bytestream, iqRouter));
- session->onFinished.connect(boost::bind(&IBBSendSessionTest::handleFinished, this, _1));
- return session;
- }
-
- void handleFinished(boost::optional<FileTransferError> error) {
- finished = true;
- this->error = error;
- }
-
- private:
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- bool finished;
- boost::optional<FileTransferError> error;
- boost::shared_ptr<ByteArrayReadBytestream> bytestream;
+ CPPUNIT_TEST_SUITE(IBBSendSessionTest);
+ CPPUNIT_TEST(testStart);
+ CPPUNIT_TEST(testStart_ResponseStartsSending);
+ CPPUNIT_TEST(testResponseContinuesSending);
+ CPPUNIT_TEST(testRespondToAllFinishes);
+ CPPUNIT_TEST(testErrorResponseFinishesWithError);
+ CPPUNIT_TEST(testStopDuringSessionCloses);
+ CPPUNIT_TEST(testStopAfterFinishedDoesNotClose);
+ CPPUNIT_TEST(testDataStreamPauseStopsSendingData);
+ CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData);
+ CPPUNIT_TEST(testDataStreamResumeBeforePauseDoesNotSendData);
+ CPPUNIT_TEST(testDataStreamResumeAfterResumeDoesNotSendData);
+
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ bytestream = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
+ finished = false;
+ }
+
+ void tearDown() {
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testStart() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(1234);
+
+ testling->start();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set));
+ IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>();
+ CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction());
+ CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
+ }
+
+ void testStart_ResponseStartsSending() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(3);
+ testling->start();
+
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
+ IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
+ CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction());
+ CPPUNIT_ASSERT(createByteArray("abc") == ibb->getData());
+ CPPUNIT_ASSERT_EQUAL(0, ibb->getSequenceNumber());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
+ }
+
+ void testResponseContinuesSending() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(2, JID("foo@bar.com/baz"), IQ::Set));
+ IBB::ref ibb = stanzaChannel->sentStanzas[2]->getPayload<IBB>();
+ CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction());
+ CPPUNIT_ASSERT(createByteArray("def") == ibb->getData());
+ CPPUNIT_ASSERT_EQUAL(1, ibb->getSequenceNumber());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
+ }
+
+ void testRespondToAllFinishes() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(!error);
+ }
+
+ void testErrorResponseFinishesWithError() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(error);
+ }
+
+ void testStopDuringSessionCloses() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(3);
+ testling->start();
+ testling->stop();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
+ IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
+ CPPUNIT_ASSERT_EQUAL(IBB::Close, ibb->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
+ CPPUNIT_ASSERT(finished);
+ CPPUNIT_ASSERT(!error);
+ }
+
+ void testStopAfterFinishedDoesNotClose() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ testling->setBlockSize(16);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ CPPUNIT_ASSERT(finished);
+
+ testling->stop();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testDataStreamPauseStopsSendingData() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ bytestream->setDataComplete(false);
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ CPPUNIT_ASSERT(!finished);
+ CPPUNIT_ASSERT(!error);
+
+ CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testDataStreamResumeAfterPauseSendsData() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ bytestream->setDataComplete(false);
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ bytestream->addData(createByteArray("xyz"));
+
+ CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testDataStreamResumeBeforePauseDoesNotSendData() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ bytestream->setDataComplete(false);
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ bytestream->addData(createByteArray("xyz"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testDataStreamResumeAfterResumeDoesNotSendData() {
+ boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
+ bytestream->setDataComplete(false);
+ testling->setBlockSize(3);
+ testling->start();
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+ stanzaChannel->onIQReceived(createIBBResult());
+
+ bytestream->addData(createByteArray("xyz"));
+ bytestream->addData(createByteArray("xuv"));
+
+ CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ private:
+ IQ::ref createIBBResult() {
+ return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getTo(), stanzaChannel->sentStanzas[stanzaChannel->sentStanzas.size()-1]->getID(), boost::shared_ptr<IBB>());
+ }
+
+ private:
+ boost::shared_ptr<IBBSendSession> createSession(const std::string& to) {
+ boost::shared_ptr<IBBSendSession> session(new IBBSendSession("myid", JID(), JID(to), bytestream, iqRouter));
+ session->onFinished.connect(boost::bind(&IBBSendSessionTest::handleFinished, this, _1));
+ return session;
+ }
+
+ void handleFinished(boost::optional<FileTransferError> error) {
+ finished = true;
+ this->error = error;
+ }
+
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ bool finished;
+ boost::optional<FileTransferError> error;
+ boost::shared_ptr<ByteArrayReadBytestream> bytestream;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IBBSendSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
index 2fb39bb..a76773c 100644
--- a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
@@ -48,198 +48,198 @@ using namespace Swift;
using namespace boost;
class IncomingJingleFileTransferTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IncomingJingleFileTransferTest);
- CPPUNIT_TEST(test_AcceptOnyIBBSendsSessionAccept);
- CPPUNIT_TEST(test_OnlyIBBTransferReceiveWorks);
- //CPPUNIT_TEST(test_AcceptFailingS5BFallsBackToIBB);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IncomingJingleFileTransferTest);
+ CPPUNIT_TEST(test_AcceptOnyIBBSendsSessionAccept);
+ CPPUNIT_TEST(test_OnlyIBBTransferReceiveWorks);
+ //CPPUNIT_TEST(test_AcceptFailingS5BFallsBackToIBB);
+ CPPUNIT_TEST_SUITE_END();
public:
- shared_ptr<IncomingJingleFileTransfer> createTestling() {
- JID ourJID("our@jid.org/full");
- return boost::make_shared<IncomingJingleFileTransfer>(ourJID, shared_ptr<JingleSession>(session), jingleContentPayload, ftTransporterFactory, timerFactory, crypto.get());
- }
-
- IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
- IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
- request->setFrom(from);
- return request;
- }
-
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- eventLoop = new DummyEventLoop();
- resolver = new StaticDomainNameResolver(eventLoop);
- session = boost::make_shared<FakeJingleSession>("foo@bar.com/baz", "mysession");
- jingleContentPayload = make_shared<JingleContentPayload>();
- // fakeRJTCSF = make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>();
- // fakeLJTCF = make_shared<FakeLocalJingleTransportCandidateGeneratorFactory>();
- stanzaChannel = new DummyStanzaChannel();
- connectionFactory = new DummyConnectionFactory(eventLoop);
- serverConnectionFactory = new DummyConnectionServerFactory(eventLoop);
- iqRouter = new IQRouter(stanzaChannel);
- bytestreamRegistry = new SOCKS5BytestreamRegistry();
- networkEnvironment = new PlatformNetworkEnvironment();
- natTraverser = new PlatformNATTraversalWorker(eventLoop);
- bytestreamServerManager = new SOCKS5BytestreamServerManager(bytestreamRegistry, serverConnectionFactory, networkEnvironment, natTraverser);
- idGenerator = new SimpleIDGenerator();
- timerFactory = new DummyTimerFactory();
- bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com");
- ftTransporterFactory = new DefaultFileTransferTransporterFactory(bytestreamRegistry, bytestreamServerManager, bytestreamProxy, idGenerator, connectionFactory, timerFactory, crypto.get(), iqRouter);
- }
-
- void tearDown() {
- delete ftTransporterFactory;
- delete bytestreamProxy;
- delete timerFactory;
- delete idGenerator;
- delete bytestreamServerManager;
- delete natTraverser;
- delete networkEnvironment;
- delete bytestreamRegistry;
- delete iqRouter;
- delete serverConnectionFactory;
- delete connectionFactory;
- delete stanzaChannel;
- delete resolver;
- delete eventLoop;
- Log::setLogLevel(Log::error);
- }
-
- // Tests whether IncomingJingleFileTransfer would accept a IBB only file transfer.
- void test_AcceptOnyIBBSendsSessionAccept() {
- //1. create your test incoming file transfer
- shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
- desc->setFileInfo(JingleFileTransferFileInfo("foo.txt", "", 10));
- jingleContentPayload->addDescription(desc);
- JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
- tpRef->setSessionID("mysession");
- jingleContentPayload->addTransport(tpRef);
-
- shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
-
- //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
- shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
- fileTransfer->accept(byteStream);
-
- // check whether accept has been called
- getCall<FakeJingleSession::AcceptCall>(0);
- }
-
- void test_OnlyIBBTransferReceiveWorks() {
- //1. create your test incoming file transfer
- shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
- desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
- jingleContentPayload->addDescription(desc);
- JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
- tpRef->setSessionID("mysession");
- jingleContentPayload->addTransport(tpRef);
-
- shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
-
- //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
- shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
- fileTransfer->accept(byteStream);
-
- // check whether accept has been called
- getCall<FakeJingleSession::AcceptCall>(0);
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
- CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
- }
-
- void test_AcceptFailingS5BFallsBackToIBB() {
- //1. create your test incoming file transfer
- addFileTransferDescription();
-
- // add SOCKS5BytestreamTransportPayload
- JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
-
- shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
-
- //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
- shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
- fileTransfer->accept(byteStream);
-
- // candidates are gathered
-
- // check whether accept has been called
- FakeJingleSession::AcceptCall acceptCall = getCall<FakeJingleSession::AcceptCall>(0);
- CPPUNIT_ASSERT_EQUAL(payLoad->getSessionID(), acceptCall.payload->getSessionID());
-
- // check for candidate error
- FakeJingleSession::InfoTransportCall infoTransportCall = getCall<FakeJingleSession::InfoTransportCall>(1);
- JingleS5BTransportPayload::ref s5bPayload = dynamic_pointer_cast<JingleS5BTransportPayload>(infoTransportCall.payload);
- CPPUNIT_ASSERT(s5bPayload->hasCandidateError());
-
- // indicate transport replace (Romeo)
- session->handleTransportReplaceReceived(getContentID(), addJingleIBBPayload());
-
- FakeJingleSession::AcceptTransportCall acceptTransportCall = getCall<FakeJingleSession::AcceptTransportCall>(2);
-
- // send a bit of data
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
- stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
- CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
- }
+ shared_ptr<IncomingJingleFileTransfer> createTestling() {
+ JID ourJID("our@jid.org/full");
+ return boost::make_shared<IncomingJingleFileTransfer>(ourJID, shared_ptr<JingleSession>(session), jingleContentPayload, ftTransporterFactory, timerFactory, crypto.get());
+ }
+
+ IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
+ IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
+ request->setFrom(from);
+ return request;
+ }
+
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ session = boost::make_shared<FakeJingleSession>("foo@bar.com/baz", "mysession");
+ jingleContentPayload = make_shared<JingleContentPayload>();
+ // fakeRJTCSF = make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>();
+ // fakeLJTCF = make_shared<FakeLocalJingleTransportCandidateGeneratorFactory>();
+ stanzaChannel = new DummyStanzaChannel();
+ connectionFactory = new DummyConnectionFactory(eventLoop);
+ serverConnectionFactory = new DummyConnectionServerFactory(eventLoop);
+ iqRouter = new IQRouter(stanzaChannel);
+ bytestreamRegistry = new SOCKS5BytestreamRegistry();
+ networkEnvironment = new PlatformNetworkEnvironment();
+ natTraverser = new PlatformNATTraversalWorker(eventLoop);
+ bytestreamServerManager = new SOCKS5BytestreamServerManager(bytestreamRegistry, serverConnectionFactory, networkEnvironment, natTraverser);
+ idGenerator = new SimpleIDGenerator();
+ timerFactory = new DummyTimerFactory();
+ bytestreamProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com");
+ ftTransporterFactory = new DefaultFileTransferTransporterFactory(bytestreamRegistry, bytestreamServerManager, bytestreamProxy, idGenerator, connectionFactory, timerFactory, crypto.get(), iqRouter);
+ }
+
+ void tearDown() {
+ delete ftTransporterFactory;
+ delete bytestreamProxy;
+ delete timerFactory;
+ delete idGenerator;
+ delete bytestreamServerManager;
+ delete natTraverser;
+ delete networkEnvironment;
+ delete bytestreamRegistry;
+ delete iqRouter;
+ delete serverConnectionFactory;
+ delete connectionFactory;
+ delete stanzaChannel;
+ delete resolver;
+ delete eventLoop;
+ Log::setLogLevel(Log::error);
+ }
+
+ // Tests whether IncomingJingleFileTransfer would accept a IBB only file transfer.
+ void test_AcceptOnyIBBSendsSessionAccept() {
+ //1. create your test incoming file transfer
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("foo.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // check whether accept has been called
+ getCall<FakeJingleSession::AcceptCall>(0);
+ }
+
+ void test_OnlyIBBTransferReceiveWorks() {
+ //1. create your test incoming file transfer
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // check whether accept has been called
+ getCall<FakeJingleSession::AcceptCall>(0);
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
+ }
+
+ void test_AcceptFailingS5BFallsBackToIBB() {
+ //1. create your test incoming file transfer
+ addFileTransferDescription();
+
+ // add SOCKS5BytestreamTransportPayload
+ JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // candidates are gathered
+
+ // check whether accept has been called
+ FakeJingleSession::AcceptCall acceptCall = getCall<FakeJingleSession::AcceptCall>(0);
+ CPPUNIT_ASSERT_EQUAL(payLoad->getSessionID(), acceptCall.payload->getSessionID());
+
+ // check for candidate error
+ FakeJingleSession::InfoTransportCall infoTransportCall = getCall<FakeJingleSession::InfoTransportCall>(1);
+ JingleS5BTransportPayload::ref s5bPayload = dynamic_pointer_cast<JingleS5BTransportPayload>(infoTransportCall.payload);
+ CPPUNIT_ASSERT(s5bPayload->hasCandidateError());
+
+ // indicate transport replace (Romeo)
+ session->handleTransportReplaceReceived(getContentID(), addJingleIBBPayload());
+
+ FakeJingleSession::AcceptTransportCall acceptTransportCall = getCall<FakeJingleSession::AcceptTransportCall>(2);
+
+ // send a bit of data
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
+ }
#if 0
- void test_S5BTransferReceiveTest() {
- addFileTransferDescription();
- JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
- }
+ void test_S5BTransferReceiveTest() {
+ addFileTransferDescription();
+ JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
+ }
#endif
private:
- void addFileTransferDescription() {
- shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
- desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
- jingleContentPayload->addDescription(desc);
- }
-
- shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
- JingleS5BTransportPayload::ref payLoad = make_shared<JingleS5BTransportPayload>();
- payLoad->setSessionID("mysession");
- jingleContentPayload->addTransport(payLoad);
- return payLoad;
- }
-
- shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
- JingleIBBTransportPayload::ref payLoad = make_shared<JingleIBBTransportPayload>();
- payLoad->setSessionID("mysession");
- jingleContentPayload->addTransport(payLoad);
- return payLoad;
- }
-
- JingleContentID getContentID() const {
- return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
- }
-
- template <typename T> T getCall(int i) const {
- size_t index = static_cast<size_t>(i);
- CPPUNIT_ASSERT(index < session->calledCommands.size());
- T* cmd = boost::get<T>(&session->calledCommands[index]);
- CPPUNIT_ASSERT(cmd);
- return *cmd;
- }
+ void addFileTransferDescription() {
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ }
+
+ shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = make_shared<JingleIBBTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ JingleContentID getContentID() const {
+ return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
+ }
+
+ template <typename T> T getCall(int i) const {
+ size_t index = static_cast<size_t>(i);
+ CPPUNIT_ASSERT(index < session->calledCommands.size());
+ T* cmd = boost::get<T>(&session->calledCommands[index]);
+ CPPUNIT_ASSERT(cmd);
+ return *cmd;
+ }
private:
- EventLoop* eventLoop;
- boost::shared_ptr<CryptoProvider> crypto;
- boost::shared_ptr<FakeJingleSession> session;
- shared_ptr<JingleContentPayload> jingleContentPayload;
-// shared_ptr<FakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF;
-// shared_ptr<FakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF;
- FileTransferTransporterFactory* ftTransporterFactory;
- SOCKS5BytestreamServerManager* bytestreamServerManager;
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- SOCKS5BytestreamRegistry* bytestreamRegistry;
- DummyConnectionFactory* connectionFactory;
- DummyConnectionServerFactory* serverConnectionFactory;
- SOCKS5BytestreamProxiesManager* bytestreamProxy;
- DummyTimerFactory* timerFactory;
- NetworkEnvironment* networkEnvironment;
- NATTraverser* natTraverser;
- IDGenerator* idGenerator;
- DomainNameResolver* resolver;
+ EventLoop* eventLoop;
+ boost::shared_ptr<CryptoProvider> crypto;
+ boost::shared_ptr<FakeJingleSession> session;
+ shared_ptr<JingleContentPayload> jingleContentPayload;
+// shared_ptr<FakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF;
+// shared_ptr<FakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF;
+ FileTransferTransporterFactory* ftTransporterFactory;
+ SOCKS5BytestreamServerManager* bytestreamServerManager;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ DummyConnectionFactory* connectionFactory;
+ DummyConnectionServerFactory* serverConnectionFactory;
+ SOCKS5BytestreamProxiesManager* bytestreamProxy;
+ DummyTimerFactory* timerFactory;
+ NetworkEnvironment* networkEnvironment;
+ NATTraverser* natTraverser;
+ IDGenerator* idGenerator;
+ DomainNameResolver* resolver;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IncomingJingleFileTransferTest);
diff --git a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
index fee26d5..401463c 100644
--- a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
@@ -52,232 +52,232 @@
using namespace Swift;
class OutgoingJingleFileTransferTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(OutgoingJingleFileTransferTest);
- CPPUNIT_TEST(test_SendSessionInitiateOnStart);
- CPPUNIT_TEST(test_FallbackToIBBAfterFailingS5B);
- CPPUNIT_TEST(test_ReceiveSessionTerminateAfterSessionInitiate);
- CPPUNIT_TEST(test_DeclineEmitsFinishedStateCanceled);
- CPPUNIT_TEST_SUITE_END();
-
- class FTStatusHelper {
- public:
- FTStatusHelper() : finishedCalled(false), error(FileTransferError::UnknownError) {
- }
-
- void handleFileTransferFinished(boost::optional<FileTransferError> error) {
- finishedCalled = true;
- if (error.is_initialized()) this->error = error.get().getType();
- }
-
- void handleFileTransferStatusChanged(FileTransfer::State fileTransferSTate) {
- state = fileTransferSTate;
- }
-
- public:
- bool finishedCalled;
- FileTransferError::Type error;
- boost::optional<FileTransfer::State> state;
- };
+ CPPUNIT_TEST_SUITE(OutgoingJingleFileTransferTest);
+ CPPUNIT_TEST(test_SendSessionInitiateOnStart);
+ CPPUNIT_TEST(test_FallbackToIBBAfterFailingS5B);
+ CPPUNIT_TEST(test_ReceiveSessionTerminateAfterSessionInitiate);
+ CPPUNIT_TEST(test_DeclineEmitsFinishedStateCanceled);
+ CPPUNIT_TEST_SUITE_END();
+
+ class FTStatusHelper {
+ public:
+ FTStatusHelper() : finishedCalled(false), error(FileTransferError::UnknownError) {
+ }
+
+ void handleFileTransferFinished(boost::optional<FileTransferError> error) {
+ finishedCalled = true;
+ if (error.is_initialized()) this->error = error.get().getType();
+ }
+
+ void handleFileTransferStatusChanged(FileTransfer::State fileTransferSTate) {
+ state = fileTransferSTate;
+ }
+
+ public:
+ bool finishedCalled;
+ FileTransferError::Type error;
+ boost::optional<FileTransfer::State> state;
+ };
public:
- boost::shared_ptr<OutgoingJingleFileTransfer> createTestling(const FileTransferOptions& options = FileTransferOptions().withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false)) {
- JID to("test@foo.com/bla");
- JingleFileTransferFileInfo fileInfo;
- fileInfo.setDescription("some file");
- fileInfo.setName("test.bin");
- fileInfo.addHash(HashElement("sha-1", ByteArray()));
- fileInfo.setSize(1024 * 1024);
- return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(
- to,
- boost::shared_ptr<JingleSession>(fakeJingleSession),
- stream,
- ftTransportFactory,
- timerFactory,
- idGen,
- fileInfo,
- options,
- crypto.get()));
- }
-
- IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
- IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
- request->setFrom(from);
- return request;
- }
-
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession");
- jingleContentPayload = boost::make_shared<JingleContentPayload>();
- stanzaChannel = new DummyStanzaChannel();
- iqRouter = new IQRouter(stanzaChannel);
- eventLoop = new DummyEventLoop();
- timerFactory = new DummyTimerFactory();
- connectionFactory = new DummyConnectionFactory(eventLoop);
- serverConnectionFactory = new DummyConnectionServerFactory(eventLoop);
- s5bRegistry = new SOCKS5BytestreamRegistry();
- networkEnvironment = new PlatformNetworkEnvironment();
- natTraverser = new PlatformNATTraversalWorker(eventLoop);
- bytestreamServerManager = new SOCKS5BytestreamServerManager(s5bRegistry, serverConnectionFactory, networkEnvironment, natTraverser);
-
- data.clear();
- for (int n=0; n < 1024 * 1024; ++n) {
- data.push_back(34);
- }
-
- stream = boost::make_shared<ByteArrayReadBytestream>(data);
-
- idGen = new IDGenerator();
- s5bProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com");
- ftTransportFactory = new DummyFileTransferTransporterFactory(s5bRegistry, bytestreamServerManager, s5bProxy, idGen, connectionFactory, timerFactory, crypto.get(), iqRouter);
- }
-
- void tearDown() {
- delete ftTransportFactory;
- delete s5bProxy;
- delete idGen;
- delete bytestreamServerManager;
- delete natTraverser;
- delete networkEnvironment;
- delete s5bRegistry;
- delete serverConnectionFactory;
- delete connectionFactory;
- delete timerFactory;
- delete eventLoop;
- delete iqRouter;
- delete stanzaChannel;
- }
-
-
- void test_SendSessionInitiateOnStart() {
- boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
- transfer->start();
-
- FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
- JingleFileTransferDescription::ref description = boost::dynamic_pointer_cast<JingleFileTransferDescription>(call.description);
- CPPUNIT_ASSERT(description);
- CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getFileInfo().getSize());
-
- JingleIBBTransportPayload::ref transport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(call.payload);
- CPPUNIT_ASSERT(transport);
- }
-
- void test_FallbackToIBBAfterFailingS5B() {
- boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(FileTransferOptions().withAssistedAllowed(true).withDirectAllowed(true).withProxiedAllowed(true));
- transfer->start();
-
- FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
-
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload));
- fakeJingleSession->handleSessionAcceptReceived(call.id, call.description, call.payload);
-
- // send candidate failure
- JingleS5BTransportPayload::ref candidateFailurePayload = boost::make_shared<JingleS5BTransportPayload>();
- candidateFailurePayload->setCandidateError(true);
- candidateFailurePayload->setSessionID(call.payload->getSessionID());
- fakeJingleSession->handleTransportInfoReceived(call.id, candidateFailurePayload);
-
- // no S5B candidates -> fallback to IBB
- // call at position 1 is the candidate our candidate error
- FakeJingleSession::ReplaceTransportCall replaceCall = getCall<FakeJingleSession::ReplaceTransportCall>(2);
-
- // accept transport replace
- fakeJingleSession->handleTransportAcceptReceived(replaceCall.id, replaceCall.payload);
-
- IQ::ref iqOpenStanza = stanzaChannel->getStanzaAtIndex<IQ>(0);
- CPPUNIT_ASSERT(iqOpenStanza);
- IBB::ref ibbOpen = iqOpenStanza->getPayload<IBB>();
- CPPUNIT_ASSERT(ibbOpen);
- CPPUNIT_ASSERT_EQUAL(IBB::Open, ibbOpen->getAction());
- }
-
- void test_ReceiveSessionTerminateAfterSessionInitiate() {
- boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
- transfer->start();
-
- getCall<FakeJingleSession::InitiateCall>(0);
-
- FTStatusHelper helper;
- helper.finishedCalled = false;
- transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1));
- fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Busy));
- CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled);
- CPPUNIT_ASSERT(FileTransferError::PeerError == helper.error);
- }
-
- void test_DeclineEmitsFinishedStateCanceled() {
- boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
- transfer->start();
-
- getCall<FakeJingleSession::InitiateCall>(0);
-
- FTStatusHelper helper;
- helper.finishedCalled = false;
- transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1));
- transfer->onStateChanged.connect(bind(&FTStatusHelper::handleFileTransferStatusChanged, &helper, _1));
- fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Decline));
- CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled);
- CPPUNIT_ASSERT(FileTransferError::UnknownError == helper.error);
- CPPUNIT_ASSERT_EQUAL(true, helper.state.is_initialized());
- CPPUNIT_ASSERT(FileTransfer::State::Canceled == helper.state.get().type);
- }
+ boost::shared_ptr<OutgoingJingleFileTransfer> createTestling(const FileTransferOptions& options = FileTransferOptions().withAssistedAllowed(false).withDirectAllowed(false).withProxiedAllowed(false)) {
+ JID to("test@foo.com/bla");
+ JingleFileTransferFileInfo fileInfo;
+ fileInfo.setDescription("some file");
+ fileInfo.setName("test.bin");
+ fileInfo.addHash(HashElement("sha-1", ByteArray()));
+ fileInfo.setSize(1024 * 1024);
+ return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(
+ to,
+ boost::shared_ptr<JingleSession>(fakeJingleSession),
+ stream,
+ ftTransportFactory,
+ timerFactory,
+ idGen,
+ fileInfo,
+ options,
+ crypto.get()));
+ }
+
+ IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
+ IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
+ request->setFrom(from);
+ return request;
+ }
+
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession");
+ jingleContentPayload = boost::make_shared<JingleContentPayload>();
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ eventLoop = new DummyEventLoop();
+ timerFactory = new DummyTimerFactory();
+ connectionFactory = new DummyConnectionFactory(eventLoop);
+ serverConnectionFactory = new DummyConnectionServerFactory(eventLoop);
+ s5bRegistry = new SOCKS5BytestreamRegistry();
+ networkEnvironment = new PlatformNetworkEnvironment();
+ natTraverser = new PlatformNATTraversalWorker(eventLoop);
+ bytestreamServerManager = new SOCKS5BytestreamServerManager(s5bRegistry, serverConnectionFactory, networkEnvironment, natTraverser);
+
+ data.clear();
+ for (int n=0; n < 1024 * 1024; ++n) {
+ data.push_back(34);
+ }
+
+ stream = boost::make_shared<ByteArrayReadBytestream>(data);
+
+ idGen = new IDGenerator();
+ s5bProxy = new SOCKS5BytestreamProxiesManager(connectionFactory, timerFactory, resolver, iqRouter, "bar.com");
+ ftTransportFactory = new DummyFileTransferTransporterFactory(s5bRegistry, bytestreamServerManager, s5bProxy, idGen, connectionFactory, timerFactory, crypto.get(), iqRouter);
+ }
+
+ void tearDown() {
+ delete ftTransportFactory;
+ delete s5bProxy;
+ delete idGen;
+ delete bytestreamServerManager;
+ delete natTraverser;
+ delete networkEnvironment;
+ delete s5bRegistry;
+ delete serverConnectionFactory;
+ delete connectionFactory;
+ delete timerFactory;
+ delete eventLoop;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+
+ void test_SendSessionInitiateOnStart() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+ JingleFileTransferDescription::ref description = boost::dynamic_pointer_cast<JingleFileTransferDescription>(call.description);
+ CPPUNIT_ASSERT(description);
+ CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getFileInfo().getSize());
+
+ JingleIBBTransportPayload::ref transport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(call.payload);
+ CPPUNIT_ASSERT(transport);
+ }
+
+ void test_FallbackToIBBAfterFailingS5B() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(FileTransferOptions().withAssistedAllowed(true).withDirectAllowed(true).withProxiedAllowed(true));
+ transfer->start();
+
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload));
+ fakeJingleSession->handleSessionAcceptReceived(call.id, call.description, call.payload);
+
+ // send candidate failure
+ JingleS5BTransportPayload::ref candidateFailurePayload = boost::make_shared<JingleS5BTransportPayload>();
+ candidateFailurePayload->setCandidateError(true);
+ candidateFailurePayload->setSessionID(call.payload->getSessionID());
+ fakeJingleSession->handleTransportInfoReceived(call.id, candidateFailurePayload);
+
+ // no S5B candidates -> fallback to IBB
+ // call at position 1 is the candidate our candidate error
+ FakeJingleSession::ReplaceTransportCall replaceCall = getCall<FakeJingleSession::ReplaceTransportCall>(2);
+
+ // accept transport replace
+ fakeJingleSession->handleTransportAcceptReceived(replaceCall.id, replaceCall.payload);
+
+ IQ::ref iqOpenStanza = stanzaChannel->getStanzaAtIndex<IQ>(0);
+ CPPUNIT_ASSERT(iqOpenStanza);
+ IBB::ref ibbOpen = iqOpenStanza->getPayload<IBB>();
+ CPPUNIT_ASSERT(ibbOpen);
+ CPPUNIT_ASSERT_EQUAL(IBB::Open, ibbOpen->getAction());
+ }
+
+ void test_ReceiveSessionTerminateAfterSessionInitiate() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ getCall<FakeJingleSession::InitiateCall>(0);
+
+ FTStatusHelper helper;
+ helper.finishedCalled = false;
+ transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1));
+ fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Busy));
+ CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled);
+ CPPUNIT_ASSERT(FileTransferError::PeerError == helper.error);
+ }
+
+ void test_DeclineEmitsFinishedStateCanceled() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ getCall<FakeJingleSession::InitiateCall>(0);
+
+ FTStatusHelper helper;
+ helper.finishedCalled = false;
+ transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1));
+ transfer->onStateChanged.connect(bind(&FTStatusHelper::handleFileTransferStatusChanged, &helper, _1));
+ fakeJingleSession->handleSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Decline));
+ CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled);
+ CPPUNIT_ASSERT(FileTransferError::UnknownError == helper.error);
+ CPPUNIT_ASSERT_EQUAL(true, helper.state.is_initialized());
+ CPPUNIT_ASSERT(FileTransfer::State::Canceled == helper.state.get().type);
+ }
//TODO: some more testcases
private:
- void addFileTransferDescription() {
- boost::shared_ptr<JingleFileTransferDescription> desc = boost::make_shared<JingleFileTransferDescription>();
- desc->setFileInfo(JingleFileTransferFileInfo());
- jingleContentPayload->addDescription(desc);
- }
-
- boost::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
- JingleS5BTransportPayload::ref payLoad = boost::make_shared<JingleS5BTransportPayload>();
- payLoad->setSessionID("mysession");
- jingleContentPayload->addTransport(payLoad);
- return payLoad;
- }
-
- boost::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
- JingleIBBTransportPayload::ref payLoad = boost::make_shared<JingleIBBTransportPayload>();
- payLoad->setSessionID("mysession");
- jingleContentPayload->addTransport(payLoad);
- return payLoad;
- }
-
- JingleContentID getContentID() const {
- return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
- }
-
- template <typename T> T getCall(int i) const {
- size_t index = static_cast<size_t>(i);
- CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size());
- T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]);
- CPPUNIT_ASSERT(cmd);
- return *cmd;
- }
+ void addFileTransferDescription() {
+ boost::shared_ptr<JingleFileTransferDescription> desc = boost::make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo());
+ jingleContentPayload->addDescription(desc);
+ }
+
+ boost::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = boost::make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ boost::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = boost::make_shared<JingleIBBTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ JingleContentID getContentID() const {
+ return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
+ }
+
+ template <typename T> T getCall(int i) const {
+ size_t index = static_cast<size_t>(i);
+ CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size());
+ T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]);
+ CPPUNIT_ASSERT(cmd);
+ return *cmd;
+ }
private:
- std::vector<unsigned char> data;
- boost::shared_ptr<ByteArrayReadBytestream> stream;
- FakeJingleSession* fakeJingleSession;
- boost::shared_ptr<JingleContentPayload> jingleContentPayload;
- FileTransferTransporterFactory* ftTransportFactory;
- SOCKS5BytestreamServerManager* bytestreamServerManager;
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- IDGenerator* idGen;
- EventLoop *eventLoop;
- SOCKS5BytestreamRegistry* s5bRegistry;
- SOCKS5BytestreamProxiesManager* s5bProxy;
- DummyTimerFactory* timerFactory;
- DummyConnectionFactory* connectionFactory;
- DummyConnectionServerFactory* serverConnectionFactory;
- boost::shared_ptr<CryptoProvider> crypto;
- NetworkEnvironment* networkEnvironment;
- NATTraverser* natTraverser;
- DomainNameResolver* resolver;
+ std::vector<unsigned char> data;
+ boost::shared_ptr<ByteArrayReadBytestream> stream;
+ FakeJingleSession* fakeJingleSession;
+ boost::shared_ptr<JingleContentPayload> jingleContentPayload;
+ FileTransferTransporterFactory* ftTransportFactory;
+ SOCKS5BytestreamServerManager* bytestreamServerManager;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ IDGenerator* idGen;
+ EventLoop *eventLoop;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxiesManager* s5bProxy;
+ DummyTimerFactory* timerFactory;
+ DummyConnectionFactory* connectionFactory;
+ DummyConnectionServerFactory* serverConnectionFactory;
+ boost::shared_ptr<CryptoProvider> crypto;
+ NetworkEnvironment* networkEnvironment;
+ NATTraverser* natTraverser;
+ DomainNameResolver* resolver;
};
CPPUNIT_TEST_SUITE_REGISTRATION(OutgoingJingleFileTransferTest);
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
index a0f6033..ceffdb7 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -43,275 +43,275 @@ using namespace Swift;
static boost::mt19937 randomGen;
class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest);
- CPPUNIT_TEST(testForSessionReady);
- CPPUNIT_TEST(testErrorHandlingHello);
- CPPUNIT_TEST(testErrorHandlingRequest);
- CPPUNIT_TEST(testWriteBytestream);
- CPPUNIT_TEST(testReadBytestream);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest);
+ CPPUNIT_TEST(testForSessionReady);
+ CPPUNIT_TEST(testErrorHandlingHello);
+ CPPUNIT_TEST(testErrorHandlingRequest);
+ CPPUNIT_TEST(testWriteBytestream);
+ CPPUNIT_TEST(testReadBytestream);
+ CPPUNIT_TEST_SUITE_END();
public:
- SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)) {}
-
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- destination = "092a44d859d19c9eed676b551ee80025903351c2";
- randomGen.seed(static_cast<unsigned int>(time(NULL)));
- eventLoop = new DummyEventLoop();
- timerFactory = new DummyTimerFactory();
- connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
- //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
- //stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
-// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
- }
-
- void tearDown() {
- //connection.reset();
- delete timerFactory;
- delete eventLoop;
- }
-
- void testForSessionReady() {
- TestHelper helper;
- connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
-
- SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
- clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
-
- clientSession->start();
- eventLoop->processEvents();
- CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput);
-
- helper.unprocessedInput.clear();
- serverRespondHelloOK();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
- CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4])));
- CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
-
- helper.unprocessedInput.clear();
- serverRespondRequestOK();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
- CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
- }
-
- void testErrorHandlingHello() {
- TestHelper helper;
- connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
-
- SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
- clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
-
- clientSession->start();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
-
- helper.unprocessedInput.clear();
- serverRespondHelloAuthFail();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
- CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
- }
-
- void testErrorHandlingRequest() {
- TestHelper helper;
- connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
-
- SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
- clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
-
- clientSession->start();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
-
- helper.unprocessedInput.clear();
- serverRespondHelloOK();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
- CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4])));
- CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
-
- helper.unprocessedInput.clear();
- serverRespondRequestFail();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
- CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
- }
-
- void testWriteBytestream() {
- TestHelper helper;
- connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
-
- SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
- clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
-
- clientSession->start();
- eventLoop->processEvents();
-
- helper.unprocessedInput.clear();
- serverRespondHelloOK();
- eventLoop->processEvents();
-
- helper.unprocessedInput.clear();
- serverRespondRequestOK();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
- CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
-
- boost::shared_ptr<ByteArrayWriteBytestream> output = boost::make_shared<ByteArrayWriteBytestream>();
- clientSession->startReceiving(output);
-
- ByteArray transferData = generateRandomByteArray(1024);
- connection->onDataRead(createSafeByteArrayRef(vecptr(transferData), transferData.size()));
- CPPUNIT_ASSERT_EQUAL(transferData, output->getData());
- }
-
- void testReadBytestream() {
- TestHelper helper;
- connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
-
- SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
- clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
-
- clientSession->start();
- eventLoop->processEvents();
-
- helper.unprocessedInput.clear();
- serverRespondHelloOK();
- eventLoop->processEvents();
-
- helper.unprocessedInput.clear();
- serverRespondRequestOK();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
- CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
-
- helper.unprocessedInput.clear();
- ByteArray transferData = generateRandomByteArray(1024);
- boost::shared_ptr<ByteArrayReadBytestream> input = boost::make_shared<ByteArrayReadBytestream>(transferData);
- clientSession->startSending(input);
- eventLoop->processEvents();
+ SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)) {}
+
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ destination = "092a44d859d19c9eed676b551ee80025903351c2";
+ randomGen.seed(static_cast<unsigned int>(time(NULL)));
+ eventLoop = new DummyEventLoop();
+ timerFactory = new DummyTimerFactory();
+ connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
+ //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
+ //stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
+// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
+ }
+
+ void tearDown() {
+ //connection.reset();
+ delete timerFactory;
+ delete eventLoop;
+ }
+
+ void testForSessionReady() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4])));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+ }
+
+ void testErrorHandlingHello() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloAuthFail();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
+ CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
+ }
+
+ void testErrorHandlingRequest() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(static_cast<char>(destination.size())), createByteArray(static_cast<char>(helper.unprocessedInput[4])));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestFail();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
+ CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
+ }
+
+ void testWriteBytestream() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+
+ boost::shared_ptr<ByteArrayWriteBytestream> output = boost::make_shared<ByteArrayWriteBytestream>();
+ clientSession->startReceiving(output);
+
+ ByteArray transferData = generateRandomByteArray(1024);
+ connection->onDataRead(createSafeByteArrayRef(vecptr(transferData), transferData.size()));
+ CPPUNIT_ASSERT_EQUAL(transferData, output->getData());
+ }
+
+ void testReadBytestream() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+
+ helper.unprocessedInput.clear();
+ ByteArray transferData = generateRandomByteArray(1024);
+ boost::shared_ptr<ByteArrayReadBytestream> input = boost::make_shared<ByteArrayReadBytestream>(transferData);
+ clientSession->startSending(input);
+ eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(createByteArray(vecptr(transferData), transferData.size()), helper.unprocessedInput);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray(vecptr(transferData), transferData.size()), helper.unprocessedInput);
+ }
private:
- static ByteArray generateRandomByteArray(size_t len) {
- boost::uniform_int<> dist(0, 255);
- boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist);
- ByteArray result(len);
- for (size_t i=0; i < len; ++i ) {
- result[i] = static_cast<unsigned char>(randomByte());
- }
- return result;
- }
-
- // Server responses
- void serverRespondHelloOK() {
- connection->onDataRead(createSafeByteArrayRef("\x05\00", 2));
- }
-
- void serverRespondHelloAuthFail() {
- connection->onDataRead(createSafeByteArrayRef("\x05\xFF", 2));
- }
-
- void serverRespondRequestOK() {
- boost::shared_ptr<SafeByteArray> dataToSend = createSafeByteArrayRef("\x05\x00\x00\x03", 4);
- append(*dataToSend, createSafeByteArray(static_cast<char>(destination.size())));
- append(*dataToSend, createSafeByteArray(destination));
- append(*dataToSend, createSafeByteArray("\x00", 1));
- connection->onDataRead(dataToSend);
- }
-
- void serverRespondRequestFail() {
- boost::shared_ptr<SafeByteArray> correctData = createSafeByteArrayRef("\x05\x00\x00\x03", 4);
- append(*correctData, createSafeByteArray(static_cast<char>(destination.size())));
- append(*correctData, createSafeByteArray(destination));
- append(*correctData, createSafeByteArray("\x00", 1));
-
- boost::shared_ptr<SafeByteArray> dataToSend;
- //ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51");
- //append(dataToSend, failingData);
- //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl;
- do {
- ByteArray rndArray = generateRandomByteArray(correctData->size());
- dataToSend = createSafeByteArrayRef(vecptr(rndArray), rndArray.size());
- } while (*dataToSend == *correctData);
- connection->onDataRead(dataToSend);
- }
+ static ByteArray generateRandomByteArray(size_t len) {
+ boost::uniform_int<> dist(0, 255);
+ boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist);
+ ByteArray result(len);
+ for (size_t i=0; i < len; ++i ) {
+ result[i] = static_cast<unsigned char>(randomByte());
+ }
+ return result;
+ }
+
+ // Server responses
+ void serverRespondHelloOK() {
+ connection->onDataRead(createSafeByteArrayRef("\x05\00", 2));
+ }
+
+ void serverRespondHelloAuthFail() {
+ connection->onDataRead(createSafeByteArrayRef("\x05\xFF", 2));
+ }
+
+ void serverRespondRequestOK() {
+ boost::shared_ptr<SafeByteArray> dataToSend = createSafeByteArrayRef("\x05\x00\x00\x03", 4);
+ append(*dataToSend, createSafeByteArray(static_cast<char>(destination.size())));
+ append(*dataToSend, createSafeByteArray(destination));
+ append(*dataToSend, createSafeByteArray("\x00", 1));
+ connection->onDataRead(dataToSend);
+ }
+
+ void serverRespondRequestFail() {
+ boost::shared_ptr<SafeByteArray> correctData = createSafeByteArrayRef("\x05\x00\x00\x03", 4);
+ append(*correctData, createSafeByteArray(static_cast<char>(destination.size())));
+ append(*correctData, createSafeByteArray(destination));
+ append(*correctData, createSafeByteArray("\x00", 1));
+
+ boost::shared_ptr<SafeByteArray> dataToSend;
+ //ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51");
+ //append(dataToSend, failingData);
+ //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl;
+ do {
+ ByteArray rndArray = generateRandomByteArray(correctData->size());
+ dataToSend = createSafeByteArrayRef(vecptr(rndArray), rndArray.size());
+ } while (*dataToSend == *correctData);
+ connection->onDataRead(dataToSend);
+ }
private:
- struct TestHelper {
- TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {}
- ByteArray unprocessedInput;
- bool sessionReadyCalled;
- bool sessionReadyError;
+ struct TestHelper {
+ TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {}
+ ByteArray unprocessedInput;
+ bool sessionReadyCalled;
+ bool sessionReadyError;
- void handleConnectionDataWritten(const SafeByteArray& data) {
- append(unprocessedInput, data);
- //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl;
- }
+ void handleConnectionDataWritten(const SafeByteArray& data) {
+ append(unprocessedInput, data);
+ //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl;
+ }
- void handleSessionReady(bool error) {
- sessionReadyCalled = true;
- sessionReadyError = error;
- }
- };
+ void handleSessionReady(bool error) {
+ sessionReadyCalled = true;
+ sessionReadyError = error;
+ }
+ };
private:
- struct MockeryConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<MockeryConnection> {
- public:
- MockeryConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive), disconnectCalled(false) {}
-
- void listen() { assert(false); }
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- if (isResponsive) {
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
-
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-
- void disconnect() {
- disconnectCalled = true;
- }
-
- void write(const SafeByteArray& data) {
- eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
- onDataSent(data);
- }
-
- boost::signal<void (const SafeByteArray&)> onDataSent;
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- bool isResponsive;
- bool disconnectCalled;
- };
+ struct MockeryConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<MockeryConnection> {
+ public:
+ MockeryConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive), disconnectCalled(false) {}
+
+ void listen() { assert(false); }
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ if (isResponsive) {
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+
+ void disconnect() {
+ disconnectCalled = true;
+ }
+
+ void write(const SafeByteArray& data) {
+ eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
+ onDataSent(data);
+ }
+
+ boost::signal<void (const SafeByteArray&)> onDataSent;
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ bool isResponsive;
+ bool disconnectCalled;
+ };
private:
- HostAddressPort destinationAddressPort;
- std::string destination;
- DummyEventLoop* eventLoop;
- DummyTimerFactory* timerFactory;
- boost::shared_ptr<MockeryConnection> connection;
- const std::vector<HostAddressPort> failingPorts;
- boost::shared_ptr<CryptoProvider> crypto;
+ HostAddressPort destinationAddressPort;
+ std::string destination;
+ DummyEventLoop* eventLoop;
+ DummyTimerFactory* timerFactory;
+ boost::shared_ptr<MockeryConnection> connection;
+ const std::vector<HostAddressPort> failingPorts;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamClientSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
index 84dcf7c..12690ff 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
@@ -21,193 +21,193 @@
using namespace Swift;
class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SOCKS5BytestreamServerSessionTest);
- CPPUNIT_TEST(testAuthenticate);
- CPPUNIT_TEST(testAuthenticate_Chunked);
- CPPUNIT_TEST(testRequest);
- CPPUNIT_TEST(testRequest_UnknownBytestream);
- CPPUNIT_TEST(testReceiveData);
- CPPUNIT_TEST(testReceiveData_Chunked);
- CPPUNIT_TEST(testDataStreamPauseStopsSendingData);
- CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- receivedDataChunks = 0;
- eventLoop = new DummyEventLoop();
- bytestreams = new SOCKS5BytestreamRegistry();
- connection = boost::make_shared<DummyConnection>(eventLoop);
- connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
- stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
- finished = false;
- }
-
- void tearDown() {
- connection.reset();
- delete bytestreams;
- delete eventLoop;
- }
-
- void testAuthenticate() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
-
- receive(createSafeByteArray("\x05\x02\x01\x02"));
-
- CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
- }
-
- void testAuthenticate_Chunked() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
-
- receive(createSafeByteArray("\x05\x02\x01"));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size()));
- receive(createSafeByteArray("\x01"));
- CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
- }
-
- void testRequest() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams->setHasBytestream("abcdef", true);
- authenticate();
-
- ByteArray hostname(createByteArray("abcdef"));
- receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
- CPPUNIT_ASSERT(createByteArray("\x05\x00\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == createByteArray(&receivedData[0], 13));
- }
-
- void testRequest_UnknownBytestream() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- authenticate();
-
- ByteArray hostname(createByteArray("abcdef"));
- receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
- CPPUNIT_ASSERT(createByteArray("\x05\x04\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == receivedData);
- }
-
- void testReceiveData() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams->setHasBytestream("abcdef", true);
- authenticate();
- request("abcdef");
- eventLoop->processEvents();
- testling->startSending(stream1);
- skipHeader("abcdef");
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
- CPPUNIT_ASSERT_EQUAL(2, receivedDataChunks);
- }
-
- void testReceiveData_Chunked() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- testling->setChunkSize(3);
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams->setHasBytestream("abcdef", true);
- authenticate();
- request("abcdef");
- eventLoop->processEvents();
- testling->startSending(stream1);
- eventLoop->processEvents();
- skipHeader("abcdef");
- CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
- CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks);
- }
-
- void testDataStreamPauseStopsSendingData() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- testling->setChunkSize(3);
- stream1->setDataComplete(false);
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams->setHasBytestream("abcdef", true);
- authenticate();
- request("abcdef");
- eventLoop->processEvents();
- testling->startSending(stream1);
- eventLoop->processEvents();
- skipHeader("abcdef");
- CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
- CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks);
-
- CPPUNIT_ASSERT(!finished);
- CPPUNIT_ASSERT(!error);
- }
-
- void testDataStreamResumeAfterPauseSendsData() {
- boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
- testling->setChunkSize(3);
- stream1->setDataComplete(false);
- StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams->setHasBytestream("abcdef", true);
- authenticate();
- request("abcdef");
- eventLoop->processEvents();
- testling->startSending(stream1);
- eventLoop->processEvents();
- skipHeader("abcdef");
-
- stream1->addData(createByteArray("xyz"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(createByteArray("abcdefgxyz") == receivedData);
- CPPUNIT_ASSERT(!finished);
- CPPUNIT_ASSERT(!error);
- }
-
- private:
- void receive(const SafeByteArray& data) {
- connection->receive(data);
- eventLoop->processEvents();
- }
-
- void authenticate() {
- receive(createSafeByteArray("\x05\x02\x01\x02"));
- receivedData.clear();
- receivedDataChunks = 0;
- }
-
- void request(const std::string& hostname) {
- receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
- }
-
- void skipHeader(const std::string& hostname) {
- size_t headerSize = 7 + hostname.size();
- receivedData = createByteArray(&receivedData[headerSize], receivedData.size() - headerSize);
- }
-
-
- void handleDataWritten(const SafeByteArray& data) {
- receivedData.insert(receivedData.end(), data.begin(), data.end());
- receivedDataChunks++;
- }
-
- private:
- SOCKS5BytestreamServerSession* createSession() {
- SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, bytestreams);
- session->onFinished.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleFinished, this, _1));
- return session;
- }
-
- void handleFinished(boost::optional<FileTransferError> error) {
- finished = true;
- this->error = error;
- }
-
- private:
- DummyEventLoop* eventLoop;
- SOCKS5BytestreamRegistry* bytestreams;
- boost::shared_ptr<DummyConnection> connection;
- std::vector<unsigned char> receivedData;
- int receivedDataChunks;
- boost::shared_ptr<ByteArrayReadBytestream> stream1;
- bool finished;
- boost::optional<FileTransferError> error;
+ CPPUNIT_TEST_SUITE(SOCKS5BytestreamServerSessionTest);
+ CPPUNIT_TEST(testAuthenticate);
+ CPPUNIT_TEST(testAuthenticate_Chunked);
+ CPPUNIT_TEST(testRequest);
+ CPPUNIT_TEST(testRequest_UnknownBytestream);
+ CPPUNIT_TEST(testReceiveData);
+ CPPUNIT_TEST(testReceiveData_Chunked);
+ CPPUNIT_TEST(testDataStreamPauseStopsSendingData);
+ CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ receivedDataChunks = 0;
+ eventLoop = new DummyEventLoop();
+ bytestreams = new SOCKS5BytestreamRegistry();
+ connection = boost::make_shared<DummyConnection>(eventLoop);
+ connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
+ stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
+ finished = false;
+ }
+
+ void tearDown() {
+ connection.reset();
+ delete bytestreams;
+ delete eventLoop;
+ }
+
+ void testAuthenticate() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+
+ receive(createSafeByteArray("\x05\x02\x01\x02"));
+
+ CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
+ }
+
+ void testAuthenticate_Chunked() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+
+ receive(createSafeByteArray("\x05\x02\x01"));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size()));
+ receive(createSafeByteArray("\x01"));
+ CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
+ }
+
+ void testRequest() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ bytestreams->setHasBytestream("abcdef", true);
+ authenticate();
+
+ ByteArray hostname(createByteArray("abcdef"));
+ receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
+ CPPUNIT_ASSERT(createByteArray("\x05\x00\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == createByteArray(&receivedData[0], 13));
+ }
+
+ void testRequest_UnknownBytestream() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ authenticate();
+
+ ByteArray hostname(createByteArray("abcdef"));
+ receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
+ CPPUNIT_ASSERT(createByteArray("\x05\x04\x00\x03\x06\x61\x62\x63\x64\x65\x66\x00\x00", 13) == receivedData);
+ }
+
+ void testReceiveData() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ bytestreams->setHasBytestream("abcdef", true);
+ authenticate();
+ request("abcdef");
+ eventLoop->processEvents();
+ testling->startSending(stream1);
+ skipHeader("abcdef");
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
+ CPPUNIT_ASSERT_EQUAL(2, receivedDataChunks);
+ }
+
+ void testReceiveData_Chunked() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ testling->setChunkSize(3);
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ bytestreams->setHasBytestream("abcdef", true);
+ authenticate();
+ request("abcdef");
+ eventLoop->processEvents();
+ testling->startSending(stream1);
+ eventLoop->processEvents();
+ skipHeader("abcdef");
+ CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
+ CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks);
+ }
+
+ void testDataStreamPauseStopsSendingData() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ testling->setChunkSize(3);
+ stream1->setDataComplete(false);
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ bytestreams->setHasBytestream("abcdef", true);
+ authenticate();
+ request("abcdef");
+ eventLoop->processEvents();
+ testling->startSending(stream1);
+ eventLoop->processEvents();
+ skipHeader("abcdef");
+ CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
+ CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks);
+
+ CPPUNIT_ASSERT(!finished);
+ CPPUNIT_ASSERT(!error);
+ }
+
+ void testDataStreamResumeAfterPauseSendsData() {
+ boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
+ testling->setChunkSize(3);
+ stream1->setDataComplete(false);
+ StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
+ bytestreams->setHasBytestream("abcdef", true);
+ authenticate();
+ request("abcdef");
+ eventLoop->processEvents();
+ testling->startSending(stream1);
+ eventLoop->processEvents();
+ skipHeader("abcdef");
+
+ stream1->addData(createByteArray("xyz"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(createByteArray("abcdefgxyz") == receivedData);
+ CPPUNIT_ASSERT(!finished);
+ CPPUNIT_ASSERT(!error);
+ }
+
+ private:
+ void receive(const SafeByteArray& data) {
+ connection->receive(data);
+ eventLoop->processEvents();
+ }
+
+ void authenticate() {
+ receive(createSafeByteArray("\x05\x02\x01\x02"));
+ receivedData.clear();
+ receivedDataChunks = 0;
+ }
+
+ void request(const std::string& hostname) {
+ receive(concat(createSafeByteArray("\x05\x01\x00\x03", 4), createSafeByteArray(static_cast<char>(hostname.size())), createSafeByteArray(hostname), createSafeByteArray("\x00\x00", 2)));
+ }
+
+ void skipHeader(const std::string& hostname) {
+ size_t headerSize = 7 + hostname.size();
+ receivedData = createByteArray(&receivedData[headerSize], receivedData.size() - headerSize);
+ }
+
+
+ void handleDataWritten(const SafeByteArray& data) {
+ receivedData.insert(receivedData.end(), data.begin(), data.end());
+ receivedDataChunks++;
+ }
+
+ private:
+ SOCKS5BytestreamServerSession* createSession() {
+ SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, bytestreams);
+ session->onFinished.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleFinished, this, _1));
+ return session;
+ }
+
+ void handleFinished(boost::optional<FileTransferError> error) {
+ finished = true;
+ this->error = error;
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ SOCKS5BytestreamRegistry* bytestreams;
+ boost::shared_ptr<DummyConnection> connection;
+ std::vector<unsigned char> receivedData;
+ int receivedDataChunks;
+ boost::shared_ptr<ByteArrayReadBytestream> stream1;
+ bool finished;
+ boost::optional<FileTransferError> error;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamServerSessionTest);
diff --git a/Swiften/FileTransfer/WriteBytestream.h b/Swiften/FileTransfer/WriteBytestream.h
index 76237c4..ffcfdcc 100644
--- a/Swiften/FileTransfer/WriteBytestream.h
+++ b/Swiften/FileTransfer/WriteBytestream.h
@@ -14,19 +14,19 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class SWIFTEN_API WriteBytestream {
- public:
- typedef boost::shared_ptr<WriteBytestream> ref;
+ class SWIFTEN_API WriteBytestream {
+ public:
+ typedef boost::shared_ptr<WriteBytestream> ref;
- virtual ~WriteBytestream();
+ virtual ~WriteBytestream();
- /**
- * Write data from vector argument to bytestream.
- *
- * On success true is returned and \ref onWrite is called. On failure false is returned.
- */
- virtual bool write(const std::vector<unsigned char>&) = 0;
+ /**
+ * Write data from vector argument to bytestream.
+ *
+ * On success true is returned and \ref onWrite is called. On failure false is returned.
+ */
+ virtual bool write(const std::vector<unsigned char>&) = 0;
- boost::signal<void (const std::vector<unsigned char>&)> onWrite;
- };
+ boost::signal<void (const std::vector<unsigned char>&)> onWrite;
+ };
}
diff --git a/Swiften/History/HistoryMessage.h b/Swiften/History/HistoryMessage.h
index e07ef60..e910899 100644
--- a/Swiften/History/HistoryMessage.h
+++ b/Swiften/History/HistoryMessage.h
@@ -12,63 +12,63 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API HistoryMessage {
- public:
- enum Type {
- Chat = 0,
- Groupchat = 1,
- PrivateMessage = 2
- };
+ class SWIFTEN_API HistoryMessage {
+ public:
+ enum Type {
+ Chat = 0,
+ Groupchat = 1,
+ PrivateMessage = 2
+ };
- HistoryMessage(
- const std::string& message,
- const JID& fromJID,
- const JID& toJID,
- Type type,
- const boost::posix_time::ptime& time,
- int utcOffset = 0) :
- message_(message),
- fromJID_(fromJID),
- toJID_(toJID),
- type_(type),
- time_(time),
- utcOffset_(utcOffset) {
- }
+ HistoryMessage(
+ const std::string& message,
+ const JID& fromJID,
+ const JID& toJID,
+ Type type,
+ const boost::posix_time::ptime& time,
+ int utcOffset = 0) :
+ message_(message),
+ fromJID_(fromJID),
+ toJID_(toJID),
+ type_(type),
+ time_(time),
+ utcOffset_(utcOffset) {
+ }
- const std::string& getMessage() const {
- return message_;
- }
+ const std::string& getMessage() const {
+ return message_;
+ }
- const JID& getFromJID() const {
- return fromJID_;
- }
+ const JID& getFromJID() const {
+ return fromJID_;
+ }
- const JID& getToJID() const {
- return toJID_;
- }
+ const JID& getToJID() const {
+ return toJID_;
+ }
- Type getType() const {
- return type_;
- }
+ Type getType() const {
+ return type_;
+ }
- boost::posix_time::ptime getTime() const {
- return time_;
- }
+ boost::posix_time::ptime getTime() const {
+ return time_;
+ }
- int getOffset() const {
- return utcOffset_;
- }
+ int getOffset() const {
+ return utcOffset_;
+ }
- bool operator==(const HistoryMessage& o) const {
- return message_ == o.message_ && fromJID_ == o.fromJID_ && toJID_ == o.toJID_ && type_ == o.type_ && time_ == o.time_;
- }
+ bool operator==(const HistoryMessage& o) const {
+ return message_ == o.message_ && fromJID_ == o.fromJID_ && toJID_ == o.toJID_ && type_ == o.type_ && time_ == o.time_;
+ }
- private:
- std::string message_;
- JID fromJID_;
- JID toJID_;
- Type type_;
- boost::posix_time::ptime time_;
- int utcOffset_;
- };
+ private:
+ std::string message_;
+ JID fromJID_;
+ JID toJID_;
+ Type type_;
+ boost::posix_time::ptime time_;
+ int utcOffset_;
+ };
}
diff --git a/Swiften/History/HistoryStorage.h b/Swiften/History/HistoryStorage.h
index ee8f15b..10b6bb0 100644
--- a/Swiften/History/HistoryStorage.h
+++ b/Swiften/History/HistoryStorage.h
@@ -17,20 +17,20 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- typedef std::map<JID, std::set<boost::gregorian::date> > ContactsMap;
+ typedef std::map<JID, std::set<boost::gregorian::date> > ContactsMap;
- class SWIFTEN_API HistoryStorage {
- /**
- * Messages are stored using localtime timestamps.
- */
- public:
- virtual ~HistoryStorage() {}
+ class SWIFTEN_API HistoryStorage {
+ /**
+ * Messages are stored using localtime timestamps.
+ */
+ public:
+ virtual ~HistoryStorage() {}
- virtual void addMessage(const HistoryMessage& message) = 0;
- virtual std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
- virtual std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
- virtual std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
- virtual ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const = 0;
- virtual boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const = 0;
- };
+ virtual void addMessage(const HistoryMessage& message) = 0;
+ virtual std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
+ virtual std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
+ virtual std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const = 0;
+ virtual ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const = 0;
+ virtual boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const = 0;
+ };
}
diff --git a/Swiften/History/SQLiteHistoryStorage.cpp b/Swiften/History/SQLiteHistoryStorage.cpp
index 8306803..beb7ba1 100644
--- a/Swiften/History/SQLiteHistoryStorage.cpp
+++ b/Swiften/History/SQLiteHistoryStorage.cpp
@@ -17,366 +17,366 @@
#include <Swiften/Base/Path.h>
inline std::string getEscapedString(const std::string& s) {
- std::string result(s);
-
- size_t pos = result.find('\'');
- while (pos != std::string::npos) {
- result.insert(pos, "'");
- pos = result.find('\'', pos + 2);
- }
- return result;
+ std::string result(s);
+
+ size_t pos = result.find('\'');
+ while (pos != std::string::npos) {
+ result.insert(pos, "'");
+ pos = result.find('\'', pos + 2);
+ }
+ return result;
}
namespace Swift {
SQLiteHistoryStorage::SQLiteHistoryStorage(const boost::filesystem::path& file) : db_(0) {
- thread_ = new boost::thread(boost::bind(&SQLiteHistoryStorage::run, this));
-
- sqlite3_open(pathToString(file).c_str(), &db_);
- if (!db_) {
- std::cerr << "Error opening database " << pathToString(file) << std::endl;
- }
-
- char* errorMessage;
- int result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS messages('message' STRING, 'fromBare' INTEGER, 'fromResource' STRING, 'toBare' INTEGER, 'toResource' STRING, 'type' INTEGER, 'time' INTEGER, 'offset' INTEGER)", 0, 0, &errorMessage);
- if (result != SQLITE_OK) {
- std::cerr << "SQL Error: " << errorMessage << std::endl;
- sqlite3_free(errorMessage);
- }
-
- result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS jids('id' INTEGER PRIMARY KEY ASC AUTOINCREMENT, 'jid' STRING UNIQUE NOT NULL)", 0, 0, &errorMessage);
- if (result != SQLITE_OK) {
- std::cerr << "SQL Error: " << errorMessage << std::endl;
- sqlite3_free(errorMessage);
- }
+ thread_ = new boost::thread(boost::bind(&SQLiteHistoryStorage::run, this));
+
+ sqlite3_open(pathToString(file).c_str(), &db_);
+ if (!db_) {
+ std::cerr << "Error opening database " << pathToString(file) << std::endl;
+ }
+
+ char* errorMessage;
+ int result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS messages('message' STRING, 'fromBare' INTEGER, 'fromResource' STRING, 'toBare' INTEGER, 'toResource' STRING, 'type' INTEGER, 'time' INTEGER, 'offset' INTEGER)", 0, 0, &errorMessage);
+ if (result != SQLITE_OK) {
+ std::cerr << "SQL Error: " << errorMessage << std::endl;
+ sqlite3_free(errorMessage);
+ }
+
+ result = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS jids('id' INTEGER PRIMARY KEY ASC AUTOINCREMENT, 'jid' STRING UNIQUE NOT NULL)", 0, 0, &errorMessage);
+ if (result != SQLITE_OK) {
+ std::cerr << "SQL Error: " << errorMessage << std::endl;
+ sqlite3_free(errorMessage);
+ }
}
SQLiteHistoryStorage::~SQLiteHistoryStorage() {
- sqlite3_close(db_);
- delete thread_;
+ sqlite3_close(db_);
+ delete thread_;
}
void SQLiteHistoryStorage::addMessage(const HistoryMessage& message) {
- int secondsSinceEpoch = (message.getTime() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds();
-
- std::string statement = std::string("INSERT INTO messages('message', 'fromBare', 'fromResource', 'toBare', 'toResource', 'type', 'time', 'offset') VALUES(") +
- "'" + getEscapedString(message.getMessage()) + "', " +
- boost::lexical_cast<std::string>(getIDForJID(message.getFromJID().toBare())) + ", '" +
- getEscapedString(message.getFromJID().getResource()) + "', " +
- boost::lexical_cast<std::string>(getIDForJID(message.getToJID().toBare())) + ", '" +
- getEscapedString(message.getToJID().getResource()) + "', " +
- boost::lexical_cast<std::string>(message.getType()) + ", " +
- boost::lexical_cast<std::string>(secondsSinceEpoch) + ", " +
- boost::lexical_cast<std::string>(message.getOffset()) + ")";
- char* errorMessage;
- int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage);
- if (result != SQLITE_OK) {
- std::cerr << "SQL Error: " << errorMessage << std::endl;
- sqlite3_free(errorMessage);
- }
+ int secondsSinceEpoch = (message.getTime() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds();
+
+ std::string statement = std::string("INSERT INTO messages('message', 'fromBare', 'fromResource', 'toBare', 'toResource', 'type', 'time', 'offset') VALUES(") +
+ "'" + getEscapedString(message.getMessage()) + "', " +
+ boost::lexical_cast<std::string>(getIDForJID(message.getFromJID().toBare())) + ", '" +
+ getEscapedString(message.getFromJID().getResource()) + "', " +
+ boost::lexical_cast<std::string>(getIDForJID(message.getToJID().toBare())) + ", '" +
+ getEscapedString(message.getToJID().getResource()) + "', " +
+ boost::lexical_cast<std::string>(message.getType()) + ", " +
+ boost::lexical_cast<std::string>(secondsSinceEpoch) + ", " +
+ boost::lexical_cast<std::string>(message.getOffset()) + ")";
+ char* errorMessage;
+ int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage);
+ if (result != SQLITE_OK) {
+ std::cerr << "SQL Error: " << errorMessage << std::endl;
+ sqlite3_free(errorMessage);
+ }
}
std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- sqlite3_stmt* selectStatement;
-
- boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
- boost::optional<long long> contactID = getIDFromJID(contactJID.toBare());
-
- if (!selfID || !contactID) {
- // JIDs missing from the database
- return std::vector<HistoryMessage>();
- }
-
- std::string selectQuery = "SELECT * FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type);
- if (contactJID.isBare()) {
- // match only bare jid
- selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" +
- boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" +
- boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))";
- }
- else {
- // match resource too
- selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" +
- boost::lexical_cast<std::string>(*contactID) +" AND toResource='" +
- getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" +
- boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" +
- getEscapedString(contactJID.getResource()) + "') AND toBare=" +
- boost::lexical_cast<std::string>(*selfID) + ")))";
- }
-
- if (!date.is_not_a_date()) {
- int lowerBound = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds();
- int upperBound = lowerBound + 86400;
-
- selectQuery += " AND (time>=" + boost::lexical_cast<std::string>(lowerBound) +
- " AND time<" + boost::lexical_cast<std::string>(upperBound) + ")";
- }
-
- int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
- r = sqlite3_step(selectStatement);
-
- // Retrieve result
- std::vector<HistoryMessage> result;
- while (r == SQLITE_ROW) {
- std::string message(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0)));
-
- // fromJID
- boost::optional<JID> fromJID(getJIDFromID(sqlite3_column_int(selectStatement, 1)));
- std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 2)));
- if (fromJID) {
- fromJID = boost::optional<JID>(JID(fromJID->getNode(), fromJID->getDomain(), fromResource));
- }
-
- // toJID
- boost::optional<JID> toJID(getJIDFromID(sqlite3_column_int(selectStatement, 3)));
- std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 4)));
- if (toJID) {
- toJID = boost::optional<JID>(JID(toJID->getNode(), toJID->getDomain(), toResource));
- }
-
- // message type
- HistoryMessage::Type type = static_cast<HistoryMessage::Type>(sqlite3_column_int(selectStatement, 5));
-
- // timestamp
- int secondsSinceEpoch(sqlite3_column_int(selectStatement, 6));
- boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
-
- // offset from utc
- int offset = sqlite3_column_int(selectStatement, 7);
-
- result.push_back(HistoryMessage(message, (fromJID ? *fromJID : JID()), (toJID ? *toJID : JID()), type, time, offset));
- r = sqlite3_step(selectStatement);
- }
- if (r != SQLITE_DONE) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
- sqlite3_finalize(selectStatement);
-
- return result;
+ sqlite3_stmt* selectStatement;
+
+ boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
+ boost::optional<long long> contactID = getIDFromJID(contactJID.toBare());
+
+ if (!selfID || !contactID) {
+ // JIDs missing from the database
+ return std::vector<HistoryMessage>();
+ }
+
+ std::string selectQuery = "SELECT * FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type);
+ if (contactJID.isBare()) {
+ // match only bare jid
+ selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" +
+ boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" +
+ boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))";
+ }
+ else {
+ // match resource too
+ selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" +
+ boost::lexical_cast<std::string>(*contactID) +" AND toResource='" +
+ getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" +
+ boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" +
+ getEscapedString(contactJID.getResource()) + "') AND toBare=" +
+ boost::lexical_cast<std::string>(*selfID) + ")))";
+ }
+
+ if (!date.is_not_a_date()) {
+ int lowerBound = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds();
+ int upperBound = lowerBound + 86400;
+
+ selectQuery += " AND (time>=" + boost::lexical_cast<std::string>(lowerBound) +
+ " AND time<" + boost::lexical_cast<std::string>(upperBound) + ")";
+ }
+
+ int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+ r = sqlite3_step(selectStatement);
+
+ // Retrieve result
+ std::vector<HistoryMessage> result;
+ while (r == SQLITE_ROW) {
+ std::string message(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0)));
+
+ // fromJID
+ boost::optional<JID> fromJID(getJIDFromID(sqlite3_column_int(selectStatement, 1)));
+ std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 2)));
+ if (fromJID) {
+ fromJID = boost::optional<JID>(JID(fromJID->getNode(), fromJID->getDomain(), fromResource));
+ }
+
+ // toJID
+ boost::optional<JID> toJID(getJIDFromID(sqlite3_column_int(selectStatement, 3)));
+ std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 4)));
+ if (toJID) {
+ toJID = boost::optional<JID>(JID(toJID->getNode(), toJID->getDomain(), toResource));
+ }
+
+ // message type
+ HistoryMessage::Type type = static_cast<HistoryMessage::Type>(sqlite3_column_int(selectStatement, 5));
+
+ // timestamp
+ int secondsSinceEpoch(sqlite3_column_int(selectStatement, 6));
+ boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
+
+ // offset from utc
+ int offset = sqlite3_column_int(selectStatement, 7);
+
+ result.push_back(HistoryMessage(message, (fromJID ? *fromJID : JID()), (toJID ? *toJID : JID()), type, time, offset));
+ r = sqlite3_step(selectStatement);
+ }
+ if (r != SQLITE_DONE) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+ sqlite3_finalize(selectStatement);
+
+ return result;
}
long long SQLiteHistoryStorage::getIDForJID(const JID& jid) {
- boost::optional<long long> id = getIDFromJID(jid);
- if (id) {
- return *id;
- }
- else {
- return addJID(jid);
- }
+ boost::optional<long long> id = getIDFromJID(jid);
+ if (id) {
+ return *id;
+ }
+ else {
+ return addJID(jid);
+ }
}
long long SQLiteHistoryStorage::addJID(const JID& jid) {
- std::string statement = std::string("INSERT INTO jids('jid') VALUES('") + getEscapedString(jid.toString()) + "')";
- char* errorMessage;
- int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage);
- if (result != SQLITE_OK) {
- std::cerr << "SQL Error: " << errorMessage << std::endl;
- sqlite3_free(errorMessage);
- }
- return sqlite3_last_insert_rowid(db_);
+ std::string statement = std::string("INSERT INTO jids('jid') VALUES('") + getEscapedString(jid.toString()) + "')";
+ char* errorMessage;
+ int result = sqlite3_exec(db_, statement.c_str(), 0, 0, &errorMessage);
+ if (result != SQLITE_OK) {
+ std::cerr << "SQL Error: " << errorMessage << std::endl;
+ sqlite3_free(errorMessage);
+ }
+ return sqlite3_last_insert_rowid(db_);
}
boost::optional<JID> SQLiteHistoryStorage::getJIDFromID(long long id) const {
- boost::optional<JID> result;
- sqlite3_stmt* selectStatement;
- std::string selectQuery("SELECT jid FROM jids WHERE id=" + boost::lexical_cast<std::string>(id));
- int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
- r = sqlite3_step(selectStatement);
- if (r == SQLITE_ROW) {
- result = boost::optional<JID>(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0)));
- }
- sqlite3_finalize(selectStatement);
- return result;
+ boost::optional<JID> result;
+ sqlite3_stmt* selectStatement;
+ std::string selectQuery("SELECT jid FROM jids WHERE id=" + boost::lexical_cast<std::string>(id));
+ int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+ r = sqlite3_step(selectStatement);
+ if (r == SQLITE_ROW) {
+ result = boost::optional<JID>(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 0)));
+ }
+ sqlite3_finalize(selectStatement);
+ return result;
}
boost::optional<long long> SQLiteHistoryStorage::getIDFromJID(const JID& jid) const {
- boost::optional<long long> result;
- sqlite3_stmt* selectStatement;
- std::string selectQuery("SELECT id FROM jids WHERE jid='" + jid.toString() + "'");
- long long r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
- r = sqlite3_step(selectStatement);
- if (r == SQLITE_ROW) {
- result = boost::optional<long long>(sqlite3_column_int(selectStatement, 0));
- }
- sqlite3_finalize(selectStatement);
- return result;
+ boost::optional<long long> result;
+ sqlite3_stmt* selectStatement;
+ std::string selectQuery("SELECT id FROM jids WHERE jid='" + jid.toString() + "'");
+ long long r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+ r = sqlite3_step(selectStatement);
+ if (r == SQLITE_ROW) {
+ result = boost::optional<long long>(sqlite3_column_int(selectStatement, 0));
+ }
+ sqlite3_finalize(selectStatement);
+ return result;
}
ContactsMap SQLiteHistoryStorage::getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const {
- ContactsMap result;
- sqlite3_stmt* selectStatement;
-
- // get id
- boost::optional<long long> id = getIDFromJID(selfJID);
- if (!id) {
- return result;
- }
-
- // get contacts
- std::string query = "SELECT DISTINCT messages.'fromBare', messages.'fromResource', messages.'toBare', messages.'toResource', messages.'time' "
- "FROM messages WHERE (type="
- + boost::lexical_cast<std::string>(type) + " AND (toBare="
- + boost::lexical_cast<std::string>(*id) + " OR fromBare=" + boost::lexical_cast<std::string>(*id) + "))";
-
- // match keyword
- if (getEscapedString(keyword).length()) {
- query += " AND message LIKE '%" + getEscapedString(keyword) + "%'";
- }
-
- int r = sqlite3_prepare(db_, query.c_str(), boost::numeric_cast<int>(query.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
-
- r = sqlite3_step(selectStatement);
- while (r == SQLITE_ROW) {
- int fromBareID = sqlite3_column_int(selectStatement, 0);
- std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 1)));
- int toBareID = sqlite3_column_int(selectStatement, 2);
- std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 3)));
- std::string resource;
-
- int secondsSinceEpoch(sqlite3_column_int(selectStatement, 4));
- boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
-
- boost::optional<JID> contactJID;
-
- if (fromBareID == *id) {
- contactJID = getJIDFromID(toBareID);
- resource = toResource;
- }
- else {
- contactJID = getJIDFromID(fromBareID);
- resource = fromResource;
- }
-
- // check if it is a MUC contact (from a private conversation)
- if (type == HistoryMessage::PrivateMessage) {
- contactJID = boost::optional<JID>(JID(contactJID->getNode(), contactJID->getDomain(), resource));
- }
-
- if (contactJID) {
- result[*contactJID].insert(time.date());
- }
-
- r = sqlite3_step(selectStatement);
- }
-
- if (r != SQLITE_DONE) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
- sqlite3_finalize(selectStatement);
-
- return result;
+ ContactsMap result;
+ sqlite3_stmt* selectStatement;
+
+ // get id
+ boost::optional<long long> id = getIDFromJID(selfJID);
+ if (!id) {
+ return result;
+ }
+
+ // get contacts
+ std::string query = "SELECT DISTINCT messages.'fromBare', messages.'fromResource', messages.'toBare', messages.'toResource', messages.'time' "
+ "FROM messages WHERE (type="
+ + boost::lexical_cast<std::string>(type) + " AND (toBare="
+ + boost::lexical_cast<std::string>(*id) + " OR fromBare=" + boost::lexical_cast<std::string>(*id) + "))";
+
+ // match keyword
+ if (getEscapedString(keyword).length()) {
+ query += " AND message LIKE '%" + getEscapedString(keyword) + "%'";
+ }
+
+ int r = sqlite3_prepare(db_, query.c_str(), boost::numeric_cast<int>(query.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+
+ r = sqlite3_step(selectStatement);
+ while (r == SQLITE_ROW) {
+ int fromBareID = sqlite3_column_int(selectStatement, 0);
+ std::string fromResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 1)));
+ int toBareID = sqlite3_column_int(selectStatement, 2);
+ std::string toResource(reinterpret_cast<const char*>(sqlite3_column_text(selectStatement, 3)));
+ std::string resource;
+
+ int secondsSinceEpoch(sqlite3_column_int(selectStatement, 4));
+ boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
+
+ boost::optional<JID> contactJID;
+
+ if (fromBareID == *id) {
+ contactJID = getJIDFromID(toBareID);
+ resource = toResource;
+ }
+ else {
+ contactJID = getJIDFromID(fromBareID);
+ resource = fromResource;
+ }
+
+ // check if it is a MUC contact (from a private conversation)
+ if (type == HistoryMessage::PrivateMessage) {
+ contactJID = boost::optional<JID>(JID(contactJID->getNode(), contactJID->getDomain(), resource));
+ }
+
+ if (contactJID) {
+ result[*contactJID].insert(time.date());
+ }
+
+ r = sqlite3_step(selectStatement);
+ }
+
+ if (r != SQLITE_DONE) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+ sqlite3_finalize(selectStatement);
+
+ return result;
}
boost::gregorian::date SQLiteHistoryStorage::getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const {
- sqlite3_stmt* selectStatement;
- boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
- boost::optional<long long> contactID = getIDFromJID(contactJID.toBare());
-
- if (!selfID || !contactID) {
- // JIDs missing from the database
- return boost::gregorian::date(boost::gregorian::not_a_date_time);
- }
-
- std::string selectQuery = "SELECT time FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type);
- if (contactJID.isBare()) {
- // match only bare jid
- selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" +
- boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" +
- boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))";
- }
- else {
- // match resource too
- selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" +
- boost::lexical_cast<std::string>(*contactID) +" AND toResource='" +
- getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" +
- boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" +
- getEscapedString(contactJID.getResource()) + "') AND toBare=" +
- boost::lexical_cast<std::string>(*selfID) + ")))";
- }
-
- int timeStamp = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds() + (reverseOrder ? 0 : 86400);
-
- selectQuery += " AND time" + (reverseOrder ? std::string("<") : std::string(">")) + boost::lexical_cast<std::string>(timeStamp);
- selectQuery += " ORDER BY time " + (reverseOrder ? std::string("DESC") : std::string("ASC")) + " LIMIT 1";
-
- int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
-
- r = sqlite3_step(selectStatement);
- if (r == SQLITE_ROW) {
- int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0));
- boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
- std::cout << "next day is: " << time.date() << "\n";
- return time.date();
- }
-
- return boost::gregorian::date(boost::gregorian::not_a_date_time);
+ sqlite3_stmt* selectStatement;
+ boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
+ boost::optional<long long> contactID = getIDFromJID(contactJID.toBare());
+
+ if (!selfID || !contactID) {
+ // JIDs missing from the database
+ return boost::gregorian::date(boost::gregorian::not_a_date_time);
+ }
+
+ std::string selectQuery = "SELECT time FROM messages WHERE (type=" + boost::lexical_cast<std::string>(type);
+ if (contactJID.isBare()) {
+ // match only bare jid
+ selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND toBare=" +
+ boost::lexical_cast<std::string>(*contactID) + ") OR (fromBare=" +
+ boost::lexical_cast<std::string>(*contactID) + " AND toBare=" + boost::lexical_cast<std::string>(*selfID) + ")))";
+ }
+ else {
+ // match resource too
+ selectQuery += " AND ((fromBare=" + boost::lexical_cast<std::string>(*selfID) + " AND (toBare=" +
+ boost::lexical_cast<std::string>(*contactID) +" AND toResource='" +
+ getEscapedString(contactJID.getResource()) + "')) OR ((fromBare=" +
+ boost::lexical_cast<std::string>(*contactID) + " AND fromResource='" +
+ getEscapedString(contactJID.getResource()) + "') AND toBare=" +
+ boost::lexical_cast<std::string>(*selfID) + ")))";
+ }
+
+ int timeStamp = (boost::posix_time::ptime(date) - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_seconds() + (reverseOrder ? 0 : 86400);
+
+ selectQuery += " AND time" + (reverseOrder ? std::string("<") : std::string(">")) + boost::lexical_cast<std::string>(timeStamp);
+ selectQuery += " ORDER BY time " + (reverseOrder ? std::string("DESC") : std::string("ASC")) + " LIMIT 1";
+
+ int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
+
+ r = sqlite3_step(selectStatement);
+ if (r == SQLITE_ROW) {
+ int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0));
+ boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
+ std::cout << "next day is: " << time.date() << "\n";
+ return time.date();
+ }
+
+ return boost::gregorian::date(boost::gregorian::not_a_date_time);
}
std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- boost::gregorian::date nextDate = getNextDateWithLogs(selfJID, contactJID, type, date, false);
+ boost::gregorian::date nextDate = getNextDateWithLogs(selfJID, contactJID, type, date, false);
- if (nextDate.is_not_a_date()) {
- return std::vector<HistoryMessage>();
- }
+ if (nextDate.is_not_a_date()) {
+ return std::vector<HistoryMessage>();
+ }
- return getMessagesFromDate(selfJID, contactJID, type, nextDate);
+ return getMessagesFromDate(selfJID, contactJID, type, nextDate);
}
std::vector<HistoryMessage> SQLiteHistoryStorage::getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const {
- boost::gregorian::date previousDate = getNextDateWithLogs(selfJID, contactJID, type, date, true);
+ boost::gregorian::date previousDate = getNextDateWithLogs(selfJID, contactJID, type, date, true);
- if (previousDate.is_not_a_date()) {
- return std::vector<HistoryMessage>();
- }
+ if (previousDate.is_not_a_date()) {
+ return std::vector<HistoryMessage>();
+ }
- return getMessagesFromDate(selfJID, contactJID, type, previousDate);
+ return getMessagesFromDate(selfJID, contactJID, type, previousDate);
}
boost::posix_time::ptime SQLiteHistoryStorage::getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const {
- boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
- boost::optional<long long> mucID = getIDFromJID(mucJID.toBare());
+ boost::optional<long long> selfID = getIDFromJID(selfJID.toBare());
+ boost::optional<long long> mucID = getIDFromJID(mucJID.toBare());
- if (!selfID || !mucID) {
- // JIDs missing from the database
- return boost::posix_time::ptime(boost::posix_time::not_a_date_time);
- }
+ if (!selfID || !mucID) {
+ // JIDs missing from the database
+ return boost::posix_time::ptime(boost::posix_time::not_a_date_time);
+ }
- sqlite3_stmt* selectStatement;
- std::string selectQuery = "SELECT messages.'time', messages.'offset' from messages WHERE type=1 AND (toBare=" +
- boost::lexical_cast<std::string>(*selfID) + " AND fromBare=" +
- boost::lexical_cast<std::string>(*mucID) + ") ORDER BY time DESC LIMIT 1";
+ sqlite3_stmt* selectStatement;
+ std::string selectQuery = "SELECT messages.'time', messages.'offset' from messages WHERE type=1 AND (toBare=" +
+ boost::lexical_cast<std::string>(*selfID) + " AND fromBare=" +
+ boost::lexical_cast<std::string>(*mucID) + ") ORDER BY time DESC LIMIT 1";
- int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
- if (r != SQLITE_OK) {
- std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
- }
+ int r = sqlite3_prepare(db_, selectQuery.c_str(), boost::numeric_cast<int>(selectQuery.size()), &selectStatement, NULL);
+ if (r != SQLITE_OK) {
+ std::cout << "Error: " << sqlite3_errmsg(db_) << std::endl;
+ }
- r = sqlite3_step(selectStatement);
- if (r == SQLITE_ROW) {
- int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0));
- boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
- int offset = sqlite3_column_int(selectStatement, 1);
+ r = sqlite3_step(selectStatement);
+ if (r == SQLITE_ROW) {
+ int secondsSinceEpoch(sqlite3_column_int(selectStatement, 0));
+ boost::posix_time::ptime time(boost::gregorian::date(1970, 1, 1), boost::posix_time::seconds(secondsSinceEpoch));
+ int offset = sqlite3_column_int(selectStatement, 1);
- return time - boost::posix_time::hours(offset);
- }
+ return time - boost::posix_time::hours(offset);
+ }
- return boost::posix_time::ptime(boost::posix_time::not_a_date_time);
+ return boost::posix_time::ptime(boost::posix_time::not_a_date_time);
}
void SQLiteHistoryStorage::run() {
diff --git a/Swiften/History/SQLiteHistoryStorage.h b/Swiften/History/SQLiteHistoryStorage.h
index 95b13b9..b0223f5 100644
--- a/Swiften/History/SQLiteHistoryStorage.h
+++ b/Swiften/History/SQLiteHistoryStorage.h
@@ -16,28 +16,28 @@
struct sqlite3;
namespace Swift {
- class SWIFTEN_API SQLiteHistoryStorage : public HistoryStorage {
- public:
- SQLiteHistoryStorage(const boost::filesystem::path& file);
- ~SQLiteHistoryStorage();
-
- void addMessage(const HistoryMessage& message);
- ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const;
- std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
- boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const;
-
- private:
- void run();
- boost::gregorian::date getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const;
- long long getIDForJID(const JID&);
- long long addJID(const JID&);
-
- boost::optional<JID> getJIDFromID(long long id) const;
- boost::optional<long long> getIDFromJID(const JID& jid) const;
-
- sqlite3* db_;
- boost::thread* thread_;
- };
+ class SWIFTEN_API SQLiteHistoryStorage : public HistoryStorage {
+ public:
+ SQLiteHistoryStorage(const boost::filesystem::path& file);
+ ~SQLiteHistoryStorage();
+
+ void addMessage(const HistoryMessage& message);
+ ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const;
+ std::vector<HistoryMessage> getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ std::vector<HistoryMessage> getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ std::vector<HistoryMessage> getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const;
+ boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) const;
+
+ private:
+ void run();
+ boost::gregorian::date getNextDateWithLogs(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date, bool reverseOrder) const;
+ long long getIDForJID(const JID&);
+ long long addJID(const JID&);
+
+ boost::optional<JID> getJIDFromID(long long id) const;
+ boost::optional<long long> getIDFromJID(const JID& jid) const;
+
+ sqlite3* db_;
+ boost::thread* thread_;
+ };
}
diff --git a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
index 560c992..5968d7e 100644
--- a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
+++ b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
@@ -14,103 +14,103 @@
using namespace Swift;
class SQLiteHistoryManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SQLiteHistoryManagerTest);
- //CPPUNIT_TEST(testAddMessage);
- //CPPUNIT_TEST(testAddMessage_TwoMessages);
- //CPPUNIT_TEST(testGetIDForJID_SameJID);
- //CPPUNIT_TEST(testGetIDForJID_DifferentJIDs);
- //CPPUNIT_TEST(getJIDFromID);
- //CPPUNIT_TEST(getJIDFromID_UnexistingID);
- //CPPUNIT_TEST(getIDFromJID);
- //CPPUNIT_TEST(getIDFromJID_UnexistingJID);
- //CPPUNIT_TEST_SUITE_END();
-
- public:
- SQLiteHistoryManagerTest() {}
-
- void setUp() {
- }
-
- void tearDown() {
- }
-
- void testAddMessage() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- HistoryMessage testMessage("Test", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03"));
- testling->addMessage(testMessage);
-
- std::vector<HistoryMessage> messages = testling->getMessages();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(messages.size()));
- CPPUNIT_ASSERT(testMessage == messages[0]);
- }
-
- void testAddMessage_TwoMessages() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- HistoryMessage testMessage1("Test1", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03"));
- testling->addMessage(testMessage1);
- HistoryMessage testMessage2("Test2", JID("fum@baz.org"), JID("foo@bar.com"), boost::posix_time::time_from_string("1975-03-09 22:04"));
- testling->addMessage(testMessage2);
-
- std::vector<HistoryMessage> messages = testling->getMessages();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(messages.size()));
- CPPUNIT_ASSERT(testMessage1 == messages[0]);
- CPPUNIT_ASSERT(testMessage2 == messages[1]);
- }
-
- void testGetIDForJID_SameJID() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- int id1 = testling->getIDForJID(JID("foo@bar.com"));
- int id2 = testling->getIDForJID(JID("foo@bar.com"));
-
- CPPUNIT_ASSERT_EQUAL(id1, id2);
- }
-
- void testGetIDForJID_DifferentJIDs() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- int id1 = testling->getIDForJID(JID("foo@bar.com"));
- int id2 = testling->getIDForJID(JID("foo@baz.com"));
-
- CPPUNIT_ASSERT(id1 != id2);
- }
-
- void getJIDFromID() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- int id = testling->addJID(JID("foo@bar.com"));
-
- boost::optional<JID> result(testling->getJIDFromID(id));
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), *result);
- }
-
- void getJIDFromID_UnexistingID() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
-
- boost::optional<JID> result(testling->getJIDFromID(1));
-
- CPPUNIT_ASSERT(!result);
- }
-
- void getIDFromJID() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
- int id = testling->addJID(JID("foo@bar.com"));
-
- boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com")));
- CPPUNIT_ASSERT(result);
- CPPUNIT_ASSERT_EQUAL(id, *result);
- }
-
- void getIDFromJID_UnexistingJID() {
- boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
-
- boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com")));
-
- CPPUNIT_ASSERT(!result);
- }
-
- private:
- SQLiteHistoryManager* createHistoryManager() {
- return new SQLiteHistoryManager(":memory:");
- }
+ CPPUNIT_TEST_SUITE(SQLiteHistoryManagerTest);
+ //CPPUNIT_TEST(testAddMessage);
+ //CPPUNIT_TEST(testAddMessage_TwoMessages);
+ //CPPUNIT_TEST(testGetIDForJID_SameJID);
+ //CPPUNIT_TEST(testGetIDForJID_DifferentJIDs);
+ //CPPUNIT_TEST(getJIDFromID);
+ //CPPUNIT_TEST(getJIDFromID_UnexistingID);
+ //CPPUNIT_TEST(getIDFromJID);
+ //CPPUNIT_TEST(getIDFromJID_UnexistingJID);
+ //CPPUNIT_TEST_SUITE_END();
+
+ public:
+ SQLiteHistoryManagerTest() {}
+
+ void setUp() {
+ }
+
+ void tearDown() {
+ }
+
+ void testAddMessage() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ HistoryMessage testMessage("Test", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03"));
+ testling->addMessage(testMessage);
+
+ std::vector<HistoryMessage> messages = testling->getMessages();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(messages.size()));
+ CPPUNIT_ASSERT(testMessage == messages[0]);
+ }
+
+ void testAddMessage_TwoMessages() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ HistoryMessage testMessage1("Test1", JID("foo@bar.com"), JID("fum@baz.org"), boost::posix_time::time_from_string("1980-01-21 22:03"));
+ testling->addMessage(testMessage1);
+ HistoryMessage testMessage2("Test2", JID("fum@baz.org"), JID("foo@bar.com"), boost::posix_time::time_from_string("1975-03-09 22:04"));
+ testling->addMessage(testMessage2);
+
+ std::vector<HistoryMessage> messages = testling->getMessages();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(messages.size()));
+ CPPUNIT_ASSERT(testMessage1 == messages[0]);
+ CPPUNIT_ASSERT(testMessage2 == messages[1]);
+ }
+
+ void testGetIDForJID_SameJID() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ int id1 = testling->getIDForJID(JID("foo@bar.com"));
+ int id2 = testling->getIDForJID(JID("foo@bar.com"));
+
+ CPPUNIT_ASSERT_EQUAL(id1, id2);
+ }
+
+ void testGetIDForJID_DifferentJIDs() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ int id1 = testling->getIDForJID(JID("foo@bar.com"));
+ int id2 = testling->getIDForJID(JID("foo@baz.com"));
+
+ CPPUNIT_ASSERT(id1 != id2);
+ }
+
+ void getJIDFromID() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ int id = testling->addJID(JID("foo@bar.com"));
+
+ boost::optional<JID> result(testling->getJIDFromID(id));
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), *result);
+ }
+
+ void getJIDFromID_UnexistingID() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+
+ boost::optional<JID> result(testling->getJIDFromID(1));
+
+ CPPUNIT_ASSERT(!result);
+ }
+
+ void getIDFromJID() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+ int id = testling->addJID(JID("foo@bar.com"));
+
+ boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com")));
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(id, *result);
+ }
+
+ void getIDFromJID_UnexistingJID() {
+ boost::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+
+ boost::optional<int> result(testling->getIDFromJID(JID("foo@bar.com")));
+
+ CPPUNIT_ASSERT(!result);
+ }
+
+ private:
+ SQLiteHistoryManager* createHistoryManager() {
+ return new SQLiteHistoryManager(":memory:");
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SQLiteHistoryManagerTest);
diff --git a/Swiften/IDN/ICUConverter.cpp b/Swiften/IDN/ICUConverter.cpp
index 74b2813..b83739c 100644
--- a/Swiften/IDN/ICUConverter.cpp
+++ b/Swiften/IDN/ICUConverter.cpp
@@ -19,139 +19,139 @@ using namespace Swift;
using boost::numeric_cast;
namespace {
- typedef std::vector<UChar, SafeAllocator<UChar> > ICUString;
-
- const char* toConstCharArray(const std::string& input) {
- return input.c_str();
- }
-
- const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) {
- return reinterpret_cast<const char*>(vecptr(input));
- }
-
- template<typename T>
- ICUString convertToICUString(const T& s) {
- ICUString result;
- result.resize(s.size());
- UErrorCode status = U_ZERO_ERROR;
- int32_t icuResultLength = numeric_cast<int32_t>(result.size());
- u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status);
- if (status == U_BUFFER_OVERFLOW_ERROR) {
- status = U_ZERO_ERROR;
- result.resize(numeric_cast<size_t>(icuResultLength));
- u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status);
- }
- if (U_FAILURE(status)) {
- return ICUString();
- }
- result.resize(numeric_cast<size_t>(icuResultLength));
- return result;
- }
-
- std::vector<char, SafeAllocator<char> > convertToArray(const ICUString& input) {
- std::vector<char, SafeAllocator<char> > result;
- result.resize(input.size());
- UErrorCode status = U_ZERO_ERROR;
- int32_t inputLength = numeric_cast<int32_t>(result.size());
- u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status);
- if (status == U_BUFFER_OVERFLOW_ERROR) {
- status = U_ZERO_ERROR;
- result.resize(numeric_cast<size_t>(inputLength));
- u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status);
- }
- if (U_FAILURE(status)) {
- return std::vector<char, SafeAllocator<char> >();
- }
-
- result.resize(numeric_cast<size_t>(inputLength) + 1);
- result[result.size() - 1] = '\0';
- return result;
- }
-
- std::string convertToString(const ICUString& input) {
- return std::string(vecptr(convertToArray(input)));
- }
-
- UStringPrepProfileType getICUProfileType(IDNConverter::StringPrepProfile profile) {
- switch(profile) {
- case IDNConverter::NamePrep: return USPREP_RFC3491_NAMEPREP;
- case IDNConverter::XMPPNodePrep: return USPREP_RFC3920_NODEPREP;
- case IDNConverter::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP;
- case IDNConverter::SASLPrep: return USPREP_RFC4013_SASLPREP;
- }
- assert(false);
- return USPREP_RFC3491_NAMEPREP;
- }
-
- template<typename StringType>
- std::vector<char, SafeAllocator<char> > getStringPreparedDetail(const StringType& s, IDNConverter::StringPrepProfile profile) {
- UErrorCode status = U_ZERO_ERROR;
-
- boost::shared_ptr<UStringPrepProfile> icuProfile(usprep_openByType(getICUProfileType(profile), &status), usprep_close);
- assert(U_SUCCESS(status));
-
- ICUString icuInput = convertToICUString(s);
- ICUString icuResult;
- UParseError parseError;
- icuResult.resize(icuInput.size());
- int32_t icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status);
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
- if (status == U_BUFFER_OVERFLOW_ERROR) {
- status = U_ZERO_ERROR;
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
- icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status);
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
- }
- if (U_FAILURE(status)) {
- return std::vector<char, SafeAllocator<char> >();
- }
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
-
- return convertToArray(icuResult);
- }
+ typedef std::vector<UChar, SafeAllocator<UChar> > ICUString;
+
+ const char* toConstCharArray(const std::string& input) {
+ return input.c_str();
+ }
+
+ const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) {
+ return reinterpret_cast<const char*>(vecptr(input));
+ }
+
+ template<typename T>
+ ICUString convertToICUString(const T& s) {
+ ICUString result;
+ result.resize(s.size());
+ UErrorCode status = U_ZERO_ERROR;
+ int32_t icuResultLength = numeric_cast<int32_t>(result.size());
+ u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status);
+ if (status == U_BUFFER_OVERFLOW_ERROR) {
+ status = U_ZERO_ERROR;
+ result.resize(numeric_cast<size_t>(icuResultLength));
+ u_strFromUTF8Lenient(vecptr(result), numeric_cast<int32_t>(result.size()), &icuResultLength, toConstCharArray(s), numeric_cast<int32_t>(s.size()), &status);
+ }
+ if (U_FAILURE(status)) {
+ return ICUString();
+ }
+ result.resize(numeric_cast<size_t>(icuResultLength));
+ return result;
+ }
+
+ std::vector<char, SafeAllocator<char> > convertToArray(const ICUString& input) {
+ std::vector<char, SafeAllocator<char> > result;
+ result.resize(input.size());
+ UErrorCode status = U_ZERO_ERROR;
+ int32_t inputLength = numeric_cast<int32_t>(result.size());
+ u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status);
+ if (status == U_BUFFER_OVERFLOW_ERROR) {
+ status = U_ZERO_ERROR;
+ result.resize(numeric_cast<size_t>(inputLength));
+ u_strToUTF8(vecptr(result), numeric_cast<int32_t>(result.size()), &inputLength, vecptr(input), numeric_cast<int32_t>(input.size()), &status);
+ }
+ if (U_FAILURE(status)) {
+ return std::vector<char, SafeAllocator<char> >();
+ }
+
+ result.resize(numeric_cast<size_t>(inputLength) + 1);
+ result[result.size() - 1] = '\0';
+ return result;
+ }
+
+ std::string convertToString(const ICUString& input) {
+ return std::string(vecptr(convertToArray(input)));
+ }
+
+ UStringPrepProfileType getICUProfileType(IDNConverter::StringPrepProfile profile) {
+ switch(profile) {
+ case IDNConverter::NamePrep: return USPREP_RFC3491_NAMEPREP;
+ case IDNConverter::XMPPNodePrep: return USPREP_RFC3920_NODEPREP;
+ case IDNConverter::XMPPResourcePrep: return USPREP_RFC3920_RESOURCEPREP;
+ case IDNConverter::SASLPrep: return USPREP_RFC4013_SASLPREP;
+ }
+ assert(false);
+ return USPREP_RFC3491_NAMEPREP;
+ }
+
+ template<typename StringType>
+ std::vector<char, SafeAllocator<char> > getStringPreparedDetail(const StringType& s, IDNConverter::StringPrepProfile profile) {
+ UErrorCode status = U_ZERO_ERROR;
+
+ boost::shared_ptr<UStringPrepProfile> icuProfile(usprep_openByType(getICUProfileType(profile), &status), usprep_close);
+ assert(U_SUCCESS(status));
+
+ ICUString icuInput = convertToICUString(s);
+ ICUString icuResult;
+ UParseError parseError;
+ icuResult.resize(icuInput.size());
+ int32_t icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status);
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+ if (status == U_BUFFER_OVERFLOW_ERROR) {
+ status = U_ZERO_ERROR;
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+ icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status);
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+ }
+ if (U_FAILURE(status)) {
+ return std::vector<char, SafeAllocator<char> >();
+ }
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+
+ return convertToArray(icuResult);
+ }
}
namespace Swift {
std::string ICUConverter::getStringPrepared(const std::string& s, StringPrepProfile profile) {
- if (s.empty()) {
- return "";
- }
- std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile);
- if (preparedData.empty()) {
- throw std::exception();
- }
- return std::string(vecptr(preparedData));
+ if (s.empty()) {
+ return "";
+ }
+ std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile);
+ if (preparedData.empty()) {
+ throw std::exception();
+ }
+ return std::string(vecptr(preparedData));
}
SafeByteArray ICUConverter::getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) {
- if (s.empty()) {
- return SafeByteArray();
- }
- std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile);
- if (preparedData.empty()) {
- throw std::exception();
- }
- return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData)));
+ if (s.empty()) {
+ return SafeByteArray();
+ }
+ std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedDetail(s, profile);
+ if (preparedData.empty()) {
+ throw std::exception();
+ }
+ return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData)));
}
boost::optional<std::string> ICUConverter::getIDNAEncoded(const std::string& domain) {
- UErrorCode status = U_ZERO_ERROR;
- ICUString icuInput = convertToICUString(domain);
- ICUString icuResult;
- icuResult.resize(icuInput.size());
- UParseError parseError;
- int32_t icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status);
- if (status == U_BUFFER_OVERFLOW_ERROR) {
- status = U_ZERO_ERROR;
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
- icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status);
- }
- if (U_FAILURE(status)) {
- return boost::optional<std::string>();
- }
- icuResult.resize(numeric_cast<size_t>(icuResultLength));
- return convertToString(icuResult);
+ UErrorCode status = U_ZERO_ERROR;
+ ICUString icuInput = convertToICUString(domain);
+ ICUString icuResult;
+ icuResult.resize(icuInput.size());
+ UParseError parseError;
+ int32_t icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status);
+ if (status == U_BUFFER_OVERFLOW_ERROR) {
+ status = U_ZERO_ERROR;
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+ icuResultLength = uidna_IDNToASCII(vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), UIDNA_USE_STD3_RULES, &parseError, &status);
+ }
+ if (U_FAILURE(status)) {
+ return boost::optional<std::string>();
+ }
+ icuResult.resize(numeric_cast<size_t>(icuResultLength));
+ return convertToString(icuResult);
}
}
diff --git a/Swiften/IDN/ICUConverter.h b/Swiften/IDN/ICUConverter.h
index da66d2f..0a0b0d3 100644
--- a/Swiften/IDN/ICUConverter.h
+++ b/Swiften/IDN/ICUConverter.h
@@ -13,11 +13,11 @@
#include <Swiften/IDN/IDNConverter.h>
namespace Swift {
- class SWIFTEN_API ICUConverter : public IDNConverter {
- public:
- virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
- virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
+ class SWIFTEN_API ICUConverter : public IDNConverter {
+ public:
+ virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
+ virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
- virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE;
- };
+ virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/IDN/IDNConverter.h b/Swiften/IDN/IDNConverter.h
index cbd5124..27ddd78 100644
--- a/Swiften/IDN/IDNConverter.h
+++ b/Swiften/IDN/IDNConverter.h
@@ -14,21 +14,21 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API IDNConverter {
- public:
- virtual ~IDNConverter();
-
- enum StringPrepProfile {
- NamePrep,
- XMPPNodePrep,
- XMPPResourcePrep,
- SASLPrep
- };
-
- virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) = 0;
- virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) = 0;
-
- // Thread-safe
- virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) = 0;
- };
+ class SWIFTEN_API IDNConverter {
+ public:
+ virtual ~IDNConverter();
+
+ enum StringPrepProfile {
+ NamePrep,
+ XMPPNodePrep,
+ XMPPResourcePrep,
+ SASLPrep
+ };
+
+ virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) = 0;
+ virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) = 0;
+
+ // Thread-safe
+ virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) = 0;
+ };
}
diff --git a/Swiften/IDN/LibIDNConverter.cpp b/Swiften/IDN/LibIDNConverter.cpp
index 78303b1..334f43b 100644
--- a/Swiften/IDN/LibIDNConverter.cpp
+++ b/Swiften/IDN/LibIDNConverter.cpp
@@ -7,8 +7,8 @@
#include <Swiften/IDN/LibIDNConverter.h>
extern "C" {
- #include <stringprep.h>
- #include <idna.h>
+ #include <stringprep.h>
+ #include <idna.h>
}
#include <cassert>
@@ -24,64 +24,64 @@ extern "C" {
using namespace Swift;
namespace {
- static const int MAX_STRINGPREP_SIZE = 1024;
+ static const int MAX_STRINGPREP_SIZE = 1024;
- const Stringprep_profile* getLibIDNProfile(IDNConverter::StringPrepProfile profile) {
- switch(profile) {
- case IDNConverter::NamePrep: return stringprep_nameprep;
- case IDNConverter::XMPPNodePrep: return stringprep_xmpp_nodeprep;
- case IDNConverter::XMPPResourcePrep: return stringprep_xmpp_resourceprep;
- case IDNConverter::SASLPrep: return stringprep_saslprep;
- }
- assert(false);
- return 0;
- }
+ const Stringprep_profile* getLibIDNProfile(IDNConverter::StringPrepProfile profile) {
+ switch(profile) {
+ case IDNConverter::NamePrep: return stringprep_nameprep;
+ case IDNConverter::XMPPNodePrep: return stringprep_xmpp_nodeprep;
+ case IDNConverter::XMPPResourcePrep: return stringprep_xmpp_resourceprep;
+ case IDNConverter::SASLPrep: return stringprep_saslprep;
+ }
+ assert(false);
+ return 0;
+ }
- template<typename StringType, typename ContainerType>
- ContainerType getStringPreparedInternal(const StringType& s, IDNConverter::StringPrepProfile profile) {
- ContainerType input(s.begin(), s.end());
- if (!UTF8IsValid(s.data(), s.size())) {
- return ContainerType();
- }
+ template<typename StringType, typename ContainerType>
+ ContainerType getStringPreparedInternal(const StringType& s, IDNConverter::StringPrepProfile profile) {
+ ContainerType input(s.begin(), s.end());
+ if (!UTF8IsValid(s.data(), s.size())) {
+ return ContainerType();
+ }
- input.resize(MAX_STRINGPREP_SIZE);
- if (stringprep(&input[0], MAX_STRINGPREP_SIZE, static_cast<Stringprep_profile_flags>(0), getLibIDNProfile(profile)) == 0) {
- return input;
- }
- else {
- return ContainerType();
- }
- }
+ input.resize(MAX_STRINGPREP_SIZE);
+ if (stringprep(&input[0], MAX_STRINGPREP_SIZE, static_cast<Stringprep_profile_flags>(0), getLibIDNProfile(profile)) == 0) {
+ return input;
+ }
+ else {
+ return ContainerType();
+ }
+ }
}
namespace Swift {
std::string LibIDNConverter::getStringPrepared(const std::string& s, StringPrepProfile profile) {
- std::vector<char> preparedData = getStringPreparedInternal< std::string, std::vector<char> >(s, profile);
- if (preparedData.empty()) {
- throw std::exception();
- }
- return std::string(vecptr(preparedData));
+ std::vector<char> preparedData = getStringPreparedInternal< std::string, std::vector<char> >(s, profile);
+ if (preparedData.empty()) {
+ throw std::exception();
+ }
+ return std::string(vecptr(preparedData));
}
SafeByteArray LibIDNConverter::getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) {
- std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedInternal<SafeByteArray, std::vector<char, SafeAllocator<char> > >(s, profile);
- if (preparedData.empty()) {
- throw std::exception();
- }
- return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData)));
+ std::vector<char, SafeAllocator<char> > preparedData = getStringPreparedInternal<SafeByteArray, std::vector<char, SafeAllocator<char> > >(s, profile);
+ if (preparedData.empty()) {
+ throw std::exception();
+ }
+ return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData)));
}
boost::optional<std::string> LibIDNConverter::getIDNAEncoded(const std::string& domain) {
- char* output;
- if (idna_to_ascii_8z(domain.c_str(), &output, IDNA_USE_STD3_ASCII_RULES) == IDNA_SUCCESS) {
- std::string result(output);
- free(output);
- return result;
- }
- else {
- return boost::optional<std::string>();
- }
+ char* output;
+ if (idna_to_ascii_8z(domain.c_str(), &output, IDNA_USE_STD3_ASCII_RULES) == IDNA_SUCCESS) {
+ std::string result(output);
+ free(output);
+ return result;
+ }
+ else {
+ return boost::optional<std::string>();
+ }
}
}
diff --git a/Swiften/IDN/LibIDNConverter.h b/Swiften/IDN/LibIDNConverter.h
index fe68710..3f1d1f7 100644
--- a/Swiften/IDN/LibIDNConverter.h
+++ b/Swiften/IDN/LibIDNConverter.h
@@ -13,12 +13,12 @@
#include <Swiften/IDN/IDNConverter.h>
namespace Swift {
- class SWIFTEN_API LibIDNConverter : public IDNConverter {
- public:
- virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
- virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
+ class SWIFTEN_API LibIDNConverter : public IDNConverter {
+ public:
+ virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
+ virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE;
- virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE;
- };
+ virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/IDN/PlatformIDNConverter.cpp b/Swiften/IDN/PlatformIDNConverter.cpp
index 4735d8e..041c934 100644
--- a/Swiften/IDN/PlatformIDNConverter.cpp
+++ b/Swiften/IDN/PlatformIDNConverter.cpp
@@ -15,14 +15,14 @@ namespace Swift {
IDNConverter* PlatformIDNConverter::create() {
#if defined(HAVE_LIBIDN)
- return new LibIDNConverter();
+ return new LibIDNConverter();
#elif defined(HAVE_ICU)
- return new ICUConverter();
+ return new ICUConverter();
#else
#if defined(NEED_IDN)
#error "No IDN implementation"
#endif
- return 0;
+ return 0;
#endif
}
diff --git a/Swiften/IDN/PlatformIDNConverter.h b/Swiften/IDN/PlatformIDNConverter.h
index eaa7aa0..704f7a7 100644
--- a/Swiften/IDN/PlatformIDNConverter.h
+++ b/Swiften/IDN/PlatformIDNConverter.h
@@ -9,9 +9,9 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class IDNConverter;
+ class IDNConverter;
- namespace PlatformIDNConverter {
- SWIFTEN_API IDNConverter* create();
- }
+ namespace PlatformIDNConverter {
+ SWIFTEN_API IDNConverter* create();
+ }
}
diff --git a/Swiften/IDN/UTF8Validator.h b/Swiften/IDN/UTF8Validator.h
index 5df8769..d912ef9 100644
--- a/Swiften/IDN/UTF8Validator.h
+++ b/Swiften/IDN/UTF8Validator.h
@@ -13,55 +13,55 @@ namespace Swift {
// UTF-8 validation based on the description in https://tools.ietf.org/html/rfc3629#section-3 .
template <typename CharType>
bool UTF8IsValid(const CharType* data, size_t length) {
- bool isValid = true;
- const CharType* current = data;
- const CharType* end = data + length;
- while (isValid && (current < end)) {
- // one byte sequences
- if ((*current & 0x80) == 0x0) {
- current++;
- continue;
- }
- // longer byte sequences
- else {
- // two byte sequences
- if ((*current & 0xE0) == 0xC0) {
- current++;
- if ( (current < end) && ((*current & 0xC0) == 0x80) ) {
- current++;
- continue;
- }
- }
- // three byte sequences
- else if ((*current & 0xF0) == 0xE0) {
- current++;
- if ( ((current + 1) < end) && ((*current & 0xC0) == 0x80) ) {
- current++;
- if ((*current & 0xC0) == 0x80) {
- current++;
- continue;
- }
- }
- }
- // four byte sequences
- else if ((*current & 0xF8) == 0xF0) {
- current++;
- if ( ((current + 2) < end) && ((*current & 0xC0) == 0x80) ) {
- current++;
- if ((*current & 0xC0) == 0x80) {
- current++;
- if ((*current & 0xC0) == 0x80) {
- current++;
- continue;
- }
- }
- }
- }
- // invalid sequences
- isValid = false;
- }
- }
- return isValid;
+ bool isValid = true;
+ const CharType* current = data;
+ const CharType* end = data + length;
+ while (isValid && (current < end)) {
+ // one byte sequences
+ if ((*current & 0x80) == 0x0) {
+ current++;
+ continue;
+ }
+ // longer byte sequences
+ else {
+ // two byte sequences
+ if ((*current & 0xE0) == 0xC0) {
+ current++;
+ if ( (current < end) && ((*current & 0xC0) == 0x80) ) {
+ current++;
+ continue;
+ }
+ }
+ // three byte sequences
+ else if ((*current & 0xF0) == 0xE0) {
+ current++;
+ if ( ((current + 1) < end) && ((*current & 0xC0) == 0x80) ) {
+ current++;
+ if ((*current & 0xC0) == 0x80) {
+ current++;
+ continue;
+ }
+ }
+ }
+ // four byte sequences
+ else if ((*current & 0xF8) == 0xF0) {
+ current++;
+ if ( ((current + 2) < end) && ((*current & 0xC0) == 0x80) ) {
+ current++;
+ if ((*current & 0xC0) == 0x80) {
+ current++;
+ if ((*current & 0xC0) == 0x80) {
+ current++;
+ continue;
+ }
+ }
+ }
+ }
+ // invalid sequences
+ isValid = false;
+ }
+ }
+ return isValid;
}
}
diff --git a/Swiften/IDN/UnitTest/IDNConverterTest.cpp b/Swiften/IDN/UnitTest/IDNConverterTest.cpp
index 7d1bcf0..e0c97b5 100644
--- a/Swiften/IDN/UnitTest/IDNConverterTest.cpp
+++ b/Swiften/IDN/UnitTest/IDNConverterTest.cpp
@@ -15,50 +15,50 @@
using namespace Swift;
class IDNConverterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IDNConverterTest);
- CPPUNIT_TEST(testStringPrep);
- CPPUNIT_TEST(testStringPrep_Empty);
- CPPUNIT_TEST(testGetEncoded);
- CPPUNIT_TEST(testGetEncoded_International);
- CPPUNIT_TEST(testGetEncoded_Invalid);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IDNConverterTest);
+ CPPUNIT_TEST(testStringPrep);
+ CPPUNIT_TEST(testStringPrep_Empty);
+ CPPUNIT_TEST(testGetEncoded);
+ CPPUNIT_TEST(testGetEncoded_International);
+ CPPUNIT_TEST(testGetEncoded_Invalid);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- testling = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
- }
+ public:
+ void setUp() {
+ testling = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ }
- void testStringPrep() {
- std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep);
+ void testStringPrep() {
+ std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep);
- CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), result);
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), result);
+ }
- void testStringPrep_Empty() {
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::NamePrep));
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPNodePrep));
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPResourcePrep));
- }
+ void testStringPrep_Empty() {
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::NamePrep));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPNodePrep));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPResourcePrep));
+ }
- void testGetEncoded() {
- boost::optional<std::string> result = testling->getIDNAEncoded("www.swift.im");
- CPPUNIT_ASSERT(!!result);
- CPPUNIT_ASSERT_EQUAL(std::string("www.swift.im"), *result);
- }
+ void testGetEncoded() {
+ boost::optional<std::string> result = testling->getIDNAEncoded("www.swift.im");
+ CPPUNIT_ASSERT(!!result);
+ CPPUNIT_ASSERT_EQUAL(std::string("www.swift.im"), *result);
+ }
- void testGetEncoded_International() {
- boost::optional<std::string> result = testling->getIDNAEncoded("www.tron\xc3\x87on.com");
- CPPUNIT_ASSERT(!!result);
- CPPUNIT_ASSERT_EQUAL(std::string("www.xn--tronon-zua.com"), *result);
- }
+ void testGetEncoded_International() {
+ boost::optional<std::string> result = testling->getIDNAEncoded("www.tron\xc3\x87on.com");
+ CPPUNIT_ASSERT(!!result);
+ CPPUNIT_ASSERT_EQUAL(std::string("www.xn--tronon-zua.com"), *result);
+ }
- void testGetEncoded_Invalid() {
- boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com");
- CPPUNIT_ASSERT(!result);
- }
+ void testGetEncoded_Invalid() {
+ boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com");
+ CPPUNIT_ASSERT(!result);
+ }
- private:
- boost::shared_ptr<IDNConverter> testling;
+ private:
+ boost::shared_ptr<IDNConverter> testling;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IDNConverterTest);
diff --git a/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp b/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp
index 0295757..6db7770 100644
--- a/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp
+++ b/Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp
@@ -12,42 +12,42 @@
using namespace Swift;
class UTF8ValidatorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(UTF8ValidatorTest);
+ CPPUNIT_TEST_SUITE(UTF8ValidatorTest);
- CPPUNIT_TEST(testValidUTF8Sequences);
- CPPUNIT_TEST(testInvalidUTF8Sequences);
+ CPPUNIT_TEST(testValidUTF8Sequences);
+ CPPUNIT_TEST(testInvalidUTF8Sequences);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE_END();
public:
- void testValidUTF8Sequences() {
- {
- unsigned char test[] = {0x74, 0x65, 0x73, 0x74};
- CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test)));
- }
-
- {
- unsigned char test[] = {0xf4, 0x8f, 0x80, 0xbf};
- CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test)));
- }
- }
-
- void testInvalidUTF8Sequences() {
- {
- unsigned char test[] = {0x41, 0xC2, 0x3E, 0x42};
- CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
- }
-
- {
- unsigned char test[] = {0xf4};
- CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
- }
-
- {
- unsigned char test[] = {0xf4, 0x8f, 0x65, 0x73, 0x80, 0xbf};
- CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
- }
- }
+ void testValidUTF8Sequences() {
+ {
+ unsigned char test[] = {0x74, 0x65, 0x73, 0x74};
+ CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test)));
+ }
+
+ {
+ unsigned char test[] = {0xf4, 0x8f, 0x80, 0xbf};
+ CPPUNIT_ASSERT(UTF8IsValid(test, sizeof(test)));
+ }
+ }
+
+ void testInvalidUTF8Sequences() {
+ {
+ unsigned char test[] = {0x41, 0xC2, 0x3E, 0x42};
+ CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
+ }
+
+ {
+ unsigned char test[] = {0xf4};
+ CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
+ }
+
+ {
+ unsigned char test[] = {0xf4, 0x8f, 0x65, 0x73, 0x80, 0xbf};
+ CPPUNIT_ASSERT(!UTF8IsValid(test, sizeof(test)));
+ }
+ }
};
diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp
index 37fb755..ae08386 100644
--- a/Swiften/JID/JID.cpp
+++ b/Swiften/JID/JID.cpp
@@ -47,283 +47,283 @@ static IDNConverter* idnConverter = NULL;
#ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER
namespace {
- struct IDNInitializer {
- IDNInitializer() : defaultIDNConverter(PlatformIDNConverter::create()) {
- idnConverter = defaultIDNConverter.get();
- }
- boost::shared_ptr<IDNConverter> defaultIDNConverter;
- } initializer;
+ struct IDNInitializer {
+ IDNInitializer() : defaultIDNConverter(PlatformIDNConverter::create()) {
+ idnConverter = defaultIDNConverter.get();
+ }
+ boost::shared_ptr<IDNConverter> defaultIDNConverter;
+ } initializer;
}
#endif
static std::string getEscaped(char c) {
- return makeString() << '\\' << std::hex << static_cast<int>(c);
+ return makeString() << '\\' << std::hex << static_cast<int>(c);
}
static bool getEscapeSequenceValue(const std::string& sequence, unsigned char& value) {
- std::stringstream s;
- unsigned int v;
- s << std::hex << sequence;
- s >> v;
- value = static_cast<unsigned char>(v);
- return (!s.fail() && !s.bad() && (value == 0x5C || std::find(escapedChars.begin(), escapedChars.end(), value) != escapedChars.end()));
+ std::stringstream s;
+ unsigned int v;
+ s << std::hex << sequence;
+ s >> v;
+ value = static_cast<unsigned char>(v);
+ return (!s.fail() && !s.bad() && (value == 0x5C || std::find(escapedChars.begin(), escapedChars.end(), value) != escapedChars.end()));
}
// Disabling this code for now, since GCC4.5+boost1.42 (on ubuntu) seems to
// result in a bug. Replacing it with naive code.
#if 0
struct UnescapedCharacterFinder {
- template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) {
- for (; begin != end; ++begin) {
- if (std::find(escapedChars.begin(), escapedChars.end(), *begin) != escapedChars.end()) {
- return boost::iterator_range<Iterator>(begin, begin + 1);
- }
- else if (*begin == '\\') {
- // Check if we have an escaped dissalowed character sequence
- Iterator innerBegin = begin + 1;
- if (innerBegin != end && innerBegin + 1 != end) {
- Iterator innerEnd = innerBegin + 2;
- unsigned char value;
- if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) {
- return boost::iterator_range<Iterator>(begin, begin + 1);
- }
- }
- }
- }
- return boost::iterator_range<Iterator>(end, end);
- }
+ template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) {
+ for (; begin != end; ++begin) {
+ if (std::find(escapedChars.begin(), escapedChars.end(), *begin) != escapedChars.end()) {
+ return boost::iterator_range<Iterator>(begin, begin + 1);
+ }
+ else if (*begin == '\\') {
+ // Check if we have an escaped dissalowed character sequence
+ Iterator innerBegin = begin + 1;
+ if (innerBegin != end && innerBegin + 1 != end) {
+ Iterator innerEnd = innerBegin + 2;
+ unsigned char value;
+ if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) {
+ return boost::iterator_range<Iterator>(begin, begin + 1);
+ }
+ }
+ }
+ }
+ return boost::iterator_range<Iterator>(end, end);
+ }
};
struct UnescapedCharacterFormatter {
- template<typename FindResult> std::string operator()(const FindResult& match) const {
- std::ostringstream s;
- s << '\\' << std::hex << static_cast<int>(*match.begin());
- return s.str();
- }
+ template<typename FindResult> std::string operator()(const FindResult& match) const {
+ std::ostringstream s;
+ s << '\\' << std::hex << static_cast<int>(*match.begin());
+ return s.str();
+ }
};
struct EscapedCharacterFinder {
- template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) {
- for (; begin != end; ++begin) {
- if (*begin == '\\') {
- Iterator innerEnd = begin + 1;
- for (size_t i = 0; i < 2 && innerEnd != end; ++i, ++innerEnd) {
- }
- unsigned char value;
- if (getEscapeSequenceValue(std::string(begin + 1, innerEnd), value)) {
- return boost::iterator_range<Iterator>(begin, innerEnd);
- }
- }
- }
- return boost::iterator_range<Iterator>(end, end);
- }
+ template<typename Iterator> boost::iterator_range<Iterator> operator()(Iterator begin, Iterator end) {
+ for (; begin != end; ++begin) {
+ if (*begin == '\\') {
+ Iterator innerEnd = begin + 1;
+ for (size_t i = 0; i < 2 && innerEnd != end; ++i, ++innerEnd) {
+ }
+ unsigned char value;
+ if (getEscapeSequenceValue(std::string(begin + 1, innerEnd), value)) {
+ return boost::iterator_range<Iterator>(begin, innerEnd);
+ }
+ }
+ }
+ return boost::iterator_range<Iterator>(end, end);
+ }
};
struct EscapedCharacterFormatter {
- template<typename FindResult> std::string operator()(const FindResult& match) const {
- unsigned char value;
- if (getEscapeSequenceValue(std::string(match.begin() + 1, match.end()), value)) {
- return std::string(reinterpret_cast<const char*>(&value), 1);
- }
- return boost::copy_range<std::string>(match);
- }
+ template<typename FindResult> std::string operator()(const FindResult& match) const {
+ unsigned char value;
+ if (getEscapeSequenceValue(std::string(match.begin() + 1, match.end()), value)) {
+ return std::string(reinterpret_cast<const char*>(&value), 1);
+ }
+ return boost::copy_range<std::string>(match);
+ }
};
#endif
namespace Swift {
JID::JID(const char* jid) : valid_(true) {
- assert(jid);
- initializeFromString(std::string(jid));
+ assert(jid);
+ initializeFromString(std::string(jid));
}
JID::JID(const std::string& jid) : valid_(true) {
- initializeFromString(jid);
+ initializeFromString(jid);
}
JID::JID(const std::string& node, const std::string& domain) : valid_(true), hasResource_(false) {
- nameprepAndSetComponents(node, domain, "");
+ nameprepAndSetComponents(node, domain, "");
}
JID::JID(const std::string& node, const std::string& domain, const std::string& resource) : valid_(true), hasResource_(true) {
- if (resource.empty()) {
- valid_ = false;
- }
- nameprepAndSetComponents(node, domain, resource);
+ if (resource.empty()) {
+ valid_ = false;
+ }
+ nameprepAndSetComponents(node, domain, resource);
}
void JID::initializeFromString(const std::string& jid) {
- if (String::beginsWith(jid, '@')) {
- valid_ = false;
- return;
- }
-
- std::string bare, resource;
- size_t slashIndex = jid.find('/');
- if (slashIndex != jid.npos) {
- hasResource_ = true;
- bare = jid.substr(0, slashIndex);
- resource = jid.substr(slashIndex + 1, jid.npos);
- }
- else {
- hasResource_ = false;
- bare = jid;
- }
- std::pair<std::string,std::string> nodeAndDomain = String::getSplittedAtFirst(bare, '@');
- if (nodeAndDomain.second.empty()) {
- nameprepAndSetComponents("", nodeAndDomain.first, resource);
- }
- else {
- nameprepAndSetComponents(nodeAndDomain.first, nodeAndDomain.second, resource);
- }
+ if (String::beginsWith(jid, '@')) {
+ valid_ = false;
+ return;
+ }
+
+ std::string bare, resource;
+ size_t slashIndex = jid.find('/');
+ if (slashIndex != jid.npos) {
+ hasResource_ = true;
+ bare = jid.substr(0, slashIndex);
+ resource = jid.substr(slashIndex + 1, jid.npos);
+ }
+ else {
+ hasResource_ = false;
+ bare = jid;
+ }
+ std::pair<std::string,std::string> nodeAndDomain = String::getSplittedAtFirst(bare, '@');
+ if (nodeAndDomain.second.empty()) {
+ nameprepAndSetComponents("", nodeAndDomain.first, resource);
+ }
+ else {
+ nameprepAndSetComponents(nodeAndDomain.first, nodeAndDomain.second, resource);
+ }
}
void JID::nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource) {
- if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) {
- valid_ = false;
- return;
- }
+ if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) {
+ valid_ = false;
+ return;
+ }
#ifndef SWIFTEN_CACHE_JID_PREP
- node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep);
- domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep);
- resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
+ node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep);
+ domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep);
+ resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
#else
- boost::mutex::scoped_lock lock(namePrepCacheMutex);
-
- std::pair<PrepCache::iterator, bool> r;
-
- r = nodePrepCache.insert(std::make_pair(node, std::string()));
- if (r.second) {
- try {
- r.first->second = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep);
- }
- catch (...) {
- nodePrepCache.erase(r.first);
- valid_ = false;
- return;
- }
- }
- node_ = r.first->second;
-
- r = domainPrepCache.insert(std::make_pair(domain, std::string()));
- if (r.second) {
- try {
- r.first->second = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep);
- }
- catch (...) {
- domainPrepCache.erase(r.first);
- valid_ = false;
- return;
- }
- }
- domain_ = r.first->second;
-
- r = resourcePrepCache.insert(std::make_pair(resource, std::string()));
- if (r.second) {
- try {
- r.first->second = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
- }
- catch (...) {
- resourcePrepCache.erase(r.first);
- valid_ = false;
- return;
- }
- }
- resource_ = r.first->second;
+ boost::mutex::scoped_lock lock(namePrepCacheMutex);
+
+ std::pair<PrepCache::iterator, bool> r;
+
+ r = nodePrepCache.insert(std::make_pair(node, std::string()));
+ if (r.second) {
+ try {
+ r.first->second = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep);
+ }
+ catch (...) {
+ nodePrepCache.erase(r.first);
+ valid_ = false;
+ return;
+ }
+ }
+ node_ = r.first->second;
+
+ r = domainPrepCache.insert(std::make_pair(domain, std::string()));
+ if (r.second) {
+ try {
+ r.first->second = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep);
+ }
+ catch (...) {
+ domainPrepCache.erase(r.first);
+ valid_ = false;
+ return;
+ }
+ }
+ domain_ = r.first->second;
+
+ r = resourcePrepCache.insert(std::make_pair(resource, std::string()));
+ if (r.second) {
+ try {
+ r.first->second = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
+ }
+ catch (...) {
+ resourcePrepCache.erase(r.first);
+ valid_ = false;
+ return;
+ }
+ }
+ resource_ = r.first->second;
#endif
- if (domain_.empty()) {
- valid_ = false;
- return;
- }
+ if (domain_.empty()) {
+ valid_ = false;
+ return;
+ }
}
std::string JID::toString() const {
- std::string string;
- if (!node_.empty()) {
- string += node_ + "@";
- }
- string += domain_;
- if (!isBare()) {
- string += "/" + resource_;
- }
- return string;
+ std::string string;
+ if (!node_.empty()) {
+ string += node_ + "@";
+ }
+ string += domain_;
+ if (!isBare()) {
+ string += "/" + resource_;
+ }
+ return string;
}
int JID::compare(const Swift::JID& o, CompareType compareType) const {
- if (node_ < o.node_) { return -1; }
- if (node_ > o.node_) { return 1; }
- if (domain_ < o.domain_) { return -1; }
- if (domain_ > o.domain_) { return 1; }
- if (compareType == WithResource) {
- if (hasResource_ != o.hasResource_) {
- return hasResource_ ? 1 : -1;
- }
- if (resource_ < o.resource_) { return -1; }
- if (resource_ > o.resource_) { return 1; }
- }
- return 0;
+ if (node_ < o.node_) { return -1; }
+ if (node_ > o.node_) { return 1; }
+ if (domain_ < o.domain_) { return -1; }
+ if (domain_ > o.domain_) { return 1; }
+ if (compareType == WithResource) {
+ if (hasResource_ != o.hasResource_) {
+ return hasResource_ ? 1 : -1;
+ }
+ if (resource_ < o.resource_) { return -1; }
+ if (resource_ > o.resource_) { return 1; }
+ }
+ return 0;
}
std::string JID::getEscapedNode(const std::string& node) {
- std::string result;
- for (std::string::const_iterator i = node.begin(); i != node.end(); ++i) {
- if (std::find(escapedChars.begin(), escapedChars.end(), *i) != escapedChars.end()) {
- result += getEscaped(*i);
- continue;
- }
- else if (*i == '\\') {
- // Check if we have an escaped dissalowed character sequence
- std::string::const_iterator innerBegin = i + 1;
- if (innerBegin != node.end() && innerBegin + 1 != node.end()) {
- std::string::const_iterator innerEnd = innerBegin + 2;
- unsigned char value;
- if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) {
- result += getEscaped(*i);
- continue;
- }
- }
- }
- result += *i;
- }
- return result;
- //return boost::find_format_all_copy(node, UnescapedCharacterFinder(), UnescapedCharacterFormatter());
+ std::string result;
+ for (std::string::const_iterator i = node.begin(); i != node.end(); ++i) {
+ if (std::find(escapedChars.begin(), escapedChars.end(), *i) != escapedChars.end()) {
+ result += getEscaped(*i);
+ continue;
+ }
+ else if (*i == '\\') {
+ // Check if we have an escaped dissalowed character sequence
+ std::string::const_iterator innerBegin = i + 1;
+ if (innerBegin != node.end() && innerBegin + 1 != node.end()) {
+ std::string::const_iterator innerEnd = innerBegin + 2;
+ unsigned char value;
+ if (getEscapeSequenceValue(std::string(innerBegin, innerEnd), value)) {
+ result += getEscaped(*i);
+ continue;
+ }
+ }
+ }
+ result += *i;
+ }
+ return result;
+ //return boost::find_format_all_copy(node, UnescapedCharacterFinder(), UnescapedCharacterFormatter());
}
-
+
std::string JID::getUnescapedNode() const {
- std::string result;
- for (std::string::const_iterator j = node_.begin(); j != node_.end();) {
- if (*j == '\\') {
- std::string::const_iterator innerEnd = j + 1;
- for (size_t i = 0; i < 2 && innerEnd != node_.end(); ++i, ++innerEnd) {
- }
- unsigned char value;
- if (getEscapeSequenceValue(std::string(j + 1, innerEnd), value)) {
- result += std::string(reinterpret_cast<const char*>(&value), 1);
- j = innerEnd;
- continue;
- }
- }
- result += *j;
- ++j;
- }
- return result;
- //return boost::find_format_all_copy(node_, EscapedCharacterFinder(), EscapedCharacterFormatter());
+ std::string result;
+ for (std::string::const_iterator j = node_.begin(); j != node_.end();) {
+ if (*j == '\\') {
+ std::string::const_iterator innerEnd = j + 1;
+ for (size_t i = 0; i < 2 && innerEnd != node_.end(); ++i, ++innerEnd) {
+ }
+ unsigned char value;
+ if (getEscapeSequenceValue(std::string(j + 1, innerEnd), value)) {
+ result += std::string(reinterpret_cast<const char*>(&value), 1);
+ j = innerEnd;
+ continue;
+ }
+ }
+ result += *j;
+ ++j;
+ }
+ return result;
+ //return boost::find_format_all_copy(node_, EscapedCharacterFinder(), EscapedCharacterFormatter());
}
void JID::setIDNConverter(IDNConverter* converter) {
- idnConverter = converter;
+ idnConverter = converter;
}
std::ostream& operator<<(std::ostream& os, const JID& j) {
- os << j.toString();
- return os;
+ os << j.toString();
+ return os;
}
boost::optional<JID> JID::parse(const std::string& s) {
- JID jid(s);
- return jid.isValid() ? jid : boost::optional<JID>();
+ JID jid(s);
+ return jid.isValid() ? jid : boost::optional<JID>();
}
}
diff --git a/Swiften/JID/JID.h b/Swiften/JID/JID.h
index 2be7ca9..302e37e 100644
--- a/Swiften/JID/JID.h
+++ b/Swiften/JID/JID.h
@@ -14,185 +14,185 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class IDNConverter;
-
- /**
- * This represents the JID used in XMPP
- * (RFC6120 - http://tools.ietf.org/html/rfc6120 ).
- * For a description of format, see the RFC or page 14 of
- * XMPP: The Definitive Guide (Saint-Andre et al.)
- *
- * Particularly - a Bare JID is a JID without a resource part.
- *
- * A JID can be invalid (when isValid() returns false). No member methods are
- * guaranteed to work correctly if they do.
- */
- class SWIFTEN_API JID {
- public:
- enum CompareType {
- WithResource, WithoutResource
- };
-
- /**
- * Create a JID from its String representation.
- *
- * e.g.
- * wonderland.lit
- * wonderland.lit/rabbithole
- * alice@wonderland.lit
- * alice@wonderland.lit/TeaParty
- *
- * @param jid String representation. Invalid JID if empty or invalid.
- */
- JID(const std::string& jid = std::string());
-
- /**
- * See std::string constructor.
- *
- * Must not be NULL.
- */
- JID(const char*);
-
- /**
- * Create a bare JID from the node and domain parts.
- *
- * JID("node@domain") == JID("node", "domain")
- * unless you pass in empty values.
- *
- * @param node JID node part.
- * @param domain JID domain part.
- */
- JID(const std::string& node, const std::string& domain);
- /**
- * Create a bare JID from the node, domain and resource parts.
- *
- * JID("node@domain/resource") == JID("node", "domain", "resource")
- * unless you pass in empty values.
- *
- * @param node JID node part.
- * @param domain JID domain part.
- * @param resource JID resource part.
- */
- JID(const std::string& node, const std::string& domain, const std::string& resource);
-
- /**
- * @return Is a correctly-formatted JID.
- */
- bool isValid() const {
- return valid_;
- }
-
- /**
- * e.g. JID("node@domain").getNode() == "node"
- * @return could be empty.
- */
- const std::string& getNode() const {
- return node_;
- }
-
- /**
- * e.g. JID("node@domain").getDomain() == "domain"
- */
- const std::string& getDomain() const {
- return domain_;
- }
-
- /**
- * e.g. JID("node@domain/resource").getResource() == "resource"
- * @return could be empty.
- */
- const std::string& getResource() const {
- return resource_;
- }
-
- /**
- * Is a bare JID, i.e. has no resource part.
- */
- bool isBare() const {
- return !hasResource_;
- }
-
- /**
- * Returns the given node, escaped according to XEP-0106.
- * The resulting node is a valid node for a JID, whereas the input value can contain characters
- * that are not allowed.
- */
- static std::string getEscapedNode(const std::string& node);
-
- /**
- * Returns the node of the current JID, unescaped according to XEP-0106.
- */
- std::string getUnescapedNode() const;
-
- /**
- * Get the JID without a resource.
- * @return Invalid if the original is invalid.
- */
- JID toBare() const {
- JID result(*this);
- result.hasResource_ = false;
- result.resource_ = "";
- return result;
- }
-
- /**
- * Get the full JID with the supplied resource.
- */
- JID withResource(const std::string& resource) const {
- JID result(this->getNode(), this->getDomain(), resource);
- return result;
- }
-
- std::string toString() const;
-
- bool equals(const JID& o, CompareType compareType) const {
- return compare(o, compareType) == 0;
- }
-
- int compare(const JID& o, CompareType compareType) const;
-
- operator std::string() const {
- return toString();
- }
-
- bool operator<(const Swift::JID& b) const {
- return compare(b, Swift::JID::WithResource) < 0;
- }
-
- SWIFTEN_API friend std::ostream& operator<<(std::ostream& os, const Swift::JID& j);
-
- friend bool operator==(const Swift::JID& a, const Swift::JID& b) {
- return a.compare(b, Swift::JID::WithResource) == 0;
- }
-
- friend bool operator!=(const Swift::JID& a, const Swift::JID& b) {
- return a.compare(b, Swift::JID::WithResource) != 0;
- }
-
- /**
- * Returns an empty optional if the JID is invalid, and an
- * optional with a value if the JID is valid.
- */
- static boost::optional<JID> parse(const std::string&);
-
- /**
- * If Swiften was compiled with SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER (not default), use this method at
- * the beginning of the program to set an IDN converter to use for JID IDN conversions.
- * By default, this method shouldn't be used.
- */
- static void setIDNConverter(IDNConverter*);
-
- private:
- void nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource);
- void initializeFromString(const std::string&);
-
- private:
- bool valid_;
- std::string node_;
- std::string domain_;
- bool hasResource_;
- std::string resource_;
- };
-
- SWIFTEN_API std::ostream& operator<<(std::ostream& os, const Swift::JID& j);
+ class IDNConverter;
+
+ /**
+ * This represents the JID used in XMPP
+ * (RFC6120 - http://tools.ietf.org/html/rfc6120 ).
+ * For a description of format, see the RFC or page 14 of
+ * XMPP: The Definitive Guide (Saint-Andre et al.)
+ *
+ * Particularly - a Bare JID is a JID without a resource part.
+ *
+ * A JID can be invalid (when isValid() returns false). No member methods are
+ * guaranteed to work correctly if they do.
+ */
+ class SWIFTEN_API JID {
+ public:
+ enum CompareType {
+ WithResource, WithoutResource
+ };
+
+ /**
+ * Create a JID from its String representation.
+ *
+ * e.g.
+ * wonderland.lit
+ * wonderland.lit/rabbithole
+ * alice@wonderland.lit
+ * alice@wonderland.lit/TeaParty
+ *
+ * @param jid String representation. Invalid JID if empty or invalid.
+ */
+ JID(const std::string& jid = std::string());
+
+ /**
+ * See std::string constructor.
+ *
+ * Must not be NULL.
+ */
+ JID(const char*);
+
+ /**
+ * Create a bare JID from the node and domain parts.
+ *
+ * JID("node@domain") == JID("node", "domain")
+ * unless you pass in empty values.
+ *
+ * @param node JID node part.
+ * @param domain JID domain part.
+ */
+ JID(const std::string& node, const std::string& domain);
+ /**
+ * Create a bare JID from the node, domain and resource parts.
+ *
+ * JID("node@domain/resource") == JID("node", "domain", "resource")
+ * unless you pass in empty values.
+ *
+ * @param node JID node part.
+ * @param domain JID domain part.
+ * @param resource JID resource part.
+ */
+ JID(const std::string& node, const std::string& domain, const std::string& resource);
+
+ /**
+ * @return Is a correctly-formatted JID.
+ */
+ bool isValid() const {
+ return valid_;
+ }
+
+ /**
+ * e.g. JID("node@domain").getNode() == "node"
+ * @return could be empty.
+ */
+ const std::string& getNode() const {
+ return node_;
+ }
+
+ /**
+ * e.g. JID("node@domain").getDomain() == "domain"
+ */
+ const std::string& getDomain() const {
+ return domain_;
+ }
+
+ /**
+ * e.g. JID("node@domain/resource").getResource() == "resource"
+ * @return could be empty.
+ */
+ const std::string& getResource() const {
+ return resource_;
+ }
+
+ /**
+ * Is a bare JID, i.e. has no resource part.
+ */
+ bool isBare() const {
+ return !hasResource_;
+ }
+
+ /**
+ * Returns the given node, escaped according to XEP-0106.
+ * The resulting node is a valid node for a JID, whereas the input value can contain characters
+ * that are not allowed.
+ */
+ static std::string getEscapedNode(const std::string& node);
+
+ /**
+ * Returns the node of the current JID, unescaped according to XEP-0106.
+ */
+ std::string getUnescapedNode() const;
+
+ /**
+ * Get the JID without a resource.
+ * @return Invalid if the original is invalid.
+ */
+ JID toBare() const {
+ JID result(*this);
+ result.hasResource_ = false;
+ result.resource_ = "";
+ return result;
+ }
+
+ /**
+ * Get the full JID with the supplied resource.
+ */
+ JID withResource(const std::string& resource) const {
+ JID result(this->getNode(), this->getDomain(), resource);
+ return result;
+ }
+
+ std::string toString() const;
+
+ bool equals(const JID& o, CompareType compareType) const {
+ return compare(o, compareType) == 0;
+ }
+
+ int compare(const JID& o, CompareType compareType) const;
+
+ operator std::string() const {
+ return toString();
+ }
+
+ bool operator<(const Swift::JID& b) const {
+ return compare(b, Swift::JID::WithResource) < 0;
+ }
+
+ SWIFTEN_API friend std::ostream& operator<<(std::ostream& os, const Swift::JID& j);
+
+ friend bool operator==(const Swift::JID& a, const Swift::JID& b) {
+ return a.compare(b, Swift::JID::WithResource) == 0;
+ }
+
+ friend bool operator!=(const Swift::JID& a, const Swift::JID& b) {
+ return a.compare(b, Swift::JID::WithResource) != 0;
+ }
+
+ /**
+ * Returns an empty optional if the JID is invalid, and an
+ * optional with a value if the JID is valid.
+ */
+ static boost::optional<JID> parse(const std::string&);
+
+ /**
+ * If Swiften was compiled with SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER (not default), use this method at
+ * the beginning of the program to set an IDN converter to use for JID IDN conversions.
+ * By default, this method shouldn't be used.
+ */
+ static void setIDNConverter(IDNConverter*);
+
+ private:
+ void nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource);
+ void initializeFromString(const std::string&);
+
+ private:
+ bool valid_;
+ std::string node_;
+ std::string domain_;
+ bool hasResource_;
+ std::string resource_;
+ };
+
+ SWIFTEN_API std::ostream& operator<<(std::ostream& os, const Swift::JID& j);
}
diff --git a/Swiften/JID/UnitTest/JIDTest.cpp b/Swiften/JID/UnitTest/JIDTest.cpp
index 8f43576..ffe28a1 100644
--- a/Swiften/JID/UnitTest/JIDTest.cpp
+++ b/Swiften/JID/UnitTest/JIDTest.cpp
@@ -13,405 +13,405 @@ using namespace Swift;
class JIDTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(JIDTest);
- CPPUNIT_TEST(testConstructorWithString);
- CPPUNIT_TEST(testConstructorWithString_NoResource);
- CPPUNIT_TEST(testConstructorWithString_NoNode);
- CPPUNIT_TEST(testConstructorWithString_EmptyResource);
- CPPUNIT_TEST(testConstructorWithString_OnlyDomain);
- CPPUNIT_TEST(testConstructorWithString_InvalidDomain);
- CPPUNIT_TEST(testConstructorWithString_UpperCaseNode);
- CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain);
- CPPUNIT_TEST(testConstructorWithString_UpperCaseResource);
- CPPUNIT_TEST(testConstructorWithString_EmptyNode);
- CPPUNIT_TEST(testConstructorWithString_IllegalResource);
- CPPUNIT_TEST(testConstructorWithString_SpacesInNode);
- CPPUNIT_TEST(testConstructorWithStrings);
- CPPUNIT_TEST(testConstructorWithStrings_EmptyDomain);
- CPPUNIT_TEST(testConstructorWithStrings_EmptyResource);
- CPPUNIT_TEST(testIsBare);
- CPPUNIT_TEST(testIsBare_NotBare);
- CPPUNIT_TEST(testToBare);
- CPPUNIT_TEST(testToBare_EmptyNode);
- CPPUNIT_TEST(testToBare_EmptyResource);
- CPPUNIT_TEST(testToString);
- CPPUNIT_TEST(testToString_EmptyNode);
- CPPUNIT_TEST(testToString_EmptyResource);
- CPPUNIT_TEST(testToString_NoResource);
- CPPUNIT_TEST(testCompare_SmallerNode);
- CPPUNIT_TEST(testCompare_LargerNode);
- CPPUNIT_TEST(testCompare_SmallerDomain);
- CPPUNIT_TEST(testCompare_LargerDomain);
- CPPUNIT_TEST(testCompare_SmallerResource);
- CPPUNIT_TEST(testCompare_LargerResource);
- CPPUNIT_TEST(testCompare_Equal);
- CPPUNIT_TEST(testCompare_EqualWithoutResource);
- CPPUNIT_TEST(testCompare_NoResourceAndEmptyResource);
- CPPUNIT_TEST(testCompare_EmptyResourceAndNoResource);
- CPPUNIT_TEST(testEquals);
- CPPUNIT_TEST(testEquals_NotEqual);
- CPPUNIT_TEST(testEquals_WithoutResource);
- CPPUNIT_TEST(testSmallerThan);
- CPPUNIT_TEST(testSmallerThan_Equal);
- CPPUNIT_TEST(testSmallerThan_Larger);
- CPPUNIT_TEST(testHasResource);
- CPPUNIT_TEST(testHasResource_NoResource);
- CPPUNIT_TEST(testGetEscapedNode);
- CPPUNIT_TEST(testGetEscapedNode_XEP106Examples);
- CPPUNIT_TEST(testGetEscapedNode_BackslashAtEnd);
- CPPUNIT_TEST(testGetUnescapedNode);
- CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- JIDTest() {}
-
- void testConstructorWithString() {
- JID testling("foo@bar/baz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
- CPPUNIT_ASSERT(!testling.isBare());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_NoResource() {
- JID testling("foo@bar");
-
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource());
- CPPUNIT_ASSERT(testling.isBare());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_EmptyResource() {
- JID testling("bar/");
-
- CPPUNIT_ASSERT(testling.isValid());
- CPPUNIT_ASSERT(!testling.isBare());
- }
-
- void testConstructorWithString_NoNode() {
- JID testling("bar/baz");
-
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
- CPPUNIT_ASSERT(!testling.isBare());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_OnlyDomain() {
- JID testling("bar");
-
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource());
- CPPUNIT_ASSERT(testling.isBare());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_InvalidDomain() {
- CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid());
- }
-
- void testConstructorWithString_UpperCaseNode() {
- JID testling("Fo\xCE\xA9@bar");
-
- CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_UpperCaseDomain() {
- JID testling("Fo\xCE\xA9");
-
- CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getDomain());
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_UpperCaseResource() {
- JID testling("bar/Fo\xCE\xA9");
-
- CPPUNIT_ASSERT_EQUAL(testling.getResource(), std::string("Fo\xCE\xA9"));
- CPPUNIT_ASSERT(testling.isValid());
- }
-
- void testConstructorWithString_EmptyNode() {
- JID testling("@bar");
-
- CPPUNIT_ASSERT(!testling.isValid());
- }
-
- void testConstructorWithString_IllegalResource() {
- JID testling("foo@bar.com/\xd8\xb1\xd9\x85\xd9\x82\xd9\x87\x20\xd8\xaa\xd8\xb1\xd9\x86\xd8\xb3\x20");
+ CPPUNIT_TEST_SUITE(JIDTest);
+ CPPUNIT_TEST(testConstructorWithString);
+ CPPUNIT_TEST(testConstructorWithString_NoResource);
+ CPPUNIT_TEST(testConstructorWithString_NoNode);
+ CPPUNIT_TEST(testConstructorWithString_EmptyResource);
+ CPPUNIT_TEST(testConstructorWithString_OnlyDomain);
+ CPPUNIT_TEST(testConstructorWithString_InvalidDomain);
+ CPPUNIT_TEST(testConstructorWithString_UpperCaseNode);
+ CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain);
+ CPPUNIT_TEST(testConstructorWithString_UpperCaseResource);
+ CPPUNIT_TEST(testConstructorWithString_EmptyNode);
+ CPPUNIT_TEST(testConstructorWithString_IllegalResource);
+ CPPUNIT_TEST(testConstructorWithString_SpacesInNode);
+ CPPUNIT_TEST(testConstructorWithStrings);
+ CPPUNIT_TEST(testConstructorWithStrings_EmptyDomain);
+ CPPUNIT_TEST(testConstructorWithStrings_EmptyResource);
+ CPPUNIT_TEST(testIsBare);
+ CPPUNIT_TEST(testIsBare_NotBare);
+ CPPUNIT_TEST(testToBare);
+ CPPUNIT_TEST(testToBare_EmptyNode);
+ CPPUNIT_TEST(testToBare_EmptyResource);
+ CPPUNIT_TEST(testToString);
+ CPPUNIT_TEST(testToString_EmptyNode);
+ CPPUNIT_TEST(testToString_EmptyResource);
+ CPPUNIT_TEST(testToString_NoResource);
+ CPPUNIT_TEST(testCompare_SmallerNode);
+ CPPUNIT_TEST(testCompare_LargerNode);
+ CPPUNIT_TEST(testCompare_SmallerDomain);
+ CPPUNIT_TEST(testCompare_LargerDomain);
+ CPPUNIT_TEST(testCompare_SmallerResource);
+ CPPUNIT_TEST(testCompare_LargerResource);
+ CPPUNIT_TEST(testCompare_Equal);
+ CPPUNIT_TEST(testCompare_EqualWithoutResource);
+ CPPUNIT_TEST(testCompare_NoResourceAndEmptyResource);
+ CPPUNIT_TEST(testCompare_EmptyResourceAndNoResource);
+ CPPUNIT_TEST(testEquals);
+ CPPUNIT_TEST(testEquals_NotEqual);
+ CPPUNIT_TEST(testEquals_WithoutResource);
+ CPPUNIT_TEST(testSmallerThan);
+ CPPUNIT_TEST(testSmallerThan_Equal);
+ CPPUNIT_TEST(testSmallerThan_Larger);
+ CPPUNIT_TEST(testHasResource);
+ CPPUNIT_TEST(testHasResource_NoResource);
+ CPPUNIT_TEST(testGetEscapedNode);
+ CPPUNIT_TEST(testGetEscapedNode_XEP106Examples);
+ CPPUNIT_TEST(testGetEscapedNode_BackslashAtEnd);
+ CPPUNIT_TEST(testGetUnescapedNode);
+ CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ JIDTest() {}
+
+ void testConstructorWithString() {
+ JID testling("foo@bar/baz");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
+ CPPUNIT_ASSERT(!testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_NoResource() {
+ JID testling("foo@bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource());
+ CPPUNIT_ASSERT(testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_EmptyResource() {
+ JID testling("bar/");
+
+ CPPUNIT_ASSERT(testling.isValid());
+ CPPUNIT_ASSERT(!testling.isBare());
+ }
+
+ void testConstructorWithString_NoNode() {
+ JID testling("bar/baz");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
+ CPPUNIT_ASSERT(!testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_OnlyDomain() {
+ JID testling("bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource());
+ CPPUNIT_ASSERT(testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_InvalidDomain() {
+ CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid());
+ }
+
+ void testConstructorWithString_UpperCaseNode() {
+ JID testling("Fo\xCE\xA9@bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_UpperCaseDomain() {
+ JID testling("Fo\xCE\xA9");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getDomain());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_UpperCaseResource() {
+ JID testling("bar/Fo\xCE\xA9");
+
+ CPPUNIT_ASSERT_EQUAL(testling.getResource(), std::string("Fo\xCE\xA9"));
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_EmptyNode() {
+ JID testling("@bar");
+
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
+
+ void testConstructorWithString_IllegalResource() {
+ JID testling("foo@bar.com/\xd8\xb1\xd9\x85\xd9\x82\xd9\x87\x20\xd8\xaa\xd8\xb1\xd9\x86\xd8\xb3\x20");
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testConstructorWithString_SpacesInNode() {
- CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid());
- CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid());
- }
+ void testConstructorWithString_SpacesInNode() {
+ CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid());
+ CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid());
+ }
- void testConstructorWithStrings() {
- JID testling("foo", "bar", "baz");
+ void testConstructorWithStrings() {
+ JID testling("foo", "bar", "baz");
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
- CPPUNIT_ASSERT(testling.isValid());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("baz"), testling.getResource());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
- void testConstructorWithStrings_EmptyDomain() {
- JID testling("foo", "", "baz");
+ void testConstructorWithStrings_EmptyDomain() {
+ JID testling("foo", "", "baz");
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testConstructorWithStrings_EmptyResource() {
- JID testling("foo", "bar", "");
+ void testConstructorWithStrings_EmptyResource() {
+ JID testling("foo", "bar", "");
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testIsBare() {
- CPPUNIT_ASSERT(JID("foo@bar").isBare());
- }
+ void testIsBare() {
+ CPPUNIT_ASSERT(JID("foo@bar").isBare());
+ }
- void testIsBare_NotBare() {
- CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare());
- }
+ void testIsBare_NotBare() {
+ CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare());
+ }
- void testToBare() {
- JID testling("foo@bar/baz");
+ void testToBare() {
+ JID testling("foo@bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.toBare().getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
- CPPUNIT_ASSERT(testling.toBare().isBare());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.toBare().getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
+ CPPUNIT_ASSERT(testling.toBare().isBare());
+ }
- void testToBare_EmptyNode() {
- JID testling("bar/baz");
+ void testToBare_EmptyNode() {
+ JID testling("bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
- CPPUNIT_ASSERT(testling.toBare().isBare());
- CPPUNIT_ASSERT(testling.isValid());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
+ CPPUNIT_ASSERT(testling.toBare().isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
- void testToBare_EmptyResource() {
- JID testling("bar/");
+ void testToBare_EmptyResource() {
+ JID testling("bar/");
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
- CPPUNIT_ASSERT(testling.toBare().isBare());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
+ CPPUNIT_ASSERT(testling.toBare().isBare());
+ }
- void testToString() {
- JID testling("foo@bar/baz");
+ void testToString() {
+ JID testling("foo@bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString());
+ }
- void testToString_EmptyNode() {
- JID testling("bar/baz");
+ void testToString_EmptyNode() {
+ JID testling("bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString());
+ }
- void testToString_NoResource() {
- JID testling("foo@bar");
+ void testToString_NoResource() {
+ JID testling("foo@bar");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString());
+ }
- void testToString_EmptyResource() {
- JID testling("foo@bar/");
+ void testToString_EmptyResource() {
+ JID testling("foo@bar/");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/"), testling.toString());
+ }
- void testCompare_SmallerNode() {
- JID testling1("a@c");
- JID testling2("b@b");
+ void testCompare_SmallerNode() {
+ JID testling1("a@c");
+ JID testling2("b@b");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_LargerNode() {
- JID testling1("c@a");
- JID testling2("b@b");
+ void testCompare_LargerNode() {
+ JID testling1("c@a");
+ JID testling2("b@b");
- CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_SmallerDomain() {
- JID testling1("x@a/c");
- JID testling2("x@b/b");
+ void testCompare_SmallerDomain() {
+ JID testling1("x@a/c");
+ JID testling2("x@b/b");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_LargerDomain() {
- JID testling1("x@b/b");
- JID testling2("x@a/c");
+ void testCompare_LargerDomain() {
+ JID testling1("x@b/b");
+ JID testling2("x@a/c");
- CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_SmallerResource() {
- JID testling1("x@y/a");
- JID testling2("x@y/b");
+ void testCompare_SmallerResource() {
+ JID testling1("x@y/a");
+ JID testling2("x@y/b");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_LargerResource() {
- JID testling1("x@y/b");
- JID testling2("x@y/a");
+ void testCompare_LargerResource() {
+ JID testling1("x@y/b");
+ JID testling2("x@y/a");
- CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_Equal() {
- JID testling1("x@y/z");
- JID testling2("x@y/z");
+ void testCompare_Equal() {
+ JID testling1("x@y/z");
+ JID testling2("x@y/z");
- CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_EqualWithoutResource() {
- JID testling1("x@y/a");
- JID testling2("x@y/b");
+ void testCompare_EqualWithoutResource() {
+ JID testling1("x@y/a");
+ JID testling2("x@y/b");
- CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithoutResource));
- }
+ CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithoutResource));
+ }
- void testCompare_NoResourceAndEmptyResource() {
- JID testling1("x@y/");
- JID testling2("x@y");
+ void testCompare_NoResourceAndEmptyResource() {
+ JID testling1("x@y/");
+ JID testling2("x@y");
- CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_EmptyResourceAndNoResource() {
- JID testling1("x@y");
- JID testling2("x@y/");
+ void testCompare_EmptyResourceAndNoResource() {
+ JID testling1("x@y");
+ JID testling2("x@y/");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
- void testEquals() {
- JID testling1("x@y/c");
- JID testling2("x@y/c");
+ void testEquals() {
+ JID testling1("x@y/c");
+ JID testling2("x@y/c");
- CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithResource));
- }
-
- void testEquals_NotEqual() {
- JID testling1("x@y/c");
- JID testling2("x@y/d");
-
- CPPUNIT_ASSERT(!testling1.equals(testling2, JID::WithResource));
- }
-
- void testEquals_WithoutResource() {
- JID testling1("x@y/c");
- JID testling2("x@y/d");
-
- CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithoutResource));
- }
-
- void testSmallerThan() {
- JID testling1("x@y/c");
- JID testling2("x@y/d");
-
- CPPUNIT_ASSERT(testling1 < testling2);
- }
-
- void testSmallerThan_Equal() {
- JID testling1("x@y/d");
- JID testling2("x@y/d");
-
- CPPUNIT_ASSERT(!(testling1 < testling2));
- }
-
- void testSmallerThan_Larger() {
- JID testling1("x@y/d");
- JID testling2("x@y/c");
-
- CPPUNIT_ASSERT(!(testling1 < testling2));
- }
-
- void testHasResource() {
- JID testling("x@y/d");
-
- CPPUNIT_ASSERT(!testling.isBare());
- }
-
- void testHasResource_NoResource() {
- JID testling("x@y");
-
- CPPUNIT_ASSERT(testling.isBare());
- }
-
- void testGetEscapedNode() {
- std::string escaped = JID::getEscapedNode("alice@wonderland.lit");
- CPPUNIT_ASSERT_EQUAL(std::string("alice\\40wonderland.lit"), escaped);
-
- escaped = JID::getEscapedNode("\\& \" ' / <\\\\> @ :\\3a\\40");
- CPPUNIT_ASSERT_EQUAL(std::string("\\\\26\\20\\22\\20\\27\\20\\2f\\20\\3c\\\\\\3e\\20\\40\\20\\3a\\5c3a\\5c40"), escaped);
- }
-
- void testGetEscapedNode_XEP106Examples() {
- CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID::getEscapedNode("\\2plus\\2is\\4"));
- CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID::getEscapedNode("foo\\bar"));
- CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID::getEscapedNode("foob\\41r"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("space cadet"), std::string("space\\20cadet"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("call me \"ishmael\""), std::string("call\\20me\\20\\22ishmael\\22"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("at&t guy"), std::string("at\\26t\\20guy"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("d'artagnan"), std::string("d\\27artagnan"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("/.fanboy"), std::string("\\2f.fanboy"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("::foo::"), std::string("\\3a\\3afoo\\3a\\3a"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("<foo>"), std::string("\\3cfoo\\3e"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("user@host"), std::string("user\\40host"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\net"), std::string("c\\3a\\net"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\\\net"), std::string("c\\3a\\\\net"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\cool stuff"), std::string("c\\3a\\cool\\20stuff"));
- CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\5commas"), std::string("c\\3a\\5c5commas"));
- }
-
- void testGetEscapedNode_BackslashAtEnd() {
- CPPUNIT_ASSERT_EQUAL(std::string("foo\\"), JID::getEscapedNode("foo\\"));
- }
-
- void testGetUnescapedNode() {
- std::string input = "\\& \" ' / <\\\\> @ : \\5c\\40";
- JID testling(JID::getEscapedNode(input) + "@y");
- CPPUNIT_ASSERT(testling.isValid());
- CPPUNIT_ASSERT_EQUAL(input, testling.getUnescapedNode());
- }
-
- void testGetUnescapedNode_XEP106Examples() {
- CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID("\\2plus\\2is\\4@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID("foo\\bar@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID("foob\\41r@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("space cadet"), JID("space\\20cadet@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("call me \"ishmael\""), JID("call\\20me\\20\\22ishmael\\22@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("at&t guy"), JID("at\\26t\\20guy@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("d'artagnan"), JID("d\\27artagnan@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("/.fanboy"), JID("\\2f.fanboy@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("::foo::"), JID("\\3a\\3afoo\\3a\\3a@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("<foo>"), JID("\\3cfoo\\3e@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("user@host"), JID("user\\40host@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("c:\\net"), JID("c\\3a\\net@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("c:\\\\net"), JID("c\\3a\\\\net@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("c:\\cool stuff"), JID("c\\3a\\cool\\20stuff@example.com").getUnescapedNode());
- CPPUNIT_ASSERT_EQUAL(std::string("c:\\5commas"), JID("c\\3a\\5c5commas@example.com").getUnescapedNode());
- }
+ CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithResource));
+ }
+
+ void testEquals_NotEqual() {
+ JID testling1("x@y/c");
+ JID testling2("x@y/d");
+
+ CPPUNIT_ASSERT(!testling1.equals(testling2, JID::WithResource));
+ }
+
+ void testEquals_WithoutResource() {
+ JID testling1("x@y/c");
+ JID testling2("x@y/d");
+
+ CPPUNIT_ASSERT(testling1.equals(testling2, JID::WithoutResource));
+ }
+
+ void testSmallerThan() {
+ JID testling1("x@y/c");
+ JID testling2("x@y/d");
+
+ CPPUNIT_ASSERT(testling1 < testling2);
+ }
+
+ void testSmallerThan_Equal() {
+ JID testling1("x@y/d");
+ JID testling2("x@y/d");
+
+ CPPUNIT_ASSERT(!(testling1 < testling2));
+ }
+
+ void testSmallerThan_Larger() {
+ JID testling1("x@y/d");
+ JID testling2("x@y/c");
+
+ CPPUNIT_ASSERT(!(testling1 < testling2));
+ }
+
+ void testHasResource() {
+ JID testling("x@y/d");
+
+ CPPUNIT_ASSERT(!testling.isBare());
+ }
+
+ void testHasResource_NoResource() {
+ JID testling("x@y");
+
+ CPPUNIT_ASSERT(testling.isBare());
+ }
+
+ void testGetEscapedNode() {
+ std::string escaped = JID::getEscapedNode("alice@wonderland.lit");
+ CPPUNIT_ASSERT_EQUAL(std::string("alice\\40wonderland.lit"), escaped);
+
+ escaped = JID::getEscapedNode("\\& \" ' / <\\\\> @ :\\3a\\40");
+ CPPUNIT_ASSERT_EQUAL(std::string("\\\\26\\20\\22\\20\\27\\20\\2f\\20\\3c\\\\\\3e\\20\\40\\20\\3a\\5c3a\\5c40"), escaped);
+ }
+
+ void testGetEscapedNode_XEP106Examples() {
+ CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID::getEscapedNode("\\2plus\\2is\\4"));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID::getEscapedNode("foo\\bar"));
+ CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID::getEscapedNode("foob\\41r"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("space cadet"), std::string("space\\20cadet"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("call me \"ishmael\""), std::string("call\\20me\\20\\22ishmael\\22"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("at&t guy"), std::string("at\\26t\\20guy"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("d'artagnan"), std::string("d\\27artagnan"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("/.fanboy"), std::string("\\2f.fanboy"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("::foo::"), std::string("\\3a\\3afoo\\3a\\3a"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("<foo>"), std::string("\\3cfoo\\3e"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("user@host"), std::string("user\\40host"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\net"), std::string("c\\3a\\net"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\\\net"), std::string("c\\3a\\\\net"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\cool stuff"), std::string("c\\3a\\cool\\20stuff"));
+ CPPUNIT_ASSERT_EQUAL(JID::getEscapedNode("c:\\5commas"), std::string("c\\3a\\5c5commas"));
+ }
+
+ void testGetEscapedNode_BackslashAtEnd() {
+ CPPUNIT_ASSERT_EQUAL(std::string("foo\\"), JID::getEscapedNode("foo\\"));
+ }
+
+ void testGetUnescapedNode() {
+ std::string input = "\\& \" ' / <\\\\> @ : \\5c\\40";
+ JID testling(JID::getEscapedNode(input) + "@y");
+ CPPUNIT_ASSERT(testling.isValid());
+ CPPUNIT_ASSERT_EQUAL(input, testling.getUnescapedNode());
+ }
+
+ void testGetUnescapedNode_XEP106Examples() {
+ CPPUNIT_ASSERT_EQUAL(std::string("\\2plus\\2is\\4"), JID("\\2plus\\2is\\4@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("foo\\bar"), JID("foo\\bar@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("foob\\41r"), JID("foob\\41r@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("space cadet"), JID("space\\20cadet@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("call me \"ishmael\""), JID("call\\20me\\20\\22ishmael\\22@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("at&t guy"), JID("at\\26t\\20guy@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("d'artagnan"), JID("d\\27artagnan@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("/.fanboy"), JID("\\2f.fanboy@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("::foo::"), JID("\\3a\\3afoo\\3a\\3a@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("<foo>"), JID("\\3cfoo\\3e@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("user@host"), JID("user\\40host@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("c:\\net"), JID("c\\3a\\net@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("c:\\\\net"), JID("c\\3a\\\\net@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("c:\\cool stuff"), JID("c\\3a\\cool\\20stuff@example.com").getUnescapedNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("c:\\5commas"), JID("c\\3a\\5c5commas@example.com").getUnescapedNode());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(JIDTest);
diff --git a/Swiften/Jingle/AbstractJingleSessionListener.cpp b/Swiften/Jingle/AbstractJingleSessionListener.cpp
index c533f12..791dcb3 100644
--- a/Swiften/Jingle/AbstractJingleSessionListener.cpp
+++ b/Swiften/Jingle/AbstractJingleSessionListener.cpp
@@ -11,31 +11,31 @@
using namespace Swift;
void AbstractJingleSessionListener::handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
void AbstractJingleSessionListener::handleTransportInfoAcknowledged(const std::string&) {
diff --git a/Swiften/Jingle/AbstractJingleSessionListener.h b/Swiften/Jingle/AbstractJingleSessionListener.h
index 6256506..678f173 100644
--- a/Swiften/Jingle/AbstractJingleSessionListener.h
+++ b/Swiften/Jingle/AbstractJingleSessionListener.h
@@ -11,16 +11,16 @@
#include <Swiften/Jingle/JingleSessionListener.h>
namespace Swift {
- class SWIFTEN_API AbstractJingleSessionListener : public JingleSessionListener {
- public:
- virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
- virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE;
- virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
- virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE;
- };
+ class SWIFTEN_API AbstractJingleSessionListener : public JingleSessionListener {
+ public:
+ virtual void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Jingle/FakeJingleSession.cpp b/Swiften/Jingle/FakeJingleSession.cpp
index fae3425..ec792ab 100644
--- a/Swiften/Jingle/FakeJingleSession.cpp
+++ b/Swiften/Jingle/FakeJingleSession.cpp
@@ -26,56 +26,56 @@ FakeJingleSession::~FakeJingleSession() {
}
void FakeJingleSession::sendInitiate(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) {
- calledCommands.push_back(InitiateCall(id, desc, payload));
+ calledCommands.push_back(InitiateCall(id, desc, payload));
}
void FakeJingleSession::sendTerminate(JinglePayload::Reason::Type reason) {
- calledCommands.push_back(TerminateCall(reason));
+ calledCommands.push_back(TerminateCall(reason));
}
void FakeJingleSession::sendInfo(boost::shared_ptr<Payload> payload) {
- calledCommands.push_back(InfoCall(payload));
+ calledCommands.push_back(InfoCall(payload));
}
void FakeJingleSession::sendAccept(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) {
- calledCommands.push_back(AcceptCall(id, desc, payload));
+ calledCommands.push_back(AcceptCall(id, desc, payload));
}
std::string FakeJingleSession::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref payload) {
- calledCommands.push_back(InfoTransportCall(id, payload));
- return idGenerator.generateID();
+ calledCommands.push_back(InfoTransportCall(id, payload));
+ return idGenerator.generateID();
}
void FakeJingleSession::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref payload) {
- calledCommands.push_back(AcceptTransportCall(id, payload));
+ calledCommands.push_back(AcceptTransportCall(id, payload));
}
void FakeJingleSession::sendTransportReject(const JingleContentID& id, JingleTransportPayload::ref payload) {
- calledCommands.push_back(RejectTransportCall(id, payload));
+ calledCommands.push_back(RejectTransportCall(id, payload));
}
void FakeJingleSession::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref payload) {
- calledCommands.push_back(ReplaceTransportCall(id, payload));
+ calledCommands.push_back(ReplaceTransportCall(id, payload));
}
void FakeJingleSession::handleTransportReplaceReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) {
- notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport);
+ notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport);
}
void FakeJingleSession::handleTransportAcceptReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) {
- notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport);
+ notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport);
}
void FakeJingleSession::handleTransportInfoReceived(const JingleContentID& contentID, JingleTransportPayload::ref transport) {
- notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport);
+ notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport);
}
void FakeJingleSession::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
- notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, reason);
+ notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, reason);
}
void FakeJingleSession::handleSessionAcceptReceived(const JingleContentID& contentID, boost::shared_ptr<JingleDescription> desc, boost::shared_ptr<JingleTransportPayload> payload) {
- notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, desc, payload);
+ notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, desc, payload);
}
}
diff --git a/Swiften/Jingle/FakeJingleSession.h b/Swiften/Jingle/FakeJingleSession.h
index dc7e56a..0107384 100644
--- a/Swiften/Jingle/FakeJingleSession.h
+++ b/Swiften/Jingle/FakeJingleSession.h
@@ -28,87 +28,87 @@
#include <Swiften/Jingle/JingleSession.h>
namespace Swift {
- class JingleContentID;
-
- class SWIFTEN_API FakeJingleSession : public JingleSession {
- public:
- struct InitiateCall {
- InitiateCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
- JingleContentID id;
- JingleDescription::ref description;
- JingleTransportPayload::ref payload;
- };
-
- struct TerminateCall {
- TerminateCall(JinglePayload::Reason::Type r) : reason(r) {}
- JinglePayload::Reason::Type reason;
- };
-
- struct InfoCall {
- InfoCall(boost::shared_ptr<Payload> info) : payload(info) {}
- boost::shared_ptr<Payload> payload;
- };
-
- struct AcceptCall {
- AcceptCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
- JingleContentID id;
- JingleDescription::ref description;
- JingleTransportPayload::ref payload;
- };
-
- struct InfoTransportCall {
- InfoTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
- JingleContentID id;
- JingleTransportPayload::ref payload;
- };
-
- struct AcceptTransportCall {
- AcceptTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
- JingleContentID id;
- JingleTransportPayload::ref payload;
- };
-
- struct RejectTransportCall {
- RejectTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
- JingleContentID id;
- JingleTransportPayload::ref payload;
- };
-
- struct ReplaceTransportCall {
- ReplaceTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
- JingleContentID id;
- JingleTransportPayload::ref payload;
- };
-
- typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command;
-
- public:
- typedef boost::shared_ptr<FakeJingleSession> ref;
-
- FakeJingleSession(const JID& initiator, const std::string& id);
- virtual ~FakeJingleSession();
-
- virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
- virtual void sendTerminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
- virtual void sendInfo(boost::shared_ptr<Payload>) SWIFTEN_OVERRIDE;
- virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) SWIFTEN_OVERRIDE;
- virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
- virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
- virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
- virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
-
- void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>);
- void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>);
- void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>);
-
- void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref);
- void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
- void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
- void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
- void handleTransportInfoAcknowledged(const std::string& id);
-
- public:
- std::vector<Command> calledCommands;
- SimpleIDGenerator idGenerator;
- };
+ class JingleContentID;
+
+ class SWIFTEN_API FakeJingleSession : public JingleSession {
+ public:
+ struct InitiateCall {
+ InitiateCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
+ JingleContentID id;
+ JingleDescription::ref description;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct TerminateCall {
+ TerminateCall(JinglePayload::Reason::Type r) : reason(r) {}
+ JinglePayload::Reason::Type reason;
+ };
+
+ struct InfoCall {
+ InfoCall(boost::shared_ptr<Payload> info) : payload(info) {}
+ boost::shared_ptr<Payload> payload;
+ };
+
+ struct AcceptCall {
+ AcceptCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
+ JingleContentID id;
+ JingleDescription::ref description;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct InfoTransportCall {
+ InfoTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct AcceptTransportCall {
+ AcceptTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct RejectTransportCall {
+ RejectTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct ReplaceTransportCall {
+ ReplaceTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command;
+
+ public:
+ typedef boost::shared_ptr<FakeJingleSession> ref;
+
+ FakeJingleSession(const JID& initiator, const std::string& id);
+ virtual ~FakeJingleSession();
+
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
+ virtual void sendTerminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
+ virtual void sendInfo(boost::shared_ptr<Payload>) SWIFTEN_OVERRIDE;
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) SWIFTEN_OVERRIDE;
+ virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE;
+
+ void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>);
+ void handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>);
+ void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>);
+
+ void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref);
+ void handleTransportAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
+ void handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
+ void handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>);
+ void handleTransportInfoAcknowledged(const std::string& id);
+
+ public:
+ std::vector<Command> calledCommands;
+ SimpleIDGenerator idGenerator;
+ };
}
diff --git a/Swiften/Jingle/IncomingJingleSessionHandler.h b/Swiften/Jingle/IncomingJingleSessionHandler.h
index fba9acc..4c30f7c 100644
--- a/Swiften/Jingle/IncomingJingleSessionHandler.h
+++ b/Swiften/Jingle/IncomingJingleSessionHandler.h
@@ -10,10 +10,10 @@
#include <Swiften/Jingle/JingleSession.h>
namespace Swift {
- class SWIFTEN_API IncomingJingleSessionHandler {
- public:
- virtual ~IncomingJingleSessionHandler();
+ class SWIFTEN_API IncomingJingleSessionHandler {
+ public:
+ virtual ~IncomingJingleSessionHandler();
- virtual bool handleIncomingJingleSession(JingleSession::ref, const std::vector<JingleContentPayload::ref>& contents, const JID& recipient) = 0;
- };
+ virtual bool handleIncomingJingleSession(JingleSession::ref, const std::vector<JingleContentPayload::ref>& contents, const JID& recipient) = 0;
+ };
}
diff --git a/Swiften/Jingle/Jingle.h b/Swiften/Jingle/Jingle.h
index bf05b1c..13c235b 100644
--- a/Swiften/Jingle/Jingle.h
+++ b/Swiften/Jingle/Jingle.h
@@ -11,15 +11,15 @@
#include <Swiften/Elements/JingleContentPayload.h>
namespace Swift {
- namespace Jingle {
- template<typename T>
- JingleContentPayload::ref getContentWithDescription(const std::vector<JingleContentPayload::ref>& contents) {
- for (size_t i = 0; i < contents.size(); ++i) {
- if (contents[i]->getDescription<T>()) {
- return contents[i];
- }
- }
- return JingleContentPayload::ref();
- }
- }
+ namespace Jingle {
+ template<typename T>
+ JingleContentPayload::ref getContentWithDescription(const std::vector<JingleContentPayload::ref>& contents) {
+ for (size_t i = 0; i < contents.size(); ++i) {
+ if (contents[i]->getDescription<T>()) {
+ return contents[i];
+ }
+ }
+ return JingleContentPayload::ref();
+ }
+ }
}
diff --git a/Swiften/Jingle/JingleContentID.h b/Swiften/Jingle/JingleContentID.h
index 2d842fa..60f412b 100644
--- a/Swiften/Jingle/JingleContentID.h
+++ b/Swiften/Jingle/JingleContentID.h
@@ -12,21 +12,21 @@
#include <Swiften/Elements/JingleContentPayload.h>
namespace Swift {
- class SWIFTEN_API JingleContentID {
- public:
- JingleContentID(const std::string& name, JingleContentPayload::Creator creator) : name(name), creator(creator) {
- }
-
- const std::string getName() const {
- return this->name;
- }
-
- JingleContentPayload::Creator getCreator() const {
- return this->creator;
- }
+ class SWIFTEN_API JingleContentID {
+ public:
+ JingleContentID(const std::string& name, JingleContentPayload::Creator creator) : name(name), creator(creator) {
+ }
- private:
- std::string name;
- JingleContentPayload::Creator creator;
- };
+ const std::string getName() const {
+ return this->name;
+ }
+
+ JingleContentPayload::Creator getCreator() const {
+ return this->creator;
+ }
+
+ private:
+ std::string name;
+ JingleContentPayload::Creator creator;
+ };
}
diff --git a/Swiften/Jingle/JingleResponder.cpp b/Swiften/Jingle/JingleResponder.cpp
index 16ed1da..d0c2edd 100644
--- a/Swiften/Jingle/JingleResponder.cpp
+++ b/Swiften/Jingle/JingleResponder.cpp
@@ -21,41 +21,41 @@ JingleResponder::~JingleResponder() {
}
bool JingleResponder::handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload) {
- if (payload->getAction() == JinglePayload::SessionInitiate) {
- if (sessionManager->getSession(from, payload->getSessionID())) {
- // TODO: Add tie-break error
- sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel);
- }
- else {
- sendResponse(from, id, boost::shared_ptr<JinglePayload>());
- if (!payload->getInitiator().isBare()) {
- JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router);
- sessionManager->handleIncomingSession(from, to, session, payload->getContents());
- } else {
- SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl;
- }
- }
- }
- else {
- JingleSessionImpl::ref session;
- if (payload->getInitiator().isValid()) {
- SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl;
- session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID());
- } else {
- SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl;
- session = sessionManager->getSession(from, payload->getSessionID());
- }
- if (session) {
- session->handleIncomingAction(payload);
- sendResponse(from, id, boost::shared_ptr<JinglePayload>());
- }
- else {
- SWIFT_LOG(warning) << "Didn't find jingle session!";
- // TODO: Add jingle-specific error
- sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
- }
- }
- return true;
+ if (payload->getAction() == JinglePayload::SessionInitiate) {
+ if (sessionManager->getSession(from, payload->getSessionID())) {
+ // TODO: Add tie-break error
+ sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel);
+ }
+ else {
+ sendResponse(from, id, boost::shared_ptr<JinglePayload>());
+ if (!payload->getInitiator().isBare()) {
+ JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router);
+ sessionManager->handleIncomingSession(from, to, session, payload->getContents());
+ } else {
+ SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl;
+ }
+ }
+ }
+ else {
+ JingleSessionImpl::ref session;
+ if (payload->getInitiator().isValid()) {
+ SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl;
+ session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID());
+ } else {
+ SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl;
+ session = sessionManager->getSession(from, payload->getSessionID());
+ }
+ if (session) {
+ session->handleIncomingAction(payload);
+ sendResponse(from, id, boost::shared_ptr<JinglePayload>());
+ }
+ else {
+ SWIFT_LOG(warning) << "Didn't find jingle session!";
+ // TODO: Add jingle-specific error
+ sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
+ }
+ }
+ return true;
}
}
diff --git a/Swiften/Jingle/JingleResponder.h b/Swiften/Jingle/JingleResponder.h
index 1468a54..1340835 100644
--- a/Swiften/Jingle/JingleResponder.h
+++ b/Swiften/Jingle/JingleResponder.h
@@ -11,18 +11,18 @@
#include <Swiften/Queries/SetResponder.h>
namespace Swift {
- class IQRouter;
- class JingleSessionManager;
+ class IQRouter;
+ class JingleSessionManager;
- class SWIFTEN_API JingleResponder : public SetResponder<JinglePayload> {
- public:
- JingleResponder(JingleSessionManager* sessionManager, IQRouter* router);
- virtual ~JingleResponder();
- private:
- virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload);
+ class SWIFTEN_API JingleResponder : public SetResponder<JinglePayload> {
+ public:
+ JingleResponder(JingleSessionManager* sessionManager, IQRouter* router);
+ virtual ~JingleResponder();
+ private:
+ virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload);
- private:
- JingleSessionManager* sessionManager;
- IQRouter* router;
- };
+ private:
+ JingleSessionManager* sessionManager;
+ IQRouter* router;
+ };
}
diff --git a/Swiften/Jingle/JingleSession.cpp b/Swiften/Jingle/JingleSession.cpp
index 65a68f9..8abbd56 100644
--- a/Swiften/Jingle/JingleSession.cpp
+++ b/Swiften/Jingle/JingleSession.cpp
@@ -16,9 +16,9 @@
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());
+ // 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/JingleSession.h b/Swiften/Jingle/JingleSession.h
index 6c76f3c..7a64c47 100644
--- a/Swiften/Jingle/JingleSession.h
+++ b/Swiften/Jingle/JingleSession.h
@@ -19,36 +19,36 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class JingleSessionListener;
- class JingleContentID;
-
- class SWIFTEN_API JingleSession : public Listenable<JingleSessionListener> {
- public:
- typedef boost::shared_ptr<JingleSession> ref;
-
- JingleSession(const JID& initiator, const std::string& id);
- virtual ~JingleSession();
-
- const JID& getInitiator() const {
- return initiator;
- }
-
- const std::string& getID() const {
- return id;
- }
-
- virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) = 0;
- virtual void sendTerminate(JinglePayload::Reason::Type reason) = 0;
- virtual void sendInfo(boost::shared_ptr<Payload>) = 0;
- virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0;
- virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) = 0;
- virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) = 0;
- virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) = 0;
- virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) = 0;
-
- private:
- JID initiator;
- std::string id;
- std::vector<JingleSessionListener*> listeners;
- };
+ class JingleSessionListener;
+ class JingleContentID;
+
+ class SWIFTEN_API JingleSession : public Listenable<JingleSessionListener> {
+ public:
+ typedef boost::shared_ptr<JingleSession> ref;
+
+ JingleSession(const JID& initiator, const std::string& id);
+ virtual ~JingleSession();
+
+ const JID& getInitiator() const {
+ return initiator;
+ }
+
+ const std::string& getID() const {
+ return id;
+ }
+
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) = 0;
+ virtual void sendTerminate(JinglePayload::Reason::Type reason) = 0;
+ virtual void sendInfo(boost::shared_ptr<Payload>) = 0;
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0;
+ virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) = 0;
+
+ private:
+ JID initiator;
+ std::string id;
+ std::vector<JingleSessionListener*> listeners;
+ };
}
diff --git a/Swiften/Jingle/JingleSessionImpl.cpp b/Swiften/Jingle/JingleSessionImpl.cpp
index a19947a..3063242 100644
--- a/Swiften/Jingle/JingleSessionImpl.cpp
+++ b/Swiften/Jingle/JingleSessionImpl.cpp
@@ -23,185 +23,185 @@
namespace Swift {
JingleSessionImpl::JingleSessionImpl(const JID& initiator, const JID& peerJID, const std::string& id, IQRouter* router) : JingleSession(initiator, id), iqRouter(router), peerJID(peerJID) {
- SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl;
+ SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl;
}
void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) {
- if (action->getAction() == JinglePayload::SessionTerminate) {
- notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, action->getReason());
- return;
- }
- if (action->getAction() == JinglePayload::SessionInfo) {
- notifyListeners(&JingleSessionListener::handleSessionInfoReceived, action);
- return;
- }
-
- JingleContentPayload::ref content = action->getPayload<JingleContentPayload>();
- if (!content) {
- SWIFT_LOG(debug) << "no content payload!" << std::endl;
- return;
- }
- JingleContentID contentID(content->getName(), content->getCreator());
- JingleDescription::ref description = content->getDescriptions().empty() ? JingleDescription::ref() : content->getDescriptions()[0];
- JingleTransportPayload::ref transport = content->getTransports().empty() ? JingleTransportPayload::ref() : content->getTransports()[0];
- switch(action->getAction()) {
- case JinglePayload::SessionAccept:
- notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, description, transport);
- return;
- case JinglePayload::TransportAccept:
- notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport);
- return;
- case JinglePayload::TransportInfo:
- notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport);
- return;
- case JinglePayload::TransportReject:
- notifyListeners(&JingleSessionListener::handleTransportRejectReceived, contentID, transport);
- return;
- case JinglePayload::TransportReplace:
- notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport);
- return;
- // following unused Jingle actions
- case JinglePayload::ContentAccept:
- case JinglePayload::ContentAdd:
- case JinglePayload::ContentModify:
- case JinglePayload::ContentReject:
- case JinglePayload::ContentRemove:
- case JinglePayload::DescriptionInfo:
- case JinglePayload::SecurityInfo:
-
- // handled elsewhere
- case JinglePayload::SessionInitiate:
- case JinglePayload::SessionInfo:
- case JinglePayload::SessionTerminate:
-
- case JinglePayload::UnknownAction:
- return;
- }
- assert(false);
+ if (action->getAction() == JinglePayload::SessionTerminate) {
+ notifyListeners(&JingleSessionListener::handleSessionTerminateReceived, action->getReason());
+ return;
+ }
+ if (action->getAction() == JinglePayload::SessionInfo) {
+ notifyListeners(&JingleSessionListener::handleSessionInfoReceived, action);
+ return;
+ }
+
+ JingleContentPayload::ref content = action->getPayload<JingleContentPayload>();
+ if (!content) {
+ SWIFT_LOG(debug) << "no content payload!" << std::endl;
+ return;
+ }
+ JingleContentID contentID(content->getName(), content->getCreator());
+ JingleDescription::ref description = content->getDescriptions().empty() ? JingleDescription::ref() : content->getDescriptions()[0];
+ JingleTransportPayload::ref transport = content->getTransports().empty() ? JingleTransportPayload::ref() : content->getTransports()[0];
+ switch(action->getAction()) {
+ case JinglePayload::SessionAccept:
+ notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, description, transport);
+ return;
+ case JinglePayload::TransportAccept:
+ notifyListeners(&JingleSessionListener::handleTransportAcceptReceived, contentID, transport);
+ return;
+ case JinglePayload::TransportInfo:
+ notifyListeners(&JingleSessionListener::handleTransportInfoReceived, contentID, transport);
+ return;
+ case JinglePayload::TransportReject:
+ notifyListeners(&JingleSessionListener::handleTransportRejectReceived, contentID, transport);
+ return;
+ case JinglePayload::TransportReplace:
+ notifyListeners(&JingleSessionListener::handleTransportReplaceReceived, contentID, transport);
+ return;
+ // following unused Jingle actions
+ case JinglePayload::ContentAccept:
+ case JinglePayload::ContentAdd:
+ case JinglePayload::ContentModify:
+ case JinglePayload::ContentReject:
+ case JinglePayload::ContentRemove:
+ case JinglePayload::DescriptionInfo:
+ case JinglePayload::SecurityInfo:
+
+ // handled elsewhere
+ case JinglePayload::SessionInitiate:
+ case JinglePayload::SessionInfo:
+ case JinglePayload::SessionTerminate:
+
+ case JinglePayload::UnknownAction:
+ return;
+ }
+ assert(false);
}
void JingleSessionImpl::sendInitiate(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transport) {
- JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID());
- payload->setInitiator(getInitiator());
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addDescription(description);
- content->addTransport(transport);
- payload->addPayload(content);
-
- sendSetRequest(payload);
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID());
+ payload->setInitiator(getInitiator());
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addDescription(description);
+ content->addTransport(transport);
+ payload->addPayload(content);
+
+ sendSetRequest(payload);
}
void JingleSessionImpl::sendTerminate(JinglePayload::Reason::Type reason) {
- JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionTerminate, getID());
- payload->setReason(JinglePayload::Reason(reason));
- payload->setInitiator(getInitiator());
- sendSetRequest(payload);
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionTerminate, getID());
+ payload->setReason(JinglePayload::Reason(reason));
+ payload->setInitiator(getInitiator());
+ sendSetRequest(payload);
}
void JingleSessionImpl::sendInfo(boost::shared_ptr<Payload> info) {
- JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInfo, getID());
- payload->addPayload(info);
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInfo, getID());
+ payload->addPayload(info);
- sendSetRequest(payload);
+ sendSetRequest(payload);
}
void JingleSessionImpl::sendAccept(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transPayload) {
- JinglePayload::ref payload = createPayload();
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addTransport(transPayload);
- content->addDescription(description);
- payload->setAction(JinglePayload::SessionAccept);
- payload->addPayload(content);
-
- // put into IQ:set and send it away
- sendSetRequest(payload);
+ JinglePayload::ref payload = createPayload();
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ content->addDescription(description);
+ payload->setAction(JinglePayload::SessionAccept);
+ payload->addPayload(content);
+
+ // put into IQ:set and send it away
+ sendSetRequest(payload);
}
void JingleSessionImpl::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
- JinglePayload::ref payload = createPayload();
+ JinglePayload::ref payload = createPayload();
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addTransport(transPayload);
- payload->setAction(JinglePayload::TransportAccept);
- payload->addPayload(content);
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportAccept);
+ payload->addPayload(content);
- // put into IQ:set and send it away
- sendSetRequest(payload);
+ // put into IQ:set and send it away
+ sendSetRequest(payload);
}
std::string JingleSessionImpl::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
- JinglePayload::ref payload = createPayload();
+ JinglePayload::ref payload = createPayload();
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addTransport(transPayload);
- payload->setAction(JinglePayload::TransportInfo);
- payload->addPayload(content);
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->addPayload(content);
- return sendSetRequest(payload);
+ return sendSetRequest(payload);
}
void JingleSessionImpl::sendTransportReject(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
- JinglePayload::ref payload = createPayload();
+ JinglePayload::ref payload = createPayload();
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addTransport(transPayload);
- payload->setAction(JinglePayload::TransportReject);
- payload->addPayload(content);
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportReject);
+ payload->addPayload(content);
- sendSetRequest(payload);
+ sendSetRequest(payload);
}
void JingleSessionImpl::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
- JinglePayload::ref payload = createPayload();
+ JinglePayload::ref payload = createPayload();
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(id.getCreator());
- content->setName(id.getName());
- content->addTransport(transPayload);
- payload->setAction(JinglePayload::TransportReplace);
- payload->addContent(content);
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportReplace);
+ payload->addContent(content);
- sendSetRequest(payload);
+ sendSetRequest(payload);
}
std::string JingleSessionImpl::sendSetRequest(JinglePayload::ref payload) {
- boost::shared_ptr<GenericRequest<JinglePayload> > request = boost::make_shared<GenericRequest<JinglePayload> >(
- IQ::Set, peerJID, payload, iqRouter);
- pendingRequests.insert(std::make_pair(
- request,
- request->onResponse.connect(boost::bind(&JingleSessionImpl::handleRequestResponse, this, request))));
- return request->send();
+ boost::shared_ptr<GenericRequest<JinglePayload> > request = boost::make_shared<GenericRequest<JinglePayload> >(
+ IQ::Set, peerJID, payload, iqRouter);
+ pendingRequests.insert(std::make_pair(
+ request,
+ request->onResponse.connect(boost::bind(&JingleSessionImpl::handleRequestResponse, this, request))));
+ return request->send();
}
JinglePayload::ref JingleSessionImpl::createPayload() const {
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setSessionID(getID());
- payload->setInitiator(getInitiator());
- return payload;
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setSessionID(getID());
+ payload->setInitiator(getInitiator());
+ return payload;
}
void JingleSessionImpl::handleRequestResponse(RequestRef request) {
- RequestsMap::iterator i = pendingRequests.find(request);
- assert(i != pendingRequests.end());
- if (i->first->getPayloadGeneric()->getAction() == JinglePayload::TransportInfo) {
- notifyListeners(&JingleSessionListener::handleTransportInfoAcknowledged, i->first->getID());
- }
- i->second.disconnect();
- pendingRequests.erase(i);
+ RequestsMap::iterator i = pendingRequests.find(request);
+ assert(i != pendingRequests.end());
+ if (i->first->getPayloadGeneric()->getAction() == JinglePayload::TransportInfo) {
+ notifyListeners(&JingleSessionListener::handleTransportInfoAcknowledged, i->first->getID());
+ }
+ i->second.disconnect();
+ pendingRequests.erase(i);
}
diff --git a/Swiften/Jingle/JingleSessionImpl.h b/Swiften/Jingle/JingleSessionImpl.h
index 4d21cd3..eec2370 100644
--- a/Swiften/Jingle/JingleSessionImpl.h
+++ b/Swiften/Jingle/JingleSessionImpl.h
@@ -14,38 +14,38 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class IQRouter;
- class Request;
-
- class JingleSessionImpl : public JingleSession {
- friend class JingleResponder;
- public:
- typedef boost::shared_ptr<JingleSessionImpl> ref;
-
- JingleSessionImpl(const JID& initiator, const JID&, const std::string& id, IQRouter* router);
-
- virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
- virtual void sendTerminate(JinglePayload::Reason::Type reason);
- virtual void sendInfo(boost::shared_ptr<Payload>);
- virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
- virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref);
- virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref);
- virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref);
- virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref);
-
- private:
- typedef boost::shared_ptr<GenericRequest<JinglePayload> > RequestRef;
-
- void handleIncomingAction(JinglePayload::ref);
-
- std::string sendSetRequest(JinglePayload::ref payload);
- JinglePayload::ref createPayload() const;
- void handleRequestResponse(RequestRef);
-
- private:
- IQRouter *iqRouter;
- JID peerJID;
- typedef std::map<RequestRef, boost::bsignals::connection > RequestsMap;
- RequestsMap pendingRequests;
- };
+ class IQRouter;
+ class Request;
+
+ class JingleSessionImpl : public JingleSession {
+ friend class JingleResponder;
+ public:
+ typedef boost::shared_ptr<JingleSessionImpl> ref;
+
+ JingleSessionImpl(const JID& initiator, const JID&, const std::string& id, IQRouter* router);
+
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
+ virtual void sendTerminate(JinglePayload::Reason::Type reason);
+ virtual void sendInfo(boost::shared_ptr<Payload>);
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
+ virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref);
+
+ private:
+ typedef boost::shared_ptr<GenericRequest<JinglePayload> > RequestRef;
+
+ void handleIncomingAction(JinglePayload::ref);
+
+ std::string sendSetRequest(JinglePayload::ref payload);
+ JinglePayload::ref createPayload() const;
+ void handleRequestResponse(RequestRef);
+
+ private:
+ IQRouter *iqRouter;
+ JID peerJID;
+ typedef std::map<RequestRef, boost::bsignals::connection > RequestsMap;
+ RequestsMap pendingRequests;
+ };
}
diff --git a/Swiften/Jingle/JingleSessionListener.h b/Swiften/Jingle/JingleSessionListener.h
index dabeb05..54101b6 100644
--- a/Swiften/Jingle/JingleSessionListener.h
+++ b/Swiften/Jingle/JingleSessionListener.h
@@ -10,31 +10,31 @@
#include <Swiften/Elements/JinglePayload.h>
namespace Swift {
- class JingleContentID;
- class JingleTransportPayload;
- class JingleDescription;
+ class JingleContentID;
+ class JingleTransportPayload;
+ class JingleDescription;
- class SWIFTEN_API JingleSessionListener {
- public:
- virtual ~JingleSessionListener();
+ class SWIFTEN_API JingleSessionListener {
+ public:
+ virtual ~JingleSessionListener();
- virtual void handleSessionAcceptReceived(
- const JingleContentID&,
- boost::shared_ptr<JingleDescription>,
- boost::shared_ptr<JingleTransportPayload>) = 0;
- virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) = 0;
- virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) = 0;
- virtual void handleTransportAcceptReceived(
- const JingleContentID&,
- boost::shared_ptr<JingleTransportPayload>) = 0;
- virtual void handleTransportInfoReceived(
- const JingleContentID&,
- boost::shared_ptr<JingleTransportPayload>) = 0;
- virtual void handleTransportRejectReceived(
- const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0;
- virtual void handleTransportReplaceReceived(
- const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleSessionAcceptReceived(
+ const JingleContentID&,
+ boost::shared_ptr<JingleDescription>,
+ boost::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) = 0;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) = 0;
+ virtual void handleTransportAcceptReceived(
+ const JingleContentID&,
+ boost::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportInfoReceived(
+ const JingleContentID&,
+ boost::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportRejectReceived(
+ const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportReplaceReceived(
+ const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) = 0;
- virtual void handleTransportInfoAcknowledged(const std::string& id) = 0;
- };
+ virtual void handleTransportInfoAcknowledged(const std::string& id) = 0;
+ };
}
diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp
index 81014e7..ca6cebb 100644
--- a/Swiften/Jingle/JingleSessionManager.cpp
+++ b/Swiften/Jingle/JingleSessionManager.cpp
@@ -15,41 +15,41 @@
namespace Swift {
JingleSessionManager::JingleSessionManager(IQRouter* router) : router(router) {
- responder = new JingleResponder(this, router);
- responder->start();
+ responder = new JingleResponder(this, router);
+ responder->start();
}
JingleSessionManager::~JingleSessionManager() {
- responder->stop();
- delete responder;
+ 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();
+ 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);
+ incomingSessionHandlers.push_back(handler);
}
void JingleSessionManager::removeIncomingSessionHandler(IncomingJingleSessionHandler* handler) {
- erase(incomingSessionHandlers, 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;
+ 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) {
- if (handler->handleIncomingJingleSession(session, contents, recipient)) {
- return;
- }
- }
- // TODO: Finish session
+ sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
+ foreach (IncomingJingleSessionHandler* handler, incomingSessionHandlers) {
+ if (handler->handleIncomingJingleSession(session, contents, recipient)) {
+ return;
+ }
+ }
+ // TODO: Finish session
}
diff --git a/Swiften/Jingle/JingleSessionManager.h b/Swiften/Jingle/JingleSessionManager.h
index fbfdb50..fea6c73 100644
--- a/Swiften/Jingle/JingleSessionManager.h
+++ b/Swiften/Jingle/JingleSessionManager.h
@@ -15,38 +15,38 @@
#include <Swiften/Jingle/JingleSessionImpl.h>
namespace Swift {
- class IQRouter;
- class JingleResponder;
- class IncomingJingleSessionHandler;
-
- class SWIFTEN_API JingleSessionManager {
- friend class JingleResponder;
- public:
- JingleSessionManager(IQRouter* router);
- ~JingleSessionManager();
-
- JingleSessionImpl::ref getSession(const JID& jid, const std::string& id) const;
-
- void addIncomingSessionHandler(IncomingJingleSessionHandler* handler);
- void removeIncomingSessionHandler(IncomingJingleSessionHandler* handler);
-
- void registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref);
- protected:
- void handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents);
-
- private:
- IQRouter* router;
- JingleResponder* responder;
- std::vector<IncomingJingleSessionHandler*> incomingSessionHandlers;
- struct JIDSession {
- JIDSession(const JID& initiator, const std::string& session) : initiator(initiator), session(session) {}
- bool operator<(const JIDSession& o) const {
- return initiator == o.initiator ? session < o.session : initiator < o.initiator;
- }
- JID initiator;
- std::string session;
- };
- typedef std::map<JIDSession, JingleSessionImpl::ref> SessionMap;
- SessionMap sessions;
- };
+ class IQRouter;
+ class JingleResponder;
+ class IncomingJingleSessionHandler;
+
+ class SWIFTEN_API JingleSessionManager {
+ friend class JingleResponder;
+ public:
+ JingleSessionManager(IQRouter* router);
+ ~JingleSessionManager();
+
+ JingleSessionImpl::ref getSession(const JID& jid, const std::string& id) const;
+
+ void addIncomingSessionHandler(IncomingJingleSessionHandler* handler);
+ void removeIncomingSessionHandler(IncomingJingleSessionHandler* handler);
+
+ void registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref);
+ protected:
+ void handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents);
+
+ private:
+ IQRouter* router;
+ JingleResponder* responder;
+ std::vector<IncomingJingleSessionHandler*> incomingSessionHandlers;
+ struct JIDSession {
+ JIDSession(const JID& initiator, const std::string& session) : initiator(initiator), session(session) {}
+ bool operator<(const JIDSession& o) const {
+ return initiator == o.initiator ? session < o.session : initiator < o.initiator;
+ }
+ JID initiator;
+ std::string session;
+ };
+ typedef std::map<JIDSession, JingleSessionImpl::ref> SessionMap;
+ SessionMap sessions;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
index 98038e1..a1bdb3e 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
@@ -15,47 +15,47 @@
namespace Swift {
void AvahiBrowseQuery::startBrowsing() {
- std::cout << "Start browsing" << std::endl;
- assert(!browser);
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- browser = avahi_service_browser_new(querier->getClient(), AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_presence._tcp", NULL, static_cast<AvahiLookupFlags>(0), &handleServiceDiscoveredStatic, this);
- if (!browser) {
- std::cout << "Error" << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
- }
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ std::cout << "Start browsing" << std::endl;
+ assert(!browser);
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ browser = avahi_service_browser_new(querier->getClient(), AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_presence._tcp", NULL, static_cast<AvahiLookupFlags>(0), &handleServiceDiscoveredStatic, this);
+ if (!browser) {
+ std::cout << "Error" << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
+ }
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiBrowseQuery::stopBrowsing() {
- std::cout << "Stop browsing" << std::endl;
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- avahi_service_browser_free(browser);
- browser = NULL;
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ std::cout << "Stop browsing" << std::endl;
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ avahi_service_browser_free(browser);
+ browser = NULL;
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiBrowseQuery::handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags) {
- switch (event) {
- case AVAHI_BROWSER_FAILURE:
- std::cout << "Service browse error" << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
- break;
- case AVAHI_BROWSER_NEW: {
- DNSSDServiceID service(name, domain, type, interfaceIndex);
- std::cout << "Service discovered " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this());
- break;
- }
- case AVAHI_BROWSER_REMOVE: {
- std::cout << "Service went away " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl;
- DNSSDServiceID service(name, domain, type, interfaceIndex);
- eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this());
- break;
- }
- case AVAHI_BROWSER_ALL_FOR_NOW:
- case AVAHI_BROWSER_CACHE_EXHAUSTED:
- break;
- }
+ switch (event) {
+ case AVAHI_BROWSER_FAILURE:
+ std::cout << "Service browse error" << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
+ break;
+ case AVAHI_BROWSER_NEW: {
+ DNSSDServiceID service(name, domain, type, interfaceIndex);
+ std::cout << "Service discovered " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this());
+ break;
+ }
+ case AVAHI_BROWSER_REMOVE: {
+ std::cout << "Service went away " << name << " " << domain << " " << type << " " << interfaceIndex << std::endl;
+ DNSSDServiceID service(name, domain, type, interfaceIndex);
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this());
+ break;
+ }
+ case AVAHI_BROWSER_ALL_FOR_NOW:
+ case AVAHI_BROWSER_CACHE_EXHAUSTED:
+ break;
+ }
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h
index d473534..767ee1d 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h
@@ -13,25 +13,25 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
namespace Swift {
- class AvahiQuerier;
+ class AvahiQuerier;
- class AvahiBrowseQuery : public DNSSDBrowseQuery, public AvahiQuery {
- public:
- AvahiBrowseQuery(boost::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : AvahiQuery(q, eventLoop), browser(NULL) {
- }
+ class AvahiBrowseQuery : public DNSSDBrowseQuery, public AvahiQuery {
+ public:
+ AvahiBrowseQuery(boost::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : AvahiQuery(q, eventLoop), browser(NULL) {
+ }
- void startBrowsing();
- void stopBrowsing();
+ void startBrowsing();
+ void stopBrowsing();
- private:
- static void handleServiceDiscoveredStatic(AvahiServiceBrowser *b, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags flags, void* context) {
- static_cast<AvahiBrowseQuery*>(context)->handleServiceDiscovered(b, interfaceIndex, protocol, event, name, type, domain, flags);
- }
+ private:
+ static void handleServiceDiscoveredStatic(AvahiServiceBrowser *b, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags flags, void* context) {
+ static_cast<AvahiBrowseQuery*>(context)->handleServiceDiscovered(b, interfaceIndex, protocol, event, name, type, domain, flags);
+ }
- void handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags);
+ void handleServiceDiscovered(AvahiServiceBrowser *, AvahiIfIndex interfaceIndex, AvahiProtocol, AvahiBrowserEvent event, const char *name, const char *type, const char *domain, AvahiLookupResultFlags);
- private:
- AvahiServiceBrowser* browser;
-
- };
+ private:
+ AvahiServiceBrowser* browser;
+
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp
index c9449ff..11f1650 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp
@@ -22,45 +22,45 @@ AvahiQuerier::~AvahiQuerier() {
}
boost::shared_ptr<DNSSDBrowseQuery> AvahiQuerier::createBrowseQuery() {
- return boost::shared_ptr<DNSSDBrowseQuery>(new AvahiBrowseQuery(shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDBrowseQuery>(new AvahiBrowseQuery(shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDRegisterQuery> AvahiQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
- return boost::shared_ptr<DNSSDRegisterQuery>(new AvahiRegisterQuery(name, port, info, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDRegisterQuery>(new AvahiRegisterQuery(name, port, info, shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDResolveServiceQuery> AvahiQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
- return boost::shared_ptr<DNSSDResolveServiceQuery>(new AvahiResolveServiceQuery(service, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDResolveServiceQuery>(new AvahiResolveServiceQuery(service, shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDResolveHostnameQuery> AvahiQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
- return boost::shared_ptr<DNSSDResolveHostnameQuery>(new AvahiResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDResolveHostnameQuery>(new AvahiResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop));
}
void AvahiQuerier::start() {
- std::cout << "Starrting querier" << std::endl;
- assert(!threadedPoll);
- threadedPoll = avahi_threaded_poll_new();
- int error;
- assert(!client);
- client = avahi_client_new(
- avahi_threaded_poll_get(threadedPoll),
- static_cast<AvahiClientFlags>(0), NULL, this, &error); // TODO
- if (!client) {
- // TODO
- std::cerr << "Avahi Error: " << avahi_strerror(error) << std::endl;
- return;
- }
- std::cout << "Starrting event loop" << std::endl;
- avahi_threaded_poll_start(threadedPoll);
+ std::cout << "Starrting querier" << std::endl;
+ assert(!threadedPoll);
+ threadedPoll = avahi_threaded_poll_new();
+ int error;
+ assert(!client);
+ client = avahi_client_new(
+ avahi_threaded_poll_get(threadedPoll),
+ static_cast<AvahiClientFlags>(0), NULL, this, &error); // TODO
+ if (!client) {
+ // TODO
+ std::cerr << "Avahi Error: " << avahi_strerror(error) << std::endl;
+ return;
+ }
+ std::cout << "Starrting event loop" << std::endl;
+ avahi_threaded_poll_start(threadedPoll);
}
void AvahiQuerier::stop() {
- assert(threadedPoll);
- avahi_threaded_poll_stop(threadedPoll);
- assert(client);
- avahi_client_free(client);
- avahi_threaded_poll_free(threadedPoll);
+ assert(threadedPoll);
+ avahi_threaded_poll_stop(threadedPoll);
+ assert(client);
+ avahi_client_free(client);
+ avahi_threaded_poll_free(threadedPoll);
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h
index 3176536..fa9580e 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h
@@ -20,37 +20,37 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
namespace Swift {
- class EventLoop;
-
- class AvahiQuerier :
- public DNSSDQuerier,
- public boost::enable_shared_from_this<AvahiQuerier> {
- public:
- AvahiQuerier(EventLoop* eventLoop);
- ~AvahiQuerier();
-
- boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
- boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
- const std::string& name, int port, const ByteArray& info);
- boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
- const DNSSDServiceID&);
- boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
- const std::string& hostname, int interfaceIndex);
-
- void start();
- void stop();
-
- AvahiThreadedPoll* getThreadedPoll() const {
- return threadedPoll;
- }
-
- AvahiClient* getClient() const {
- return client;
- }
-
- private:
- EventLoop* eventLoop;
- AvahiClient* client;
- AvahiThreadedPoll* threadedPoll;
- };
+ class EventLoop;
+
+ class AvahiQuerier :
+ public DNSSDQuerier,
+ public boost::enable_shared_from_this<AvahiQuerier> {
+ public:
+ AvahiQuerier(EventLoop* eventLoop);
+ ~AvahiQuerier();
+
+ boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex);
+
+ void start();
+ void stop();
+
+ AvahiThreadedPoll* getThreadedPoll() const {
+ return threadedPoll;
+ }
+
+ AvahiClient* getClient() const {
+ return client;
+ }
+
+ private:
+ EventLoop* eventLoop;
+ AvahiClient* client;
+ AvahiThreadedPoll* threadedPoll;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
index c2d745c..5752003 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
@@ -12,19 +12,19 @@
#include <Swiften/EventLoop/EventOwner.h>
namespace Swift {
- class AvahiQuerier;
- class EventLoop;
+ class AvahiQuerier;
+ class EventLoop;
- class AvahiQuery :
- public EventOwner,
- public boost::enable_shared_from_this<AvahiQuery> {
- public:
- AvahiQuery(boost::shared_ptr<AvahiQuerier>, EventLoop* eventLoop);
- virtual ~AvahiQuery();
-
- protected:
- boost::shared_ptr<AvahiQuerier> querier;
- EventLoop* eventLoop;
- };
+ class AvahiQuery :
+ public EventOwner,
+ public boost::enable_shared_from_this<AvahiQuery> {
+ public:
+ AvahiQuery(boost::shared_ptr<AvahiQuerier>, EventLoop* eventLoop);
+ virtual ~AvahiQuery();
+
+ protected:
+ boost::shared_ptr<AvahiQuerier> querier;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
index 48fe17d..04790d5 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
@@ -15,87 +15,87 @@
namespace Swift {
void AvahiRegisterQuery::registerService() {
- std::cout << "Registering service " << name << ":" << port << std::endl;
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- if (!group) {
- std::cout << "Creating entry group" << std::endl;
- group = avahi_entry_group_new(querier->getClient(), handleEntryGroupChange, this);
- if (!group) {
- std::cout << "Error ceating entry group" << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
- }
-
- doRegisterService();
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ std::cout << "Registering service " << name << ":" << port << std::endl;
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ if (!group) {
+ std::cout << "Creating entry group" << std::endl;
+ group = avahi_entry_group_new(querier->getClient(), handleEntryGroupChange, this);
+ if (!group) {
+ std::cout << "Error ceating entry group" << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
+ }
+
+ doRegisterService();
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiRegisterQuery::unregisterService() {
- if (group) {
- avahi_entry_group_free(group);
- group = NULL;
- }
+ if (group) {
+ avahi_entry_group_free(group);
+ group = NULL;
+ }
}
void AvahiRegisterQuery::updateServiceInfo(const ByteArray& txtRecord) {
- this->txtRecord = txtRecord;
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- assert(group);
- avahi_entry_group_reset(group);
- doRegisterService();
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ this->txtRecord = txtRecord;
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ assert(group);
+ avahi_entry_group_reset(group);
+ doRegisterService();
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiRegisterQuery::doRegisterService() {
- AvahiStringList* txtList;
- avahi_string_list_parse(vecptr(txtRecord), txtRecord.size(), &txtList);
-
- int result = avahi_entry_group_add_service_strlst(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), name.c_str(), "_presence._tcp", NULL, NULL, port, txtList);
- if (result < 0) {
- std::cout << "Error registering service: " << avahi_strerror(result) << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
- result = avahi_entry_group_commit(group);
- if (result < 0) {
- std::cout << "Error registering service: " << avahi_strerror(result) << std::endl;
- }
+ AvahiStringList* txtList;
+ avahi_string_list_parse(vecptr(txtRecord), txtRecord.size(), &txtList);
+
+ int result = avahi_entry_group_add_service_strlst(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, static_cast<AvahiPublishFlags>(0), name.c_str(), "_presence._tcp", NULL, NULL, port, txtList);
+ if (result < 0) {
+ std::cout << "Error registering service: " << avahi_strerror(result) << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
+ result = avahi_entry_group_commit(group);
+ if (result < 0) {
+ std::cout << "Error registering service: " << avahi_strerror(result) << std::endl;
+ }
}
void AvahiRegisterQuery::handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state) {
- std::cout << "ENtry group callback: " << state << std::endl;
- switch (state) {
- case AVAHI_ENTRY_GROUP_ESTABLISHED :
- // Domain is a hack!
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, "local", "_presence._tcp", 0))), shared_from_this());
- std::cout << "Entry group established" << std::endl;
- break;
- case AVAHI_ENTRY_GROUP_COLLISION : {
- std::cout << "Entry group collision" << std::endl;
- /*char *n;
- n = avahi_alternative_service_name(name);
- avahi_free(name);
- name = n;*/
- break;
- }
-
- case AVAHI_ENTRY_GROUP_FAILURE :
- std::cout << "Entry group failure " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << std::endl;
- break;
-
- case AVAHI_ENTRY_GROUP_UNCOMMITED:
- case AVAHI_ENTRY_GROUP_REGISTERING:
- ;
-
- /*
- DNSServiceErrorType result = DNSServiceRegister(
- &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, port,
- txtRecord.getSize(), txtRecord.getData(),
- &AvahiRegisterQuery::handleServiceRegisteredStatic, this);
- if (result != kDNSServiceErr_NoError) {
- sdRef = NULL;
- }*/
- //eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
+ std::cout << "ENtry group callback: " << state << std::endl;
+ switch (state) {
+ case AVAHI_ENTRY_GROUP_ESTABLISHED :
+ // Domain is a hack!
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, "local", "_presence._tcp", 0))), shared_from_this());
+ std::cout << "Entry group established" << std::endl;
+ break;
+ case AVAHI_ENTRY_GROUP_COLLISION : {
+ std::cout << "Entry group collision" << std::endl;
+ /*char *n;
+ n = avahi_alternative_service_name(name);
+ avahi_free(name);
+ name = n;*/
+ break;
+ }
+
+ case AVAHI_ENTRY_GROUP_FAILURE :
+ std::cout << "Entry group failure " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << std::endl;
+ break;
+
+ case AVAHI_ENTRY_GROUP_UNCOMMITED:
+ case AVAHI_ENTRY_GROUP_REGISTERING:
+ ;
+
+ /*
+ DNSServiceErrorType result = DNSServiceRegister(
+ &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, port,
+ txtRecord.getSize(), txtRecord.getData(),
+ &AvahiRegisterQuery::handleServiceRegisteredStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = NULL;
+ }*/
+ //eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h
index 4da9bfd..5570559 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h
@@ -14,44 +14,44 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
namespace Swift {
- class AvahiQuerier;
+ class AvahiQuerier;
- class AvahiRegisterQuery : public DNSSDRegisterQuery, public AvahiQuery {
- public:
- AvahiRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) {
- }
+ class AvahiRegisterQuery : public DNSSDRegisterQuery, public AvahiQuery {
+ public:
+ AvahiRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) {
+ }
- void registerService();
- void unregisterService();
- void updateServiceInfo(const ByteArray& txtRecord);
+ void registerService();
+ void unregisterService();
+ void updateServiceInfo(const ByteArray& txtRecord);
- private:
- void doRegisterService();
+ private:
+ void doRegisterService();
- static void handleEntryGroupChange(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) {
- static_cast<AvahiRegisterQuery*>(userdata)->handleEntryGroupChange(g, state);
- }
+ static void handleEntryGroupChange(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) {
+ static_cast<AvahiRegisterQuery*>(userdata)->handleEntryGroupChange(g, state);
+ }
- void handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state);
+ void handleEntryGroupChange(AvahiEntryGroup* g, AvahiEntryGroupState state);
/*
- static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) {
- static_cast<AvahiRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain);
- }
-
- void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) {
- if (errorCode != kDNSServiceErr_NoError) {
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
- else {
- }
- }
- */
-
- private:
- std::string name;
- int port;
- ByteArray txtRecord;
- AvahiEntryGroup* group;
- };
+ static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) {
+ static_cast<AvahiRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain);
+ }
+
+ void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) {
+ if (errorCode != kDNSServiceErr_NoError) {
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
+ else {
+ }
+ }
+ */
+
+ private:
+ std::string name;
+ int port;
+ ByteArray txtRecord;
+ AvahiEntryGroup* group;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
index a9910a3..af1a048 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
@@ -13,11 +13,11 @@
namespace Swift {
AvahiResolveHostnameQuery::AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), hostname(hostname) {
- std::cout << "Resolving hostname " << hostname << std::endl;
+ std::cout << "Resolving hostname " << hostname << std::endl;
}
void AvahiResolveHostnameQuery::run() {
- eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>(HostAddress(hostname))), shared_from_this());
+ eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>(HostAddress(hostname))), shared_from_this());
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
index 000d966..9d21bf9 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
@@ -16,19 +16,19 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class AvahiQuerier;
+ class AvahiQuerier;
- class AvahiResolveHostnameQuery : public DNSSDResolveHostnameQuery, public AvahiQuery {
- public:
- AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop);
+ class AvahiResolveHostnameQuery : public DNSSDResolveHostnameQuery, public AvahiQuery {
+ public:
+ AvahiResolveHostnameQuery(const std::string& hostname, int, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop);
- void run();
+ void run();
- void finish() {
- }
+ void finish() {
+ }
- private:
- HostAddress hostAddress;
- std::string hostname;
- };
+ private:
+ HostAddress hostAddress;
+ std::string hostname;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp
index 470e165..a5e52b2 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp
@@ -15,52 +15,52 @@
namespace Swift {
void AvahiResolveServiceQuery::start() {
- std::cout << "Start resolving " << service.getName() << " " << service.getType() << " " << service.getDomain() << std::endl;
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- assert(!resolver);
- resolver = avahi_service_resolver_new(querier->getClient(), service.getNetworkInterfaceID(), AVAHI_PROTO_UNSPEC, service.getName().c_str(), service.getType().c_str(), service.getDomain().c_str(), AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), handleServiceResolvedStatic, this);
- if (!resolver) {
- std::cout << "Error starting resolver" << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
- }
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ std::cout << "Start resolving " << service.getName() << " " << service.getType() << " " << service.getDomain() << std::endl;
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ assert(!resolver);
+ resolver = avahi_service_resolver_new(querier->getClient(), service.getNetworkInterfaceID(), AVAHI_PROTO_UNSPEC, service.getName().c_str(), service.getType().c_str(), service.getDomain().c_str(), AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), handleServiceResolvedStatic, this);
+ if (!resolver) {
+ std::cout << "Error starting resolver" << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
+ }
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiResolveServiceQuery::stop() {
- std::cout << "Stop resolving" << std::endl;
- avahi_threaded_poll_lock(querier->getThreadedPoll());
- avahi_service_resolver_free(resolver);
- resolver = NULL;
- avahi_threaded_poll_unlock(querier->getThreadedPoll());
+ std::cout << "Stop resolving" << std::endl;
+ avahi_threaded_poll_lock(querier->getThreadedPoll());
+ avahi_service_resolver_free(resolver);
+ resolver = NULL;
+ avahi_threaded_poll_unlock(querier->getThreadedPoll());
}
void AvahiResolveServiceQuery::handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags) {
- std::cout << "Resolve finished" << std::endl;
- switch(event) {
- case AVAHI_RESOLVER_FAILURE:
- std::cout << "Resolve error " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(resolver))) << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
- break;
- case AVAHI_RESOLVER_FOUND: {
- std::cout << "Success" << std::endl;
- char a[AVAHI_ADDRESS_STR_MAX];
- avahi_address_snprint(a, sizeof(a), address);
+ std::cout << "Resolve finished" << std::endl;
+ switch(event) {
+ case AVAHI_RESOLVER_FAILURE:
+ std::cout << "Resolve error " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(resolver))) << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
+ break;
+ case AVAHI_RESOLVER_FOUND: {
+ std::cout << "Success" << std::endl;
+ char a[AVAHI_ADDRESS_STR_MAX];
+ avahi_address_snprint(a, sizeof(a), address);
- ByteArray txtRecord;
- txtRecord.resize(1024);
- avahi_string_list_serialize(txt, vecptr(txtRecord), txtRecord.size());
+ ByteArray txtRecord;
+ txtRecord.resize(1024);
+ avahi_string_list_serialize(txt, vecptr(txtRecord), txtRecord.size());
- // FIXME: Probably not accurate
- std::string fullname = std::string(name) + "." + std::string(type) + "." + std::string(domain) + ".";
- std::cout << "Result: " << fullname << "->" << std::string(a) << ":" << port << std::endl;
- eventLoop->postEvent(
- boost::bind(
- boost::ref(onServiceResolved),
- Result(fullname, std::string(a), port, txtRecord)),
- shared_from_this());
- break;
- }
- }
+ // FIXME: Probably not accurate
+ std::string fullname = std::string(name) + "." + std::string(type) + "." + std::string(domain) + ".";
+ std::cout << "Result: " << fullname << "->" << std::string(a) << ":" << port << std::endl;
+ eventLoop->postEvent(
+ boost::bind(
+ boost::ref(onServiceResolved),
+ Result(fullname, std::string(a), port, txtRecord)),
+ shared_from_this());
+ break;
+ }
+ }
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h
index 90c2fda..c95d131 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h
@@ -15,25 +15,25 @@
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
namespace Swift {
- class AvahiQuerier;
+ class AvahiQuerier;
- class AvahiResolveServiceQuery : public DNSSDResolveServiceQuery, public AvahiQuery {
- public:
- AvahiResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), service(service), resolver(NULL) {
- }
+ class AvahiResolveServiceQuery : public DNSSDResolveServiceQuery, public AvahiQuery {
+ public:
+ AvahiResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), service(service), resolver(NULL) {
+ }
- void start();
- void stop();
+ void start();
+ void stop();
- private:
- static void handleServiceResolvedStatic(AvahiServiceResolver* resolver, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void* context) {
- static_cast<AvahiResolveServiceQuery*>(context)->handleServiceResolved(resolver, interfaceIndex, protocol, event, name, type, domain, host_name, address, port, txt, flags);
- }
+ private:
+ static void handleServiceResolvedStatic(AvahiServiceResolver* resolver, AvahiIfIndex interfaceIndex, AvahiProtocol protocol, AvahiResolverEvent event, const char *name, const char *type, const char *domain, const char *host_name, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags, void* context) {
+ static_cast<AvahiResolveServiceQuery*>(context)->handleServiceResolved(resolver, interfaceIndex, protocol, event, name, type, domain, host_name, address, port, txt, flags);
+ }
- void handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags);
+ void handleServiceResolved(AvahiServiceResolver* resolver, AvahiIfIndex, AvahiProtocol, AvahiResolverEvent event, const char *name, const char * type, const char* domain, const char * /*host_name*/, const AvahiAddress *address, uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags);
- private:
- DNSSDServiceID service;
- AvahiServiceResolver* resolver;
- };
+ private:
+ DNSSDServiceID service;
+ AvahiServiceResolver* resolver;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h
index 60b5dee..6cfaf22 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h
@@ -13,51 +13,51 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
namespace Swift {
- class BonjourQuerier;
-
- class BonjourBrowseQuery : public DNSSDBrowseQuery, public BonjourQuery {
- public:
- BonjourBrowseQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : BonjourQuery(q, eventLoop) {
- DNSServiceErrorType result = DNSServiceBrowse(
- &sdRef, 0, 0, "_presence._tcp", 0,
- &BonjourBrowseQuery::handleServiceDiscoveredStatic, this);
- if (result != kDNSServiceErr_NoError) {
- sdRef = NULL;
- }
- }
-
- void startBrowsing() {
- if (!sdRef) {
- eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
- }
- else {
- run();
- }
- }
-
- void stopBrowsing() {
- finish();
- }
-
- private:
- static void handleServiceDiscoveredStatic(DNSServiceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain, void *context) {
- static_cast<BonjourBrowseQuery*>(context)->handleServiceDiscovered(flags, interfaceIndex, errorCode, name, type, domain);
- }
-
- void handleServiceDiscovered(DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain) {
- if (errorCode != kDNSServiceErr_NoError) {
- eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
- }
- else {
- //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl;
- DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex));
- if (flags & kDNSServiceFlagsAdd) {
- eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this());
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this());
- }
- }
- }
- };
+ class BonjourQuerier;
+
+ class BonjourBrowseQuery : public DNSSDBrowseQuery, public BonjourQuery {
+ public:
+ BonjourBrowseQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : BonjourQuery(q, eventLoop) {
+ DNSServiceErrorType result = DNSServiceBrowse(
+ &sdRef, 0, 0, "_presence._tcp", 0,
+ &BonjourBrowseQuery::handleServiceDiscoveredStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = NULL;
+ }
+ }
+
+ void startBrowsing() {
+ if (!sdRef) {
+ eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
+ }
+ else {
+ run();
+ }
+ }
+
+ void stopBrowsing() {
+ finish();
+ }
+
+ private:
+ static void handleServiceDiscoveredStatic(DNSServiceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain, void *context) {
+ static_cast<BonjourBrowseQuery*>(context)->handleServiceDiscovered(flags, interfaceIndex, errorCode, name, type, domain);
+ }
+
+ void handleServiceDiscovered(DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain) {
+ if (errorCode != kDNSServiceErr_NoError) {
+ eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this());
+ }
+ else {
+ //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl;
+ DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex));
+ if (flags & kDNSServiceFlagsAdd) {
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this());
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this());
+ }
+ }
+ }
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
index ac62b49..19ebae3 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
@@ -20,117 +20,117 @@
namespace Swift {
BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), thread(0) {
- 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];
+ 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);
+ assert(!thread);
}
boost::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() {
- return boost::shared_ptr<DNSSDBrowseQuery>(new BonjourBrowseQuery(shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDBrowseQuery>(new BonjourBrowseQuery(shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
- return boost::shared_ptr<DNSSDRegisterQuery>(new BonjourRegisterQuery(name, port, info, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDRegisterQuery>(new BonjourRegisterQuery(name, port, info, shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
- return boost::shared_ptr<DNSSDResolveServiceQuery>(new BonjourResolveServiceQuery(service, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDResolveServiceQuery>(new BonjourResolveServiceQuery(service, shared_from_this(), eventLoop));
}
boost::shared_ptr<DNSSDResolveHostnameQuery> BonjourQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
- return boost::shared_ptr<DNSSDResolveHostnameQuery>(new BonjourResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop));
+ return boost::shared_ptr<DNSSDResolveHostnameQuery>(new BonjourResolveHostnameQuery(hostname, interfaceIndex, shared_from_this(), eventLoop));
}
void BonjourQuerier::addRunningQuery(boost::shared_ptr<BonjourQuery> query) {
- {
- boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
- runningQueries.push_back(query);
- }
- runningQueriesAvailableEvent.notify_one();
- interruptSelect();
+ {
+ boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
+ runningQueries.push_back(query);
+ }
+ runningQueriesAvailableEvent.notify_one();
+ interruptSelect();
}
void BonjourQuerier::removeRunningQuery(boost::shared_ptr<BonjourQuery> query) {
- {
- boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
- erase(runningQueries, query);
- }
+ {
+ boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
+ erase(runningQueries, query);
+ }
}
void BonjourQuerier::interruptSelect() {
- char c = 0;
- write(interruptSelectWriteSocket, &c, 1);
+ char c = 0;
+ write(interruptSelectWriteSocket, &c, 1);
}
void BonjourQuerier::start() {
- assert(!thread);
- thread = new boost::thread(boost::bind(&BonjourQuerier::run, shared_from_this()));
+ assert(!thread);
+ thread = new boost::thread(boost::bind(&BonjourQuerier::run, shared_from_this()));
}
void BonjourQuerier::stop() {
- if (thread) {
- stopRequested = true;
- assert(runningQueries.empty());
- runningQueriesAvailableEvent.notify_one();
- interruptSelect();
- thread->join();
- delete thread;
- thread = NULL;
- stopRequested = false;
- }
+ if (thread) {
+ stopRequested = true;
+ assert(runningQueries.empty());
+ runningQueriesAvailableEvent.notify_one();
+ interruptSelect();
+ thread->join();
+ delete thread;
+ thread = NULL;
+ stopRequested = false;
+ }
}
void BonjourQuerier::run() {
- while (!stopRequested) {
- fd_set fdSet;
- int maxSocket;
- {
- boost::unique_lock<boost::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 boost::shared_ptr<BonjourQuery>& query, runningQueries) {
- int socketID = query->getSocketID();
- maxSocket = std::max(maxSocket, socketID);
- FD_SET(socketID, &fdSet);
- }
- }
-
- if (select(maxSocket+1, &fdSet, NULL, NULL, 0) <= 0) {
- continue;
- }
-
- if (FD_ISSET(interruptSelectReadSocket, &fdSet)) {
- char dummy;
- while (read(interruptSelectReadSocket, &dummy, 1) > 0) {}
- }
-
- {
- boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
- foreach(boost::shared_ptr<BonjourQuery> query, runningQueries) {
- if (FD_ISSET(query->getSocketID(), &fdSet)) {
- query->processResult();
- }
- }
- }
- }
+ while (!stopRequested) {
+ fd_set fdSet;
+ int maxSocket;
+ {
+ boost::unique_lock<boost::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 boost::shared_ptr<BonjourQuery>& query, runningQueries) {
+ int socketID = query->getSocketID();
+ maxSocket = std::max(maxSocket, socketID);
+ FD_SET(socketID, &fdSet);
+ }
+ }
+
+ if (select(maxSocket+1, &fdSet, NULL, NULL, 0) <= 0) {
+ continue;
+ }
+
+ if (FD_ISSET(interruptSelectReadSocket, &fdSet)) {
+ char dummy;
+ while (read(interruptSelectReadSocket, &dummy, 1) > 0) {}
+ }
+
+ {
+ boost::lock_guard<boost::mutex> lock(runningQueriesMutex);
+ foreach(boost::shared_ptr<BonjourQuery> query, runningQueries) {
+ if (FD_ISSET(query->getSocketID(), &fdSet)) {
+ query->processResult();
+ }
+ }
+ }
+ }
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h
index 532c73e..74140ac 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h
@@ -18,40 +18,40 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
namespace Swift {
- class BonjourQuerier :
- public DNSSDQuerier,
- public boost::enable_shared_from_this<BonjourQuerier> {
- public:
- BonjourQuerier(EventLoop* eventLoop);
- ~BonjourQuerier();
-
- boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
- boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
- const std::string& name, int port, const ByteArray& info);
- boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
- const DNSSDServiceID&);
- boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
- const std::string& hostname, int interfaceIndex);
-
- void start();
- void stop();
-
- private:
- friend class BonjourQuery;
-
- void addRunningQuery(boost::shared_ptr<BonjourQuery>);
- void removeRunningQuery(boost::shared_ptr<BonjourQuery>);
- void interruptSelect();
- void run();
-
- private:
- EventLoop* eventLoop;
- bool stopRequested;
- boost::thread* thread;
- boost::mutex runningQueriesMutex;
- std::list< boost::shared_ptr<BonjourQuery> > runningQueries;
- int interruptSelectReadSocket;
- int interruptSelectWriteSocket;
- boost::condition_variable runningQueriesAvailableEvent;
- };
+ class BonjourQuerier :
+ public DNSSDQuerier,
+ public boost::enable_shared_from_this<BonjourQuerier> {
+ public:
+ BonjourQuerier(EventLoop* eventLoop);
+ ~BonjourQuerier();
+
+ boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex);
+
+ void start();
+ void stop();
+
+ private:
+ friend class BonjourQuery;
+
+ void addRunningQuery(boost::shared_ptr<BonjourQuery>);
+ void removeRunningQuery(boost::shared_ptr<BonjourQuery>);
+ void interruptSelect();
+ void run();
+
+ private:
+ EventLoop* eventLoop;
+ bool stopRequested;
+ boost::thread* thread;
+ boost::mutex runningQueriesMutex;
+ std::list< boost::shared_ptr<BonjourQuery> > runningQueries;
+ int interruptSelectReadSocket;
+ int interruptSelectWriteSocket;
+ boost::condition_variable runningQueriesAvailableEvent;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
index a4036e9..c2a69b4 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
@@ -14,25 +14,25 @@ BonjourQuery::BonjourQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* event
}
BonjourQuery::~BonjourQuery() {
- DNSServiceRefDeallocate(sdRef);
+ DNSServiceRefDeallocate(sdRef);
}
void BonjourQuery::processResult() {
- boost::lock_guard<boost::mutex> lock(sdRefMutex);
- DNSServiceProcessResult(sdRef);
+ boost::lock_guard<boost::mutex> lock(sdRefMutex);
+ DNSServiceProcessResult(sdRef);
}
int BonjourQuery::getSocketID() const {
- boost::lock_guard<boost::mutex> lock(sdRefMutex);
- return DNSServiceRefSockFD(sdRef);
+ boost::lock_guard<boost::mutex> lock(sdRefMutex);
+ return DNSServiceRefSockFD(sdRef);
}
void BonjourQuery::run() {
- querier->addRunningQuery(shared_from_this());
+ querier->addRunningQuery(shared_from_this());
}
void BonjourQuery::finish() {
- querier->removeRunningQuery(shared_from_this());
+ querier->removeRunningQuery(shared_from_this());
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h
index 5e62965..2e3eb80 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h
@@ -15,27 +15,27 @@
#include <Swiften/EventLoop/EventOwner.h>
namespace Swift {
- class BonjourQuerier;
- class EventLoop;
-
- class BonjourQuery :
- public EventOwner,
- public boost::enable_shared_from_this<BonjourQuery> {
- public:
- BonjourQuery(boost::shared_ptr<BonjourQuerier>, EventLoop* eventLoop);
- virtual ~BonjourQuery();
-
- void processResult();
- int getSocketID() const;
-
- protected:
- void run();
- void finish();
-
- protected:
- EventLoop* eventLoop;
- boost::shared_ptr<BonjourQuerier> querier;
- mutable boost::mutex sdRefMutex;
- DNSServiceRef sdRef;
- };
+ class BonjourQuerier;
+ class EventLoop;
+
+ class BonjourQuery :
+ public EventOwner,
+ public boost::enable_shared_from_this<BonjourQuery> {
+ public:
+ BonjourQuery(boost::shared_ptr<BonjourQuerier>, EventLoop* eventLoop);
+ virtual ~BonjourQuery();
+
+ void processResult();
+ int getSocketID() const;
+
+ protected:
+ void run();
+ void finish();
+
+ protected:
+ EventLoop* eventLoop;
+ boost::shared_ptr<BonjourQuerier> querier;
+ mutable boost::mutex sdRefMutex;
+ DNSServiceRef sdRef;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
index b48fbf4..58b6fdd 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
@@ -15,50 +15,50 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
namespace Swift {
- class BonjourQuerier;
+ class BonjourQuerier;
- class BonjourRegisterQuery : public DNSSDRegisterQuery, public BonjourQuery {
- public:
- BonjourRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
- DNSServiceErrorType result = DNSServiceRegister(
- &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, boost::numeric_cast<unsigned short>(port),
- boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord),
- &BonjourRegisterQuery::handleServiceRegisteredStatic, this);
- if (result != kDNSServiceErr_NoError) {
- sdRef = NULL;
- }
- }
+ class BonjourRegisterQuery : public DNSSDRegisterQuery, public BonjourQuery {
+ public:
+ BonjourRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
+ DNSServiceErrorType result = DNSServiceRegister(
+ &sdRef, 0, 0, name.c_str(), "_presence._tcp", NULL, NULL, boost::numeric_cast<unsigned short>(port),
+ boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord),
+ &BonjourRegisterQuery::handleServiceRegisteredStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = NULL;
+ }
+ }
- void registerService() {
- if (sdRef) {
- run();
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
- }
+ void registerService() {
+ if (sdRef) {
+ run();
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
+ }
- void unregisterService() {
- finish();
- }
+ void unregisterService() {
+ finish();
+ }
- void updateServiceInfo(const ByteArray& txtRecord) {
- boost::lock_guard<boost::mutex> lock(sdRefMutex);
- DNSServiceUpdateRecord(sdRef, NULL, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0);
- }
+ void updateServiceInfo(const ByteArray& txtRecord) {
+ boost::lock_guard<boost::mutex> lock(sdRefMutex);
+ DNSServiceUpdateRecord(sdRef, NULL, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0);
+ }
- private:
- static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) {
- static_cast<BonjourRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain);
- }
+ private:
+ static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) {
+ static_cast<BonjourRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain);
+ }
- void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) {
- if (errorCode != kDNSServiceErr_NoError) {
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, domain, regtype, 0))), shared_from_this());
- }
- }
- };
+ void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) {
+ if (errorCode != kDNSServiceErr_NoError) {
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>(DNSSDServiceID(name, domain, regtype, 0))), shared_from_this());
+ }
+ }
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h
index 5da9f75..755984c 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h
@@ -18,55 +18,55 @@
#include <netinet/in.h>
namespace Swift {
- class BonjourQuerier;
+ class BonjourQuerier;
- class BonjourResolveHostnameQuery : public DNSSDResolveHostnameQuery, public BonjourQuery {
- public:
- BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
- DNSServiceErrorType result = DNSServiceGetAddrInfo(
- &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4,
- hostname.c_str(),
- &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this);
- if (result != kDNSServiceErr_NoError) {
- sdRef = NULL;
- }
- }
+ class BonjourResolveHostnameQuery : public DNSSDResolveHostnameQuery, public BonjourQuery {
+ public:
+ BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
+ DNSServiceErrorType result = DNSServiceGetAddrInfo(
+ &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4,
+ hostname.c_str(),
+ &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = NULL;
+ }
+ }
- //void DNSSDResolveHostnameQuery::run() {
- void run() {
- if (sdRef) {
- BonjourQuery::run();
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>()), shared_from_this());
- }
- }
+ //void DNSSDResolveHostnameQuery::run() {
+ void run() {
+ if (sdRef) {
+ BonjourQuery::run();
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onHostnameResolved), boost::optional<HostAddress>()), shared_from_this());
+ }
+ }
- void finish() {
- BonjourQuery::finish();
- }
+ void finish() {
+ BonjourQuery::finish();
+ }
- private:
- static void handleHostnameResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char*, const struct sockaddr *address, uint32_t, void *context) {
- static_cast<BonjourResolveHostnameQuery*>(context)->handleHostnameResolved(errorCode, address);
- }
+ private:
+ static void handleHostnameResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char*, const struct sockaddr *address, uint32_t, void *context) {
+ static_cast<BonjourResolveHostnameQuery*>(context)->handleHostnameResolved(errorCode, address);
+ }
- void handleHostnameResolved(DNSServiceErrorType errorCode, const struct sockaddr *rawAddress) {
- if (errorCode) {
- eventLoop->postEvent(
- boost::bind(boost::ref(onHostnameResolved),
- boost::optional<HostAddress>()),
- shared_from_this());
- }
- else {
- assert(rawAddress->sa_family == AF_INET);
- const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(rawAddress);
- uint32_t address = ntohl(sa->sin_addr.s_addr);
- eventLoop->postEvent(boost::bind(
- boost::ref(onHostnameResolved),
- HostAddress(reinterpret_cast<unsigned char*>(&address), 4)),
- shared_from_this());
- }
- }
- };
+ void handleHostnameResolved(DNSServiceErrorType errorCode, const struct sockaddr *rawAddress) {
+ if (errorCode) {
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onHostnameResolved),
+ boost::optional<HostAddress>()),
+ shared_from_this());
+ }
+ else {
+ assert(rawAddress->sa_family == AF_INET);
+ const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(rawAddress);
+ uint32_t address = ntohl(sa->sin_addr.s_addr);
+ eventLoop->postEvent(boost::bind(
+ boost::ref(onHostnameResolved),
+ HostAddress(reinterpret_cast<unsigned char*>(&address), 4)),
+ shared_from_this());
+ }
+ }
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h
index ecb6864..7833641 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h
@@ -13,52 +13,52 @@
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
namespace Swift {
- class BonjourQuerier;
+ class BonjourQuerier;
- class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery {
- public:
- BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
- DNSServiceErrorType result = DNSServiceResolve(
- &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()),
- service.getName().c_str(), service.getType().c_str(),
- service.getDomain().c_str(),
- &BonjourResolveServiceQuery::handleServiceResolvedStatic, this);
- if (result != kDNSServiceErr_NoError) {
- sdRef = NULL;
- }
- }
+ class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery {
+ public:
+ BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
+ DNSServiceErrorType result = DNSServiceResolve(
+ &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()),
+ service.getName().c_str(), service.getType().c_str(),
+ service.getDomain().c_str(),
+ &BonjourResolveServiceQuery::handleServiceResolvedStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = NULL;
+ }
+ }
- void start() {
- if (sdRef) {
- run();
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
- }
- }
+ void start() {
+ if (sdRef) {
+ run();
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
+ }
+ }
- void stop() {
- finish();
- }
+ void stop() {
+ finish();
+ }
- private:
- static void handleServiceResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord, void *context) {
- static_cast<BonjourResolveServiceQuery*>(context)->handleServiceResolved(errorCode, fullname, hosttarget, port, txtLen, txtRecord);
- }
+ private:
+ static void handleServiceResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord, void *context) {
+ static_cast<BonjourResolveServiceQuery*>(context)->handleServiceResolved(errorCode, fullname, hosttarget, port, txtLen, txtRecord);
+ }
- void handleServiceResolved(DNSServiceErrorType errorCode, const char* fullName, const char* host, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord) {
- if (errorCode != kDNSServiceErr_NoError) {
- eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
- }
- else {
- //std::cout << "Service resolved: name:" << fullName << " host:" << host << " port:" << port << std::endl;
- eventLoop->postEvent(
- boost::bind(
- boost::ref(onServiceResolved),
- Result(std::string(fullName), std::string(host), port,
- createByteArray(reinterpret_cast<const char*>(txtRecord), txtLen))),
- shared_from_this());
- }
- }
- };
+ void handleServiceResolved(DNSServiceErrorType errorCode, const char* fullName, const char* host, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord) {
+ if (errorCode != kDNSServiceErr_NoError) {
+ eventLoop->postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
+ }
+ else {
+ //std::cout << "Service resolved: name:" << fullName << " host:" << host << " port:" << port << std::endl;
+ eventLoop->postEvent(
+ boost::bind(
+ boost::ref(onServiceResolved),
+ Result(std::string(fullName), std::string(host), port,
+ createByteArray(reinterpret_cast<const char*>(txtRecord), txtLen))),
+ shared_from_this());
+ }
+ }
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h
index d02490c..5502678 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h
@@ -10,15 +10,15 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
namespace Swift {
- class DNSSDBrowseQuery {
- public:
- virtual ~DNSSDBrowseQuery();
+ class DNSSDBrowseQuery {
+ public:
+ virtual ~DNSSDBrowseQuery();
- virtual void startBrowsing() = 0;
- virtual void stopBrowsing() = 0;
+ virtual void startBrowsing() = 0;
+ virtual void stopBrowsing() = 0;
- boost::signal<void (const DNSSDServiceID&)> onServiceAdded;
- boost::signal<void (const DNSSDServiceID&)> onServiceRemoved;
- boost::signal<void ()> onError;
- };
+ boost::signal<void (const DNSSDServiceID&)> onServiceAdded;
+ boost::signal<void (const DNSSDServiceID&)> onServiceRemoved;
+ boost::signal<void ()> onError;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
index 924b7c9..85051fe 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
@@ -11,25 +11,25 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- class DNSSDServiceID;
- class DNSSDBrowseQuery;
- class DNSSDRegisterQuery;
- class DNSSDResolveServiceQuery;
- class DNSSDResolveHostnameQuery;
+ class DNSSDServiceID;
+ class DNSSDBrowseQuery;
+ class DNSSDRegisterQuery;
+ class DNSSDResolveServiceQuery;
+ class DNSSDResolveHostnameQuery;
- class DNSSDQuerier {
- public:
- virtual ~DNSSDQuerier();
+ class DNSSDQuerier {
+ public:
+ virtual ~DNSSDQuerier();
- virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void start() = 0;
+ virtual void stop() = 0;
- virtual boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0;
- virtual boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
- const std::string& name, int port, const ByteArray& info) = 0;
- virtual boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
- const DNSSDServiceID&) = 0;
- virtual boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
- const std::string& hostname, int interfaceIndex) = 0;
- };
+ virtual boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0;
+ virtual boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info) = 0;
+ virtual boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&) = 0;
+ virtual boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex) = 0;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h
index 08e4608..e8e07bd 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h
@@ -13,14 +13,14 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
namespace Swift {
- class DNSSDRegisterQuery {
- public:
- virtual ~DNSSDRegisterQuery();
+ class DNSSDRegisterQuery {
+ public:
+ virtual ~DNSSDRegisterQuery();
- virtual void registerService() = 0;
- virtual void unregisterService() = 0;
- virtual void updateServiceInfo(const ByteArray& info) = 0;
+ virtual void registerService() = 0;
+ virtual void unregisterService() = 0;
+ virtual void updateServiceInfo(const ByteArray& info) = 0;
- boost::signal<void (boost::optional<DNSSDServiceID>)> onRegisterFinished;
- };
+ boost::signal<void (boost::optional<DNSSDServiceID>)> onRegisterFinished;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
index f8ad3de..a4f818c 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
@@ -12,13 +12,13 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class DNSSDResolveHostnameQuery {
- public:
- virtual ~DNSSDResolveHostnameQuery();
+ class DNSSDResolveHostnameQuery {
+ public:
+ virtual ~DNSSDResolveHostnameQuery();
- virtual void run() = 0;
- virtual void finish() = 0;
+ virtual void run() = 0;
+ virtual void finish() = 0;
- boost::signal<void (const boost::optional<HostAddress>&)> onHostnameResolved;
- };
+ boost::signal<void (const boost::optional<HostAddress>&)> onHostnameResolved;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
index 4728927..4d25075 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
@@ -13,22 +13,22 @@
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
namespace Swift {
- class DNSSDResolveServiceQuery {
- public:
- struct Result {
- Result(const std::string& fullName, const std::string& host, int port, const ByteArray& info) :
- fullName(fullName), host(host), port(port), info(info) {}
- std::string fullName;
- std::string host;
- int port;
- ByteArray info;
- };
+ class DNSSDResolveServiceQuery {
+ public:
+ struct Result {
+ Result(const std::string& fullName, const std::string& host, int port, const ByteArray& info) :
+ fullName(fullName), host(host), port(port), info(info) {}
+ std::string fullName;
+ std::string host;
+ int port;
+ ByteArray info;
+ };
- virtual ~DNSSDResolveServiceQuery();
+ virtual ~DNSSDResolveServiceQuery();
- virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void start() = 0;
+ virtual void stop() = 0;
- boost::signal<void (const boost::optional<Result>&)> onServiceResolved;
- };
+ boost::signal<void (const boost::optional<Result>&)> onServiceResolved;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
index a7dc0ee..5f8c2eb 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
@@ -11,64 +11,64 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API DNSSDServiceID {
- public:
- static const char* PresenceServiceType;
+ class SWIFTEN_API DNSSDServiceID {
+ public:
+ static const char* PresenceServiceType;
- DNSSDServiceID(
- const std::string& name,
- const std::string& domain,
- const std::string& type = PresenceServiceType,
- int networkInterface = -1) :
- name(name),
- domain(domain),
- type(type),
- networkInterface(networkInterface) {
- }
+ DNSSDServiceID(
+ const std::string& name,
+ const std::string& domain,
+ const std::string& type = PresenceServiceType,
+ int networkInterface = -1) :
+ name(name),
+ domain(domain),
+ type(type),
+ networkInterface(networkInterface) {
+ }
- bool operator==(const DNSSDServiceID& o) const {
- return name == o.name && domain == o.domain && type == o.type && (networkInterface != 0 && o.networkInterface != 0 ? networkInterface == o.networkInterface : true);
- }
+ bool operator==(const DNSSDServiceID& o) const {
+ return name == o.name && domain == o.domain && type == o.type && (networkInterface != 0 && o.networkInterface != 0 ? networkInterface == o.networkInterface : true);
+ }
- bool operator<(const DNSSDServiceID& o) const {
- if (o.name == name) {
- if (o.domain == domain) {
- if (o.type == type) {
- return networkInterface < o.networkInterface;
- }
- else {
- return type < o.type;
- }
- }
- else {
- return domain < o.domain;
- }
- }
- else {
- return o.name < name;
- }
- }
+ bool operator<(const DNSSDServiceID& o) const {
+ if (o.name == name) {
+ if (o.domain == domain) {
+ if (o.type == type) {
+ return networkInterface < o.networkInterface;
+ }
+ else {
+ return type < o.type;
+ }
+ }
+ else {
+ return domain < o.domain;
+ }
+ }
+ else {
+ return o.name < name;
+ }
+ }
- const std::string& getName() const {
- return name;
- }
+ const std::string& getName() const {
+ return name;
+ }
- const std::string& getDomain() const {
- return domain;
- }
+ const std::string& getDomain() const {
+ return domain;
+ }
- const std::string& getType() const {
- return type;
- }
+ const std::string& getType() const {
+ return type;
+ }
- int getNetworkInterfaceID() const {
- return networkInterface;
- }
+ int getNetworkInterfaceID() const {
+ return networkInterface;
+ }
- private:
- std::string name;
- std::string domain;
- std::string type;
- int networkInterface;
- };
+ private:
+ std::string name;
+ std::string domain;
+ std::string type;
+ int networkInterface;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h
index 07ed44c..860de41 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h
@@ -10,19 +10,19 @@
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
namespace Swift {
- class FakeDNSSDQuerier;
+ class FakeDNSSDQuerier;
- class FakeDNSSDBrowseQuery : public DNSSDBrowseQuery, public FakeDNSSDQuery {
- public:
- FakeDNSSDBrowseQuery(boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier) {
- }
+ class FakeDNSSDBrowseQuery : public DNSSDBrowseQuery, public FakeDNSSDQuery {
+ public:
+ FakeDNSSDBrowseQuery(boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier) {
+ }
- void startBrowsing() {
- run();
- }
+ void startBrowsing() {
+ run();
+ }
- void stopBrowsing() {
- finish();
- }
- };
+ void stopBrowsing() {
+ finish();
+ }
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
index 74c152e..89698a6 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
@@ -24,117 +24,117 @@ FakeDNSSDQuerier::FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLo
}
FakeDNSSDQuerier::~FakeDNSSDQuerier() {
- if (!runningQueries.empty()) {
- std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl;
- }
+ if (!runningQueries.empty()) {
+ std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl;
+ }
}
boost::shared_ptr<DNSSDBrowseQuery> FakeDNSSDQuerier::createBrowseQuery() {
- return boost::shared_ptr<DNSSDBrowseQuery>(new FakeDNSSDBrowseQuery(shared_from_this()));
+ return boost::shared_ptr<DNSSDBrowseQuery>(new FakeDNSSDBrowseQuery(shared_from_this()));
}
boost::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
- return boost::shared_ptr<DNSSDRegisterQuery>(new FakeDNSSDRegisterQuery(name, port, info, shared_from_this()));
+ return boost::shared_ptr<DNSSDRegisterQuery>(new FakeDNSSDRegisterQuery(name, port, info, shared_from_this()));
}
boost::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
- return boost::shared_ptr<DNSSDResolveServiceQuery>(new FakeDNSSDResolveServiceQuery(service, shared_from_this()));
+ return boost::shared_ptr<DNSSDResolveServiceQuery>(new FakeDNSSDResolveServiceQuery(service, shared_from_this()));
}
boost::shared_ptr<DNSSDResolveHostnameQuery> FakeDNSSDQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
- return boost::shared_ptr<DNSSDResolveHostnameQuery>(new FakeDNSSDResolveHostnameQuery(hostname, interfaceIndex, shared_from_this()));
+ return boost::shared_ptr<DNSSDResolveHostnameQuery>(new FakeDNSSDResolveHostnameQuery(hostname, interfaceIndex, shared_from_this()));
}
void FakeDNSSDQuerier::addRunningQuery(boost::shared_ptr<FakeDNSSDQuery> query) {
- runningQueries.push_back(query);
- allQueriesEverRun.push_back(query);
- if (boost::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = boost::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) {
- foreach(const DNSSDServiceID& service, services) {
- eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this());
- }
- }
- else if (boost::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = boost::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());
- }
- }
- }
- else if (boost::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = boost::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) {
- DNSSDServiceID service(registerQuery->name, domain);
- eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this());
- }
- else if (boost::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = boost::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());
- }
- }
+ runningQueries.push_back(query);
+ allQueriesEverRun.push_back(query);
+ if (boost::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = boost::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) {
+ foreach(const DNSSDServiceID& service, services) {
+ eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this());
+ }
+ }
+ else if (boost::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = boost::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());
+ }
+ }
+ }
+ else if (boost::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = boost::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) {
+ DNSSDServiceID service(registerQuery->name, domain);
+ eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this());
+ }
+ else if (boost::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = boost::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(boost::shared_ptr<FakeDNSSDQuery> query) {
- erase(runningQueries, query);
+ erase(runningQueries, query);
}
void FakeDNSSDQuerier::addService(const DNSSDServiceID& id) {
- services.insert(id);
- foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
- eventLoop->postEvent(boost::bind(boost::ref(query->onServiceAdded), id), shared_from_this());
- }
+ services.insert(id);
+ foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& 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 boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
- eventLoop->postEvent(boost::bind(boost::ref(query->onServiceRemoved), id), shared_from_this());
- }
+ services.erase(id);
+ serviceInfo.erase(id);
+ foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& 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 boost::shared_ptr<FakeDNSSDResolveServiceQuery>& query, getQueries<FakeDNSSDResolveServiceQuery>()) {
- if (query->service == id) {
- eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this());
- }
- }
+ std::pair<ServiceInfoMap::iterator, bool> r = serviceInfo.insert(std::make_pair(id, info));
+ if (!r.second) {
+ r.first->second = info;
+ }
+ foreach(const boost::shared_ptr<FakeDNSSDResolveServiceQuery>& 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 boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
- if (query->name == name && query->port == port && query->info == info) {
- return true;
- }
- }
- return false;
+ foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
+ if (query->name == name && query->port == port && query->info == info) {
+ return true;
+ }
+ }
+ return false;
}
void FakeDNSSDQuerier::setBrowseError() {
- foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
- eventLoop->postEvent(boost::ref(query->onError), shared_from_this());
- }
+ foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
+ eventLoop->postEvent(boost::ref(query->onError), shared_from_this());
+ }
}
void FakeDNSSDQuerier::setRegisterError() {
- foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
- eventLoop->postEvent(boost::bind(boost::ref(query->onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
- }
+ foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& 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 boost::shared_ptr<FakeDNSSDResolveHostnameQuery>& query, getQueries<FakeDNSSDResolveHostnameQuery>()) {
- if (query->hostname == hostname) {
- eventLoop->postEvent(boost::bind(
- boost::ref(query->onHostnameResolved), address), shared_from_this());
- }
- }
+ addresses[hostname] = address;
+ foreach(const boost::shared_ptr<FakeDNSSDResolveHostnameQuery>& query, getQueries<FakeDNSSDResolveHostnameQuery>()) {
+ if (query->hostname == hostname) {
+ eventLoop->postEvent(boost::bind(
+ boost::ref(query->onHostnameResolved), address), shared_from_this());
+ }
+ }
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
index e68c36d..536bf90 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
@@ -21,78 +21,78 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class FakeDNSSDQuery;
- class FakeDNSSDBrowseQuery;
- class EventLoop;
+ class FakeDNSSDQuery;
+ class FakeDNSSDBrowseQuery;
+ class EventLoop;
- class SWIFTEN_API FakeDNSSDQuerier :
- public DNSSDQuerier,
- public EventOwner,
- public boost::enable_shared_from_this<FakeDNSSDQuerier> {
- public:
- FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLoop);
- ~FakeDNSSDQuerier();
+ class SWIFTEN_API FakeDNSSDQuerier :
+ public DNSSDQuerier,
+ public EventOwner,
+ public boost::enable_shared_from_this<FakeDNSSDQuerier> {
+ public:
+ FakeDNSSDQuerier(const std::string& domain, EventLoop* eventLoop);
+ ~FakeDNSSDQuerier();
- void start() {}
- void stop() {}
+ void start() {}
+ void stop() {}
- void clearAllQueriesEverRun() {
- allQueriesEverRun.clear();
- }
+ void clearAllQueriesEverRun() {
+ allQueriesEverRun.clear();
+ }
- boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
- boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
- const std::string& name, int port, const ByteArray& info);
- boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
- const DNSSDServiceID&);
- boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
- const std::string& hostname, int interfaceIndex);
+ boost::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ boost::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ boost::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ boost::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex);
- void addRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
- void removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
+ void addRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
+ void removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
- void addService(const DNSSDServiceID& id);
- void removeService(const DNSSDServiceID& id);
- void setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info);
- bool isServiceRegistered(const std::string& name, int port, const ByteArray& info);
- void setAddress(const std::string& hostname, boost::optional<HostAddress> address);
+ void addService(const DNSSDServiceID& id);
+ void removeService(const DNSSDServiceID& id);
+ void setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info);
+ bool isServiceRegistered(const std::string& name, int port, const ByteArray& info);
+ void setAddress(const std::string& hostname, boost::optional<HostAddress> address);
- void setBrowseError();
- void setRegisterError();
+ void setBrowseError();
+ void setRegisterError();
- public:
- template<typename T>
- std::vector< boost::shared_ptr<T> > getAllQueriesEverRun() const {
- std::vector< boost::shared_ptr<T> > result;
- for (QueryList::const_iterator i = allQueriesEverRun.begin(); i != allQueriesEverRun.end(); ++i) {
- if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) {
- result.push_back(resultQuery);
- }
- }
- return result;
- }
+ public:
+ template<typename T>
+ std::vector< boost::shared_ptr<T> > getAllQueriesEverRun() const {
+ std::vector< boost::shared_ptr<T> > result;
+ for (QueryList::const_iterator i = allQueriesEverRun.begin(); i != allQueriesEverRun.end(); ++i) {
+ if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) {
+ result.push_back(resultQuery);
+ }
+ }
+ return result;
+ }
- private:
- template<typename T>
- std::vector< boost::shared_ptr<T> > getQueries() const {
- std::vector< boost::shared_ptr<T> > result;
- for (QueryList::const_iterator i = runningQueries.begin(); i != runningQueries.end(); ++i) {
- if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) {
- result.push_back(resultQuery);
- }
- }
- return result;
- }
+ private:
+ template<typename T>
+ std::vector< boost::shared_ptr<T> > getQueries() const {
+ std::vector< boost::shared_ptr<T> > result;
+ for (QueryList::const_iterator i = runningQueries.begin(); i != runningQueries.end(); ++i) {
+ if (boost::shared_ptr<T> resultQuery = boost::dynamic_pointer_cast<T>(*i)) {
+ result.push_back(resultQuery);
+ }
+ }
+ return result;
+ }
- private:
- std::string domain;
- EventLoop* eventLoop;
- typedef std::list< boost::shared_ptr<FakeDNSSDQuery> > QueryList;
- QueryList runningQueries;
- QueryList allQueriesEverRun;
- std::set<DNSSDServiceID> services;
- typedef std::map<DNSSDServiceID,DNSSDResolveServiceQuery::Result> ServiceInfoMap;
- ServiceInfoMap serviceInfo;
- std::map<std::string, boost::optional<HostAddress> > addresses;
- };
+ private:
+ std::string domain;
+ EventLoop* eventLoop;
+ typedef std::list< boost::shared_ptr<FakeDNSSDQuery> > QueryList;
+ QueryList runningQueries;
+ QueryList allQueriesEverRun;
+ std::set<DNSSDServiceID> services;
+ typedef std::map<DNSSDServiceID,DNSSDResolveServiceQuery::Result> ServiceInfoMap;
+ ServiceInfoMap serviceInfo;
+ std::map<std::string, boost::optional<HostAddress> > addresses;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp
index a6456d9..980b757 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp
@@ -17,11 +17,11 @@ FakeDNSSDQuery::~FakeDNSSDQuery() {
}
void FakeDNSSDQuery::run() {
- querier->addRunningQuery(shared_from_this());
+ querier->addRunningQuery(shared_from_this());
}
void FakeDNSSDQuery::finish() {
- querier->removeRunningQuery(shared_from_this());
+ querier->removeRunningQuery(shared_from_this());
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h
index 22fa982..0d7dedc 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h
@@ -12,20 +12,20 @@
#include <Swiften/EventLoop/EventOwner.h>
namespace Swift {
- class FakeDNSSDQuerier;
+ class FakeDNSSDQuerier;
- class FakeDNSSDQuery :
- public EventOwner,
- public boost::enable_shared_from_this<FakeDNSSDQuery> {
- public:
- FakeDNSSDQuery(boost::shared_ptr<FakeDNSSDQuerier>);
- virtual ~FakeDNSSDQuery();
-
- protected:
- void run();
- void finish();
-
- protected:
- boost::shared_ptr<FakeDNSSDQuerier> querier;
- };
+ class FakeDNSSDQuery :
+ public EventOwner,
+ public boost::enable_shared_from_this<FakeDNSSDQuery> {
+ public:
+ FakeDNSSDQuery(boost::shared_ptr<FakeDNSSDQuerier>);
+ virtual ~FakeDNSSDQuery();
+
+ protected:
+ void run();
+ void finish();
+
+ protected:
+ boost::shared_ptr<FakeDNSSDQuerier> querier;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
index 5e6fe7d..484b2c2 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
@@ -13,27 +13,27 @@
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
namespace Swift {
- class FakeDNSSDQuerier;
+ class FakeDNSSDQuerier;
- class FakeDNSSDRegisterQuery : public DNSSDRegisterQuery, public FakeDNSSDQuery {
- public:
- FakeDNSSDRegisterQuery(const std::string& name, int port, const ByteArray& info, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) {
- }
+ class FakeDNSSDRegisterQuery : public DNSSDRegisterQuery, public FakeDNSSDQuery {
+ public:
+ FakeDNSSDRegisterQuery(const std::string& name, int port, const ByteArray& info, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) {
+ }
- void registerService() {
- run();
- }
+ void registerService() {
+ run();
+ }
- void updateServiceInfo(const ByteArray& i) {
- info = i;
- }
+ void updateServiceInfo(const ByteArray& i) {
+ info = i;
+ }
- void unregisterService() {
- finish();
- }
+ void unregisterService() {
+ finish();
+ }
- std::string name;
- int port;
- ByteArray info;
- };
+ std::string name;
+ int port;
+ ByteArray info;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h
index 77da7ae..0b6a95d 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h
@@ -13,22 +13,22 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class FakeDNSSDQuerier;
+ class FakeDNSSDQuerier;
- class FakeDNSSDResolveHostnameQuery : public DNSSDResolveHostnameQuery, public FakeDNSSDQuery {
- public:
- FakeDNSSDResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), hostname(hostname), interfaceIndex(interfaceIndex) {
- }
+ class FakeDNSSDResolveHostnameQuery : public DNSSDResolveHostnameQuery, public FakeDNSSDQuery {
+ public:
+ FakeDNSSDResolveHostnameQuery(const std::string& hostname, int interfaceIndex, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), hostname(hostname), interfaceIndex(interfaceIndex) {
+ }
- void run() {
- FakeDNSSDQuery::run();
- }
+ void run() {
+ FakeDNSSDQuery::run();
+ }
- void finish() {
- FakeDNSSDQuery::finish();
- }
+ void finish() {
+ FakeDNSSDQuery::finish();
+ }
- std::string hostname;
- int interfaceIndex;
- };
+ std::string hostname;
+ int interfaceIndex;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h
index a20cc16..180fbb2 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h
@@ -11,21 +11,21 @@
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
namespace Swift {
- class FakeDNSSDQuerier;
+ class FakeDNSSDQuerier;
- class FakeDNSSDResolveServiceQuery : public DNSSDResolveServiceQuery, public FakeDNSSDQuery {
- public:
- FakeDNSSDResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), service(service) {
- }
+ class FakeDNSSDResolveServiceQuery : public DNSSDResolveServiceQuery, public FakeDNSSDQuery {
+ public:
+ FakeDNSSDResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), service(service) {
+ }
- void start() {
- run();
- }
+ void start() {
+ run();
+ }
- void stop() {
- finish();
- }
+ void stop() {
+ finish();
+ }
- DNSSDServiceID service;
- };
+ DNSSDServiceID service;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp
index ee7194f..f2bfa2e 100644
--- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp
+++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp
@@ -20,20 +20,20 @@ PlatformDNSSDQuerierFactory::PlatformDNSSDQuerierFactory(EventLoop* eventLoop) :
boost::shared_ptr<DNSSDQuerier> PlatformDNSSDQuerierFactory::createQuerier() {
#if defined(HAVE_BONJOUR)
- return boost::shared_ptr<DNSSDQuerier>(new BonjourQuerier(eventLoop));
+ return boost::shared_ptr<DNSSDQuerier>(new BonjourQuerier(eventLoop));
#elif defined(HAVE_AVAHI)
- return boost::shared_ptr<DNSSDQuerier>(new AvahiQuerier(eventLoop));
+ return boost::shared_ptr<DNSSDQuerier>(new AvahiQuerier(eventLoop));
#else
- (void)eventLoop;
- return boost::shared_ptr<DNSSDQuerier>();
+ (void)eventLoop;
+ return boost::shared_ptr<DNSSDQuerier>();
#endif
}
bool PlatformDNSSDQuerierFactory::canCreate() {
#if defined(HAVE_BONJOUR) || defined(HAVE_AVAHI)
- return true;
+ return true;
#else
- return false;
+ return false;
#endif
}
diff --git a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h
index 2ba8b25..dc40d01 100644
--- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h
+++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h
@@ -11,18 +11,18 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class DNSSDQuerier;
- class EventLoop;
+ class DNSSDQuerier;
+ class EventLoop;
- class SWIFTEN_API PlatformDNSSDQuerierFactory {
- public:
- PlatformDNSSDQuerierFactory(EventLoop* eventLoop);
+ class SWIFTEN_API PlatformDNSSDQuerierFactory {
+ public:
+ PlatformDNSSDQuerierFactory(EventLoop* eventLoop);
- boost::shared_ptr<DNSSDQuerier> createQuerier();
+ boost::shared_ptr<DNSSDQuerier> createQuerier();
- bool canCreate();
+ bool canCreate();
- private:
- EventLoop* eventLoop;
- };
+ private:
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
index e39b32b..435b065 100644
--- a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
@@ -20,49 +20,49 @@
namespace Swift {
IncomingLinkLocalSession::IncomingLinkLocalSession(
- const JID& localJID,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory) :
- Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
- initialized(false) {
- setLocalJID(localJID);
+ const JID& localJID,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory) :
+ Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
+ initialized(false) {
+ setLocalJID(localJID);
}
void IncomingLinkLocalSession::handleStreamStart(const ProtocolHeader& incomingHeader) {
- setRemoteJID(JID(incomingHeader.getFrom()));
- if (!getRemoteJID().isValid()) {
- finishSession();
- return;
- }
+ setRemoteJID(JID(incomingHeader.getFrom()));
+ if (!getRemoteJID().isValid()) {
+ finishSession();
+ return;
+ }
- ProtocolHeader header;
- header.setFrom(getLocalJID());
- getXMPPLayer()->writeHeader(header);
+ ProtocolHeader header;
+ header.setFrom(getLocalJID());
+ getXMPPLayer()->writeHeader(header);
- if (incomingHeader.getVersion() == "1.0") {
- getXMPPLayer()->writeElement(boost::make_shared<StreamFeatures>());
- }
- else {
- setInitialized();
- }
+ if (incomingHeader.getVersion() == "1.0") {
+ getXMPPLayer()->writeElement(boost::make_shared<StreamFeatures>());
+ }
+ else {
+ setInitialized();
+ }
}
void IncomingLinkLocalSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
- // If we get our first stanza before streamfeatures, our session is implicitly
- // initialized
- if (stanza && !isInitialized()) {
- setInitialized();
- }
-
- onElementReceived(element);
+ boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
+ // If we get our first stanza before streamfeatures, our session is implicitly
+ // initialized
+ if (stanza && !isInitialized()) {
+ setInitialized();
+ }
+
+ onElementReceived(element);
}
void IncomingLinkLocalSession::setInitialized() {
- initialized = true;
- onSessionStarted();
+ initialized = true;
+ onSessionStarted();
}
diff --git a/Swiften/LinkLocal/IncomingLinkLocalSession.h b/Swiften/LinkLocal/IncomingLinkLocalSession.h
index 9ac6bac..44a8719 100644
--- a/Swiften/LinkLocal/IncomingLinkLocalSession.h
+++ b/Swiften/LinkLocal/IncomingLinkLocalSession.h
@@ -15,31 +15,31 @@
#include <Swiften/Session/Session.h>
namespace Swift {
- class ProtocolHeader;
- class XMLParserFactory;
- class ToplevelElement;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
-
- class SWIFTEN_API IncomingLinkLocalSession : public Session {
- public:
- IncomingLinkLocalSession(
- const JID& localJID,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory);
-
- boost::signal<void ()> onSessionStarted;
-
- private:
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamStart(const ProtocolHeader&);
- void setInitialized();
- bool isInitialized() const {
- return initialized;
- }
-
- bool initialized;
- };
+ class ProtocolHeader;
+ class XMLParserFactory;
+ class ToplevelElement;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+
+ class SWIFTEN_API IncomingLinkLocalSession : public Session {
+ public:
+ IncomingLinkLocalSession(
+ const JID& localJID,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+
+ boost::signal<void ()> onSessionStarted;
+
+ private:
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+ void setInitialized();
+ bool isInitialized() const {
+ return initialized;
+ }
+
+ bool initialized;
+ };
}
diff --git a/Swiften/LinkLocal/LinkLocalConnector.cpp b/Swiften/LinkLocal/LinkLocalConnector.cpp
index 7533f24..9123e8e 100644
--- a/Swiften/LinkLocal/LinkLocalConnector.cpp
+++ b/Swiften/LinkLocal/LinkLocalConnector.cpp
@@ -18,61 +18,61 @@
namespace Swift {
LinkLocalConnector::LinkLocalConnector(
- const LinkLocalService& service,
- boost::shared_ptr<DNSSDQuerier> querier,
- boost::shared_ptr<Connection> connection) :
- service(service),
- querier(querier),
- connection(connection) {
+ const LinkLocalService& service,
+ boost::shared_ptr<DNSSDQuerier> querier,
+ boost::shared_ptr<Connection> connection) :
+ service(service),
+ querier(querier),
+ connection(connection) {
}
LinkLocalConnector::~LinkLocalConnector() {
- assert(!resolveQuery);
+ assert(!resolveQuery);
}
void LinkLocalConnector::connect() {
- resolveQuery = querier->createResolveHostnameQuery(
- service.getHostname(),
- service.getID().getNetworkInterfaceID());
- resolveQueryHostNameResolvedConnection = resolveQuery->onHostnameResolved.connect(boost::bind(
- &LinkLocalConnector::handleHostnameResolved,
- boost::dynamic_pointer_cast<LinkLocalConnector>(shared_from_this()),
- _1));
- resolveQuery->run();
+ resolveQuery = querier->createResolveHostnameQuery(
+ service.getHostname(),
+ service.getID().getNetworkInterfaceID());
+ resolveQueryHostNameResolvedConnection = resolveQuery->onHostnameResolved.connect(boost::bind(
+ &LinkLocalConnector::handleHostnameResolved,
+ boost::dynamic_pointer_cast<LinkLocalConnector>(shared_from_this()),
+ _1));
+ resolveQuery->run();
}
void LinkLocalConnector::cancel() {
- if (resolveQuery) {
- resolveQuery->finish();
- resolveQueryHostNameResolvedConnection.disconnect();
- resolveQuery.reset();
- }
- connectionConnectFinishedConnection.disconnect();
- connection->disconnect();
+ if (resolveQuery) {
+ resolveQuery->finish();
+ resolveQueryHostNameResolvedConnection.disconnect();
+ resolveQuery.reset();
+ }
+ connectionConnectFinishedConnection.disconnect();
+ connection->disconnect();
}
void LinkLocalConnector::handleHostnameResolved(const boost::optional<HostAddress>& address) {
- resolveQuery->finish();
- resolveQueryHostNameResolvedConnection.disconnect();
- resolveQuery.reset();
- if (address) {
- connectionConnectFinishedConnection = connection->onConnectFinished.connect(
- boost::bind(&LinkLocalConnector::handleConnected, shared_from_this(), _1));
- connection->connect(HostAddressPort(*address, service.getPort()));
- }
- else {
- onConnectFinished(true);
- }
+ resolveQuery->finish();
+ resolveQueryHostNameResolvedConnection.disconnect();
+ resolveQuery.reset();
+ if (address) {
+ connectionConnectFinishedConnection = connection->onConnectFinished.connect(
+ boost::bind(&LinkLocalConnector::handleConnected, shared_from_this(), _1));
+ connection->connect(HostAddressPort(*address, service.getPort()));
+ }
+ else {
+ onConnectFinished(true);
+ }
}
void LinkLocalConnector::handleConnected(bool error) {
- onConnectFinished(error);
- assert(connectionConnectFinishedConnection.connected());
- connectionConnectFinishedConnection.disconnect();
+ onConnectFinished(error);
+ assert(connectionConnectFinishedConnection.connected());
+ connectionConnectFinishedConnection.disconnect();
}
void LinkLocalConnector::queueElement(boost::shared_ptr<ToplevelElement> element) {
- queuedElements.push_back(element);
+ queuedElements.push_back(element);
}
diff --git a/Swiften/LinkLocal/LinkLocalConnector.h b/Swiften/LinkLocal/LinkLocalConnector.h
index 363ae4b..4e05dce 100644
--- a/Swiften/LinkLocal/LinkLocalConnector.h
+++ b/Swiften/LinkLocal/LinkLocalConnector.h
@@ -17,51 +17,51 @@
#include <Swiften/Network/Connection.h>
namespace Swift {
- class ConnectionFactory;
- class HostAddress;
- class ToplevelElement;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
- class DNSSDQuerier;
- class DNSSDResolveHostnameQuery;
+ class ConnectionFactory;
+ class HostAddress;
+ class ToplevelElement;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+ class DNSSDQuerier;
+ class DNSSDResolveHostnameQuery;
- class SWIFTEN_API LinkLocalConnector : public boost::enable_shared_from_this<LinkLocalConnector> {
- public:
- LinkLocalConnector(
- const LinkLocalService& service,
- boost::shared_ptr<DNSSDQuerier> querier,
- boost::shared_ptr<Connection> connection);
- ~LinkLocalConnector();
+ class SWIFTEN_API LinkLocalConnector : public boost::enable_shared_from_this<LinkLocalConnector> {
+ public:
+ LinkLocalConnector(
+ const LinkLocalService& service,
+ boost::shared_ptr<DNSSDQuerier> querier,
+ boost::shared_ptr<Connection> connection);
+ ~LinkLocalConnector();
- const LinkLocalService& getService() const {
- return service;
- }
+ const LinkLocalService& getService() const {
+ return service;
+ }
- void connect();
- void cancel();
- void queueElement(boost::shared_ptr<ToplevelElement> element);
+ void connect();
+ void cancel();
+ void queueElement(boost::shared_ptr<ToplevelElement> element);
- const std::vector<boost::shared_ptr<ToplevelElement> >& getQueuedElements() const {
- return queuedElements;
- }
+ const std::vector<boost::shared_ptr<ToplevelElement> >& getQueuedElements() const {
+ return queuedElements;
+ }
- boost::shared_ptr<Connection> getConnection() const {
- return connection;
- }
+ boost::shared_ptr<Connection> getConnection() const {
+ return connection;
+ }
- boost::signal<void (bool)> onConnectFinished;
+ boost::signal<void (bool)> onConnectFinished;
- private:
- void handleHostnameResolved(const boost::optional<HostAddress>& address);
- void handleConnected(bool error);
+ private:
+ void handleHostnameResolved(const boost::optional<HostAddress>& address);
+ void handleConnected(bool error);
- private:
- LinkLocalService service;
- boost::shared_ptr<DNSSDQuerier> querier;
- boost::shared_ptr<DNSSDResolveHostnameQuery> resolveQuery;
- boost::bsignals::connection resolveQueryHostNameResolvedConnection;
- boost::shared_ptr<Connection> connection;
- boost::bsignals::connection connectionConnectFinishedConnection;
- std::vector<boost::shared_ptr<ToplevelElement> > queuedElements;
- };
+ private:
+ LinkLocalService service;
+ boost::shared_ptr<DNSSDQuerier> querier;
+ boost::shared_ptr<DNSSDResolveHostnameQuery> resolveQuery;
+ boost::bsignals::connection resolveQueryHostNameResolvedConnection;
+ boost::shared_ptr<Connection> connection;
+ boost::bsignals::connection connectionConnectFinishedConnection;
+ std::vector<boost::shared_ptr<ToplevelElement> > queuedElements;
+ };
}
diff --git a/Swiften/LinkLocal/LinkLocalService.cpp b/Swiften/LinkLocal/LinkLocalService.cpp
index ecf3ea1..636362e 100644
--- a/Swiften/LinkLocal/LinkLocalService.cpp
+++ b/Swiften/LinkLocal/LinkLocalService.cpp
@@ -9,25 +9,25 @@
namespace Swift {
std::string LinkLocalService::getDescription() const {
- LinkLocalServiceInfo info = 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 getName();
+ LinkLocalServiceInfo info = 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 getName();
}
JID LinkLocalService::getJID() const {
- return JID(getName());
+ return JID(getName());
}
}
diff --git a/Swiften/LinkLocal/LinkLocalService.h b/Swiften/LinkLocal/LinkLocalService.h
index d8096b1..9b0e2ab 100644
--- a/Swiften/LinkLocal/LinkLocalService.h
+++ b/Swiften/LinkLocal/LinkLocalService.h
@@ -15,40 +15,40 @@
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
namespace Swift {
- class SWIFTEN_API LinkLocalService {
- public:
- LinkLocalService(
- const DNSSDServiceID& id,
- const DNSSDResolveServiceQuery::Result& info) :
- id(id),
- info(info) {}
-
- const DNSSDServiceID& getID() const {
- return id;
- }
-
- const std::string& getName() const {
- return id.getName();
- }
-
- int getPort() const {
- return info.port;
- }
-
- const std::string& getHostname() const {
- return info.host;
- }
-
- LinkLocalServiceInfo getInfo() const {
- return LinkLocalServiceInfo::createFromTXTRecord(info.info);
- }
-
- std::string getDescription() const;
-
- JID getJID() const;
-
- private:
- DNSSDServiceID id;
- DNSSDResolveServiceQuery::Result info;
- };
+ class SWIFTEN_API LinkLocalService {
+ public:
+ LinkLocalService(
+ const DNSSDServiceID& id,
+ const DNSSDResolveServiceQuery::Result& info) :
+ id(id),
+ info(info) {}
+
+ const DNSSDServiceID& getID() const {
+ return id;
+ }
+
+ const std::string& getName() const {
+ return id.getName();
+ }
+
+ int getPort() const {
+ return info.port;
+ }
+
+ const std::string& getHostname() const {
+ return info.host;
+ }
+
+ LinkLocalServiceInfo getInfo() const {
+ return LinkLocalServiceInfo::createFromTXTRecord(info.info);
+ }
+
+ std::string getDescription() const;
+
+ JID getJID() const;
+
+ private:
+ DNSSDServiceID id;
+ DNSSDResolveServiceQuery::Result info;
+ };
}
diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp
index ab2834d..d9dfd64 100644
--- a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp
+++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp
@@ -19,139 +19,139 @@ LinkLocalServiceBrowser::LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier>
}
LinkLocalServiceBrowser::~LinkLocalServiceBrowser() {
- if (isRunning()) {
- std::cerr << "WARNING: LinkLocalServiceBrowser still running on destruction" << std::endl;
- }
+ if (isRunning()) {
+ std::cerr << "WARNING: LinkLocalServiceBrowser still running on destruction" << std::endl;
+ }
}
void LinkLocalServiceBrowser::start() {
- assert(!isRunning());
- haveError = false;
- browseQuery = querier->createBrowseQuery();
- browseQuery->onServiceAdded.connect(
- boost::bind(&LinkLocalServiceBrowser::handleServiceAdded, this, _1));
- browseQuery->onServiceRemoved.connect(
- boost::bind(&LinkLocalServiceBrowser::handleServiceRemoved, this, _1));
- browseQuery->onError.connect(
- boost::bind(&LinkLocalServiceBrowser::handleBrowseError, this));
- browseQuery->startBrowsing();
+ assert(!isRunning());
+ haveError = false;
+ browseQuery = querier->createBrowseQuery();
+ browseQuery->onServiceAdded.connect(
+ boost::bind(&LinkLocalServiceBrowser::handleServiceAdded, this, _1));
+ browseQuery->onServiceRemoved.connect(
+ boost::bind(&LinkLocalServiceBrowser::handleServiceRemoved, this, _1));
+ browseQuery->onError.connect(
+ boost::bind(&LinkLocalServiceBrowser::handleBrowseError, this));
+ browseQuery->startBrowsing();
}
void LinkLocalServiceBrowser::stop() {
- assert(isRunning());
- if (isRegistered()) {
- unregisterService();
- }
- for (ResolveQueryMap::const_iterator i = resolveQueries.begin(); i != resolveQueries.end(); ++i) {
- i->second->stop();
- }
- resolveQueries.clear();
- services.clear();
- browseQuery->stopBrowsing();
- browseQuery.reset();
- onStopped(haveError);
+ assert(isRunning());
+ if (isRegistered()) {
+ unregisterService();
+ }
+ for (ResolveQueryMap::const_iterator i = resolveQueries.begin(); i != resolveQueries.end(); ++i) {
+ i->second->stop();
+ }
+ resolveQueries.clear();
+ services.clear();
+ browseQuery->stopBrowsing();
+ browseQuery.reset();
+ onStopped(haveError);
}
bool LinkLocalServiceBrowser::isRunning() const {
- return !!browseQuery;
+ return !!browseQuery;
}
bool LinkLocalServiceBrowser::hasError() const {
- return haveError;
+ return haveError;
}
bool LinkLocalServiceBrowser::isRegistered() const {
- return !!registerQuery;
+ return !!registerQuery;
}
void LinkLocalServiceBrowser::registerService(const std::string& name, int port, const LinkLocalServiceInfo& info) {
- assert(!registerQuery);
- registerQuery = querier->createRegisterQuery(name, port, info.toTXTRecord());
- registerQuery->onRegisterFinished.connect(
- boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1));
- registerQuery->registerService();
+ assert(!registerQuery);
+ registerQuery = querier->createRegisterQuery(name, port, info.toTXTRecord());
+ registerQuery->onRegisterFinished.connect(
+ boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1));
+ registerQuery->registerService();
}
void LinkLocalServiceBrowser::updateService(const LinkLocalServiceInfo& info) {
- assert(registerQuery);
- registerQuery->updateServiceInfo(info.toTXTRecord());
+ assert(registerQuery);
+ registerQuery->updateServiceInfo(info.toTXTRecord());
}
void LinkLocalServiceBrowser::unregisterService() {
- assert(registerQuery);
- registerQuery->unregisterService();
- registerQuery.reset();
- selfService.reset();
+ assert(registerQuery);
+ registerQuery->unregisterService();
+ registerQuery.reset();
+ selfService.reset();
}
std::vector<LinkLocalService> LinkLocalServiceBrowser::getServices() const {
- std::vector<LinkLocalService> result;
- for (ServiceMap::const_iterator i = services.begin(); i != services.end(); ++i) {
- result.push_back(LinkLocalService(i->first, i->second));
- }
- return result;
+ std::vector<LinkLocalService> result;
+ for (ServiceMap::const_iterator i = services.begin(); i != services.end(); ++i) {
+ result.push_back(LinkLocalService(i->first, i->second));
+ }
+ return result;
}
void LinkLocalServiceBrowser::handleServiceAdded(const DNSSDServiceID& service) {
- if (selfService && service == *selfService) {
- return;
- }
+ if (selfService && service == *selfService) {
+ return;
+ }
- std::pair<ResolveQueryMap::iterator, bool> r = resolveQueries.insert(std::make_pair(service, boost::shared_ptr<DNSSDResolveServiceQuery>()));
- if (r.second) {
- // There was no existing query yet. Start a new query.
- boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(service);
- resolveQuery->onServiceResolved.connect(
- boost::bind(&LinkLocalServiceBrowser::handleServiceResolved, this, service, _1));
- r.first->second = resolveQuery;
- resolveQuery->start();
- }
+ std::pair<ResolveQueryMap::iterator, bool> r = resolveQueries.insert(std::make_pair(service, boost::shared_ptr<DNSSDResolveServiceQuery>()));
+ if (r.second) {
+ // There was no existing query yet. Start a new query.
+ boost::shared_ptr<DNSSDResolveServiceQuery> resolveQuery = querier->createResolveServiceQuery(service);
+ resolveQuery->onServiceResolved.connect(
+ boost::bind(&LinkLocalServiceBrowser::handleServiceResolved, this, service, _1));
+ r.first->second = resolveQuery;
+ resolveQuery->start();
+ }
}
void LinkLocalServiceBrowser::handleServiceRemoved(const DNSSDServiceID& service) {
- ResolveQueryMap::iterator i = resolveQueries.find(service);
- if (i == resolveQueries.end()) {
- // Can happen after an unregister(), when getting the old 'self'
- // service remove notification.
- return;
- }
- i->second->stop();
- resolveQueries.erase(i);
- ServiceMap::iterator j = services.find(service);
- assert(j != services.end());
- LinkLocalService linkLocalService(j->first, j->second);
- services.erase(j);
- onServiceRemoved(linkLocalService);
+ ResolveQueryMap::iterator i = resolveQueries.find(service);
+ if (i == resolveQueries.end()) {
+ // Can happen after an unregister(), when getting the old 'self'
+ // service remove notification.
+ return;
+ }
+ i->second->stop();
+ resolveQueries.erase(i);
+ ServiceMap::iterator j = services.find(service);
+ assert(j != services.end());
+ LinkLocalService linkLocalService(j->first, j->second);
+ services.erase(j);
+ onServiceRemoved(linkLocalService);
}
void LinkLocalServiceBrowser::handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result) {
- if (result) {
- std::pair<ServiceMap::iterator, bool> r = services.insert(std::make_pair(service, *result));
- if (r.second) {
- onServiceAdded(LinkLocalService(r.first->first, r.first->second));
- }
- else {
- r.first->second = *result;
- onServiceChanged(LinkLocalService(r.first->first, r.first->second));
- }
- }
+ if (result) {
+ std::pair<ServiceMap::iterator, bool> r = services.insert(std::make_pair(service, *result));
+ if (r.second) {
+ onServiceAdded(LinkLocalService(r.first->first, r.first->second));
+ }
+ else {
+ r.first->second = *result;
+ onServiceChanged(LinkLocalService(r.first->first, r.first->second));
+ }
+ }
}
void LinkLocalServiceBrowser::handleRegisterFinished(const boost::optional<DNSSDServiceID>& result) {
- if (result) {
- selfService = result;
- onServiceRegistered(*result);
- }
- else {
- haveError = true;
- stop();
- }
+ if (result) {
+ selfService = result;
+ onServiceRegistered(*result);
+ }
+ else {
+ haveError = true;
+ stop();
+ }
}
void LinkLocalServiceBrowser::handleBrowseError() {
- haveError = true;
- stop();
+ haveError = true;
+ stop();
}
}
diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.h b/Swiften/LinkLocal/LinkLocalServiceBrowser.h
index 7bd4818..3795258 100644
--- a/Swiften/LinkLocal/LinkLocalServiceBrowser.h
+++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.h
@@ -23,54 +23,54 @@
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
namespace Swift {
- class SWIFTEN_API LinkLocalServiceBrowser {
- public:
- LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> querier);
- ~LinkLocalServiceBrowser();
+ class SWIFTEN_API LinkLocalServiceBrowser {
+ public:
+ LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> querier);
+ ~LinkLocalServiceBrowser();
- void start();
- void stop();
- bool isRunning() const;
- bool hasError() const;
+ void start();
+ void stop();
+ bool isRunning() const;
+ bool hasError() const;
- void registerService(
- const std::string& name,
- int port,
- const LinkLocalServiceInfo& info = LinkLocalServiceInfo());
- void updateService(
- const LinkLocalServiceInfo& info = LinkLocalServiceInfo());
- void unregisterService();
- bool isRegistered() const;
+ void registerService(
+ const std::string& name,
+ int port,
+ const LinkLocalServiceInfo& info = LinkLocalServiceInfo());
+ void updateService(
+ const LinkLocalServiceInfo& info = LinkLocalServiceInfo());
+ void unregisterService();
+ bool isRegistered() const;
- std::vector<LinkLocalService> getServices() const;
+ std::vector<LinkLocalService> getServices() const;
- // FIXME: Ugly that we need this
- boost::shared_ptr<DNSSDQuerier> getQuerier() const {
- return querier;
- }
+ // FIXME: Ugly that we need this
+ boost::shared_ptr<DNSSDQuerier> getQuerier() const {
+ return querier;
+ }
- boost::signal<void (const LinkLocalService&)> onServiceAdded;
- boost::signal<void (const LinkLocalService&)> onServiceChanged;
- boost::signal<void (const LinkLocalService&)> onServiceRemoved;
- boost::signal<void (const DNSSDServiceID&)> onServiceRegistered;
- boost::signal<void (bool)> onStopped;
+ boost::signal<void (const LinkLocalService&)> onServiceAdded;
+ boost::signal<void (const LinkLocalService&)> onServiceChanged;
+ boost::signal<void (const LinkLocalService&)> onServiceRemoved;
+ boost::signal<void (const DNSSDServiceID&)> onServiceRegistered;
+ boost::signal<void (bool)> onStopped;
- private:
- void handleServiceAdded(const DNSSDServiceID&);
- void handleServiceRemoved(const DNSSDServiceID&);
- void handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result);
- void handleRegisterFinished(const boost::optional<DNSSDServiceID>&);
- void handleBrowseError();
+ private:
+ void handleServiceAdded(const DNSSDServiceID&);
+ void handleServiceRemoved(const DNSSDServiceID&);
+ void handleServiceResolved(const DNSSDServiceID& service, const boost::optional<DNSSDResolveServiceQuery::Result>& result);
+ void handleRegisterFinished(const boost::optional<DNSSDServiceID>&);
+ void handleBrowseError();
- private:
- boost::shared_ptr<DNSSDQuerier> querier;
- boost::optional<DNSSDServiceID> selfService;
- boost::shared_ptr<DNSSDBrowseQuery> browseQuery;
- boost::shared_ptr<DNSSDRegisterQuery> registerQuery;
- typedef std::map<DNSSDServiceID, boost::shared_ptr<DNSSDResolveServiceQuery> > ResolveQueryMap;
- ResolveQueryMap resolveQueries;
- typedef std::map<DNSSDServiceID, DNSSDResolveServiceQuery::Result> ServiceMap;
- ServiceMap services;
- bool haveError;
- };
+ private:
+ boost::shared_ptr<DNSSDQuerier> querier;
+ boost::optional<DNSSDServiceID> selfService;
+ boost::shared_ptr<DNSSDBrowseQuery> browseQuery;
+ boost::shared_ptr<DNSSDRegisterQuery> registerQuery;
+ typedef std::map<DNSSDServiceID, boost::shared_ptr<DNSSDResolveServiceQuery> > ResolveQueryMap;
+ ResolveQueryMap resolveQueries;
+ typedef std::map<DNSSDServiceID, DNSSDResolveServiceQuery::Result> ServiceMap;
+ ServiceMap services;
+ bool haveError;
+ };
}
diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
index df341f4..7a7ed3b 100644
--- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
+++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
@@ -15,110 +15,110 @@
namespace Swift {
ByteArray LinkLocalServiceInfo::toTXTRecord() const {
- ByteArray result(getEncoded("txtvers=1"));
- if (!firstName.empty()) {
- append(result, getEncoded("1st=" + firstName));
- }
- if (!lastName.empty()) {
- append(result, getEncoded("last=" + lastName));
- }
- if (!email.empty()) {
- append(result, getEncoded("email=" + email));
- }
- if (jid.isValid()) {
- append(result, getEncoded("jid=" + jid.toString()));
- }
- if (!message.empty()) {
- append(result, getEncoded("msg=" + message));
- }
- if (!nick.empty()) {
- append(result, getEncoded("nick=" + nick));
- }
- if (port) {
- append(result, getEncoded("port.p2pj=" + std::string(boost::lexical_cast<std::string>(*port))));
- }
+ ByteArray result(getEncoded("txtvers=1"));
+ if (!firstName.empty()) {
+ append(result, getEncoded("1st=" + firstName));
+ }
+ if (!lastName.empty()) {
+ append(result, getEncoded("last=" + lastName));
+ }
+ if (!email.empty()) {
+ append(result, getEncoded("email=" + email));
+ }
+ if (jid.isValid()) {
+ append(result, getEncoded("jid=" + jid.toString()));
+ }
+ if (!message.empty()) {
+ append(result, getEncoded("msg=" + message));
+ }
+ if (!nick.empty()) {
+ append(result, getEncoded("nick=" + nick));
+ }
+ if (port) {
+ append(result, getEncoded("port.p2pj=" + std::string(boost::lexical_cast<std::string>(*port))));
+ }
- switch (status) {
- case Available: append(result, getEncoded("status=avail")); break;
- case Away: append(result, getEncoded("status=away")); break;
- case DND: append(result, getEncoded("status=dnd")); break;
- }
+ switch (status) {
+ case Available: append(result, getEncoded("status=avail")); break;
+ case Away: append(result, getEncoded("status=away")); break;
+ case DND: append(result, getEncoded("status=dnd")); break;
+ }
- return result;
+ return result;
}
ByteArray LinkLocalServiceInfo::getEncoded(const std::string& s) {
- ByteArray sizeByte;
- sizeByte.resize(1);
- sizeByte[0] = boost::numeric_cast<unsigned char>(s.size());
- return concat(sizeByte, createByteArray(s));
+ ByteArray sizeByte;
+ sizeByte.resize(1);
+ sizeByte[0] = boost::numeric_cast<unsigned char>(s.size());
+ return concat(sizeByte, createByteArray(s));
}
LinkLocalServiceInfo LinkLocalServiceInfo::createFromTXTRecord(const ByteArray& record) {
- LinkLocalServiceInfo info;
- size_t i = 0;
- size_t recordCount = record.size();
- while (i < recordCount) {
- std::pair<std::string,std::string> entry = readEntry(record, &i);
- if (entry.first.empty()) {
- break;
- }
- else if (entry.first == "1st") {
- info.setFirstName(entry.second);
- }
- else if (entry.first == "last") {
- info.setLastName(entry.second);
- }
- else if (entry.first == "email") {
- info.setEMail(entry.second);
- }
- else if (entry.first == "jid") {
- info.setJID(JID(entry.second));
- }
- else if (entry.first == "msg") {
- info.setMessage(entry.second);
- }
- else if (entry.first == "nick") {
- info.setNick(entry.second);
- }
- else if (entry.first == "port.p2pj") {
- info.setPort(boost::lexical_cast<int>(entry.second));
- }
- else if (entry.first == "status") {
- if (entry.second == "away") {
- info.setStatus(Away);
- }
- else if (entry.second == "dnd") {
- info.setStatus(DND);
- }
- }
- }
- return info;
+ LinkLocalServiceInfo info;
+ size_t i = 0;
+ size_t recordCount = record.size();
+ while (i < recordCount) {
+ std::pair<std::string,std::string> entry = readEntry(record, &i);
+ if (entry.first.empty()) {
+ break;
+ }
+ else if (entry.first == "1st") {
+ info.setFirstName(entry.second);
+ }
+ else if (entry.first == "last") {
+ info.setLastName(entry.second);
+ }
+ else if (entry.first == "email") {
+ info.setEMail(entry.second);
+ }
+ else if (entry.first == "jid") {
+ info.setJID(JID(entry.second));
+ }
+ else if (entry.first == "msg") {
+ info.setMessage(entry.second);
+ }
+ else if (entry.first == "nick") {
+ info.setNick(entry.second);
+ }
+ else if (entry.first == "port.p2pj") {
+ info.setPort(boost::lexical_cast<int>(entry.second));
+ }
+ else if (entry.first == "status") {
+ if (entry.second == "away") {
+ info.setStatus(Away);
+ }
+ else if (entry.second == "dnd") {
+ info.setStatus(DND);
+ }
+ }
+ }
+ return info;
}
std::pair<std::string,std::string> LinkLocalServiceInfo::readEntry(const ByteArray& record, size_t* index) {
- size_t& i = *index;
- std::string key;
- std::string value;
+ size_t& i = *index;
+ std::string key;
+ std::string value;
- size_t entryEnd = i + 1 + record[i];
- ++i;
- bool inKey = true;
- while (i < entryEnd && i < record.size()) {
- if (inKey) {
- if (record[i] == '=') {
- inKey = false;
- }
- else {
- key += static_cast<char>(record[i]);
- }
- }
- else {
- value += static_cast<char>(record[i]);
- }
- ++i;
- }
- return std::make_pair(key, value);
+ size_t entryEnd = i + 1 + record[i];
+ ++i;
+ bool inKey = true;
+ while (i < entryEnd && i < record.size()) {
+ if (inKey) {
+ if (record[i] == '=') {
+ inKey = false;
+ }
+ else {
+ key += static_cast<char>(record[i]);
+ }
+ }
+ else {
+ value += static_cast<char>(record[i]);
+ }
+ ++i;
+ }
+ return std::make_pair(key, value);
}
}
diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.h b/Swiften/LinkLocal/LinkLocalServiceInfo.h
index c6e4af3..9f15c6e 100644
--- a/Swiften/LinkLocal/LinkLocalServiceInfo.h
+++ b/Swiften/LinkLocal/LinkLocalServiceInfo.h
@@ -16,52 +16,52 @@
namespace Swift {
- class SWIFTEN_API LinkLocalServiceInfo {
- public:
- enum Status { Available, Away, DND };
+ class SWIFTEN_API LinkLocalServiceInfo {
+ public:
+ enum Status { Available, Away, DND };
- LinkLocalServiceInfo() : status(Available) {}
+ LinkLocalServiceInfo() : status(Available) {}
- const std::string& getFirstName() const { return firstName; }
- void setFirstName(const std::string& f) { firstName = f; }
+ const std::string& getFirstName() const { return firstName; }
+ void setFirstName(const std::string& f) { firstName = f; }
- const std::string& getLastName() const { return lastName; }
- void setLastName(const std::string& l) { lastName = l; }
+ const std::string& getLastName() const { return lastName; }
+ void setLastName(const std::string& l) { lastName = l; }
- const std::string& getEMail() const { return email; }
- void setEMail(const std::string& e) { email = e; }
+ const std::string& getEMail() const { return email; }
+ void setEMail(const std::string& e) { email = e; }
- const JID& getJID() const { return jid; }
- void setJID(const JID& j) { jid = j; }
+ const JID& getJID() const { return jid; }
+ void setJID(const JID& j) { jid = j; }
- const std::string& getMessage() const { return message; }
- void setMessage(const std::string& m) { message = m; }
+ const std::string& getMessage() const { return message; }
+ void setMessage(const std::string& m) { message = m; }
- const std::string& getNick() const { return nick; }
- void setNick(const std::string& n) { nick = n; }
+ const std::string& getNick() const { return nick; }
+ void setNick(const std::string& n) { nick = n; }
- Status getStatus() const { return status; }
- void setStatus(Status s) { status = s; }
+ Status getStatus() const { return status; }
+ void setStatus(Status s) { status = s; }
- boost::optional<int> getPort() const { return port; }
- void setPort(int p) { port = p; }
+ boost::optional<int> getPort() const { return port; }
+ void setPort(int p) { port = p; }
- ByteArray toTXTRecord() const;
+ ByteArray toTXTRecord() const;
- static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record);
+ static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record);
- private:
- static ByteArray getEncoded(const std::string&);
- static std::pair<std::string,std::string> readEntry(const ByteArray&, size_t*);
+ private:
+ static ByteArray getEncoded(const std::string&);
+ static std::pair<std::string,std::string> readEntry(const ByteArray&, size_t*);
- private:
- std::string firstName;
- std::string lastName;
- std::string email;
- JID jid;
- std::string message;
- std::string nick;
- Status status;
- boost::optional<int> port;
- };
+ private:
+ std::string firstName;
+ std::string lastName;
+ std::string email;
+ JID jid;
+ std::string message;
+ std::string nick;
+ Status status;
+ boost::optional<int> port;
+ };
}
diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
index 47ab116..89d0e89 100644
--- a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
@@ -17,36 +17,36 @@
namespace Swift {
OutgoingLinkLocalSession::OutgoingLinkLocalSession(
- const JID& localJID,
- const JID& remoteJID,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory) :
- Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory) {
- setLocalJID(localJID);
- setRemoteJID(remoteJID);
+ const JID& localJID,
+ const JID& remoteJID,
+ boost::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);
+ ProtocolHeader header;
+ header.setFrom(getLocalJID());
+ getXMPPLayer()->writeHeader(header);
}
void OutgoingLinkLocalSession::handleStreamStart(const ProtocolHeader&) {
- foreach(const boost::shared_ptr<ToplevelElement>& stanza, queuedElements_) {
- sendElement(stanza);
- }
- queuedElements_.clear();
+ foreach(const boost::shared_ptr<ToplevelElement>& stanza, queuedElements_) {
+ sendElement(stanza);
+ }
+ queuedElements_.clear();
}
void OutgoingLinkLocalSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- onElementReceived(element);
+ onElementReceived(element);
}
void OutgoingLinkLocalSession::queueElement(boost::shared_ptr<ToplevelElement> element) {
- queuedElements_.push_back(element);
+ queuedElements_.push_back(element);
}
diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.h b/Swiften/LinkLocal/OutgoingLinkLocalSession.h
index 7227aba..b467918 100644
--- a/Swiften/LinkLocal/OutgoingLinkLocalSession.h
+++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.h
@@ -17,30 +17,30 @@
#include <Swiften/Session/Session.h>
namespace Swift {
- class ConnectionFactory;
- class XMLParserFactory;
- class ToplevelElement;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
-
- class SWIFTEN_API OutgoingLinkLocalSession : public Session {
- public:
- OutgoingLinkLocalSession(
- const JID& localJID,
- const JID& remoteJID,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory);
-
- void queueElement(boost::shared_ptr<ToplevelElement> element);
-
- private:
- void handleSessionStarted();
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamStart(const ProtocolHeader&);
-
- private:
- std::vector<boost::shared_ptr<ToplevelElement> > queuedElements_;
- };
+ class ConnectionFactory;
+ class XMLParserFactory;
+ class ToplevelElement;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+
+ class SWIFTEN_API OutgoingLinkLocalSession : public Session {
+ public:
+ OutgoingLinkLocalSession(
+ const JID& localJID,
+ const JID& remoteJID,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+
+ void queueElement(boost::shared_ptr<ToplevelElement> element);
+
+ private:
+ void handleSessionStarted();
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+
+ private:
+ std::vector<boost::shared_ptr<ToplevelElement> > queuedElements_;
+ };
}
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
index 617e625..3511f90 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
@@ -20,124 +20,124 @@
using namespace Swift;
class LinkLocalConnectorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkLocalConnectorTest);
- CPPUNIT_TEST(testConnect);
- CPPUNIT_TEST(testConnect_UnableToResolve);
- CPPUNIT_TEST(testConnect_UnableToConnect);
- CPPUNIT_TEST(testCancel_DuringResolve);
- CPPUNIT_TEST(testCancel_DuringConnect);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop = new DummyEventLoop();
- querier = boost::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop);
- connection = boost::make_shared<FakeConnection>(eventLoop);
- connectFinished = false;
- }
-
- void tearDown() {
- querier->clearAllQueriesEverRun();
- delete eventLoop;
- }
-
- void testConnect() {
- boost::shared_ptr<LinkLocalConnector>
- testling(createConnector("rabbithole.local", 1234));
- querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
-
- testling->connect();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(!connectError);
- CPPUNIT_ASSERT(connection->connectedTo);
- CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1"));
- CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234);
- }
-
- void testConnect_UnableToResolve() {
- boost::shared_ptr<LinkLocalConnector>
- testling(createConnector("rabbithole.local", 1234));
- querier->setAddress("rabbithole.local", boost::optional<HostAddress>());
-
- testling->connect();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(connectError);
- CPPUNIT_ASSERT(!connection->connectedTo);
- }
-
- void testConnect_UnableToConnect() {
- boost::shared_ptr<LinkLocalConnector>
- testling(createConnector("rabbithole.local", 1234));
- querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
- connection->setError(Connection::ReadError);
-
- testling->connect();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(connectError);
- CPPUNIT_ASSERT(!connection->connectedTo);
- }
-
- void testCancel_DuringResolve() {
- boost::shared_ptr<LinkLocalConnector>
- testling(createConnector("rabbithole.local", 1234));
- testling->connect();
- eventLoop->processEvents();
- CPPUNIT_ASSERT(!connectFinished);
-
- testling->cancel();
- eventLoop->processEvents();
- querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
- }
-
- void testCancel_DuringConnect() {
- boost::shared_ptr<LinkLocalConnector>
- testling(createConnector("rabbithole.local", 1234));
- querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
- connection->setDelayConnect();
- testling->connect();
- eventLoop->processEvents();
- CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state);
-
- testling->cancel();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
- }
-
- private:
- boost::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, int port) {
- LinkLocalService service(
- DNSSDServiceID("myname", "local."),
- DNSSDResolveServiceQuery::Result(
- "myname._presence._tcp.local", hostname, port,
- LinkLocalServiceInfo().toTXTRecord()));
- boost::shared_ptr<LinkLocalConnector> result(
- new LinkLocalConnector(service, querier, connection));
- result->onConnectFinished.connect(
- boost::bind(&LinkLocalConnectorTest::handleConnected, this, _1));
- return result;
- }
-
- void handleConnected(bool e) {
- connectFinished = true;
- connectError = e;
- }
-
- private:
- DummyEventLoop* eventLoop;
- boost::shared_ptr<FakeDNSSDQuerier> querier;
- boost::shared_ptr<FakeConnection> connection;
- bool connectFinished;
- bool connectError;
+ CPPUNIT_TEST_SUITE(LinkLocalConnectorTest);
+ CPPUNIT_TEST(testConnect);
+ CPPUNIT_TEST(testConnect_UnableToResolve);
+ CPPUNIT_TEST(testConnect_UnableToConnect);
+ CPPUNIT_TEST(testCancel_DuringResolve);
+ CPPUNIT_TEST(testCancel_DuringConnect);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ querier = boost::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop);
+ connection = boost::make_shared<FakeConnection>(eventLoop);
+ connectFinished = false;
+ }
+
+ void tearDown() {
+ querier->clearAllQueriesEverRun();
+ delete eventLoop;
+ }
+
+ void testConnect() {
+ boost::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+
+ testling->connect();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(!connectError);
+ CPPUNIT_ASSERT(connection->connectedTo);
+ CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1"));
+ CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234);
+ }
+
+ void testConnect_UnableToResolve() {
+ boost::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", boost::optional<HostAddress>());
+
+ testling->connect();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(connectError);
+ CPPUNIT_ASSERT(!connection->connectedTo);
+ }
+
+ void testConnect_UnableToConnect() {
+ boost::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+ connection->setError(Connection::ReadError);
+
+ testling->connect();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(connectError);
+ CPPUNIT_ASSERT(!connection->connectedTo);
+ }
+
+ void testCancel_DuringResolve() {
+ boost::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(!connectFinished);
+
+ testling->cancel();
+ eventLoop->processEvents();
+ querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
+ }
+
+ void testCancel_DuringConnect() {
+ boost::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+ connection->setDelayConnect();
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state);
+
+ testling->cancel();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
+ }
+
+ private:
+ boost::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, int port) {
+ LinkLocalService service(
+ DNSSDServiceID("myname", "local."),
+ DNSSDResolveServiceQuery::Result(
+ "myname._presence._tcp.local", hostname, port,
+ LinkLocalServiceInfo().toTXTRecord()));
+ boost::shared_ptr<LinkLocalConnector> result(
+ new LinkLocalConnector(service, querier, connection));
+ result->onConnectFinished.connect(
+ boost::bind(&LinkLocalConnectorTest::handleConnected, this, _1));
+ return result;
+ }
+
+ void handleConnected(bool e) {
+ connectFinished = true;
+ connectError = e;
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ boost::shared_ptr<FakeDNSSDQuerier> querier;
+ boost::shared_ptr<FakeConnection> connection;
+ bool connectFinished;
+ bool connectError;
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalConnectorTest);
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
index 8533b33..6d8ba97 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
@@ -23,392 +23,392 @@
using namespace Swift;
class LinkLocalServiceBrowserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkLocalServiceBrowserTest);
- CPPUNIT_TEST(testConstructor);
- CPPUNIT_TEST(testStart);
- CPPUNIT_TEST(testServiceAdded);
- CPPUNIT_TEST(testServiceAdded_NoServiceInfo);
- CPPUNIT_TEST(testServiceAdded_RegisteredService);
- CPPUNIT_TEST(testServiceAdded_UnregisteredService);
- CPPUNIT_TEST(testServiceAdded_Twice);
- CPPUNIT_TEST(testServiceChanged);
- CPPUNIT_TEST(testServiceRemoved);
- CPPUNIT_TEST(testServiceRemoved_UnregisteredService);
- CPPUNIT_TEST(testError_BrowseErrorAfterStart);
- CPPUNIT_TEST(testError_BrowseErrorAfterResolve);
- CPPUNIT_TEST(testRegisterService);
- CPPUNIT_TEST(testRegisterService_Error);
- CPPUNIT_TEST(testRegisterService_Reregister);
- CPPUNIT_TEST(testUpdateService);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop = new DummyEventLoop();
- querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
- aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit");
- aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord());
- testServiceID = new DNSSDServiceID("foo", "bar.local");
- testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord());
- testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord());
- errorStopReceived = false;
- normalStopReceived = false;
- }
-
- void tearDown() {
- querier->clearAllQueriesEverRun();
- addedServices.clear();
- removedServices.clear();
- changedServices.clear();
-
- delete aliceServiceID;
- delete aliceServiceInfo;
- delete testServiceInfo2;
- delete testServiceInfo;
- delete testServiceID;
- delete eventLoop;
- }
-
- void testConstructor() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
-
- CPPUNIT_ASSERT(!testling->isRunning());
- CPPUNIT_ASSERT(!testling->hasError());
- }
-
- void testStart() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
-
- CPPUNIT_ASSERT(testling->isRunning());
- CPPUNIT_ASSERT(!testling->hasError());
-
- testling->stop();
- }
-
- void testServiceAdded() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- querier->setServiceInfo(*testServiceID,*testServiceInfo);
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
- std::vector<LinkLocalService> services = testling->getServices();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
- CPPUNIT_ASSERT(*testServiceID == services[0].getID());
- CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort());
- CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname());
-
- testling->stop();
- }
-
- void testServiceAdded_NoServiceInfo() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
-
- testling->stop();
- }
-
- void testServiceAdded_RegisteredService() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- testling->registerService("alice", 1234, LinkLocalServiceInfo());
- eventLoop->processEvents();
- querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo);
- querier->addService(*aliceServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
-
- testling->stop();
- }
-
- void testServiceAdded_UnregisteredService() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
- testling->registerService("alice", 1234, LinkLocalServiceInfo());
- eventLoop->processEvents();
- testling->unregisterService();
- eventLoop->processEvents();
-
- querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo);
- querier->addService(*aliceServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT(addedServices[0].getID() == *aliceServiceID);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
- std::vector<LinkLocalService> services = testling->getServices();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
- CPPUNIT_ASSERT(*aliceServiceID == services[0].getID());
- CPPUNIT_ASSERT(aliceServiceInfo->port == services[0].getPort());
- CPPUNIT_ASSERT(aliceServiceInfo->host == services[0].getHostname());
-
- testling->stop();
- }
-
- void testServiceRemoved_UnregisteredService() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
- testling->registerService("alice", 1234, LinkLocalServiceInfo());
- eventLoop->processEvents();
- testling->unregisterService();
- eventLoop->processEvents();
-
- querier->removeService(*aliceServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
-
- testling->stop();
- }
-
- void testServiceAdded_Twice() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- querier->setServiceInfo(*testServiceID,*testServiceInfo);
- querier->addService(*testServiceID);
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(querier->getAllQueriesEverRun<FakeDNSSDResolveServiceQuery>().size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
- std::vector<LinkLocalService> services = testling->getServices();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
- CPPUNIT_ASSERT(*testServiceID == services[0].getID());
- CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort());
- CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname());
-
- testling->stop();
- }
-
-
- void testServiceChanged() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- querier->setServiceInfo(*testServiceID,*testServiceInfo);
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- querier->setServiceInfo(*testServiceID,*testServiceInfo2);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
- CPPUNIT_ASSERT(changedServices[0].getID() == *testServiceID);
- std::vector<LinkLocalService> services = testling->getServices();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
- CPPUNIT_ASSERT(*testServiceID == services[0].getID());
- CPPUNIT_ASSERT(testServiceInfo2->port == services[0].getPort());
- CPPUNIT_ASSERT(testServiceInfo2->host == services[0].getHostname());
-
- testling->stop();
- }
-
- void testServiceRemoved() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- querier->setServiceInfo(*testServiceID,*testServiceInfo);
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- querier->removeService(*testServiceID);
- eventLoop->processEvents();
- querier->setServiceInfo(*testServiceID,*testServiceInfo2);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(removedServices.size()));
- CPPUNIT_ASSERT(removedServices[0].getID() == *testServiceID);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
-
- testling->stop();
- }
-
- void testError_BrowseErrorAfterStart() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
-
- querier->setBrowseError();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(!testling->isRunning());
- CPPUNIT_ASSERT(testling->hasError());
- CPPUNIT_ASSERT(errorStopReceived);
- }
-
- void testError_BrowseErrorAfterResolve() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- querier->setServiceInfo(*testServiceID,*testServiceInfo);
- querier->addService(*testServiceID);
- eventLoop->processEvents();
-
- querier->setBrowseError();
- eventLoop->processEvents();
- querier->setServiceInfo(*testServiceID,*testServiceInfo2);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(!testling->isRunning());
- CPPUNIT_ASSERT(testling->hasError());
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
- CPPUNIT_ASSERT(errorStopReceived);
- }
-
- void testRegisterService() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- LinkLocalServiceInfo info;
- info.setFirstName("Foo");
- testling->registerService("foo@bar", 1234, info);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(registeredServices.size()));
- CPPUNIT_ASSERT(registeredServices[0] == DNSSDServiceID("foo@bar", "wonderland.lit"));
- testling->stop();
- }
-
- void testRegisterService_Error() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- LinkLocalServiceInfo info;
- testling->registerService("foo@bar", 1234, info);
- eventLoop->processEvents();
-
- querier->setRegisterError();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(!testling->isRunning());
- CPPUNIT_ASSERT(testling->hasError());
- CPPUNIT_ASSERT(errorStopReceived);
- CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
- }
-
- void testRegisterService_Reregister() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
- LinkLocalServiceInfo info;
- info.setFirstName("Foo");
- testling->registerService("foo@bar", 1234, info);
- eventLoop->processEvents();
- testling->unregisterService();
- eventLoop->processEvents();
-
- info.setFirstName("Bar");
- testling->registerService("bar@baz", 3456, info);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, info.toTXTRecord()));
-
- testling->stop();
- }
-
- void testUpdateService() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
- testling->start();
- eventLoop->processEvents();
-
- LinkLocalServiceInfo info;
- info.setFirstName("Foo");
- testling->registerService("foo@bar", 1234, info);
- eventLoop->processEvents();
- info.setFirstName("Bar");
- testling->updateService(info);
-
- CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
-
- testling->stop();
- }
-
- private:
- boost::shared_ptr<LinkLocalServiceBrowser> createTestling() {
- boost::shared_ptr<LinkLocalServiceBrowser> testling(
- new LinkLocalServiceBrowser(querier));
- testling->onServiceAdded.connect(boost::bind(
- &LinkLocalServiceBrowserTest::handleServiceAdded, this, _1));
- testling->onServiceChanged.connect(boost::bind(
- &LinkLocalServiceBrowserTest::handleServiceChanged, this, _1));
- testling->onServiceRemoved.connect(boost::bind(
- &LinkLocalServiceBrowserTest::handleServiceRemoved, this, _1));
- testling->onServiceRegistered.connect(boost::bind(
- &LinkLocalServiceBrowserTest::handleServiceRegistered, this, _1));
- testling->onStopped.connect(boost::bind(
- &LinkLocalServiceBrowserTest::handleStopped, this, _1));
- return testling;
- }
-
- void handleServiceAdded(const LinkLocalService& service) {
- addedServices.push_back(service);
- }
-
- void handleServiceRemoved(const LinkLocalService& service) {
- removedServices.push_back(service);
- }
-
- void handleServiceChanged(const LinkLocalService& service) {
- changedServices.push_back(service);
- }
-
- void handleServiceRegistered(const DNSSDServiceID& service) {
- registeredServices.push_back(service);
- }
-
- void handleStopped(bool error) {
- CPPUNIT_ASSERT(!errorStopReceived);
- CPPUNIT_ASSERT(!normalStopReceived);
- if (error) {
- errorStopReceived = true;
- }
- else {
- normalStopReceived = true;
- }
- }
-
- private:
- DummyEventLoop* eventLoop;
- boost::shared_ptr<FakeDNSSDQuerier> querier;
- std::vector<LinkLocalService> addedServices;
- std::vector<LinkLocalService> changedServices;
- std::vector<LinkLocalService> removedServices;
- std::vector<DNSSDServiceID> registeredServices;
- DNSSDServiceID* aliceServiceID;
- DNSSDResolveServiceQuery::Result* aliceServiceInfo;
- DNSSDServiceID* testServiceID;
- DNSSDResolveServiceQuery::Result* testServiceInfo;
- DNSSDResolveServiceQuery::Result* testServiceInfo2;
- bool errorStopReceived;
- bool normalStopReceived;
+ CPPUNIT_TEST_SUITE(LinkLocalServiceBrowserTest);
+ CPPUNIT_TEST(testConstructor);
+ CPPUNIT_TEST(testStart);
+ CPPUNIT_TEST(testServiceAdded);
+ CPPUNIT_TEST(testServiceAdded_NoServiceInfo);
+ CPPUNIT_TEST(testServiceAdded_RegisteredService);
+ CPPUNIT_TEST(testServiceAdded_UnregisteredService);
+ CPPUNIT_TEST(testServiceAdded_Twice);
+ CPPUNIT_TEST(testServiceChanged);
+ CPPUNIT_TEST(testServiceRemoved);
+ CPPUNIT_TEST(testServiceRemoved_UnregisteredService);
+ CPPUNIT_TEST(testError_BrowseErrorAfterStart);
+ CPPUNIT_TEST(testError_BrowseErrorAfterResolve);
+ CPPUNIT_TEST(testRegisterService);
+ CPPUNIT_TEST(testRegisterService_Error);
+ CPPUNIT_TEST(testRegisterService_Reregister);
+ CPPUNIT_TEST(testUpdateService);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
+ aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit");
+ aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord());
+ testServiceID = new DNSSDServiceID("foo", "bar.local");
+ testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord());
+ testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord());
+ errorStopReceived = false;
+ normalStopReceived = false;
+ }
+
+ void tearDown() {
+ querier->clearAllQueriesEverRun();
+ addedServices.clear();
+ removedServices.clear();
+ changedServices.clear();
+
+ delete aliceServiceID;
+ delete aliceServiceInfo;
+ delete testServiceInfo2;
+ delete testServiceInfo;
+ delete testServiceID;
+ delete eventLoop;
+ }
+
+ void testConstructor() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+
+ CPPUNIT_ASSERT(!testling->isRunning());
+ CPPUNIT_ASSERT(!testling->hasError());
+ }
+
+ void testStart() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+
+ CPPUNIT_ASSERT(testling->isRunning());
+ CPPUNIT_ASSERT(!testling->hasError());
+
+ testling->stop();
+ }
+
+ void testServiceAdded() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ querier->setServiceInfo(*testServiceID,*testServiceInfo);
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
+ std::vector<LinkLocalService> services = testling->getServices();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
+ CPPUNIT_ASSERT(*testServiceID == services[0].getID());
+ CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort());
+ CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname());
+
+ testling->stop();
+ }
+
+ void testServiceAdded_NoServiceInfo() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
+
+ testling->stop();
+ }
+
+ void testServiceAdded_RegisteredService() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ testling->registerService("alice", 1234, LinkLocalServiceInfo());
+ eventLoop->processEvents();
+ querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo);
+ querier->addService(*aliceServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
+
+ testling->stop();
+ }
+
+ void testServiceAdded_UnregisteredService() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+ testling->registerService("alice", 1234, LinkLocalServiceInfo());
+ eventLoop->processEvents();
+ testling->unregisterService();
+ eventLoop->processEvents();
+
+ querier->setServiceInfo(*aliceServiceID, *aliceServiceInfo);
+ querier->addService(*aliceServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT(addedServices[0].getID() == *aliceServiceID);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
+ std::vector<LinkLocalService> services = testling->getServices();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
+ CPPUNIT_ASSERT(*aliceServiceID == services[0].getID());
+ CPPUNIT_ASSERT(aliceServiceInfo->port == services[0].getPort());
+ CPPUNIT_ASSERT(aliceServiceInfo->host == services[0].getHostname());
+
+ testling->stop();
+ }
+
+ void testServiceRemoved_UnregisteredService() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+ testling->registerService("alice", 1234, LinkLocalServiceInfo());
+ eventLoop->processEvents();
+ testling->unregisterService();
+ eventLoop->processEvents();
+
+ querier->removeService(*aliceServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
+
+ testling->stop();
+ }
+
+ void testServiceAdded_Twice() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ querier->setServiceInfo(*testServiceID,*testServiceInfo);
+ querier->addService(*testServiceID);
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(querier->getAllQueriesEverRun<FakeDNSSDResolveServiceQuery>().size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT(addedServices[0].getID() == *testServiceID);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
+ std::vector<LinkLocalService> services = testling->getServices();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
+ CPPUNIT_ASSERT(*testServiceID == services[0].getID());
+ CPPUNIT_ASSERT(testServiceInfo->port == services[0].getPort());
+ CPPUNIT_ASSERT(testServiceInfo->host == services[0].getHostname());
+
+ testling->stop();
+ }
+
+
+ void testServiceChanged() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ querier->setServiceInfo(*testServiceID,*testServiceInfo);
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ querier->setServiceInfo(*testServiceID,*testServiceInfo2);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(removedServices.size()));
+ CPPUNIT_ASSERT(changedServices[0].getID() == *testServiceID);
+ std::vector<LinkLocalService> services = testling->getServices();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(services.size()));
+ CPPUNIT_ASSERT(*testServiceID == services[0].getID());
+ CPPUNIT_ASSERT(testServiceInfo2->port == services[0].getPort());
+ CPPUNIT_ASSERT(testServiceInfo2->host == services[0].getHostname());
+
+ testling->stop();
+ }
+
+ void testServiceRemoved() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ querier->setServiceInfo(*testServiceID,*testServiceInfo);
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ querier->removeService(*testServiceID);
+ eventLoop->processEvents();
+ querier->setServiceInfo(*testServiceID,*testServiceInfo2);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(removedServices.size()));
+ CPPUNIT_ASSERT(removedServices[0].getID() == *testServiceID);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
+
+ testling->stop();
+ }
+
+ void testError_BrowseErrorAfterStart() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+
+ querier->setBrowseError();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(!testling->isRunning());
+ CPPUNIT_ASSERT(testling->hasError());
+ CPPUNIT_ASSERT(errorStopReceived);
+ }
+
+ void testError_BrowseErrorAfterResolve() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ querier->setServiceInfo(*testServiceID,*testServiceInfo);
+ querier->addService(*testServiceID);
+ eventLoop->processEvents();
+
+ querier->setBrowseError();
+ eventLoop->processEvents();
+ querier->setServiceInfo(*testServiceID,*testServiceInfo2);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(!testling->isRunning());
+ CPPUNIT_ASSERT(testling->hasError());
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling->getServices().size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changedServices.size()));
+ CPPUNIT_ASSERT(errorStopReceived);
+ }
+
+ void testRegisterService() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ LinkLocalServiceInfo info;
+ info.setFirstName("Foo");
+ testling->registerService("foo@bar", 1234, info);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(registeredServices.size()));
+ CPPUNIT_ASSERT(registeredServices[0] == DNSSDServiceID("foo@bar", "wonderland.lit"));
+ testling->stop();
+ }
+
+ void testRegisterService_Error() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ LinkLocalServiceInfo info;
+ testling->registerService("foo@bar", 1234, info);
+ eventLoop->processEvents();
+
+ querier->setRegisterError();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(!testling->isRunning());
+ CPPUNIT_ASSERT(testling->hasError());
+ CPPUNIT_ASSERT(errorStopReceived);
+ CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
+ }
+
+ void testRegisterService_Reregister() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+ LinkLocalServiceInfo info;
+ info.setFirstName("Foo");
+ testling->registerService("foo@bar", 1234, info);
+ eventLoop->processEvents();
+ testling->unregisterService();
+ eventLoop->processEvents();
+
+ info.setFirstName("Bar");
+ testling->registerService("bar@baz", 3456, info);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, info.toTXTRecord()));
+
+ testling->stop();
+ }
+
+ void testUpdateService() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+ eventLoop->processEvents();
+
+ LinkLocalServiceInfo info;
+ info.setFirstName("Foo");
+ testling->registerService("foo@bar", 1234, info);
+ eventLoop->processEvents();
+ info.setFirstName("Bar");
+ testling->updateService(info);
+
+ CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord()));
+
+ testling->stop();
+ }
+
+ private:
+ boost::shared_ptr<LinkLocalServiceBrowser> createTestling() {
+ boost::shared_ptr<LinkLocalServiceBrowser> testling(
+ new LinkLocalServiceBrowser(querier));
+ testling->onServiceAdded.connect(boost::bind(
+ &LinkLocalServiceBrowserTest::handleServiceAdded, this, _1));
+ testling->onServiceChanged.connect(boost::bind(
+ &LinkLocalServiceBrowserTest::handleServiceChanged, this, _1));
+ testling->onServiceRemoved.connect(boost::bind(
+ &LinkLocalServiceBrowserTest::handleServiceRemoved, this, _1));
+ testling->onServiceRegistered.connect(boost::bind(
+ &LinkLocalServiceBrowserTest::handleServiceRegistered, this, _1));
+ testling->onStopped.connect(boost::bind(
+ &LinkLocalServiceBrowserTest::handleStopped, this, _1));
+ return testling;
+ }
+
+ void handleServiceAdded(const LinkLocalService& service) {
+ addedServices.push_back(service);
+ }
+
+ void handleServiceRemoved(const LinkLocalService& service) {
+ removedServices.push_back(service);
+ }
+
+ void handleServiceChanged(const LinkLocalService& service) {
+ changedServices.push_back(service);
+ }
+
+ void handleServiceRegistered(const DNSSDServiceID& service) {
+ registeredServices.push_back(service);
+ }
+
+ void handleStopped(bool error) {
+ CPPUNIT_ASSERT(!errorStopReceived);
+ CPPUNIT_ASSERT(!normalStopReceived);
+ if (error) {
+ errorStopReceived = true;
+ }
+ else {
+ normalStopReceived = true;
+ }
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ boost::shared_ptr<FakeDNSSDQuerier> querier;
+ std::vector<LinkLocalService> addedServices;
+ std::vector<LinkLocalService> changedServices;
+ std::vector<LinkLocalService> removedServices;
+ std::vector<DNSSDServiceID> registeredServices;
+ DNSSDServiceID* aliceServiceID;
+ DNSSDResolveServiceQuery::Result* aliceServiceInfo;
+ DNSSDServiceID* testServiceID;
+ DNSSDResolveServiceQuery::Result* testServiceInfo;
+ DNSSDResolveServiceQuery::Result* testServiceInfo2;
+ bool errorStopReceived;
+ bool normalStopReceived;
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceBrowserTest);
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp
index 55fdfb3..0a94a98 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp
@@ -15,58 +15,58 @@
using namespace Swift;
class LinkLocalServiceInfoTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkLocalServiceInfoTest);
- CPPUNIT_TEST(testGetTXTRecord);
- CPPUNIT_TEST(testCreateFromTXTRecord);
- CPPUNIT_TEST(testCreateFromTXTRecord_InvalidSize);
- CPPUNIT_TEST(testGetTXTRecordCreateFromTXTRecord_RoundTrip);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(LinkLocalServiceInfoTest);
+ CPPUNIT_TEST(testGetTXTRecord);
+ CPPUNIT_TEST(testCreateFromTXTRecord);
+ CPPUNIT_TEST(testCreateFromTXTRecord_InvalidSize);
+ CPPUNIT_TEST(testGetTXTRecordCreateFromTXTRecord_RoundTrip);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetTXTRecord() {
- LinkLocalServiceInfo info;
- info.setFirstName("Remko");
- info.setLastName("Tron\xc3\xe7on");
- info.setStatus(LinkLocalServiceInfo::Away);
+ public:
+ void testGetTXTRecord() {
+ LinkLocalServiceInfo info;
+ info.setFirstName("Remko");
+ info.setLastName("Tron\xc3\xe7on");
+ info.setStatus(LinkLocalServiceInfo::Away);
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), info.toTXTRecord());
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), info.toTXTRecord());
+ }
- void testCreateFromTXTRecord() {
- LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")));
+ void testCreateFromTXTRecord() {
+ LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")));
- CPPUNIT_ASSERT_EQUAL(std::string("Remko"), info.getFirstName());
- CPPUNIT_ASSERT_EQUAL(std::string("Tron\xc3\xe7on"), info.getLastName());
- CPPUNIT_ASSERT_EQUAL(LinkLocalServiceInfo::Away, info.getStatus());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("Remko"), info.getFirstName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Tron\xc3\xe7on"), info.getLastName());
+ CPPUNIT_ASSERT_EQUAL(LinkLocalServiceInfo::Away, info.getStatus());
+ }
- void testCreateFromTXTRecord_InvalidSize() {
- LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x10last=a"));
+ void testCreateFromTXTRecord_InvalidSize() {
+ LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x10last=a"));
- CPPUNIT_ASSERT_EQUAL(std::string("a"), info.getLastName());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("a"), info.getLastName());
+ }
- void testGetTXTRecordCreateFromTXTRecord_RoundTrip() {
- LinkLocalServiceInfo info;
- info.setFirstName("Remko");
- info.setLastName("Tron\xc3\xe7on");
- info.setEMail("remko-email@swift.im");
- info.setJID(JID("remko-jid@swift.im"));
- info.setMessage("I'm busy");
- info.setNick("el-tramo");
- info.setStatus(LinkLocalServiceInfo::DND);
- info.setPort(1234);
+ void testGetTXTRecordCreateFromTXTRecord_RoundTrip() {
+ LinkLocalServiceInfo info;
+ info.setFirstName("Remko");
+ info.setLastName("Tron\xc3\xe7on");
+ info.setEMail("remko-email@swift.im");
+ info.setJID(JID("remko-jid@swift.im"));
+ info.setMessage("I'm busy");
+ info.setNick("el-tramo");
+ info.setStatus(LinkLocalServiceInfo::DND);
+ info.setPort(1234);
- LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(info.toTXTRecord());
- CPPUNIT_ASSERT_EQUAL(info.getFirstName(), info2.getFirstName());
- CPPUNIT_ASSERT_EQUAL(info.getLastName(), info2.getLastName());
- CPPUNIT_ASSERT_EQUAL(info.getEMail(), info2.getEMail());
- CPPUNIT_ASSERT_EQUAL(info.getJID(), info2.getJID());
- CPPUNIT_ASSERT_EQUAL(info.getMessage(), info2.getMessage());
- CPPUNIT_ASSERT_EQUAL(info.getNick(), info2.getNick());
- CPPUNIT_ASSERT(info.getStatus() == info2.getStatus());
- CPPUNIT_ASSERT(info.getPort() == info2.getPort());
- }
+ LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(info.toTXTRecord());
+ CPPUNIT_ASSERT_EQUAL(info.getFirstName(), info2.getFirstName());
+ CPPUNIT_ASSERT_EQUAL(info.getLastName(), info2.getLastName());
+ CPPUNIT_ASSERT_EQUAL(info.getEMail(), info2.getEMail());
+ CPPUNIT_ASSERT_EQUAL(info.getJID(), info2.getJID());
+ CPPUNIT_ASSERT_EQUAL(info.getMessage(), info2.getMessage());
+ CPPUNIT_ASSERT_EQUAL(info.getNick(), info2.getNick());
+ CPPUNIT_ASSERT(info.getStatus() == info2.getStatus());
+ CPPUNIT_ASSERT(info.getPort() == info2.getPort());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceInfoTest);
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp
index 0eb2464..206d824 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp
@@ -12,57 +12,57 @@
using namespace Swift;
class LinkLocalServiceTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(LinkLocalServiceTest);
- CPPUNIT_TEST(testGetDescription_WithNick);
- CPPUNIT_TEST(testGetDescription_WithFirstName);
- CPPUNIT_TEST(testGetDescription_WithLastName);
- CPPUNIT_TEST(testGetDescription_WithFirstAndLastName);
- CPPUNIT_TEST(testGetDescription_NoInfo);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testGetDescription_WithNick() {
- LinkLocalService testling = createService("alice@wonderland", "Alice", "Alice In", "Wonderland");
-
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), testling.getDescription());
- }
-
- void testGetDescription_WithFirstName() {
- LinkLocalService testling = createService("alice@wonderland", "", "Alice In");
-
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), testling.getDescription());
- }
-
- void testGetDescription_WithLastName() {
- LinkLocalService testling = createService("alice@wonderland", "", "", "Wonderland");
-
- CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), testling.getDescription());
- }
-
- void testGetDescription_WithFirstAndLastName() {
- LinkLocalService testling = createService("alice@wonderland", "", "Alice In", "Wonderland");
-
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), testling.getDescription());
- }
-
- void testGetDescription_NoInfo() {
- LinkLocalService testling = createService("alice@wonderland");
-
- CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland"), testling.getDescription());
- }
-
- private:
- LinkLocalService createService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) {
- DNSSDServiceID service(name, "local.");
- LinkLocalServiceInfo info;
- info.setFirstName(firstName);
- info.setLastName(lastName);
- info.setNick(nickName);
- return LinkLocalService(service,
- DNSSDResolveServiceQuery::Result(
- name + "._presence._tcp.local", "rabbithole.local", 1234,
- info.toTXTRecord()));
- }
+ CPPUNIT_TEST_SUITE(LinkLocalServiceTest);
+ CPPUNIT_TEST(testGetDescription_WithNick);
+ CPPUNIT_TEST(testGetDescription_WithFirstName);
+ CPPUNIT_TEST(testGetDescription_WithLastName);
+ CPPUNIT_TEST(testGetDescription_WithFirstAndLastName);
+ CPPUNIT_TEST(testGetDescription_NoInfo);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testGetDescription_WithNick() {
+ LinkLocalService testling = createService("alice@wonderland", "Alice", "Alice In", "Wonderland");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), testling.getDescription());
+ }
+
+ void testGetDescription_WithFirstName() {
+ LinkLocalService testling = createService("alice@wonderland", "", "Alice In");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), testling.getDescription());
+ }
+
+ void testGetDescription_WithLastName() {
+ LinkLocalService testling = createService("alice@wonderland", "", "", "Wonderland");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), testling.getDescription());
+ }
+
+ void testGetDescription_WithFirstAndLastName() {
+ LinkLocalService testling = createService("alice@wonderland", "", "Alice In", "Wonderland");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), testling.getDescription());
+ }
+
+ void testGetDescription_NoInfo() {
+ LinkLocalService testling = createService("alice@wonderland");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland"), testling.getDescription());
+ }
+
+ private:
+ LinkLocalService createService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) {
+ DNSSDServiceID service(name, "local.");
+ LinkLocalServiceInfo info;
+ info.setFirstName(firstName);
+ info.setLastName(lastName);
+ info.setNick(nickName);
+ return LinkLocalService(service,
+ DNSSDResolveServiceQuery::Result(
+ name + "._presence._tcp.local", "rabbithole.local", 1234,
+ info.toTXTRecord()));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceTest);
diff --git a/Swiften/MUC/MUC.h b/Swiften/MUC/MUC.h
index fbd7be6..e8f953e 100644
--- a/Swiften/MUC/MUC.h
+++ b/Swiften/MUC/MUC.h
@@ -24,77 +24,77 @@
#include <Swiften/MUC/MUCRegistry.h>
namespace Swift {
- class StanzaChannel;
- class IQRouter;
- class DirectedPresenceSender;
+ class StanzaChannel;
+ class IQRouter;
+ class DirectedPresenceSender;
- class SWIFTEN_API MUC {
- public:
- typedef boost::shared_ptr<MUC> ref;
+ class SWIFTEN_API MUC {
+ public:
+ typedef boost::shared_ptr<MUC> ref;
- enum JoinResult { JoinSucceeded, JoinFailed };
- enum LeavingType { LeavePart, LeaveKick, LeaveBan, LeaveDestroy, LeaveNotMember, Disconnect };
+ enum JoinResult { JoinSucceeded, JoinFailed };
+ enum LeavingType { LeavePart, LeaveKick, LeaveBan, LeaveDestroy, LeaveNotMember, Disconnect };
- public:
- virtual ~MUC();
+ public:
+ virtual ~MUC();
- /**
- * Returns the (bare) JID of the MUC.
- */
- virtual JID getJID() const = 0;
+ /**
+ * Returns the (bare) JID of the MUC.
+ */
+ virtual JID getJID() const = 0;
- /**
- * Returns if the room is unlocked and other people can join the room.
- * @return True if joinable by others; false otherwise.
- */
- virtual bool isUnlocked() const = 0;
+ /**
+ * Returns if the room is unlocked and other people can join the room.
+ * @return True if joinable by others; false otherwise.
+ */
+ virtual bool isUnlocked() const = 0;
- virtual void joinAs(const std::string &nick) = 0;
- virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) = 0;
- /*virtual void queryRoomInfo(); */
- /*virtual void queryRoomItems(); */
- /*virtual std::string getCurrentNick() = 0; */
- virtual std::map<std::string, MUCOccupant> getOccupants() const = 0;
- virtual void changeNickname(const std::string& newNickname) = 0;
- virtual void part() = 0;
- /*virtual void handleIncomingMessage(Message::ref message) = 0; */
- /** Expose public so it can be called when e.g. user goes offline */
- virtual void handleUserLeft(LeavingType) = 0;
- /** Get occupant information*/
- virtual const MUCOccupant& getOccupant(const std::string& nick) = 0;
- virtual bool hasOccupant(const std::string& nick) = 0;
- virtual void kickOccupant(const JID& jid) = 0;
- virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role) = 0;
- virtual void requestAffiliationList(MUCOccupant::Affiliation) = 0;
- virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) = 0;
- virtual void changeSubject(const std::string& subject) = 0;
- virtual void requestConfigurationForm() = 0;
- virtual void configureRoom(Form::ref) = 0;
- virtual void cancelConfigureRoom() = 0;
- virtual void destroyRoom() = 0;
- /** Send an invite for the person to join the MUC */
- virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false) = 0;
- virtual void setCreateAsReservedIfNew() = 0;
- virtual void setPassword(const boost::optional<std::string>& password) = 0;
+ virtual void joinAs(const std::string &nick) = 0;
+ virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) = 0;
+ /*virtual void queryRoomInfo(); */
+ /*virtual void queryRoomItems(); */
+ /*virtual std::string getCurrentNick() = 0; */
+ virtual std::map<std::string, MUCOccupant> getOccupants() const = 0;
+ virtual void changeNickname(const std::string& newNickname) = 0;
+ virtual void part() = 0;
+ /*virtual void handleIncomingMessage(Message::ref message) = 0; */
+ /** Expose public so it can be called when e.g. user goes offline */
+ virtual void handleUserLeft(LeavingType) = 0;
+ /** Get occupant information*/
+ virtual const MUCOccupant& getOccupant(const std::string& nick) = 0;
+ virtual bool hasOccupant(const std::string& nick) = 0;
+ virtual void kickOccupant(const JID& jid) = 0;
+ virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role) = 0;
+ virtual void requestAffiliationList(MUCOccupant::Affiliation) = 0;
+ virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) = 0;
+ virtual void changeSubject(const std::string& subject) = 0;
+ virtual void requestConfigurationForm() = 0;
+ virtual void configureRoom(Form::ref) = 0;
+ virtual void cancelConfigureRoom() = 0;
+ virtual void destroyRoom() = 0;
+ /** Send an invite for the person to join the MUC */
+ virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false) = 0;
+ virtual void setCreateAsReservedIfNew() = 0;
+ virtual void setPassword(const boost::optional<std::string>& password) = 0;
- public:
- boost::signal<void (const std::string& /*nick*/)> onJoinComplete;
- boost::signal<void (ErrorPayload::ref)> onJoinFailed;
- boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Role)> onRoleChangeFailed;
- boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Affiliation)> onAffiliationChangeFailed;
- boost::signal<void (ErrorPayload::ref)> onConfigurationFailed;
- boost::signal<void (ErrorPayload::ref)> onAffiliationListFailed;
- boost::signal<void (Presence::ref)> onOccupantPresenceChange;
- boost::signal<void (const std::string&, const MUCOccupant& /*now*/, const MUCOccupant::Role& /*old*/)> onOccupantRoleChanged;
- boost::signal<void (const std::string&, const MUCOccupant::Affiliation& /*new*/, const MUCOccupant::Affiliation& /*old*/)> onOccupantAffiliationChanged;
- boost::signal<void (const MUCOccupant&)> onOccupantJoined;
- boost::signal<void (const std::string& /*oldNickname*/, const std::string& /*newNickname*/ )> onOccupantNicknameChanged;
- boost::signal<void (const MUCOccupant&, LeavingType, const std::string& /*reason*/)> onOccupantLeft;
- boost::signal<void (Form::ref)> onConfigurationFormReceived;
- boost::signal<void (MUCOccupant::Affiliation, const std::vector<JID>&)> onAffiliationListReceived;
- boost::signal<void ()> onUnlocked;
- /* boost::signal<void (const MUCInfo&)> onInfoResult; */
- /* boost::signal<void (const blah&)> onItemsResult; */
+ public:
+ boost::signal<void (const std::string& /*nick*/)> onJoinComplete;
+ boost::signal<void (ErrorPayload::ref)> onJoinFailed;
+ boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Role)> onRoleChangeFailed;
+ boost::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Affiliation)> onAffiliationChangeFailed;
+ boost::signal<void (ErrorPayload::ref)> onConfigurationFailed;
+ boost::signal<void (ErrorPayload::ref)> onAffiliationListFailed;
+ boost::signal<void (Presence::ref)> onOccupantPresenceChange;
+ boost::signal<void (const std::string&, const MUCOccupant& /*now*/, const MUCOccupant::Role& /*old*/)> onOccupantRoleChanged;
+ boost::signal<void (const std::string&, const MUCOccupant::Affiliation& /*new*/, const MUCOccupant::Affiliation& /*old*/)> onOccupantAffiliationChanged;
+ boost::signal<void (const MUCOccupant&)> onOccupantJoined;
+ boost::signal<void (const std::string& /*oldNickname*/, const std::string& /*newNickname*/ )> onOccupantNicknameChanged;
+ boost::signal<void (const MUCOccupant&, LeavingType, const std::string& /*reason*/)> onOccupantLeft;
+ boost::signal<void (Form::ref)> onConfigurationFormReceived;
+ boost::signal<void (MUCOccupant::Affiliation, const std::vector<JID>&)> onAffiliationListReceived;
+ boost::signal<void ()> onUnlocked;
+ /* boost::signal<void (const MUCInfo&)> onInfoResult; */
+ /* boost::signal<void (const blah&)> onItemsResult; */
- };
+ };
}
diff --git a/Swiften/MUC/MUCBookmark.h b/Swiften/MUC/MUCBookmark.h
index 1f54a8f..92050f1 100644
--- a/Swiften/MUC/MUCBookmark.h
+++ b/Swiften/MUC/MUCBookmark.h
@@ -15,76 +15,76 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API MUCBookmark {
- public:
- MUCBookmark(const Storage::Room& room) {
- name_ = room.name;
- room_ = room.jid;
- nick_ = room.nick;
- password_ = room.password;
- autojoin_ = room.autoJoin;
- }
-
- MUCBookmark(const JID& room, const std::string& bookmarkName) : room_(room), name_(bookmarkName), autojoin_(false) {
- }
-
- void setAutojoin(bool enabled) {
- autojoin_ = enabled;
- }
-
- bool getAutojoin() const {
- return autojoin_;
- }
-
- void setNick(const boost::optional<std::string>& nick) {
- nick_ = nick;
- }
-
- void setPassword(const boost::optional<std::string>& password) {
- password_ = password;
- }
-
- const boost::optional<std::string>& getNick() const {
- return nick_;
- }
-
- const boost::optional<std::string>& getPassword() const {
- return password_;
- }
-
- const std::string& getName() const {
- return name_;
- }
-
- const JID& getRoom() const {
- return room_;
- }
-
- bool operator==(const MUCBookmark& rhs) const {
- /* FIXME: not checking passwords for equality - which might make sense, perhaps */
- return rhs.room_ == room_ && rhs.name_ == name_ && rhs.nick_ == nick_ /*&& rhs.password_ == password_*/ && rhs.autojoin_ == autojoin_;
- }
-
- Storage::Room toStorage() const {
- Storage::Room room;
- room.name = name_;
- room.jid = room_;
- if (nick_) {
- room.nick = *nick_;
- }
- if (password_) {
- room.password = *password_;
- }
- room.autoJoin = autojoin_;
- return room;
- }
-
- private:
- JID room_;
- std::string name_;
- boost::optional<std::string> nick_;
- boost::optional<std::string> password_;
- bool autojoin_;
- };
+ class SWIFTEN_API MUCBookmark {
+ public:
+ MUCBookmark(const Storage::Room& room) {
+ name_ = room.name;
+ room_ = room.jid;
+ nick_ = room.nick;
+ password_ = room.password;
+ autojoin_ = room.autoJoin;
+ }
+
+ MUCBookmark(const JID& room, const std::string& bookmarkName) : room_(room), name_(bookmarkName), autojoin_(false) {
+ }
+
+ void setAutojoin(bool enabled) {
+ autojoin_ = enabled;
+ }
+
+ bool getAutojoin() const {
+ return autojoin_;
+ }
+
+ void setNick(const boost::optional<std::string>& nick) {
+ nick_ = nick;
+ }
+
+ void setPassword(const boost::optional<std::string>& password) {
+ password_ = password;
+ }
+
+ const boost::optional<std::string>& getNick() const {
+ return nick_;
+ }
+
+ const boost::optional<std::string>& getPassword() const {
+ return password_;
+ }
+
+ const std::string& getName() const {
+ return name_;
+ }
+
+ const JID& getRoom() const {
+ return room_;
+ }
+
+ bool operator==(const MUCBookmark& rhs) const {
+ /* FIXME: not checking passwords for equality - which might make sense, perhaps */
+ return rhs.room_ == room_ && rhs.name_ == name_ && rhs.nick_ == nick_ /*&& rhs.password_ == password_*/ && rhs.autojoin_ == autojoin_;
+ }
+
+ Storage::Room toStorage() const {
+ Storage::Room room;
+ room.name = name_;
+ room.jid = room_;
+ if (nick_) {
+ room.nick = *nick_;
+ }
+ if (password_) {
+ room.password = *password_;
+ }
+ room.autoJoin = autojoin_;
+ return room;
+ }
+
+ private:
+ JID room_;
+ std::string name_;
+ boost::optional<std::string> nick_;
+ boost::optional<std::string> password_;
+ bool autojoin_;
+ };
}
diff --git a/Swiften/MUC/MUCBookmarkManager.cpp b/Swiften/MUC/MUCBookmarkManager.cpp
index b109be2..1d8c2aa 100644
--- a/Swiften/MUC/MUCBookmarkManager.cpp
+++ b/Swiften/MUC/MUCBookmarkManager.cpp
@@ -19,103 +19,103 @@
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();
+ 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(boost::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()) {
- receivedBookmarks.push_back(MUCBookmark(room));
- }
-
- std::vector<MUCBookmark> newBookmarks;
- foreach (const MUCBookmark& oldBookmark, bookmarks_) {
- if (containsEquivalent(receivedBookmarks, oldBookmark)) {
- newBookmarks.push_back(oldBookmark);
- } else {
- onBookmarkRemoved(oldBookmark);
- }
- }
-
- foreach (const MUCBookmark& newBookmark, receivedBookmarks) {
- if (!containsEquivalent(bookmarks_, newBookmark)) {
- newBookmarks.push_back(newBookmark);
- onBookmarkAdded(newBookmark);
- }
- }
- bookmarks_ = newBookmarks;
+ if (error) {
+ return;
+ }
+
+ ready_ = true;
+ onBookmarksReady();
+
+ storage = payload;
+
+ std::vector<MUCBookmark> receivedBookmarks;
+ foreach (Storage::Room room, payload->getRooms()) {
+ receivedBookmarks.push_back(MUCBookmark(room));
+ }
+
+ std::vector<MUCBookmark> newBookmarks;
+ foreach (const MUCBookmark& oldBookmark, bookmarks_) {
+ if (containsEquivalent(receivedBookmarks, oldBookmark)) {
+ newBookmarks.push_back(oldBookmark);
+ } else {
+ onBookmarkRemoved(oldBookmark);
+ }
+ }
+
+ foreach (const MUCBookmark& 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();
+ return std::find(list.begin(), list.end(), bookmark) != list.end();
}
void MUCBookmarkManager::replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) {
- if (!ready_) return;
- for (size_t i = 0; i < bookmarks_.size(); i++) {
- if (bookmarks_[i] == oldBookmark) {
- bookmarks_[i] = newBookmark;
- flush();
- onBookmarkRemoved(oldBookmark);
- onBookmarkAdded(newBookmark);
- return;
- }
- }
+ if (!ready_) return;
+ for (size_t i = 0; i < bookmarks_.size(); i++) {
+ if (bookmarks_[i] == oldBookmark) {
+ bookmarks_[i] = newBookmark;
+ flush();
+ onBookmarkRemoved(oldBookmark);
+ onBookmarkAdded(newBookmark);
+ return;
+ }
+ }
}
void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) {
- if (!ready_) return;
- bookmarks_.push_back(bookmark);
- onBookmarkAdded(bookmark);
- flush();
+ 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();
+ 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 = boost::make_shared<Storage>();
- }
- // Update the storage element
- storage->clearRooms();
- foreach(const MUCBookmark& 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();
+ if (!storage) {
+ storage = boost::make_shared<Storage>();
+ }
+ // Update the storage element
+ storage->clearRooms();
+ foreach(const MUCBookmark& 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_;
+ return bookmarks_;
}
}
diff --git a/Swiften/MUC/MUCBookmarkManager.h b/Swiften/MUC/MUCBookmarkManager.h
index fb5d9f1..18dd677 100644
--- a/Swiften/MUC/MUCBookmarkManager.h
+++ b/Swiften/MUC/MUCBookmarkManager.h
@@ -18,35 +18,35 @@
#include <Swiften/MUC/MUCBookmark.h>
namespace Swift {
- class IQRouter;
-
- class SWIFTEN_API MUCBookmarkManager {
- public:
- MUCBookmarkManager(IQRouter* iqRouter);
-
- void addBookmark(const MUCBookmark& bookmark);
- void removeBookmark(const MUCBookmark& bookmark);
- void replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark);
-
- const std::vector<MUCBookmark>& getBookmarks() const;
-
- public:
- boost::signal<void (const MUCBookmark&)> onBookmarkAdded;
- boost::signal<void (const MUCBookmark&)> onBookmarkRemoved;
- /**
- * When server bookmarks are ready to be used (request response has been received).
- */
- boost::signal<void ()> onBookmarksReady;
-
- private:
- bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark);
- void handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error);
- void flush();
-
- private:
- bool ready_;
- std::vector<MUCBookmark> bookmarks_;
- IQRouter* iqRouter_;
- boost::shared_ptr<Storage> storage;
- };
+ class IQRouter;
+
+ class SWIFTEN_API MUCBookmarkManager {
+ public:
+ MUCBookmarkManager(IQRouter* iqRouter);
+
+ void addBookmark(const MUCBookmark& bookmark);
+ void removeBookmark(const MUCBookmark& bookmark);
+ void replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark);
+
+ const std::vector<MUCBookmark>& getBookmarks() const;
+
+ public:
+ boost::signal<void (const MUCBookmark&)> onBookmarkAdded;
+ boost::signal<void (const MUCBookmark&)> onBookmarkRemoved;
+ /**
+ * When server bookmarks are ready to be used (request response has been received).
+ */
+ boost::signal<void ()> onBookmarksReady;
+
+ private:
+ bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark);
+ void handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error);
+ void flush();
+
+ private:
+ bool ready_;
+ std::vector<MUCBookmark> bookmarks_;
+ IQRouter* iqRouter_;
+ boost::shared_ptr<Storage> storage;
+ };
}
diff --git a/Swiften/MUC/MUCImpl.cpp b/Swiften/MUC/MUCImpl.cpp
index 774bf7a..8562ec8 100644
--- a/Swiften/MUC/MUCImpl.cpp
+++ b/Swiften/MUC/MUCImpl.cpp
@@ -31,7 +31,7 @@ namespace Swift {
typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair;
MUCImpl::MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry) : ownMUCJID(muc), stanzaChannel(stanzaChannel), iqRouter_(iqRouter), presenceSender(presenceSender), mucRegistry(mucRegistry), createAsReservedIfNew(false), unlocking(false), isUnlocked_(false) {
- scopedConnection_ = stanzaChannel->onPresenceReceived.connect(boost::bind(&MUCImpl::handleIncomingPresence, this, _1));
+ scopedConnection_ = stanzaChannel->onPresenceReceived.connect(boost::bind(&MUCImpl::handleIncomingPresence, this, _1));
}
MUCImpl::~MUCImpl()
@@ -44,427 +44,427 @@ MUCImpl::~MUCImpl()
* Join the MUC with default context.
*/
void MUCImpl::joinAs(const std::string &nick) {
- joinSince_ = boost::posix_time::not_a_date_time;
- internalJoin(nick);
+ joinSince_ = boost::posix_time::not_a_date_time;
+ internalJoin(nick);
}
/**
* Set the password used for entering the room.
*/
void MUCImpl::setPassword(const boost::optional<std::string>& newPassword) {
- password = newPassword;
+ password = newPassword;
}
/**
* Join the MUC with context since date.
*/
void MUCImpl::joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since) {
- joinSince_ = since;
- internalJoin(nick);
+ joinSince_ = since;
+ internalJoin(nick);
}
std::map<std::string, MUCOccupant> MUCImpl::getOccupants() const {
- return occupants;
+ return occupants;
}
bool MUCImpl::isEqualExceptID(const Presence& lhs, const Presence& rhs) {
- bool isEqual = false;
- if (lhs.getFrom() == rhs.getFrom() && lhs.getTo() == rhs.getTo() && lhs.getStatus() == rhs.getStatus() && lhs.getShow() == rhs.getShow()) {
- CapsInfo::ref lhsCaps = lhs.getPayload<CapsInfo>();
- CapsInfo::ref rhsCaps = rhs.getPayload<CapsInfo>();
-
- if (!!lhsCaps && !!rhsCaps) {
- isEqual = (*lhsCaps == *rhsCaps);
- }
- else {
- isEqual = (!lhsCaps && !rhsCaps);
- }
- }
- return isEqual;
+ bool isEqual = false;
+ if (lhs.getFrom() == rhs.getFrom() && lhs.getTo() == rhs.getTo() && lhs.getStatus() == rhs.getStatus() && lhs.getShow() == rhs.getShow()) {
+ CapsInfo::ref lhsCaps = lhs.getPayload<CapsInfo>();
+ CapsInfo::ref rhsCaps = rhs.getPayload<CapsInfo>();
+
+ if (!!lhsCaps && !!rhsCaps) {
+ isEqual = (*lhsCaps == *rhsCaps);
+ }
+ else {
+ isEqual = (!lhsCaps && !rhsCaps);
+ }
+ }
+ return isEqual;
}
void MUCImpl::internalJoin(const std::string &nick) {
- //TODO: history request
- joinComplete_ = false;
- joinSucceeded_ = false;
-
- mucRegistry->addMUC(getJID());
-
- ownMUCJID = JID(ownMUCJID.getNode(), ownMUCJID.getDomain(), nick);
-
- Presence::ref joinPresence = presenceSender->getLastSentUndirectedPresence() ? (*presenceSender->getLastSentUndirectedPresence())->clone() : boost::make_shared<Presence>();
- assert(joinPresence->getType() == Presence::Available);
- joinPresence->setTo(ownMUCJID);
- MUCPayload::ref mucPayload = boost::make_shared<MUCPayload>();
- if (joinSince_ != boost::posix_time::not_a_date_time) {
- mucPayload->setSince(joinSince_);
- }
- if (password) {
- mucPayload->setPassword(*password);
- }
- joinPresence->addPayload(mucPayload);
- joinRequestPresence_ = joinPresence;
- presenceSender->sendPresence(joinPresence);
+ //TODO: history request
+ joinComplete_ = false;
+ joinSucceeded_ = false;
+
+ mucRegistry->addMUC(getJID());
+
+ ownMUCJID = JID(ownMUCJID.getNode(), ownMUCJID.getDomain(), nick);
+
+ Presence::ref joinPresence = presenceSender->getLastSentUndirectedPresence() ? (*presenceSender->getLastSentUndirectedPresence())->clone() : boost::make_shared<Presence>();
+ assert(joinPresence->getType() == Presence::Available);
+ joinPresence->setTo(ownMUCJID);
+ MUCPayload::ref mucPayload = boost::make_shared<MUCPayload>();
+ if (joinSince_ != boost::posix_time::not_a_date_time) {
+ mucPayload->setSince(joinSince_);
+ }
+ if (password) {
+ mucPayload->setPassword(*password);
+ }
+ joinPresence->addPayload(mucPayload);
+ joinRequestPresence_ = joinPresence;
+ presenceSender->sendPresence(joinPresence);
}
void MUCImpl::changeNickname(const std::string& newNickname) {
- Presence::ref changeNicknamePresence = boost::make_shared<Presence>();
- changeNicknamePresence->setTo(ownMUCJID.toBare().toString() + std::string("/") + newNickname);
- presenceSender->sendPresence(changeNicknamePresence);
+ Presence::ref changeNicknamePresence = boost::make_shared<Presence>();
+ changeNicknamePresence->setTo(ownMUCJID.toBare().toString() + std::string("/") + newNickname);
+ presenceSender->sendPresence(changeNicknamePresence);
}
void MUCImpl::part() {
- presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
- mucRegistry->removeMUC(getJID());
+ presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
+ mucRegistry->removeMUC(getJID());
}
void MUCImpl::handleUserLeft(LeavingType type) {
- std::map<std::string,MUCOccupant>::iterator i = occupants.find(ownMUCJID.getResource());
- if (i != occupants.end()) {
- MUCOccupant me = i->second;
- occupants.erase(i);
- onOccupantLeft(me, type, "");
- }
- occupants.clear();
- joinComplete_ = false;
- joinSucceeded_ = false;
- isUnlocked_ = false;
- presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
+ std::map<std::string,MUCOccupant>::iterator i = occupants.find(ownMUCJID.getResource());
+ if (i != occupants.end()) {
+ MUCOccupant me = i->second;
+ occupants.erase(i);
+ onOccupantLeft(me, type, "");
+ }
+ occupants.clear();
+ joinComplete_ = false;
+ joinSucceeded_ = false;
+ isUnlocked_ = false;
+ presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
}
void MUCImpl::handleIncomingPresence(Presence::ref presence) {
- if (!isFromMUC(presence->getFrom())) {
- return;
- }
-
- MUCUserPayload::ref mucPayload;
- foreach (MUCUserPayload::ref payload, presence->getPayloads<MUCUserPayload>()) {
- if (!payload->getItems().empty() || !payload->getStatusCodes().empty()) {
- mucPayload = payload;
- }
- }
-
- // On the first incoming presence, check if our join has succeeded
- // (i.e. we start getting non-error presence from the MUC) or not
- if (!joinSucceeded_) {
- if (presence->getType() == Presence::Error) {
- std::string reason;
- onJoinFailed(presence->getPayload<ErrorPayload>());
- return;
- }
- else {
- joinSucceeded_ = true;
- presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
- if (presenceSender->getLastSentUndirectedPresence() && !isEqualExceptID(**(presenceSender->getLastSentUndirectedPresence()), *joinRequestPresence_)) {
- // our presence changed between join request and join complete, send current presence to MUC
- Presence::ref latestPresence = boost::make_shared<Presence>(**presenceSender->getLastSentUndirectedPresence());
- latestPresence->setTo(ownMUCJID);
- presenceSender->sendPresence(latestPresence);
- }
- }
- }
-
- std::string nick = presence->getFrom().getResource();
- if (nick.empty()) {
- return;
- }
- MUCOccupant::Role role(MUCOccupant::NoRole);
- MUCOccupant::Affiliation affiliation(MUCOccupant::NoAffiliation);
- boost::optional<JID> realJID;
- if (mucPayload && mucPayload->getItems().size() > 0) {
- role = mucPayload->getItems()[0].role ? mucPayload->getItems()[0].role.get() : MUCOccupant::NoRole;
- affiliation = mucPayload->getItems()[0].affiliation ? mucPayload->getItems()[0].affiliation.get() : MUCOccupant::NoAffiliation;
- realJID = mucPayload->getItems()[0].realJID;
- }
-
- //100 is non-anonymous
- //TODO: 100 may also be specified in a <message/>
- //170 is room logging to http
- //TODO: Nick changes
- if (presence->getType() == Presence::Unavailable) {
- LeavingType type = LeavePart;
- boost::optional<std::string> newNickname;
- if (mucPayload) {
- if (boost::dynamic_pointer_cast<MUCDestroyPayload>(mucPayload->getPayload())) {
- type = LeaveDestroy;
- }
- else foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) {
- if (status.code == 307) {
- type = LeaveKick;
- }
- else if (status.code == 301) {
- type = LeaveBan;
- }
- else if (status.code == 321) {
- type = LeaveNotMember;
- }
- else if (status.code == 303) {
- if (mucPayload->getItems().size() == 1) {
- newNickname = mucPayload->getItems()[0].nick;
- }
- }
- }
- }
- if (newNickname) {
- std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick);
- if (i != occupants.end()) {
- MUCOccupant occupant = i->second;
- occupants.erase(i);
- occupant.setNick(newNickname.get());
- occupants.insert(std::make_pair(newNickname.get(), occupant));
- onOccupantNicknameChanged(nick, newNickname.get());
- }
- }
- else {
- if (presence->getFrom() == ownMUCJID) {
- handleUserLeft(type);
- return;
- }
- else {
- std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick);
- if (i != occupants.end()) {
- //TODO: part type
- MUCOccupant occupant = i->second;
- occupants.erase(i);
- onOccupantLeft(occupant, type, "");
- }
- }
- }
- }
- else if (presence->getType() == Presence::Available) {
- std::map<std::string, MUCOccupant>::iterator it = occupants.find(nick);
- MUCOccupant occupant(nick, role, affiliation);
- bool isJoin = true;
- if (realJID) {
- occupant.setRealJID(realJID.get());
- }
- if (it != occupants.end()) {
- isJoin = false;
- MUCOccupant oldOccupant = it->second;
- if (oldOccupant.getRole() != role) {
- onOccupantRoleChanged(nick, occupant, oldOccupant.getRole());
- }
- if (oldOccupant.getAffiliation() != affiliation) {
- onOccupantAffiliationChanged(nick, affiliation, oldOccupant.getAffiliation());
- }
- occupants.erase(it);
- }
- std::pair<std::map<std::string, MUCOccupant>::iterator, bool> result = occupants.insert(std::make_pair(nick, occupant));
- if (isJoin) {
- onOccupantJoined(result.first->second);
- }
- onOccupantPresenceChange(presence);
- }
- if (mucPayload && !joinComplete_) {
- bool isLocked = false;
- foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) {
- if (status.code == 110) {
- /* Simply knowing this is your presence is enough, 210 doesn't seem to be necessary. */
- joinComplete_ = true;
- if (ownMUCJID != presence->getFrom()) {
- presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
- ownMUCJID = presence->getFrom();
- presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
- }
- }
- // MUC status 201: a new room has been created
- if (status.code == 201) {
- isLocked = true;
- /* Room is created and locked */
- /* Currently deal with this by making an instant room */
- if (ownMUCJID != presence->getFrom()) {
- presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
- ownMUCJID = presence->getFrom();
- presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
- }
- if (createAsReservedIfNew) {
- unlocking = true;
- requestConfigurationForm();
- }
- else {
- // Accept default room configuration and create an instant room http://xmpp.org/extensions/xep-0045.html#createroom-instant
- MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
- presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
- mucPayload->setPayload(boost::make_shared<Form>(Form::SubmitType));
- boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared< GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2));
- request->send();
- }
- }
- }
- if (joinComplete_ && !isLocked) {
- onJoinComplete(getOwnNick());
- }
- if (!isLocked && !isUnlocked_ && (presence->getFrom() == ownMUCJID)) {
- isUnlocked_ = true;
- onUnlocked();
- }
- }
+ if (!isFromMUC(presence->getFrom())) {
+ return;
+ }
+
+ MUCUserPayload::ref mucPayload;
+ foreach (MUCUserPayload::ref payload, presence->getPayloads<MUCUserPayload>()) {
+ if (!payload->getItems().empty() || !payload->getStatusCodes().empty()) {
+ mucPayload = payload;
+ }
+ }
+
+ // On the first incoming presence, check if our join has succeeded
+ // (i.e. we start getting non-error presence from the MUC) or not
+ if (!joinSucceeded_) {
+ if (presence->getType() == Presence::Error) {
+ std::string reason;
+ onJoinFailed(presence->getPayload<ErrorPayload>());
+ return;
+ }
+ else {
+ joinSucceeded_ = true;
+ presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
+ if (presenceSender->getLastSentUndirectedPresence() && !isEqualExceptID(**(presenceSender->getLastSentUndirectedPresence()), *joinRequestPresence_)) {
+ // our presence changed between join request and join complete, send current presence to MUC
+ Presence::ref latestPresence = boost::make_shared<Presence>(**presenceSender->getLastSentUndirectedPresence());
+ latestPresence->setTo(ownMUCJID);
+ presenceSender->sendPresence(latestPresence);
+ }
+ }
+ }
+
+ std::string nick = presence->getFrom().getResource();
+ if (nick.empty()) {
+ return;
+ }
+ MUCOccupant::Role role(MUCOccupant::NoRole);
+ MUCOccupant::Affiliation affiliation(MUCOccupant::NoAffiliation);
+ boost::optional<JID> realJID;
+ if (mucPayload && mucPayload->getItems().size() > 0) {
+ role = mucPayload->getItems()[0].role ? mucPayload->getItems()[0].role.get() : MUCOccupant::NoRole;
+ affiliation = mucPayload->getItems()[0].affiliation ? mucPayload->getItems()[0].affiliation.get() : MUCOccupant::NoAffiliation;
+ realJID = mucPayload->getItems()[0].realJID;
+ }
+
+ //100 is non-anonymous
+ //TODO: 100 may also be specified in a <message/>
+ //170 is room logging to http
+ //TODO: Nick changes
+ if (presence->getType() == Presence::Unavailable) {
+ LeavingType type = LeavePart;
+ boost::optional<std::string> newNickname;
+ if (mucPayload) {
+ if (boost::dynamic_pointer_cast<MUCDestroyPayload>(mucPayload->getPayload())) {
+ type = LeaveDestroy;
+ }
+ else foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) {
+ if (status.code == 307) {
+ type = LeaveKick;
+ }
+ else if (status.code == 301) {
+ type = LeaveBan;
+ }
+ else if (status.code == 321) {
+ type = LeaveNotMember;
+ }
+ else if (status.code == 303) {
+ if (mucPayload->getItems().size() == 1) {
+ newNickname = mucPayload->getItems()[0].nick;
+ }
+ }
+ }
+ }
+ if (newNickname) {
+ std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick);
+ if (i != occupants.end()) {
+ MUCOccupant occupant = i->second;
+ occupants.erase(i);
+ occupant.setNick(newNickname.get());
+ occupants.insert(std::make_pair(newNickname.get(), occupant));
+ onOccupantNicknameChanged(nick, newNickname.get());
+ }
+ }
+ else {
+ if (presence->getFrom() == ownMUCJID) {
+ handleUserLeft(type);
+ return;
+ }
+ else {
+ std::map<std::string,MUCOccupant>::iterator i = occupants.find(nick);
+ if (i != occupants.end()) {
+ //TODO: part type
+ MUCOccupant occupant = i->second;
+ occupants.erase(i);
+ onOccupantLeft(occupant, type, "");
+ }
+ }
+ }
+ }
+ else if (presence->getType() == Presence::Available) {
+ std::map<std::string, MUCOccupant>::iterator it = occupants.find(nick);
+ MUCOccupant occupant(nick, role, affiliation);
+ bool isJoin = true;
+ if (realJID) {
+ occupant.setRealJID(realJID.get());
+ }
+ if (it != occupants.end()) {
+ isJoin = false;
+ MUCOccupant oldOccupant = it->second;
+ if (oldOccupant.getRole() != role) {
+ onOccupantRoleChanged(nick, occupant, oldOccupant.getRole());
+ }
+ if (oldOccupant.getAffiliation() != affiliation) {
+ onOccupantAffiliationChanged(nick, affiliation, oldOccupant.getAffiliation());
+ }
+ occupants.erase(it);
+ }
+ std::pair<std::map<std::string, MUCOccupant>::iterator, bool> result = occupants.insert(std::make_pair(nick, occupant));
+ if (isJoin) {
+ onOccupantJoined(result.first->second);
+ }
+ onOccupantPresenceChange(presence);
+ }
+ if (mucPayload && !joinComplete_) {
+ bool isLocked = false;
+ foreach (MUCUserPayload::StatusCode status, mucPayload->getStatusCodes()) {
+ if (status.code == 110) {
+ /* Simply knowing this is your presence is enough, 210 doesn't seem to be necessary. */
+ joinComplete_ = true;
+ if (ownMUCJID != presence->getFrom()) {
+ presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
+ ownMUCJID = presence->getFrom();
+ presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
+ }
+ }
+ // MUC status 201: a new room has been created
+ if (status.code == 201) {
+ isLocked = true;
+ /* Room is created and locked */
+ /* Currently deal with this by making an instant room */
+ if (ownMUCJID != presence->getFrom()) {
+ presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
+ ownMUCJID = presence->getFrom();
+ presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
+ }
+ if (createAsReservedIfNew) {
+ unlocking = true;
+ requestConfigurationForm();
+ }
+ else {
+ // Accept default room configuration and create an instant room http://xmpp.org/extensions/xep-0045.html#createroom-instant
+ MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
+ presenceSender->addDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::DontSendPresence);
+ mucPayload->setPayload(boost::make_shared<Form>(Form::SubmitType));
+ boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared< GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2));
+ request->send();
+ }
+ }
+ }
+ if (joinComplete_ && !isLocked) {
+ onJoinComplete(getOwnNick());
+ }
+ if (!isLocked && !isUnlocked_ && (presence->getFrom() == ownMUCJID)) {
+ isUnlocked_ = true;
+ onUnlocked();
+ }
+ }
}
void MUCImpl::handleCreationConfigResponse(MUCOwnerPayload::ref /*unused*/, ErrorPayload::ref error) {
- unlocking = false;
- if (error) {
- presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
- onJoinFailed(error);
- } else {
- onJoinComplete(getOwnNick()); /* Previously, this wasn't needed here, as the presence duplication bug caused an emit elsewhere. */
- isUnlocked_ = true;
- onUnlocked();
- }
+ unlocking = false;
+ if (error) {
+ presenceSender->removeDirectedPresenceReceiver(ownMUCJID, DirectedPresenceSender::AndSendPresence);
+ onJoinFailed(error);
+ } else {
+ onJoinComplete(getOwnNick()); /* Previously, this wasn't needed here, as the presence duplication bug caused an emit elsewhere. */
+ isUnlocked_ = true;
+ onUnlocked();
+ }
}
bool MUCImpl::hasOccupant(const std::string& nick) {
- return occupants.find(nick) != occupants.end();
+ return occupants.find(nick) != occupants.end();
}
const MUCOccupant& MUCImpl::getOccupant(const std::string& nick) {
- return occupants.find(nick)->second;
+ return occupants.find(nick)->second;
}
void MUCImpl::kickOccupant(const JID& jid) {
- changeOccupantRole(jid, MUCOccupant::NoRole);
+ changeOccupantRole(jid, MUCOccupant::NoRole);
}
/**
* Call with the room JID, not the real JID.
*/
void MUCImpl::changeOccupantRole(const JID& jid, MUCOccupant::Role role) {
- MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
- MUCItem item;
- item.role = role;
- item.nick = jid.getResource();
- mucPayload->addItem(item);
- boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleOccupantRoleChangeResponse, this, _1, _2, jid, role));
- request->send();
-
+ MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.role = role;
+ item.nick = jid.getResource();
+ mucPayload->addItem(item);
+ boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleOccupantRoleChangeResponse, this, _1, _2, jid, role));
+ request->send();
+
}
void MUCImpl::handleOccupantRoleChangeResponse(MUCAdminPayload::ref /*unused*/, ErrorPayload::ref error, const JID& jid, MUCOccupant::Role role) {
- if (error) {
- onRoleChangeFailed(error, jid, role);
- }
+ if (error) {
+ onRoleChangeFailed(error, jid, role);
+ }
}
void MUCImpl::requestAffiliationList(MUCOccupant::Affiliation affiliation) {
- MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
- MUCItem item;
- item.affiliation = affiliation;
- mucPayload->addItem(item);
- boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared< GenericRequest<MUCAdminPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationListResponse, this, _1, _2, affiliation));
- request->send();
+ MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.affiliation = affiliation;
+ mucPayload->addItem(item);
+ boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared< GenericRequest<MUCAdminPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationListResponse, this, _1, _2, affiliation));
+ request->send();
}
/**
* Must be called with the real JID, not the room JID.
*/
void MUCImpl::changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) {
- MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
- MUCItem item;
- item.affiliation = affiliation;
- item.realJID = jid.toBare();
- mucPayload->addItem(item);
- boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationChangeResponse, this, _1, _2, jid, affiliation));
- request->send();
+ MUCAdminPayload::ref mucPayload = boost::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.affiliation = affiliation;
+ item.realJID = jid.toBare();
+ mucPayload->addItem(item);
+ boost::shared_ptr<GenericRequest<MUCAdminPayload> > request = boost::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationChangeResponse, this, _1, _2, jid, affiliation));
+ request->send();
}
void MUCImpl::handleAffiliationListResponse(MUCAdminPayload::ref payload, ErrorPayload::ref error, MUCOccupant::Affiliation affiliation) {
- if (error) {
- onAffiliationListFailed(error);
- }
- else {
- std::vector<JID> jids;
- foreach (MUCItem item, payload->getItems()) {
- if (item.realJID) {
- jids.push_back(*item.realJID);
- }
- }
- onAffiliationListReceived(affiliation, jids);
- }
+ if (error) {
+ onAffiliationListFailed(error);
+ }
+ else {
+ std::vector<JID> jids;
+ foreach (MUCItem item, payload->getItems()) {
+ if (item.realJID) {
+ jids.push_back(*item.realJID);
+ }
+ }
+ onAffiliationListReceived(affiliation, jids);
+ }
}
void MUCImpl::handleAffiliationChangeResponse(MUCAdminPayload::ref /*unused*/, ErrorPayload::ref error, const JID& jid, MUCOccupant::Affiliation affiliation) {
- if (error) {
- onAffiliationChangeFailed(error, jid, affiliation);
- }
+ if (error) {
+ onAffiliationChangeFailed(error, jid, affiliation);
+ }
}
void MUCImpl::changeSubject(const std::string& subject) {
- Message::ref message = boost::make_shared<Message>();
- message->setSubject(subject);
- message->setType(Message::Groupchat);
- message->setTo(ownMUCJID.toBare());
- stanzaChannel->sendMessage(message);
+ Message::ref message = boost::make_shared<Message>();
+ message->setSubject(subject);
+ message->setType(Message::Groupchat);
+ message->setTo(ownMUCJID.toBare());
+ stanzaChannel->sendMessage(message);
}
void MUCImpl::requestConfigurationForm() {
- MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
- boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationFormReceived, this, _1, _2));
- request->send();
+ MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
+ boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Get, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationFormReceived, this, _1, _2));
+ request->send();
}
void MUCImpl::cancelConfigureRoom() {
- MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
- mucPayload->setPayload(boost::make_shared<Form>(Form::CancelType));
- boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- request->send();
+ MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
+ mucPayload->setPayload(boost::make_shared<Form>(Form::CancelType));
+ boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->send();
}
void MUCImpl::handleConfigurationFormReceived(MUCOwnerPayload::ref payload, ErrorPayload::ref error) {
- Form::ref form;
- if (payload) {
- form = payload->getForm();
- }
- if (error || !form) {
- onConfigurationFailed(error);
- } else {
- onConfigurationFormReceived(form);
- }
+ Form::ref form;
+ if (payload) {
+ form = payload->getForm();
+ }
+ if (error || !form) {
+ onConfigurationFailed(error);
+ } else {
+ onConfigurationFormReceived(form);
+ }
}
void MUCImpl::handleConfigurationResultReceived(MUCOwnerPayload::ref /*payload*/, ErrorPayload::ref error) {
- if (error) {
- onConfigurationFailed(error);
- }
+ if (error) {
+ onConfigurationFailed(error);
+ }
}
void MUCImpl::configureRoom(Form::ref form) {
- MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
- mucPayload->setPayload(form);
- boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- if (unlocking) {
- request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2));
- }
- else {
- request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2));
- }
- request->send();
+ MUCOwnerPayload::ref mucPayload(new MUCOwnerPayload());
+ mucPayload->setPayload(form);
+ boost::shared_ptr<GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ if (unlocking) {
+ request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2));
+ }
+ else {
+ request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2));
+ }
+ request->send();
}
void MUCImpl::destroyRoom() {
- MUCOwnerPayload::ref mucPayload = boost::make_shared<MUCOwnerPayload>();
- MUCDestroyPayload::ref mucDestroyPayload = boost::make_shared<MUCDestroyPayload>();
- mucPayload->setPayload(mucDestroyPayload);
- boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
- request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2));
- request->send();
+ MUCOwnerPayload::ref mucPayload = boost::make_shared<MUCOwnerPayload>();
+ MUCDestroyPayload::ref mucDestroyPayload = boost::make_shared<MUCDestroyPayload>();
+ mucPayload->setPayload(mucDestroyPayload);
+ boost::shared_ptr< GenericRequest<MUCOwnerPayload> > request = boost::make_shared<GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleConfigurationResultReceived, this, _1, _2));
+ request->send();
}
void MUCImpl::invitePerson(const JID& person, const std::string& reason, bool isImpromptu, bool isReuseChat) {
- Message::ref message = boost::make_shared<Message>();
- message->setTo(person);
- message->setType(Message::Normal);
- MUCInvitationPayload::ref invite = boost::make_shared<MUCInvitationPayload>();
- invite->setReason(reason);
- invite->setJID(ownMUCJID.toBare());
- invite->setIsImpromptu(isImpromptu);
- invite->setIsContinuation(isReuseChat);
- message->addPayload(invite);
- stanzaChannel->sendMessage(message);
+ Message::ref message = boost::make_shared<Message>();
+ message->setTo(person);
+ message->setType(Message::Normal);
+ MUCInvitationPayload::ref invite = boost::make_shared<MUCInvitationPayload>();
+ invite->setReason(reason);
+ invite->setJID(ownMUCJID.toBare());
+ invite->setIsImpromptu(isImpromptu);
+ invite->setIsContinuation(isReuseChat);
+ message->addPayload(invite);
+ stanzaChannel->sendMessage(message);
}
//TODO: Invites(direct/mediated)
diff --git a/Swiften/MUC/MUCImpl.h b/Swiften/MUC/MUCImpl.h
index 8103e69..9b4377a 100644
--- a/Swiften/MUC/MUCImpl.h
+++ b/Swiften/MUC/MUCImpl.h
@@ -25,106 +25,106 @@
#include <Swiften/MUC/MUCRegistry.h>
namespace Swift {
- class StanzaChannel;
- class IQRouter;
- class DirectedPresenceSender;
-
- class SWIFTEN_API MUCImpl : public MUC {
- public:
- typedef boost::shared_ptr<MUCImpl> ref;
-
- public:
- MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry);
- virtual ~MUCImpl();
-
- /**
- * Returns the (bare) JID of the MUC.
- */
- virtual JID getJID() const {
- return ownMUCJID.toBare();
- }
-
- /**
- * Returns if the room is unlocked and other people can join the room.
- * @return True if joinable by others; false otherwise.
- */
- virtual bool isUnlocked() const {
- return isUnlocked_;
- }
-
- virtual void joinAs(const std::string &nick);
- virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since);
- /*virtual void queryRoomInfo(); */
- /*virtual void queryRoomItems(); */
- /*virtual std::string getCurrentNick(); */
- virtual std::map<std::string, MUCOccupant> getOccupants() const;
-
- /**
- * Send a new presence to the MUC indicating a nickname change. Any custom status the user had in the is cleared.
- * @param newNickname The nickname to change to.
- */
- virtual void changeNickname(const std::string& newNickname);
- virtual void part();
- /*virtual void handleIncomingMessage(Message::ref message); */
- /** Expose public so it can be called when e.g. user goes offline */
- virtual void handleUserLeft(LeavingType);
- /** Get occupant information*/
- virtual const MUCOccupant& getOccupant(const std::string& nick);
- virtual bool hasOccupant(const std::string& nick);
- virtual void kickOccupant(const JID& jid);
- virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role);
- virtual void requestAffiliationList(MUCOccupant::Affiliation);
- virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation);
- virtual void changeSubject(const std::string& subject);
- virtual void requestConfigurationForm();
- virtual void configureRoom(Form::ref);
- virtual void cancelConfigureRoom();
- virtual void destroyRoom();
- /** Send an invite for the person to join the MUC */
- virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false);
- virtual void setCreateAsReservedIfNew() {createAsReservedIfNew = true;}
- virtual void setPassword(const boost::optional<std::string>& password);
-
- private:
- bool isFromMUC(const JID& j) const {
- return ownMUCJID.equals(j, JID::WithoutResource);
- }
-
- const std::string& getOwnNick() const {
- return ownMUCJID.getResource();
- }
-
- /**
- * This function compares two Presence elements for equality based on to, from, status, show and entity capability information.
- * @return True if equal; else otherwise.
- */
- static bool isEqualExceptID(const Presence& lhs, const Presence& rhs);
-
- private:
- void handleIncomingPresence(Presence::ref presence);
- void internalJoin(const std::string& nick);
- void handleCreationConfigResponse(MUCOwnerPayload::ref, ErrorPayload::ref);
- void handleOccupantRoleChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Role);
- void handleAffiliationChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Affiliation);
- void handleAffiliationListResponse(MUCAdminPayload::ref, ErrorPayload::ref, MUCOccupant::Affiliation);
- void handleConfigurationFormReceived(MUCOwnerPayload::ref, ErrorPayload::ref);
- void handleConfigurationResultReceived(MUCOwnerPayload::ref, ErrorPayload::ref);
-
- private:
- JID ownMUCJID;
- StanzaChannel* stanzaChannel;
- IQRouter* iqRouter_;
- DirectedPresenceSender* presenceSender;
- MUCRegistry* mucRegistry;
- std::map<std::string, MUCOccupant> occupants;
- bool joinSucceeded_;
- bool joinComplete_;
- boost::bsignals::scoped_connection scopedConnection_;
- boost::posix_time::ptime joinSince_;
- bool createAsReservedIfNew;
- bool unlocking;
- bool isUnlocked_;
- boost::optional<std::string> password;
- Presence::ref joinRequestPresence_;
- };
+ class StanzaChannel;
+ class IQRouter;
+ class DirectedPresenceSender;
+
+ class SWIFTEN_API MUCImpl : public MUC {
+ public:
+ typedef boost::shared_ptr<MUCImpl> ref;
+
+ public:
+ MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry);
+ virtual ~MUCImpl();
+
+ /**
+ * Returns the (bare) JID of the MUC.
+ */
+ virtual JID getJID() const {
+ return ownMUCJID.toBare();
+ }
+
+ /**
+ * Returns if the room is unlocked and other people can join the room.
+ * @return True if joinable by others; false otherwise.
+ */
+ virtual bool isUnlocked() const {
+ return isUnlocked_;
+ }
+
+ virtual void joinAs(const std::string &nick);
+ virtual void joinWithContextSince(const std::string &nick, const boost::posix_time::ptime& since);
+ /*virtual void queryRoomInfo(); */
+ /*virtual void queryRoomItems(); */
+ /*virtual std::string getCurrentNick(); */
+ virtual std::map<std::string, MUCOccupant> getOccupants() const;
+
+ /**
+ * Send a new presence to the MUC indicating a nickname change. Any custom status the user had in the is cleared.
+ * @param newNickname The nickname to change to.
+ */
+ virtual void changeNickname(const std::string& newNickname);
+ virtual void part();
+ /*virtual void handleIncomingMessage(Message::ref message); */
+ /** Expose public so it can be called when e.g. user goes offline */
+ virtual void handleUserLeft(LeavingType);
+ /** Get occupant information*/
+ virtual const MUCOccupant& getOccupant(const std::string& nick);
+ virtual bool hasOccupant(const std::string& nick);
+ virtual void kickOccupant(const JID& jid);
+ virtual void changeOccupantRole(const JID& jid, MUCOccupant::Role role);
+ virtual void requestAffiliationList(MUCOccupant::Affiliation);
+ virtual void changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation);
+ virtual void changeSubject(const std::string& subject);
+ virtual void requestConfigurationForm();
+ virtual void configureRoom(Form::ref);
+ virtual void cancelConfigureRoom();
+ virtual void destroyRoom();
+ /** Send an invite for the person to join the MUC */
+ virtual void invitePerson(const JID& person, const std::string& reason = "", bool isImpromptu = false, bool isReuseChat = false);
+ virtual void setCreateAsReservedIfNew() {createAsReservedIfNew = true;}
+ virtual void setPassword(const boost::optional<std::string>& password);
+
+ private:
+ bool isFromMUC(const JID& j) const {
+ return ownMUCJID.equals(j, JID::WithoutResource);
+ }
+
+ const std::string& getOwnNick() const {
+ return ownMUCJID.getResource();
+ }
+
+ /**
+ * This function compares two Presence elements for equality based on to, from, status, show and entity capability information.
+ * @return True if equal; else otherwise.
+ */
+ static bool isEqualExceptID(const Presence& lhs, const Presence& rhs);
+
+ private:
+ void handleIncomingPresence(Presence::ref presence);
+ void internalJoin(const std::string& nick);
+ void handleCreationConfigResponse(MUCOwnerPayload::ref, ErrorPayload::ref);
+ void handleOccupantRoleChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Role);
+ void handleAffiliationChangeResponse(MUCAdminPayload::ref, ErrorPayload::ref, const JID&, MUCOccupant::Affiliation);
+ void handleAffiliationListResponse(MUCAdminPayload::ref, ErrorPayload::ref, MUCOccupant::Affiliation);
+ void handleConfigurationFormReceived(MUCOwnerPayload::ref, ErrorPayload::ref);
+ void handleConfigurationResultReceived(MUCOwnerPayload::ref, ErrorPayload::ref);
+
+ private:
+ JID ownMUCJID;
+ StanzaChannel* stanzaChannel;
+ IQRouter* iqRouter_;
+ DirectedPresenceSender* presenceSender;
+ MUCRegistry* mucRegistry;
+ std::map<std::string, MUCOccupant> occupants;
+ bool joinSucceeded_;
+ bool joinComplete_;
+ boost::bsignals::scoped_connection scopedConnection_;
+ boost::posix_time::ptime joinSince_;
+ bool createAsReservedIfNew;
+ bool unlocking;
+ bool isUnlocked_;
+ boost::optional<std::string> password;
+ Presence::ref joinRequestPresence_;
+ };
}
diff --git a/Swiften/MUC/MUCManager.cpp b/Swiften/MUC/MUCManager.cpp
index 58a9a15..b4e3b00 100644
--- a/Swiften/MUC/MUCManager.cpp
+++ b/Swiften/MUC/MUCManager.cpp
@@ -14,7 +14,7 @@ MUCManager::MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, Directe
}
MUC::ref MUCManager::createMUC(const JID& jid) {
- return boost::make_shared<MUCImpl>(stanzaChannel, iqRouter, presenceSender, jid, mucRegistry);
+ return boost::make_shared<MUCImpl>(stanzaChannel, iqRouter, presenceSender, jid, mucRegistry);
}
}
diff --git a/Swiften/MUC/MUCManager.h b/Swiften/MUC/MUCManager.h
index 5e237f5..c1f0f61 100644
--- a/Swiften/MUC/MUCManager.h
+++ b/Swiften/MUC/MUCManager.h
@@ -10,21 +10,21 @@
#include <Swiften/MUC/MUC.h>
namespace Swift {
- class IQRouter;
- class StanzaChannel;
- class DirectedPresenceSender;
- class MUCRegistry;
+ class IQRouter;
+ class StanzaChannel;
+ class DirectedPresenceSender;
+ class MUCRegistry;
- class SWIFTEN_API MUCManager {
- public:
- MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, MUCRegistry* mucRegistry);
+ class SWIFTEN_API MUCManager {
+ public:
+ MUCManager(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, MUCRegistry* mucRegistry);
- MUC::ref createMUC(const JID&);
+ MUC::ref createMUC(const JID&);
- private:
- StanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- DirectedPresenceSender* presenceSender;
- MUCRegistry* mucRegistry;
- };
+ private:
+ StanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ DirectedPresenceSender* presenceSender;
+ MUCRegistry* mucRegistry;
+ };
}
diff --git a/Swiften/MUC/MUCRegistry.cpp b/Swiften/MUC/MUCRegistry.cpp
index 38433a7..9315173 100644
--- a/Swiften/MUC/MUCRegistry.cpp
+++ b/Swiften/MUC/MUCRegistry.cpp
@@ -14,15 +14,15 @@ MUCRegistry::~MUCRegistry() {
}
bool MUCRegistry::isMUC(const JID& j) const {
- return std::find(mucs.begin(), mucs.end(), j) != mucs.end();
+ return std::find(mucs.begin(), mucs.end(), j) != mucs.end();
}
void MUCRegistry::addMUC(const JID& j) {
- mucs.push_back(j);
+ mucs.push_back(j);
}
void MUCRegistry::removeMUC(const JID& j) {
- erase(mucs, j);
+ erase(mucs, j);
}
diff --git a/Swiften/MUC/MUCRegistry.h b/Swiften/MUC/MUCRegistry.h
index e69cdb5..3f61c71 100644
--- a/Swiften/MUC/MUCRegistry.h
+++ b/Swiften/MUC/MUCRegistry.h
@@ -12,17 +12,17 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class JID;
+ class JID;
- class SWIFTEN_API MUCRegistry {
- public:
- ~MUCRegistry();
+ class SWIFTEN_API MUCRegistry {
+ public:
+ ~MUCRegistry();
- bool isMUC(const JID& j) const;
- void addMUC(const JID& j);
- void removeMUC(const JID& j);
+ bool isMUC(const JID& j) const;
+ void addMUC(const JID& j);
+ void removeMUC(const JID& j);
- private:
- std::vector<JID> mucs;
- };
+ private:
+ std::vector<JID> mucs;
+ };
}
diff --git a/Swiften/MUC/UnitTest/MUCTest.cpp b/Swiften/MUC/UnitTest/MUCTest.cpp
index a422c12..548617c 100644
--- a/Swiften/MUC/UnitTest/MUCTest.cpp
+++ b/Swiften/MUC/UnitTest/MUCTest.cpp
@@ -24,254 +24,254 @@
using namespace Swift;
class MUCTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MUCTest);
- CPPUNIT_TEST(testJoin);
- CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess);
- CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess);
- CPPUNIT_TEST(testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess);
- CPPUNIT_TEST(testCreateInstant);
- CPPUNIT_TEST(testReplicateBug);
- CPPUNIT_TEST(testNicknameChange);
- /*CPPUNIT_TEST(testJoin_Success);
- CPPUNIT_TEST(testJoin_Fail);*/
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- channel = new DummyStanzaChannel();
- router = new IQRouter(channel);
- mucRegistry = new MUCRegistry();
- stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel);
- presenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender);
- nickChanges = 0;
- }
-
- void tearDown() {
- delete presenceSender;
- delete stanzaChannelPresenceSender;
- delete mucRegistry;
- delete router;
- delete channel;
- }
-
- void testJoin() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- testling->joinAs("Alice");
-
- CPPUNIT_ASSERT(mucRegistry->isMUC(JID("foo@bar.com")));
- Presence::ref p = channel->getStanzaAtIndex<Presence>(0);
- CPPUNIT_ASSERT(p);
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
- }
-
- void testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- testling->joinAs("Alice");
-
- presenceSender->sendPresence(Presence::create("Test"));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
- }
-
- void testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- testling->joinAs("Alice");
-
- presenceSender->sendPresence(Presence::create("Test"));
- receivePresence(JID("foo@bar.com/Rabbit"), "Here");
-
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size()));
- Presence::ref p = channel->getStanzaAtIndex<Presence>(2);
- CPPUNIT_ASSERT(p);
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
- CPPUNIT_ASSERT_EQUAL(std::string("Test"), p->getStatus());
- }
-
- void testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- testling->joinAs("Alice");
-
- receivePresence(JID("foo@bar.com/Rabbit"), "Here");
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- Presence::ref p = channel->getStanzaAtIndex<Presence>(0);
- CPPUNIT_ASSERT(p);
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
- CPPUNIT_ASSERT_EQUAL(std::string(""), p->getStatus());
- }
-
- void testCreateInstant() {
- MUC::ref testling = createMUC(JID("rabbithole@wonderland.lit"));
- testling->joinAs("Alice");
- Presence::ref serverRespondsLocked = boost::make_shared<Presence>();
- serverRespondsLocked->setFrom(JID("rabbithole@wonderland.lit/Alice"));
- MUCUserPayload::ref mucPayload(new MUCUserPayload());
- MUCItem myItem;
- myItem.affiliation = MUCOccupant::Owner;
- myItem.role = MUCOccupant::Moderator;
- mucPayload->addItem(myItem);
- mucPayload->addStatusCode(MUCUserPayload::StatusCode(110));
- mucPayload->addStatusCode(MUCUserPayload::StatusCode(201));
- serverRespondsLocked->addPayload(mucPayload);
- channel->onPresenceReceived(serverRespondsLocked);
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
- IQ::ref iq = channel->getStanzaAtIndex<IQ>(1);
- CPPUNIT_ASSERT(iq);
- CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>());
- CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm());
- CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType());
- }
-
- void testReplicateBug() {
- Presence::ref initialPresence = boost::make_shared<Presence>();
- initialPresence->setStatus("");
- VCard::ref vcard = boost::make_shared<VCard>();
- vcard->setPhoto(createByteArray("15c30080ae98ec48be94bf0e191d43edd06e500a"));
- initialPresence->addPayload(vcard);
- CapsInfo::ref caps = boost::make_shared<CapsInfo>();
- caps->setNode("http://swift.im");
- caps->setVersion("p2UP0DrcVgKM6jJqYN/B92DKK0o=");
- initialPresence->addPayload(caps);
- channel->sendPresence(initialPresence);
-
- MUC::ref testling = createMUC(JID("test@rooms.swift.im"));
- testling->joinAs("Test");
- Presence::ref serverRespondsLocked = boost::make_shared<Presence>();
- serverRespondsLocked->setFrom(JID("test@rooms.swift.im/Test"));
- serverRespondsLocked->setTo(JID("test@swift.im/6913d576d55f0b67"));
- serverRespondsLocked->addPayload(vcard);
- serverRespondsLocked->addPayload(caps);
- serverRespondsLocked->setStatus("");
- MUCUserPayload::ref mucPayload(new MUCUserPayload());
- MUCItem myItem;
- myItem.affiliation = MUCOccupant::Owner;
- myItem.role = MUCOccupant::Moderator;
- mucPayload->addItem(myItem);
- mucPayload->addStatusCode(MUCUserPayload::StatusCode(201));
- serverRespondsLocked->addPayload(mucPayload);
- channel->onPresenceReceived(serverRespondsLocked);
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size()));
- IQ::ref iq = channel->getStanzaAtIndex<IQ>(2);
- CPPUNIT_ASSERT(iq);
- CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>());
- CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm());
- CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType());
- }
-
- void testNicknameChange() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- // Join as Rabbit
- testling->joinAs("Rabbit");
-
- // Rabbit joins
- Presence::ref rabbitJoins = boost::make_shared<Presence>();
- rabbitJoins->setTo("test@swift.im/6913d576d55f0b67");
- rabbitJoins->setFrom(testling->getJID().toString() + "/Rabbit");
- channel->onPresenceReceived(rabbitJoins);
- CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Rabbit"));
-
- // Alice joins
- Presence::ref aliceJoins = boost::make_shared<Presence>();
- aliceJoins->setTo("test@swift.im/6913d576d55f0b67");
- aliceJoins->setFrom(testling->getJID().toString() + "/Alice");
- channel->onPresenceReceived(aliceJoins);
- CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice"));
-
- // Change nick to Dodo
- testling->changeNickname("Dodo");
- Presence::ref stanza = channel->getStanzaAtIndex<Presence>(1);
- CPPUNIT_ASSERT(stanza);
- CPPUNIT_ASSERT_EQUAL(std::string("Dodo"), stanza->getTo().getResource());
-
- // Alice changes nick to Alice2
- stanza = boost::make_shared<Presence>();
- stanza->setFrom(JID("foo@bar.com/Alice"));
- stanza->setTo(JID(router->getJID()));
- stanza->setType(Presence::Unavailable);
- MUCUserPayload::ref mucPayload(new MUCUserPayload());
- MUCItem myItem;
- myItem.affiliation = MUCOccupant::Member;
- myItem.nick = "Alice2";
- myItem.role = MUCOccupant::Participant;
- mucPayload->addItem(myItem);
- mucPayload->addStatusCode(303);
- stanza->addPayload(mucPayload);
- channel->onPresenceReceived(stanza);
- CPPUNIT_ASSERT_EQUAL(1, nickChanges);
- CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Alice"));
- CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice2"));
-
- // We (Rabbit) change nick to Robot
- stanza = boost::make_shared<Presence>();
- stanza->setFrom(JID("foo@bar.com/Rabbit"));
- stanza->setTo(JID(router->getJID()));
- stanza->setType(Presence::Unavailable);
- mucPayload = MUCUserPayload::ref(new MUCUserPayload());
- myItem.affiliation = MUCOccupant::Member;
- myItem.nick = "Robot";
- myItem.role = MUCOccupant::Participant;
- mucPayload->addItem(myItem);
- mucPayload->addStatusCode(303);
- stanza->addPayload(mucPayload);
- channel->onPresenceReceived(stanza);
- CPPUNIT_ASSERT_EQUAL(2, nickChanges);
- CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Rabbit"));
- CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Robot"));
- }
-
- /*void testJoin_Success() {
- MUC::ref testling = createMUC(JID("foo@bar.com"));
- testling->onJoinFinished.connect(boost::bind(&MUCTest::handleJoinFinished, this, _1, _2));
- testling->joinAs("Alice");
- receivePresence(JID("foo@bar.com/Rabbit"), "Here");
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(joinResults.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), joinResults[0].nick);
- CPPUNIT_ASSERT(joinResults[0].error);
- }
-
- void testJoin_Fail() {
- //CPPUNIT_ASSERT(!mucRegistry->isMUC(JID("foo@bar.com")));
- }*/
-
- private:
- MUC::ref createMUC(const JID& jid) {
- MUC::ref muc = boost::make_shared<MUCImpl>(channel, router, presenceSender, jid, mucRegistry);
- muc->onOccupantNicknameChanged.connect(boost::bind(&MUCTest::handleOccupantNicknameChanged, this, _1, _2));
- return muc;
- }
-
- void handleJoinFinished(const std::string& nick, ErrorPayload::ref error) {
- JoinResult r;
- r.nick = nick;
- r.error = error;
- joinResults.push_back(r);
- }
-
- void receivePresence(const JID& jid, const std::string& status) {
- Presence::ref p = Presence::create(status);
- p->setFrom(jid);
- //MUCUserPayload::ref mucUserPayload = boost::make_shared<MUCUserPayload>();
- //mucUserPayload->addItem(item);
- //p->addPayload(mucUserPayload);
- channel->onPresenceReceived(p);
- }
-
- void handleOccupantNicknameChanged(const std::string&, const std::string&) {
- nickChanges++;
- }
-
- private:
- DummyStanzaChannel* channel;
- IQRouter* router;
- MUCRegistry* mucRegistry;
- StanzaChannelPresenceSender* stanzaChannelPresenceSender;
- DirectedPresenceSender* presenceSender;
- struct JoinResult {
- std::string nick;
- ErrorPayload::ref error;
- };
- std::vector<JoinResult> joinResults;
- int nickChanges;
+ CPPUNIT_TEST_SUITE(MUCTest);
+ CPPUNIT_TEST(testJoin);
+ CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess);
+ CPPUNIT_TEST(testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess);
+ CPPUNIT_TEST(testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess);
+ CPPUNIT_TEST(testCreateInstant);
+ CPPUNIT_TEST(testReplicateBug);
+ CPPUNIT_TEST(testNicknameChange);
+ /*CPPUNIT_TEST(testJoin_Success);
+ CPPUNIT_TEST(testJoin_Fail);*/
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ channel = new DummyStanzaChannel();
+ router = new IQRouter(channel);
+ mucRegistry = new MUCRegistry();
+ stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel);
+ presenceSender = new DirectedPresenceSender(stanzaChannelPresenceSender);
+ nickChanges = 0;
+ }
+
+ void tearDown() {
+ delete presenceSender;
+ delete stanzaChannelPresenceSender;
+ delete mucRegistry;
+ delete router;
+ delete channel;
+ }
+
+ void testJoin() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ testling->joinAs("Alice");
+
+ CPPUNIT_ASSERT(mucRegistry->isMUC(JID("foo@bar.com")));
+ Presence::ref p = channel->getStanzaAtIndex<Presence>(0);
+ CPPUNIT_ASSERT(p);
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
+ }
+
+ void testJoin_ChangePresenceDuringJoinDoesNotSendPresenceBeforeJoinSuccess() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ testling->joinAs("Alice");
+
+ presenceSender->sendPresence(Presence::create("Test"));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
+ }
+
+ void testJoin_ChangePresenceDuringJoinResendsPresenceAfterJoinSuccess() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ testling->joinAs("Alice");
+
+ presenceSender->sendPresence(Presence::create("Test"));
+ receivePresence(JID("foo@bar.com/Rabbit"), "Here");
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size()));
+ Presence::ref p = channel->getStanzaAtIndex<Presence>(2);
+ CPPUNIT_ASSERT(p);
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
+ CPPUNIT_ASSERT_EQUAL(std::string("Test"), p->getStatus());
+ }
+
+ void testJoin_NoPresenceChangeDuringJoinDoesNotResendAfterJoinSuccess() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ testling->joinAs("Alice");
+
+ receivePresence(JID("foo@bar.com/Rabbit"), "Here");
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ Presence::ref p = channel->getStanzaAtIndex<Presence>(0);
+ CPPUNIT_ASSERT(p);
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/Alice"), p->getTo());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), p->getStatus());
+ }
+
+ void testCreateInstant() {
+ MUC::ref testling = createMUC(JID("rabbithole@wonderland.lit"));
+ testling->joinAs("Alice");
+ Presence::ref serverRespondsLocked = boost::make_shared<Presence>();
+ serverRespondsLocked->setFrom(JID("rabbithole@wonderland.lit/Alice"));
+ MUCUserPayload::ref mucPayload(new MUCUserPayload());
+ MUCItem myItem;
+ myItem.affiliation = MUCOccupant::Owner;
+ myItem.role = MUCOccupant::Moderator;
+ mucPayload->addItem(myItem);
+ mucPayload->addStatusCode(MUCUserPayload::StatusCode(110));
+ mucPayload->addStatusCode(MUCUserPayload::StatusCode(201));
+ serverRespondsLocked->addPayload(mucPayload);
+ channel->onPresenceReceived(serverRespondsLocked);
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
+ IQ::ref iq = channel->getStanzaAtIndex<IQ>(1);
+ CPPUNIT_ASSERT(iq);
+ CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>());
+ CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm());
+ CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType());
+ }
+
+ void testReplicateBug() {
+ Presence::ref initialPresence = boost::make_shared<Presence>();
+ initialPresence->setStatus("");
+ VCard::ref vcard = boost::make_shared<VCard>();
+ vcard->setPhoto(createByteArray("15c30080ae98ec48be94bf0e191d43edd06e500a"));
+ initialPresence->addPayload(vcard);
+ CapsInfo::ref caps = boost::make_shared<CapsInfo>();
+ caps->setNode("http://swift.im");
+ caps->setVersion("p2UP0DrcVgKM6jJqYN/B92DKK0o=");
+ initialPresence->addPayload(caps);
+ channel->sendPresence(initialPresence);
+
+ MUC::ref testling = createMUC(JID("test@rooms.swift.im"));
+ testling->joinAs("Test");
+ Presence::ref serverRespondsLocked = boost::make_shared<Presence>();
+ serverRespondsLocked->setFrom(JID("test@rooms.swift.im/Test"));
+ serverRespondsLocked->setTo(JID("test@swift.im/6913d576d55f0b67"));
+ serverRespondsLocked->addPayload(vcard);
+ serverRespondsLocked->addPayload(caps);
+ serverRespondsLocked->setStatus("");
+ MUCUserPayload::ref mucPayload(new MUCUserPayload());
+ MUCItem myItem;
+ myItem.affiliation = MUCOccupant::Owner;
+ myItem.role = MUCOccupant::Moderator;
+ mucPayload->addItem(myItem);
+ mucPayload->addStatusCode(MUCUserPayload::StatusCode(201));
+ serverRespondsLocked->addPayload(mucPayload);
+ channel->onPresenceReceived(serverRespondsLocked);
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(channel->sentStanzas.size()));
+ IQ::ref iq = channel->getStanzaAtIndex<IQ>(2);
+ CPPUNIT_ASSERT(iq);
+ CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>());
+ CPPUNIT_ASSERT(iq->getPayload<MUCOwnerPayload>()->getForm());
+ CPPUNIT_ASSERT_EQUAL(Form::SubmitType, iq->getPayload<MUCOwnerPayload>()->getForm()->getType());
+ }
+
+ void testNicknameChange() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ // Join as Rabbit
+ testling->joinAs("Rabbit");
+
+ // Rabbit joins
+ Presence::ref rabbitJoins = boost::make_shared<Presence>();
+ rabbitJoins->setTo("test@swift.im/6913d576d55f0b67");
+ rabbitJoins->setFrom(testling->getJID().toString() + "/Rabbit");
+ channel->onPresenceReceived(rabbitJoins);
+ CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Rabbit"));
+
+ // Alice joins
+ Presence::ref aliceJoins = boost::make_shared<Presence>();
+ aliceJoins->setTo("test@swift.im/6913d576d55f0b67");
+ aliceJoins->setFrom(testling->getJID().toString() + "/Alice");
+ channel->onPresenceReceived(aliceJoins);
+ CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice"));
+
+ // Change nick to Dodo
+ testling->changeNickname("Dodo");
+ Presence::ref stanza = channel->getStanzaAtIndex<Presence>(1);
+ CPPUNIT_ASSERT(stanza);
+ CPPUNIT_ASSERT_EQUAL(std::string("Dodo"), stanza->getTo().getResource());
+
+ // Alice changes nick to Alice2
+ stanza = boost::make_shared<Presence>();
+ stanza->setFrom(JID("foo@bar.com/Alice"));
+ stanza->setTo(JID(router->getJID()));
+ stanza->setType(Presence::Unavailable);
+ MUCUserPayload::ref mucPayload(new MUCUserPayload());
+ MUCItem myItem;
+ myItem.affiliation = MUCOccupant::Member;
+ myItem.nick = "Alice2";
+ myItem.role = MUCOccupant::Participant;
+ mucPayload->addItem(myItem);
+ mucPayload->addStatusCode(303);
+ stanza->addPayload(mucPayload);
+ channel->onPresenceReceived(stanza);
+ CPPUNIT_ASSERT_EQUAL(1, nickChanges);
+ CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Alice"));
+ CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Alice2"));
+
+ // We (Rabbit) change nick to Robot
+ stanza = boost::make_shared<Presence>();
+ stanza->setFrom(JID("foo@bar.com/Rabbit"));
+ stanza->setTo(JID(router->getJID()));
+ stanza->setType(Presence::Unavailable);
+ mucPayload = MUCUserPayload::ref(new MUCUserPayload());
+ myItem.affiliation = MUCOccupant::Member;
+ myItem.nick = "Robot";
+ myItem.role = MUCOccupant::Participant;
+ mucPayload->addItem(myItem);
+ mucPayload->addStatusCode(303);
+ stanza->addPayload(mucPayload);
+ channel->onPresenceReceived(stanza);
+ CPPUNIT_ASSERT_EQUAL(2, nickChanges);
+ CPPUNIT_ASSERT_EQUAL(false, testling->hasOccupant("Rabbit"));
+ CPPUNIT_ASSERT_EQUAL(true, testling->hasOccupant("Robot"));
+ }
+
+ /*void testJoin_Success() {
+ MUC::ref testling = createMUC(JID("foo@bar.com"));
+ testling->onJoinFinished.connect(boost::bind(&MUCTest::handleJoinFinished, this, _1, _2));
+ testling->joinAs("Alice");
+ receivePresence(JID("foo@bar.com/Rabbit"), "Here");
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(joinResults.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), joinResults[0].nick);
+ CPPUNIT_ASSERT(joinResults[0].error);
+ }
+
+ void testJoin_Fail() {
+ //CPPUNIT_ASSERT(!mucRegistry->isMUC(JID("foo@bar.com")));
+ }*/
+
+ private:
+ MUC::ref createMUC(const JID& jid) {
+ MUC::ref muc = boost::make_shared<MUCImpl>(channel, router, presenceSender, jid, mucRegistry);
+ muc->onOccupantNicknameChanged.connect(boost::bind(&MUCTest::handleOccupantNicknameChanged, this, _1, _2));
+ return muc;
+ }
+
+ void handleJoinFinished(const std::string& nick, ErrorPayload::ref error) {
+ JoinResult r;
+ r.nick = nick;
+ r.error = error;
+ joinResults.push_back(r);
+ }
+
+ void receivePresence(const JID& jid, const std::string& status) {
+ Presence::ref p = Presence::create(status);
+ p->setFrom(jid);
+ //MUCUserPayload::ref mucUserPayload = boost::make_shared<MUCUserPayload>();
+ //mucUserPayload->addItem(item);
+ //p->addPayload(mucUserPayload);
+ channel->onPresenceReceived(p);
+ }
+
+ void handleOccupantNicknameChanged(const std::string&, const std::string&) {
+ nickChanges++;
+ }
+
+ private:
+ DummyStanzaChannel* channel;
+ IQRouter* router;
+ MUCRegistry* mucRegistry;
+ StanzaChannelPresenceSender* stanzaChannelPresenceSender;
+ DirectedPresenceSender* presenceSender;
+ struct JoinResult {
+ std::string nick;
+ ErrorPayload::ref error;
+ };
+ std::vector<JoinResult> joinResults;
+ int nickChanges;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MUCTest);
diff --git a/Swiften/MUC/UnitTest/MockMUC.cpp b/Swiften/MUC/UnitTest/MockMUC.cpp
index 6131183..93e7d0b 100644
--- a/Swiften/MUC/UnitTest/MockMUC.cpp
+++ b/Swiften/MUC/UnitTest/MockMUC.cpp
@@ -18,34 +18,34 @@ MockMUC::~MockMUC() {
void MockMUC::insertOccupant(const MUCOccupant& occupant)
{
- occupants_.insert(std::make_pair(occupant.getNick(), occupant));
- onOccupantJoined(occupant);
+ occupants_.insert(std::make_pair(occupant.getNick(), occupant));
+ onOccupantJoined(occupant);
}
const MUCOccupant& MockMUC::getOccupant(const std::string& nick) {
- return occupants_.find(nick)->second;
+ return occupants_.find(nick)->second;
}
bool MockMUC::hasOccupant(const std::string& nick) {
- return occupants_.find(nick) != occupants_.end();
+ return occupants_.find(nick) != occupants_.end();
}
void MockMUC::changeAffiliation(const JID &jid, MUCOccupant::Affiliation newAffilation) {
- std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource());
- if (i != occupants_.end()) {
- const MUCOccupant old = i->second;
- i->second = MUCOccupant(old.getNick(), old.getRole(), newAffilation);
- onOccupantAffiliationChanged(i->first, newAffilation, old.getAffiliation());
- }
+ std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource());
+ if (i != occupants_.end()) {
+ const MUCOccupant old = i->second;
+ i->second = MUCOccupant(old.getNick(), old.getRole(), newAffilation);
+ onOccupantAffiliationChanged(i->first, newAffilation, old.getAffiliation());
+ }
}
void MockMUC::changeOccupantRole(const JID &jid, MUCOccupant::Role newRole) {
- std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource());
- if (i != occupants_.end()) {
- const MUCOccupant old = i->second;
- i->second = MUCOccupant(old.getNick(), newRole, old.getAffiliation());
- onOccupantRoleChanged(i->first, i->second, old.getRole());
- }
+ std::map<std::string, MUCOccupant>::iterator i = occupants_.find(jid.getResource());
+ if (i != occupants_.end()) {
+ const MUCOccupant old = i->second;
+ i->second = MUCOccupant(old.getNick(), newRole, old.getAffiliation());
+ onOccupantRoleChanged(i->first, i->second, old.getRole());
+ }
}
}
diff --git a/Swiften/MUC/UnitTest/MockMUC.h b/Swiften/MUC/UnitTest/MockMUC.h
index c54e738..c61f8a9 100644
--- a/Swiften/MUC/UnitTest/MockMUC.h
+++ b/Swiften/MUC/UnitTest/MockMUC.h
@@ -25,74 +25,74 @@
#include <Swiften/MUC/MUCRegistry.h>
namespace Swift {
- class StanzaChannel;
- class IQRouter;
- class DirectedPresenceSender;
+ class StanzaChannel;
+ class IQRouter;
+ class DirectedPresenceSender;
- class SWIFTEN_API MockMUC : public MUC{
- public:
- typedef boost::shared_ptr<MockMUC> ref;
+ class SWIFTEN_API MockMUC : public MUC{
+ public:
+ typedef boost::shared_ptr<MockMUC> ref;
- public:
- MockMUC(const JID &muc);
- virtual ~MockMUC();
+ public:
+ MockMUC(const JID &muc);
+ virtual ~MockMUC();
- /**
- * Cause a user to appear to have entered the room. For testing only.
- */
- void insertOccupant(const MUCOccupant& occupant);
+ /**
+ * Cause a user to appear to have entered the room. For testing only.
+ */
+ void insertOccupant(const MUCOccupant& occupant);
- /**
- * Returns the (bare) JID of the MUC.
- */
- virtual JID getJID() const {
- return ownMUCJID.toBare();
- }
- /**
- * Returns if the room is unlocked and other people can join the room.
- * @return True if joinable by others; false otherwise.
- */
- virtual bool isUnlocked() const { return true; }
+ /**
+ * Returns the (bare) JID of the MUC.
+ */
+ virtual JID getJID() const {
+ return ownMUCJID.toBare();
+ }
+ /**
+ * Returns if the room is unlocked and other people can join the room.
+ * @return True if joinable by others; false otherwise.
+ */
+ virtual bool isUnlocked() const { return true; }
- virtual void joinAs(const std::string&) {}
- virtual void joinWithContextSince(const std::string&, const boost::posix_time::ptime&) {}
- /*virtual void queryRoomInfo(); */
- /*virtual void queryRoomItems(); */
- /*virtual std::string getCurrentNick() = 0; */
- virtual std::map<std::string, MUCOccupant> getOccupants() const { return occupants_; }
- virtual void changeNickname(const std::string&) { }
- virtual void part() {}
- /*virtual void handleIncomingMessage(Message::ref message) = 0; */
- /** Expose public so it can be called when e.g. user goes offline */
- virtual void handleUserLeft(LeavingType) {}
- /** Get occupant information*/
- virtual const MUCOccupant& getOccupant(const std::string&);
- virtual bool hasOccupant(const std::string&);
- virtual void kickOccupant(const JID&) {}
- virtual void changeOccupantRole(const JID&, MUCOccupant::Role);
- virtual void requestAffiliationList(MUCOccupant::Affiliation) {}
- virtual void changeAffiliation(const JID&, MUCOccupant::Affiliation);
- virtual void changeSubject(const std::string&) {}
- virtual void requestConfigurationForm() {}
- virtual void configureRoom(Form::ref) {}
- virtual void cancelConfigureRoom() {}
- virtual void destroyRoom() {}
- /** Send an invite for the person to join the MUC */
- virtual void invitePerson(const JID&, const std::string&, bool, bool) {}
- virtual void setCreateAsReservedIfNew() {}
- virtual void setPassword(const boost::optional<std::string>&) {}
+ virtual void joinAs(const std::string&) {}
+ virtual void joinWithContextSince(const std::string&, const boost::posix_time::ptime&) {}
+ /*virtual void queryRoomInfo(); */
+ /*virtual void queryRoomItems(); */
+ /*virtual std::string getCurrentNick() = 0; */
+ virtual std::map<std::string, MUCOccupant> getOccupants() const { return occupants_; }
+ virtual void changeNickname(const std::string&) { }
+ virtual void part() {}
+ /*virtual void handleIncomingMessage(Message::ref message) = 0; */
+ /** Expose public so it can be called when e.g. user goes offline */
+ virtual void handleUserLeft(LeavingType) {}
+ /** Get occupant information*/
+ virtual const MUCOccupant& getOccupant(const std::string&);
+ virtual bool hasOccupant(const std::string&);
+ virtual void kickOccupant(const JID&) {}
+ virtual void changeOccupantRole(const JID&, MUCOccupant::Role);
+ virtual void requestAffiliationList(MUCOccupant::Affiliation) {}
+ virtual void changeAffiliation(const JID&, MUCOccupant::Affiliation);
+ virtual void changeSubject(const std::string&) {}
+ virtual void requestConfigurationForm() {}
+ virtual void configureRoom(Form::ref) {}
+ virtual void cancelConfigureRoom() {}
+ virtual void destroyRoom() {}
+ /** Send an invite for the person to join the MUC */
+ virtual void invitePerson(const JID&, const std::string&, bool, bool) {}
+ virtual void setCreateAsReservedIfNew() {}
+ virtual void setPassword(const boost::optional<std::string>&) {}
- protected:
- virtual bool isFromMUC(const JID& j) const {
- return ownMUCJID.equals(j, JID::WithoutResource);
- }
+ protected:
+ virtual bool isFromMUC(const JID& j) const {
+ return ownMUCJID.equals(j, JID::WithoutResource);
+ }
- virtual const std::string& getOwnNick() const {
- return ownMUCJID.getResource();
- }
+ virtual const std::string& getOwnNick() const {
+ return ownMUCJID.getResource();
+ }
- private:
- JID ownMUCJID;
- std::map<std::string, MUCOccupant> occupants_;
- };
+ private:
+ JID ownMUCJID;
+ std::map<std::string, MUCOccupant> occupants_;
+ };
}
diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp
index b04609f..887a5f0 100644
--- a/Swiften/Network/BOSHConnection.cpp
+++ b/Swiften/Network/BOSHConnection.cpp
@@ -32,63 +32,63 @@
namespace Swift {
BOSHConnection::BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions)
- : boshURL_(boshURL),
- connector_(connector),
- parserFactory_(parserFactory),
- sid_(),
- waitingForStartResponse_(false),
- rid_(~0ULL),
- pending_(false),
- connectionReady_(false)
+ : boshURL_(boshURL),
+ connector_(connector),
+ parserFactory_(parserFactory),
+ sid_(),
+ waitingForStartResponse_(false),
+ rid_(~0ULL),
+ pending_(false),
+ connectionReady_(false)
{
- if (boshURL_.getScheme() == "https") {
- tlsLayer_ = boost::make_shared<TLSLayer>(tlsContextFactory, tlsOptions);
- // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer.
- // The dummyLayer_ will serve as the parent layer.
- dummyLayer_ = boost::make_shared<DummyStreamLayer>(tlsLayer_.get());
- }
+ if (boshURL_.getScheme() == "https") {
+ tlsLayer_ = boost::make_shared<TLSLayer>(tlsContextFactory, tlsOptions);
+ // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer.
+ // The dummyLayer_ will serve as the parent layer.
+ dummyLayer_ = boost::make_shared<DummyStreamLayer>(tlsLayer_.get());
+ }
}
BOSHConnection::~BOSHConnection() {
- cancelConnector();
- if (connection_) {
- connection_->onDataRead.disconnect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1));
- connection_->onDisconnected.disconnect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
- }
- BOSHConnection::disconnect();
+ cancelConnector();
+ if (connection_) {
+ connection_->onDataRead.disconnect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.disconnect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
+ }
+ BOSHConnection::disconnect();
}
void BOSHConnection::connect() {
- connector_->onConnectFinished.connect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1));
- connector_->start();
+ connector_->onConnectFinished.connect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1));
+ connector_->start();
}
void BOSHConnection::cancelConnector() {
- if (connector_) {
- connector_->onConnectFinished.disconnect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1));
- connector_->stop();
- connector_.reset();
- }
+ if (connector_) {
+ connector_->onConnectFinished.disconnect(boost::bind(&BOSHConnection::handleConnectFinished, shared_from_this(), _1));
+ connector_->stop();
+ connector_.reset();
+ }
}
void BOSHConnection::handleTLSConnected() {
- SWIFT_LOG(debug) << std::endl;
- onConnectFinished(false);
+ SWIFT_LOG(debug) << std::endl;
+ onConnectFinished(false);
}
void BOSHConnection::handleTLSApplicationDataRead(const SafeByteArray& data) {
- SWIFT_LOG(debug) << std::endl;
- handleDataRead(boost::make_shared<SafeByteArray>(data));
+ SWIFT_LOG(debug) << std::endl;
+ handleDataRead(boost::make_shared<SafeByteArray>(data));
}
void BOSHConnection::handleTLSNetowrkDataWriteRequest(const SafeByteArray& data) {
- SWIFT_LOG(debug) << std::endl;
- connection_->write(data);
+ SWIFT_LOG(debug) << std::endl;
+ connection_->write(data);
}
void BOSHConnection::handleRawDataRead(boost::shared_ptr<SafeByteArray> data) {
- SWIFT_LOG(debug) << std::endl;
- tlsLayer_->handleDataRead(*data.get());
+ SWIFT_LOG(debug) << std::endl;
+ tlsLayer_->handleDataRead(*data.get());
}
void BOSHConnection::handleTLSError(boost::shared_ptr<TLSError> /* error */) {
@@ -96,298 +96,298 @@ void BOSHConnection::handleTLSError(boost::shared_ptr<TLSError> /* error */) {
}
void BOSHConnection::writeData(const SafeByteArray& data) {
- if (tlsLayer_) {
- tlsLayer_->writeData(data);
- }
- else {
- connection_->write(data);
- }
+ if (tlsLayer_) {
+ tlsLayer_->writeData(data);
+ }
+ else {
+ connection_->write(data);
+ }
}
void BOSHConnection::disconnect() {
- if (connection_) {
- connection_->disconnect();
- sid_ = "";
- }
- else {
- /* handleDisconnected takes care of the connector_ as well */
- handleDisconnected(boost::optional<Connection::Error>());
- }
+ if (connection_) {
+ connection_->disconnect();
+ sid_ = "";
+ }
+ else {
+ /* handleDisconnected takes care of the connector_ as well */
+ handleDisconnected(boost::optional<Connection::Error>());
+ }
}
void BOSHConnection::restartStream() {
- write(createSafeByteArray(""), true, false);
+ write(createSafeByteArray(""), true, false);
}
bool BOSHConnection::setClientCertificate(CertificateWithKey::ref cert) {
- if (tlsLayer_) {
- SWIFT_LOG(debug) << "set client certificate" << std::endl;
- return tlsLayer_->setClientCertificate(cert);
- }
- else {
- return false;
- }
+ if (tlsLayer_) {
+ SWIFT_LOG(debug) << "set client certificate" << std::endl;
+ return tlsLayer_->setClientCertificate(cert);
+ }
+ else {
+ return false;
+ }
}
Certificate::ref BOSHConnection::getPeerCertificate() const {
- Certificate::ref peerCertificate;
- if (tlsLayer_) {
- peerCertificate = tlsLayer_->getPeerCertificate();
- }
- return peerCertificate;
+ Certificate::ref peerCertificate;
+ if (tlsLayer_) {
+ peerCertificate = tlsLayer_->getPeerCertificate();
+ }
+ return peerCertificate;
}
std::vector<Certificate::ref> BOSHConnection::getPeerCertificateChain() const {
- std::vector<Certificate::ref> peerCertificateChain;
- if (tlsLayer_) {
- peerCertificateChain = tlsLayer_->getPeerCertificateChain();
- }
- return peerCertificateChain;
+ std::vector<Certificate::ref> peerCertificateChain;
+ if (tlsLayer_) {
+ peerCertificateChain = tlsLayer_->getPeerCertificateChain();
+ }
+ return peerCertificateChain;
}
CertificateVerificationError::ref BOSHConnection::getPeerCertificateVerificationError() const {
- CertificateVerificationError::ref verificationError;
- if (tlsLayer_) {
- verificationError = tlsLayer_->getPeerCertificateVerificationError();
- }
- return verificationError;
+ CertificateVerificationError::ref verificationError;
+ if (tlsLayer_) {
+ verificationError = tlsLayer_->getPeerCertificateVerificationError();
+ }
+ return verificationError;
}
void BOSHConnection::terminateStream() {
- write(createSafeByteArray(""), false, true);
+ write(createSafeByteArray(""), false, true);
}
void BOSHConnection::write(const SafeByteArray& data) {
- write(data, false, false);
+ write(data, false, false);
}
std::pair<SafeByteArray, size_t> BOSHConnection::createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL) {
- size_t size;
- std::stringstream content;
- SafeByteArray contentTail = createSafeByteArray("</body>");
- std::stringstream header;
-
- content << "<body rid='" << rid << "' sid='" << sid << "'";
- if (streamRestart) {
- content << " xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'";
- }
- if (terminate) {
- content << " type='terminate'";
- }
- content << " xmlns='http://jabber.org/protocol/httpbind'>";
-
- SafeByteArray safeContent = createSafeByteArray(content.str());
- safeContent.insert(safeContent.end(), data.begin(), data.end());
- safeContent.insert(safeContent.end(), contentTail.begin(), contentTail.end());
-
- size = safeContent.size();
-
- header << "POST " << boshURL.getPath() << " HTTP/1.1\r\n"
- << "Host: " << boshURL.getHost();
- if (boshURL.getPort()) {
- header << ":" << *boshURL.getPort();
- }
- header << "\r\n"
- // << "Accept-Encoding: deflate\r\n"
- << "Content-Type: text/xml; charset=utf-8\r\n"
- << "Content-Length: " << size << "\r\n\r\n";
-
- SafeByteArray safeHeader = createSafeByteArray(header.str());
- safeHeader.insert(safeHeader.end(), safeContent.begin(), safeContent.end());
-
- return std::pair<SafeByteArray, size_t>(safeHeader, size);
+ size_t size;
+ std::stringstream content;
+ SafeByteArray contentTail = createSafeByteArray("</body>");
+ std::stringstream header;
+
+ content << "<body rid='" << rid << "' sid='" << sid << "'";
+ if (streamRestart) {
+ content << " xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'";
+ }
+ if (terminate) {
+ content << " type='terminate'";
+ }
+ content << " xmlns='http://jabber.org/protocol/httpbind'>";
+
+ SafeByteArray safeContent = createSafeByteArray(content.str());
+ safeContent.insert(safeContent.end(), data.begin(), data.end());
+ safeContent.insert(safeContent.end(), contentTail.begin(), contentTail.end());
+
+ size = safeContent.size();
+
+ header << "POST " << boshURL.getPath() << " HTTP/1.1\r\n"
+ << "Host: " << boshURL.getHost();
+ if (boshURL.getPort()) {
+ header << ":" << *boshURL.getPort();
+ }
+ header << "\r\n"
+ // << "Accept-Encoding: deflate\r\n"
+ << "Content-Type: text/xml; charset=utf-8\r\n"
+ << "Content-Length: " << size << "\r\n\r\n";
+
+ SafeByteArray safeHeader = createSafeByteArray(header.str());
+ safeHeader.insert(safeHeader.end(), safeContent.begin(), safeContent.end());
+
+ return std::pair<SafeByteArray, size_t>(safeHeader, size);
}
void BOSHConnection::write(const SafeByteArray& data, bool streamRestart, bool terminate) {
- assert(connectionReady_);
- assert(!sid_.empty());
+ assert(connectionReady_);
+ assert(!sid_.empty());
- SafeByteArray safeHeader = createHTTPRequest(data, streamRestart, terminate, rid_, sid_, boshURL_).first;
+ SafeByteArray safeHeader = createHTTPRequest(data, streamRestart, terminate, rid_, sid_, boshURL_).first;
- onBOSHDataWritten(safeHeader);
- writeData(safeHeader);
- pending_ = true;
+ onBOSHDataWritten(safeHeader);
+ writeData(safeHeader);
+ pending_ = true;
- SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl;
+ SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl;
}
void BOSHConnection::handleConnectFinished(Connection::ref connection) {
- cancelConnector();
- connectionReady_ = !!connection;
- if (connectionReady_) {
- connection_ = connection;
- if (tlsLayer_) {
- connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleRawDataRead, shared_from_this(), _1));
- connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
-
- tlsLayer_->getContext()->onDataForNetwork.connect(boost::bind(&BOSHConnection::handleTLSNetowrkDataWriteRequest, shared_from_this(), _1));
- tlsLayer_->getContext()->onDataForApplication.connect(boost::bind(&BOSHConnection::handleTLSApplicationDataRead, shared_from_this(), _1));
- tlsLayer_->onConnected.connect(boost::bind(&BOSHConnection::handleTLSConnected, shared_from_this()));
- tlsLayer_->onError.connect(boost::bind(&BOSHConnection::handleTLSError, shared_from_this(), _1));
- tlsLayer_->connect();
- }
- else {
- connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1));
- connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
- }
- }
-
- if (!connectionReady_ || !tlsLayer_) {
- onConnectFinished(!connectionReady_);
- }
+ cancelConnector();
+ connectionReady_ = !!connection;
+ if (connectionReady_) {
+ connection_ = connection;
+ if (tlsLayer_) {
+ connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleRawDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
+
+ tlsLayer_->getContext()->onDataForNetwork.connect(boost::bind(&BOSHConnection::handleTLSNetowrkDataWriteRequest, shared_from_this(), _1));
+ tlsLayer_->getContext()->onDataForApplication.connect(boost::bind(&BOSHConnection::handleTLSApplicationDataRead, shared_from_this(), _1));
+ tlsLayer_->onConnected.connect(boost::bind(&BOSHConnection::handleTLSConnected, shared_from_this()));
+ tlsLayer_->onError.connect(boost::bind(&BOSHConnection::handleTLSError, shared_from_this(), _1));
+ tlsLayer_->connect();
+ }
+ else {
+ connection_->onDataRead.connect(boost::bind(&BOSHConnection::handleDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.connect(boost::bind(&BOSHConnection::handleDisconnected, shared_from_this(), _1));
+ }
+ }
+
+ if (!connectionReady_ || !tlsLayer_) {
+ onConnectFinished(!connectionReady_);
+ }
}
void BOSHConnection::startStream(const std::string& to, unsigned long long rid) {
- assert(connectionReady_);
- // Session Creation Request
- std::stringstream content;
- std::stringstream header;
-
- content << "<body content='text/xml; charset=utf-8'"
- << " hold='1'"
- << " to='" << to << "'"
- << " rid='" << rid << "'"
- << " ver='1.6'"
- << " wait='60'" /* FIXME: we probably want this configurable*/
- // << " ack='0'" FIXME: support acks
- << " xml:lang='en'"
- << " xmlns:xmpp='urn:xmpp:bosh'"
- << " xmpp:version='1.0'"
- << " xmlns='http://jabber.org/protocol/httpbind' />";
-
- std::string contentString = content.str();
-
- header << "POST " << boshURL_.getPath() << " HTTP/1.1\r\n"
- << "Host: " << boshURL_.getHost();
- if (boshURL_.getPort()) {
- header << ":" << *boshURL_.getPort();
- }
- header << "\r\n"
- // << "Accept-Encoding: deflate\r\n"
- << "Content-Type: text/xml; charset=utf-8\r\n"
- << "Content-Length: " << contentString.size() << "\r\n\r\n"
- << contentString;
-
- waitingForStartResponse_ = true;
- SafeByteArray safeHeader = createSafeByteArray(header.str());
- onBOSHDataWritten(safeHeader);
- writeData(safeHeader);
- SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl;
+ assert(connectionReady_);
+ // Session Creation Request
+ std::stringstream content;
+ std::stringstream header;
+
+ content << "<body content='text/xml; charset=utf-8'"
+ << " hold='1'"
+ << " to='" << to << "'"
+ << " rid='" << rid << "'"
+ << " ver='1.6'"
+ << " wait='60'" /* FIXME: we probably want this configurable*/
+ // << " ack='0'" FIXME: support acks
+ << " xml:lang='en'"
+ << " xmlns:xmpp='urn:xmpp:bosh'"
+ << " xmpp:version='1.0'"
+ << " xmlns='http://jabber.org/protocol/httpbind' />";
+
+ std::string contentString = content.str();
+
+ header << "POST " << boshURL_.getPath() << " HTTP/1.1\r\n"
+ << "Host: " << boshURL_.getHost();
+ if (boshURL_.getPort()) {
+ header << ":" << *boshURL_.getPort();
+ }
+ header << "\r\n"
+ // << "Accept-Encoding: deflate\r\n"
+ << "Content-Type: text/xml; charset=utf-8\r\n"
+ << "Content-Length: " << contentString.size() << "\r\n\r\n"
+ << contentString;
+
+ waitingForStartResponse_ = true;
+ SafeByteArray safeHeader = createSafeByteArray(header.str());
+ onBOSHDataWritten(safeHeader);
+ writeData(safeHeader);
+ SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl;
}
void BOSHConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- onBOSHDataRead(*data);
- buffer_ = concat(buffer_, *data);
- std::string response = safeByteArrayToString(buffer_);
- if (response.find("\r\n\r\n") == std::string::npos) {
- onBOSHDataRead(createSafeByteArray("[[Previous read incomplete, pending]]"));
- return;
- }
-
- std::string httpCode = response.substr(response.find(" ") + 1, 3);
- if (httpCode != "200") {
- onHTTPError(httpCode);
- return;
- }
-
- BOSHBodyExtractor parser(parserFactory_, createByteArray(response.substr(response.find("\r\n\r\n") + 4)));
- if (parser.getBody()) {
- if (parser.getBody()->attributes.getAttribute("type") == "terminate") {
- BOSHError::Type errorType = parseTerminationCondition(parser.getBody()->attributes.getAttribute("condition"));
- onSessionTerminated(errorType == BOSHError::NoError ? boost::shared_ptr<BOSHError>() : boost::make_shared<BOSHError>(errorType));
- }
- buffer_.clear();
- if (waitingForStartResponse_) {
- waitingForStartResponse_ = false;
- sid_ = parser.getBody()->attributes.getAttribute("sid");
- std::string requestsString = parser.getBody()->attributes.getAttribute("requests");
- size_t requests = 2;
- if (!requestsString.empty()) {
- try {
- requests = boost::lexical_cast<size_t>(requestsString);
- }
- catch (const boost::bad_lexical_cast&) {
- }
- }
- onSessionStarted(sid_, requests);
- }
- SafeByteArray payload = createSafeByteArray(parser.getBody()->content);
- /* Say we're good to go again, so don't add anything after here in the method */
- pending_ = false;
- onXMPPDataRead(payload);
- }
+ onBOSHDataRead(*data);
+ buffer_ = concat(buffer_, *data);
+ std::string response = safeByteArrayToString(buffer_);
+ if (response.find("\r\n\r\n") == std::string::npos) {
+ onBOSHDataRead(createSafeByteArray("[[Previous read incomplete, pending]]"));
+ return;
+ }
+
+ std::string httpCode = response.substr(response.find(" ") + 1, 3);
+ if (httpCode != "200") {
+ onHTTPError(httpCode);
+ return;
+ }
+
+ BOSHBodyExtractor parser(parserFactory_, createByteArray(response.substr(response.find("\r\n\r\n") + 4)));
+ if (parser.getBody()) {
+ if (parser.getBody()->attributes.getAttribute("type") == "terminate") {
+ BOSHError::Type errorType = parseTerminationCondition(parser.getBody()->attributes.getAttribute("condition"));
+ onSessionTerminated(errorType == BOSHError::NoError ? boost::shared_ptr<BOSHError>() : boost::make_shared<BOSHError>(errorType));
+ }
+ buffer_.clear();
+ if (waitingForStartResponse_) {
+ waitingForStartResponse_ = false;
+ sid_ = parser.getBody()->attributes.getAttribute("sid");
+ std::string requestsString = parser.getBody()->attributes.getAttribute("requests");
+ size_t requests = 2;
+ if (!requestsString.empty()) {
+ try {
+ requests = boost::lexical_cast<size_t>(requestsString);
+ }
+ catch (const boost::bad_lexical_cast&) {
+ }
+ }
+ onSessionStarted(sid_, requests);
+ }
+ SafeByteArray payload = createSafeByteArray(parser.getBody()->content);
+ /* Say we're good to go again, so don't add anything after here in the method */
+ pending_ = false;
+ onXMPPDataRead(payload);
+ }
}
BOSHError::Type BOSHConnection::parseTerminationCondition(const std::string& text) {
- BOSHError::Type condition = BOSHError::UndefinedCondition;
- if (text == "bad-request") {
- condition = BOSHError::BadRequest;
- }
- else if (text == "host-gone") {
- condition = BOSHError::HostGone;
- }
- else if (text == "host-unknown") {
- condition = BOSHError::HostUnknown;
- }
- else if (text == "improper-addressing") {
- condition = BOSHError::ImproperAddressing;
- }
- else if (text == "internal-server-error") {
- condition = BOSHError::InternalServerError;
- }
- else if (text == "item-not-found") {
- condition = BOSHError::ItemNotFound;
- }
- else if (text == "other-request") {
- condition = BOSHError::OtherRequest;
- }
- else if (text == "policy-violation") {
- condition = BOSHError::PolicyViolation;
- }
- else if (text == "remote-connection-failed") {
- condition = BOSHError::RemoteConnectionFailed;
- }
- else if (text == "remote-stream-error") {
- condition = BOSHError::RemoteStreamError;
- }
- else if (text == "see-other-uri") {
- condition = BOSHError::SeeOtherURI;
- }
- else if (text == "system-shutdown") {
- condition = BOSHError::SystemShutdown;
- }
- else if (text == "") {
- condition = BOSHError::NoError;
- }
- return condition;
+ BOSHError::Type condition = BOSHError::UndefinedCondition;
+ if (text == "bad-request") {
+ condition = BOSHError::BadRequest;
+ }
+ else if (text == "host-gone") {
+ condition = BOSHError::HostGone;
+ }
+ else if (text == "host-unknown") {
+ condition = BOSHError::HostUnknown;
+ }
+ else if (text == "improper-addressing") {
+ condition = BOSHError::ImproperAddressing;
+ }
+ else if (text == "internal-server-error") {
+ condition = BOSHError::InternalServerError;
+ }
+ else if (text == "item-not-found") {
+ condition = BOSHError::ItemNotFound;
+ }
+ else if (text == "other-request") {
+ condition = BOSHError::OtherRequest;
+ }
+ else if (text == "policy-violation") {
+ condition = BOSHError::PolicyViolation;
+ }
+ else if (text == "remote-connection-failed") {
+ condition = BOSHError::RemoteConnectionFailed;
+ }
+ else if (text == "remote-stream-error") {
+ condition = BOSHError::RemoteStreamError;
+ }
+ else if (text == "see-other-uri") {
+ condition = BOSHError::SeeOtherURI;
+ }
+ else if (text == "system-shutdown") {
+ condition = BOSHError::SystemShutdown;
+ }
+ else if (text == "") {
+ condition = BOSHError::NoError;
+ }
+ return condition;
}
const std::string& BOSHConnection::getSID() {
- return sid_;
+ return sid_;
}
void BOSHConnection::setRID(unsigned long long rid) {
- rid_ = rid;
+ rid_ = rid;
}
void BOSHConnection::setSID(const std::string& sid) {
- sid_ = sid;
+ sid_ = sid;
}
void BOSHConnection::handleDisconnected(const boost::optional<Connection::Error>& error) {
- cancelConnector();
- onDisconnected(error ? true : false);
- sid_ = "";
- connectionReady_ = false;
+ cancelConnector();
+ onDisconnected(error ? true : false);
+ sid_ = "";
+ connectionReady_ = false;
}
bool BOSHConnection::isReadyToSend() {
- /* Without pipelining you need to not send more without first receiving the response */
- /* With pipelining you can. Assuming we can't, here */
- return connectionReady_ && !pending_ && !waitingForStartResponse_ && !sid_.empty();
+ /* Without pipelining you need to not send more without first receiving the response */
+ /* With pipelining you can. Assuming we can't, here */
+ return connectionReady_ && !pending_ && !waitingForStartResponse_ && !sid_.empty();
}
}
diff --git a/Swiften/Network/BOSHConnection.h b/Swiften/Network/BOSHConnection.h
index da43e71..dc0f3a5 100644
--- a/Swiften/Network/BOSHConnection.h
+++ b/Swiften/Network/BOSHConnection.h
@@ -26,101 +26,101 @@
#include <Swiften/TLS/TLSError.h>
namespace boost {
- class thread;
- namespace system {
- class error_code;
- }
+ class thread;
+ namespace system {
+ class error_code;
+ }
}
class BOSHConnectionTest;
namespace Swift {
- class XMLParserFactory;
- class TLSContextFactory;
- class TLSLayer;
- struct TLSOptions;
- class HighLayer;
-
- class SWIFTEN_API BOSHError : public SessionStream::SessionStreamError {
- public:
- enum Type {
- BadRequest, HostGone, HostUnknown, ImproperAddressing,
- InternalServerError, ItemNotFound, OtherRequest, PolicyViolation,
- RemoteConnectionFailed, RemoteStreamError, SeeOtherURI, SystemShutdown, UndefinedCondition,
- NoError};
-
- BOSHError(Type type) : SessionStream::SessionStreamError(SessionStream::SessionStreamError::ConnectionReadError), type(type) {}
- Type getType() {return type;}
- typedef boost::shared_ptr<BOSHError> ref;
-
- private:
- Type type;
- };
-
- class SWIFTEN_API BOSHConnection : public boost::enable_shared_from_this<BOSHConnection> {
- public:
- typedef boost::shared_ptr<BOSHConnection> ref;
- static ref create(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) {
- return ref(new BOSHConnection(boshURL, connector, parserFactory, tlsContextFactory, tlsOptions));
- }
- virtual ~BOSHConnection();
- virtual void connect();
- virtual void disconnect();
- virtual void write(const SafeByteArray& data);
-
- const std::string& getSID();
- void setRID(unsigned long long rid);
- void setSID(const std::string& sid);
- void startStream(const std::string& to, unsigned long long rid);
- void terminateStream();
- bool isReadyToSend();
- void restartStream();
-
- bool setClientCertificate(CertificateWithKey::ref cert);
- Certificate::ref getPeerCertificate() const;
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- CertificateVerificationError::ref getPeerCertificateVerificationError() const;
-
- boost::signal<void (bool /* error */)> onConnectFinished;
- boost::signal<void (bool /* error */)> onDisconnected;
- boost::signal<void (BOSHError::ref)> onSessionTerminated;
- boost::signal<void (const std::string& /*sid*/, size_t /*requests*/)> onSessionStarted;
- boost::signal<void (const SafeByteArray&)> onXMPPDataRead;
- boost::signal<void (const SafeByteArray&)> onBOSHDataRead;
- boost::signal<void (const SafeByteArray&)> onBOSHDataWritten;
- boost::signal<void (const std::string&)> onHTTPError;
-
- private:
- friend class ::BOSHConnectionTest;
-
- BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions);
-
- static std::pair<SafeByteArray, size_t> createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL);
- void handleConnectFinished(Connection::ref);
- void handleDataRead(boost::shared_ptr<SafeByteArray> data);
- void handleDisconnected(const boost::optional<Connection::Error>& error);
- void write(const SafeByteArray& data, bool streamRestart, bool terminate); /* FIXME: refactor */
- BOSHError::Type parseTerminationCondition(const std::string& text);
- void cancelConnector();
-
- void handleTLSConnected();
- void handleTLSApplicationDataRead(const SafeByteArray& data);
- void handleTLSNetowrkDataWriteRequest(const SafeByteArray& data);
- void handleRawDataRead(boost::shared_ptr<SafeByteArray> data);
- void handleTLSError(boost::shared_ptr<TLSError> error);
- void writeData(const SafeByteArray& data);
-
- URL boshURL_;
- Connector::ref connector_;
- XMLParserFactory* parserFactory_;
- boost::shared_ptr<Connection> connection_;
- boost::shared_ptr<HighLayer> dummyLayer_;
- boost::shared_ptr<TLSLayer> tlsLayer_;
- std::string sid_;
- bool waitingForStartResponse_;
- unsigned long long rid_;
- SafeByteArray buffer_;
- bool pending_;
- bool connectionReady_;
- };
+ class XMLParserFactory;
+ class TLSContextFactory;
+ class TLSLayer;
+ struct TLSOptions;
+ class HighLayer;
+
+ class SWIFTEN_API BOSHError : public SessionStream::SessionStreamError {
+ public:
+ enum Type {
+ BadRequest, HostGone, HostUnknown, ImproperAddressing,
+ InternalServerError, ItemNotFound, OtherRequest, PolicyViolation,
+ RemoteConnectionFailed, RemoteStreamError, SeeOtherURI, SystemShutdown, UndefinedCondition,
+ NoError};
+
+ BOSHError(Type type) : SessionStream::SessionStreamError(SessionStream::SessionStreamError::ConnectionReadError), type(type) {}
+ Type getType() {return type;}
+ typedef boost::shared_ptr<BOSHError> ref;
+
+ private:
+ Type type;
+ };
+
+ class SWIFTEN_API BOSHConnection : public boost::enable_shared_from_this<BOSHConnection> {
+ public:
+ typedef boost::shared_ptr<BOSHConnection> ref;
+ static ref create(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) {
+ return ref(new BOSHConnection(boshURL, connector, parserFactory, tlsContextFactory, tlsOptions));
+ }
+ virtual ~BOSHConnection();
+ virtual void connect();
+ virtual void disconnect();
+ virtual void write(const SafeByteArray& data);
+
+ const std::string& getSID();
+ void setRID(unsigned long long rid);
+ void setSID(const std::string& sid);
+ void startStream(const std::string& to, unsigned long long rid);
+ void terminateStream();
+ bool isReadyToSend();
+ void restartStream();
+
+ bool setClientCertificate(CertificateWithKey::ref cert);
+ Certificate::ref getPeerCertificate() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const;
+ CertificateVerificationError::ref getPeerCertificateVerificationError() const;
+
+ boost::signal<void (bool /* error */)> onConnectFinished;
+ boost::signal<void (bool /* error */)> onDisconnected;
+ boost::signal<void (BOSHError::ref)> onSessionTerminated;
+ boost::signal<void (const std::string& /*sid*/, size_t /*requests*/)> onSessionStarted;
+ boost::signal<void (const SafeByteArray&)> onXMPPDataRead;
+ boost::signal<void (const SafeByteArray&)> onBOSHDataRead;
+ boost::signal<void (const SafeByteArray&)> onBOSHDataWritten;
+ boost::signal<void (const std::string&)> onHTTPError;
+
+ private:
+ friend class ::BOSHConnectionTest;
+
+ BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions);
+
+ static std::pair<SafeByteArray, size_t> createHTTPRequest(const SafeByteArray& data, bool streamRestart, bool terminate, unsigned long long rid, const std::string& sid, const URL& boshURL);
+ void handleConnectFinished(Connection::ref);
+ void handleDataRead(boost::shared_ptr<SafeByteArray> data);
+ void handleDisconnected(const boost::optional<Connection::Error>& error);
+ void write(const SafeByteArray& data, bool streamRestart, bool terminate); /* FIXME: refactor */
+ BOSHError::Type parseTerminationCondition(const std::string& text);
+ void cancelConnector();
+
+ void handleTLSConnected();
+ void handleTLSApplicationDataRead(const SafeByteArray& data);
+ void handleTLSNetowrkDataWriteRequest(const SafeByteArray& data);
+ void handleRawDataRead(boost::shared_ptr<SafeByteArray> data);
+ void handleTLSError(boost::shared_ptr<TLSError> error);
+ void writeData(const SafeByteArray& data);
+
+ URL boshURL_;
+ Connector::ref connector_;
+ XMLParserFactory* parserFactory_;
+ boost::shared_ptr<Connection> connection_;
+ boost::shared_ptr<HighLayer> dummyLayer_;
+ boost::shared_ptr<TLSLayer> tlsLayer_;
+ std::string sid_;
+ bool waitingForStartResponse_;
+ unsigned long long rid_;
+ SafeByteArray buffer_;
+ bool pending_;
+ bool connectionReady_;
+ };
}
diff --git a/Swiften/Network/BOSHConnectionPool.cpp b/Swiften/Network/BOSHConnectionPool.cpp
index 57c1bcc..7d5c164 100644
--- a/Swiften/Network/BOSHConnectionPool.cpp
+++ b/Swiften/Network/BOSHConnectionPool.cpp
@@ -18,284 +18,284 @@
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, boost::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);
+ 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) {
- if (connection) {
- destroyConnection(connection);
- connection->disconnect();
- }
- }
- foreach (ConnectionFactory* factory, myConnectionFactories) {
- delete factory;
- }
- delete resolver;
+ /* 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) {
+ if (connection) {
+ destroyConnection(connection);
+ connection->disconnect();
+ }
+ }
+ foreach (ConnectionFactory* factory, myConnectionFactories) {
+ delete factory;
+ }
+ delete resolver;
}
void BOSHConnectionPool::write(const SafeByteArray& data) {
- dataQueue.push_back(data);
- tryToSendQueuedData();
+ dataQueue.push_back(data);
+ tryToSendQueuedData();
}
void BOSHConnectionPool::handleDataRead(const SafeByteArray& data) {
- onXMPPDataRead(data);
- tryToSendQueuedData(); /* Will rebalance the connections */
+ 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;
- }
+ BOSHConnection::ref connection = getSuitableConnection();
+ if (connection) {
+ pendingRestart = false;
+ rid++;
+ connection->setRID(rid);
+ connection->restartStream();
+ restartCount++;
+ }
+ else {
+ pendingRestart = true;
+ }
}
void BOSHConnectionPool::setTLSCertificate(CertificateWithKey::ref certWithKey) {
- clientCertificate = certWithKey;
+ clientCertificate = certWithKey;
}
bool BOSHConnectionPool::isTLSEncrypted() const {
- return !pinnedCertificateChain_.empty();
+ return !pinnedCertificateChain_.empty();
}
Certificate::ref BOSHConnectionPool::getPeerCertificate() const {
- Certificate::ref peerCertificate;
- if (!pinnedCertificateChain_.empty()) {
- peerCertificate = pinnedCertificateChain_[0];
- }
- return peerCertificate;
+ Certificate::ref peerCertificate;
+ if (!pinnedCertificateChain_.empty()) {
+ peerCertificate = pinnedCertificateChain_[0];
+ }
+ return peerCertificate;
}
std::vector<Certificate::ref> BOSHConnectionPool::getPeerCertificateChain() const {
- return pinnedCertificateChain_;
+ return pinnedCertificateChain_;
}
boost::shared_ptr<CertificateVerificationError> BOSHConnectionPool::getPeerCertificateVerificationError() const {
- return lastVerificationError_;
+ return lastVerificationError_;
}
void BOSHConnectionPool::writeFooter() {
- pendingTerminate = true;
- tryToSendQueuedData();
+ pendingTerminate = true;
+ tryToSendQueuedData();
}
void BOSHConnectionPool::open() {
- createConnection();
+ createConnection();
}
void BOSHConnectionPool::close() {
- if (!sid.empty()) {
- writeFooter();
- }
- else {
- pendingTerminate = true;
- std::vector<BOSHConnection::ref> connectionCopies = connections;
- foreach (BOSHConnection::ref connection, connectionCopies) {
- if (connection) {
- connection->disconnect();
- }
- }
- }
+ if (!sid.empty()) {
+ writeFooter();
+ }
+ else {
+ pendingTerminate = true;
+ std::vector<BOSHConnection::ref> connectionCopies = connections;
+ foreach (BOSHConnection::ref connection, connectionCopies) {
+ if (connection) {
+ connection->disconnect();
+ }
+ }
+ }
}
void BOSHConnectionPool::handleSessionStarted(const std::string& sessionID, size_t requests) {
- sid = sessionID;
- requestLimit = requests;
- onSessionStarted();
+ sid = sessionID;
+ requestLimit = requests;
+ onSessionStarted();
}
void BOSHConnectionPool::handleConnectFinished(bool error, BOSHConnection::ref connection) {
- if (error) {
- onSessionTerminated(boost::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();
- }
+ if (error) {
+ onSessionTerminated(boost::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) {
- 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;
+ BOSHConnection::ref suitableConnection;
+ foreach (BOSHConnection::ref 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) {
- 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) {
- 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. */
- }
- }
- }
- }
+ 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) {
+ 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) {
+ 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*/) {
- handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition));
+ handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition));
}
void BOSHConnectionPool::handleConnectionDisconnected(bool/* error*/, BOSHConnection::ref connection) {
- destroyConnection(connection);
- if (pendingTerminate && sid.empty() && connections.empty()) {
- handleSessionTerminated(BOSHError::ref());
- }
- //else if (error) {
- // handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition));
- //}
- else {
- /* We might have just freed up a connection slot to send with */
- tryToSendQueuedData();
- }
+ destroyConnection(connection);
+ if (pendingTerminate && sid.empty() && connections.empty()) {
+ handleSessionTerminated(BOSHError::ref());
+ }
+ //else if (error) {
+ // handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition));
+ //}
+ else {
+ /* We might have just freed up a connection slot to send with */
+ tryToSendQueuedData();
+ }
}
boost::shared_ptr<BOSHConnection> BOSHConnectionPool::createConnection() {
- Connector::ref connector = Connector::create(boshURL.getHost(), URL::getPortOrDefaultPort(boshURL), boost::optional<std::string>(), resolver, connectionFactory, timerFactory);
- BOSHConnection::ref connection = BOSHConnection::create(boshURL, connector, xmlParserFactory, tlsContextFactory_, tlsOptions_);
- connection->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1));
- connection->onSessionStarted.connect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2));
- connection->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1));
- connection->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1));
- connection->onDisconnected.connect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection));
- connection->onConnectFinished.connect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection));
- connection->onSessionTerminated.connect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1));
- connection->onHTTPError.connect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1));
-
- if (boshURL.getScheme() == "https") {
- bool success = connection->setClientCertificate(clientCertificate);
- SWIFT_LOG(debug) << "setClientCertificate, success: " << success << std::endl;
- }
-
- connection->connect();
- connections.push_back(connection);
- return connection;
+ Connector::ref connector = Connector::create(boshURL.getHost(), URL::getPortOrDefaultPort(boshURL), boost::optional<std::string>(), resolver, connectionFactory, timerFactory);
+ BOSHConnection::ref connection = BOSHConnection::create(boshURL, connector, xmlParserFactory, tlsContextFactory_, tlsOptions_);
+ connection->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1));
+ connection->onSessionStarted.connect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2));
+ connection->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1));
+ connection->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1));
+ connection->onDisconnected.connect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection));
+ connection->onConnectFinished.connect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection));
+ connection->onSessionTerminated.connect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1));
+ connection->onHTTPError.connect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1));
+
+ if (boshURL.getScheme() == "https") {
+ bool success = connection->setClientCertificate(clientCertificate);
+ SWIFT_LOG(debug) << "setClientCertificate, success: " << success << std::endl;
+ }
+
+ connection->connect();
+ connections.push_back(connection);
+ return connection;
}
void BOSHConnectionPool::destroyConnection(boost::shared_ptr<BOSHConnection> connection) {
- connections.erase(std::remove(connections.begin(), connections.end(), connection), connections.end());
- connection->onXMPPDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1));
- connection->onSessionStarted.disconnect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2));
- connection->onBOSHDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1));
- connection->onBOSHDataWritten.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1));
- connection->onDisconnected.disconnect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection));
- connection->onConnectFinished.disconnect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection));
- connection->onSessionTerminated.disconnect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1));
- connection->onHTTPError.disconnect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1));
+ connections.erase(std::remove(connections.begin(), connections.end(), connection), connections.end());
+ connection->onXMPPDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleDataRead, this, _1));
+ connection->onSessionStarted.disconnect(boost::bind(&BOSHConnectionPool::handleSessionStarted, this, _1, _2));
+ connection->onBOSHDataRead.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataRead, this, _1));
+ connection->onBOSHDataWritten.disconnect(boost::bind(&BOSHConnectionPool::handleBOSHDataWritten, this, _1));
+ connection->onDisconnected.disconnect(boost::bind(&BOSHConnectionPool::handleConnectionDisconnected, this, _1, connection));
+ connection->onConnectFinished.disconnect(boost::bind(&BOSHConnectionPool::handleConnectFinished, this, _1, connection));
+ connection->onSessionTerminated.disconnect(boost::bind(&BOSHConnectionPool::handleSessionTerminated, this, _1));
+ connection->onHTTPError.disconnect(boost::bind(&BOSHConnectionPool::handleHTTPError, this, _1));
}
void BOSHConnectionPool::handleSessionTerminated(BOSHError::ref error) {
- onSessionTerminated(error);
+ onSessionTerminated(error);
}
void BOSHConnectionPool::handleBOSHDataRead(const SafeByteArray& data) {
- onBOSHDataRead(data);
+ onBOSHDataRead(data);
}
void BOSHConnectionPool::handleBOSHDataWritten(const SafeByteArray& data) {
- onBOSHDataWritten(data);
+ onBOSHDataWritten(data);
}
}
diff --git a/Swiften/Network/BOSHConnectionPool.h b/Swiften/Network/BOSHConnectionPool.h
index df116ff..5088be6 100644
--- a/Swiften/Network/BOSHConnectionPool.h
+++ b/Swiften/Network/BOSHConnectionPool.h
@@ -16,73 +16,73 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class CachingDomainNameResolver;
- class EventLoop;
- class HTTPConnectProxiedConnectionFactory;
- class HTTPTrafficFilter;
- class TLSContextFactory;
- class CachingDomainNameResolver;
- class EventLoop;
+ class CachingDomainNameResolver;
+ class EventLoop;
+ class HTTPConnectProxiedConnectionFactory;
+ class HTTPTrafficFilter;
+ class TLSContextFactory;
+ class CachingDomainNameResolver;
+ class EventLoop;
- class SWIFTEN_API BOSHConnectionPool : public boost::bsignals::trackable {
- public:
- BOSHConnectionPool(const URL& boshURL, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, 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, boost::shared_ptr<HTTPTrafficFilter> trafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
- ~BOSHConnectionPool();
+ class SWIFTEN_API BOSHConnectionPool : public boost::bsignals::trackable {
+ public:
+ BOSHConnectionPool(const URL& boshURL, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, 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, boost::shared_ptr<HTTPTrafficFilter> trafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
+ ~BOSHConnectionPool();
- void open();
- void write(const SafeByteArray& data);
- void writeFooter();
- void close();
- void restartStream();
+ void open();
+ void write(const SafeByteArray& data);
+ void writeFooter();
+ void close();
+ void restartStream();
- void setTLSCertificate(CertificateWithKey::ref certWithKey);
- bool isTLSEncrypted() const;
- Certificate::ref getPeerCertificate() const;
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ void setTLSCertificate(CertificateWithKey::ref certWithKey);
+ bool isTLSEncrypted() const;
+ Certificate::ref getPeerCertificate() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const;
+ boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
- boost::signal<void (BOSHError::ref)> onSessionTerminated;
- boost::signal<void ()> onSessionStarted;
- boost::signal<void (const SafeByteArray&)> onXMPPDataRead;
- boost::signal<void (const SafeByteArray&)> onBOSHDataRead;
- boost::signal<void (const SafeByteArray&)> onBOSHDataWritten;
+ boost::signal<void (BOSHError::ref)> onSessionTerminated;
+ boost::signal<void ()> onSessionStarted;
+ boost::signal<void (const SafeByteArray&)> onXMPPDataRead;
+ boost::signal<void (const SafeByteArray&)> onBOSHDataRead;
+ boost::signal<void (const SafeByteArray&)> onBOSHDataWritten;
- private:
- void handleDataRead(const SafeByteArray& data);
- void handleSessionStarted(const std::string& sid, size_t requests);
- void handleBOSHDataRead(const SafeByteArray& data);
- void handleBOSHDataWritten(const SafeByteArray& data);
- void handleSessionTerminated(BOSHError::ref condition);
- void handleConnectFinished(bool, BOSHConnection::ref connection);
- void handleConnectionDisconnected(bool error, BOSHConnection::ref connection);
- void handleHTTPError(const std::string& errorCode);
+ private:
+ void handleDataRead(const SafeByteArray& data);
+ void handleSessionStarted(const std::string& sid, size_t requests);
+ void handleBOSHDataRead(const SafeByteArray& data);
+ void handleBOSHDataWritten(const SafeByteArray& data);
+ void handleSessionTerminated(BOSHError::ref condition);
+ void handleConnectFinished(bool, BOSHConnection::ref connection);
+ void handleConnectionDisconnected(bool error, BOSHConnection::ref connection);
+ void handleHTTPError(const std::string& errorCode);
- private:
- BOSHConnection::ref createConnection();
- void destroyConnection(BOSHConnection::ref connection);
- void tryToSendQueuedData();
- BOSHConnection::ref getSuitableConnection();
+ private:
+ BOSHConnection::ref createConnection();
+ void destroyConnection(BOSHConnection::ref connection);
+ void tryToSendQueuedData();
+ BOSHConnection::ref getSuitableConnection();
- private:
- URL boshURL;
- ConnectionFactory* connectionFactory;
- XMLParserFactory* xmlParserFactory;
- TimerFactory* timerFactory;
- std::vector<BOSHConnection::ref> connections;
- std::string sid;
- unsigned long long rid;
- std::vector<SafeByteArray> dataQueue;
- bool pendingTerminate;
- std::string to;
- size_t requestLimit;
- int restartCount;
- bool pendingRestart;
- std::vector<ConnectionFactory*> myConnectionFactories;
- CachingDomainNameResolver* resolver;
- CertificateWithKey::ref clientCertificate;
- TLSContextFactory* tlsContextFactory_;
- TLSOptions tlsOptions_;
- std::vector<boost::shared_ptr<Certificate> > pinnedCertificateChain_;
- boost::shared_ptr<CertificateVerificationError> lastVerificationError_;
- };
+ private:
+ URL boshURL;
+ ConnectionFactory* connectionFactory;
+ XMLParserFactory* xmlParserFactory;
+ TimerFactory* timerFactory;
+ std::vector<BOSHConnection::ref> connections;
+ std::string sid;
+ unsigned long long rid;
+ std::vector<SafeByteArray> dataQueue;
+ bool pendingTerminate;
+ std::string to;
+ size_t requestLimit;
+ int restartCount;
+ bool pendingRestart;
+ std::vector<ConnectionFactory*> myConnectionFactories;
+ CachingDomainNameResolver* resolver;
+ CertificateWithKey::ref clientCertificate;
+ TLSContextFactory* tlsContextFactory_;
+ TLSOptions tlsOptions_;
+ std::vector<boost::shared_ptr<Certificate> > pinnedCertificateChain_;
+ boost::shared_ptr<CertificateVerificationError> lastVerificationError_;
+ };
}
diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp
index a88a739..80cb6b8 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -32,147 +32,147 @@ static const size_t BUFFER_SIZE = 4096;
// A reference-counted non-modifiable buffer class.
class SharedBuffer {
- public:
- SharedBuffer(const SafeByteArray& data) :
- data_(new std::vector<char, SafeAllocator<char> >(data.begin(), data.end())),
- buffer_(boost::asio::buffer(*data_)) {
- }
-
- // ConstBufferSequence requirements.
- typedef boost::asio::const_buffer value_type;
- typedef const boost::asio::const_buffer* const_iterator;
- const boost::asio::const_buffer* begin() const { return &buffer_; }
- const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
-
- private:
- boost::shared_ptr< std::vector<char, SafeAllocator<char> > > data_;
- boost::asio::const_buffer buffer_;
+ public:
+ SharedBuffer(const SafeByteArray& data) :
+ data_(new std::vector<char, SafeAllocator<char> >(data.begin(), data.end())),
+ buffer_(boost::asio::buffer(*data_)) {
+ }
+
+ // ConstBufferSequence requirements.
+ typedef boost::asio::const_buffer value_type;
+ typedef const boost::asio::const_buffer* const_iterator;
+ const boost::asio::const_buffer* begin() const { return &buffer_; }
+ const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
+
+ private:
+ boost::shared_ptr< std::vector<char, SafeAllocator<char> > > data_;
+ boost::asio::const_buffer buffer_;
};
// -----------------------------------------------------------------------------
BoostConnection::BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) :
- eventLoop(eventLoop), ioService(ioService), socket_(*ioService), writing_(false), closeSocketAfterNextWrite_(false) {
+ eventLoop(eventLoop), ioService(ioService), socket_(*ioService), writing_(false), closeSocketAfterNextWrite_(false) {
}
BoostConnection::~BoostConnection() {
}
void BoostConnection::listen() {
- doRead();
+ doRead();
}
void BoostConnection::connect(const HostAddressPort& addressPort) {
- boost::asio::ip::tcp::endpoint endpoint(
- boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort()));
- socket_.async_connect(
- endpoint,
- boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error));
+ boost::asio::ip::tcp::endpoint endpoint(
+ boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort()));
+ socket_.async_connect(
+ endpoint,
+ boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error));
}
void BoostConnection::disconnect() {
- //MainEventLoop::removeEventsFromOwner(shared_from_this());
-
- // Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep.
- // See e.g. http://bugs.python.org/issue7401
- // We therefore wait until any pending write finishes, which hopefully should fix our hang on exit during close().
- boost::lock_guard<boost::mutex> lock(writeMutex_);
- if (writing_) {
- closeSocketAfterNextWrite_ = true;
- } else {
- closeSocket();
- }
+ //MainEventLoop::removeEventsFromOwner(shared_from_this());
+
+ // Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep.
+ // See e.g. http://bugs.python.org/issue7401
+ // We therefore wait until any pending write finishes, which hopefully should fix our hang on exit during close().
+ boost::lock_guard<boost::mutex> lock(writeMutex_);
+ if (writing_) {
+ closeSocketAfterNextWrite_ = true;
+ } else {
+ closeSocket();
+ }
}
void BoostConnection::closeSocket() {
- boost::lock_guard<boost::mutex> lock(readCloseMutex_);
- boost::system::error_code errorCode;
- socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode);
- socket_.close();
+ boost::lock_guard<boost::mutex> lock(readCloseMutex_);
+ boost::system::error_code errorCode;
+ socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode);
+ socket_.close();
}
void BoostConnection::write(const SafeByteArray& data) {
- boost::lock_guard<boost::mutex> lock(writeMutex_);
- if (!writing_) {
- writing_ = true;
- doWrite(data);
- }
- else {
- append(writeQueue_, data);
- }
+ boost::lock_guard<boost::mutex> lock(writeMutex_);
+ if (!writing_) {
+ writing_ = true;
+ doWrite(data);
+ }
+ else {
+ append(writeQueue_, data);
+ }
}
void BoostConnection::doWrite(const SafeByteArray& data) {
- boost::asio::async_write(socket_, SharedBuffer(data),
- boost::bind(&BoostConnection::handleDataWritten, shared_from_this(), boost::asio::placeholders::error));
+ boost::asio::async_write(socket_, SharedBuffer(data),
+ boost::bind(&BoostConnection::handleDataWritten, shared_from_this(), boost::asio::placeholders::error));
}
void BoostConnection::handleConnectFinished(const boost::system::error_code& error) {
- SWIFT_LOG(debug) << "Connect finished: " << error << std::endl;
- if (!error) {
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), false), shared_from_this());
- doRead();
- }
- else if (error != boost::asio::error::operation_aborted) {
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), true), shared_from_this());
- }
+ SWIFT_LOG(debug) << "Connect finished: " << error << std::endl;
+ if (!error) {
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), false), shared_from_this());
+ doRead();
+ }
+ else if (error != boost::asio::error::operation_aborted) {
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), true), shared_from_this());
+ }
}
void BoostConnection::doRead() {
- readBuffer_ = boost::make_shared<SafeByteArray>(BUFFER_SIZE);
- boost::lock_guard<boost::mutex> lock(readCloseMutex_);
- socket_.async_read_some(
- boost::asio::buffer(*readBuffer_),
- boost::bind(&BoostConnection::handleSocketRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
+ readBuffer_ = boost::make_shared<SafeByteArray>(BUFFER_SIZE);
+ boost::lock_guard<boost::mutex> lock(readCloseMutex_);
+ socket_.async_read_some(
+ boost::asio::buffer(*readBuffer_),
+ boost::bind(&BoostConnection::handleSocketRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void BoostConnection::handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred) {
- SWIFT_LOG(debug) << "Socket read " << error << std::endl;
- if (!error) {
- readBuffer_->resize(bytesTransferred);
- eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this());
- doRead();
- }
- else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) {
- eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this());
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), ReadError), shared_from_this());
- }
+ SWIFT_LOG(debug) << "Socket read " << error << std::endl;
+ if (!error) {
+ readBuffer_->resize(bytesTransferred);
+ eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this());
+ doRead();
+ }
+ else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) {
+ eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this());
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), ReadError), shared_from_this());
+ }
}
void BoostConnection::handleDataWritten(const boost::system::error_code& error) {
- SWIFT_LOG(debug) << "Data written " << error << std::endl;
- if (!error) {
- eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
- }
- else if (/*error == boost::asio::error::eof || */error == boost::asio::error::operation_aborted) {
- eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this());
- }
- else {
- eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), WriteError), shared_from_this());
- }
- {
- boost::lock_guard<boost::mutex> lock(writeMutex_);
- if (writeQueue_.empty()) {
- writing_ = false;
- if (closeSocketAfterNextWrite_) {
- closeSocket();
- }
- }
- else {
- doWrite(writeQueue_);
- writeQueue_.clear();
- }
- }
+ SWIFT_LOG(debug) << "Data written " << error << std::endl;
+ if (!error) {
+ eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
+ }
+ else if (/*error == boost::asio::error::eof || */error == boost::asio::error::operation_aborted) {
+ eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this());
+ }
+ else {
+ eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), WriteError), shared_from_this());
+ }
+ {
+ boost::lock_guard<boost::mutex> lock(writeMutex_);
+ if (writeQueue_.empty()) {
+ writing_ = false;
+ if (closeSocketAfterNextWrite_) {
+ closeSocket();
+ }
+ }
+ else {
+ doWrite(writeQueue_);
+ writeQueue_.clear();
+ }
+ }
}
HostAddressPort BoostConnection::getLocalAddress() const {
- return HostAddressPort(socket_.local_endpoint());
+ return HostAddressPort(socket_.local_endpoint());
}
HostAddressPort BoostConnection::getRemoteAddress() const {
- return HostAddressPort(socket_.remote_endpoint());
+ return HostAddressPort(socket_.remote_endpoint());
}
diff --git a/Swiften/Network/BoostConnection.h b/Swiften/Network/BoostConnection.h
index be44d51..9909455 100644
--- a/Swiften/Network/BoostConnection.h
+++ b/Swiften/Network/BoostConnection.h
@@ -20,62 +20,62 @@
#include <Swiften/TLS/CertificateWithKey.h>
namespace boost {
- class thread;
- namespace system {
- class error_code;
- }
+ class thread;
+ namespace system {
+ class error_code;
+ }
}
namespace Swift {
- class EventLoop;
-
- class SWIFTEN_API BoostConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<BoostConnection> {
- public:
- typedef boost::shared_ptr<BoostConnection> ref;
-
- virtual ~BoostConnection();
-
- static ref create(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
- return ref(new BoostConnection(ioService, eventLoop));
- }
-
- virtual void listen();
- virtual void connect(const HostAddressPort& address);
- virtual void disconnect();
- virtual void write(const SafeByteArray& data);
-
- boost::asio::ip::tcp::socket& getSocket() {
- return socket_;
- }
-
- virtual HostAddressPort getLocalAddress() const;
- virtual HostAddressPort getRemoteAddress() const;
-
- bool setClientCertificate(CertificateWithKey::ref cert);
-
- Certificate::ref getPeerCertificate() const;
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
-
- private:
- BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
-
- void handleConnectFinished(const boost::system::error_code& error);
- void handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred);
- void handleDataWritten(const boost::system::error_code& error);
- void doRead();
- void doWrite(const SafeByteArray& data);
- void closeSocket();
-
- private:
- EventLoop* eventLoop;
- boost::shared_ptr<boost::asio::io_service> ioService;
- boost::asio::ip::tcp::socket socket_;
- boost::shared_ptr<SafeByteArray> readBuffer_;
- boost::mutex writeMutex_;
- bool writing_;
- SafeByteArray writeQueue_;
- bool closeSocketAfterNextWrite_;
- boost::mutex readCloseMutex_;
- };
+ class EventLoop;
+
+ class SWIFTEN_API BoostConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<BoostConnection> {
+ public:
+ typedef boost::shared_ptr<BoostConnection> ref;
+
+ virtual ~BoostConnection();
+
+ static ref create(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
+ return ref(new BoostConnection(ioService, eventLoop));
+ }
+
+ virtual void listen();
+ virtual void connect(const HostAddressPort& address);
+ virtual void disconnect();
+ virtual void write(const SafeByteArray& data);
+
+ boost::asio::ip::tcp::socket& getSocket() {
+ return socket_;
+ }
+
+ virtual HostAddressPort getLocalAddress() const;
+ virtual HostAddressPort getRemoteAddress() const;
+
+ bool setClientCertificate(CertificateWithKey::ref cert);
+
+ Certificate::ref getPeerCertificate() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const;
+ boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+
+ private:
+ BoostConnection(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
+
+ void handleConnectFinished(const boost::system::error_code& error);
+ void handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred);
+ void handleDataWritten(const boost::system::error_code& error);
+ void doRead();
+ void doWrite(const SafeByteArray& data);
+ void closeSocket();
+
+ private:
+ EventLoop* eventLoop;
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ boost::asio::ip::tcp::socket socket_;
+ boost::shared_ptr<SafeByteArray> readBuffer_;
+ boost::mutex writeMutex_;
+ bool writing_;
+ SafeByteArray writeQueue_;
+ bool closeSocketAfterNextWrite_;
+ boost::mutex readCloseMutex_;
+ };
}
diff --git a/Swiften/Network/BoostConnectionFactory.cpp b/Swiften/Network/BoostConnectionFactory.cpp
index 4aec324..d22f600 100644
--- a/Swiften/Network/BoostConnectionFactory.cpp
+++ b/Swiften/Network/BoostConnectionFactory.cpp
@@ -14,7 +14,7 @@ BoostConnectionFactory::BoostConnectionFactory(boost::shared_ptr<boost::asio::io
}
boost::shared_ptr<Connection> BoostConnectionFactory::createConnection() {
- return BoostConnection::create(ioService, eventLoop);
+ return BoostConnection::create(ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostConnectionFactory.h b/Swiften/Network/BoostConnectionFactory.h
index c98180c..46502de 100644
--- a/Swiften/Network/BoostConnectionFactory.h
+++ b/Swiften/Network/BoostConnectionFactory.h
@@ -13,16 +13,16 @@
#include <Swiften/Network/ConnectionFactory.h>
namespace Swift {
- class BoostConnection;
+ class BoostConnection;
- class SWIFTEN_API BoostConnectionFactory : public ConnectionFactory {
- public:
- BoostConnectionFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
+ class SWIFTEN_API BoostConnectionFactory : public ConnectionFactory {
+ public:
+ BoostConnectionFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<Connection> createConnection();
+ virtual boost::shared_ptr<Connection> createConnection();
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp
index 48b323d..0b20a7f 100644
--- a/Swiften/Network/BoostConnectionServer.cpp
+++ b/Swiften/Network/BoostConnectionServer.cpp
@@ -26,84 +26,84 @@ BoostConnectionServer::BoostConnectionServer(const HostAddress &address, int por
}
void BoostConnectionServer::start() {
- boost::optional<Error> error = tryStart();
- if (error) {
- eventLoop->postEvent(boost::bind(boost::ref(onStopped), *error), shared_from_this());
- }
+ boost::optional<Error> error = tryStart();
+ if (error) {
+ eventLoop->postEvent(boost::bind(boost::ref(onStopped), *error), shared_from_this());
+ }
}
boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart() {
- try {
- assert(!acceptor_);
- boost::asio::ip::tcp::endpoint endpoint;
- if (address_.isValid()) {
- endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_));
- }
- else {
- endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_));
- }
- acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint);
- if (endpoint.protocol() == boost::asio::ip::tcp::v6()) {
- boost::system::error_code ec;
- acceptor_->set_option(boost::asio::ip::v6_only(false), ec);
- SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl;
- }
- acceptNextConnection();
- }
- catch (const boost::system::system_error& e) {
- if (e.code() == boost::asio::error::address_in_use) {
- return Conflict;
- }
- else {
- return UnknownError;
- }
- }
- return boost::optional<Error>();
+ try {
+ assert(!acceptor_);
+ boost::asio::ip::tcp::endpoint endpoint;
+ if (address_.isValid()) {
+ endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_));
+ }
+ else {
+ endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_));
+ }
+ acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint);
+ if (endpoint.protocol() == boost::asio::ip::tcp::v6()) {
+ boost::system::error_code ec;
+ acceptor_->set_option(boost::asio::ip::v6_only(false), ec);
+ SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl;
+ }
+ acceptNextConnection();
+ }
+ catch (const boost::system::system_error& e) {
+ if (e.code() == boost::asio::error::address_in_use) {
+ return Conflict;
+ }
+ else {
+ return UnknownError;
+ }
+ }
+ return boost::optional<Error>();
}
void BoostConnectionServer::stop() {
- stop(boost::optional<Error>());
+ stop(boost::optional<Error>());
}
void BoostConnectionServer::stop(boost::optional<Error> e) {
- if (acceptor_) {
- acceptor_->close();
- delete acceptor_;
- acceptor_ = NULL;
- }
- eventLoop->postEvent(boost::bind(boost::ref(onStopped), e), shared_from_this());
+ if (acceptor_) {
+ acceptor_->close();
+ delete acceptor_;
+ acceptor_ = NULL;
+ }
+ eventLoop->postEvent(boost::bind(boost::ref(onStopped), e), shared_from_this());
}
void BoostConnectionServer::acceptNextConnection() {
- BoostConnection::ref newConnection(BoostConnection::create(ioService_, eventLoop));
- acceptor_->async_accept(newConnection->getSocket(),
- boost::bind(&BoostConnectionServer::handleAccept, shared_from_this(), newConnection, boost::asio::placeholders::error));
+ BoostConnection::ref newConnection(BoostConnection::create(ioService_, eventLoop));
+ acceptor_->async_accept(newConnection->getSocket(),
+ boost::bind(&BoostConnectionServer::handleAccept, shared_from_this(), newConnection, boost::asio::placeholders::error));
}
void BoostConnectionServer::handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error) {
- if (error) {
- eventLoop->postEvent(
- boost::bind(
- &BoostConnectionServer::stop, shared_from_this(), UnknownError),
- shared_from_this());
- }
- else {
- eventLoop->postEvent(
- boost::bind(boost::ref(onNewConnection), newConnection),
- shared_from_this());
- newConnection->listen();
- acceptNextConnection();
- }
+ if (error) {
+ eventLoop->postEvent(
+ boost::bind(
+ &BoostConnectionServer::stop, shared_from_this(), UnknownError),
+ shared_from_this());
+ }
+ else {
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onNewConnection), newConnection),
+ shared_from_this());
+ newConnection->listen();
+ acceptNextConnection();
+ }
}
HostAddressPort BoostConnectionServer::getAddressPort() const {
- if (acceptor_) {
- return HostAddressPort(acceptor_->local_endpoint());
- }
- else {
- return HostAddressPort();
- }
+ if (acceptor_) {
+ return HostAddressPort(acceptor_->local_endpoint());
+ }
+ else {
+ return HostAddressPort();
+ }
}
}
diff --git a/Swiften/Network/BoostConnectionServer.h b/Swiften/Network/BoostConnectionServer.h
index 042cc24..8ee2a6d 100644
--- a/Swiften/Network/BoostConnectionServer.h
+++ b/Swiften/Network/BoostConnectionServer.h
@@ -19,39 +19,39 @@
#include <Swiften/Network/ConnectionServer.h>
namespace Swift {
- class SWIFTEN_API BoostConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<BoostConnectionServer> {
- public:
- typedef boost::shared_ptr<BoostConnectionServer> ref;
+ class SWIFTEN_API BoostConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<BoostConnectionServer> {
+ public:
+ typedef boost::shared_ptr<BoostConnectionServer> ref;
- static ref create(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
- return ref(new BoostConnectionServer(port, ioService, eventLoop));
- }
+ static ref create(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
+ return ref(new BoostConnectionServer(port, ioService, eventLoop));
+ }
- static ref create(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
- return ref(new BoostConnectionServer(address, port, ioService, eventLoop));
- }
+ static ref create(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) {
+ return ref(new BoostConnectionServer(address, port, ioService, eventLoop));
+ }
- virtual boost::optional<Error> tryStart(); // FIXME: This should become the new start
- virtual void start();
- virtual void stop();
+ virtual boost::optional<Error> tryStart(); // FIXME: This should become the new start
+ virtual void start();
+ virtual void stop();
- virtual HostAddressPort getAddressPort() const;
+ virtual HostAddressPort getAddressPort() const;
- boost::signal<void (boost::optional<Error>)> onStopped;
+ boost::signal<void (boost::optional<Error>)> onStopped;
- private:
- BoostConnectionServer(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
- BoostConnectionServer(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
+ private:
+ BoostConnectionServer(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
+ BoostConnectionServer(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
- void stop(boost::optional<Error> e);
- void acceptNextConnection();
- void handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error);
+ void stop(boost::optional<Error> e);
+ void acceptNextConnection();
+ void handleAccept(boost::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error);
- private:
- HostAddress address_;
- int port_;
- boost::shared_ptr<boost::asio::io_service> ioService_;
- EventLoop* eventLoop;
- boost::asio::ip::tcp::acceptor* acceptor_;
- };
+ private:
+ HostAddress address_;
+ int port_;
+ boost::shared_ptr<boost::asio::io_service> ioService_;
+ EventLoop* eventLoop;
+ boost::asio::ip::tcp::acceptor* acceptor_;
+ };
}
diff --git a/Swiften/Network/BoostConnectionServerFactory.cpp b/Swiften/Network/BoostConnectionServerFactory.cpp
index 12173c3..25afdb6 100644
--- a/Swiften/Network/BoostConnectionServerFactory.cpp
+++ b/Swiften/Network/BoostConnectionServerFactory.cpp
@@ -20,11 +20,11 @@ BoostConnectionServerFactory::BoostConnectionServerFactory(boost::shared_ptr<boo
}
boost::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(int port) {
- return BoostConnectionServer::create(port, ioService, eventLoop);
+ return BoostConnectionServer::create(port, ioService, eventLoop);
}
boost::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) {
- return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop);
+ return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostConnectionServerFactory.h b/Swiften/Network/BoostConnectionServerFactory.h
index 831ab45..1e0daa3 100644
--- a/Swiften/Network/BoostConnectionServerFactory.h
+++ b/Swiften/Network/BoostConnectionServerFactory.h
@@ -19,18 +19,18 @@
#include <Swiften/Network/ConnectionServerFactory.h>
namespace Swift {
- class ConnectionServer;
+ class ConnectionServer;
- class SWIFTEN_API BoostConnectionServerFactory : public ConnectionServerFactory {
- public:
- BoostConnectionServerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
+ class SWIFTEN_API BoostConnectionServerFactory : public ConnectionServerFactory {
+ public:
+ BoostConnectionServerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port);
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port);
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/BoostIOServiceThread.cpp b/Swiften/Network/BoostIOServiceThread.cpp
index af74c85..ba9dd5b 100644
--- a/Swiften/Network/BoostIOServiceThread.cpp
+++ b/Swiften/Network/BoostIOServiceThread.cpp
@@ -11,27 +11,27 @@
namespace Swift {
BoostIOServiceThread::BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService) {
- if (!!ioService) {
- ioService_ = ioService;
- thread_ = NULL;
- }
- else {
- ioService_ = boost::make_shared<boost::asio::io_service>();
- thread_ = new boost::thread(boost::bind(&BoostIOServiceThread::doRun, this));
- }
+ if (!!ioService) {
+ ioService_ = ioService;
+ thread_ = NULL;
+ }
+ else {
+ ioService_ = boost::make_shared<boost::asio::io_service>();
+ thread_ = new boost::thread(boost::bind(&BoostIOServiceThread::doRun, this));
+ }
}
BoostIOServiceThread::~BoostIOServiceThread() {
- if (thread_) {
- ioService_->stop();
- thread_->join();
- delete thread_;
- }
+ if (thread_) {
+ ioService_->stop();
+ thread_->join();
+ delete thread_;
+ }
}
void BoostIOServiceThread::doRun() {
- boost::asio::io_service::work work(*ioService_);
- ioService_->run();
+ boost::asio::io_service::work work(*ioService_);
+ ioService_->run();
}
}
diff --git a/Swiften/Network/BoostIOServiceThread.h b/Swiften/Network/BoostIOServiceThread.h
index f493dfb..54f1840 100644
--- a/Swiften/Network/BoostIOServiceThread.h
+++ b/Swiften/Network/BoostIOServiceThread.h
@@ -13,28 +13,28 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API BoostIOServiceThread {
- public:
- /**
- * Construct the object.
- * @param ioService If this optional parameter is provided, the behaviour
- * of this class changes completely - it no longer spawns its own thread
- * and instead acts as a simple wrapper of the io_service. Use this if
- * you are re-using an io_service from elsewhere (particularly if you
- * are using the BoostASIOEventLoop).
- */
- BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>());
- ~BoostIOServiceThread();
+ class SWIFTEN_API BoostIOServiceThread {
+ public:
+ /**
+ * Construct the object.
+ * @param ioService If this optional parameter is provided, the behaviour
+ * of this class changes completely - it no longer spawns its own thread
+ * and instead acts as a simple wrapper of the io_service. Use this if
+ * you are re-using an io_service from elsewhere (particularly if you
+ * are using the BoostASIOEventLoop).
+ */
+ BoostIOServiceThread(boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>());
+ ~BoostIOServiceThread();
- boost::shared_ptr<boost::asio::io_service> getIOService() const {
- return ioService_;
- }
+ boost::shared_ptr<boost::asio::io_service> getIOService() const {
+ return ioService_;
+ }
- private:
- void doRun();
+ private:
+ void doRun();
- private:
- boost::shared_ptr<boost::asio::io_service> ioService_;
- boost::thread* thread_;
- };
+ private:
+ boost::shared_ptr<boost::asio::io_service> ioService_;
+ boost::thread* thread_;
+ };
}
diff --git a/Swiften/Network/BoostNetworkFactories.cpp b/Swiften/Network/BoostNetworkFactories.cpp
index 871a38b..40282f2 100644
--- a/Swiften/Network/BoostNetworkFactories.cpp
+++ b/Swiften/Network/BoostNetworkFactories.cpp
@@ -29,44 +29,44 @@
namespace Swift {
BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService) : ioServiceThread(ioService), eventLoop(eventLoop) {
- timerFactory = new BoostTimerFactory(ioServiceThread.getIOService(), eventLoop);
- connectionFactory = new BoostConnectionFactory(ioServiceThread.getIOService(), eventLoop);
- connectionServerFactory = new BoostConnectionServerFactory(ioServiceThread.getIOService(), eventLoop);
+ timerFactory = new BoostTimerFactory(ioServiceThread.getIOService(), eventLoop);
+ connectionFactory = new BoostConnectionFactory(ioServiceThread.getIOService(), eventLoop);
+ connectionServerFactory = new BoostConnectionServerFactory(ioServiceThread.getIOService(), eventLoop);
#ifdef SWIFT_EXPERIMENTAL_FT
- natTraverser = new PlatformNATTraversalWorker(eventLoop);
+ natTraverser = new PlatformNATTraversalWorker(eventLoop);
#else
- natTraverser = new NullNATTraverser(eventLoop);
+ natTraverser = new NullNATTraverser(eventLoop);
#endif
- networkEnvironment = new PlatformNetworkEnvironment();
- xmlParserFactory = new PlatformXMLParserFactory();
- tlsFactories = new PlatformTLSFactories();
- proxyProvider = new PlatformProxyProvider();
- idnConverter = PlatformIDNConverter::create();
+ networkEnvironment = new PlatformNetworkEnvironment();
+ xmlParserFactory = new PlatformXMLParserFactory();
+ tlsFactories = new PlatformTLSFactories();
+ proxyProvider = new PlatformProxyProvider();
+ idnConverter = PlatformIDNConverter::create();
#ifdef USE_UNBOUND
- // TODO: What to do about idnConverter.
- domainNameResolver = new UnboundDomainNameResolver(idnConverter, ioServiceThread.getIOService(), eventLoop);
+ // TODO: What to do about idnConverter.
+ domainNameResolver = new UnboundDomainNameResolver(idnConverter, ioServiceThread.getIOService(), eventLoop);
#else
- domainNameResolver = new PlatformDomainNameResolver(idnConverter, eventLoop);
+ domainNameResolver = new PlatformDomainNameResolver(idnConverter, eventLoop);
#endif
- cryptoProvider = PlatformCryptoProvider::create();
+ cryptoProvider = PlatformCryptoProvider::create();
}
BoostNetworkFactories::~BoostNetworkFactories() {
- delete cryptoProvider;
- delete domainNameResolver;
- delete idnConverter;
- delete proxyProvider;
- delete tlsFactories;
- delete xmlParserFactory;
- delete networkEnvironment;
- delete natTraverser;
- delete connectionServerFactory;
- delete connectionFactory;
- delete timerFactory;
+ delete cryptoProvider;
+ delete domainNameResolver;
+ delete idnConverter;
+ delete proxyProvider;
+ delete tlsFactories;
+ delete xmlParserFactory;
+ delete networkEnvironment;
+ delete natTraverser;
+ delete connectionServerFactory;
+ delete connectionFactory;
+ delete timerFactory;
}
TLSContextFactory* BoostNetworkFactories::getTLSContextFactory() const {
- return tlsFactories->getTLSContextFactory();
+ return tlsFactories->getTLSContextFactory();
}
}
diff --git a/Swiften/Network/BoostNetworkFactories.h b/Swiften/Network/BoostNetworkFactories.h
index 12755b9..ccacbf0 100644
--- a/Swiften/Network/BoostNetworkFactories.h
+++ b/Swiften/Network/BoostNetworkFactories.h
@@ -12,83 +12,83 @@
#include <Swiften/Network/NetworkFactories.h>
namespace Swift {
- class EventLoop;
- class NATTraverser;
- class PlatformTLSFactories;
-
- class SWIFTEN_API BoostNetworkFactories : public NetworkFactories {
- public:
- /**
- * Construct the network factories, using the provided EventLoop.
- * @param ioService If this optional parameter is provided, it will be
- * used for the construction of the BoostIOServiceThread.
- */
- BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>());
- virtual ~BoostNetworkFactories();
-
- virtual TimerFactory* getTimerFactory() const SWIFTEN_OVERRIDE {
- return timerFactory;
- }
-
- virtual ConnectionFactory* getConnectionFactory() const SWIFTEN_OVERRIDE {
- return connectionFactory;
- }
-
- BoostIOServiceThread* getIOServiceThread() {
- return &ioServiceThread;
- }
-
- DomainNameResolver* getDomainNameResolver() const SWIFTEN_OVERRIDE {
- return domainNameResolver;
- }
-
- ConnectionServerFactory* getConnectionServerFactory() const SWIFTEN_OVERRIDE {
- return connectionServerFactory;
- }
-
- NetworkEnvironment* getNetworkEnvironment() const SWIFTEN_OVERRIDE {
- return networkEnvironment;
- }
-
- NATTraverser* getNATTraverser() const SWIFTEN_OVERRIDE {
- return natTraverser;
- }
-
- virtual XMLParserFactory* getXMLParserFactory() const SWIFTEN_OVERRIDE {
- return xmlParserFactory;
- }
-
- virtual TLSContextFactory* getTLSContextFactory() const SWIFTEN_OVERRIDE;
-
- virtual ProxyProvider* getProxyProvider() const SWIFTEN_OVERRIDE {
- return proxyProvider;
- }
-
- virtual EventLoop* getEventLoop() const SWIFTEN_OVERRIDE {
- return eventLoop;
- }
-
- virtual IDNConverter* getIDNConverter() const SWIFTEN_OVERRIDE {
- return idnConverter;
- }
-
- virtual CryptoProvider* getCryptoProvider() const SWIFTEN_OVERRIDE {
- return cryptoProvider;
- }
-
- private:
- BoostIOServiceThread ioServiceThread;
- TimerFactory* timerFactory;
- ConnectionFactory* connectionFactory;
- DomainNameResolver* domainNameResolver;
- ConnectionServerFactory* connectionServerFactory;
- NATTraverser* natTraverser;
- NetworkEnvironment* networkEnvironment;
- XMLParserFactory* xmlParserFactory;
- PlatformTLSFactories* tlsFactories;
- ProxyProvider* proxyProvider;
- EventLoop* eventLoop;
- IDNConverter* idnConverter;
- CryptoProvider* cryptoProvider;
- };
+ class EventLoop;
+ class NATTraverser;
+ class PlatformTLSFactories;
+
+ class SWIFTEN_API BoostNetworkFactories : public NetworkFactories {
+ public:
+ /**
+ * Construct the network factories, using the provided EventLoop.
+ * @param ioService If this optional parameter is provided, it will be
+ * used for the construction of the BoostIOServiceThread.
+ */
+ BoostNetworkFactories(EventLoop* eventLoop, boost::shared_ptr<boost::asio::io_service> ioService = boost::shared_ptr<boost::asio::io_service>());
+ virtual ~BoostNetworkFactories();
+
+ virtual TimerFactory* getTimerFactory() const SWIFTEN_OVERRIDE {
+ return timerFactory;
+ }
+
+ virtual ConnectionFactory* getConnectionFactory() const SWIFTEN_OVERRIDE {
+ return connectionFactory;
+ }
+
+ BoostIOServiceThread* getIOServiceThread() {
+ return &ioServiceThread;
+ }
+
+ DomainNameResolver* getDomainNameResolver() const SWIFTEN_OVERRIDE {
+ return domainNameResolver;
+ }
+
+ ConnectionServerFactory* getConnectionServerFactory() const SWIFTEN_OVERRIDE {
+ return connectionServerFactory;
+ }
+
+ NetworkEnvironment* getNetworkEnvironment() const SWIFTEN_OVERRIDE {
+ return networkEnvironment;
+ }
+
+ NATTraverser* getNATTraverser() const SWIFTEN_OVERRIDE {
+ return natTraverser;
+ }
+
+ virtual XMLParserFactory* getXMLParserFactory() const SWIFTEN_OVERRIDE {
+ return xmlParserFactory;
+ }
+
+ virtual TLSContextFactory* getTLSContextFactory() const SWIFTEN_OVERRIDE;
+
+ virtual ProxyProvider* getProxyProvider() const SWIFTEN_OVERRIDE {
+ return proxyProvider;
+ }
+
+ virtual EventLoop* getEventLoop() const SWIFTEN_OVERRIDE {
+ return eventLoop;
+ }
+
+ virtual IDNConverter* getIDNConverter() const SWIFTEN_OVERRIDE {
+ return idnConverter;
+ }
+
+ virtual CryptoProvider* getCryptoProvider() const SWIFTEN_OVERRIDE {
+ return cryptoProvider;
+ }
+
+ private:
+ BoostIOServiceThread ioServiceThread;
+ TimerFactory* timerFactory;
+ ConnectionFactory* connectionFactory;
+ DomainNameResolver* domainNameResolver;
+ ConnectionServerFactory* connectionServerFactory;
+ NATTraverser* natTraverser;
+ NetworkEnvironment* networkEnvironment;
+ XMLParserFactory* xmlParserFactory;
+ PlatformTLSFactories* tlsFactories;
+ ProxyProvider* proxyProvider;
+ EventLoop* eventLoop;
+ IDNConverter* idnConverter;
+ CryptoProvider* cryptoProvider;
+ };
}
diff --git a/Swiften/Network/BoostTimer.cpp b/Swiften/Network/BoostTimer.cpp
index c30fe32..734a9c8 100644
--- a/Swiften/Network/BoostTimer.cpp
+++ b/Swiften/Network/BoostTimer.cpp
@@ -15,48 +15,48 @@
namespace Swift {
BoostTimer::BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) :
- timeout(milliseconds), ioService(service), eventLoop(eventLoop), shuttingDown(false) {
- timer.reset(new boost::asio::deadline_timer(*service));
+ timeout(milliseconds), ioService(service), eventLoop(eventLoop), shuttingDown(false) {
+ timer.reset(new boost::asio::deadline_timer(*service));
}
BoostTimer::~BoostTimer() {
- {
- boost::mutex::scoped_lock lockTimer(timerMutex);
- timer.reset();
- }
+ {
+ boost::mutex::scoped_lock lockTimer(timerMutex);
+ timer.reset();
+ }
}
void BoostTimer::start() {
- {
- boost::mutex::scoped_lock lockTimer(timerMutex);
- shuttingDown = false;
- timer->expires_from_now(boost::posix_time::milliseconds(timeout));
- timer->async_wait(boost::bind(&BoostTimer::handleTimerTick, shared_from_this(), boost::asio::placeholders::error));
- }
+ {
+ boost::mutex::scoped_lock lockTimer(timerMutex);
+ shuttingDown = false;
+ timer->expires_from_now(boost::posix_time::milliseconds(timeout));
+ timer->async_wait(boost::bind(&BoostTimer::handleTimerTick, shared_from_this(), boost::asio::placeholders::error));
+ }
}
void BoostTimer::stop() {
- {
- boost::mutex::scoped_lock lockTimer(timerMutex);
- shuttingDown = true;
- timer->cancel();
- eventLoop->removeEventsFromOwner(shared_from_this());
- }
+ {
+ boost::mutex::scoped_lock lockTimer(timerMutex);
+ shuttingDown = true;
+ timer->cancel();
+ eventLoop->removeEventsFromOwner(shared_from_this());
+ }
}
void BoostTimer::handleTimerTick(const boost::system::error_code& error) {
- if (error) {
- assert(error == boost::asio::error::operation_aborted);
- }
- else {
- {
- boost::mutex::scoped_lock lockTimer(timerMutex);
- if (shuttingDown) {
- return;
- }
- eventLoop->postEvent(boost::bind(boost::ref(onTick)), shared_from_this());
- }
- }
+ if (error) {
+ assert(error == boost::asio::error::operation_aborted);
+ }
+ else {
+ {
+ boost::mutex::scoped_lock lockTimer(timerMutex);
+ if (shuttingDown) {
+ return;
+ }
+ eventLoop->postEvent(boost::bind(boost::ref(onTick)), shared_from_this());
+ }
+ }
}
}
diff --git a/Swiften/Network/BoostTimer.h b/Swiften/Network/BoostTimer.h
index 3227031..79c71cd 100644
--- a/Swiften/Network/BoostTimer.h
+++ b/Swiften/Network/BoostTimer.h
@@ -17,32 +17,32 @@
#include <Swiften/Network/Timer.h>
namespace Swift {
- class EventLoop;
+ class EventLoop;
- class SWIFTEN_API BoostTimer : public Timer, public EventOwner, public boost::enable_shared_from_this<BoostTimer> {
- public:
- typedef boost::shared_ptr<BoostTimer> ref;
+ class SWIFTEN_API BoostTimer : public Timer, public EventOwner, public boost::enable_shared_from_this<BoostTimer> {
+ public:
+ typedef boost::shared_ptr<BoostTimer> ref;
- virtual ~BoostTimer();
+ virtual ~BoostTimer();
- static ref create(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) {
- return ref(new BoostTimer(milliseconds, service, eventLoop));
- }
+ static ref create(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop) {
+ return ref(new BoostTimer(milliseconds, service, eventLoop));
+ }
- virtual void start();
- virtual void stop();
+ virtual void start();
+ virtual void stop();
- private:
- BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop);
+ private:
+ BoostTimer(int milliseconds, boost::shared_ptr<boost::asio::io_service> service, EventLoop* eventLoop);
- void handleTimerTick(const boost::system::error_code& error);
+ void handleTimerTick(const boost::system::error_code& error);
- private:
- int timeout;
- boost::shared_ptr<boost::asio::io_service> ioService;
- boost::scoped_ptr<boost::asio::deadline_timer> timer;
- boost::mutex timerMutex;
- EventLoop* eventLoop;
- bool shuttingDown;
- };
+ private:
+ int timeout;
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ boost::scoped_ptr<boost::asio::deadline_timer> timer;
+ boost::mutex timerMutex;
+ EventLoop* eventLoop;
+ bool shuttingDown;
+ };
}
diff --git a/Swiften/Network/BoostTimerFactory.cpp b/Swiften/Network/BoostTimerFactory.cpp
index 4281a1f..086eb60 100644
--- a/Swiften/Network/BoostTimerFactory.cpp
+++ b/Swiften/Network/BoostTimerFactory.cpp
@@ -14,7 +14,7 @@ BoostTimerFactory::BoostTimerFactory(boost::shared_ptr<boost::asio::io_service>
}
boost::shared_ptr<Timer> BoostTimerFactory::createTimer(int milliseconds) {
- return BoostTimer::create(milliseconds, ioService, eventLoop);
+ return BoostTimer::create(milliseconds, ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostTimerFactory.h b/Swiften/Network/BoostTimerFactory.h
index 328c64e..4fbabe9 100644
--- a/Swiften/Network/BoostTimerFactory.h
+++ b/Swiften/Network/BoostTimerFactory.h
@@ -13,17 +13,17 @@
#include <Swiften/Network/TimerFactory.h>
namespace Swift {
- class BoostTimer;
- class EventLoop;
+ class BoostTimer;
+ class EventLoop;
- class SWIFTEN_API BoostTimerFactory : public TimerFactory {
- public:
- BoostTimerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
+ class SWIFTEN_API BoostTimerFactory : public TimerFactory {
+ public:
+ BoostTimerFactory(boost::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<Timer> createTimer(int milliseconds);
+ virtual boost::shared_ptr<Timer> createTimer(int milliseconds);
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/CachingDomainNameResolver.cpp b/Swiften/Network/CachingDomainNameResolver.cpp
index 8a2336b..d731eb9 100644
--- a/Swiften/Network/CachingDomainNameResolver.cpp
+++ b/Swiften/Network/CachingDomainNameResolver.cpp
@@ -18,13 +18,13 @@ CachingDomainNameResolver::~CachingDomainNameResolver() {
}
DomainNameServiceQuery::ref CachingDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
- //TODO: Cache
- return realResolver->createServiceQuery(serviceLookupPrefix, domain);
+ //TODO: Cache
+ return realResolver->createServiceQuery(serviceLookupPrefix, domain);
}
DomainNameAddressQuery::ref CachingDomainNameResolver::createAddressQuery(const std::string& name) {
- //TODO: Cache
- return realResolver->createAddressQuery(name);
+ //TODO: Cache
+ return realResolver->createAddressQuery(name);
}
}
diff --git a/Swiften/Network/CachingDomainNameResolver.h b/Swiften/Network/CachingDomainNameResolver.h
index 2a0b1b7..25cb86c 100644
--- a/Swiften/Network/CachingDomainNameResolver.h
+++ b/Swiften/Network/CachingDomainNameResolver.h
@@ -16,17 +16,17 @@
* FIXME: Does not do any caching yet.
*/
namespace Swift {
- class EventLoop;
+ class EventLoop;
- class SWIFTEN_API CachingDomainNameResolver : public DomainNameResolver {
- public:
- CachingDomainNameResolver(DomainNameResolver* realResolver, EventLoop* eventLoop);
- ~CachingDomainNameResolver();
+ class SWIFTEN_API CachingDomainNameResolver : public DomainNameResolver {
+ public:
+ CachingDomainNameResolver(DomainNameResolver* realResolver, EventLoop* eventLoop);
+ ~CachingDomainNameResolver();
- virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
- virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name);
+ virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name);
- private:
- DomainNameResolver* realResolver;
- };
+ private:
+ DomainNameResolver* realResolver;
+ };
}
diff --git a/Swiften/Network/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp
index 3cc4057..08c4aac 100644
--- a/Swiften/Network/ChainedConnector.cpp
+++ b/Swiften/Network/ChainedConnector.cpp
@@ -18,79 +18,79 @@
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) {
+ 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();
- }
+ if (currentConnector) {
+ currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
+ currentConnector->stop();
+ currentConnector.reset();
+ }
}
void ChainedConnector::setTimeoutMilliseconds(int milliseconds) {
- timeoutMilliseconds = milliseconds;
+ timeoutMilliseconds = milliseconds;
}
void ChainedConnector::start() {
- SWIFT_LOG(debug) << "Starting queued connector for " << hostname << std::endl;
+ SWIFT_LOG(debug) << "Starting queued connector for " << hostname << std::endl;
- connectionFactoryQueue = std::deque<ConnectionFactory*>(connectionFactories.begin(), connectionFactories.end());
- tryNextConnectionFactory();
+ connectionFactoryQueue = std::deque<ConnectionFactory*>(connectionFactories.begin(), connectionFactories.end());
+ tryNextConnectionFactory();
}
void ChainedConnector::stop() {
- if (currentConnector) {
- currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
- currentConnector->stop();
- currentConnector.reset();
- }
- finish(boost::shared_ptr<Connection>(), boost::shared_ptr<Error>());
+ if (currentConnector) {
+ currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
+ currentConnector->stop();
+ currentConnector.reset();
+ }
+ finish(boost::shared_ptr<Connection>(), boost::shared_ptr<Error>());
}
void ChainedConnector::tryNextConnectionFactory() {
- assert(!currentConnector);
- if (connectionFactoryQueue.empty()) {
- SWIFT_LOG(debug) << "No more connection factories" << std::endl;
- finish(boost::shared_ptr<Connection>(), lastError);
- }
- else {
- ConnectionFactory* connectionFactory = connectionFactoryQueue.front();
- SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name() << std::endl;
- connectionFactoryQueue.pop_front();
- currentConnector = Connector::create(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory);
- currentConnector->setTimeoutMilliseconds(timeoutMilliseconds);
- currentConnector->onConnectFinished.connect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
- currentConnector->start();
- }
+ assert(!currentConnector);
+ if (connectionFactoryQueue.empty()) {
+ SWIFT_LOG(debug) << "No more connection factories" << std::endl;
+ finish(boost::shared_ptr<Connection>(), lastError);
+ }
+ else {
+ ConnectionFactory* connectionFactory = connectionFactoryQueue.front();
+ SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name() << std::endl;
+ connectionFactoryQueue.pop_front();
+ currentConnector = Connector::create(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory);
+ currentConnector->setTimeoutMilliseconds(timeoutMilliseconds);
+ currentConnector->onConnectFinished.connect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
+ currentConnector->start();
+ }
}
void ChainedConnector::handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) {
- SWIFT_LOG(debug) << "Connector finished" << std::endl;
- currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
- lastError = error;
- currentConnector.reset();
- if (connection) {
- finish(connection, error);
- }
- else {
- tryNextConnectionFactory();
- }
+ SWIFT_LOG(debug) << "Connector finished" << std::endl;
+ currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2));
+ lastError = error;
+ currentConnector.reset();
+ if (connection) {
+ finish(connection, error);
+ }
+ else {
+ tryNextConnectionFactory();
+ }
}
void ChainedConnector::finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) {
- onConnectFinished(connection, error);
+ onConnectFinished(connection, error);
}
diff --git a/Swiften/Network/ChainedConnector.h b/Swiften/Network/ChainedConnector.h
index 9bcc961..416dccb 100644
--- a/Swiften/Network/ChainedConnector.h
+++ b/Swiften/Network/ChainedConnector.h
@@ -18,38 +18,38 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class Connection;
- class Connector;
- class ConnectionFactory;
- class TimerFactory;
- class DomainNameResolver;
-
- class SWIFTEN_API ChainedConnector {
- public:
- ChainedConnector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*);
- ~ChainedConnector();
-
- void setTimeoutMilliseconds(int milliseconds);
- void start();
- void stop();
-
- boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished;
-
- private:
- void finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error>);
- void tryNextConnectionFactory();
- void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error>);
-
- private:
- std::string hostname;
- int port;
- boost::optional<std::string> serviceLookupPrefix;
- DomainNameResolver* resolver;
- std::vector<ConnectionFactory*> connectionFactories;
- TimerFactory* timerFactory;
- int timeoutMilliseconds;
- std::deque<ConnectionFactory*> connectionFactoryQueue;
- boost::shared_ptr<Connector> currentConnector;
- boost::shared_ptr<Error> lastError;
- };
+ class Connection;
+ class Connector;
+ class ConnectionFactory;
+ class TimerFactory;
+ class DomainNameResolver;
+
+ class SWIFTEN_API ChainedConnector {
+ public:
+ ChainedConnector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*);
+ ~ChainedConnector();
+
+ void setTimeoutMilliseconds(int milliseconds);
+ void start();
+ void stop();
+
+ boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished;
+
+ private:
+ void finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error>);
+ void tryNextConnectionFactory();
+ void handleConnectorFinished(boost::shared_ptr<Connection>, boost::shared_ptr<Error>);
+
+ private:
+ std::string hostname;
+ int port;
+ boost::optional<std::string> serviceLookupPrefix;
+ DomainNameResolver* resolver;
+ std::vector<ConnectionFactory*> connectionFactories;
+ TimerFactory* timerFactory;
+ int timeoutMilliseconds;
+ std::deque<ConnectionFactory*> connectionFactoryQueue;
+ boost::shared_ptr<Connector> currentConnector;
+ boost::shared_ptr<Error> lastError;
+ };
}
diff --git a/Swiften/Network/Connection.h b/Swiften/Network/Connection.h
index 39b63d4..c38b98f 100644
--- a/Swiften/Network/Connection.h
+++ b/Swiften/Network/Connection.h
@@ -13,32 +13,32 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class HostAddressPort;
-
- class SWIFTEN_API Connection {
- public:
- typedef boost::shared_ptr<Connection> ref;
-
- enum Error {
- ReadError,
- WriteError
- };
-
- Connection();
- virtual ~Connection();
-
- virtual void listen() = 0;
- virtual void connect(const HostAddressPort& address) = 0;
- virtual void disconnect() = 0;
- virtual void write(const SafeByteArray& data) = 0;
-
- virtual HostAddressPort getLocalAddress() const = 0;
- virtual HostAddressPort getRemoteAddress() const = 0;
-
- public:
- boost::signal<void (bool /* error */)> onConnectFinished;
- boost::signal<void (const boost::optional<Error>&)> onDisconnected;
- boost::signal<void (boost::shared_ptr<SafeByteArray>)> onDataRead;
- boost::signal<void ()> onDataWritten;
- };
+ class HostAddressPort;
+
+ class SWIFTEN_API Connection {
+ public:
+ typedef boost::shared_ptr<Connection> ref;
+
+ enum Error {
+ ReadError,
+ WriteError
+ };
+
+ Connection();
+ virtual ~Connection();
+
+ virtual void listen() = 0;
+ virtual void connect(const HostAddressPort& address) = 0;
+ virtual void disconnect() = 0;
+ virtual void write(const SafeByteArray& data) = 0;
+
+ virtual HostAddressPort getLocalAddress() const = 0;
+ virtual HostAddressPort getRemoteAddress() const = 0;
+
+ public:
+ boost::signal<void (bool /* error */)> onConnectFinished;
+ boost::signal<void (const boost::optional<Error>&)> onDisconnected;
+ boost::signal<void (boost::shared_ptr<SafeByteArray>)> onDataRead;
+ boost::signal<void ()> onDataWritten;
+ };
}
diff --git a/Swiften/Network/ConnectionFactory.h b/Swiften/Network/ConnectionFactory.h
index d8e1b71..fd65908 100644
--- a/Swiften/Network/ConnectionFactory.h
+++ b/Swiften/Network/ConnectionFactory.h
@@ -11,12 +11,12 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class Connection;
+ class Connection;
- class SWIFTEN_API ConnectionFactory {
- public:
- virtual ~ConnectionFactory();
+ class SWIFTEN_API ConnectionFactory {
+ public:
+ virtual ~ConnectionFactory();
- virtual boost::shared_ptr<Connection> createConnection() = 0;
- };
+ virtual boost::shared_ptr<Connection> createConnection() = 0;
+ };
}
diff --git a/Swiften/Network/ConnectionServer.h b/Swiften/Network/ConnectionServer.h
index 7b0cdd1..a8c77eb 100644
--- a/Swiften/Network/ConnectionServer.h
+++ b/Swiften/Network/ConnectionServer.h
@@ -15,23 +15,23 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API ConnectionServer {
- public:
- enum Error {
- Conflict,
- UnknownError
- };
+ class SWIFTEN_API ConnectionServer {
+ public:
+ enum Error {
+ Conflict,
+ UnknownError
+ };
- virtual ~ConnectionServer();
+ virtual ~ConnectionServer();
- virtual HostAddressPort getAddressPort() const = 0;
+ virtual HostAddressPort getAddressPort() const = 0;
- virtual boost::optional<Error> tryStart() = 0; // FIXME: This should become the new start
+ virtual boost::optional<Error> tryStart() = 0; // FIXME: This should become the new start
- virtual void start() = 0;
+ virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void stop() = 0;
- boost::signal<void (boost::shared_ptr<Connection>)> onNewConnection;
- };
+ boost::signal<void (boost::shared_ptr<Connection>)> onNewConnection;
+ };
}
diff --git a/Swiften/Network/ConnectionServerFactory.h b/Swiften/Network/ConnectionServerFactory.h
index 8e488c9..7f988bf 100644
--- a/Swiften/Network/ConnectionServerFactory.h
+++ b/Swiften/Network/ConnectionServerFactory.h
@@ -17,15 +17,15 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class ConnectionServer;
- class HostAddress;
+ class ConnectionServer;
+ class HostAddress;
- class SWIFTEN_API ConnectionServerFactory {
- public:
- virtual ~ConnectionServerFactory();
+ class SWIFTEN_API ConnectionServerFactory {
+ public:
+ virtual ~ConnectionServerFactory();
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0;
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0;
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0;
- };
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0;
+ };
}
diff --git a/Swiften/Network/Connector.cpp b/Swiften/Network/Connector.cpp
index 2775c97..bd25e70 100644
--- a/Swiften/Network/Connector.cpp
+++ b/Swiften/Network/Connector.cpp
@@ -21,174 +21,174 @@ Connector::Connector(const std::string& hostname, int port, const boost::optiona
}
void Connector::setTimeoutMilliseconds(int milliseconds) {
- timeoutMilliseconds = milliseconds;
+ timeoutMilliseconds = milliseconds;
}
void Connector::start() {
- SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl;
- assert(!currentConnection);
- assert(!serviceQuery);
- assert(!timer);
- queriedAllServices = false;
- if (timeoutMilliseconds > 0) {
- timer = timerFactory->createTimer(timeoutMilliseconds);
- timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this()));
- }
- if (serviceLookupPrefix) {
- serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname);
- serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
- serviceQuery->run();
- }
- else if (HostAddress(hostname).isValid()) {
- // hostname is already a valid address; skip name lookup.
- foundSomeDNS = true;
- addressQueryResults.push_back(HostAddress(hostname));
- tryNextAddress();
- } else {
- queryAddress(hostname);
- }
+ SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl;
+ assert(!currentConnection);
+ assert(!serviceQuery);
+ assert(!timer);
+ queriedAllServices = false;
+ if (timeoutMilliseconds > 0) {
+ timer = timerFactory->createTimer(timeoutMilliseconds);
+ timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this()));
+ }
+ if (serviceLookupPrefix) {
+ serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname);
+ serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
+ serviceQuery->run();
+ }
+ else if (HostAddress(hostname).isValid()) {
+ // hostname is already a valid address; skip name lookup.
+ foundSomeDNS = true;
+ addressQueryResults.push_back(HostAddress(hostname));
+ tryNextAddress();
+ } else {
+ queryAddress(hostname);
+ }
}
void Connector::stop() {
- if (currentConnection) {
- currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
- currentConnection->disconnect();
- }
- finish(boost::shared_ptr<Connection>());
+ if (currentConnection) {
+ currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection->disconnect();
+ }
+ finish(boost::shared_ptr<Connection>());
}
void Connector::queryAddress(const std::string& hostname) {
- assert(!addressQuery);
- addressQuery = resolver->createAddressQuery(hostname);
- addressQuery->onResult.connect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2));
- addressQuery->run();
+ assert(!addressQuery);
+ addressQuery = resolver->createAddressQuery(hostname);
+ addressQuery->onResult.connect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2));
+ addressQuery->run();
}
void Connector::handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result) {
- SWIFT_LOG(debug) << result.size() << " SRV result(s)" << std::endl;
- serviceQueryResults = std::deque<DomainNameServiceQuery::Result>(result.begin(), result.end());
- serviceQuery.reset();
- if (!serviceQueryResults.empty()) {
- foundSomeDNS = true;
- }
- tryNextServiceOrFallback();
+ SWIFT_LOG(debug) << result.size() << " SRV result(s)" << std::endl;
+ serviceQueryResults = std::deque<DomainNameServiceQuery::Result>(result.begin(), result.end());
+ serviceQuery.reset();
+ if (!serviceQueryResults.empty()) {
+ foundSomeDNS = true;
+ }
+ tryNextServiceOrFallback();
}
void Connector::tryNextServiceOrFallback() {
- if (queriedAllServices) {
- SWIFT_LOG(debug) << "Queried all services" << std::endl;
- finish(boost::shared_ptr<Connection>());
- }
- else if (serviceQueryResults.empty()) {
- SWIFT_LOG(debug) << "Falling back on A resolution" << std::endl;
- // Fall back on simple address resolving
- queriedAllServices = true;
- queryAddress(hostname);
- }
- else {
- SWIFT_LOG(debug) << "Querying next address" << std::endl;
- queryAddress(serviceQueryResults.front().hostname);
- }
+ if (queriedAllServices) {
+ SWIFT_LOG(debug) << "Queried all services" << std::endl;
+ finish(boost::shared_ptr<Connection>());
+ }
+ else if (serviceQueryResults.empty()) {
+ SWIFT_LOG(debug) << "Falling back on A resolution" << std::endl;
+ // Fall back on simple address resolving
+ queriedAllServices = true;
+ queryAddress(hostname);
+ }
+ else {
+ SWIFT_LOG(debug) << "Querying next address" << std::endl;
+ queryAddress(serviceQueryResults.front().hostname);
+ }
}
void Connector::handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) {
- SWIFT_LOG(debug) << addresses.size() << " addresses" << std::endl;
- addressQuery.reset();
- if (error || addresses.empty()) {
- if (!serviceQueryResults.empty()) {
- serviceQueryResults.pop_front();
- }
- tryNextServiceOrFallback();
- }
- else {
- foundSomeDNS = true;
- addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end());
- tryNextAddress();
- }
+ SWIFT_LOG(debug) << addresses.size() << " addresses" << std::endl;
+ addressQuery.reset();
+ if (error || addresses.empty()) {
+ if (!serviceQueryResults.empty()) {
+ serviceQueryResults.pop_front();
+ }
+ tryNextServiceOrFallback();
+ }
+ else {
+ foundSomeDNS = true;
+ addressQueryResults = std::deque<HostAddress>(addresses.begin(), addresses.end());
+ tryNextAddress();
+ }
}
void Connector::tryNextAddress() {
- if (addressQueryResults.empty()) {
- SWIFT_LOG(debug) << "Done trying addresses. Moving on." << std::endl;
- // Done trying all addresses. Move on to the next host.
- if (!serviceQueryResults.empty()) {
- serviceQueryResults.pop_front();
- }
- tryNextServiceOrFallback();
- }
- else {
- SWIFT_LOG(debug) << "Trying next address" << std::endl;
- HostAddress address = addressQueryResults.front();
- addressQueryResults.pop_front();
-
- int connectPort = (port == -1 ? 5222 : port);
- if (!serviceQueryResults.empty()) {
- connectPort = serviceQueryResults.front().port;
- }
-
- tryConnect(HostAddressPort(address, connectPort));
- }
+ if (addressQueryResults.empty()) {
+ SWIFT_LOG(debug) << "Done trying addresses. Moving on." << std::endl;
+ // Done trying all addresses. Move on to the next host.
+ if (!serviceQueryResults.empty()) {
+ serviceQueryResults.pop_front();
+ }
+ tryNextServiceOrFallback();
+ }
+ else {
+ SWIFT_LOG(debug) << "Trying next address" << std::endl;
+ HostAddress address = addressQueryResults.front();
+ addressQueryResults.pop_front();
+
+ int connectPort = (port == -1 ? 5222 : port);
+ if (!serviceQueryResults.empty()) {
+ connectPort = serviceQueryResults.front().port;
+ }
+
+ tryConnect(HostAddressPort(address, connectPort));
+ }
}
void Connector::tryConnect(const HostAddressPort& target) {
- assert(!currentConnection);
- SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort() << std::endl;
- currentConnection = connectionFactory->createConnection();
- currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
- currentConnection->connect(target);
- if (timer) {
- timer->start();
- }
+ assert(!currentConnection);
+ SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort() << std::endl;
+ currentConnection = connectionFactory->createConnection();
+ currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection->connect(target);
+ if (timer) {
+ timer->start();
+ }
}
void Connector::handleConnectionConnectFinished(bool error) {
- SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success") << std::endl;
- if (timer) {
- timer->stop();
- timer.reset();
- }
- currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
- if (error) {
- currentConnection.reset();
- if (!addressQueryResults.empty()) {
- tryNextAddress();
- }
- else {
- if (!serviceQueryResults.empty()) {
- serviceQueryResults.pop_front();
- }
- tryNextServiceOrFallback();
- }
- }
- else {
- finish(currentConnection);
- }
+ SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success") << std::endl;
+ if (timer) {
+ timer->stop();
+ timer.reset();
+ }
+ currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
+ if (error) {
+ currentConnection.reset();
+ if (!addressQueryResults.empty()) {
+ tryNextAddress();
+ }
+ else {
+ if (!serviceQueryResults.empty()) {
+ serviceQueryResults.pop_front();
+ }
+ tryNextServiceOrFallback();
+ }
+ }
+ else {
+ finish(currentConnection);
+ }
}
void Connector::finish(boost::shared_ptr<Connection> connection) {
- if (timer) {
- timer->stop();
- timer->onTick.disconnect(boost::bind(&Connector::handleTimeout, shared_from_this()));
- timer.reset();
- }
- if (serviceQuery) {
- serviceQuery->onResult.disconnect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
- serviceQuery.reset();
- }
- if (addressQuery) {
- addressQuery->onResult.disconnect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2));
- addressQuery.reset();
- }
- if (currentConnection) {
- currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
- currentConnection.reset();
- }
- onConnectFinished(connection, (connection || foundSomeDNS) ? boost::shared_ptr<Error>() : boost::make_shared<DomainNameResolveError>());
+ if (timer) {
+ timer->stop();
+ timer->onTick.disconnect(boost::bind(&Connector::handleTimeout, shared_from_this()));
+ timer.reset();
+ }
+ if (serviceQuery) {
+ serviceQuery->onResult.disconnect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
+ serviceQuery.reset();
+ }
+ if (addressQuery) {
+ addressQuery->onResult.disconnect(boost::bind(&Connector::handleAddressQueryResult, shared_from_this(), _1, _2));
+ addressQuery.reset();
+ }
+ if (currentConnection) {
+ currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection.reset();
+ }
+ onConnectFinished(connection, (connection || foundSomeDNS) ? boost::shared_ptr<Error>() : boost::make_shared<DomainNameResolveError>());
}
void Connector::handleTimeout() {
- SWIFT_LOG(debug) << "Timeout" << std::endl;
- handleConnectionConnectFinished(true);
+ SWIFT_LOG(debug) << "Timeout" << std::endl;
+ handleConnectionConnectFinished(true);
}
}
diff --git a/Swiften/Network/Connector.h b/Swiften/Network/Connector.h
index 3ed76fa..52486b6 100644
--- a/Swiften/Network/Connector.h
+++ b/Swiften/Network/Connector.h
@@ -21,61 +21,61 @@
#include <Swiften/Network/Timer.h>
namespace Swift {
- class DomainNameAddressQuery;
- class DomainNameResolver;
- class ConnectionFactory;
- class TimerFactory;
+ class DomainNameAddressQuery;
+ class DomainNameResolver;
+ class ConnectionFactory;
+ class TimerFactory;
- class SWIFTEN_API Connector : public boost::bsignals::trackable, public boost::enable_shared_from_this<Connector> {
- public:
- typedef boost::shared_ptr<Connector> ref;
+ class SWIFTEN_API Connector : public boost::bsignals::trackable, public boost::enable_shared_from_this<Connector> {
+ public:
+ typedef boost::shared_ptr<Connector> ref;
- static Connector::ref create(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) {
- return ref(new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory));
- }
+ static Connector::ref create(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) {
+ return ref(new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory));
+ }
- void setTimeoutMilliseconds(int milliseconds);
- /**
- * Start the connection attempt.
- * Note that after calling this method, the caller is responsible for calling #stop()
- * if it wants to cancel it. Not doing so can leak references.
- */
- void start();
- void stop();
+ void setTimeoutMilliseconds(int milliseconds);
+ /**
+ * Start the connection attempt.
+ * Note that after calling this method, the caller is responsible for calling #stop()
+ * if it wants to cancel it. Not doing so can leak references.
+ */
+ void start();
+ void stop();
- boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished;
+ boost::signal<void (boost::shared_ptr<Connection>, boost::shared_ptr<Error>)> onConnectFinished;
- private:
- Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*);
+ private:
+ Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*);
- void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result);
- void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error);
- void queryAddress(const std::string& hostname);
+ void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result);
+ void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error);
+ void queryAddress(const std::string& hostname);
- void tryNextServiceOrFallback();
- void tryNextAddress();
- void tryConnect(const HostAddressPort& target);
+ void tryNextServiceOrFallback();
+ void tryNextAddress();
+ void tryConnect(const HostAddressPort& target);
- void handleConnectionConnectFinished(bool error);
- void finish(boost::shared_ptr<Connection>);
- void handleTimeout();
+ void handleConnectionConnectFinished(bool error);
+ void finish(boost::shared_ptr<Connection>);
+ void handleTimeout();
- private:
- std::string hostname;
- int port;
- boost::optional<std::string> serviceLookupPrefix;
- DomainNameResolver* resolver;
- ConnectionFactory* connectionFactory;
- TimerFactory* timerFactory;
- int timeoutMilliseconds;
- boost::shared_ptr<Timer> timer;
- boost::shared_ptr<DomainNameServiceQuery> serviceQuery;
- std::deque<DomainNameServiceQuery::Result> serviceQueryResults;
- boost::shared_ptr<DomainNameAddressQuery> addressQuery;
- std::deque<HostAddress> addressQueryResults;
- bool queriedAllServices;
- boost::shared_ptr<Connection> currentConnection;
- bool foundSomeDNS;
- };
+ private:
+ std::string hostname;
+ int port;
+ boost::optional<std::string> serviceLookupPrefix;
+ DomainNameResolver* resolver;
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+ int timeoutMilliseconds;
+ boost::shared_ptr<Timer> timer;
+ boost::shared_ptr<DomainNameServiceQuery> serviceQuery;
+ std::deque<DomainNameServiceQuery::Result> serviceQueryResults;
+ boost::shared_ptr<DomainNameAddressQuery> addressQuery;
+ std::deque<HostAddress> addressQueryResults;
+ bool queriedAllServices;
+ boost::shared_ptr<Connection> currentConnection;
+ bool foundSomeDNS;
+ };
}
diff --git a/Swiften/Network/DomainNameAddressQuery.h b/Swiften/Network/DomainNameAddressQuery.h
index 7b4b9b0..10bcd5a 100644
--- a/Swiften/Network/DomainNameAddressQuery.h
+++ b/Swiften/Network/DomainNameAddressQuery.h
@@ -14,14 +14,14 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class DomainNameAddressQuery {
- public:
- typedef boost::shared_ptr<DomainNameAddressQuery> ref;
+ class DomainNameAddressQuery {
+ public:
+ typedef boost::shared_ptr<DomainNameAddressQuery> ref;
- virtual ~DomainNameAddressQuery();
+ virtual ~DomainNameAddressQuery();
- virtual void run() = 0;
+ virtual void run() = 0;
- boost::signal<void (const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>)> onResult;
- };
+ boost::signal<void (const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>)> onResult;
+ };
}
diff --git a/Swiften/Network/DomainNameResolveError.h b/Swiften/Network/DomainNameResolveError.h
index c788537..f231f9a 100644
--- a/Swiften/Network/DomainNameResolveError.h
+++ b/Swiften/Network/DomainNameResolveError.h
@@ -10,8 +10,8 @@
#include <Swiften/Base/Error.h>
namespace Swift {
- class SWIFTEN_API DomainNameResolveError : public Error {
- public:
- DomainNameResolveError() {}
- };
+ class SWIFTEN_API DomainNameResolveError : public Error {
+ public:
+ DomainNameResolveError() {}
+ };
}
diff --git a/Swiften/Network/DomainNameResolver.h b/Swiften/Network/DomainNameResolver.h
index e398774..97997c9 100644
--- a/Swiften/Network/DomainNameResolver.h
+++ b/Swiften/Network/DomainNameResolver.h
@@ -13,15 +13,15 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class DomainNameServiceQuery;
- class DomainNameAddressQuery;
-
+ class DomainNameServiceQuery;
+ class DomainNameAddressQuery;
- class SWIFTEN_API DomainNameResolver {
- public:
- virtual ~DomainNameResolver();
- virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) = 0;
- virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name) = 0;
- };
+ class SWIFTEN_API DomainNameResolver {
+ public:
+ virtual ~DomainNameResolver();
+
+ virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) = 0;
+ virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name) = 0;
+ };
}
diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp
index 4410ed9..708bbce 100644
--- a/Swiften/Network/DomainNameServiceQuery.cpp
+++ b/Swiften/Network/DomainNameServiceQuery.cpp
@@ -22,11 +22,11 @@ using namespace Swift;
namespace lambda = boost::lambda;
namespace {
- struct ResultPriorityComparator {
- bool operator()(const DomainNameServiceQuery::Result& a, const DomainNameServiceQuery::Result& b) const {
- return a.priority < b.priority;
- }
- };
+ struct ResultPriorityComparator {
+ bool operator()(const DomainNameServiceQuery::Result& a, const DomainNameServiceQuery::Result& b) const {
+ return a.priority < b.priority;
+ }
+ };
}
namespace Swift {
@@ -35,31 +35,31 @@ DomainNameServiceQuery::~DomainNameServiceQuery() {
}
void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator) {
- ResultPriorityComparator comparator;
- std::stable_sort(queries.begin(), queries.end(), comparator);
+ ResultPriorityComparator comparator;
+ std::stable_sort(queries.begin(), queries.end(), comparator);
- std::vector<DomainNameServiceQuery::Result>::iterator i = queries.begin();
- while (i != queries.end()) {
- std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator);
- if (std::distance(i, next) > 1) {
- std::vector<int> weights;
- std::transform(i, next, std::back_inserter(weights),
- /* easy hack to account for '0' weights getting at least some weight */
- lambda::bind(&Result::weight, lambda::_1) + 1);
- for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) {
- std::vector<int> cumulativeWeights;
- std::partial_sum(
- weights.begin() + j,
- weights.end(),
- std::back_inserter(cumulativeWeights));
- int randomNumber = generator.generateRandomInteger(cumulativeWeights.back());
- BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin());
- std::swap(i[j], i[j + selectedIndex]);
- std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]);
- }
- }
- i = next;
- }
+ std::vector<DomainNameServiceQuery::Result>::iterator i = queries.begin();
+ while (i != queries.end()) {
+ std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator);
+ if (std::distance(i, next) > 1) {
+ std::vector<int> weights;
+ std::transform(i, next, std::back_inserter(weights),
+ /* easy hack to account for '0' weights getting at least some weight */
+ lambda::bind(&Result::weight, lambda::_1) + 1);
+ for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) {
+ std::vector<int> cumulativeWeights;
+ std::partial_sum(
+ weights.begin() + j,
+ weights.end(),
+ std::back_inserter(cumulativeWeights));
+ int randomNumber = generator.generateRandomInteger(cumulativeWeights.back());
+ BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin());
+ std::swap(i[j], i[j + selectedIndex]);
+ std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]);
+ }
+ }
+ i = next;
+ }
}
diff --git a/Swiften/Network/DomainNameServiceQuery.h b/Swiften/Network/DomainNameServiceQuery.h
index 240ae4e..acbccf0 100644
--- a/Swiften/Network/DomainNameServiceQuery.h
+++ b/Swiften/Network/DomainNameServiceQuery.h
@@ -17,25 +17,25 @@
#include <Swiften/Network/DomainNameResolveError.h>
namespace Swift {
- class RandomGenerator;
+ class RandomGenerator;
- class SWIFTEN_API DomainNameServiceQuery {
- public:
- typedef boost::shared_ptr<DomainNameServiceQuery> ref;
+ class SWIFTEN_API DomainNameServiceQuery {
+ public:
+ typedef boost::shared_ptr<DomainNameServiceQuery> ref;
- struct Result {
- Result(const std::string& hostname = "", int port = -1, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {}
- std::string hostname;
- int port;
- int priority;
- int weight;
- };
+ struct Result {
+ Result(const std::string& hostname = "", int port = -1, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {}
+ std::string hostname;
+ int port;
+ int priority;
+ int weight;
+ };
- virtual ~DomainNameServiceQuery();
+ virtual ~DomainNameServiceQuery();
- virtual void run() = 0;
- static void sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator);
+ virtual void run() = 0;
+ static void sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator);
- boost::signal<void (const std::vector<Result>&)> onResult;
- };
+ boost::signal<void (const std::vector<Result>&)> onResult;
+ };
}
diff --git a/Swiften/Network/DummyConnection.cpp b/Swiften/Network/DummyConnection.cpp
index 53f3db7..a4e5419 100644
--- a/Swiften/Network/DummyConnection.cpp
+++ b/Swiften/Network/DummyConnection.cpp
@@ -17,15 +17,15 @@ DummyConnection::DummyConnection(EventLoop* eventLoop) : eventLoop(eventLoop) {
}
void DummyConnection::receive(const SafeByteArray& data) {
- eventLoop->postEvent(boost::bind(boost::ref(onDataRead), boost::make_shared<SafeByteArray>(data)), shared_from_this());
+ eventLoop->postEvent(boost::bind(boost::ref(onDataRead), boost::make_shared<SafeByteArray>(data)), shared_from_this());
}
void DummyConnection::listen() {
- assert(false);
+ assert(false);
}
void DummyConnection::connect(const HostAddressPort&) {
- assert(false);
+ assert(false);
}
diff --git a/Swiften/Network/DummyConnection.h b/Swiften/Network/DummyConnection.h
index edc2473..fcfdb15 100644
--- a/Swiften/Network/DummyConnection.h
+++ b/Swiften/Network/DummyConnection.h
@@ -15,36 +15,36 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API DummyConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<DummyConnection> {
- public:
- DummyConnection(EventLoop* eventLoop);
+ class SWIFTEN_API DummyConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<DummyConnection> {
+ public:
+ DummyConnection(EventLoop* eventLoop);
- void listen();
- void connect(const HostAddressPort&);
+ void listen();
+ void connect(const HostAddressPort&);
- void disconnect() {
- //assert(false);
- }
+ void disconnect() {
+ //assert(false);
+ }
- void write(const SafeByteArray& data) {
- eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
- onDataSent(data);
- }
+ void write(const SafeByteArray& data) {
+ eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
+ onDataSent(data);
+ }
- void receive(const SafeByteArray& data);
+ void receive(const SafeByteArray& data);
- HostAddressPort getLocalAddress() const {
- return localAddress;
- }
+ HostAddressPort getLocalAddress() const {
+ return localAddress;
+ }
- HostAddressPort getRemoteAddress() const {
- return remoteAddress;
- }
+ HostAddressPort getRemoteAddress() const {
+ return remoteAddress;
+ }
- boost::signal<void (const SafeByteArray&)> onDataSent;
+ boost::signal<void (const SafeByteArray&)> onDataSent;
- EventLoop* eventLoop;
- HostAddressPort localAddress;
- HostAddressPort remoteAddress;
- };
+ EventLoop* eventLoop;
+ HostAddressPort localAddress;
+ HostAddressPort remoteAddress;
+ };
}
diff --git a/Swiften/Network/DummyConnectionFactory.h b/Swiften/Network/DummyConnectionFactory.h
index e8a294e..f861312 100644
--- a/Swiften/Network/DummyConnectionFactory.h
+++ b/Swiften/Network/DummyConnectionFactory.h
@@ -17,13 +17,13 @@ class EventLoop;
class DummyConnectionFactory : public ConnectionFactory {
public:
- DummyConnectionFactory(EventLoop *eventLoop) : eventLoop(eventLoop) {}
- virtual ~DummyConnectionFactory() {}
- virtual boost::shared_ptr<Connection> createConnection() {
- return boost::make_shared<DummyConnection>(eventLoop);
- }
+ DummyConnectionFactory(EventLoop *eventLoop) : eventLoop(eventLoop) {}
+ virtual ~DummyConnectionFactory() {}
+ virtual boost::shared_ptr<Connection> createConnection() {
+ return boost::make_shared<DummyConnection>(eventLoop);
+ }
private:
- EventLoop* eventLoop;
+ EventLoop* eventLoop;
};
}
diff --git a/Swiften/Network/DummyConnectionServer.h b/Swiften/Network/DummyConnectionServer.h
index 1195cad..0bf7386 100644
--- a/Swiften/Network/DummyConnectionServer.h
+++ b/Swiften/Network/DummyConnectionServer.h
@@ -15,29 +15,29 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API DummyConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<DummyConnectionServer> {
- public:
- DummyConnectionServer(EventLoop* /*eventLoop*/, int port) : localAddressPort(HostAddress(), port) {}
- DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, int port) : localAddressPort(hostAddress, port) {}
- virtual ~DummyConnectionServer() {}
+ class SWIFTEN_API DummyConnectionServer : public ConnectionServer, public EventOwner, public boost::enable_shared_from_this<DummyConnectionServer> {
+ public:
+ DummyConnectionServer(EventLoop* /*eventLoop*/, int port) : localAddressPort(HostAddress(), port) {}
+ DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, int port) : localAddressPort(hostAddress, port) {}
+ virtual ~DummyConnectionServer() {}
- virtual HostAddressPort getAddressPort() const {
- return localAddressPort;
- }
+ virtual HostAddressPort getAddressPort() const {
+ return localAddressPort;
+ }
- virtual boost::optional<Error> tryStart() {
- return boost::optional<Error>();
- }
+ virtual boost::optional<Error> tryStart() {
+ return boost::optional<Error>();
+ }
- virtual void start() {
+ virtual void start() {
- }
+ }
- virtual void stop() {
+ virtual void stop() {
- }
+ }
- private:
- HostAddressPort localAddressPort;
- };
+ private:
+ HostAddressPort localAddressPort;
+ };
}
diff --git a/Swiften/Network/DummyConnectionServerFactory.h b/Swiften/Network/DummyConnectionServerFactory.h
index 6369452..0952a38 100644
--- a/Swiften/Network/DummyConnectionServerFactory.h
+++ b/Swiften/Network/DummyConnectionServerFactory.h
@@ -17,19 +17,19 @@ class EventLoop;
class DummyConnectionServerFactory : public ConnectionServerFactory {
public:
- DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {}
- virtual ~DummyConnectionServerFactory() {}
+ DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {}
+ virtual ~DummyConnectionServerFactory() {}
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) {
- return boost::make_shared<DummyConnectionServer>(eventLoop, port);
- }
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port) {
+ return boost::make_shared<DummyConnectionServer>(eventLoop, port);
+ }
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) {
- return boost::make_shared<DummyConnectionServer>(eventLoop, hostAddress, port);
- }
+ virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) {
+ return boost::make_shared<DummyConnectionServer>(eventLoop, hostAddress, port);
+ }
private:
- EventLoop* eventLoop;
+ EventLoop* eventLoop;
};
}
diff --git a/Swiften/Network/DummyTimerFactory.cpp b/Swiften/Network/DummyTimerFactory.cpp
index 6967e92..cae5c84 100644
--- a/Swiften/Network/DummyTimerFactory.cpp
+++ b/Swiften/Network/DummyTimerFactory.cpp
@@ -14,27 +14,27 @@
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;
+ 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;
};
@@ -42,19 +42,19 @@ DummyTimerFactory::DummyTimerFactory() : currentTime(0) {
}
boost::shared_ptr<Timer> DummyTimerFactory::createTimer(int milliseconds) {
- boost::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this));
- timers.push_back(timer);
- return timer;
+ boost::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this));
+ timers.push_back(timer);
+ return timer;
}
void DummyTimerFactory::setTime(int time) {
- assert(time > currentTime);
- foreach(boost::shared_ptr<DummyTimer> timer, timers) {
- if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) {
- timer->onTick();
- }
- }
- currentTime = time;
+ assert(time > currentTime);
+ foreach(boost::shared_ptr<DummyTimer> timer, timers) {
+ if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) {
+ timer->onTick();
+ }
+ }
+ currentTime = time;
}
}
diff --git a/Swiften/Network/DummyTimerFactory.h b/Swiften/Network/DummyTimerFactory.h
index 2f2ba43..bb2f813 100644
--- a/Swiften/Network/DummyTimerFactory.h
+++ b/Swiften/Network/DummyTimerFactory.h
@@ -12,18 +12,18 @@
#include <Swiften/Network/TimerFactory.h>
namespace Swift {
- class SWIFTEN_API DummyTimerFactory : public TimerFactory {
- public:
- class DummyTimer;
+ class SWIFTEN_API DummyTimerFactory : public TimerFactory {
+ public:
+ class DummyTimer;
- DummyTimerFactory();
+ DummyTimerFactory();
- virtual boost::shared_ptr<Timer> createTimer(int milliseconds);
- void setTime(int time);
+ virtual boost::shared_ptr<Timer> createTimer(int milliseconds);
+ void setTime(int time);
- private:
- friend class DummyTimer;
- int currentTime;
- std::list<boost::shared_ptr<DummyTimer> > timers;
- };
+ private:
+ friend class DummyTimer;
+ int currentTime;
+ std::list<boost::shared_ptr<DummyTimer> > timers;
+ };
}
diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp
index b61a73f..aa8027f 100644
--- a/Swiften/Network/EnvironmentProxyProvider.cpp
+++ b/Swiften/Network/EnvironmentProxyProvider.cpp
@@ -22,35 +22,35 @@
namespace Swift {
EnvironmentProxyProvider::EnvironmentProxyProvider() {
- socksProxy = getFromEnv("all_proxy", "socks");
- httpProxy = getFromEnv("http_proxy", "http");
- SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl;
+ socksProxy = getFromEnv("all_proxy", "socks");
+ httpProxy = getFromEnv("http_proxy", "http");
+ SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl;
}
HostAddressPort EnvironmentProxyProvider::getHTTPConnectProxy() const {
- return httpProxy;
+ return httpProxy;
}
HostAddressPort EnvironmentProxyProvider::getSOCKS5Proxy() const {
- return socksProxy;
+ return socksProxy;
}
HostAddressPort EnvironmentProxyProvider::getFromEnv(const char* envVarName, std::string proxyProtocol) {
- char* envVar = NULL;
- std::string address;
- int port = 0;
+ char* envVar = NULL;
+ std::string address;
+ int port = 0;
- envVar = getenv(envVarName);
+ envVar = getenv(envVarName);
- proxyProtocol += "://";
- address = envVar != NULL ? envVar : "0.0.0.0";
- if(envVar != NULL && address.compare(0, proxyProtocol.length(), proxyProtocol) == 0) {
- address = address.substr(proxyProtocol.length(), address.length());
- port = atoi(address.substr(address.find(':') + 1, address.length()).c_str());
- address = address.substr(0, address.find(':'));
- }
+ proxyProtocol += "://";
+ address = envVar != NULL ? envVar : "0.0.0.0";
+ if(envVar != NULL && address.compare(0, proxyProtocol.length(), proxyProtocol) == 0) {
+ address = address.substr(proxyProtocol.length(), address.length());
+ port = atoi(address.substr(address.find(':') + 1, address.length()).c_str());
+ address = address.substr(0, address.find(':'));
+ }
- return HostAddressPort(HostAddress(address), port);
+ return HostAddressPort(HostAddress(address), port);
}
}
diff --git a/Swiften/Network/EnvironmentProxyProvider.h b/Swiften/Network/EnvironmentProxyProvider.h
index 0afad9d..59463ff 100644
--- a/Swiften/Network/EnvironmentProxyProvider.h
+++ b/Swiften/Network/EnvironmentProxyProvider.h
@@ -16,16 +16,16 @@
#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
- class SWIFTEN_API EnvironmentProxyProvider : public ProxyProvider {
- public:
- EnvironmentProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
- private:
- HostAddressPort getFromEnv(const char* envVarName, std::string proxyProtocol);
- HostAddressPort socksProxy;
- HostAddressPort httpProxy;
- };
+ class SWIFTEN_API EnvironmentProxyProvider : public ProxyProvider {
+ public:
+ EnvironmentProxyProvider();
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
+ private:
+ HostAddressPort getFromEnv(const char* envVarName, std::string proxyProtocol);
+ HostAddressPort socksProxy;
+ HostAddressPort httpProxy;
+ };
}
diff --git a/Swiften/Network/FakeConnection.cpp b/Swiften/Network/FakeConnection.cpp
index dc19e4b..82b792a 100644
--- a/Swiften/Network/FakeConnection.cpp
+++ b/Swiften/Network/FakeConnection.cpp
@@ -17,48 +17,48 @@ FakeConnection::~FakeConnection() {
}
void FakeConnection::listen() {
- assert(false);
+ assert(false);
}
void FakeConnection::setError(const Error& e) {
- error = boost::optional<Error>(e);
- state = DisconnectedWithError;
- if (connectedTo) {
- eventLoop->postEvent(
- boost::bind(boost::ref(onDisconnected), error),
- shared_from_this());
- }
+ error = boost::optional<Error>(e);
+ state = DisconnectedWithError;
+ if (connectedTo) {
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onDisconnected), error),
+ shared_from_this());
+ }
}
void FakeConnection::connect(const HostAddressPort& address) {
- if (delayConnect) {
- state = Connecting;
- }
- else {
- if (!error) {
- connectedTo = address;
- state = Connected;
- }
- else {
- state = DisconnectedWithError;
- }
- eventLoop->postEvent(
- boost::bind(boost::ref(onConnectFinished), error ? true : false),
- shared_from_this());
- }
+ if (delayConnect) {
+ state = Connecting;
+ }
+ else {
+ if (!error) {
+ connectedTo = address;
+ state = Connected;
+ }
+ else {
+ state = DisconnectedWithError;
+ }
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onConnectFinished), error ? true : false),
+ shared_from_this());
+ }
}
void FakeConnection::disconnect() {
- if (!error) {
- state = Disconnected;
- }
- else {
- state = DisconnectedWithError;
- }
- connectedTo.reset();
- eventLoop->postEvent(
- boost::bind(boost::ref(onDisconnected), error),
- shared_from_this());
+ if (!error) {
+ state = Disconnected;
+ }
+ else {
+ state = DisconnectedWithError;
+ }
+ connectedTo.reset();
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onDisconnected), error),
+ shared_from_this());
}
}
diff --git a/Swiften/Network/FakeConnection.h b/Swiften/Network/FakeConnection.h
index ec62ad7..c7d1f27 100644
--- a/Swiften/Network/FakeConnection.h
+++ b/Swiften/Network/FakeConnection.h
@@ -18,47 +18,47 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API FakeConnection :
- public Connection,
- public EventOwner,
- public boost::enable_shared_from_this<FakeConnection> {
- public:
- enum State {
- Initial,
- Connecting,
- Connected,
- Disconnected,
- DisconnectedWithError
- };
+ class SWIFTEN_API FakeConnection :
+ public Connection,
+ public EventOwner,
+ public boost::enable_shared_from_this<FakeConnection> {
+ public:
+ enum State {
+ Initial,
+ Connecting,
+ Connected,
+ Disconnected,
+ DisconnectedWithError
+ };
- FakeConnection(EventLoop* eventLoop);
- virtual ~FakeConnection();
+ FakeConnection(EventLoop* eventLoop);
+ virtual ~FakeConnection();
- virtual void listen();
- virtual HostAddressPort getLocalAddress() const {
- return HostAddressPort();
- }
- virtual HostAddressPort getRemoteAddress() const {
- return HostAddressPort();
- }
+ virtual void listen();
+ virtual HostAddressPort getLocalAddress() const {
+ return HostAddressPort();
+ }
+ virtual HostAddressPort getRemoteAddress() const {
+ return HostAddressPort();
+ }
- void setError(const Error& e);
- virtual void connect(const HostAddressPort& address);
- virtual void disconnect();
+ void setError(const Error& e);
+ virtual void connect(const HostAddressPort& address);
+ virtual void disconnect();
- virtual void write(const SafeByteArray& data) {
- dataWritten.push_back(data);
- }
+ virtual void write(const SafeByteArray& data) {
+ dataWritten.push_back(data);
+ }
- void setDelayConnect() {
- delayConnect = true;
- }
+ void setDelayConnect() {
+ delayConnect = true;
+ }
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> connectedTo;
- std::vector<SafeByteArray> dataWritten;
- boost::optional<Error> error;
- State state;
- bool delayConnect;
- };
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> connectedTo;
+ std::vector<SafeByteArray> dataWritten;
+ boost::optional<Error> error;
+ State state;
+ bool delayConnect;
+ };
}
diff --git a/Swiften/Network/GConfProxyProvider.cpp b/Swiften/Network/GConfProxyProvider.cpp
index ed9be3c..35303d5 100644
--- a/Swiften/Network/GConfProxyProvider.cpp
+++ b/Swiften/Network/GConfProxyProvider.cpp
@@ -24,43 +24,43 @@
namespace Swift {
GConfProxyProvider::GConfProxyProvider() {
- // Ensure static GLib initialization methods are called
- static bool glibInitialized = false;
- if (!glibInitialized) {
- g_type_init();
- glibInitialized = true;
- }
-
- socksProxy = getFromGConf("/system/proxy/socks_host", "/system/proxy/socks_port");
- httpProxy = getFromGConf("/system/http_proxy/host", "/system/http_proxy/port");
- SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl;
+ // Ensure static GLib initialization methods are called
+ static bool glibInitialized = false;
+ if (!glibInitialized) {
+ g_type_init();
+ glibInitialized = true;
+ }
+
+ socksProxy = getFromGConf("/system/proxy/socks_host", "/system/proxy/socks_port");
+ httpProxy = getFromGConf("/system/http_proxy/host", "/system/http_proxy/port");
+ SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl;
}
HostAddressPort GConfProxyProvider::getHTTPConnectProxy() const {
- return httpProxy;
+ return httpProxy;
}
HostAddressPort GConfProxyProvider::getSOCKS5Proxy() const {
- return socksProxy;
+ return socksProxy;
}
HostAddressPort GConfProxyProvider::getFromGConf(const char* gcHost, const char* gcPort) {
- std::string address;
- int port = 0;
- gchar* str;
+ std::string address;
+ int port = 0;
+ gchar* str;
- GConfClient* client = gconf_client_get_default();
+ GConfClient* client = gconf_client_get_default();
- str = gconf_client_get_string(client, gcHost, NULL);
- port = static_cast<int> (gconf_client_get_int(client, gcPort, NULL));
+ str = gconf_client_get_string(client, gcHost, NULL);
+ port = static_cast<int> (gconf_client_get_int(client, gcPort, NULL));
- if(str) {
- address = static_cast<char*> (str);
- g_free(str);
- }
+ if(str) {
+ address = static_cast<char*> (str);
+ g_free(str);
+ }
- g_object_unref(client);
- return HostAddressPort(HostAddress(address), port);
+ g_object_unref(client);
+ return HostAddressPort(HostAddress(address), port);
}
}
diff --git a/Swiften/Network/GConfProxyProvider.h b/Swiften/Network/GConfProxyProvider.h
index 31f38a9..826a67b 100644
--- a/Swiften/Network/GConfProxyProvider.h
+++ b/Swiften/Network/GConfProxyProvider.h
@@ -9,16 +9,16 @@
#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
- class GConfProxyProvider : public ProxyProvider {
- public:
- GConfProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
- private:
- HostAddressPort getFromGConf(const char* gcHost, const char* gcPort);
- HostAddressPort socksProxy;
- HostAddressPort httpProxy;
- };
+ class GConfProxyProvider : public ProxyProvider {
+ public:
+ GConfProxyProvider();
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
+ private:
+ HostAddressPort getFromGConf(const char* gcHost, const char* gcPort);
+ HostAddressPort socksProxy;
+ HostAddressPort httpProxy;
+ };
}
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp
index 3ed2ac5..991e815 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp
@@ -33,16 +33,16 @@
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) {
+ 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() {
@@ -50,116 +50,116 @@ HTTPConnectProxiedConnection::~HTTPConnectProxiedConnection() {
}
void HTTPConnectProxiedConnection::setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter) {
- trafficFilter_ = 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_) {
- 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);
+ 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_) {
+ 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)));
- }
- }
+ 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) {
- request << field.first << ":" << field.second << "\r\n";
- }
- request << "\r\n";
- write(createSafeByteArray(request.str()));
+ typedef std::pair<std::string, std::string> HTTPHeaderField;
+ std::stringstream request;
+
+ request << statusLine << "\r\n";
+ foreach (const HTTPHeaderField& field, headerFields) {
+ request << field.first << ":" << field.second << "\r\n";
+ }
+ request << "\r\n";
+ write(createSafeByteArray(request.str()));
}
void HTTPConnectProxiedConnection::handleProxyInitializeData(boost::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;
- return;
- }
- }
-
- std::vector<std::string> tmp = String::split(statusLine, ' ');
- if (tmp.size() > 1) {
- try {
- int status = boost::lexical_cast<int>(tmp[1]);
- SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl;
- if (status / 100 == 2) { // all 2XX states are OK
- setProxyInitializeFinished(true);
- }
- else {
- SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_ << std::endl;
- setProxyInitializeFinished(false);
- }
- }
- catch (boost::bad_lexical_cast&) {
- SWIFT_LOG(warning) << "Unexpected response: " << tmp[1] << std::endl;
- setProxyInitializeFinished(false);
- }
- }
- else {
- setProxyInitializeFinished(false);
- }
- httpResponseBuffer_.clear();
+ 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;
+ return;
+ }
+ }
+
+ std::vector<std::string> tmp = String::split(statusLine, ' ');
+ if (tmp.size() > 1) {
+ try {
+ int status = boost::lexical_cast<int>(tmp[1]);
+ SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl;
+ if (status / 100 == 2) { // all 2XX states are OK
+ setProxyInitializeFinished(true);
+ }
+ else {
+ SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_ << std::endl;
+ setProxyInitializeFinished(false);
+ }
+ }
+ catch (boost::bad_lexical_cast&) {
+ SWIFT_LOG(warning) << "Unexpected response: " << tmp[1] << std::endl;
+ setProxyInitializeFinished(false);
+ }
+ }
+ else {
+ setProxyInitializeFinished(false);
+ }
+ httpResponseBuffer_.clear();
}
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.h b/Swiften/Network/HTTPConnectProxiedConnection.h
index 24f36b9..adb8d08 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.h
+++ b/Swiften/Network/HTTPConnectProxiedConnection.h
@@ -19,38 +19,38 @@
#include <Swiften/Network/ProxiedConnection.h>
namespace Swift {
- class ConnectionFactory;
- class DomainNameResolver;
- class EventLoop;
- class HTTPTrafficFilter;
- class TimerFactory;
+ class ConnectionFactory;
+ class DomainNameResolver;
+ class EventLoop;
+ class HTTPTrafficFilter;
+ class TimerFactory;
- class SWIFTEN_API HTTPConnectProxiedConnection : public ProxiedConnection {
- public:
- typedef boost::shared_ptr<HTTPConnectProxiedConnection> ref;
+ class SWIFTEN_API HTTPConnectProxiedConnection : public ProxiedConnection {
+ public:
+ typedef boost::shared_ptr<HTTPConnectProxiedConnection> ref;
- virtual ~HTTPConnectProxiedConnection();
+ virtual ~HTTPConnectProxiedConnection();
- static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword) {
- return ref(new HTTPConnectProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, authID, authPassword));
- }
+ static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword) {
+ return ref(new HTTPConnectProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, authID, authPassword));
+ }
- void setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter);
+ void setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter);
- private:
- HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword);
+ private:
+ HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword);
- virtual void initializeProxy();
- virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data);
+ virtual void initializeProxy();
+ virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data);
- void sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields);
- void parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields);
+ void sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields);
+ void parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields);
- private:
- SafeByteArray authID_;
- SafeByteArray authPassword_;
- boost::shared_ptr<HTTPTrafficFilter> trafficFilter_;
- std::string httpResponseBuffer_;
- std::vector<std::pair<std::string, std::string> > nextHTTPRequestHeaders_;
- };
+ private:
+ SafeByteArray authID_;
+ SafeByteArray authPassword_;
+ boost::shared_ptr<HTTPTrafficFilter> trafficFilter_;
+ std::string httpResponseBuffer_;
+ std::vector<std::pair<std::string, std::string> > nextHTTPRequestHeaders_;
+ };
}
diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp
index 91b241e..735791f 100644
--- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp
@@ -24,9 +24,9 @@ HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainN
}
boost::shared_ptr<Connection> HTTPConnectProxiedConnectionFactory::createConnection() {
- HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_);
- proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_);
- return proxyConnection;
+ HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_);
+ proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_);
+ return proxyConnection;
}
}
diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h
index 05e9447..455fba0 100644
--- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h
+++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h
@@ -18,26 +18,26 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class DomainNameResolver;
- class TimerFactory;
- class EventLoop;
- class HTTPTrafficFilter;
+ class DomainNameResolver;
+ class TimerFactory;
+ class EventLoop;
+ class HTTPTrafficFilter;
- class SWIFTEN_API HTTPConnectProxiedConnectionFactory : public ConnectionFactory {
- public:
- HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
- HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
+ class SWIFTEN_API HTTPConnectProxiedConnectionFactory : public ConnectionFactory {
+ public:
+ HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
+ HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = boost::shared_ptr<HTTPTrafficFilter>());
- virtual boost::shared_ptr<Connection> createConnection();
+ virtual boost::shared_ptr<Connection> createConnection();
- private:
- DomainNameResolver* resolver_;
- ConnectionFactory* connectionFactory_;
- TimerFactory* timerFactory_;
- std::string proxyHost_;
- int proxyPort_;
- SafeString authID_;
- SafeString authPassword_;
- boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_;
- };
+ private:
+ DomainNameResolver* resolver_;
+ ConnectionFactory* connectionFactory_;
+ TimerFactory* timerFactory_;
+ std::string proxyHost_;
+ int proxyPort_;
+ SafeString authID_;
+ SafeString authPassword_;
+ boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_;
+ };
}
diff --git a/Swiften/Network/HTTPTrafficFilter.h b/Swiften/Network/HTTPTrafficFilter.h
index cc1af21..5c29bd6 100644
--- a/Swiften/Network/HTTPTrafficFilter.h
+++ b/Swiften/Network/HTTPTrafficFilter.h
@@ -17,15 +17,15 @@
namespace Swift {
class SWIFTEN_API HTTPTrafficFilter {
- public:
- virtual ~HTTPTrafficFilter();
- /**
- * @brief This method is called by the HTTPConnectPRoxiedConnection on every incoming HTTP response.
- * It can be used to insert additional HTTP requests into the HTTP CONNECT proxy initalization process.
- * @return A vector of HTTP header fields to use in a new request. If an empty vector is returned,
- * no new request will be send and the normal proxy logic continues.
- */
- virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& /* responseHeader */) = 0;
+ public:
+ virtual ~HTTPTrafficFilter();
+ /**
+ * @brief This method is called by the HTTPConnectPRoxiedConnection on every incoming HTTP response.
+ * It can be used to insert additional HTTP requests into the HTTP CONNECT proxy initalization process.
+ * @return A vector of HTTP header fields to use in a new request. If an empty vector is returned,
+ * no new request will be send and the normal proxy logic continues.
+ */
+ virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& /* responseHeader */) = 0;
};
}
diff --git a/Swiften/Network/HostAddress.cpp b/Swiften/Network/HostAddress.cpp
index ae1a008..64a4ff6 100644
--- a/Swiften/Network/HostAddress.cpp
+++ b/Swiften/Network/HostAddress.cpp
@@ -25,48 +25,48 @@ HostAddress::HostAddress() {
}
HostAddress::HostAddress(const std::string& address) {
- try {
- address_ = boost::asio::ip::address::from_string(address);
- }
- catch (const std::exception&) {
- }
+ try {
+ address_ = boost::asio::ip::address::from_string(address);
+ }
+ catch (const std::exception&) {
+ }
}
HostAddress::HostAddress(const unsigned char* address, size_t length) {
- assert(length == 4 || length == 16);
- if (length == 4) {
- boost::asio::ip::address_v4::bytes_type data;
- for (size_t i = 0; i < length; ++i) {
- data[i] = address[i];
- }
- address_ = boost::asio::ip::address(boost::asio::ip::address_v4(data));
- }
- else {
- boost::asio::ip::address_v6::bytes_type data;
- for (size_t i = 0; i < length; ++i) {
- data[i] = address[i];
- }
- address_ = boost::asio::ip::address(boost::asio::ip::address_v6(data));
- }
+ assert(length == 4 || length == 16);
+ if (length == 4) {
+ boost::asio::ip::address_v4::bytes_type data;
+ for (size_t i = 0; i < length; ++i) {
+ data[i] = address[i];
+ }
+ address_ = boost::asio::ip::address(boost::asio::ip::address_v4(data));
+ }
+ else {
+ boost::asio::ip::address_v6::bytes_type data;
+ for (size_t i = 0; i < length; ++i) {
+ data[i] = address[i];
+ }
+ address_ = boost::asio::ip::address(boost::asio::ip::address_v6(data));
+ }
}
HostAddress::HostAddress(const boost::asio::ip::address& address) : address_(address) {
}
std::string HostAddress::toString() const {
- return address_.to_string();
+ return address_.to_string();
}
bool HostAddress::isValid() const {
- return !(address_.is_v4() && address_.to_v4().to_ulong() == 0);
+ return !(address_.is_v4() && address_.to_v4().to_ulong() == 0);
}
boost::asio::ip::address HostAddress::getRawAddress() const {
- return address_;
+ return address_;
}
bool HostAddress::isLocalhost() const {
- return address_ == localhost4 || address_ == localhost6;
+ return address_ == localhost4 || address_ == localhost6;
}
}
diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h
index 91c3e73..00fe9bf 100644
--- a/Swiften/Network/HostAddress.h
+++ b/Swiften/Network/HostAddress.h
@@ -12,24 +12,24 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API HostAddress {
- public:
- HostAddress();
- HostAddress(const std::string&);
- HostAddress(const unsigned char* address, size_t length);
- HostAddress(const boost::asio::ip::address& address);
-
- std::string toString() const;
- boost::asio::ip::address getRawAddress() const;
-
- bool operator==(const HostAddress& o) const {
- return address_ == o.address_;
- }
-
- bool isValid() const;
- bool isLocalhost() const;
-
- private:
- boost::asio::ip::address address_;
- };
+ class SWIFTEN_API HostAddress {
+ public:
+ HostAddress();
+ HostAddress(const std::string&);
+ HostAddress(const unsigned char* address, size_t length);
+ HostAddress(const boost::asio::ip::address& address);
+
+ std::string toString() const;
+ boost::asio::ip::address getRawAddress() const;
+
+ bool operator==(const HostAddress& o) const {
+ return address_ == o.address_;
+ }
+
+ bool isValid() const;
+ bool isLocalhost() const;
+
+ private:
+ boost::asio::ip::address address_;
+ };
}
diff --git a/Swiften/Network/HostAddressPort.cpp b/Swiften/Network/HostAddressPort.cpp
index 3229761..a73b2ad 100644
--- a/Swiften/Network/HostAddressPort.cpp
+++ b/Swiften/Network/HostAddressPort.cpp
@@ -14,10 +14,10 @@ HostAddressPort::HostAddressPort(const HostAddress& address, int port) : address
}
HostAddressPort::HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint) {
- address_ = HostAddress(endpoint.address());
- port_ = endpoint.port();
+ address_ = HostAddress(endpoint.address());
+ port_ = endpoint.port();
}
std::string HostAddressPort::toString() const {
- return getAddress().toString() + ":" + boost::lexical_cast<std::string>(getPort());
+ return getAddress().toString() + ":" + boost::lexical_cast<std::string>(getPort());
}
diff --git a/Swiften/Network/HostAddressPort.h b/Swiften/Network/HostAddressPort.h
index f06d4a5..e42e1d1 100644
--- a/Swiften/Network/HostAddressPort.h
+++ b/Swiften/Network/HostAddressPort.h
@@ -12,31 +12,31 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class SWIFTEN_API HostAddressPort {
- public:
- HostAddressPort(const HostAddress& address = HostAddress(), int port = -1);
- HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint);
-
- const HostAddress& getAddress() const {
- return address_;
- }
-
- int getPort() const {
- return port_;
- }
-
- bool operator==(const HostAddressPort& o) const {
- return address_ == o.address_ && port_ == o.port_;
- }
-
- bool isValid() const {
- return address_.isValid() && port_ > 0;
- }
-
- std::string toString() const;
-
- private:
- HostAddress address_;
- int port_;
- };
+ class SWIFTEN_API HostAddressPort {
+ public:
+ HostAddressPort(const HostAddress& address = HostAddress(), int port = -1);
+ HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint);
+
+ const HostAddress& getAddress() const {
+ return address_;
+ }
+
+ int getPort() const {
+ return port_;
+ }
+
+ bool operator==(const HostAddressPort& o) const {
+ return address_ == o.address_ && port_ == o.port_;
+ }
+
+ bool isValid() const {
+ return address_.isValid() && port_ > 0;
+ }
+
+ std::string toString() const;
+
+ private:
+ HostAddress address_;
+ int port_;
+ };
}
diff --git a/Swiften/Network/HostNameOrAddress.cpp b/Swiften/Network/HostNameOrAddress.cpp
index 8b6e5c5..5c5e5e0 100644
--- a/Swiften/Network/HostNameOrAddress.cpp
+++ b/Swiften/Network/HostNameOrAddress.cpp
@@ -9,21 +9,21 @@
using namespace Swift;
namespace {
- struct ToStringVisitor : public boost::static_visitor<std::string> {
- std::string operator()(const HostAddress& address) const {
- return address.toString();
- }
-
- std::string operator()(const std::string & str) const {
- return str;
- }
- };
+ struct ToStringVisitor : public boost::static_visitor<std::string> {
+ std::string operator()(const HostAddress& address) const {
+ return address.toString();
+ }
+
+ std::string operator()(const std::string & str) const {
+ return str;
+ }
+ };
}
namespace Swift {
std::string toString(const HostNameOrAddress& address) {
- return boost::apply_visitor(ToStringVisitor(), address);
+ return boost::apply_visitor(ToStringVisitor(), address);
}
}
diff --git a/Swiften/Network/HostNameOrAddress.h b/Swiften/Network/HostNameOrAddress.h
index d6ef439..81c0995 100644
--- a/Swiften/Network/HostNameOrAddress.h
+++ b/Swiften/Network/HostNameOrAddress.h
@@ -12,7 +12,7 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- typedef boost::variant<std::string, HostAddress> HostNameOrAddress;
+ typedef boost::variant<std::string, HostAddress> HostNameOrAddress;
- std::string toString(const HostNameOrAddress& address);
+ std::string toString(const HostNameOrAddress& address);
}
diff --git a/Swiften/Network/MacOSXProxyProvider.cpp b/Swiften/Network/MacOSXProxyProvider.cpp
index a489add..858d568 100644
--- a/Swiften/Network/MacOSXProxyProvider.cpp
+++ b/Swiften/Network/MacOSXProxyProvider.cpp
@@ -29,49 +29,49 @@ using namespace Swift;
#ifndef SWIFTEN_PLATFORM_IPHONE
static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabledKey, CFStringRef hostKey, CFStringRef portKey) {
- CFNumberRef numberValue = NULL;
- HostAddressPort ret = HostAddressPort(HostAddress(), 0);
-
- if(CFDictionaryGetValueIfPresent(dict, reinterpret_cast<const void*> (enabledKey), reinterpret_cast<const void**> (&numberValue)) == true) {
- const int i = 0;
- CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i);
- CFComparisonResult result = CFNumberCompare(numberValue, zero, NULL);
- CFRelease(zero);
-
- if(result != kCFCompareEqualTo) {
- int port = 0;
- std::string host = "";
-
- try {
- CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey));
- if(numberValue != NULL) {
- CFNumberGetValue(numberValue, kCFNumberIntType, &port);
- }
-
- CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey));
- if(stringValue != NULL) {
- std::vector<char> buffer;
- // length must be +1 for the ending zero; and the Docu of CFStringGetCString tells it like
- // if the string is toby the length must be at least 5.
- CFIndex length = CFStringGetLength(stringValue) + 1;
- buffer.resize(boost::numeric_cast<size_t>(length));
- if(CFStringGetCString(stringValue, &buffer[0], length, kCFStringEncodingMacRoman)) {
- for(std::vector<char>::iterator iter = buffer.begin(); iter != buffer.end(); ++iter) {
- host += *iter;
- }
- }
- }
- }
- catch(...) {
- std::cerr << "Exception caught ... " << std::endl;
- }
-
- if(host != "" && port != 0) {
- ret = HostAddressPort(HostAddress(host), port);
- }
- }
- }
- return ret;
+ CFNumberRef numberValue = NULL;
+ HostAddressPort ret = HostAddressPort(HostAddress(), 0);
+
+ if(CFDictionaryGetValueIfPresent(dict, reinterpret_cast<const void*> (enabledKey), reinterpret_cast<const void**> (&numberValue)) == true) {
+ const int i = 0;
+ CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i);
+ CFComparisonResult result = CFNumberCompare(numberValue, zero, NULL);
+ CFRelease(zero);
+
+ if(result != kCFCompareEqualTo) {
+ int port = 0;
+ std::string host = "";
+
+ try {
+ CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey));
+ if(numberValue != NULL) {
+ CFNumberGetValue(numberValue, kCFNumberIntType, &port);
+ }
+
+ CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey));
+ if(stringValue != NULL) {
+ std::vector<char> buffer;
+ // length must be +1 for the ending zero; and the Docu of CFStringGetCString tells it like
+ // if the string is toby the length must be at least 5.
+ CFIndex length = CFStringGetLength(stringValue) + 1;
+ buffer.resize(boost::numeric_cast<size_t>(length));
+ if(CFStringGetCString(stringValue, &buffer[0], length, kCFStringEncodingMacRoman)) {
+ for(std::vector<char>::iterator iter = buffer.begin(); iter != buffer.end(); ++iter) {
+ host += *iter;
+ }
+ }
+ }
+ }
+ catch(...) {
+ std::cerr << "Exception caught ... " << std::endl;
+ }
+
+ if(host != "" && port != 0) {
+ ret = HostAddressPort(HostAddress(host), port);
+ }
+ }
+ }
+ return ret;
}
#endif
namespace Swift {
@@ -80,27 +80,27 @@ MacOSXProxyProvider::MacOSXProxyProvider() {
}
HostAddressPort MacOSXProxyProvider::getHTTPConnectProxy() const {
- HostAddressPort result;
+ HostAddressPort result;
#ifndef SWIFTEN_PLATFORM_IPHONE
- CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL);
- if(proxies != NULL) {
- result = getFromDictionary(proxies, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort);
- CFRelease(proxies);
- }
+ CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL);
+ if(proxies != NULL) {
+ result = getFromDictionary(proxies, kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort);
+ CFRelease(proxies);
+ }
#endif
- return result;
+ return result;
}
HostAddressPort MacOSXProxyProvider::getSOCKS5Proxy() const {
- HostAddressPort result;
+ HostAddressPort result;
#ifndef SWIFTEN_PLATFORM_IPHONE
- CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL);
- if(proxies != NULL) {
- result = getFromDictionary(proxies, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort);
- CFRelease(proxies);
- }
+ CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL);
+ if(proxies != NULL) {
+ result = getFromDictionary(proxies, kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort);
+ CFRelease(proxies);
+ }
#endif
- return result;
+ return result;
}
}
diff --git a/Swiften/Network/MacOSXProxyProvider.h b/Swiften/Network/MacOSXProxyProvider.h
index 53a7760..56ffd9f 100644
--- a/Swiften/Network/MacOSXProxyProvider.h
+++ b/Swiften/Network/MacOSXProxyProvider.h
@@ -17,10 +17,10 @@
#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
- class MacOSXProxyProvider : public ProxyProvider {
- public:
- MacOSXProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
- };
+ class MacOSXProxyProvider : public ProxyProvider {
+ public:
+ MacOSXProxyProvider();
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
+ };
}
diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp
index 3ca2ec4..3da6572 100644
--- a/Swiften/Network/MiniUPnPInterface.cpp
+++ b/Swiften/Network/MiniUPnPInterface.cpp
@@ -24,94 +24,94 @@
namespace Swift {
struct MiniUPnPInterface::Private {
- bool isValid;
- std::string localAddress;
- UPNPDev* deviceList;
- UPNPUrls urls;
- IGDdatas data;
+ bool isValid;
+ std::string localAddress;
+ UPNPDev* deviceList;
+ UPNPUrls urls;
+ IGDdatas data;
};
MiniUPnPInterface::MiniUPnPInterface() : p(boost::make_shared<Private>()) {
- p->isValid = false;
- int error = 0;
- p->deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error);
- if (!p->deviceList) {
- return;
- }
-
- char lanAddress[64];
- if (!UPNP_GetValidIGD(p->deviceList, &p->urls, &p->data, lanAddress, sizeof(lanAddress))) {
- return;
- }
- p->localAddress = std::string(lanAddress);
- p->isValid = true;
+ p->isValid = false;
+ int error = 0;
+ p->deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error);
+ if (!p->deviceList) {
+ return;
+ }
+
+ char lanAddress[64];
+ if (!UPNP_GetValidIGD(p->deviceList, &p->urls, &p->data, lanAddress, sizeof(lanAddress))) {
+ return;
+ }
+ p->localAddress = std::string(lanAddress);
+ p->isValid = true;
}
MiniUPnPInterface::~MiniUPnPInterface() {
- if (p->isValid) {
- FreeUPNPUrls(&p->urls);
- }
- freeUPNPDevlist(p->deviceList);
+ if (p->isValid) {
+ FreeUPNPUrls(&p->urls);
+ }
+ freeUPNPDevlist(p->deviceList);
}
boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() {
- if (!p->isValid) {
- return boost::optional<HostAddress>();
- }
- char externalIPAddress[40];
- int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress);
- if (ret != UPNPCOMMAND_SUCCESS) {
- return boost::optional<HostAddress>();
- }
- else {
- return HostAddress(std::string(externalIPAddress));
- }
+ if (!p->isValid) {
+ return boost::optional<HostAddress>();
+ }
+ char externalIPAddress[40];
+ int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress);
+ if (ret != UPNPCOMMAND_SUCCESS) {
+ return boost::optional<HostAddress>();
+ }
+ else {
+ return HostAddress(std::string(externalIPAddress));
+ }
}
boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(int actualLocalPort, int actualPublicPort) {
- if (!p->isValid) {
- return boost::optional<NATPortMapping>();
- }
-
- NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP);
-
- std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort());
- std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort());
- std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds());
-
- int ret = UPNP_AddPortMapping(
- p->urls.controlURL,
- p->data.first.servicetype,
- publicPort.c_str(),
- localPort.c_str(),
- p->localAddress.c_str(),
- "Swift",
- mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP",
- 0,
- leaseSeconds.c_str());
- if (ret == UPNPCOMMAND_SUCCESS) {
- return mapping;
- }
- else {
- return boost::optional<NATPortMapping>();
- }
+ if (!p->isValid) {
+ return boost::optional<NATPortMapping>();
+ }
+
+ NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP);
+
+ std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort());
+ std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort());
+ std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds());
+
+ int ret = UPNP_AddPortMapping(
+ p->urls.controlURL,
+ p->data.first.servicetype,
+ publicPort.c_str(),
+ localPort.c_str(),
+ p->localAddress.c_str(),
+ "Swift",
+ mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP",
+ 0,
+ leaseSeconds.c_str());
+ if (ret == UPNPCOMMAND_SUCCESS) {
+ return mapping;
+ }
+ else {
+ return boost::optional<NATPortMapping>();
+ }
}
bool MiniUPnPInterface::removePortForward(const NATPortMapping& mapping) {
- if (!p->isValid) {
- return false;
- }
+ if (!p->isValid) {
+ return false;
+ }
- std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort());
- std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort());
- std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds());
+ std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort());
+ std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort());
+ std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds());
- int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", 0);
- return ret == UPNPCOMMAND_SUCCESS;
+ int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", 0);
+ return ret == UPNPCOMMAND_SUCCESS;
}
bool MiniUPnPInterface::isAvailable() {
- return p->isValid;
+ return p->isValid;
}
}
diff --git a/Swiften/Network/MiniUPnPInterface.h b/Swiften/Network/MiniUPnPInterface.h
index 46e45e5..5253e71 100644
--- a/Swiften/Network/MiniUPnPInterface.h
+++ b/Swiften/Network/MiniUPnPInterface.h
@@ -14,19 +14,19 @@
#include <Swiften/Network/NATTraversalInterface.h>
namespace Swift {
- class MiniUPnPInterface : public NATTraversalInterface, boost::noncopyable {
- public:
- MiniUPnPInterface();
- virtual ~MiniUPnPInterface();
+ class MiniUPnPInterface : public NATTraversalInterface, boost::noncopyable {
+ public:
+ MiniUPnPInterface();
+ virtual ~MiniUPnPInterface();
- virtual bool isAvailable();
+ virtual bool isAvailable();
- boost::optional<HostAddress> getPublicIP();
- boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort);
- bool removePortForward(const NATPortMapping&);
+ boost::optional<HostAddress> getPublicIP();
+ boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort);
+ bool removePortForward(const NATPortMapping&);
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp
index e84d6ec..4818170 100644
--- a/Swiften/Network/NATPMPInterface.cpp
+++ b/Swiften/Network/NATPMPInterface.cpp
@@ -26,117 +26,117 @@
namespace Swift {
struct NATPMPInterface::Private {
- natpmp_t natpmp;
+ natpmp_t natpmp;
};
NATPMPInterface::NATPMPInterface() : p(boost::make_shared<Private>()) {
- initnatpmp(&p->natpmp, 0, 0);
+ initnatpmp(&p->natpmp, 0, 0);
}
NATPMPInterface::~NATPMPInterface() {
- closenatpmp(&p->natpmp);
+ closenatpmp(&p->natpmp);
}
bool NATPMPInterface::isAvailable() {
- return getPublicIP() ? true : false;
+ return getPublicIP() ? true : false;
}
boost::optional<HostAddress> NATPMPInterface::getPublicIP() {
- if (sendpublicaddressrequest(&p->natpmp) < 0) {
- SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl;
- return boost::optional<HostAddress>();
- }
-
- int r = 0;
- natpmpresp_t response;
- do {
- fd_set fds;
- struct timeval timeout;
- FD_ZERO(&fds);
- FD_SET(p->natpmp.s, &fds);
- getnatpmprequesttimeout(&p->natpmp, &timeout);
-
- // Limit NAT-PMP timeout to ten seconds.
- timeout.tv_sec = 10;
- timeout.tv_usec = 0;
-
- select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
- r = readnatpmpresponseorretry(&p->natpmp, &response);
- } while (false /*r == NATPMP_TRYAGAIN*/);
-
- if (r == 0) {
- return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4));
- }
- else {
- SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
- return boost::optional<HostAddress>();
- }
+ if (sendpublicaddressrequest(&p->natpmp) < 0) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl;
+ return boost::optional<HostAddress>();
+ }
+
+ int r = 0;
+ natpmpresp_t response;
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(p->natpmp.s, &fds);
+ getnatpmprequesttimeout(&p->natpmp, &timeout);
+
+ // Limit NAT-PMP timeout to ten seconds.
+ timeout.tv_sec = 10;
+ timeout.tv_usec = 0;
+
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&p->natpmp, &response);
+ } while (false /*r == NATPMP_TRYAGAIN*/);
+
+ if (r == 0) {
+ return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4));
+ }
+ else {
+ SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
+ return boost::optional<HostAddress>();
+ }
}
boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, int publicPort) {
- NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP);
- if (sendnewportmappingrequest(
- &p->natpmp,
- mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP,
- boost::numeric_cast<uint16_t>(mapping.getLocalPort()),
- boost::numeric_cast<uint16_t>(mapping.getPublicPort()),
- boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) {
- SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl;
- return boost::optional<NATPortMapping>();
- }
-
- int r = 0;
- natpmpresp_t response;
- do {
- fd_set fds;
- struct timeval timeout;
- FD_ZERO(&fds);
- FD_SET(p->natpmp.s, &fds);
- getnatpmprequesttimeout(&p->natpmp, &timeout);
-
- // Limit NAT-PMP timeout to ten seconds.
- timeout.tv_sec = 10;
- timeout.tv_usec = 0;
-
- select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
- r = readnatpmpresponseorretry(&p->natpmp, &response);
- } while(false /*r == NATPMP_TRYAGAIN*/);
-
- if (r == 0) {
- NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime));
- return result;
- }
- else {
- SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl;
- return boost::optional<NATPortMapping>();
- }
+ NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP);
+ if (sendnewportmappingrequest(
+ &p->natpmp,
+ mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP,
+ boost::numeric_cast<uint16_t>(mapping.getLocalPort()),
+ boost::numeric_cast<uint16_t>(mapping.getPublicPort()),
+ boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl;
+ return boost::optional<NATPortMapping>();
+ }
+
+ int r = 0;
+ natpmpresp_t response;
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(p->natpmp.s, &fds);
+ getnatpmprequesttimeout(&p->natpmp, &timeout);
+
+ // Limit NAT-PMP timeout to ten seconds.
+ timeout.tv_sec = 10;
+ timeout.tv_usec = 0;
+
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&p->natpmp, &response);
+ } while(false /*r == NATPMP_TRYAGAIN*/);
+
+ if (r == 0) {
+ NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime));
+ return result;
+ }
+ else {
+ SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl;
+ return boost::optional<NATPortMapping>();
+ }
}
bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) {
- if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) {
- SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl;
- return false;
- }
-
- int r = 0;
- natpmpresp_t response;
- do {
- fd_set fds;
- struct timeval timeout;
- FD_ZERO(&fds);
- FD_SET(p->natpmp.s, &fds);
- getnatpmprequesttimeout(&p->natpmp, &timeout);
- select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
- r = readnatpmpresponseorretry(&p->natpmp, &response);
- } while(r == NATPMP_TRYAGAIN);
-
- if (r == 0) {
- return true;
- }
- else {
- SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl;
- return false;
- }
+ if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl;
+ return false;
+ }
+
+ int r = 0;
+ natpmpresp_t response;
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(p->natpmp.s, &fds);
+ getnatpmprequesttimeout(&p->natpmp, &timeout);
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&p->natpmp, &response);
+ } while(r == NATPMP_TRYAGAIN);
+
+ if (r == 0) {
+ return true;
+ }
+ else {
+ SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl;
+ return false;
+ }
}
diff --git a/Swiften/Network/NATPMPInterface.h b/Swiften/Network/NATPMPInterface.h
index 467ee5c..a4bb816 100644
--- a/Swiften/Network/NATPMPInterface.h
+++ b/Swiften/Network/NATPMPInterface.h
@@ -14,19 +14,19 @@
#include <Swiften/Network/NATTraversalInterface.h>
namespace Swift {
- class NATPMPInterface : public NATTraversalInterface, boost::noncopyable {
- public:
- NATPMPInterface();
- virtual ~NATPMPInterface();
+ class NATPMPInterface : public NATTraversalInterface, boost::noncopyable {
+ public:
+ NATPMPInterface();
+ virtual ~NATPMPInterface();
- virtual bool isAvailable();
+ virtual bool isAvailable();
- virtual boost::optional<HostAddress> getPublicIP();
- virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort);
- virtual bool removePortForward(const NATPortMapping&);
+ virtual boost::optional<HostAddress> getPublicIP();
+ virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort);
+ virtual bool removePortForward(const NATPortMapping&);
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Network/NATPortMapping.h b/Swiften/Network/NATPortMapping.h
index 3ddf39e..ff8fde3 100644
--- a/Swiften/Network/NATPortMapping.h
+++ b/Swiften/Network/NATPortMapping.h
@@ -16,38 +16,38 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class SWIFTEN_API NATPortMapping {
- public:
- enum Protocol {
- TCP,
- UDP
- };
-
- NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) :
- publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) {
-
- }
-
- int getPublicPort() const {
- return publicPort;
- }
-
- int getLocalPort() const {
- return localPort;
- }
-
- Protocol getProtocol() const {
- return protocol;
- }
-
- int getLeaseInSeconds() const {
- return leaseInSeconds;
- }
-
- private:
- int publicPort;
- int localPort;
- Protocol protocol;
- int leaseInSeconds;
- };
+ class SWIFTEN_API NATPortMapping {
+ public:
+ enum Protocol {
+ TCP,
+ UDP
+ };
+
+ NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) :
+ publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) {
+
+ }
+
+ int getPublicPort() const {
+ return publicPort;
+ }
+
+ int getLocalPort() const {
+ return localPort;
+ }
+
+ Protocol getProtocol() const {
+ return protocol;
+ }
+
+ int getLeaseInSeconds() const {
+ return leaseInSeconds;
+ }
+
+ private:
+ int publicPort;
+ int localPort;
+ Protocol protocol;
+ int leaseInSeconds;
+ };
}
diff --git a/Swiften/Network/NATTraversalForwardPortRequest.h b/Swiften/Network/NATTraversalForwardPortRequest.h
index 155d30b..0565b4c 100644
--- a/Swiften/Network/NATTraversalForwardPortRequest.h
+++ b/Swiften/Network/NATTraversalForwardPortRequest.h
@@ -17,13 +17,13 @@
#include <Swiften/Network/NATPortMapping.h>
namespace Swift {
- class SWIFTEN_API NATTraversalForwardPortRequest {
- public:
- virtual ~NATTraversalForwardPortRequest();
+ class SWIFTEN_API NATTraversalForwardPortRequest {
+ public:
+ virtual ~NATTraversalForwardPortRequest();
- virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void start() = 0;
+ virtual void stop() = 0;
- boost::signal<void (boost::optional<NATPortMapping>)> onResult;
- };
+ boost::signal<void (boost::optional<NATPortMapping>)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraversalGetPublicIPRequest.h b/Swiften/Network/NATTraversalGetPublicIPRequest.h
index 725afd2..8cdc067 100644
--- a/Swiften/Network/NATTraversalGetPublicIPRequest.h
+++ b/Swiften/Network/NATTraversalGetPublicIPRequest.h
@@ -17,13 +17,13 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class SWIFTEN_API NATTraversalGetPublicIPRequest {
- public:
- virtual ~NATTraversalGetPublicIPRequest();
+ class SWIFTEN_API NATTraversalGetPublicIPRequest {
+ public:
+ virtual ~NATTraversalGetPublicIPRequest();
- virtual void start() = 0;
- virtual void stop() = 0;
+ virtual void start() = 0;
+ virtual void stop() = 0;
- boost::signal<void (boost::optional<HostAddress>)> onResult;
- };
+ boost::signal<void (boost::optional<HostAddress>)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraversalInterface.h b/Swiften/Network/NATTraversalInterface.h
index 4e5f5fc..ea9ed6a 100644
--- a/Swiften/Network/NATTraversalInterface.h
+++ b/Swiften/Network/NATTraversalInterface.h
@@ -12,14 +12,14 @@
#include <Swiften/Network/NATPortMapping.h>
namespace Swift {
- class SWIFTEN_API NATTraversalInterface {
- public:
- virtual ~NATTraversalInterface();
+ class SWIFTEN_API NATTraversalInterface {
+ public:
+ virtual ~NATTraversalInterface();
- virtual bool isAvailable() = 0;
+ virtual bool isAvailable() = 0;
- virtual boost::optional<HostAddress> getPublicIP() = 0;
- virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort) = 0;
- virtual bool removePortForward(const NATPortMapping&) = 0;
- };
+ virtual boost::optional<HostAddress> getPublicIP() = 0;
+ virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort) = 0;
+ virtual bool removePortForward(const NATPortMapping&) = 0;
+ };
}
diff --git a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h
index efbf6ea..8200197 100644
--- a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h
+++ b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h
@@ -17,26 +17,26 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class SWIFTEN_API NATTraversalRemovePortForwardingRequest {
- public:
- struct PortMapping {
- enum Protocol {
- TCP,
- UDP
- };
-
- unsigned int publicPort;
- unsigned int localPort;
- Protocol protocol;
- unsigned long leaseInSeconds;
- };
-
- public:
- virtual ~NATTraversalRemovePortForwardingRequest();
-
- virtual void start() = 0;
- virtual void stop() = 0;
-
- boost::signal<void (boost::optional<bool> /* failure */)> onResult;
- };
+ class SWIFTEN_API NATTraversalRemovePortForwardingRequest {
+ public:
+ struct PortMapping {
+ enum Protocol {
+ TCP,
+ UDP
+ };
+
+ unsigned int publicPort;
+ unsigned int localPort;
+ Protocol protocol;
+ unsigned long leaseInSeconds;
+ };
+
+ public:
+ virtual ~NATTraversalRemovePortForwardingRequest();
+
+ virtual void start() = 0;
+ virtual void stop() = 0;
+
+ boost::signal<void (boost::optional<bool> /* failure */)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraverser.h b/Swiften/Network/NATTraverser.h
index e86704a..0ff6bb3 100644
--- a/Swiften/Network/NATTraverser.h
+++ b/Swiften/Network/NATTraverser.h
@@ -11,16 +11,16 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class NATTraversalGetPublicIPRequest;
- class NATTraversalForwardPortRequest;
- class NATTraversalRemovePortForwardingRequest;
+ class NATTraversalGetPublicIPRequest;
+ class NATTraversalForwardPortRequest;
+ class NATTraversalRemovePortForwardingRequest;
- class SWIFTEN_API NATTraverser {
- public:
- virtual ~NATTraverser();
+ class SWIFTEN_API NATTraverser {
+ public:
+ virtual ~NATTraverser();
- virtual boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0;
- virtual boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0;
- virtual boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0;
- };
+ virtual boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0;
+ virtual boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0;
+ virtual boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0;
+ };
}
diff --git a/Swiften/Network/NetworkEnvironment.cpp b/Swiften/Network/NetworkEnvironment.cpp
index dff310e..19f727c 100644
--- a/Swiften/Network/NetworkEnvironment.cpp
+++ b/Swiften/Network/NetworkEnvironment.cpp
@@ -16,17 +16,17 @@ NetworkEnvironment::~NetworkEnvironment() {
}
HostAddress NetworkEnvironment::getLocalAddress() const {
- std::vector<NetworkInterface> networkInterfaces = getNetworkInterfaces();
- foreach (const NetworkInterface& iface, networkInterfaces) {
- if (!iface.isLoopback()) {
- foreach (const HostAddress& address, iface.getAddresses()) {
- if (address.getRawAddress().is_v4()) {
- return address;
- }
- }
- }
- }
- return HostAddress();
+ std::vector<NetworkInterface> networkInterfaces = getNetworkInterfaces();
+ foreach (const NetworkInterface& iface, networkInterfaces) {
+ if (!iface.isLoopback()) {
+ foreach (const HostAddress& address, iface.getAddresses()) {
+ if (address.getRawAddress().is_v4()) {
+ return address;
+ }
+ }
+ }
+ }
+ return HostAddress();
}
}
diff --git a/Swiften/Network/NetworkEnvironment.h b/Swiften/Network/NetworkEnvironment.h
index 36a2bde..c98a78f 100644
--- a/Swiften/Network/NetworkEnvironment.h
+++ b/Swiften/Network/NetworkEnvironment.h
@@ -13,12 +13,12 @@
#include <Swiften/Network/NetworkInterface.h>
namespace Swift {
- class SWIFTEN_API NetworkEnvironment {
- public:
- virtual ~NetworkEnvironment();
+ class SWIFTEN_API NetworkEnvironment {
+ public:
+ virtual ~NetworkEnvironment();
- virtual std::vector<NetworkInterface> getNetworkInterfaces() const = 0;
+ virtual std::vector<NetworkInterface> getNetworkInterfaces() const = 0;
- HostAddress getLocalAddress() const;
- };
+ HostAddress getLocalAddress() const;
+ };
}
diff --git a/Swiften/Network/NetworkFactories.h b/Swiften/Network/NetworkFactories.h
index 81ce0c5..7c76c67 100644
--- a/Swiften/Network/NetworkFactories.h
+++ b/Swiften/Network/NetworkFactories.h
@@ -9,38 +9,38 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class TimerFactory;
- class ConnectionFactory;
- class DomainNameResolver;
- class ConnectionServerFactory;
- class NATTraverser;
- class XMLParserFactory;
- class TLSContextFactory;
- class CertificateFactory;
- class ProxyProvider;
- class EventLoop;
- class IDNConverter;
- class NetworkEnvironment;
- class CryptoProvider;
+ class TimerFactory;
+ class ConnectionFactory;
+ class DomainNameResolver;
+ class ConnectionServerFactory;
+ class NATTraverser;
+ class XMLParserFactory;
+ class TLSContextFactory;
+ class CertificateFactory;
+ class ProxyProvider;
+ class EventLoop;
+ class IDNConverter;
+ class NetworkEnvironment;
+ class CryptoProvider;
- /**
- * An interface collecting network factories.
- */
- class SWIFTEN_API NetworkFactories {
- public:
- virtual ~NetworkFactories();
+ /**
+ * An interface collecting network factories.
+ */
+ class SWIFTEN_API NetworkFactories {
+ public:
+ virtual ~NetworkFactories();
- virtual TimerFactory* getTimerFactory() const = 0;
- virtual ConnectionFactory* getConnectionFactory() const = 0;
- virtual DomainNameResolver* getDomainNameResolver() const = 0;
- virtual ConnectionServerFactory* getConnectionServerFactory() const = 0;
- virtual NATTraverser* getNATTraverser() const = 0;
- virtual NetworkEnvironment* getNetworkEnvironment() const = 0;
- virtual XMLParserFactory* getXMLParserFactory() const = 0;
- virtual TLSContextFactory* getTLSContextFactory() const = 0;
- virtual ProxyProvider* getProxyProvider() const = 0;
- virtual EventLoop* getEventLoop() const = 0;
- virtual IDNConverter* getIDNConverter() const = 0;
- virtual CryptoProvider* getCryptoProvider() const = 0;
- };
+ virtual TimerFactory* getTimerFactory() const = 0;
+ virtual ConnectionFactory* getConnectionFactory() const = 0;
+ virtual DomainNameResolver* getDomainNameResolver() const = 0;
+ virtual ConnectionServerFactory* getConnectionServerFactory() const = 0;
+ virtual NATTraverser* getNATTraverser() const = 0;
+ virtual NetworkEnvironment* getNetworkEnvironment() const = 0;
+ virtual XMLParserFactory* getXMLParserFactory() const = 0;
+ virtual TLSContextFactory* getTLSContextFactory() const = 0;
+ virtual ProxyProvider* getProxyProvider() const = 0;
+ virtual EventLoop* getEventLoop() const = 0;
+ virtual IDNConverter* getIDNConverter() const = 0;
+ virtual CryptoProvider* getCryptoProvider() const = 0;
+ };
}
diff --git a/Swiften/Network/NetworkInterface.h b/Swiften/Network/NetworkInterface.h
index 0c1ba07..91aefc4 100644
--- a/Swiften/Network/NetworkInterface.h
+++ b/Swiften/Network/NetworkInterface.h
@@ -18,30 +18,30 @@
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class SWIFTEN_API NetworkInterface {
- public:
- NetworkInterface(const std::string& name, bool loopback) : name(name), loopback(loopback) {
- }
-
- void addAddress(const HostAddress& address) {
- addresses.push_back(address);
- }
-
- const std::vector<HostAddress>& getAddresses() const {
- return addresses;
- }
-
- const std::string& getName() const {
- return name;
- }
-
- bool isLoopback() const {
- return loopback;
- }
-
- private:
- std::string name;
- bool loopback;
- std::vector<HostAddress> addresses;
- };
+ class SWIFTEN_API NetworkInterface {
+ public:
+ NetworkInterface(const std::string& name, bool loopback) : name(name), loopback(loopback) {
+ }
+
+ void addAddress(const HostAddress& address) {
+ addresses.push_back(address);
+ }
+
+ const std::vector<HostAddress>& getAddresses() const {
+ return addresses;
+ }
+
+ const std::string& getName() const {
+ return name;
+ }
+
+ bool isLoopback() const {
+ return loopback;
+ }
+
+ private:
+ std::string name;
+ bool loopback;
+ std::vector<HostAddress> addresses;
+ };
}
diff --git a/Swiften/Network/NullNATTraversalInterface.h b/Swiften/Network/NullNATTraversalInterface.h
index 281dca2..ecbf110 100644
--- a/Swiften/Network/NullNATTraversalInterface.h
+++ b/Swiften/Network/NullNATTraversalInterface.h
@@ -11,22 +11,22 @@
#include <Swiften/Network/NATTraversalInterface.h>
namespace Swift {
- class NullNATTraversalInterface : public NATTraversalInterface {
- public:
- virtual bool isAvailable() {
- return true;
- }
+ class NullNATTraversalInterface : public NATTraversalInterface {
+ public:
+ virtual bool isAvailable() {
+ return true;
+ }
- virtual boost::optional<HostAddress> getPublicIP() {
- return boost::optional<HostAddress>();
- }
+ virtual boost::optional<HostAddress> getPublicIP() {
+ return boost::optional<HostAddress>();
+ }
- virtual boost::optional<NATPortMapping> addPortForward(int, int) {
- return boost::optional<NATPortMapping>();
- }
+ virtual boost::optional<NATPortMapping> addPortForward(int, int) {
+ return boost::optional<NATPortMapping>();
+ }
- virtual bool removePortForward(const NATPortMapping&) {
- return false;
- }
- };
+ virtual bool removePortForward(const NATPortMapping&) {
+ return false;
+ }
+ };
}
diff --git a/Swiften/Network/NullNATTraverser.cpp b/Swiften/Network/NullNATTraverser.cpp
index 3f7b1c1..c4e121b 100644
--- a/Swiften/Network/NullNATTraverser.cpp
+++ b/Swiften/Network/NullNATTraverser.cpp
@@ -17,66 +17,66 @@
namespace Swift {
class NullNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPRequest {
- public:
- NullNATTraversalGetPublicIPRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
- }
+ public:
+ NullNATTraversalGetPublicIPRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
+ }
- virtual void start() {
- eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<HostAddress>()));
- }
+ virtual void start() {
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<HostAddress>()));
+ }
- virtual void stop() {
- }
+ virtual void stop() {
+ }
- private:
- EventLoop* eventLoop;
+ private:
+ EventLoop* eventLoop;
};
class NullNATTraversalForwardPortRequest : public NATTraversalForwardPortRequest {
- public:
- NullNATTraversalForwardPortRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
- }
+ public:
+ NullNATTraversalForwardPortRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
+ }
- virtual void start() {
- eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<NATPortMapping>()));
- }
+ virtual void start() {
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<NATPortMapping>()));
+ }
- virtual void stop() {
- }
+ virtual void stop() {
+ }
- private:
- EventLoop* eventLoop;
+ private:
+ EventLoop* eventLoop;
};
class NullNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePortForwardingRequest {
- public:
- NullNATTraversalRemovePortForwardingRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
- }
+ public:
+ NullNATTraversalRemovePortForwardingRequest(EventLoop* eventLoop) : eventLoop(eventLoop) {
+ }
- virtual void start() {
- eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<bool>(true)));
- }
+ virtual void start() {
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), boost::optional<bool>(true)));
+ }
- virtual void stop() {
- }
+ virtual void stop() {
+ }
- private:
- EventLoop* eventLoop;
+ private:
+ EventLoop* eventLoop;
};
NullNATTraverser::NullNATTraverser(EventLoop* eventLoop) : eventLoop(eventLoop) {
}
boost::shared_ptr<NATTraversalGetPublicIPRequest> NullNATTraverser::createGetPublicIPRequest() {
- return boost::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop);
+ return boost::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop);
}
boost::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(int, int) {
- return boost::make_shared<NullNATTraversalForwardPortRequest>(eventLoop);
+ return boost::make_shared<NullNATTraversalForwardPortRequest>(eventLoop);
}
boost::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(int, int) {
- return boost::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop);
+ return boost::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop);
}
}
diff --git a/Swiften/Network/NullNATTraverser.h b/Swiften/Network/NullNATTraverser.h
index 3e388d9..3492940 100644
--- a/Swiften/Network/NullNATTraverser.h
+++ b/Swiften/Network/NullNATTraverser.h
@@ -9,17 +9,17 @@
#include <Swiften/Network/NATTraverser.h>
namespace Swift {
- class EventLoop;
+ class EventLoop;
- class NullNATTraverser : public NATTraverser {
- public:
- NullNATTraverser(EventLoop* eventLoop);
+ class NullNATTraverser : public NATTraverser {
+ public:
+ NullNATTraverser(EventLoop* eventLoop);
- boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
- boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
- boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort);
+ boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
+ boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
+ boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort);
- private:
- EventLoop* eventLoop;
- };
+ private:
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/NullProxyProvider.cpp b/Swiften/Network/NullProxyProvider.cpp
index 3a04480..32a1b9d 100644
--- a/Swiften/Network/NullProxyProvider.cpp
+++ b/Swiften/Network/NullProxyProvider.cpp
@@ -12,9 +12,9 @@ NullProxyProvider::NullProxyProvider() {
}
HostAddressPort NullProxyProvider::getHTTPConnectProxy() const {
- return HostAddressPort();
+ return HostAddressPort();
}
HostAddressPort NullProxyProvider::getSOCKS5Proxy() const {
- return HostAddressPort();
+ return HostAddressPort();
}
diff --git a/Swiften/Network/NullProxyProvider.h b/Swiften/Network/NullProxyProvider.h
index 7567505..ae7aaab 100644
--- a/Swiften/Network/NullProxyProvider.h
+++ b/Swiften/Network/NullProxyProvider.h
@@ -9,11 +9,11 @@
#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
- class NullProxyProvider : public ProxyProvider {
- public:
- NullProxyProvider();
+ class NullProxyProvider : public ProxyProvider {
+ public:
+ NullProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
- };
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
+ };
}
diff --git a/Swiften/Network/PlatformDomainNameAddressQuery.cpp b/Swiften/Network/PlatformDomainNameAddressQuery.cpp
index 8b72c3b..2d72146 100644
--- a/Swiften/Network/PlatformDomainNameAddressQuery.cpp
+++ b/Swiften/Network/PlatformDomainNameAddressQuery.cpp
@@ -14,57 +14,57 @@
namespace Swift {
PlatformDomainNameAddressQuery::PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver* resolver) : PlatformDomainNameQuery(resolver), hostnameValid(false), eventLoop(eventLoop) {
- if (!!host) {
- hostname = *host;
- hostnameValid = true;
- }
+ if (!!host) {
+ hostname = *host;
+ hostnameValid = true;
+ }
}
PlatformDomainNameAddressQuery::~PlatformDomainNameAddressQuery() {
-
+
}
void PlatformDomainNameAddressQuery::run() {
- getResolver()->addQueryToQueue(shared_from_this());
+ getResolver()->addQueryToQueue(shared_from_this());
}
void PlatformDomainNameAddressQuery::runBlocking() {
- if (!hostnameValid) {
- emitError();
- return;
- }
- //std::cout << "PlatformDomainNameResolver::doRun()" << std::endl;
- boost::asio::ip::tcp::resolver resolver(ioService);
- boost::asio::ip::tcp::resolver::query query(hostname, "5222", boost::asio::ip::resolver_query_base::passive);
- try {
- //std::cout << "PlatformDomainNameResolver::doRun(): Resolving" << std::endl;
- boost::asio::ip::tcp::resolver::iterator endpointIterator = resolver.resolve(query);
- //std::cout << "PlatformDomainNameResolver::doRun(): Resolved" << std::endl;
- if (endpointIterator == boost::asio::ip::tcp::resolver::iterator()) {
- //std::cout << "PlatformDomainNameResolver::doRun(): Error 1" << std::endl;
- emitError();
- }
- else {
- std::vector<HostAddress> results;
- for ( ; endpointIterator != boost::asio::ip::tcp::resolver::iterator(); ++endpointIterator) {
- boost::asio::ip::address address = (*endpointIterator).endpoint().address();
- results.push_back(address.is_v4() ? HostAddress(&address.to_v4().to_bytes()[0], 4) : HostAddress(&address.to_v6().to_bytes()[0], 16));
- }
+ if (!hostnameValid) {
+ emitError();
+ return;
+ }
+ //std::cout << "PlatformDomainNameResolver::doRun()" << std::endl;
+ boost::asio::ip::tcp::resolver resolver(ioService);
+ boost::asio::ip::tcp::resolver::query query(hostname, "5222", boost::asio::ip::resolver_query_base::passive);
+ try {
+ //std::cout << "PlatformDomainNameResolver::doRun(): Resolving" << std::endl;
+ boost::asio::ip::tcp::resolver::iterator endpointIterator = resolver.resolve(query);
+ //std::cout << "PlatformDomainNameResolver::doRun(): Resolved" << std::endl;
+ if (endpointIterator == boost::asio::ip::tcp::resolver::iterator()) {
+ //std::cout << "PlatformDomainNameResolver::doRun(): Error 1" << std::endl;
+ emitError();
+ }
+ else {
+ std::vector<HostAddress> results;
+ for ( ; endpointIterator != boost::asio::ip::tcp::resolver::iterator(); ++endpointIterator) {
+ boost::asio::ip::address address = (*endpointIterator).endpoint().address();
+ results.push_back(address.is_v4() ? HostAddress(&address.to_v4().to_bytes()[0], 4) : HostAddress(&address.to_v6().to_bytes()[0], 16));
+ }
- //std::cout << "PlatformDomainNameResolver::doRun(): Success" << std::endl;
- eventLoop->postEvent(
- boost::bind(boost::ref(onResult), results, boost::optional<DomainNameResolveError>()),
- shared_from_this());
- }
- }
- catch (...) {
- //std::cout << "PlatformDomainNameResolver::doRun(): Error 2" << std::endl;
- emitError();
- }
+ //std::cout << "PlatformDomainNameResolver::doRun(): Success" << std::endl;
+ eventLoop->postEvent(
+ boost::bind(boost::ref(onResult), results, boost::optional<DomainNameResolveError>()),
+ shared_from_this());
+ }
+ }
+ catch (...) {
+ //std::cout << "PlatformDomainNameResolver::doRun(): Error 2" << std::endl;
+ emitError();
+ }
}
void PlatformDomainNameAddressQuery::emitError() {
- eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), shared_from_this());
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), shared_from_this());
}
}
diff --git a/Swiften/Network/PlatformDomainNameAddressQuery.h b/Swiften/Network/PlatformDomainNameAddressQuery.h
index c241f2a..a5cfda7 100644
--- a/Swiften/Network/PlatformDomainNameAddressQuery.h
+++ b/Swiften/Network/PlatformDomainNameAddressQuery.h
@@ -16,26 +16,26 @@
#include <Swiften/Network/PlatformDomainNameQuery.h>
namespace Swift {
- class PlatformDomainNameResolver;
- class EventLoop;
-
- class PlatformDomainNameAddressQuery : public DomainNameAddressQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameAddressQuery>, public EventOwner {
- public:
- PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver*);
- virtual ~PlatformDomainNameAddressQuery();
-
- void run();
-
- private:
- void runBlocking();
- void emitError();
-
- private:
- boost::asio::io_service ioService;
- std::string hostname;
- bool hostnameValid;
- EventLoop* eventLoop;
- };
+ class PlatformDomainNameResolver;
+ class EventLoop;
+
+ class PlatformDomainNameAddressQuery : public DomainNameAddressQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameAddressQuery>, public EventOwner {
+ public:
+ PlatformDomainNameAddressQuery(const boost::optional<std::string>& host, EventLoop* eventLoop, PlatformDomainNameResolver*);
+ virtual ~PlatformDomainNameAddressQuery();
+
+ void run();
+
+ private:
+ void runBlocking();
+ void emitError();
+
+ private:
+ boost::asio::io_service ioService;
+ std::string hostname;
+ bool hostnameValid;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/PlatformDomainNameQuery.h b/Swiften/Network/PlatformDomainNameQuery.h
index e8161de..3c5e152 100644
--- a/Swiften/Network/PlatformDomainNameQuery.h
+++ b/Swiften/Network/PlatformDomainNameQuery.h
@@ -9,23 +9,23 @@
#include <boost/shared_ptr.hpp>
namespace Swift {
- class PlatformDomainNameResolver;
+ class PlatformDomainNameResolver;
- class PlatformDomainNameQuery {
- public:
- typedef boost::shared_ptr<PlatformDomainNameQuery> ref;
+ class PlatformDomainNameQuery {
+ public:
+ typedef boost::shared_ptr<PlatformDomainNameQuery> ref;
- PlatformDomainNameQuery(PlatformDomainNameResolver* resolver) : resolver(resolver) {}
- virtual ~PlatformDomainNameQuery() {}
+ PlatformDomainNameQuery(PlatformDomainNameResolver* resolver) : resolver(resolver) {}
+ virtual ~PlatformDomainNameQuery() {}
- virtual void runBlocking() = 0;
+ virtual void runBlocking() = 0;
- protected:
- PlatformDomainNameResolver* getResolver() {
- return resolver;
- }
+ protected:
+ PlatformDomainNameResolver* getResolver() {
+ return resolver;
+ }
- private:
- PlatformDomainNameResolver* resolver;
- };
+ private:
+ PlatformDomainNameResolver* resolver;
+ };
}
diff --git a/Swiften/Network/PlatformDomainNameResolver.cpp b/Swiften/Network/PlatformDomainNameResolver.cpp
index 507bd37..ed08057 100644
--- a/Swiften/Network/PlatformDomainNameResolver.cpp
+++ b/Swiften/Network/PlatformDomainNameResolver.cpp
@@ -28,54 +28,54 @@ using namespace Swift;
namespace Swift {
PlatformDomainNameResolver::PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop) : idnConverter(idnConverter), eventLoop(eventLoop), stopRequested(false) {
- thread = new boost::thread(boost::bind(&PlatformDomainNameResolver::run, this));
+ thread = new boost::thread(boost::bind(&PlatformDomainNameResolver::run, this));
}
PlatformDomainNameResolver::~PlatformDomainNameResolver() {
- stopRequested = true;
- addQueryToQueue(boost::shared_ptr<PlatformDomainNameQuery>());
- thread->join();
- delete thread;
+ stopRequested = true;
+ addQueryToQueue(boost::shared_ptr<PlatformDomainNameQuery>());
+ thread->join();
+ delete thread;
}
boost::shared_ptr<DomainNameServiceQuery> PlatformDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
- boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain);
- std::string result;
- if (encodedDomain) {
- result = serviceLookupPrefix + *encodedDomain;
- }
- return boost::shared_ptr<DomainNameServiceQuery>(new PlatformDomainNameServiceQuery(result, eventLoop, this));
+ boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain);
+ std::string result;
+ if (encodedDomain) {
+ result = serviceLookupPrefix + *encodedDomain;
+ }
+ return boost::shared_ptr<DomainNameServiceQuery>(new PlatformDomainNameServiceQuery(result, eventLoop, this));
}
boost::shared_ptr<DomainNameAddressQuery> PlatformDomainNameResolver::createAddressQuery(const std::string& name) {
- return boost::shared_ptr<DomainNameAddressQuery>(new PlatformDomainNameAddressQuery(idnConverter->getIDNAEncoded(name), eventLoop, this));
+ return boost::shared_ptr<DomainNameAddressQuery>(new PlatformDomainNameAddressQuery(idnConverter->getIDNAEncoded(name), eventLoop, this));
}
void PlatformDomainNameResolver::run() {
- while (!stopRequested) {
- PlatformDomainNameQuery::ref query;
- {
- boost::unique_lock<boost::mutex> lock(queueMutex);
- while (queue.empty()) {
- queueNonEmpty.wait(lock);
- }
- query = queue.front();
- queue.pop_front();
- }
- // Check whether we don't have a non-null query (used to stop the
- // resolver)
- if (query) {
- query->runBlocking();
- }
- }
+ while (!stopRequested) {
+ PlatformDomainNameQuery::ref query;
+ {
+ boost::unique_lock<boost::mutex> lock(queueMutex);
+ while (queue.empty()) {
+ queueNonEmpty.wait(lock);
+ }
+ query = queue.front();
+ queue.pop_front();
+ }
+ // Check whether we don't have a non-null query (used to stop the
+ // resolver)
+ if (query) {
+ query->runBlocking();
+ }
+ }
}
void PlatformDomainNameResolver::addQueryToQueue(PlatformDomainNameQuery::ref query) {
- {
- boost::lock_guard<boost::mutex> lock(queueMutex);
- queue.push_back(query);
- }
- queueNonEmpty.notify_one();
+ {
+ boost::lock_guard<boost::mutex> lock(queueMutex);
+ queue.push_back(query);
+ }
+ queueNonEmpty.notify_one();
}
}
diff --git a/Swiften/Network/PlatformDomainNameResolver.h b/Swiften/Network/PlatformDomainNameResolver.h
index ae94179..95fa502 100644
--- a/Swiften/Network/PlatformDomainNameResolver.h
+++ b/Swiften/Network/PlatformDomainNameResolver.h
@@ -20,30 +20,30 @@
#include <Swiften/Network/PlatformDomainNameQuery.h>
namespace Swift {
- class IDNConverter;
- class EventLoop;
-
- class SWIFTEN_API PlatformDomainNameResolver : public DomainNameResolver {
- public:
- PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop);
- virtual ~PlatformDomainNameResolver();
-
- virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
- virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name);
-
- private:
- void run();
- void addQueryToQueue(PlatformDomainNameQuery::ref);
-
- private:
- friend class PlatformDomainNameServiceQuery;
- friend class PlatformDomainNameAddressQuery;
- IDNConverter* idnConverter;
- EventLoop* eventLoop;
- Atomic<bool> stopRequested;
- boost::thread* thread;
- std::deque<PlatformDomainNameQuery::ref> queue;
- boost::mutex queueMutex;
- boost::condition_variable queueNonEmpty;
- };
+ class IDNConverter;
+ class EventLoop;
+
+ class SWIFTEN_API PlatformDomainNameResolver : public DomainNameResolver {
+ public:
+ PlatformDomainNameResolver(IDNConverter* idnConverter, EventLoop* eventLoop);
+ virtual ~PlatformDomainNameResolver();
+
+ virtual DomainNameServiceQuery::ref createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual DomainNameAddressQuery::ref createAddressQuery(const std::string& name);
+
+ private:
+ void run();
+ void addQueryToQueue(PlatformDomainNameQuery::ref);
+
+ private:
+ friend class PlatformDomainNameServiceQuery;
+ friend class PlatformDomainNameAddressQuery;
+ IDNConverter* idnConverter;
+ EventLoop* eventLoop;
+ Atomic<bool> stopRequested;
+ boost::thread* thread;
+ std::deque<PlatformDomainNameQuery::ref> queue;
+ boost::mutex queueMutex;
+ boost::condition_variable queueNonEmpty;
+ };
}
diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
index 673aaff..71611f5 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
@@ -39,148 +39,148 @@ 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;
- }
+ if (!!serviceName) {
+ service = *serviceName;
+ serviceValid = true;
+ }
}
PlatformDomainNameServiceQuery::~PlatformDomainNameServiceQuery() {
-
+
}
void PlatformDomainNameServiceQuery::run() {
- getResolver()->addQueryToQueue(shared_from_this());
+ getResolver()->addQueryToQueue(shared_from_this());
}
void PlatformDomainNameServiceQuery::runBlocking() {
- if (!serviceValid) {
- emitError();
- return;
- }
+ if (!serviceValid) {
+ emitError();
+ return;
+ }
- SWIFT_LOG(debug) << "Querying " << service << std::endl;
+ SWIFT_LOG(debug) << "Querying " << service << std::endl;
- std::vector<DomainNameServiceQuery::Result> records;
+ std::vector<DomainNameServiceQuery::Result> records;
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- DNS_RECORD* responses;
- // FIXME: This conversion doesn't work if unicode is deffed above
- if (DnsQuery(service.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &responses, NULL) != ERROR_SUCCESS) {
- emitError();
- return;
- }
-
- DNS_RECORD* currentEntry = responses;
- while (currentEntry) {
- if (currentEntry->wType == DNS_TYPE_SRV) {
- DomainNameServiceQuery::Result record;
- record.priority = currentEntry->Data.SRV.wPriority;
- record.weight = currentEntry->Data.SRV.wWeight;
- record.port = currentEntry->Data.SRV.wPort;
-
- // The pNameTarget is actually a PCWSTR, so I would have expected this
- // conversion to not work at all, but it does.
- // Actually, it doesn't. Fix this and remove explicit cast
- // Remove unicode undef above as well
- record.hostname = std::string((const char*) currentEntry->Data.SRV.pNameTarget);
- records.push_back(record);
- }
- currentEntry = currentEntry->pNext;
- }
- DnsRecordListFree(responses, DnsFreeRecordList);
+ DNS_RECORD* responses;
+ // FIXME: This conversion doesn't work if unicode is deffed above
+ if (DnsQuery(service.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &responses, NULL) != ERROR_SUCCESS) {
+ emitError();
+ return;
+ }
+
+ DNS_RECORD* currentEntry = responses;
+ while (currentEntry) {
+ if (currentEntry->wType == DNS_TYPE_SRV) {
+ DomainNameServiceQuery::Result record;
+ record.priority = currentEntry->Data.SRV.wPriority;
+ record.weight = currentEntry->Data.SRV.wWeight;
+ record.port = currentEntry->Data.SRV.wPort;
+
+ // The pNameTarget is actually a PCWSTR, so I would have expected this
+ // conversion to not work at all, but it does.
+ // Actually, it doesn't. Fix this and remove explicit cast
+ // Remove unicode undef above as well
+ record.hostname = std::string((const char*) currentEntry->Data.SRV.pNameTarget);
+ records.push_back(record);
+ }
+ currentEntry = currentEntry->pNext;
+ }
+ DnsRecordListFree(responses, DnsFreeRecordList);
#else
- // Make sure we reinitialize the domain list every time
- res_init();
-
- ByteArray response;
- response.resize(NS_PACKETSZ);
- int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size());
- if (responseLength == -1) {
- SWIFT_LOG(debug) << "Error" << std::endl;
- emitError();
- return;
- }
-
- // Parse header
- HEADER* header = reinterpret_cast<HEADER*>(vecptr(response));
- unsigned char* messageStart = vecptr(response);
- unsigned char* messageEnd = messageStart + responseLength;
- unsigned char* currentEntry = messageStart + NS_HFIXEDSZ;
-
- // Skip over the queries
- int queriesCount = ntohs(header->qdcount);
- while (queriesCount > 0) {
- int entryLength = dn_skipname(currentEntry, messageEnd);
- if (entryLength < 0) {
- emitError();
- return;
- }
- currentEntry += entryLength + NS_QFIXEDSZ;
- queriesCount--;
- }
-
- // Process the SRV answers
- int answersCount = ntohs(header->ancount);
- while (answersCount > 0) {
- DomainNameServiceQuery::Result record;
-
- int entryLength = dn_skipname(currentEntry, messageEnd);
- currentEntry += entryLength;
- currentEntry += NS_RRFIXEDSZ;
-
- // Priority
- if (currentEntry + 2 >= messageEnd) {
- emitError();
- return;
- }
- record.priority = boost::numeric_cast<int>(ns_get16(currentEntry));
- currentEntry += 2;
-
- // Weight
- if (currentEntry + 2 >= messageEnd) {
- emitError();
- return;
- }
- record.weight = boost::numeric_cast<int>(ns_get16(currentEntry));
- currentEntry += 2;
-
- // Port
- if (currentEntry + 2 >= messageEnd) {
- emitError();
- return;
- }
- record.port = boost::numeric_cast<int>(ns_get16(currentEntry));
- currentEntry += 2;
-
- // Hostname
- if (currentEntry >= messageEnd) {
- emitError();
- return;
- }
- ByteArray entry;
- entry.resize(NS_MAXDNAME);
- entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size());
- if (entryLength < 0) {
- emitError();
- return;
- }
- record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry)));
- records.push_back(record);
- currentEntry += entryLength;
- answersCount--;
- }
+ // Make sure we reinitialize the domain list every time
+ res_init();
+
+ ByteArray response;
+ response.resize(NS_PACKETSZ);
+ int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size());
+ if (responseLength == -1) {
+ SWIFT_LOG(debug) << "Error" << std::endl;
+ emitError();
+ return;
+ }
+
+ // Parse header
+ HEADER* header = reinterpret_cast<HEADER*>(vecptr(response));
+ unsigned char* messageStart = vecptr(response);
+ unsigned char* messageEnd = messageStart + responseLength;
+ unsigned char* currentEntry = messageStart + NS_HFIXEDSZ;
+
+ // Skip over the queries
+ int queriesCount = ntohs(header->qdcount);
+ while (queriesCount > 0) {
+ int entryLength = dn_skipname(currentEntry, messageEnd);
+ if (entryLength < 0) {
+ emitError();
+ return;
+ }
+ currentEntry += entryLength + NS_QFIXEDSZ;
+ queriesCount--;
+ }
+
+ // Process the SRV answers
+ int answersCount = ntohs(header->ancount);
+ while (answersCount > 0) {
+ DomainNameServiceQuery::Result record;
+
+ int entryLength = dn_skipname(currentEntry, messageEnd);
+ currentEntry += entryLength;
+ currentEntry += NS_RRFIXEDSZ;
+
+ // Priority
+ if (currentEntry + 2 >= messageEnd) {
+ emitError();
+ return;
+ }
+ record.priority = boost::numeric_cast<int>(ns_get16(currentEntry));
+ currentEntry += 2;
+
+ // Weight
+ if (currentEntry + 2 >= messageEnd) {
+ emitError();
+ return;
+ }
+ record.weight = boost::numeric_cast<int>(ns_get16(currentEntry));
+ currentEntry += 2;
+
+ // Port
+ if (currentEntry + 2 >= messageEnd) {
+ emitError();
+ return;
+ }
+ record.port = boost::numeric_cast<int>(ns_get16(currentEntry));
+ currentEntry += 2;
+
+ // Hostname
+ if (currentEntry >= messageEnd) {
+ emitError();
+ return;
+ }
+ ByteArray entry;
+ entry.resize(NS_MAXDNAME);
+ entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size());
+ if (entryLength < 0) {
+ emitError();
+ return;
+ }
+ record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry)));
+ records.push_back(record);
+ currentEntry += entryLength;
+ answersCount--;
+ }
#endif
- BoostRandomGenerator generator;
- DomainNameServiceQuery::sortResults(records, generator);
- //std::cout << "Sending out " << records.size() << " SRV results " << std::endl;
- eventLoop->postEvent(boost::bind(boost::ref(onResult), records), shared_from_this());
+ BoostRandomGenerator generator;
+ DomainNameServiceQuery::sortResults(records, generator);
+ //std::cout << "Sending out " << records.size() << " SRV results " << std::endl;
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), records), shared_from_this());
}
void PlatformDomainNameServiceQuery::emitError() {
- eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<DomainNameServiceQuery::Result>()), shared_from_this());
+ eventLoop->postEvent(boost::bind(boost::ref(onResult), std::vector<DomainNameServiceQuery::Result>()), shared_from_this());
}
}
diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.h b/Swiften/Network/PlatformDomainNameServiceQuery.h
index afc4a90..e415005 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.h
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.h
@@ -15,22 +15,22 @@
#include <Swiften/Network/PlatformDomainNameQuery.h>
namespace Swift {
- class EventLoop;
+ class EventLoop;
- class PlatformDomainNameServiceQuery : public DomainNameServiceQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameServiceQuery>, public EventOwner {
- public:
- PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver);
- virtual ~PlatformDomainNameServiceQuery();
+ class PlatformDomainNameServiceQuery : public DomainNameServiceQuery, public PlatformDomainNameQuery, public boost::enable_shared_from_this<PlatformDomainNameServiceQuery>, public EventOwner {
+ public:
+ PlatformDomainNameServiceQuery(const boost::optional<std::string>& serviceName, EventLoop* eventLoop, PlatformDomainNameResolver* resolver);
+ virtual ~PlatformDomainNameServiceQuery();
- virtual void run();
+ virtual void run();
- private:
- void runBlocking();
- void emitError();
+ private:
+ void runBlocking();
+ void emitError();
- private:
- EventLoop* eventLoop;
- std::string service;
- bool serviceValid;
- };
+ private:
+ EventLoop* eventLoop;
+ std::string service;
+ bool serviceValid;
+ };
}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp
index ef1876c..e6fb05f 100644
--- a/Swiften/Network/PlatformNATTraversalWorker.cpp
+++ b/Swiften/Network/PlatformNATTraversalWorker.cpp
@@ -26,193 +26,193 @@
namespace Swift {
class PlatformNATTraversalRequest : public boost::enable_shared_from_this<PlatformNATTraversalRequest>, public EventOwner {
- public:
- typedef boost::shared_ptr<PlatformNATTraversalRequest> ref;
+ public:
+ typedef boost::shared_ptr<PlatformNATTraversalRequest> ref;
- public:
- PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker) : worker(worker) {
- }
+ public:
+ PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker) : worker(worker) {
+ }
- virtual ~PlatformNATTraversalRequest() {
- }
+ virtual ~PlatformNATTraversalRequest() {
+ }
- virtual void doRun() {
- worker->addRequestToQueue(shared_from_this());
- }
+ virtual void doRun() {
+ worker->addRequestToQueue(shared_from_this());
+ }
- NATTraversalInterface* getNATTraversalInterface() const {
- return worker->getNATTraversalInterface();
- }
+ NATTraversalInterface* getNATTraversalInterface() const {
+ return worker->getNATTraversalInterface();
+ }
- EventLoop* getEventLoop() const {
- return worker->getEventLoop();
- }
+ EventLoop* getEventLoop() const {
+ return worker->getEventLoop();
+ }
- virtual void runBlocking() = 0;
+ virtual void runBlocking() = 0;
- private:
- PlatformNATTraversalWorker* worker;
+ private:
+ PlatformNATTraversalWorker* worker;
};
class PlatformNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPRequest, public PlatformNATTraversalRequest {
- public:
- PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) {
- }
+ public:
+ PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) {
+ }
- virtual ~PlatformNATTraversalGetPublicIPRequest() {
- }
+ virtual ~PlatformNATTraversalGetPublicIPRequest() {
+ }
- virtual void start() {
- doRun();
- }
+ virtual void start() {
+ doRun();
+ }
- virtual void stop() {
- onResult.disconnect_all_slots();
- }
+ virtual void stop() {
+ onResult.disconnect_all_slots();
+ }
- virtual void runBlocking() {
- getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->getPublicIP()), shared_from_this());
- }
+ virtual void runBlocking() {
+ getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->getPublicIP()), shared_from_this());
+ }
};
class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortRequest, public PlatformNATTraversalRequest {
- public:
- PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned int localIP, unsigned int publicIP) : PlatformNATTraversalRequest(worker), localIP(localIP), publicIP(publicIP) {
- }
+ public:
+ PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned int localIP, unsigned int publicIP) : PlatformNATTraversalRequest(worker), localIP(localIP), publicIP(publicIP) {
+ }
- virtual ~PlatformNATTraversalForwardPortRequest() {
- }
+ virtual ~PlatformNATTraversalForwardPortRequest() {
+ }
- virtual void start() {
- doRun();
- }
+ virtual void start() {
+ doRun();
+ }
- virtual void stop() {
- onResult.disconnect_all_slots();
- }
+ virtual void stop() {
+ onResult.disconnect_all_slots();
+ }
- virtual void runBlocking() {
- getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))), shared_from_this());
- }
+ virtual void runBlocking() {
+ getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))), shared_from_this());
+ }
- private:
- unsigned int localIP;
- unsigned int publicIP;
+ private:
+ unsigned int localIP;
+ unsigned int publicIP;
};
class PlatformNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePortForwardingRequest, public PlatformNATTraversalRequest {
- public:
- PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker, const NATPortMapping& mapping) : PlatformNATTraversalRequest(worker), mapping(mapping) {
- }
+ public:
+ PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker, const NATPortMapping& mapping) : PlatformNATTraversalRequest(worker), mapping(mapping) {
+ }
- virtual ~PlatformNATTraversalRemovePortForwardingRequest() {
- }
+ virtual ~PlatformNATTraversalRemovePortForwardingRequest() {
+ }
- virtual void start() {
- doRun();
- }
+ virtual void start() {
+ doRun();
+ }
- virtual void stop() {
- onResult.disconnect_all_slots();
- }
+ virtual void stop() {
+ onResult.disconnect_all_slots();
+ }
- virtual void runBlocking() {
- getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->removePortForward(mapping)), shared_from_this());
- }
+ virtual void runBlocking() {
+ getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->removePortForward(mapping)), shared_from_this());
+ }
- private:
- NATPortMapping mapping;
+ private:
+ NATPortMapping mapping;
};
PlatformNATTraversalWorker::PlatformNATTraversalWorker(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), natPMPSupported(boost::logic::indeterminate), natPMPInterface(NULL), miniUPnPSupported(boost::logic::indeterminate), miniUPnPInterface(NULL) {
- nullNATTraversalInterface = new NullNATTraversalInterface();
- // FIXME: This should be done from start(), and the current start() should be an internal method
- thread = new boost::thread(boost::bind(&PlatformNATTraversalWorker::start, this));
+ nullNATTraversalInterface = new NullNATTraversalInterface();
+ // FIXME: This should be done from start(), and the current start() should be an internal method
+ thread = new boost::thread(boost::bind(&PlatformNATTraversalWorker::start, this));
}
PlatformNATTraversalWorker::~PlatformNATTraversalWorker() {
- stopRequested = true;
- addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>());
- thread->join();
- delete thread;
+ stopRequested = true;
+ addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>());
+ thread->join();
+ delete thread;
#ifdef HAVE_LIBNATPMP
- delete natPMPInterface;
+ delete natPMPInterface;
#endif
#ifdef HAVE_LIBMINIUPNPC
- delete miniUPnPInterface;
+ delete miniUPnPInterface;
#endif
- delete nullNATTraversalInterface;
+ delete nullNATTraversalInterface;
}
NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() const {
#ifdef HAVE_LIBMINIUPNPC
- if (boost::logic::indeterminate(miniUPnPSupported)) {
- miniUPnPInterface = new MiniUPnPInterface();
- miniUPnPSupported = miniUPnPInterface->isAvailable();
- }
- SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << miniUPnPSupported << std::endl;
- if (miniUPnPSupported) {
- return miniUPnPInterface;
- }
+ if (boost::logic::indeterminate(miniUPnPSupported)) {
+ miniUPnPInterface = new MiniUPnPInterface();
+ miniUPnPSupported = miniUPnPInterface->isAvailable();
+ }
+ SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << miniUPnPSupported << std::endl;
+ if (miniUPnPSupported) {
+ return miniUPnPInterface;
+ }
#endif
#ifdef HAVE_LIBNATPMP
- if (boost::logic::indeterminate(natPMPSupported)) {
- natPMPInterface = new NATPMPInterface();
- natPMPSupported = natPMPInterface->isAvailable();
- }
- SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << natPMPSupported << std::endl;
- if (natPMPSupported) {
- return natPMPInterface;
- }
+ if (boost::logic::indeterminate(natPMPSupported)) {
+ natPMPInterface = new NATPMPInterface();
+ natPMPSupported = natPMPInterface->isAvailable();
+ }
+ SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << natPMPSupported << std::endl;
+ if (natPMPSupported) {
+ return natPMPInterface;
+ }
#endif
- return nullNATTraversalInterface;
+ return nullNATTraversalInterface;
}
boost::shared_ptr<NATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::createGetPublicIPRequest() {
- return boost::make_shared<PlatformNATTraversalGetPublicIPRequest>(this);
+ return boost::make_shared<PlatformNATTraversalGetPublicIPRequest>(this);
}
boost::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(int localPort, int publicPort) {
- return boost::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort);
+ return boost::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort);
}
boost::shared_ptr<NATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(int localPort, int publicPort) {
- NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME
- return boost::make_shared<PlatformNATTraversalRemovePortForwardingRequest>(this, mapping);
+ NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME
+ return boost::make_shared<PlatformNATTraversalRemovePortForwardingRequest>(this, mapping);
}
void PlatformNATTraversalWorker::start() {
- while (!stopRequested) {
- PlatformNATTraversalRequest::ref request;
- {
- boost::unique_lock<boost::mutex> lock(queueMutex);
- while (queue.empty()) {
- queueNonEmpty.wait(lock);
- }
- request = queue.front();
- queue.pop_front();
- }
- // Check whether we don't have a non-null request (used to stop the
- // worker)
- if (request) {
- request->runBlocking();
- }
- }
+ while (!stopRequested) {
+ PlatformNATTraversalRequest::ref request;
+ {
+ boost::unique_lock<boost::mutex> lock(queueMutex);
+ while (queue.empty()) {
+ queueNonEmpty.wait(lock);
+ }
+ request = queue.front();
+ queue.pop_front();
+ }
+ // Check whether we don't have a non-null request (used to stop the
+ // worker)
+ if (request) {
+ request->runBlocking();
+ }
+ }
}
void PlatformNATTraversalWorker::stop() {
- // TODO
+ // TODO
}
void PlatformNATTraversalWorker::addRequestToQueue(PlatformNATTraversalRequest::ref request) {
- {
- boost::lock_guard<boost::mutex> lock(queueMutex);
- queue.push_back(request);
- }
- queueNonEmpty.notify_one();
+ {
+ boost::lock_guard<boost::mutex> lock(queueMutex);
+ queue.push_back(request);
+ }
+ queueNonEmpty.notify_one();
}
}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.h b/Swiften/Network/PlatformNATTraversalWorker.h
index 2c03dca..280a537 100644
--- a/Swiften/Network/PlatformNATTraversalWorker.h
+++ b/Swiften/Network/PlatformNATTraversalWorker.h
@@ -27,49 +27,49 @@
#include <Swiften/Network/NullNATTraversalInterface.h>
namespace Swift {
- class EventLoop;
- class NATTraversalGetPublicIPRequest;
- class NATTraversalForwardPortRequest;
- class NATTraversalRemovePortForwardingRequest;
- class PlatformNATTraversalRequest;
- class NATPMPInterface;
- class MiniUPnPInterface;
- class NATTraversalInterface;
- class NATPortMapping;
+ class EventLoop;
+ class NATTraversalGetPublicIPRequest;
+ class NATTraversalForwardPortRequest;
+ class NATTraversalRemovePortForwardingRequest;
+ class PlatformNATTraversalRequest;
+ class NATPMPInterface;
+ class MiniUPnPInterface;
+ class NATTraversalInterface;
+ class NATPortMapping;
- class SWIFTEN_API PlatformNATTraversalWorker : public NATTraverser {
- friend class PlatformNATTraversalRequest;
+ class SWIFTEN_API PlatformNATTraversalWorker : public NATTraverser {
+ friend class PlatformNATTraversalRequest;
- public:
- PlatformNATTraversalWorker(EventLoop* eventLoop);
- virtual ~PlatformNATTraversalWorker();
+ public:
+ PlatformNATTraversalWorker(EventLoop* eventLoop);
+ virtual ~PlatformNATTraversalWorker();
- boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
- boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
- boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort);
+ boost::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
+ boost::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
+ boost::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort);
- private:
- NATTraversalInterface* getNATTraversalInterface() const;
- void addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>);
- void start();
- void stop();
+ private:
+ NATTraversalInterface* getNATTraversalInterface() const;
+ void addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>);
+ void start();
+ void stop();
- EventLoop* getEventLoop() const {
- return eventLoop;
- }
+ EventLoop* getEventLoop() const {
+ return eventLoop;
+ }
- private:
- EventLoop* eventLoop;
- Atomic<bool> stopRequested;
- boost::thread* thread;
- std::deque<boost::shared_ptr<PlatformNATTraversalRequest> > queue;
- boost::mutex queueMutex;
- boost::condition_variable queueNonEmpty;
+ private:
+ EventLoop* eventLoop;
+ Atomic<bool> stopRequested;
+ boost::thread* thread;
+ std::deque<boost::shared_ptr<PlatformNATTraversalRequest> > queue;
+ boost::mutex queueMutex;
+ boost::condition_variable queueNonEmpty;
- NullNATTraversalInterface* nullNATTraversalInterface;
- mutable boost::logic::tribool natPMPSupported;
- mutable NATPMPInterface* natPMPInterface;
- mutable boost::logic::tribool miniUPnPSupported;
- mutable MiniUPnPInterface* miniUPnPInterface;
- };
+ NullNATTraversalInterface* nullNATTraversalInterface;
+ mutable boost::logic::tribool natPMPSupported;
+ mutable NATPMPInterface* natPMPInterface;
+ mutable boost::logic::tribool miniUPnPSupported;
+ mutable MiniUPnPInterface* miniUPnPInterface;
+ };
}
diff --git a/Swiften/Network/PlatformNetworkEnvironment.h b/Swiften/Network/PlatformNetworkEnvironment.h
index 2092bfd..ff29491 100644
--- a/Swiften/Network/PlatformNetworkEnvironment.h
+++ b/Swiften/Network/PlatformNetworkEnvironment.h
@@ -11,22 +11,22 @@
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <Swiften/Network/UnixNetworkEnvironment.h>
namespace Swift {
- typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
+ typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
}
#elif defined(SWIFTEN_PLATFORM_WIN32)
#include <Swiften/Network/WindowsNetworkEnvironment.h>
namespace Swift {
- typedef WindowsNetworkEnvironment PlatformNetworkEnvironment;
+ typedef WindowsNetworkEnvironment PlatformNetworkEnvironment;
}
#elif defined(SWIFTEN_PLATFORM_SOLARIS)
#include <Swiften/Network/SolarisNetworkEnvironment.h>
namespace Swift {
- typedef SolarisNetworkEnvironment PlatformNetworkEnvironment;
+ typedef SolarisNetworkEnvironment PlatformNetworkEnvironment;
}
#else
#include <Swiften/Network/UnixNetworkEnvironment.h>
namespace Swift {
- typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
+ typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
}
#endif
diff --git a/Swiften/Network/PlatformProxyProvider.h b/Swiften/Network/PlatformProxyProvider.h
index 1a0a1c6..c63e718 100644
--- a/Swiften/Network/PlatformProxyProvider.h
+++ b/Swiften/Network/PlatformProxyProvider.h
@@ -11,16 +11,16 @@
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <Swiften/Network/MacOSXProxyProvider.h>
namespace Swift {
- typedef MacOSXProxyProvider PlatformProxyProvider;
+ typedef MacOSXProxyProvider PlatformProxyProvider;
}
#elif defined(SWIFTEN_PLATFORM_WIN32)
#include <Swiften/Network/WindowsProxyProvider.h>
namespace Swift {
- typedef WindowsProxyProvider PlatformProxyProvider;
+ typedef WindowsProxyProvider PlatformProxyProvider;
}
#else
#include <Swiften/Network/UnixProxyProvider.h>
namespace Swift {
- typedef UnixProxyProvider PlatformProxyProvider;
+ typedef UnixProxyProvider PlatformProxyProvider;
}
#endif
diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp
index 69f719d..27f5cd9 100644
--- a/Swiften/Network/ProxiedConnection.cpp
+++ b/Swiften/Network/ProxiedConnection.cpp
@@ -16,112 +16,112 @@
using namespace Swift;
ProxiedConnection::ProxiedConnection(
- DomainNameResolver* resolver,
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- const std::string& proxyHost,
- int proxyPort) :
- resolver_(resolver),
- connectionFactory_(connectionFactory),
- timerFactory_(timerFactory),
- proxyHost_(proxyHost),
- proxyPort_(proxyPort),
- server_(HostAddressPort(HostAddress("0.0.0.0"), 0)) {
- connected_ = false;
+ DomainNameResolver* resolver,
+ ConnectionFactory* connectionFactory,
+ TimerFactory* timerFactory,
+ const std::string& proxyHost,
+ int proxyPort) :
+ resolver_(resolver),
+ connectionFactory_(connectionFactory),
+ timerFactory_(timerFactory),
+ proxyHost_(proxyHost),
+ proxyPort_(proxyPort),
+ server_(HostAddressPort(HostAddress("0.0.0.0"), 0)) {
+ connected_ = false;
}
ProxiedConnection::~ProxiedConnection() {
- cancelConnector();
- if (connection_) {
- connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
- connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
- }
- if (connected_) {
- SWIFT_LOG(warning) << "Connection was still established." << std::endl;
- }
+ cancelConnector();
+ if (connection_) {
+ connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
+ }
+ if (connected_) {
+ SWIFT_LOG(warning) << "Connection was still established." << std::endl;
+ }
}
void ProxiedConnection::cancelConnector() {
- if (connector_) {
- connector_->onConnectFinished.disconnect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1));
- connector_->stop();
- connector_.reset();
- }
+ if (connector_) {
+ connector_->onConnectFinished.disconnect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1));
+ connector_->stop();
+ connector_.reset();
+ }
}
void ProxiedConnection::connect(const HostAddressPort& server) {
- server_ = server;
+ server_ = server;
- connector_ = Connector::create(proxyHost_, proxyPort_, boost::optional<std::string>(), resolver_, connectionFactory_, timerFactory_);
- connector_->onConnectFinished.connect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1));
- connector_->start();
+ connector_ = Connector::create(proxyHost_, proxyPort_, boost::optional<std::string>(), resolver_, connectionFactory_, timerFactory_);
+ connector_->onConnectFinished.connect(boost::bind(&ProxiedConnection::handleConnectFinished, shared_from_this(), _1));
+ connector_->start();
}
void ProxiedConnection::listen() {
- assert(false);
- connection_->listen();
+ assert(false);
+ connection_->listen();
}
void ProxiedConnection::disconnect() {
- cancelConnector();
- connected_ = false;
- if (connection_) {
- connection_->disconnect();
- }
+ cancelConnector();
+ connected_ = false;
+ if (connection_) {
+ connection_->disconnect();
+ }
}
void ProxiedConnection::handleDisconnected(const boost::optional<Error>& error) {
- onDisconnected(error);
+ onDisconnected(error);
}
void ProxiedConnection::write(const SafeByteArray& data) {
- connection_->write(data);
+ connection_->write(data);
}
void ProxiedConnection::handleConnectFinished(Connection::ref connection) {
- cancelConnector();
- if (connection) {
- connection_ = connection;
- connection_->onDataRead.connect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
- connection_->onDisconnected.connect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
-
- initializeProxy();
- }
- else {
- onConnectFinished(true);
- }
+ cancelConnector();
+ if (connection) {
+ connection_ = connection;
+ connection_->onDataRead.connect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.connect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
+
+ initializeProxy();
+ }
+ else {
+ onConnectFinished(true);
+ }
}
void ProxiedConnection::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- if (!connected_) {
- handleProxyInitializeData(data);
- }
- else {
- onDataRead(data);
- }
+ if (!connected_) {
+ handleProxyInitializeData(data);
+ }
+ else {
+ onDataRead(data);
+ }
}
HostAddressPort ProxiedConnection::getLocalAddress() const {
- return connection_->getLocalAddress();
+ return connection_->getLocalAddress();
}
HostAddressPort ProxiedConnection::getRemoteAddress() const {
- return connection_->getRemoteAddress();
+ return connection_->getRemoteAddress();
}
void ProxiedConnection::setProxyInitializeFinished(bool success) {
- connected_ = success;
- if (!success) {
- disconnect();
- }
- onConnectFinished(!success);
+ connected_ = success;
+ if (!success) {
+ disconnect();
+ }
+ onConnectFinished(!success);
}
void ProxiedConnection::reconnect() {
- if (connected_) {
- connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
- connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
- connection_->disconnect();
- }
- connect(server_);
+ if (connected_) {
+ connection_->onDataRead.disconnect(boost::bind(&ProxiedConnection::handleDataRead, shared_from_this(), _1));
+ connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1));
+ connection_->disconnect();
+ }
+ connect(server_);
}
diff --git a/Swiften/Network/ProxiedConnection.h b/Swiften/Network/ProxiedConnection.h
index f03c7ae..80f748c 100644
--- a/Swiften/Network/ProxiedConnection.h
+++ b/Swiften/Network/ProxiedConnection.h
@@ -16,56 +16,56 @@
#include <Swiften/Network/HostAddressPort.h>
namespace boost {
- class thread;
- namespace system {
- class error_code;
- }
+ class thread;
+ namespace system {
+ class error_code;
+ }
}
namespace Swift {
- class ConnectionFactory;
-
- class SWIFTEN_API ProxiedConnection : public Connection, public boost::enable_shared_from_this<ProxiedConnection> {
- public:
- ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
- virtual ~ProxiedConnection();
-
- virtual void listen();
- virtual void connect(const HostAddressPort& address);
- virtual void disconnect();
- virtual void write(const SafeByteArray& data);
-
- virtual HostAddressPort getLocalAddress() const;
- virtual HostAddressPort getRemoteAddress() const;
-
- private:
- void handleConnectFinished(Connection::ref connection);
- void handleDataRead(boost::shared_ptr<SafeByteArray> data);
- void handleDisconnected(const boost::optional<Error>& error);
- void cancelConnector();
-
- protected:
- void setProxyInitializeFinished(bool success);
-
- virtual void initializeProxy() = 0;
- virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) = 0;
-
- const HostAddressPort& getServer() const {
- return server_;
- }
-
- void reconnect();
-
- private:
- bool connected_;
- DomainNameResolver* resolver_;
- ConnectionFactory* connectionFactory_;
- TimerFactory* timerFactory_;
- std::string proxyHost_;
- int proxyPort_;
- HostAddressPort server_;
- Connector::ref connector_;
- boost::shared_ptr<Connection> connection_;
- };
+ class ConnectionFactory;
+
+ class SWIFTEN_API ProxiedConnection : public Connection, public boost::enable_shared_from_this<ProxiedConnection> {
+ public:
+ ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
+ virtual ~ProxiedConnection();
+
+ virtual void listen();
+ virtual void connect(const HostAddressPort& address);
+ virtual void disconnect();
+ virtual void write(const SafeByteArray& data);
+
+ virtual HostAddressPort getLocalAddress() const;
+ virtual HostAddressPort getRemoteAddress() const;
+
+ private:
+ void handleConnectFinished(Connection::ref connection);
+ void handleDataRead(boost::shared_ptr<SafeByteArray> data);
+ void handleDisconnected(const boost::optional<Error>& error);
+ void cancelConnector();
+
+ protected:
+ void setProxyInitializeFinished(bool success);
+
+ virtual void initializeProxy() = 0;
+ virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) = 0;
+
+ const HostAddressPort& getServer() const {
+ return server_;
+ }
+
+ void reconnect();
+
+ private:
+ bool connected_;
+ DomainNameResolver* resolver_;
+ ConnectionFactory* connectionFactory_;
+ TimerFactory* timerFactory_;
+ std::string proxyHost_;
+ int proxyPort_;
+ HostAddressPort server_;
+ Connector::ref connector_;
+ boost::shared_ptr<Connection> connection_;
+ };
}
diff --git a/Swiften/Network/ProxyProvider.h b/Swiften/Network/ProxyProvider.h
index 96f3b21..bf737c0 100644
--- a/Swiften/Network/ProxyProvider.h
+++ b/Swiften/Network/ProxyProvider.h
@@ -19,12 +19,12 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API ProxyProvider {
- public:
- ProxyProvider();
- virtual ~ProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const = 0;
- virtual HostAddressPort getSOCKS5Proxy() const = 0;
- };
+ class SWIFTEN_API ProxyProvider {
+ public:
+ ProxyProvider();
+ virtual ~ProxyProvider();
+ virtual HostAddressPort getHTTPConnectProxy() const = 0;
+ virtual HostAddressPort getSOCKS5Proxy() const = 0;
+ };
}
diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp
index 1385fa2..2b7a3f3 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp
@@ -26,98 +26,98 @@
using namespace Swift;
SOCKS5ProxiedConnection::SOCKS5ProxiedConnection(
- DomainNameResolver* resolver,
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- const std::string& proxyHost,
- int proxyPort) :
- ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort),
- proxyState_(Initial) {
- }
+ DomainNameResolver* resolver,
+ ConnectionFactory* connectionFactory,
+ TimerFactory* timerFactory,
+ const std::string& proxyHost,
+ int proxyPort) :
+ ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort),
+ proxyState_(Initial) {
+ }
void SOCKS5ProxiedConnection::initializeProxy() {
- proxyState_ = ProxyAuthenticating;
- SafeByteArray socksConnect;
- socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05
- socksConnect.push_back(0x01); // Number of authentication methods after this byte.
- socksConnect.push_back(0x00); // 0x00 == no authentication
- // buffer.push_back(0x01); // 0x01 == GSSAPI
- // buffer.push_back(0x02); // 0x02 == Username/Password
- // rest see RFC 1928 (http://tools.ietf.org/html/rfc1928)
- write(socksConnect);
+ proxyState_ = ProxyAuthenticating;
+ SafeByteArray socksConnect;
+ socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05
+ socksConnect.push_back(0x01); // Number of authentication methods after this byte.
+ socksConnect.push_back(0x00); // 0x00 == no authentication
+ // buffer.push_back(0x01); // 0x01 == GSSAPI
+ // buffer.push_back(0x02); // 0x02 == Username/Password
+ // rest see RFC 1928 (http://tools.ietf.org/html/rfc1928)
+ write(socksConnect);
}
void SOCKS5ProxiedConnection::handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data) {
- SafeByteArray socksConnect;
- boost::asio::ip::address rawAddress = getServer().getAddress().getRawAddress();
- assert(rawAddress.is_v4() || rawAddress.is_v6());
+ SafeByteArray socksConnect;
+ boost::asio::ip::address rawAddress = getServer().getAddress().getRawAddress();
+ assert(rawAddress.is_v4() || rawAddress.is_v6());
- if (proxyState_ == ProxyAuthenticating) {
- SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs" << std::endl;
- unsigned char choosenMethod = static_cast<unsigned char> ((*data)[1]);
- if ((*data)[0] == 0x05 && choosenMethod != 0xFF) {
- switch(choosenMethod) { // use the correct Method
- case 0x00:
- try {
- proxyState_ = ProxyConnecting;
- socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05
- socksConnect.push_back(0x01); // Construct a TCP connection. (CMD)
- socksConnect.push_back(0x00); // reserved.
- socksConnect.push_back(rawAddress.is_v4() ? 0x01 : 0x04); // IPv4 == 0x01, Hostname == 0x02, IPv6 == 0x04. (ATYP)
- size_t size = rawAddress.is_v4() ? rawAddress.to_v4().to_bytes().size() : rawAddress.to_v6().to_bytes().size();
- for (size_t s = 0; s < size; s++) {
- unsigned char uc;
- if(rawAddress.is_v4()) {
- uc = rawAddress.to_v4().to_bytes()[s]; // the address.
- }
- else {
- uc = rawAddress.to_v6().to_bytes()[s]; // the address.
- }
- socksConnect.push_back(uc);
-
- }
- socksConnect.push_back(static_cast<unsigned char> ((getServer().getPort() >> 8) & 0xFF)); // highbyte of the port.
- socksConnect.push_back(static_cast<unsigned char> (getServer().getPort() & 0xFF)); // lowbyte of the port.
- write(socksConnect);
- return;
- }
- catch(...) {
- std::cerr << "exception caught" << std::endl;
- }
- write(socksConnect);
- break;
- default:
- setProxyInitializeFinished(true);
- break;
- }
- return;
- }
- setProxyInitializeFinished(false);
- }
- else if (proxyState_ == ProxyConnecting) {
- SWIFT_LOG(debug) << "Connect response received, check if successfully." << std::endl;
- SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec << std::endl;
- /*
+ if (proxyState_ == ProxyAuthenticating) {
+ SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs" << std::endl;
+ unsigned char choosenMethod = static_cast<unsigned char> ((*data)[1]);
+ if ((*data)[0] == 0x05 && choosenMethod != 0xFF) {
+ switch(choosenMethod) { // use the correct Method
+ case 0x00:
+ try {
+ proxyState_ = ProxyConnecting;
+ socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05
+ socksConnect.push_back(0x01); // Construct a TCP connection. (CMD)
+ socksConnect.push_back(0x00); // reserved.
+ socksConnect.push_back(rawAddress.is_v4() ? 0x01 : 0x04); // IPv4 == 0x01, Hostname == 0x02, IPv6 == 0x04. (ATYP)
+ size_t size = rawAddress.is_v4() ? rawAddress.to_v4().to_bytes().size() : rawAddress.to_v6().to_bytes().size();
+ for (size_t s = 0; s < size; s++) {
+ unsigned char uc;
+ if(rawAddress.is_v4()) {
+ uc = rawAddress.to_v4().to_bytes()[s]; // the address.
+ }
+ else {
+ uc = rawAddress.to_v6().to_bytes()[s]; // the address.
+ }
+ socksConnect.push_back(uc);
- data.at(1) can be one of the following:
- 0x00 succeeded
- 0x01 general SOCKS server failure
- 0x02 connection not allowed by ruleset
- 0x03 Network unreachable
- 0x04 Host unreachable
- 0x05 Connection refused
- 0x06 TTL expired
- 0x07 Command not supported (CMD)
- 0x08 Address type not supported (ATYP)
- 0x09 bis 0xFF unassigned
- */
- if ((*data)[0] == 0x05 && (*data)[1] == 0x0) {
- SWIFT_LOG(debug) << "Successfully connected the server via the proxy." << std::endl;
- setProxyInitializeFinished(true);
- }
- else {
- std::cerr << "SOCKS Proxy returned an error: " << std::hex << (*data)[1] << std::endl;
- setProxyInitializeFinished(false);
- }
- }
+ }
+ socksConnect.push_back(static_cast<unsigned char> ((getServer().getPort() >> 8) & 0xFF)); // highbyte of the port.
+ socksConnect.push_back(static_cast<unsigned char> (getServer().getPort() & 0xFF)); // lowbyte of the port.
+ write(socksConnect);
+ return;
+ }
+ catch(...) {
+ std::cerr << "exception caught" << std::endl;
+ }
+ write(socksConnect);
+ break;
+ default:
+ setProxyInitializeFinished(true);
+ break;
+ }
+ return;
+ }
+ setProxyInitializeFinished(false);
+ }
+ else if (proxyState_ == ProxyConnecting) {
+ SWIFT_LOG(debug) << "Connect response received, check if successfully." << std::endl;
+ SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec << std::endl;
+ /*
+
+ data.at(1) can be one of the following:
+ 0x00 succeeded
+ 0x01 general SOCKS server failure
+ 0x02 connection not allowed by ruleset
+ 0x03 Network unreachable
+ 0x04 Host unreachable
+ 0x05 Connection refused
+ 0x06 TTL expired
+ 0x07 Command not supported (CMD)
+ 0x08 Address type not supported (ATYP)
+ 0x09 bis 0xFF unassigned
+ */
+ if ((*data)[0] == 0x05 && (*data)[1] == 0x0) {
+ SWIFT_LOG(debug) << "Successfully connected the server via the proxy." << std::endl;
+ setProxyInitializeFinished(true);
+ }
+ else {
+ std::cerr << "SOCKS Proxy returned an error: " << std::hex << (*data)[1] << std::endl;
+ setProxyInitializeFinished(false);
+ }
+ }
}
diff --git a/Swiften/Network/SOCKS5ProxiedConnection.h b/Swiften/Network/SOCKS5ProxiedConnection.h
index ee58d96..edbc56c 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.h
+++ b/Swiften/Network/SOCKS5ProxiedConnection.h
@@ -16,29 +16,29 @@
#include <Swiften/Network/ProxiedConnection.h>
namespace Swift {
- class ConnectionFactory;
- class DomainNameResolver;
- class TimerFactory;
-
- class SWIFTEN_API SOCKS5ProxiedConnection : public ProxiedConnection {
- public:
- typedef boost::shared_ptr<SOCKS5ProxiedConnection> ref;
-
- static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) {
- return ref(new SOCKS5ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort));
- }
-
- private:
- SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
-
- virtual void initializeProxy();
- virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data);
-
- private:
- enum {
- Initial = 0,
- ProxyAuthenticating,
- ProxyConnecting
- } proxyState_;
- };
+ class ConnectionFactory;
+ class DomainNameResolver;
+ class TimerFactory;
+
+ class SWIFTEN_API SOCKS5ProxiedConnection : public ProxiedConnection {
+ public:
+ typedef boost::shared_ptr<SOCKS5ProxiedConnection> ref;
+
+ static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) {
+ return ref(new SOCKS5ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort));
+ }
+
+ private:
+ SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
+
+ virtual void initializeProxy();
+ virtual void handleProxyInitializeData(boost::shared_ptr<SafeByteArray> data);
+
+ private:
+ enum {
+ Initial = 0,
+ ProxyAuthenticating,
+ ProxyConnecting
+ } proxyState_;
+ };
}
diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp
index af99034..3e24f00 100644
--- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp
@@ -14,7 +14,7 @@ SOCKS5ProxiedConnectionFactory::SOCKS5ProxiedConnectionFactory(DomainNameResolve
}
boost::shared_ptr<Connection> SOCKS5ProxiedConnectionFactory::createConnection() {
- return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_);
+ return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_);
}
}
diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
index 0915a9b..1092381 100644
--- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
+++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
@@ -18,20 +18,20 @@
#include <Swiften/Network/HostNameOrAddress.h>
namespace Swift {
- class DomainNameResolver;
- class TimerFactory;
+ class DomainNameResolver;
+ class TimerFactory;
- class SWIFTEN_API SOCKS5ProxiedConnectionFactory : public ConnectionFactory {
- public:
- SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
+ class SWIFTEN_API SOCKS5ProxiedConnectionFactory : public ConnectionFactory {
+ public:
+ SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort);
- virtual boost::shared_ptr<Connection> createConnection();
+ virtual boost::shared_ptr<Connection> createConnection();
- private:
- DomainNameResolver* resolver_;
- ConnectionFactory* connectionFactory_;
- TimerFactory* timerFactory_;
- std::string proxyHost_;
- int proxyPort_;
- };
+ private:
+ DomainNameResolver* resolver_;
+ ConnectionFactory* connectionFactory_;
+ TimerFactory* timerFactory_;
+ std::string proxyHost_;
+ int proxyPort_;
+ };
}
diff --git a/Swiften/Network/SolarisNetworkEnvironment.cpp b/Swiften/Network/SolarisNetworkEnvironment.cpp
index 0404364..4a1012b 100644
--- a/Swiften/Network/SolarisNetworkEnvironment.cpp
+++ b/Swiften/Network/SolarisNetworkEnvironment.cpp
@@ -39,13 +39,13 @@
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
@@ -63,193 +63,193 @@
#undef ifa_broadaddr
#undef ifa_dstaddr
struct ifaddrs {
- struct ifaddrs *ifa_next; /* Pointer to next struct */
- char *ifa_name; /* Interface name */
- uint64_t ifa_flags; /* Interface flags */
- struct sockaddr *ifa_addr; /* Interface address */
- struct sockaddr *ifa_netmask; /* Interface netmask */
- struct sockaddr *ifa_dstaddr; /* P2P interface destination */
+ struct ifaddrs *ifa_next; /* Pointer to next struct */
+ char *ifa_name; /* Interface name */
+ uint64_t ifa_flags; /* Interface flags */
+ struct sockaddr *ifa_addr; /* Interface address */
+ struct sockaddr *ifa_netmask; /* Interface netmask */
+ struct sockaddr *ifa_dstaddr; /* P2P interface destination */
};
-#define ifa_broadaddr ifa_dstaddr
+#define ifa_broadaddr ifa_dstaddr
static int
get_lifreq(int fd, struct lifreq **ifr_ret)
{
- struct lifnum lifn;
- struct lifconf lifc;
- struct lifreq *lifrp;
-
- lifn.lifn_family = AF_UNSPEC;
- lifn.lifn_flags = 0;
- if (ioctl(fd, SIOCGLIFNUM, &lifn) == -1)
- lifn.lifn_count = 16;
- else
- lifn.lifn_count += 16;
-
- for (;;) {
- lifc.lifc_len = lifn.lifn_count * sizeof (*lifrp);
- lifrp = (struct lifreq *) malloc(lifc.lifc_len);
- if (lifrp == NULL)
- return (-1);
-
- lifc.lifc_family = AF_UNSPEC;
- lifc.lifc_flags = 0;
- lifc.lifc_buf = (char *)lifrp;
- if (ioctl(fd, SIOCGLIFCONF, &lifc) == -1) {
- free(lifrp);
- if (errno == EINVAL) {
- lifn.lifn_count <<= 1;
- continue;
- }
- (void) close(fd);
- return (-1);
- }
- if (lifc.lifc_len < (lifn.lifn_count - 1) * sizeof (*lifrp))
- break;
- free(lifrp);
- lifn.lifn_count <<= 1;
- }
- (void) close(fd);
-
- *ifr_ret = lifrp;
-
- return (lifc.lifc_len / sizeof (*lifrp));
+ struct lifnum lifn;
+ struct lifconf lifc;
+ struct lifreq *lifrp;
+
+ lifn.lifn_family = AF_UNSPEC;
+ lifn.lifn_flags = 0;
+ if (ioctl(fd, SIOCGLIFNUM, &lifn) == -1)
+ lifn.lifn_count = 16;
+ else
+ lifn.lifn_count += 16;
+
+ for (;;) {
+ lifc.lifc_len = lifn.lifn_count * sizeof (*lifrp);
+ lifrp = (struct lifreq *) malloc(lifc.lifc_len);
+ if (lifrp == NULL)
+ return (-1);
+
+ lifc.lifc_family = AF_UNSPEC;
+ lifc.lifc_flags = 0;
+ lifc.lifc_buf = (char *)lifrp;
+ if (ioctl(fd, SIOCGLIFCONF, &lifc) == -1) {
+ free(lifrp);
+ if (errno == EINVAL) {
+ lifn.lifn_count <<= 1;
+ continue;
+ }
+ (void) close(fd);
+ return (-1);
+ }
+ if (lifc.lifc_len < (lifn.lifn_count - 1) * sizeof (*lifrp))
+ break;
+ free(lifrp);
+ lifn.lifn_count <<= 1;
+ }
+ (void) close(fd);
+
+ *ifr_ret = lifrp;
+
+ return (lifc.lifc_len / sizeof (*lifrp));
}
static size_t
nbytes(const struct lifreq *lifrp, int nlif, size_t socklen)
{
- size_t len = 0;
- size_t slen;
-
- while (nlif > 0) {
- slen = strlen(lifrp->lifr_name) + 1;
- len += sizeof (struct ifaddrs) + ((slen + 3) & ~3);
- len += 3 * socklen;
- lifrp++;
- nlif--;
- }
- return (len);
+ size_t len = 0;
+ size_t slen;
+
+ while (nlif > 0) {
+ slen = strlen(lifrp->lifr_name) + 1;
+ len += sizeof (struct ifaddrs) + ((slen + 3) & ~3);
+ len += 3 * socklen;
+ lifrp++;
+ nlif--;
+ }
+ return (len);
}
static struct sockaddr *
addrcpy(struct sockaddr_storage *addr, char **bufp)
{
- char *buf = *bufp;
- size_t len;
-
- len = addr->ss_family == AF_INET ? sizeof (struct sockaddr_in) :
- sizeof (struct sockaddr_in6);
- (void) memcpy(buf, addr, len);
- *bufp = buf + len;
- return ((struct sockaddr *)buf);
+ char *buf = *bufp;
+ size_t len;
+
+ len = addr->ss_family == AF_INET ? sizeof (struct sockaddr_in) :
+ sizeof (struct sockaddr_in6);
+ (void) memcpy(buf, addr, len);
+ *bufp = buf + len;
+ return ((struct sockaddr *)buf);
}
static int
populate(struct ifaddrs *ifa, int fd, struct lifreq *lifrp, int nlif, int af,
- char **bufp)
+ char **bufp)
{
- char *buf = *bufp;
- size_t slen;
-
- while (nlif > 0) {
- ifa->ifa_next = (nlif > 1) ? ifa + 1 : NULL;
- (void) strcpy(ifa->ifa_name = buf, lifrp->lifr_name);
- slen = strlen(lifrp->lifr_name) + 1;
- buf += (slen + 3) & ~3;
- if (ioctl(fd, SIOCGLIFFLAGS, lifrp) == -1)
- ifa->ifa_flags = 0;
- else
- ifa->ifa_flags = lifrp->lifr_flags;
- if (ioctl(fd, SIOCGLIFADDR, lifrp) == -1)
- ifa->ifa_addr = NULL;
- else
- ifa->ifa_addr = addrcpy(&lifrp->lifr_addr, &buf);
- if (ioctl(fd, SIOCGLIFNETMASK, lifrp) == -1)
- ifa->ifa_netmask = NULL;
- else
- ifa->ifa_netmask = addrcpy(&lifrp->lifr_addr, &buf);
- if (ifa->ifa_flags & IFF_POINTOPOINT) {
- if (ioctl(fd, SIOCGLIFDSTADDR, lifrp) == -1)
- ifa->ifa_dstaddr = NULL;
- else
- ifa->ifa_dstaddr =
- addrcpy(&lifrp->lifr_dstaddr, &buf);
- } else if (ifa->ifa_flags & IFF_BROADCAST) {
- if (ioctl(fd, SIOCGLIFBRDADDR, lifrp) == -1)
- ifa->ifa_broadaddr = NULL;
- else
- ifa->ifa_broadaddr =
- addrcpy(&lifrp->lifr_broadaddr, &buf);
- } else {
- ifa->ifa_dstaddr = NULL;
- }
-
- ifa++;
- nlif--;
- lifrp++;
- }
- *bufp = buf;
- return (0);
+ char *buf = *bufp;
+ size_t slen;
+
+ while (nlif > 0) {
+ ifa->ifa_next = (nlif > 1) ? ifa + 1 : NULL;
+ (void) strcpy(ifa->ifa_name = buf, lifrp->lifr_name);
+ slen = strlen(lifrp->lifr_name) + 1;
+ buf += (slen + 3) & ~3;
+ if (ioctl(fd, SIOCGLIFFLAGS, lifrp) == -1)
+ ifa->ifa_flags = 0;
+ else
+ ifa->ifa_flags = lifrp->lifr_flags;
+ if (ioctl(fd, SIOCGLIFADDR, lifrp) == -1)
+ ifa->ifa_addr = NULL;
+ else
+ ifa->ifa_addr = addrcpy(&lifrp->lifr_addr, &buf);
+ if (ioctl(fd, SIOCGLIFNETMASK, lifrp) == -1)
+ ifa->ifa_netmask = NULL;
+ else
+ ifa->ifa_netmask = addrcpy(&lifrp->lifr_addr, &buf);
+ if (ifa->ifa_flags & IFF_POINTOPOINT) {
+ if (ioctl(fd, SIOCGLIFDSTADDR, lifrp) == -1)
+ ifa->ifa_dstaddr = NULL;
+ else
+ ifa->ifa_dstaddr =
+ addrcpy(&lifrp->lifr_dstaddr, &buf);
+ } else if (ifa->ifa_flags & IFF_BROADCAST) {
+ if (ioctl(fd, SIOCGLIFBRDADDR, lifrp) == -1)
+ ifa->ifa_broadaddr = NULL;
+ else
+ ifa->ifa_broadaddr =
+ addrcpy(&lifrp->lifr_broadaddr, &buf);
+ } else {
+ ifa->ifa_dstaddr = NULL;
+ }
+
+ ifa++;
+ nlif--;
+ lifrp++;
+ }
+ *bufp = buf;
+ return (0);
}
static int
getifaddrs(struct ifaddrs **ifap)
{
- int fd4, fd6;
- int nif4, nif6 = 0;
- struct lifreq *ifr4 = NULL;
- struct lifreq *ifr6 = NULL;
- struct ifaddrs *ifa = NULL;
- char *buf;
-
- if ((fd4 = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
- return (-1);
- if ((fd6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1 &&
- errno != EAFNOSUPPORT) {
- (void) close(fd4);
- return (-1);
- }
-
- if ((nif4 = get_lifreq(fd4, &ifr4)) == -1 ||
- (fd6 != -1 && (nif6 = get_lifreq(fd6, &ifr6)) == -1))
- goto failure;
-
- if (nif4 == 0 && nif6 == 0) {
- *ifap = NULL;
- return (0);
- }
-
- ifa = (struct ifaddrs *) malloc(nbytes(ifr4, nif4, sizeof (struct sockaddr_in)) +
- nbytes(ifr6, nif6, sizeof (struct sockaddr_in6)));
- if (ifa == NULL)
- goto failure;
-
- buf = (char *)(ifa + nif4 + nif6);
-
- if (populate(ifa, fd4, ifr4, nif4, AF_INET, &buf) == -1)
- goto failure;
- if (nif4 > 0 && nif6 > 0)
- ifa[nif4 - 1].ifa_next = ifa + nif4;
- if (populate(ifa + nif4, fd6, ifr6, nif6, AF_INET6, &buf) == -1)
- goto failure;
-
- return (0);
+ int fd4, fd6;
+ int nif4, nif6 = 0;
+ struct lifreq *ifr4 = NULL;
+ struct lifreq *ifr6 = NULL;
+ struct ifaddrs *ifa = NULL;
+ char *buf;
+
+ if ((fd4 = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
+ return (-1);
+ if ((fd6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1 &&
+ errno != EAFNOSUPPORT) {
+ (void) close(fd4);
+ return (-1);
+ }
+
+ if ((nif4 = get_lifreq(fd4, &ifr4)) == -1 ||
+ (fd6 != -1 && (nif6 = get_lifreq(fd6, &ifr6)) == -1))
+ goto failure;
+
+ if (nif4 == 0 && nif6 == 0) {
+ *ifap = NULL;
+ return (0);
+ }
+
+ ifa = (struct ifaddrs *) malloc(nbytes(ifr4, nif4, sizeof (struct sockaddr_in)) +
+ nbytes(ifr6, nif6, sizeof (struct sockaddr_in6)));
+ if (ifa == NULL)
+ goto failure;
+
+ buf = (char *)(ifa + nif4 + nif6);
+
+ if (populate(ifa, fd4, ifr4, nif4, AF_INET, &buf) == -1)
+ goto failure;
+ if (nif4 > 0 && nif6 > 0)
+ ifa[nif4 - 1].ifa_next = ifa + nif4;
+ if (populate(ifa + nif4, fd6, ifr6, nif6, AF_INET6, &buf) == -1)
+ goto failure;
+
+ return (0);
failure:
- free(ifa);
- (void) close(fd4);
- if (fd6 != -1)
- (void) close(fd6);
- free(ifr4);
- free(ifr6);
- return (-1);
+ free(ifa);
+ (void) close(fd4);
+ if (fd6 != -1)
+ (void) close(fd6);
+ free(ifr4);
+ free(ifr6);
+ return (-1);
}
static void
freeifaddrs(struct ifaddrs *ifa)
{
- free(ifa);
+ free(ifa);
}
/* End WIDE Project code */
@@ -257,38 +257,38 @@ freeifaddrs(struct ifaddrs *ifa)
namespace Swift {
std::vector<NetworkInterface> SolarisNetworkEnvironment::getNetworkInterfaces() const {
- std::map<std::string, NetworkInterface> interfaces;
-
- ifaddrs* addrs = 0;
- int ret = getifaddrs(&addrs);
- if (ret != 0) {
- return std::vector<NetworkInterface>();
- }
-
- for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) {
- std::string name(a->ifa_name);
- boost::optional<HostAddress> address;
- if (a->ifa_addr->sa_family == PF_INET) {
- sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr);
- address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
- }
- else if (a->ifa_addr->sa_family == PF_INET6) {
- sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr);
- address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
- }
- if (address) {
- std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first;
- i->second.addAddress(*address);
- }
- }
-
- freeifaddrs(addrs);
-
- std::vector<NetworkInterface> result;
- for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
- result.push_back(i->second);
- }
- return result;
+ std::map<std::string, NetworkInterface> interfaces;
+
+ ifaddrs* addrs = 0;
+ int ret = getifaddrs(&addrs);
+ if (ret != 0) {
+ return std::vector<NetworkInterface>();
+ }
+
+ for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) {
+ std::string name(a->ifa_name);
+ boost::optional<HostAddress> address;
+ if (a->ifa_addr->sa_family == PF_INET) {
+ sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr);
+ address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
+ }
+ else if (a->ifa_addr->sa_family == PF_INET6) {
+ sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr);
+ address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
+ }
+ if (address) {
+ std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first;
+ i->second.addAddress(*address);
+ }
+ }
+
+ freeifaddrs(addrs);
+
+ std::vector<NetworkInterface> result;
+ for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
+ result.push_back(i->second);
+ }
+ return result;
}
}
diff --git a/Swiften/Network/SolarisNetworkEnvironment.h b/Swiften/Network/SolarisNetworkEnvironment.h
index ed5adb7..6dc9673 100644
--- a/Swiften/Network/SolarisNetworkEnvironment.h
+++ b/Swiften/Network/SolarisNetworkEnvironment.h
@@ -20,9 +20,9 @@
namespace Swift {
- class SolarisNetworkEnvironment : public NetworkEnvironment {
- public:
- std::vector<NetworkInterface> getNetworkInterfaces() const;
- };
+ class SolarisNetworkEnvironment : public NetworkEnvironment {
+ public:
+ std::vector<NetworkInterface> getNetworkInterfaces() const;
+ };
}
diff --git a/Swiften/Network/StaticDomainNameResolver.cpp b/Swiften/Network/StaticDomainNameResolver.cpp
index ab24be5..45e6c5f 100644
--- a/Swiften/Network/StaticDomainNameResolver.cpp
+++ b/Swiften/Network/StaticDomainNameResolver.cpp
@@ -17,65 +17,65 @@
using namespace Swift;
namespace {
- struct ServiceQuery : public DomainNameServiceQuery, public boost::enable_shared_from_this<ServiceQuery> {
- ServiceQuery(const std::string& service, Swift::StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), service(service), resolver(resolver), owner(owner) {}
-
- virtual void run() {
- if (!resolver->getIsResponsive()) {
- return;
- }
- std::vector<DomainNameServiceQuery::Result> results;
- for(StaticDomainNameResolver::ServicesCollection::const_iterator i = resolver->getServices().begin(); i != resolver->getServices().end(); ++i) {
- if (i->first == service) {
- results.push_back(i->second);
- }
- }
- eventLoop->postEvent(boost::bind(&ServiceQuery::emitOnResult, shared_from_this(), results), owner);
- }
-
- void emitOnResult(std::vector<DomainNameServiceQuery::Result> results) {
- onResult(results);
- }
-
- EventLoop* eventLoop;
- std::string service;
- StaticDomainNameResolver* resolver;
- boost::shared_ptr<EventOwner> owner;
- };
-
- struct AddressQuery : public DomainNameAddressQuery, public boost::enable_shared_from_this<AddressQuery> {
- AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), host(host), resolver(resolver), owner(owner) {}
-
- virtual void run() {
- if (!resolver->getIsResponsive()) {
- return;
- }
- StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host);
- if (i != resolver->getAddresses().end()) {
- eventLoop->postEvent(
- boost::bind(&AddressQuery::emitOnResult, shared_from_this(), i->second, boost::optional<DomainNameResolveError>()));
- }
- else {
- eventLoop->postEvent(boost::bind(&AddressQuery::emitOnResult, shared_from_this(), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), owner);
- }
- }
-
- void emitOnResult(std::vector<HostAddress> results, boost::optional<DomainNameResolveError> error) {
- onResult(results, error);
- }
-
- EventLoop* eventLoop;
- std::string host;
- StaticDomainNameResolver* resolver;
- boost::shared_ptr<EventOwner> owner;
- };
+ struct ServiceQuery : public DomainNameServiceQuery, public boost::enable_shared_from_this<ServiceQuery> {
+ ServiceQuery(const std::string& service, Swift::StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), service(service), resolver(resolver), owner(owner) {}
+
+ virtual void run() {
+ if (!resolver->getIsResponsive()) {
+ return;
+ }
+ std::vector<DomainNameServiceQuery::Result> results;
+ for(StaticDomainNameResolver::ServicesCollection::const_iterator i = resolver->getServices().begin(); i != resolver->getServices().end(); ++i) {
+ if (i->first == service) {
+ results.push_back(i->second);
+ }
+ }
+ eventLoop->postEvent(boost::bind(&ServiceQuery::emitOnResult, shared_from_this(), results), owner);
+ }
+
+ void emitOnResult(std::vector<DomainNameServiceQuery::Result> results) {
+ onResult(results);
+ }
+
+ EventLoop* eventLoop;
+ std::string service;
+ StaticDomainNameResolver* resolver;
+ boost::shared_ptr<EventOwner> owner;
+ };
+
+ struct AddressQuery : public DomainNameAddressQuery, public boost::enable_shared_from_this<AddressQuery> {
+ AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, boost::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), host(host), resolver(resolver), owner(owner) {}
+
+ virtual void run() {
+ if (!resolver->getIsResponsive()) {
+ return;
+ }
+ StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host);
+ if (i != resolver->getAddresses().end()) {
+ eventLoop->postEvent(
+ boost::bind(&AddressQuery::emitOnResult, shared_from_this(), i->second, boost::optional<DomainNameResolveError>()));
+ }
+ else {
+ eventLoop->postEvent(boost::bind(&AddressQuery::emitOnResult, shared_from_this(), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), owner);
+ }
+ }
+
+ void emitOnResult(std::vector<HostAddress> results, boost::optional<DomainNameResolveError> error) {
+ onResult(results, error);
+ }
+
+ EventLoop* eventLoop;
+ std::string host;
+ StaticDomainNameResolver* resolver;
+ boost::shared_ptr<EventOwner> owner;
+ };
}
class StaticDomainNameResolverEventOwner : public EventOwner {
- public:
- ~StaticDomainNameResolverEventOwner() {
+ public:
+ ~StaticDomainNameResolverEventOwner() {
- }
+ }
};
@@ -85,36 +85,36 @@ StaticDomainNameResolver::StaticDomainNameResolver(EventLoop* eventLoop) : event
}
StaticDomainNameResolver::~StaticDomainNameResolver() {
- eventLoop->removeEventsFromOwner(owner);
+ eventLoop->removeEventsFromOwner(owner);
}
void StaticDomainNameResolver::addAddress(const std::string& domain, const HostAddress& address) {
- addresses[domain].push_back(address);
+ addresses[domain].push_back(address);
}
void StaticDomainNameResolver::addService(const std::string& service, const DomainNameServiceQuery::Result& result) {
- services.push_back(std::make_pair(service, result));
+ services.push_back(std::make_pair(service, result));
}
void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const HostAddressPort& address) {
- static int hostid = 0;
- std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid));
- hostid++;
+ static int hostid = 0;
+ std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid));
+ hostid++;
- addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0));
- addAddress(hostname, address.getAddress());
+ addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0));
+ addAddress(hostname, address.getAddress());
}
void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, int port) {
- addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0));
+ addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0));
}
boost::shared_ptr<DomainNameServiceQuery> StaticDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
- return boost::shared_ptr<DomainNameServiceQuery>(new ServiceQuery(serviceLookupPrefix + domain, this, eventLoop, owner));
+ return boost::shared_ptr<DomainNameServiceQuery>(new ServiceQuery(serviceLookupPrefix + domain, this, eventLoop, owner));
}
boost::shared_ptr<DomainNameAddressQuery> StaticDomainNameResolver::createAddressQuery(const std::string& name) {
- return boost::shared_ptr<DomainNameAddressQuery>(new AddressQuery(name, this, eventLoop, owner));
+ return boost::shared_ptr<DomainNameAddressQuery>(new AddressQuery(name, this, eventLoop, owner));
}
}
diff --git a/Swiften/Network/StaticDomainNameResolver.h b/Swiften/Network/StaticDomainNameResolver.h
index ebbc29f..6d38a26 100644
--- a/Swiften/Network/StaticDomainNameResolver.h
+++ b/Swiften/Network/StaticDomainNameResolver.h
@@ -18,43 +18,43 @@
#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
- class SWIFTEN_API StaticDomainNameResolver : public DomainNameResolver {
- public:
- typedef std::map<std::string, std::vector<HostAddress> > AddressesMap;
- typedef std::vector< std::pair<std::string, DomainNameServiceQuery::Result> > ServicesCollection;
-
- public:
- StaticDomainNameResolver(EventLoop* eventLoop);
- virtual ~StaticDomainNameResolver();
-
- void addAddress(const std::string& domain, const HostAddress& address);
- void addService(const std::string& service, const DomainNameServiceQuery::Result& result);
- void addXMPPClientService(const std::string& domain, const HostAddressPort&);
- void addXMPPClientService(const std::string& domain, const std::string& host, int port);
-
- const AddressesMap& getAddresses() const {
- return addresses;
- }
-
- const ServicesCollection& getServices() const {
- return services;
- }
-
- bool getIsResponsive() const {
- return isResponsive;
- }
-
- void setIsResponsive(bool b) {
- isResponsive = b;
- }
-
- virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
- virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name);
- private:
- EventLoop* eventLoop;
- bool isResponsive;
- AddressesMap addresses;
- ServicesCollection services;
- boost::shared_ptr<EventOwner> owner;
- };
+ class SWIFTEN_API StaticDomainNameResolver : public DomainNameResolver {
+ public:
+ typedef std::map<std::string, std::vector<HostAddress> > AddressesMap;
+ typedef std::vector< std::pair<std::string, DomainNameServiceQuery::Result> > ServicesCollection;
+
+ public:
+ StaticDomainNameResolver(EventLoop* eventLoop);
+ virtual ~StaticDomainNameResolver();
+
+ void addAddress(const std::string& domain, const HostAddress& address);
+ void addService(const std::string& service, const DomainNameServiceQuery::Result& result);
+ void addXMPPClientService(const std::string& domain, const HostAddressPort&);
+ void addXMPPClientService(const std::string& domain, const std::string& host, int port);
+
+ const AddressesMap& getAddresses() const {
+ return addresses;
+ }
+
+ const ServicesCollection& getServices() const {
+ return services;
+ }
+
+ bool getIsResponsive() const {
+ return isResponsive;
+ }
+
+ void setIsResponsive(bool b) {
+ isResponsive = b;
+ }
+
+ virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name);
+ private:
+ EventLoop* eventLoop;
+ bool isResponsive;
+ AddressesMap addresses;
+ ServicesCollection services;
+ boost::shared_ptr<EventOwner> owner;
+ };
}
diff --git a/Swiften/Network/TLSConnection.cpp b/Swiften/Network/TLSConnection.cpp
index c7087ae..4099de7 100644
--- a/Swiften/Network/TLSConnection.cpp
+++ b/Swiften/Network/TLSConnection.cpp
@@ -15,85 +15,85 @@
namespace Swift {
TLSConnection::TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions& tlsOptions) : connection(connection) {
- context = tlsFactory->createTLSContext(tlsOptions);
- context->onDataForNetwork.connect(boost::bind(&TLSConnection::handleTLSDataForNetwork, this, _1));
- context->onDataForApplication.connect(boost::bind(&TLSConnection::handleTLSDataForApplication, this, _1));
- context->onConnected.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, false));
- context->onError.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, true));
+ context = tlsFactory->createTLSContext(tlsOptions);
+ context->onDataForNetwork.connect(boost::bind(&TLSConnection::handleTLSDataForNetwork, this, _1));
+ context->onDataForApplication.connect(boost::bind(&TLSConnection::handleTLSDataForApplication, this, _1));
+ context->onConnected.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, false));
+ context->onError.connect(boost::bind(&TLSConnection::handleTLSConnectFinished, this, true));
- connection->onConnectFinished.connect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
- connection->onDataRead.connect(boost::bind(&TLSConnection::handleRawDataRead, this, _1));
- connection->onDataWritten.connect(boost::bind(&TLSConnection::handleRawDataWritten, this));
- connection->onDisconnected.connect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1));
+ connection->onConnectFinished.connect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
+ connection->onDataRead.connect(boost::bind(&TLSConnection::handleRawDataRead, this, _1));
+ connection->onDataWritten.connect(boost::bind(&TLSConnection::handleRawDataWritten, this));
+ connection->onDisconnected.connect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1));
}
TLSConnection::~TLSConnection() {
- connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
- connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1));
- connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this));
- connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1));
- delete context;
+ connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
+ connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1));
+ connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this));
+ connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1));
+ delete context;
}
void TLSConnection::handleTLSConnectFinished(bool error) {
- onConnectFinished(error);
- if (error) {
- disconnect();
- }
+ onConnectFinished(error);
+ if (error) {
+ disconnect();
+ }
}
void TLSConnection::handleTLSDataForNetwork(const SafeByteArray& data) {
- connection->write(data);
+ connection->write(data);
}
void TLSConnection::handleTLSDataForApplication(const SafeByteArray& data) {
- onDataRead(boost::make_shared<SafeByteArray>(data));
+ onDataRead(boost::make_shared<SafeByteArray>(data));
}
void TLSConnection::connect(const HostAddressPort& address) {
- connection->connect(address);
+ connection->connect(address);
}
void TLSConnection::disconnect() {
- connection->disconnect();
+ connection->disconnect();
}
void TLSConnection::write(const SafeByteArray& data) {
- context->handleDataFromApplication(data);
+ context->handleDataFromApplication(data);
}
HostAddressPort TLSConnection::getLocalAddress() const {
- return connection->getLocalAddress();
+ return connection->getLocalAddress();
}
HostAddressPort TLSConnection::getRemoteAddress() const {
- return connection->getRemoteAddress();
+ return connection->getRemoteAddress();
}
TLSContext* TLSConnection::getTLSContext() const {
- return context;
+ return context;
}
void TLSConnection::handleRawConnectFinished(bool error) {
- connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
- if (error) {
- onConnectFinished(true);
- }
- else {
- context->connect();
- }
+ connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1));
+ if (error) {
+ onConnectFinished(true);
+ }
+ else {
+ context->connect();
+ }
}
void TLSConnection::handleRawDisconnected(const boost::optional<Error>& error) {
- onDisconnected(error);
+ onDisconnected(error);
}
void TLSConnection::handleRawDataRead(boost::shared_ptr<SafeByteArray> data) {
- context->handleDataFromNetwork(*data);
+ context->handleDataFromNetwork(*data);
}
void TLSConnection::handleRawDataWritten() {
- onDataWritten();
+ onDataWritten();
}
}
diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h
index b3acffc..41543a2 100644
--- a/Swiften/Network/TLSConnection.h
+++ b/Swiften/Network/TLSConnection.h
@@ -16,37 +16,37 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class HostAddressPort;
- class TLSContextFactory;
- class TLSContext;
-
- class SWIFTEN_API TLSConnection : public Connection {
- public:
-
- TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions&);
- virtual ~TLSConnection();
-
- virtual void listen() {assert(false);}
- virtual void connect(const HostAddressPort& address);
- virtual void disconnect();
- virtual void write(const SafeByteArray& data);
-
- virtual HostAddressPort getLocalAddress() const;
- virtual HostAddressPort getRemoteAddress() const;
-
- TLSContext* getTLSContext() const;
-
- private:
- void handleRawConnectFinished(bool error);
- void handleRawDisconnected(const boost::optional<Error>& error);
- void handleRawDataRead(boost::shared_ptr<SafeByteArray> data);
- void handleRawDataWritten();
- void handleTLSConnectFinished(bool error);
- void handleTLSDataForNetwork(const SafeByteArray& data);
- void handleTLSDataForApplication(const SafeByteArray& data);
-
- private:
- TLSContext* context;
- Connection::ref connection;
- };
+ class HostAddressPort;
+ class TLSContextFactory;
+ class TLSContext;
+
+ class SWIFTEN_API TLSConnection : public Connection {
+ public:
+
+ TLSConnection(Connection::ref connection, TLSContextFactory* tlsFactory, const TLSOptions&);
+ virtual ~TLSConnection();
+
+ virtual void listen() {assert(false);}
+ virtual void connect(const HostAddressPort& address);
+ virtual void disconnect();
+ virtual void write(const SafeByteArray& data);
+
+ virtual HostAddressPort getLocalAddress() const;
+ virtual HostAddressPort getRemoteAddress() const;
+
+ TLSContext* getTLSContext() const;
+
+ private:
+ void handleRawConnectFinished(bool error);
+ void handleRawDisconnected(const boost::optional<Error>& error);
+ void handleRawDataRead(boost::shared_ptr<SafeByteArray> data);
+ void handleRawDataWritten();
+ void handleTLSConnectFinished(bool error);
+ void handleTLSDataForNetwork(const SafeByteArray& data);
+ void handleTLSDataForApplication(const SafeByteArray& data);
+
+ private:
+ TLSContext* context;
+ Connection::ref connection;
+ };
}
diff --git a/Swiften/Network/TLSConnectionFactory.cpp b/Swiften/Network/TLSConnectionFactory.cpp
index cc20b2d..e0396e2 100644
--- a/Swiften/Network/TLSConnectionFactory.cpp
+++ b/Swiften/Network/TLSConnectionFactory.cpp
@@ -22,7 +22,7 @@ TLSConnectionFactory::~TLSConnectionFactory() {
boost::shared_ptr<Connection> TLSConnectionFactory::createConnection() {
- return boost::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_);
+ return boost::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_);
}
}
diff --git a/Swiften/Network/TLSConnectionFactory.h b/Swiften/Network/TLSConnectionFactory.h
index 0c67014..8e39c35 100644
--- a/Swiften/Network/TLSConnectionFactory.h
+++ b/Swiften/Network/TLSConnectionFactory.h
@@ -14,17 +14,17 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class Connection;
+ class Connection;
- class SWIFTEN_API TLSConnectionFactory : public ConnectionFactory {
- public:
- TLSConnectionFactory(TLSContextFactory* contextFactory, ConnectionFactory* connectionFactory, const TLSOptions&);
- virtual ~TLSConnectionFactory();
+ class SWIFTEN_API TLSConnectionFactory : public ConnectionFactory {
+ public:
+ TLSConnectionFactory(TLSContextFactory* contextFactory, ConnectionFactory* connectionFactory, const TLSOptions&);
+ virtual ~TLSConnectionFactory();
- virtual boost::shared_ptr<Connection> createConnection();
- private:
- TLSContextFactory* contextFactory;
- ConnectionFactory* connectionFactory;
- TLSOptions options_;
- };
+ virtual boost::shared_ptr<Connection> createConnection();
+ private:
+ TLSContextFactory* contextFactory;
+ ConnectionFactory* connectionFactory;
+ TLSOptions options_;
+ };
}
diff --git a/Swiften/Network/Timer.h b/Swiften/Network/Timer.h
index 2697200..1abf5bc 100644
--- a/Swiften/Network/Timer.h
+++ b/Swiften/Network/Timer.h
@@ -10,32 +10,32 @@
#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- /**
- * A class for triggering an event after a given period.
- */
- class SWIFTEN_API Timer {
- public:
- typedef boost::shared_ptr<Timer> ref;
+ /**
+ * A class for triggering an event after a given period.
+ */
+ class SWIFTEN_API Timer {
+ public:
+ typedef boost::shared_ptr<Timer> ref;
- virtual ~Timer();
+ virtual ~Timer();
- /**
- * Starts the timer.
- *
- * After the given period, onTick() will be called.
- */
- virtual void start() = 0;
+ /**
+ * Starts the timer.
+ *
+ * After the given period, onTick() will be called.
+ */
+ virtual void start() = 0;
- /**
- * Cancels the timer.
- *
- * If the timer was started, onTick() will no longer be called.
- */
- virtual void stop() = 0;
+ /**
+ * Cancels the timer.
+ *
+ * If the timer was started, onTick() will no longer be called.
+ */
+ virtual void stop() = 0;
- /**
- * Emitted when the timer expires.
- */
- boost::signal<void ()> onTick;
- };
+ /**
+ * Emitted when the timer expires.
+ */
+ boost::signal<void ()> onTick;
+ };
}
diff --git a/Swiften/Network/TimerFactory.h b/Swiften/Network/TimerFactory.h
index a27e76e..47e89f8 100644
--- a/Swiften/Network/TimerFactory.h
+++ b/Swiften/Network/TimerFactory.h
@@ -12,10 +12,10 @@
#include <Swiften/Network/Timer.h>
namespace Swift {
- class SWIFTEN_API TimerFactory {
- public:
- virtual ~TimerFactory();
+ class SWIFTEN_API TimerFactory {
+ public:
+ virtual ~TimerFactory();
- virtual Timer::ref createTimer(int milliseconds) = 0;
- };
+ virtual Timer::ref createTimer(int milliseconds) = 0;
+ };
}
diff --git a/Swiften/Network/UnboundDomainNameResolver.cpp b/Swiften/Network/UnboundDomainNameResolver.cpp
index 68d40e1..a9fed24 100755
--- a/Swiften/Network/UnboundDomainNameResolver.cpp
+++ b/Swiften/Network/UnboundDomainNameResolver.cpp
@@ -34,219 +34,219 @@
namespace Swift {
class UnboundQuery {
- public:
- UnboundQuery(UnboundDomainNameResolver* resolver, ub_ctx* context) : resolver(resolver), ubContext(context) {}
- virtual ~UnboundQuery() {}
- virtual void handleResult(int err, ub_result* result) = 0;
- protected:
- UnboundDomainNameResolver* resolver;
- ub_ctx* ubContext;
+ public:
+ UnboundQuery(UnboundDomainNameResolver* resolver, ub_ctx* context) : resolver(resolver), ubContext(context) {}
+ virtual ~UnboundQuery() {}
+ virtual void handleResult(int err, ub_result* result) = 0;
+ protected:
+ UnboundDomainNameResolver* resolver;
+ ub_ctx* ubContext;
};
struct UnboundWrapperHelper {
- UnboundWrapperHelper(UnboundDomainNameResolver* resolver, boost::shared_ptr<UnboundQuery> query) : resolver(resolver), query(query) {}
- UnboundDomainNameResolver* resolver;
- boost::shared_ptr<UnboundQuery> query;
+ UnboundWrapperHelper(UnboundDomainNameResolver* resolver, boost::shared_ptr<UnboundQuery> query) : resolver(resolver), query(query) {}
+ UnboundDomainNameResolver* resolver;
+ boost::shared_ptr<UnboundQuery> query;
};
class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public UnboundQuery, public boost::enable_shared_from_this<UnboundDomainNameServiceQuery> {
- public:
- UnboundDomainNameServiceQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) {
- }
-
- virtual ~UnboundDomainNameServiceQuery() { }
-
- virtual void run() {
- int retval;
- UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this());
-
- retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_SRV,
- 1 /* CLASS IN (internet) */,
- helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL);
- if(retval != 0) {
- SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl;
- delete helper;
- }
- }
-
- void handleResult(int err, struct ub_result* result) {
- std::vector<DomainNameServiceQuery::Result> serviceRecords;
-
- if(err != 0) {
- SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl;
- } else {
- if(result->havedata) {
- ldns_pkt* replyPacket = 0;
- ldns_buffer* buffer = ldns_buffer_new(1024);
- if (buffer && ldns_wire2pkt(&replyPacket, static_cast<const uint8_t*>(result->answer_packet), result->answer_len) == LDNS_STATUS_OK) {
- ldns_rr_list* rrList = ldns_pkt_answer(replyPacket);
- for (size_t n = 0; n < ldns_rr_list_rr_count(rrList); n++) {
- ldns_rr* rr = ldns_rr_list_rr(rrList, n);
- if ((ldns_rr_get_type(rr) != LDNS_RR_TYPE_SRV) ||
- (ldns_rr_get_class(rr) != LDNS_RR_CLASS_IN) ||
- (ldns_rr_rd_count(rr) != 4)) {
- continue;
- }
-
- DomainNameServiceQuery::Result serviceRecord;
- serviceRecord.priority = ldns_rdf2native_int16(ldns_rr_rdf(rr, 0));
- serviceRecord.weight = ldns_rdf2native_int16(ldns_rr_rdf(rr, 1));
- serviceRecord.port = ldns_rdf2native_int16(ldns_rr_rdf(rr, 2));
-
- ldns_buffer_rewind(buffer);
- if ((ldns_rdf2buffer_str_dname(buffer, ldns_rr_rdf(rr, 3)) != LDNS_STATUS_OK) ||
- (ldns_buffer_position(buffer) < 2) ||
- !ldns_buffer_reserve(buffer, 1)) {
- // either name invalid, empty or buffer to small
- continue;
- }
- char terminator = 0;
- ldns_buffer_write(buffer, &terminator, sizeof(terminator));
-
- serviceRecord.hostname = std::string(reinterpret_cast<char*>(ldns_buffer_at(buffer, 0)));
- serviceRecords.push_back(serviceRecord);
- SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added" << std::endl;
- }
- }
- if (replyPacket) ldns_pkt_free(replyPacket);
- if (buffer) ldns_buffer_free(buffer);
- }
- }
-
- ub_resolve_free(result);
- onResult(serviceRecords);
- }
-
- private:
- std::string name;
+ public:
+ UnboundDomainNameServiceQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) {
+ }
+
+ virtual ~UnboundDomainNameServiceQuery() { }
+
+ virtual void run() {
+ int retval;
+ UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this());
+
+ retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_SRV,
+ 1 /* CLASS IN (internet) */,
+ helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL);
+ if(retval != 0) {
+ SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl;
+ delete helper;
+ }
+ }
+
+ void handleResult(int err, struct ub_result* result) {
+ std::vector<DomainNameServiceQuery::Result> serviceRecords;
+
+ if(err != 0) {
+ SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl;
+ } else {
+ if(result->havedata) {
+ ldns_pkt* replyPacket = 0;
+ ldns_buffer* buffer = ldns_buffer_new(1024);
+ if (buffer && ldns_wire2pkt(&replyPacket, static_cast<const uint8_t*>(result->answer_packet), result->answer_len) == LDNS_STATUS_OK) {
+ ldns_rr_list* rrList = ldns_pkt_answer(replyPacket);
+ for (size_t n = 0; n < ldns_rr_list_rr_count(rrList); n++) {
+ ldns_rr* rr = ldns_rr_list_rr(rrList, n);
+ if ((ldns_rr_get_type(rr) != LDNS_RR_TYPE_SRV) ||
+ (ldns_rr_get_class(rr) != LDNS_RR_CLASS_IN) ||
+ (ldns_rr_rd_count(rr) != 4)) {
+ continue;
+ }
+
+ DomainNameServiceQuery::Result serviceRecord;
+ serviceRecord.priority = ldns_rdf2native_int16(ldns_rr_rdf(rr, 0));
+ serviceRecord.weight = ldns_rdf2native_int16(ldns_rr_rdf(rr, 1));
+ serviceRecord.port = ldns_rdf2native_int16(ldns_rr_rdf(rr, 2));
+
+ ldns_buffer_rewind(buffer);
+ if ((ldns_rdf2buffer_str_dname(buffer, ldns_rr_rdf(rr, 3)) != LDNS_STATUS_OK) ||
+ (ldns_buffer_position(buffer) < 2) ||
+ !ldns_buffer_reserve(buffer, 1)) {
+ // either name invalid, empty or buffer to small
+ continue;
+ }
+ char terminator = 0;
+ ldns_buffer_write(buffer, &terminator, sizeof(terminator));
+
+ serviceRecord.hostname = std::string(reinterpret_cast<char*>(ldns_buffer_at(buffer, 0)));
+ serviceRecords.push_back(serviceRecord);
+ SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added" << std::endl;
+ }
+ }
+ if (replyPacket) ldns_pkt_free(replyPacket);
+ if (buffer) ldns_buffer_free(buffer);
+ }
+ }
+
+ ub_resolve_free(result);
+ onResult(serviceRecords);
+ }
+
+ private:
+ std::string name;
};
class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public UnboundQuery, public boost::enable_shared_from_this<UnboundDomainNameAddressQuery> {
- public:
- UnboundDomainNameAddressQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) {
- }
-
- virtual ~UnboundDomainNameAddressQuery() { }
-
- virtual void run() {
- int retval;
- UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this());
-
- //FIXME: support AAAA queries in some way
- retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_A,
- 1 /* CLASS IN (internet) */,
- helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL);
- if(retval != 0) {
- SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl;
- delete helper;
- }
- }
-
- void handleResult(int err, struct ub_result* result) {
- std::vector<HostAddress> addresses;
- boost::optional<DomainNameResolveError> error;
- SWIFT_LOG(debug) << "Result for: " << name << std::endl;
-
- if(err != 0) {
- SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl;
- error = DomainNameResolveError();
- } else {
- if(result->havedata) {
- for(int i=0; result->data[i]; i++) {
- char address[100];
- const char* addressStr = 0;
- if ((addressStr = inet_ntop(AF_INET, result->data[i], address, 100))) {
- SWIFT_LOG(debug) << "IPv4 address: " << addressStr << std::endl;
- addresses.push_back(HostAddress(std::string(addressStr)));
- } else if ((addressStr = inet_ntop(AF_INET6, result->data[i], address, 100))) {
- SWIFT_LOG(debug) << "IPv6 address: " << addressStr << std::endl;
- addresses.push_back(HostAddress(std::string(addressStr)));
- } else {
- SWIFT_LOG(debug) << "inet_ntop() failed" << std::endl;
- error = DomainNameResolveError();
- }
- }
- } else {
- error = DomainNameResolveError();
- }
- }
-
- ub_resolve_free(result);
- onResult(addresses, error);
- }
-
- private:
- std::string name;
+ public:
+ UnboundDomainNameAddressQuery(UnboundDomainNameResolver* resolver, ub_ctx* context, std::string name) : UnboundQuery(resolver, context), name(name) {
+ }
+
+ virtual ~UnboundDomainNameAddressQuery() { }
+
+ virtual void run() {
+ int retval;
+ UnboundWrapperHelper* helper = new UnboundWrapperHelper(resolver, shared_from_this());
+
+ //FIXME: support AAAA queries in some way
+ retval = ub_resolve_async(ubContext, const_cast<char*>(name.c_str()), LDNS_RR_TYPE_A,
+ 1 /* CLASS IN (internet) */,
+ helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL);
+ if(retval != 0) {
+ SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl;
+ delete helper;
+ }
+ }
+
+ void handleResult(int err, struct ub_result* result) {
+ std::vector<HostAddress> addresses;
+ boost::optional<DomainNameResolveError> error;
+ SWIFT_LOG(debug) << "Result for: " << name << std::endl;
+
+ if(err != 0) {
+ SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl;
+ error = DomainNameResolveError();
+ } else {
+ if(result->havedata) {
+ for(int i=0; result->data[i]; i++) {
+ char address[100];
+ const char* addressStr = 0;
+ if ((addressStr = inet_ntop(AF_INET, result->data[i], address, 100))) {
+ SWIFT_LOG(debug) << "IPv4 address: " << addressStr << std::endl;
+ addresses.push_back(HostAddress(std::string(addressStr)));
+ } else if ((addressStr = inet_ntop(AF_INET6, result->data[i], address, 100))) {
+ SWIFT_LOG(debug) << "IPv6 address: " << addressStr << std::endl;
+ addresses.push_back(HostAddress(std::string(addressStr)));
+ } else {
+ SWIFT_LOG(debug) << "inet_ntop() failed" << std::endl;
+ error = DomainNameResolveError();
+ }
+ }
+ } else {
+ error = DomainNameResolveError();
+ }
+ }
+
+ ub_resolve_free(result);
+ onResult(addresses, error);
+ }
+
+ private:
+ std::string name;
};
UnboundDomainNameResolver::UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : idnConverter(idnConverter), ioService(ioService), ubDescriptior(*ioService), eventLoop(eventLoop) {
- ubContext = ub_ctx_create();
- if(!ubContext) {
- SWIFT_LOG(debug) << "could not create unbound context" << std::endl;
- }
- eventOwner = boost::make_shared<EventOwner>();
+ ubContext = ub_ctx_create();
+ if(!ubContext) {
+ SWIFT_LOG(debug) << "could not create unbound context" << std::endl;
+ }
+ eventOwner = boost::make_shared<EventOwner>();
- ub_ctx_async(ubContext, true);
+ ub_ctx_async(ubContext, true);
- int ret;
+ int ret;
- /* read /etc/resolv.conf for DNS proxy settings (from DHCP) */
- if( (ret=ub_ctx_resolvconf(ubContext, const_cast<char*>("/etc/resolv.conf"))) != 0) {
- SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl;
- }
- /* read /etc/hosts for locally supplied host addresses */
- if( (ret=ub_ctx_hosts(ubContext, const_cast<char*>("/etc/hosts"))) != 0) {
- SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl;
- }
+ /* read /etc/resolv.conf for DNS proxy settings (from DHCP) */
+ if( (ret=ub_ctx_resolvconf(ubContext, const_cast<char*>("/etc/resolv.conf"))) != 0) {
+ SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl;
+ }
+ /* read /etc/hosts for locally supplied host addresses */
+ if( (ret=ub_ctx_hosts(ubContext, const_cast<char*>("/etc/hosts"))) != 0) {
+ SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl;
+ }
- ubDescriptior.assign(ub_fd(ubContext));
+ ubDescriptior.assign(ub_fd(ubContext));
- ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error));
+ ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error));
}
UnboundDomainNameResolver::~UnboundDomainNameResolver() {
- eventLoop->removeEventsFromOwner(eventOwner);
- if (ubContext) {
- ub_ctx_delete(ubContext);
- }
+ eventLoop->removeEventsFromOwner(eventOwner);
+ if (ubContext) {
+ ub_ctx_delete(ubContext);
+ }
}
void UnboundDomainNameResolver::unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result) {
- query->handleResult(err, result);
+ query->handleResult(err, result);
}
void UnboundDomainNameResolver::unbound_callback_wrapper(void* data, int err, ub_result* result) {
- UnboundWrapperHelper* helper = static_cast<UnboundWrapperHelper*>(data);
- UnboundDomainNameResolver* resolver = helper->resolver;
- resolver->unbound_callback(helper->query, err, result);
- delete helper;
+ UnboundWrapperHelper* helper = static_cast<UnboundWrapperHelper*>(data);
+ UnboundDomainNameResolver* resolver = helper->resolver;
+ resolver->unbound_callback(helper->query, err, result);
+ delete helper;
}
void UnboundDomainNameResolver::handleUBSocketReadable(boost::system::error_code) {
- eventLoop->postEvent(boost::bind(&UnboundDomainNameResolver::processData, this), eventOwner);
- ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error));
+ eventLoop->postEvent(boost::bind(&UnboundDomainNameResolver::processData, this), eventOwner);
+ ubDescriptior.async_read_some(boost::asio::null_buffers(), boost::bind(&UnboundDomainNameResolver::handleUBSocketReadable, this, boost::asio::placeholders::error));
}
void UnboundDomainNameResolver::processData() {
- if (ub_poll(ubContext)) {
- int ret = ub_process(ubContext);
- if(ret != 0) {
- SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret) << std::endl;
- }
- }
+ if (ub_poll(ubContext)) {
+ int ret = ub_process(ubContext);
+ if(ret != 0) {
+ SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret) << std::endl;
+ }
+ }
}
boost::shared_ptr<DomainNameServiceQuery> UnboundDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
- boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain);
- std::string result;
- if (encodedDomain) {
- result = serviceLookupPrefix + *encodedDomain;
- }
- return boost::make_shared<UnboundDomainNameServiceQuery>(this, ubContext, result);
+ boost::optional<std::string> encodedDomain = idnConverter->getIDNAEncoded(domain);
+ std::string result;
+ if (encodedDomain) {
+ result = serviceLookupPrefix + *encodedDomain;
+ }
+ return boost::make_shared<UnboundDomainNameServiceQuery>(this, ubContext, result);
}
boost::shared_ptr<DomainNameAddressQuery> UnboundDomainNameResolver::createAddressQuery(const std::string& name) {
- return boost::make_shared<UnboundDomainNameAddressQuery>(this, ubContext, idnConverter->getIDNAEncoded(name).get_value_or(""));
+ return boost::make_shared<UnboundDomainNameAddressQuery>(this, ubContext, idnConverter->getIDNAEncoded(name).get_value_or(""));
}
}
diff --git a/Swiften/Network/UnboundDomainNameResolver.h b/Swiften/Network/UnboundDomainNameResolver.h
index f7092eb..afb21c8 100755
--- a/Swiften/Network/UnboundDomainNameResolver.h
+++ b/Swiften/Network/UnboundDomainNameResolver.h
@@ -24,36 +24,36 @@ struct ub_ctx;
struct ub_result;
namespace Swift {
- class EventLoop;
- class IDNConverter;
- class TimerFactory;
+ class EventLoop;
+ class IDNConverter;
+ class TimerFactory;
- class UnboundDomainNameResolver;
- class UnboundQuery;
+ class UnboundDomainNameResolver;
+ class UnboundQuery;
- class UnboundDomainNameResolver : public DomainNameResolver, public EventOwner, public boost::enable_shared_from_this<UnboundDomainNameResolver> {
- public:
- UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
- virtual ~UnboundDomainNameResolver();
+ class UnboundDomainNameResolver : public DomainNameResolver, public EventOwner, public boost::enable_shared_from_this<UnboundDomainNameResolver> {
+ public:
+ UnboundDomainNameResolver(IDNConverter* idnConverter, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
+ virtual ~UnboundDomainNameResolver();
- virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
- virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name);
+ virtual boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name);
- static void unbound_callback_wrapper(void* data, int err, ub_result* result);
+ static void unbound_callback_wrapper(void* data, int err, ub_result* result);
- private:
- void unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result);
+ private:
+ void unbound_callback(boost::shared_ptr<UnboundQuery> query, int err, ub_result* result);
- void handleUBSocketReadable(boost::system::error_code);
- void processData();
+ void handleUBSocketReadable(boost::system::error_code);
+ void processData();
- private:
- IDNConverter* idnConverter;
- boost::shared_ptr<EventOwner> eventOwner;
- boost::shared_ptr<boost::asio::io_service> ioService;
- boost::asio::posix::stream_descriptor ubDescriptior;
- EventLoop* eventLoop;
- ub_ctx* ubContext;
- };
+ private:
+ IDNConverter* idnConverter;
+ boost::shared_ptr<EventOwner> eventOwner;
+ boost::shared_ptr<boost::asio::io_service> ioService;
+ boost::asio::posix::stream_descriptor ubDescriptior;
+ EventLoop* eventLoop;
+ ub_ctx* ubContext;
+ };
}
diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
index e8d8c4a..e781742 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
@@ -33,436 +33,436 @@ typedef boost::shared_ptr<BOSHConnectionPool> PoolRef;
class BOSHConnectionPoolTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BOSHConnectionPoolTest);
- CPPUNIT_TEST(testConnectionCount_OneWrite);
- CPPUNIT_TEST(testConnectionCount_TwoWrites);
- CPPUNIT_TEST(testConnectionCount_ThreeWrites);
- CPPUNIT_TEST(testConnectionCount_ThreeWrites_ManualConnect);
- CPPUNIT_TEST(testConnectionCount_ThreeWritesTwoReads);
- CPPUNIT_TEST(testSession);
- CPPUNIT_TEST(testWrite_Empty);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- to = "wonderland.lit";
- path = "/http-bind";
- port = "5280";
- sid = "MyShinySID";
- initial = "<body wait='60' "
- "inactivity='30' "
- "polling='5' "
- "requests='2' "
- "hold='1' "
- "maxpause='120' "
- "sid='" + sid + "' "
- "ver='1.6' "
- "from='wonderland.lit' "
- "xmlns='http://jabber.org/protocol/httpbind'/>";
- eventLoop = new DummyEventLoop();
- connectionFactory = new MockConnectionFactory(eventLoop);
- boshURL = URL("http", to, 5280, path);
- sessionTerminated = 0;
- sessionStarted = 0;
- initialRID = 2349876;
- xmppDataRead.clear();
- boshDataRead.clear();
- boshDataWritten.clear();
- resolver = new StaticDomainNameResolver(eventLoop);
- resolver->addAddress(to, HostAddress("127.0.0.1"));
- timerFactory = new DummyTimerFactory();
- }
-
- void tearDown() {
- eventLoop->processEvents();
- delete connectionFactory;
- delete resolver;
- delete timerFactory;
- delete eventLoop;
- }
-
- void testConnectionCount_OneWrite() {
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(0, sessionStarted);
- readResponse(initial, connectionFactory->connections[0]);
- CPPUNIT_ASSERT_EQUAL(1, sessionStarted);
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- testling->write(createSafeByteArray("<blah/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- CPPUNIT_ASSERT_EQUAL(1, sessionStarted);
- }
-
- void testConnectionCount_TwoWrites() {
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- eventLoop->processEvents();
- readResponse(initial, connectionFactory->connections[0]);
- eventLoop->processEvents();
- testling->write(createSafeByteArray("<blah/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- testling->write(createSafeByteArray("<bleh/>"));
- eventLoop->processEvents();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
- }
-
- void testConnectionCount_ThreeWrites() {
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- eventLoop->processEvents();
- readResponse(initial, connectionFactory->connections[0]);
- testling->restartStream();
- readResponse("<body/>", connectionFactory->connections[0]);
- testling->restartStream();
- readResponse("<body/>", connectionFactory->connections[0]);
- testling->write(createSafeByteArray("<blah/>"));
- testling->write(createSafeByteArray("<bleh/>"));
- testling->write(createSafeByteArray("<bluh/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size());
- }
-
- void testConnectionCount_ThreeWrites_ManualConnect() {
- connectionFactory->autoFinishConnect = false;
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- CPPUNIT_ASSERT_EQUAL(st(0), boshDataWritten.size()); /* Connection not connected yet, can't send data */
-
- connectionFactory->connections[0]->onConnectFinished(false);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Connection finished, stream header sent */
-
- readResponse(initial, connectionFactory->connections[0]);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Don't respond to initial data with a holding call */
-
- testling->restartStream();
- eventLoop->processEvents();
- readResponse("<body/>", connectionFactory->connections[0]);
- eventLoop->processEvents();
- testling->restartStream();
- eventLoop->processEvents();
-
-
- testling->write(createSafeByteArray("<blah/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
- CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); /* New connection isn't up yet. */
-
- connectionFactory->connections[1]->onConnectFinished(false);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New connection ready. */
-
- testling->write(createSafeByteArray("<bleh/>"));
- eventLoop->processEvents();
- testling->write(createSafeByteArray("<bluh/>"));
- CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New data can't be sent, no free connections. */
- eventLoop->processEvents();
- CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size());
- }
-
- void testConnectionCount_ThreeWritesTwoReads() {
- boost::shared_ptr<MockConnection> c0;
- boost::shared_ptr<MockConnection> c1;
- unsigned long long rid = initialRID;
-
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- c0 = connectionFactory->connections[0];
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/
-
- rid++;
- readResponse(initial, c0);
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- CPPUNIT_ASSERT(!c0->pending);
-
- rid++;
- testling->restartStream();
- eventLoop->processEvents();
- readResponse("<body/>", connectionFactory->connections[0]);
-
- rid++;
- testling->write(createSafeByteArray("<blah/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* 0 was waiting for response, open and send on 1 */
- CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* data */
- c1 = connectionFactory->connections[1];
- std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */
- CPPUNIT_ASSERT_EQUAL(fullBody, lastBody());
- CPPUNIT_ASSERT(c0->pending);
- CPPUNIT_ASSERT(c1->pending);
-
-
- rid++;
- readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing/></message></body>", c0); /* Doesn't include necessary attributes - as the support is improved this'll start to fail */
- eventLoop->processEvents();
- CPPUNIT_ASSERT(!c0->pending);
- CPPUNIT_ASSERT(c1->pending);
- CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* don't send empty in [0], still have [1] waiting */
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
-
- rid++;
- readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing><blittlebarg/></splatploing></message></body>", c1);
- eventLoop->processEvents();
- CPPUNIT_ASSERT(!c1->pending);
- CPPUNIT_ASSERT(c0->pending);
- CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* empty to make room */
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
-
- rid++;
- testling->write(createSafeByteArray("<bleh/>"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT(c0->pending);
- CPPUNIT_ASSERT(c1->pending);
- CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* data */
-
- rid++;
- testling->write(createSafeByteArray("<bluh/>"));
- CPPUNIT_ASSERT(c0->pending);
- CPPUNIT_ASSERT(c1->pending);
- CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* Don't send data, no room */
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
- }
-
- void testSession() {
- to = "prosody.doomsong.co.uk";
- resolver->addAddress("prosody.doomsong.co.uk", HostAddress("127.0.0.1"));
- path = "/http-bind/";
- boshURL = URL("http", to, 5280, path);
-
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- std::string response = "<body authid='743da605-4c2e-4de1-afac-ac040dd4a940' xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><auth xmlns='http://jabber.org/features/iq-auth'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>SCRAM-SHA-1</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features></body>";
- readResponse(response, connectionFactory->connections[0]);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- std::string send = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"SCRAM-SHA-1\">biwsbj1hZG1pbixyPWZhOWE5ZDhiLWZmMDctNGE4Yy04N2E3LTg4YWRiNDQxZGUwYg==</auth>";
- testling->write(createSafeByteArray(send));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>cj1mYTlhOWQ4Yi1mZjA3LTRhOGMtODdhNy04OGFkYjQ0MWRlMGJhZmZlMWNhMy1mMDJkLTQ5NzEtYjkyNS0yM2NlNWQ2MDQyMjYscz1OVGd5WkdWaFptTXRaVE15WXkwMFpXUmhMV0ZqTURRdFpqYzRNbUppWmpGa1pqWXgsaT00MDk2</challenge></body>";
- readResponse(response, connectionFactory->connections[0]);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- send = "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">Yz1iaXdzLHI9ZmE5YTlkOGItZmYwNy00YThjLTg3YTctODhhZGI0NDFkZTBiYWZmZTFjYTMtZjAyZC00OTcxLWI5MjUtMjNjZTVkNjA0MjI2LHA9aU11NWt3dDN2VWplU2RqL01Jb3VIRldkZjBnPQ==</response>";
- testling->write(createSafeByteArray(send));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>dj1YNmNBY3BBOWxHNjNOOXF2bVQ5S0FacERrVm89</success></body>";
- readResponse(response, connectionFactory->connections[0]);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- testling->restartStream();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- response = "<body xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind><session xmlns='urn:ietf:params:xml:ns:xmpp-session'><optional/></session><sm xmlns='urn:xmpp:sm:2'><optional/></sm></stream:features></body>";
- readResponse(response, connectionFactory->connections[0]);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* Now we've authed (restarted) we should be keeping one query in flight so the server can reply to us at any time it wants. */
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
-
- send = "<body rid='2821988967416214' sid='cf663f6b94279d4f' xmlns='http://jabber.org/protocol/httpbind'><iq id='session-bind' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>d5a9744036cd20a0</resource></bind></iq></body>";
- testling->write(createSafeByteArray(send));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size());
- CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* and as it keeps one in flight, it's needed to open a second to send these data */
-
- }
-
- void testWrite_Empty() {
- boost::shared_ptr<MockConnection> c0;
-
- PoolRef testling = createTestling();
- CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
- c0 = connectionFactory->connections[0];
-
- readResponse(initial, c0);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Shouldn't have sent anything extra */
- eventLoop->processEvents();
- testling->restartStream();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
- readResponse("<body></body>", c0);
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
- std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>";
- std::string response = boshDataWritten[2];
- size_t bodyPosition = response.find("\r\n\r\n");
- CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4));
-
-
- }
-
- private:
-
- PoolRef createTestling() {
- // make_shared is limited to 9 arguments; instead new is used here.
- PoolRef pool = PoolRef(new BOSHConnectionPool(boshURL, resolver, connectionFactory, &parserFactory, static_cast<TLSContextFactory*>(NULL), timerFactory, eventLoop, to, initialRID, URL(), SafeString(""), SafeString(""), TLSOptions()));
- pool->open();
- pool->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleXMPPDataRead, this, _1));
- pool->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataRead, this, _1));
- pool->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataWritten, this, _1));
- pool->onSessionStarted.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionStarted, this));
- pool->onSessionTerminated.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionTerminated, this));
- eventLoop->processEvents();
- eventLoop->processEvents();
- return pool;
- }
-
- std::string lastBody() {
- std::string response = boshDataWritten[boshDataWritten.size() - 1];
- size_t bodyPosition = response.find("\r\n\r\n");
- return response.substr(bodyPosition+4);
- }
-
- size_t st(int val) {
- return static_cast<size_t>(val);
- }
-
- void handleXMPPDataRead(const SafeByteArray& d) {
- xmppDataRead.push_back(safeByteArrayToString(d));
- }
-
- void handleBOSHDataRead(const SafeByteArray& d) {
- boshDataRead.push_back(safeByteArrayToString(d));
- }
-
- void handleBOSHDataWritten(const SafeByteArray& d) {
- boshDataWritten.push_back(safeByteArrayToString(d));
- }
-
-
- void handleSessionStarted() {
- sessionStarted++;
- }
-
- void handleSessionTerminated() {
- sessionTerminated++;
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop, bool autoFinishConnect) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false), pending(false), autoFinishConnect(autoFinishConnect) {
- }
-
- void listen() { assert(false); }
-
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- if (autoFinishConnect) {
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-
- void disconnect() {
- disconnected = true;
- onDisconnected(boost::optional<Connection::Error>());
- }
-
- void write(const SafeByteArray& d) {
- append(dataWritten, d);
- pending = true;
- }
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- ByteArray dataWritten;
- bool disconnected;
- bool pending;
- bool autoFinishConnect;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop, bool autoFinishConnect = true) : eventLoop(eventLoop), autoFinishConnect(autoFinishConnect) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop, autoFinishConnect);
- connections.push_back(connection);
- return connection;
- }
-
- EventLoop* eventLoop;
- std::vector< boost::shared_ptr<MockConnection> > connections;
- std::vector<HostAddressPort> failingPorts;
- bool autoFinishConnect;
- };
-
- void readResponse(const std::string& response, boost::shared_ptr<MockConnection> connection) {
- connection->pending = false;
- boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: text/xml; charset=utf-8\r\n"
- "Access-Control-Allow-Origin: *\r\n"
- "Access-Control-Allow-Headers: Content-Type\r\n"
- "Content-Length: "));
- connection->onDataRead(data1);
- boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
- connection->onDataRead(data2);
- boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
- connection->onDataRead(data3);
- boost::shared_ptr<SafeByteArray> data4 = boost::make_shared<SafeByteArray>(createSafeByteArray(response));
- connection->onDataRead(data4);
- }
-
- std::string fullRequestFor(const std::string& data) {
- std::string body = data;
- std::string result = "POST /" + path + " HTTP/1.1\r\n"
- + "Host: " + to + ":" + port + "\r\n"
- + "Content-Type: text/xml; charset=utf-8\r\n"
- + "Content-Length: " + boost::lexical_cast<std::string>(body.size()) + "\r\n\r\n"
- + body;
- return result;
- }
-
- private:
- URL boshURL;
- DummyEventLoop* eventLoop;
- MockConnectionFactory* connectionFactory;
- std::vector<std::string> xmppDataRead;
- std::vector<std::string> boshDataRead;
- std::vector<std::string> boshDataWritten;
- PlatformXMLParserFactory parserFactory;
- StaticDomainNameResolver* resolver;
- TimerFactory* timerFactory;
- std::string to;
- std::string path;
- std::string port;
- std::string sid;
- std::string initial;
- unsigned long long initialRID;
- int sessionStarted;
- int sessionTerminated;
+ CPPUNIT_TEST_SUITE(BOSHConnectionPoolTest);
+ CPPUNIT_TEST(testConnectionCount_OneWrite);
+ CPPUNIT_TEST(testConnectionCount_TwoWrites);
+ CPPUNIT_TEST(testConnectionCount_ThreeWrites);
+ CPPUNIT_TEST(testConnectionCount_ThreeWrites_ManualConnect);
+ CPPUNIT_TEST(testConnectionCount_ThreeWritesTwoReads);
+ CPPUNIT_TEST(testSession);
+ CPPUNIT_TEST(testWrite_Empty);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ to = "wonderland.lit";
+ path = "/http-bind";
+ port = "5280";
+ sid = "MyShinySID";
+ initial = "<body wait='60' "
+ "inactivity='30' "
+ "polling='5' "
+ "requests='2' "
+ "hold='1' "
+ "maxpause='120' "
+ "sid='" + sid + "' "
+ "ver='1.6' "
+ "from='wonderland.lit' "
+ "xmlns='http://jabber.org/protocol/httpbind'/>";
+ eventLoop = new DummyEventLoop();
+ connectionFactory = new MockConnectionFactory(eventLoop);
+ boshURL = URL("http", to, 5280, path);
+ sessionTerminated = 0;
+ sessionStarted = 0;
+ initialRID = 2349876;
+ xmppDataRead.clear();
+ boshDataRead.clear();
+ boshDataWritten.clear();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ resolver->addAddress(to, HostAddress("127.0.0.1"));
+ timerFactory = new DummyTimerFactory();
+ }
+
+ void tearDown() {
+ eventLoop->processEvents();
+ delete connectionFactory;
+ delete resolver;
+ delete timerFactory;
+ delete eventLoop;
+ }
+
+ void testConnectionCount_OneWrite() {
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(0, sessionStarted);
+ readResponse(initial, connectionFactory->connections[0]);
+ CPPUNIT_ASSERT_EQUAL(1, sessionStarted);
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ testling->write(createSafeByteArray("<blah/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ CPPUNIT_ASSERT_EQUAL(1, sessionStarted);
+ }
+
+ void testConnectionCount_TwoWrites() {
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ eventLoop->processEvents();
+ readResponse(initial, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ testling->write(createSafeByteArray("<blah/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ testling->write(createSafeByteArray("<bleh/>"));
+ eventLoop->processEvents();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
+ }
+
+ void testConnectionCount_ThreeWrites() {
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ eventLoop->processEvents();
+ readResponse(initial, connectionFactory->connections[0]);
+ testling->restartStream();
+ readResponse("<body/>", connectionFactory->connections[0]);
+ testling->restartStream();
+ readResponse("<body/>", connectionFactory->connections[0]);
+ testling->write(createSafeByteArray("<blah/>"));
+ testling->write(createSafeByteArray("<bleh/>"));
+ testling->write(createSafeByteArray("<bluh/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size());
+ }
+
+ void testConnectionCount_ThreeWrites_ManualConnect() {
+ connectionFactory->autoFinishConnect = false;
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ CPPUNIT_ASSERT_EQUAL(st(0), boshDataWritten.size()); /* Connection not connected yet, can't send data */
+
+ connectionFactory->connections[0]->onConnectFinished(false);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Connection finished, stream header sent */
+
+ readResponse(initial, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Don't respond to initial data with a holding call */
+
+ testling->restartStream();
+ eventLoop->processEvents();
+ readResponse("<body/>", connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ testling->restartStream();
+ eventLoop->processEvents();
+
+
+ testling->write(createSafeByteArray("<blah/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
+ CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); /* New connection isn't up yet. */
+
+ connectionFactory->connections[1]->onConnectFinished(false);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New connection ready. */
+
+ testling->write(createSafeByteArray("<bleh/>"));
+ eventLoop->processEvents();
+ testling->write(createSafeByteArray("<bluh/>"));
+ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* New data can't be sent, no free connections. */
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(st(2) >= connectionFactory->connections.size());
+ }
+
+ void testConnectionCount_ThreeWritesTwoReads() {
+ boost::shared_ptr<MockConnection> c0;
+ boost::shared_ptr<MockConnection> c1;
+ unsigned long long rid = initialRID;
+
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ c0 = connectionFactory->connections[0];
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/
+
+ rid++;
+ readResponse(initial, c0);
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ CPPUNIT_ASSERT(!c0->pending);
+
+ rid++;
+ testling->restartStream();
+ eventLoop->processEvents();
+ readResponse("<body/>", connectionFactory->connections[0]);
+
+ rid++;
+ testling->write(createSafeByteArray("<blah/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* 0 was waiting for response, open and send on 1 */
+ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* data */
+ c1 = connectionFactory->connections[1];
+ std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */
+ CPPUNIT_ASSERT_EQUAL(fullBody, lastBody());
+ CPPUNIT_ASSERT(c0->pending);
+ CPPUNIT_ASSERT(c1->pending);
+
+
+ rid++;
+ readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing/></message></body>", c0); /* Doesn't include necessary attributes - as the support is improved this'll start to fail */
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(!c0->pending);
+ CPPUNIT_ASSERT(c1->pending);
+ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* don't send empty in [0], still have [1] waiting */
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
+
+ rid++;
+ readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing><blittlebarg/></splatploing></message></body>", c1);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(!c1->pending);
+ CPPUNIT_ASSERT(c0->pending);
+ CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* empty to make room */
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
+
+ rid++;
+ testling->write(createSafeByteArray("<bleh/>"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(c0->pending);
+ CPPUNIT_ASSERT(c1->pending);
+ CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* data */
+
+ rid++;
+ testling->write(createSafeByteArray("<bluh/>"));
+ CPPUNIT_ASSERT(c0->pending);
+ CPPUNIT_ASSERT(c1->pending);
+ CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size()); /* Don't send data, no room */
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size());
+ }
+
+ void testSession() {
+ to = "prosody.doomsong.co.uk";
+ resolver->addAddress("prosody.doomsong.co.uk", HostAddress("127.0.0.1"));
+ path = "/http-bind/";
+ boshURL = URL("http", to, 5280, path);
+
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* header*/
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ std::string response = "<body authid='743da605-4c2e-4de1-afac-ac040dd4a940' xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><auth xmlns='http://jabber.org/features/iq-auth'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>SCRAM-SHA-1</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features></body>";
+ readResponse(response, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ std::string send = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"SCRAM-SHA-1\">biwsbj1hZG1pbixyPWZhOWE5ZDhiLWZmMDctNGE4Yy04N2E3LTg4YWRiNDQxZGUwYg==</auth>";
+ testling->write(createSafeByteArray(send));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>cj1mYTlhOWQ4Yi1mZjA3LTRhOGMtODdhNy04OGFkYjQ0MWRlMGJhZmZlMWNhMy1mMDJkLTQ5NzEtYjkyNS0yM2NlNWQ2MDQyMjYscz1OVGd5WkdWaFptTXRaVE15WXkwMFpXUmhMV0ZqTURRdFpqYzRNbUppWmpGa1pqWXgsaT00MDk2</challenge></body>";
+ readResponse(response, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ send = "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">Yz1iaXdzLHI9ZmE5YTlkOGItZmYwNy00YThjLTg3YTctODhhZGI0NDFkZTBiYWZmZTFjYTMtZjAyZC00OTcxLWI5MjUtMjNjZTVkNjA0MjI2LHA9aU11NWt3dDN2VWplU2RqL01Jb3VIRldkZjBnPQ==</response>";
+ testling->write(createSafeByteArray(send));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ response = "<body xmlns='http://jabber.org/protocol/httpbind' sid='743da605-4c2e-4de1-afac-ac040dd4a940' xmlns:stream = 'http://etherx.jabber.org/streams'><success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>dj1YNmNBY3BBOWxHNjNOOXF2bVQ5S0FacERrVm89</success></body>";
+ readResponse(response, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ testling->restartStream();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ response = "<body xmpp:version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns:xmpp='urn:xmpp:xbosh' inactivity='60' wait='60' polling='5' secure='true' hold='1' from='prosody.doomsong.co.uk' ver='1.6' sid='743da605-4c2e-4de1-afac-ac040dd4a940' requests='2' xmlns='http://jabber.org/protocol/httpbind'><stream:features><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind><session xmlns='urn:ietf:params:xml:ns:xmpp-session'><optional/></session><sm xmlns='urn:xmpp:sm:2'><optional/></sm></stream:features></body>";
+ readResponse(response, connectionFactory->connections[0]);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(5), boshDataWritten.size()); /* Now we've authed (restarted) we should be keeping one query in flight so the server can reply to us at any time it wants. */
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+
+ send = "<body rid='2821988967416214' sid='cf663f6b94279d4f' xmlns='http://jabber.org/protocol/httpbind'><iq id='session-bind' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>d5a9744036cd20a0</resource></bind></iq></body>";
+ testling->write(createSafeByteArray(send));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(6), boshDataWritten.size());
+ CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* and as it keeps one in flight, it's needed to open a second to send these data */
+
+ }
+
+ void testWrite_Empty() {
+ boost::shared_ptr<MockConnection> c0;
+
+ PoolRef testling = createTestling();
+ CPPUNIT_ASSERT_EQUAL(st(1), connectionFactory->connections.size());
+ c0 = connectionFactory->connections[0];
+
+ readResponse(initial, c0);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Shouldn't have sent anything extra */
+ eventLoop->processEvents();
+ testling->restartStream();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size());
+ readResponse("<body></body>", c0);
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size());
+ std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>";
+ std::string response = boshDataWritten[2];
+ size_t bodyPosition = response.find("\r\n\r\n");
+ CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4));
+
+
+ }
+
+ private:
+
+ PoolRef createTestling() {
+ // make_shared is limited to 9 arguments; instead new is used here.
+ PoolRef pool = PoolRef(new BOSHConnectionPool(boshURL, resolver, connectionFactory, &parserFactory, static_cast<TLSContextFactory*>(NULL), timerFactory, eventLoop, to, initialRID, URL(), SafeString(""), SafeString(""), TLSOptions()));
+ pool->open();
+ pool->onXMPPDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleXMPPDataRead, this, _1));
+ pool->onBOSHDataRead.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataRead, this, _1));
+ pool->onBOSHDataWritten.connect(boost::bind(&BOSHConnectionPoolTest::handleBOSHDataWritten, this, _1));
+ pool->onSessionStarted.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionStarted, this));
+ pool->onSessionTerminated.connect(boost::bind(&BOSHConnectionPoolTest::handleSessionTerminated, this));
+ eventLoop->processEvents();
+ eventLoop->processEvents();
+ return pool;
+ }
+
+ std::string lastBody() {
+ std::string response = boshDataWritten[boshDataWritten.size() - 1];
+ size_t bodyPosition = response.find("\r\n\r\n");
+ return response.substr(bodyPosition+4);
+ }
+
+ size_t st(int val) {
+ return static_cast<size_t>(val);
+ }
+
+ void handleXMPPDataRead(const SafeByteArray& d) {
+ xmppDataRead.push_back(safeByteArrayToString(d));
+ }
+
+ void handleBOSHDataRead(const SafeByteArray& d) {
+ boshDataRead.push_back(safeByteArrayToString(d));
+ }
+
+ void handleBOSHDataWritten(const SafeByteArray& d) {
+ boshDataWritten.push_back(safeByteArrayToString(d));
+ }
+
+
+ void handleSessionStarted() {
+ sessionStarted++;
+ }
+
+ void handleSessionTerminated() {
+ sessionTerminated++;
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop, bool autoFinishConnect) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false), pending(false), autoFinishConnect(autoFinishConnect) {
+ }
+
+ void listen() { assert(false); }
+
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ if (autoFinishConnect) {
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+
+ void disconnect() {
+ disconnected = true;
+ onDisconnected(boost::optional<Connection::Error>());
+ }
+
+ void write(const SafeByteArray& d) {
+ append(dataWritten, d);
+ pending = true;
+ }
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ ByteArray dataWritten;
+ bool disconnected;
+ bool pending;
+ bool autoFinishConnect;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop, bool autoFinishConnect = true) : eventLoop(eventLoop), autoFinishConnect(autoFinishConnect) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop, autoFinishConnect);
+ connections.push_back(connection);
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
+ std::vector<HostAddressPort> failingPorts;
+ bool autoFinishConnect;
+ };
+
+ void readResponse(const std::string& response, boost::shared_ptr<MockConnection> connection) {
+ connection->pending = false;
+ boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/xml; charset=utf-8\r\n"
+ "Access-Control-Allow-Origin: *\r\n"
+ "Access-Control-Allow-Headers: Content-Type\r\n"
+ "Content-Length: "));
+ connection->onDataRead(data1);
+ boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
+ connection->onDataRead(data2);
+ boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
+ connection->onDataRead(data3);
+ boost::shared_ptr<SafeByteArray> data4 = boost::make_shared<SafeByteArray>(createSafeByteArray(response));
+ connection->onDataRead(data4);
+ }
+
+ std::string fullRequestFor(const std::string& data) {
+ std::string body = data;
+ std::string result = "POST /" + path + " HTTP/1.1\r\n"
+ + "Host: " + to + ":" + port + "\r\n"
+ + "Content-Type: text/xml; charset=utf-8\r\n"
+ + "Content-Length: " + boost::lexical_cast<std::string>(body.size()) + "\r\n\r\n"
+ + body;
+ return result;
+ }
+
+ private:
+ URL boshURL;
+ DummyEventLoop* eventLoop;
+ MockConnectionFactory* connectionFactory;
+ std::vector<std::string> xmppDataRead;
+ std::vector<std::string> boshDataRead;
+ std::vector<std::string> boshDataWritten;
+ PlatformXMLParserFactory parserFactory;
+ StaticDomainNameResolver* resolver;
+ TimerFactory* timerFactory;
+ std::string to;
+ std::string path;
+ std::string port;
+ std::string sid;
+ std::string initial;
+ unsigned long long initialRID;
+ int sessionStarted;
+ int sessionTerminated;
};
diff --git a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
index 8d26a09..bae84fd 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
@@ -29,276 +29,276 @@
using namespace Swift;
class BOSHConnectionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BOSHConnectionTest);
- CPPUNIT_TEST(testHeader);
- CPPUNIT_TEST(testReadiness_ok);
- CPPUNIT_TEST(testReadiness_pending);
- CPPUNIT_TEST(testReadiness_disconnect);
- CPPUNIT_TEST(testReadiness_noSID);
- CPPUNIT_TEST(testWrite_Receive);
- CPPUNIT_TEST(testWrite_ReceiveTwice);
- CPPUNIT_TEST(testRead_Fragment);
- CPPUNIT_TEST(testHTTPRequest);
- CPPUNIT_TEST(testHTTPRequest_Empty);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop = new DummyEventLoop();
- connectionFactory = new MockConnectionFactory(eventLoop);
- resolver = new StaticDomainNameResolver(eventLoop);
- timerFactory = new DummyTimerFactory();
- tlsContextFactory = NULL;
- connectFinished = false;
- disconnected = false;
- disconnectedError = false;
- dataRead.clear();
- }
-
- void tearDown() {
- eventLoop->processEvents();
- delete connectionFactory;
- delete resolver;
- delete timerFactory;
- delete eventLoop;
- }
-
- void testHeader() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->startStream("wonderland.lit", 1);
- std::string initial("<body wait='60' "
- "inactivity='30' "
- "polling='5' "
- "requests='2' "
- "hold='1' "
- "maxpause='120' "
- "sid='MyShinySID' "
- "ver='1.6' "
- "from='wonderland.lit' "
- "xmlns='http://jabber.org/protocol/httpbind'/>");
- readResponse(initial, connectionFactory->connections[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("MyShinySID"), sid);
- CPPUNIT_ASSERT(testling->isReadyToSend());
- }
-
- void testReadiness_ok() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->setSID("blahhhhh");
- CPPUNIT_ASSERT(testling->isReadyToSend());
- }
-
- void testReadiness_pending() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->setSID("mySID");
- CPPUNIT_ASSERT(testling->isReadyToSend());
- testling->write(createSafeByteArray("<mypayload/>"));
- CPPUNIT_ASSERT(!testling->isReadyToSend());
- readResponse("<body><blah/></body>", connectionFactory->connections[0]);
- CPPUNIT_ASSERT(testling->isReadyToSend());
- }
-
- void testReadiness_disconnect() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->setSID("mySID");
- CPPUNIT_ASSERT(testling->isReadyToSend());
- connectionFactory->connections[0]->onDisconnected(boost::optional<Connection::Error>());
- CPPUNIT_ASSERT(!testling->isReadyToSend());
- }
-
-
- void testReadiness_noSID() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- CPPUNIT_ASSERT(!testling->isReadyToSend());
- }
-
- void testWrite_Receive() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->setSID("mySID");
- testling->write(createSafeByteArray("<mypayload/>"));
- readResponse("<body><blah/></body>", connectionFactory->connections[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
-
- }
-
- void testWrite_ReceiveTwice() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- testling->setSID("mySID");
- testling->write(createSafeByteArray("<mypayload/>"));
- readResponse("<body><blah/></body>", connectionFactory->connections[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
- dataRead.clear();
- testling->write(createSafeByteArray("<mypayload2/>"));
- readResponse("<body><bleh/></body>", connectionFactory->connections[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("<bleh/>"), byteArrayToString(dataRead));
- }
-
- void testRead_Fragment() {
- BOSHConnection::ref testling = createTestling();
- testling->connect();
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), connectionFactory->connections.size());
- boost::shared_ptr<MockConnection> connection = connectionFactory->connections[0];
- boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: text/xml; charset=utf-8\r\n"
- "Access-Control-Allow-Origin: *\r\n"
- "Access-Control-Allow-Headers: Content-Type\r\n"
- "Content-Length: 64\r\n"));
- boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(
- "\r\n<body xmlns='http://jabber.org/protocol/httpbind'>"
- "<bl"));
- boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray(
- "ah/>"
- "</body>"));
- connection->onDataRead(data1);
- connection->onDataRead(data2);
- CPPUNIT_ASSERT(dataRead.empty());
- connection->onDataRead(data3);
- CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
- }
-
- void testHTTPRequest() {
- std::string data = "<blah/>";
- std::string sid = "wigglebloom";
- std::string fullBody = "<body xmlns='http://jabber.org/protocol/httpbind' sid='" + sid + "' rid='20'>" + data + "</body>";
- std::pair<SafeByteArray, size_t> http = BOSHConnection::createHTTPRequest(createSafeByteArray(data), false, false, 20, sid, URL());
- CPPUNIT_ASSERT_EQUAL(fullBody.size(), http.second);
- }
-
- void testHTTPRequest_Empty() {
- std::string data = "";
- std::string sid = "wigglebloomsickle";
- std::string fullBody = "<body rid='42' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'>" + data + "</body>";
- std::pair<SafeByteArray, size_t> http = BOSHConnection::createHTTPRequest(createSafeByteArray(data), false, false, 42, sid, URL());
- CPPUNIT_ASSERT_EQUAL(fullBody.size(), http.second);
- std::string response = safeByteArrayToString(http.first);
- size_t bodyPosition = response.find("\r\n\r\n");
- CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4));
- }
-
- private:
-
- BOSHConnection::ref createTestling() {
- resolver->addAddress("wonderland.lit", HostAddress("127.0.0.1"));
- Connector::ref connector = Connector::create("wonderland.lit", 5280, boost::optional<std::string>(), resolver, connectionFactory, timerFactory);
- BOSHConnection::ref c = BOSHConnection::create(URL("http", "wonderland.lit", 5280, "/http-bind"), connector, &parserFactory, tlsContextFactory, TLSOptions());
- c->onConnectFinished.connect(boost::bind(&BOSHConnectionTest::handleConnectFinished, this, _1));
- c->onDisconnected.connect(boost::bind(&BOSHConnectionTest::handleDisconnected, this, _1));
- c->onXMPPDataRead.connect(boost::bind(&BOSHConnectionTest::handleDataRead, this, _1));
- c->onSessionStarted.connect(boost::bind(&BOSHConnectionTest::handleSID, this, _1));
- c->setRID(42);
- return c;
- }
-
- void handleConnectFinished(bool error) {
- connectFinished = true;
- connectFinishedWithError = error;
- }
-
- void handleDisconnected(bool e) {
- disconnected = true;
- disconnectedError = e;
- }
-
- void handleDataRead(const SafeByteArray& d) {
- append(dataRead, d);
- }
-
- void handleSID(const std::string& s) {
- sid = s;
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false) {
- }
-
- void listen() { assert(false); }
-
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-
- void disconnect() {
- disconnected = true;
- onDisconnected(boost::optional<Connection::Error>());
- }
-
- void write(const SafeByteArray& d) {
- append(dataWritten, d);
- }
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- ByteArray dataWritten;
- bool disconnected;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop);
- connections.push_back(connection);
- return connection;
- }
-
- EventLoop* eventLoop;
- std::vector< boost::shared_ptr<MockConnection> > connections;
- std::vector<HostAddressPort> failingPorts;
- };
-
- void readResponse(const std::string& response, boost::shared_ptr<MockConnection> connection) {
- boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: text/xml; charset=utf-8\r\n"
- "Access-Control-Allow-Origin: *\r\n"
- "Access-Control-Allow-Headers: Content-Type\r\n"
- "Content-Length: "));
- connection->onDataRead(data1);
- boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
- connection->onDataRead(data2);
- boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
- connection->onDataRead(data3);
- boost::shared_ptr<SafeByteArray> data4 = boost::make_shared<SafeByteArray>(createSafeByteArray(response));
- connection->onDataRead(data4);
- }
-
-
- private:
- DummyEventLoop* eventLoop;
- MockConnectionFactory* connectionFactory;
- bool connectFinished;
- bool connectFinishedWithError;
- bool disconnected;
- bool disconnectedError;
- ByteArray dataRead;
- PlatformXMLParserFactory parserFactory;
- StaticDomainNameResolver* resolver;
- TimerFactory* timerFactory;
- TLSContextFactory* tlsContextFactory;
- std::string sid;
+ CPPUNIT_TEST_SUITE(BOSHConnectionTest);
+ CPPUNIT_TEST(testHeader);
+ CPPUNIT_TEST(testReadiness_ok);
+ CPPUNIT_TEST(testReadiness_pending);
+ CPPUNIT_TEST(testReadiness_disconnect);
+ CPPUNIT_TEST(testReadiness_noSID);
+ CPPUNIT_TEST(testWrite_Receive);
+ CPPUNIT_TEST(testWrite_ReceiveTwice);
+ CPPUNIT_TEST(testRead_Fragment);
+ CPPUNIT_TEST(testHTTPRequest);
+ CPPUNIT_TEST(testHTTPRequest_Empty);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ connectionFactory = new MockConnectionFactory(eventLoop);
+ resolver = new StaticDomainNameResolver(eventLoop);
+ timerFactory = new DummyTimerFactory();
+ tlsContextFactory = NULL;
+ connectFinished = false;
+ disconnected = false;
+ disconnectedError = false;
+ dataRead.clear();
+ }
+
+ void tearDown() {
+ eventLoop->processEvents();
+ delete connectionFactory;
+ delete resolver;
+ delete timerFactory;
+ delete eventLoop;
+ }
+
+ void testHeader() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->startStream("wonderland.lit", 1);
+ std::string initial("<body wait='60' "
+ "inactivity='30' "
+ "polling='5' "
+ "requests='2' "
+ "hold='1' "
+ "maxpause='120' "
+ "sid='MyShinySID' "
+ "ver='1.6' "
+ "from='wonderland.lit' "
+ "xmlns='http://jabber.org/protocol/httpbind'/>");
+ readResponse(initial, connectionFactory->connections[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("MyShinySID"), sid);
+ CPPUNIT_ASSERT(testling->isReadyToSend());
+ }
+
+ void testReadiness_ok() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->setSID("blahhhhh");
+ CPPUNIT_ASSERT(testling->isReadyToSend());
+ }
+
+ void testReadiness_pending() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->setSID("mySID");
+ CPPUNIT_ASSERT(testling->isReadyToSend());
+ testling->write(createSafeByteArray("<mypayload/>"));
+ CPPUNIT_ASSERT(!testling->isReadyToSend());
+ readResponse("<body><blah/></body>", connectionFactory->connections[0]);
+ CPPUNIT_ASSERT(testling->isReadyToSend());
+ }
+
+ void testReadiness_disconnect() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->setSID("mySID");
+ CPPUNIT_ASSERT(testling->isReadyToSend());
+ connectionFactory->connections[0]->onDisconnected(boost::optional<Connection::Error>());
+ CPPUNIT_ASSERT(!testling->isReadyToSend());
+ }
+
+
+ void testReadiness_noSID() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(!testling->isReadyToSend());
+ }
+
+ void testWrite_Receive() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->setSID("mySID");
+ testling->write(createSafeByteArray("<mypayload/>"));
+ readResponse("<body><blah/></body>", connectionFactory->connections[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
+
+ }
+
+ void testWrite_ReceiveTwice() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ testling->setSID("mySID");
+ testling->write(createSafeByteArray("<mypayload/>"));
+ readResponse("<body><blah/></body>", connectionFactory->connections[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
+ dataRead.clear();
+ testling->write(createSafeByteArray("<mypayload2/>"));
+ readResponse("<body><bleh/></body>", connectionFactory->connections[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("<bleh/>"), byteArrayToString(dataRead));
+ }
+
+ void testRead_Fragment() {
+ BOSHConnection::ref testling = createTestling();
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), connectionFactory->connections.size());
+ boost::shared_ptr<MockConnection> connection = connectionFactory->connections[0];
+ boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/xml; charset=utf-8\r\n"
+ "Access-Control-Allow-Origin: *\r\n"
+ "Access-Control-Allow-Headers: Content-Type\r\n"
+ "Content-Length: 64\r\n"));
+ boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(
+ "\r\n<body xmlns='http://jabber.org/protocol/httpbind'>"
+ "<bl"));
+ boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray(
+ "ah/>"
+ "</body>"));
+ connection->onDataRead(data1);
+ connection->onDataRead(data2);
+ CPPUNIT_ASSERT(dataRead.empty());
+ connection->onDataRead(data3);
+ CPPUNIT_ASSERT_EQUAL(std::string("<blah/>"), byteArrayToString(dataRead));
+ }
+
+ void testHTTPRequest() {
+ std::string data = "<blah/>";
+ std::string sid = "wigglebloom";
+ std::string fullBody = "<body xmlns='http://jabber.org/protocol/httpbind' sid='" + sid + "' rid='20'>" + data + "</body>";
+ std::pair<SafeByteArray, size_t> http = BOSHConnection::createHTTPRequest(createSafeByteArray(data), false, false, 20, sid, URL());
+ CPPUNIT_ASSERT_EQUAL(fullBody.size(), http.second);
+ }
+
+ void testHTTPRequest_Empty() {
+ std::string data = "";
+ std::string sid = "wigglebloomsickle";
+ std::string fullBody = "<body rid='42' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'>" + data + "</body>";
+ std::pair<SafeByteArray, size_t> http = BOSHConnection::createHTTPRequest(createSafeByteArray(data), false, false, 42, sid, URL());
+ CPPUNIT_ASSERT_EQUAL(fullBody.size(), http.second);
+ std::string response = safeByteArrayToString(http.first);
+ size_t bodyPosition = response.find("\r\n\r\n");
+ CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4));
+ }
+
+ private:
+
+ BOSHConnection::ref createTestling() {
+ resolver->addAddress("wonderland.lit", HostAddress("127.0.0.1"));
+ Connector::ref connector = Connector::create("wonderland.lit", 5280, boost::optional<std::string>(), resolver, connectionFactory, timerFactory);
+ BOSHConnection::ref c = BOSHConnection::create(URL("http", "wonderland.lit", 5280, "/http-bind"), connector, &parserFactory, tlsContextFactory, TLSOptions());
+ c->onConnectFinished.connect(boost::bind(&BOSHConnectionTest::handleConnectFinished, this, _1));
+ c->onDisconnected.connect(boost::bind(&BOSHConnectionTest::handleDisconnected, this, _1));
+ c->onXMPPDataRead.connect(boost::bind(&BOSHConnectionTest::handleDataRead, this, _1));
+ c->onSessionStarted.connect(boost::bind(&BOSHConnectionTest::handleSID, this, _1));
+ c->setRID(42);
+ return c;
+ }
+
+ void handleConnectFinished(bool error) {
+ connectFinished = true;
+ connectFinishedWithError = error;
+ }
+
+ void handleDisconnected(bool e) {
+ disconnected = true;
+ disconnectedError = e;
+ }
+
+ void handleDataRead(const SafeByteArray& d) {
+ append(dataRead, d);
+ }
+
+ void handleSID(const std::string& s) {
+ sid = s;
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false) {
+ }
+
+ void listen() { assert(false); }
+
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+
+ void disconnect() {
+ disconnected = true;
+ onDisconnected(boost::optional<Connection::Error>());
+ }
+
+ void write(const SafeByteArray& d) {
+ append(dataWritten, d);
+ }
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ ByteArray dataWritten;
+ bool disconnected;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop);
+ connections.push_back(connection);
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
+ std::vector<HostAddressPort> failingPorts;
+ };
+
+ void readResponse(const std::string& response, boost::shared_ptr<MockConnection> connection) {
+ boost::shared_ptr<SafeByteArray> data1 = boost::make_shared<SafeByteArray>(createSafeByteArray(
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/xml; charset=utf-8\r\n"
+ "Access-Control-Allow-Origin: *\r\n"
+ "Access-Control-Allow-Headers: Content-Type\r\n"
+ "Content-Length: "));
+ connection->onDataRead(data1);
+ boost::shared_ptr<SafeByteArray> data2 = boost::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
+ connection->onDataRead(data2);
+ boost::shared_ptr<SafeByteArray> data3 = boost::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
+ connection->onDataRead(data3);
+ boost::shared_ptr<SafeByteArray> data4 = boost::make_shared<SafeByteArray>(createSafeByteArray(response));
+ connection->onDataRead(data4);
+ }
+
+
+ private:
+ DummyEventLoop* eventLoop;
+ MockConnectionFactory* connectionFactory;
+ bool connectFinished;
+ bool connectFinishedWithError;
+ bool disconnected;
+ bool disconnectedError;
+ ByteArray dataRead;
+ PlatformXMLParserFactory parserFactory;
+ StaticDomainNameResolver* resolver;
+ TimerFactory* timerFactory;
+ TLSContextFactory* tlsContextFactory;
+ std::string sid;
};
diff --git a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
index 3bafbf1..9496e13 100644
--- a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
@@ -22,166 +22,166 @@
using namespace Swift;
class ChainedConnectorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ChainedConnectorTest);
- CPPUNIT_TEST(testConnect_FirstConnectorSucceeds);
- CPPUNIT_TEST(testConnect_SecondConnectorSucceeds);
- CPPUNIT_TEST(testConnect_NoConnectorSucceeds);
- CPPUNIT_TEST(testConnect_NoDNS);
- CPPUNIT_TEST(testStop);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- error.reset();
- host = HostAddressPort(HostAddress("1.1.1.1"), 1234);
- eventLoop = new DummyEventLoop();
- resolver = new StaticDomainNameResolver(eventLoop);
- resolver->addXMPPClientService("foo.com", host);
- connectionFactory1 = new MockConnectionFactory(eventLoop, 1);
- connectionFactory2 = new MockConnectionFactory(eventLoop, 2);
- timerFactory = new DummyTimerFactory();
- }
-
- void tearDown() {
- delete timerFactory;
- delete connectionFactory2;
- delete connectionFactory1;
- delete resolver;
- delete eventLoop;
- }
-
- void testConnect_FirstConnectorSucceeds() {
- boost::shared_ptr<ChainedConnector> testling(createConnector());
- connectionFactory1->connects = true;
- connectionFactory2->connects = false;
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT_EQUAL(1, boost::dynamic_pointer_cast<MockConnection>(connections[0])->id);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_SecondConnectorSucceeds() {
- boost::shared_ptr<ChainedConnector> testling(createConnector());
- connectionFactory1->connects = false;
- connectionFactory2->connects = true;
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT_EQUAL(2, boost::dynamic_pointer_cast<MockConnection>(connections[0])->id);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoConnectorSucceeds() {
- boost::shared_ptr<ChainedConnector> testling(createConnector());
- connectionFactory1->connects = false;
- connectionFactory2->connects = false;
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoDNS() {
- /* Reset resolver so there's no record */
- delete resolver;
- resolver = new StaticDomainNameResolver(eventLoop);
- boost::shared_ptr<ChainedConnector> testling(createConnector());
- connectionFactory1->connects = false;
- connectionFactory2->connects = false;
-
- testling->start();
- //testling->stop();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testStop() {
- boost::shared_ptr<ChainedConnector> testling(createConnector());
- connectionFactory1->connects = true;
- connectionFactory2->connects = false;
-
- testling->start();
- testling->stop();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
- private:
- boost::shared_ptr<ChainedConnector> createConnector() {
- std::vector<ConnectionFactory*> factories;
- factories.push_back(connectionFactory1);
- factories.push_back(connectionFactory2);
- boost::shared_ptr<ChainedConnector> connector = boost::make_shared<ChainedConnector>("foo.com", -1, boost::optional<std::string>("_xmpp-client._tcp."), resolver, factories, timerFactory);
- connector->onConnectFinished.connect(boost::bind(&ChainedConnectorTest::handleConnectorFinished, this, _1, _2));
- return connector;
- }
-
- void handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> resultError) {
- error = resultError;
- boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
- if (connection) {
- assert(c);
- }
- connections.push_back(c);
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(bool connects, int id, EventLoop* eventLoop) : connects(connects), id(id), eventLoop(eventLoop) {
- }
-
- void listen() { assert(false); }
- void connect(const HostAddressPort&) {
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), !connects));
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
- void disconnect() { assert(false); }
- void write(const SafeByteArray&) { assert(false); }
-
- bool connects;
- int id;
- EventLoop* eventLoop;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop, int id) : eventLoop(eventLoop), connects(true), id(id) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- return boost::make_shared<MockConnection>(connects, id, eventLoop);
- }
-
- EventLoop* eventLoop;
- bool connects;
- int id;
- };
-
- private:
- HostAddressPort host;
- DummyEventLoop* eventLoop;
- StaticDomainNameResolver* resolver;
- MockConnectionFactory* connectionFactory1;
- MockConnectionFactory* connectionFactory2;
- DummyTimerFactory* timerFactory;
- std::vector< boost::shared_ptr<MockConnection> > connections;
- boost::shared_ptr<Error> error;
+ CPPUNIT_TEST_SUITE(ChainedConnectorTest);
+ CPPUNIT_TEST(testConnect_FirstConnectorSucceeds);
+ CPPUNIT_TEST(testConnect_SecondConnectorSucceeds);
+ CPPUNIT_TEST(testConnect_NoConnectorSucceeds);
+ CPPUNIT_TEST(testConnect_NoDNS);
+ CPPUNIT_TEST(testStop);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ error.reset();
+ host = HostAddressPort(HostAddress("1.1.1.1"), 1234);
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ resolver->addXMPPClientService("foo.com", host);
+ connectionFactory1 = new MockConnectionFactory(eventLoop, 1);
+ connectionFactory2 = new MockConnectionFactory(eventLoop, 2);
+ timerFactory = new DummyTimerFactory();
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete connectionFactory2;
+ delete connectionFactory1;
+ delete resolver;
+ delete eventLoop;
+ }
+
+ void testConnect_FirstConnectorSucceeds() {
+ boost::shared_ptr<ChainedConnector> testling(createConnector());
+ connectionFactory1->connects = true;
+ connectionFactory2->connects = false;
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT_EQUAL(1, boost::dynamic_pointer_cast<MockConnection>(connections[0])->id);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_SecondConnectorSucceeds() {
+ boost::shared_ptr<ChainedConnector> testling(createConnector());
+ connectionFactory1->connects = false;
+ connectionFactory2->connects = true;
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT_EQUAL(2, boost::dynamic_pointer_cast<MockConnection>(connections[0])->id);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoConnectorSucceeds() {
+ boost::shared_ptr<ChainedConnector> testling(createConnector());
+ connectionFactory1->connects = false;
+ connectionFactory2->connects = false;
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoDNS() {
+ /* Reset resolver so there's no record */
+ delete resolver;
+ resolver = new StaticDomainNameResolver(eventLoop);
+ boost::shared_ptr<ChainedConnector> testling(createConnector());
+ connectionFactory1->connects = false;
+ connectionFactory2->connects = false;
+
+ testling->start();
+ //testling->stop();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testStop() {
+ boost::shared_ptr<ChainedConnector> testling(createConnector());
+ connectionFactory1->connects = true;
+ connectionFactory2->connects = false;
+
+ testling->start();
+ testling->stop();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+ private:
+ boost::shared_ptr<ChainedConnector> createConnector() {
+ std::vector<ConnectionFactory*> factories;
+ factories.push_back(connectionFactory1);
+ factories.push_back(connectionFactory2);
+ boost::shared_ptr<ChainedConnector> connector = boost::make_shared<ChainedConnector>("foo.com", -1, boost::optional<std::string>("_xmpp-client._tcp."), resolver, factories, timerFactory);
+ connector->onConnectFinished.connect(boost::bind(&ChainedConnectorTest::handleConnectorFinished, this, _1, _2));
+ return connector;
+ }
+
+ void handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> resultError) {
+ error = resultError;
+ boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
+ if (connection) {
+ assert(c);
+ }
+ connections.push_back(c);
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(bool connects, int id, EventLoop* eventLoop) : connects(connects), id(id), eventLoop(eventLoop) {
+ }
+
+ void listen() { assert(false); }
+ void connect(const HostAddressPort&) {
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), !connects));
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+ void disconnect() { assert(false); }
+ void write(const SafeByteArray&) { assert(false); }
+
+ bool connects;
+ int id;
+ EventLoop* eventLoop;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop, int id) : eventLoop(eventLoop), connects(true), id(id) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ return boost::make_shared<MockConnection>(connects, id, eventLoop);
+ }
+
+ EventLoop* eventLoop;
+ bool connects;
+ int id;
+ };
+
+ private:
+ HostAddressPort host;
+ DummyEventLoop* eventLoop;
+ StaticDomainNameResolver* resolver;
+ MockConnectionFactory* connectionFactory1;
+ MockConnectionFactory* connectionFactory2;
+ DummyTimerFactory* timerFactory;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
+ boost::shared_ptr<Error> error;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChainedConnectorTest);
diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp
index a091074..ac2bc83 100644
--- a/Swiften/Network/UnitTest/ConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ConnectorTest.cpp
@@ -22,358 +22,358 @@
using namespace Swift;
class ConnectorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ConnectorTest);
- CPPUNIT_TEST(testConnect);
- CPPUNIT_TEST(testConnect_NoServiceLookups);
- CPPUNIT_TEST(testConnect_NoServiceLookups_DefaultPort);
- CPPUNIT_TEST(testConnect_FirstAddressHostFails);
- CPPUNIT_TEST(testConnect_NoSRVHost);
- CPPUNIT_TEST(testConnect_NoHosts);
- CPPUNIT_TEST(testConnect_FirstSRVHostFails);
- CPPUNIT_TEST(testConnect_AllSRVHostsFailWithoutFallbackHost);
- CPPUNIT_TEST(testConnect_AllSRVHostsFailWithFallbackHost);
- CPPUNIT_TEST(testConnect_SRVAndFallbackHostsFail);
- //CPPUNIT_TEST(testConnect_TimeoutDuringResolve);
- CPPUNIT_TEST(testConnect_TimeoutDuringConnectToOnlyCandidate);
- CPPUNIT_TEST(testConnect_TimeoutDuringConnectToCandidateFallsBack);
- CPPUNIT_TEST(testConnect_NoTimeout);
- CPPUNIT_TEST(testStop_DuringSRVQuery);
- CPPUNIT_TEST(testStop_Timeout);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- host1 = HostAddressPort(HostAddress("1.1.1.1"), 1234);
- host2 = HostAddressPort(HostAddress("2.2.2.2"), 2345);
- host3 = HostAddressPort(HostAddress("3.3.3.3"), 5222);
- eventLoop = new DummyEventLoop();
- resolver = new StaticDomainNameResolver(eventLoop);
- connectionFactory = new MockConnectionFactory(eventLoop);
- timerFactory = new DummyTimerFactory();
- }
-
- void tearDown() {
- delete timerFactory;
- delete connectionFactory;
- delete resolver;
- delete eventLoop;
- }
-
- void testConnect() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- resolver->addAddress("foo.com", host3.getAddress());
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(host1 == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoServiceLookups() {
- Connector::ref testling(createConnector(4321, boost::optional<std::string>()));
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- resolver->addAddress("foo.com", host3.getAddress());
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress());
- CPPUNIT_ASSERT(4321 == (*(connections[0]->hostAddressPort)).getPort());
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoServiceLookups_DefaultPort() {
- Connector::ref testling(createConnector(-1, boost::optional<std::string>()));
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- resolver->addAddress("foo.com", host3.getAddress());
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress());
- CPPUNIT_ASSERT_EQUAL(5222, (*(connections[0]->hostAddressPort)).getPort());
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoSRVHost() {
- Connector::ref testling(createConnector());
- resolver->addAddress("foo.com", host3.getAddress());
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(host3 == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_FirstAddressHostFails() {
- Connector::ref testling(createConnector());
-
- HostAddress address1("1.1.1.1");
- HostAddress address2("2.2.2.2");
- resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
- resolver->addAddress("host-foo.com", address1);
- resolver->addAddress("host-foo.com", address2);
- connectionFactory->failingPorts.push_back(HostAddressPort(address1, 1234));
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(HostAddressPort(address2, 1234) == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_NoHosts() {
- Connector::ref testling(createConnector());
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_FirstSRVHostFails() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- connectionFactory->failingPorts.push_back(host1);
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(host2 == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_AllSRVHostsFailWithoutFallbackHost() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- connectionFactory->failingPorts.push_back(host1);
- connectionFactory->failingPorts.push_back(host2);
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_AllSRVHostsFailWithFallbackHost() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addXMPPClientService("foo.com", host2);
- resolver->addAddress("foo.com", host3.getAddress());
- connectionFactory->failingPorts.push_back(host1);
- connectionFactory->failingPorts.push_back(host2);
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(host3 == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_SRVAndFallbackHostsFail() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
- resolver->addAddress("foo.com", host3.getAddress());
- connectionFactory->failingPorts.push_back(host1);
- connectionFactory->failingPorts.push_back(host3);
-
- testling->start();
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- /*void testConnect_TimeoutDuringResolve() {
- Connector::ref testling(createConnector());
- testling->setTimeoutMilliseconds(10);
- resolver->setIsResponsive(false);
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- CPPUNIT_ASSERT(!connections[0]);
- }*/
-
- void testConnect_TimeoutDuringConnectToOnlyCandidate() {
- Connector::ref testling(createConnector());
- testling->setTimeoutMilliseconds(10);
- resolver->addXMPPClientService("foo.com", host1);
- connectionFactory->isResponsive = false;
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testConnect_TimeoutDuringConnectToCandidateFallsBack() {
- Connector::ref testling(createConnector());
- testling->setTimeoutMilliseconds(10);
-
- resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
- HostAddress address1("1.1.1.1");
- resolver->addAddress("host-foo.com", address1);
- HostAddress address2("2.2.2.2");
- resolver->addAddress("host-foo.com", address2);
-
- connectionFactory->isResponsive = false;
- testling->start();
- eventLoop->processEvents();
- connectionFactory->isResponsive = true;
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(HostAddressPort(address2, 1234) == *(connections[0]->hostAddressPort));
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
-
- void testConnect_NoTimeout() {
- Connector::ref testling(createConnector());
- testling->setTimeoutMilliseconds(10);
- resolver->addXMPPClientService("foo.com", host1);
-
- testling->start();
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(connections[0]);
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testStop_DuringSRVQuery() {
- Connector::ref testling(createConnector());
- resolver->addXMPPClientService("foo.com", host1);
-
- testling->start();
- testling->stop();
-
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
- }
-
- void testStop_Timeout() {
- Connector::ref testling(createConnector());
- testling->setTimeoutMilliseconds(10);
- resolver->addXMPPClientService("foo.com", host1);
-
- testling->start();
- testling->stop();
-
- eventLoop->processEvents();
- timerFactory->setTime(10);
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
- CPPUNIT_ASSERT(!connections[0]);
- }
-
-
- private:
- Connector::ref createConnector(int port = -1, boost::optional<std::string> serviceLookupPrefix = boost::optional<std::string>("_xmpp-client._tcp.")) {
- Connector::ref connector = Connector::create("foo.com", port, serviceLookupPrefix, resolver, connectionFactory, timerFactory);
- connector->onConnectFinished.connect(boost::bind(&ConnectorTest::handleConnectorFinished, this, _1, _2));
- return connector;
- }
-
- void handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> resultError) {
- boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
- if (connection) {
- assert(c);
- }
- connections.push_back(c);
- error = resultError;
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {}
-
- void listen() { assert(false); }
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- if (isResponsive) {
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
- void disconnect() { assert(false); }
- void write(const SafeByteArray&) { assert(false); }
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- bool isResponsive;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop));
- }
-
- EventLoop* eventLoop;
- bool isResponsive;
- std::vector<HostAddressPort> failingPorts;
- };
-
- private:
- HostAddressPort host1;
- HostAddressPort host2;
- HostAddressPort host3;
- DummyEventLoop* eventLoop;
- StaticDomainNameResolver* resolver;
- MockConnectionFactory* connectionFactory;
- DummyTimerFactory* timerFactory;
- std::vector< boost::shared_ptr<MockConnection> > connections;
- boost::shared_ptr<Error> error;
+ CPPUNIT_TEST_SUITE(ConnectorTest);
+ CPPUNIT_TEST(testConnect);
+ CPPUNIT_TEST(testConnect_NoServiceLookups);
+ CPPUNIT_TEST(testConnect_NoServiceLookups_DefaultPort);
+ CPPUNIT_TEST(testConnect_FirstAddressHostFails);
+ CPPUNIT_TEST(testConnect_NoSRVHost);
+ CPPUNIT_TEST(testConnect_NoHosts);
+ CPPUNIT_TEST(testConnect_FirstSRVHostFails);
+ CPPUNIT_TEST(testConnect_AllSRVHostsFailWithoutFallbackHost);
+ CPPUNIT_TEST(testConnect_AllSRVHostsFailWithFallbackHost);
+ CPPUNIT_TEST(testConnect_SRVAndFallbackHostsFail);
+ //CPPUNIT_TEST(testConnect_TimeoutDuringResolve);
+ CPPUNIT_TEST(testConnect_TimeoutDuringConnectToOnlyCandidate);
+ CPPUNIT_TEST(testConnect_TimeoutDuringConnectToCandidateFallsBack);
+ CPPUNIT_TEST(testConnect_NoTimeout);
+ CPPUNIT_TEST(testStop_DuringSRVQuery);
+ CPPUNIT_TEST(testStop_Timeout);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ host1 = HostAddressPort(HostAddress("1.1.1.1"), 1234);
+ host2 = HostAddressPort(HostAddress("2.2.2.2"), 2345);
+ host3 = HostAddressPort(HostAddress("3.3.3.3"), 5222);
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ connectionFactory = new MockConnectionFactory(eventLoop);
+ timerFactory = new DummyTimerFactory();
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete connectionFactory;
+ delete resolver;
+ delete eventLoop;
+ }
+
+ void testConnect() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ resolver->addAddress("foo.com", host3.getAddress());
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(host1 == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoServiceLookups() {
+ Connector::ref testling(createConnector(4321, boost::optional<std::string>()));
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ resolver->addAddress("foo.com", host3.getAddress());
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress());
+ CPPUNIT_ASSERT(4321 == (*(connections[0]->hostAddressPort)).getPort());
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoServiceLookups_DefaultPort() {
+ Connector::ref testling(createConnector(-1, boost::optional<std::string>()));
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ resolver->addAddress("foo.com", host3.getAddress());
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress());
+ CPPUNIT_ASSERT_EQUAL(5222, (*(connections[0]->hostAddressPort)).getPort());
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoSRVHost() {
+ Connector::ref testling(createConnector());
+ resolver->addAddress("foo.com", host3.getAddress());
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(host3 == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_FirstAddressHostFails() {
+ Connector::ref testling(createConnector());
+
+ HostAddress address1("1.1.1.1");
+ HostAddress address2("2.2.2.2");
+ resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
+ resolver->addAddress("host-foo.com", address1);
+ resolver->addAddress("host-foo.com", address2);
+ connectionFactory->failingPorts.push_back(HostAddressPort(address1, 1234));
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(HostAddressPort(address2, 1234) == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoHosts() {
+ Connector::ref testling(createConnector());
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_FirstSRVHostFails() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ connectionFactory->failingPorts.push_back(host1);
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(host2 == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_AllSRVHostsFailWithoutFallbackHost() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ connectionFactory->failingPorts.push_back(host1);
+ connectionFactory->failingPorts.push_back(host2);
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_AllSRVHostsFailWithFallbackHost() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addXMPPClientService("foo.com", host2);
+ resolver->addAddress("foo.com", host3.getAddress());
+ connectionFactory->failingPorts.push_back(host1);
+ connectionFactory->failingPorts.push_back(host2);
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(host3 == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_SRVAndFallbackHostsFail() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+ resolver->addAddress("foo.com", host3.getAddress());
+ connectionFactory->failingPorts.push_back(host1);
+ connectionFactory->failingPorts.push_back(host3);
+
+ testling->start();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ /*void testConnect_TimeoutDuringResolve() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+ resolver->setIsResponsive(false);
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ CPPUNIT_ASSERT(!connections[0]);
+ }*/
+
+ void testConnect_TimeoutDuringConnectToOnlyCandidate() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+ resolver->addXMPPClientService("foo.com", host1);
+ connectionFactory->isResponsive = false;
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_TimeoutDuringConnectToCandidateFallsBack() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+
+ resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
+ HostAddress address1("1.1.1.1");
+ resolver->addAddress("host-foo.com", address1);
+ HostAddress address2("2.2.2.2");
+ resolver->addAddress("host-foo.com", address2);
+
+ connectionFactory->isResponsive = false;
+ testling->start();
+ eventLoop->processEvents();
+ connectionFactory->isResponsive = true;
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(HostAddressPort(address2, 1234) == *(connections[0]->hostAddressPort));
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+
+ void testConnect_NoTimeout() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+ resolver->addXMPPClientService("foo.com", host1);
+
+ testling->start();
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(connections[0]);
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testStop_DuringSRVQuery() {
+ Connector::ref testling(createConnector());
+ resolver->addXMPPClientService("foo.com", host1);
+
+ testling->start();
+ testling->stop();
+
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testStop_Timeout() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+ resolver->addXMPPClientService("foo.com", host1);
+
+ testling->start();
+ testling->stop();
+
+ eventLoop->processEvents();
+ timerFactory->setTime(10);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size()));
+ CPPUNIT_ASSERT(!connections[0]);
+ }
+
+
+ private:
+ Connector::ref createConnector(int port = -1, boost::optional<std::string> serviceLookupPrefix = boost::optional<std::string>("_xmpp-client._tcp.")) {
+ Connector::ref connector = Connector::create("foo.com", port, serviceLookupPrefix, resolver, connectionFactory, timerFactory);
+ connector->onConnectFinished.connect(boost::bind(&ConnectorTest::handleConnectorFinished, this, _1, _2));
+ return connector;
+ }
+
+ void handleConnectorFinished(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> resultError) {
+ boost::shared_ptr<MockConnection> c(boost::dynamic_pointer_cast<MockConnection>(connection));
+ if (connection) {
+ assert(c);
+ }
+ connections.push_back(c);
+ error = resultError;
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive) {}
+
+ void listen() { assert(false); }
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ if (isResponsive) {
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+ void disconnect() { assert(false); }
+ void write(const SafeByteArray&) { assert(false); }
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ bool isResponsive;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ return boost::shared_ptr<Connection>(new MockConnection(failingPorts, isResponsive, eventLoop));
+ }
+
+ EventLoop* eventLoop;
+ bool isResponsive;
+ std::vector<HostAddressPort> failingPorts;
+ };
+
+ private:
+ HostAddressPort host1;
+ HostAddressPort host2;
+ HostAddressPort host3;
+ DummyEventLoop* eventLoop;
+ StaticDomainNameResolver* resolver;
+ MockConnectionFactory* connectionFactory;
+ DummyTimerFactory* timerFactory;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
+ boost::shared_ptr<Error> error;
};
diff --git a/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp b/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
index d5cef84..7042b27 100644
--- a/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
+++ b/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
@@ -15,67 +15,67 @@
using namespace Swift;
namespace {
- struct RandomGenerator1 : public RandomGenerator {
- virtual int generateRandomInteger(int) {
- return 0;
- }
- };
+ struct RandomGenerator1 : public RandomGenerator {
+ virtual int generateRandomInteger(int) {
+ return 0;
+ }
+ };
- struct RandomGenerator2 : public RandomGenerator {
- virtual int generateRandomInteger(int i) {
- return i;
- }
- };
+ struct RandomGenerator2 : public RandomGenerator {
+ virtual int generateRandomInteger(int i) {
+ return i;
+ }
+ };
}
class DomainNameServiceQueryTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DomainNameServiceQueryTest);
- CPPUNIT_TEST(testSortResults_Random1);
- CPPUNIT_TEST(testSortResults_Random2);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DomainNameServiceQueryTest);
+ CPPUNIT_TEST(testSortResults_Random1);
+ CPPUNIT_TEST(testSortResults_Random2);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSortResults_Random1() {
- std::vector<DomainNameServiceQuery::Result> results;
- results.push_back(DomainNameServiceQuery::Result("server1.com", 5222, 5, 1));
- results.push_back(DomainNameServiceQuery::Result("server2.com", 5222, 3, 10));
- results.push_back(DomainNameServiceQuery::Result("server3.com", 5222, 6, 1));
- results.push_back(DomainNameServiceQuery::Result("server4.com", 5222, 3, 20));
- results.push_back(DomainNameServiceQuery::Result("server5.com", 5222, 2, 1));
- results.push_back(DomainNameServiceQuery::Result("server6.com", 5222, 3, 10));
+ public:
+ void testSortResults_Random1() {
+ std::vector<DomainNameServiceQuery::Result> results;
+ results.push_back(DomainNameServiceQuery::Result("server1.com", 5222, 5, 1));
+ results.push_back(DomainNameServiceQuery::Result("server2.com", 5222, 3, 10));
+ results.push_back(DomainNameServiceQuery::Result("server3.com", 5222, 6, 1));
+ results.push_back(DomainNameServiceQuery::Result("server4.com", 5222, 3, 20));
+ results.push_back(DomainNameServiceQuery::Result("server5.com", 5222, 2, 1));
+ results.push_back(DomainNameServiceQuery::Result("server6.com", 5222, 3, 10));
- RandomGenerator1 generator;
- DomainNameServiceQuery::sortResults(results, generator);
+ RandomGenerator1 generator;
+ DomainNameServiceQuery::sortResults(results, generator);
- CPPUNIT_ASSERT_EQUAL(std::string("server5.com"), results[0].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server2.com"), results[1].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server4.com"), results[2].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server6.com"), results[3].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server1.com"), results[4].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server3.com"), results[5].hostname);
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("server5.com"), results[0].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server2.com"), results[1].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server4.com"), results[2].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server6.com"), results[3].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server1.com"), results[4].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server3.com"), results[5].hostname);
+ }
- void testSortResults_Random2() {
- std::vector<DomainNameServiceQuery::Result> results;
- results.push_back(DomainNameServiceQuery::Result("server1.com", 5222, 5, 1));
- results.push_back(DomainNameServiceQuery::Result("server2.com", 5222, 3, 10));
- results.push_back(DomainNameServiceQuery::Result("server3.com", 5222, 6, 1));
- results.push_back(DomainNameServiceQuery::Result("server4.com", 5222, 3, 20));
- results.push_back(DomainNameServiceQuery::Result("server5.com", 5222, 2, 1));
- results.push_back(DomainNameServiceQuery::Result("server6.com", 5222, 3, 10));
- results.push_back(DomainNameServiceQuery::Result("server7.com", 5222, 3, 40));
+ void testSortResults_Random2() {
+ std::vector<DomainNameServiceQuery::Result> results;
+ results.push_back(DomainNameServiceQuery::Result("server1.com", 5222, 5, 1));
+ results.push_back(DomainNameServiceQuery::Result("server2.com", 5222, 3, 10));
+ results.push_back(DomainNameServiceQuery::Result("server3.com", 5222, 6, 1));
+ results.push_back(DomainNameServiceQuery::Result("server4.com", 5222, 3, 20));
+ results.push_back(DomainNameServiceQuery::Result("server5.com", 5222, 2, 1));
+ results.push_back(DomainNameServiceQuery::Result("server6.com", 5222, 3, 10));
+ results.push_back(DomainNameServiceQuery::Result("server7.com", 5222, 3, 40));
- RandomGenerator2 generator;
- DomainNameServiceQuery::sortResults(results, generator);
+ RandomGenerator2 generator;
+ DomainNameServiceQuery::sortResults(results, generator);
- CPPUNIT_ASSERT_EQUAL(std::string("server5.com"), results[0].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server7.com"), results[1].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server2.com"), results[2].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server4.com"), results[3].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server6.com"), results[4].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server1.com"), results[5].hostname);
- CPPUNIT_ASSERT_EQUAL(std::string("server3.com"), results[6].hostname);
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("server5.com"), results[0].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server7.com"), results[1].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server2.com"), results[2].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server4.com"), results[3].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server6.com"), results[4].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server1.com"), results[5].hostname);
+ CPPUNIT_ASSERT_EQUAL(std::string("server3.com"), results[6].hostname);
+ }
};
diff --git a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
index 1d01214..aa3d578 100644
--- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
@@ -31,409 +31,409 @@
using namespace Swift;
namespace {
- class ExampleHTTPTrafficFilter : public HTTPTrafficFilter {
- public:
- ExampleHTTPTrafficFilter() {}
- virtual ~ExampleHTTPTrafficFilter() {}
-
- virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& /* statusLine */, const std::vector<std::pair<std::string, std::string> >& response) {
- filterResponses.push_back(response);
- SWIFT_LOG(debug) << std::endl;
- return filterResponseReturn;
- }
-
- std::vector<std::vector<std::pair<std::string, std::string> > > filterResponses;
-
- std::vector<std::pair<std::string, std::string> > filterResponseReturn;
- };
-
- class ProxyAuthenticationHTTPTrafficFilter : public HTTPTrafficFilter {
- static std::string to_lower(const std::string& str) {
- std::string lower = str;
- boost::algorithm::to_lower(lower);
- return lower;
- }
-
- public:
- ProxyAuthenticationHTTPTrafficFilter() {}
- virtual ~ProxyAuthenticationHTTPTrafficFilter() {}
-
- virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& response) {
- std::vector<std::pair<std::string, std::string> > filterResponseReturn;
- std::vector<std::string> statusLineFields;
- boost::split(statusLineFields, statusLine, boost::is_any_of(" "), boost::token_compress_on);
-
- int statusCode = boost::lexical_cast<int>(statusLineFields[1]);
- if (statusCode == 407) {
- typedef std::pair<std::string, std::string> StrPair;
- foreach (const StrPair& field, response) {
- if (to_lower(field.first) == to_lower("Proxy-Authenticate")) {
- if (field.second.size() >= 6 && field.second.substr(0, 6) == " NTLM ") {
- filterResponseReturn.push_back(std::pair<std::string, std::string>("Proxy-Authorization", "NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABIAEgBIAAAABgAGAFoAAAASABIVNTUAADAAYAAAABAAEACiAAAANYKI4gUBKAoAAAAPTABBAEIAUwBNAE8ASwBFADMAXwBxAGEATABBAEIAUwBNAE8ASwBFADMA0NKq8HYYhj8AAAAAAAAAAAAAAAAAAAAAOIiih3mR+AkyM4r99sy1mdFonCu2ILODro1WTTrJ4b4JcXEzUBA2Ig=="));
- return filterResponseReturn;
- }
- else if (field.second.size() >= 5 && field.second.substr(0, 5) == " NTLM") {
- filterResponseReturn.push_back(std::pair<std::string, std::string>("Proxy-Authorization", "NTLM TlRMTVNTUAABAAAAt7II4gkACQAxAAAACQAJACgAAAVNTUAADAAFASgKAAAAD0xBQlNNT0tFM1dPUktHUk9VUA=="));
- return filterResponseReturn;
- }
- }
- }
-
- return filterResponseReturn;
- }
- else {
- return std::vector<std::pair<std::string, std::string> >();
- }
- }
- };
+ class ExampleHTTPTrafficFilter : public HTTPTrafficFilter {
+ public:
+ ExampleHTTPTrafficFilter() {}
+ virtual ~ExampleHTTPTrafficFilter() {}
+
+ virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& /* statusLine */, const std::vector<std::pair<std::string, std::string> >& response) {
+ filterResponses.push_back(response);
+ SWIFT_LOG(debug) << std::endl;
+ return filterResponseReturn;
+ }
+
+ std::vector<std::vector<std::pair<std::string, std::string> > > filterResponses;
+
+ std::vector<std::pair<std::string, std::string> > filterResponseReturn;
+ };
+
+ class ProxyAuthenticationHTTPTrafficFilter : public HTTPTrafficFilter {
+ static std::string to_lower(const std::string& str) {
+ std::string lower = str;
+ boost::algorithm::to_lower(lower);
+ return lower;
+ }
+
+ public:
+ ProxyAuthenticationHTTPTrafficFilter() {}
+ virtual ~ProxyAuthenticationHTTPTrafficFilter() {}
+
+ virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& response) {
+ std::vector<std::pair<std::string, std::string> > filterResponseReturn;
+ std::vector<std::string> statusLineFields;
+ boost::split(statusLineFields, statusLine, boost::is_any_of(" "), boost::token_compress_on);
+
+ int statusCode = boost::lexical_cast<int>(statusLineFields[1]);
+ if (statusCode == 407) {
+ typedef std::pair<std::string, std::string> StrPair;
+ foreach (const StrPair& field, response) {
+ if (to_lower(field.first) == to_lower("Proxy-Authenticate")) {
+ if (field.second.size() >= 6 && field.second.substr(0, 6) == " NTLM ") {
+ filterResponseReturn.push_back(std::pair<std::string, std::string>("Proxy-Authorization", "NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABIAEgBIAAAABgAGAFoAAAASABIVNTUAADAAYAAAABAAEACiAAAANYKI4gUBKAoAAAAPTABBAEIAUwBNAE8ASwBFADMAXwBxAGEATABBAEIAUwBNAE8ASwBFADMA0NKq8HYYhj8AAAAAAAAAAAAAAAAAAAAAOIiih3mR+AkyM4r99sy1mdFonCu2ILODro1WTTrJ4b4JcXEzUBA2Ig=="));
+ return filterResponseReturn;
+ }
+ else if (field.second.size() >= 5 && field.second.substr(0, 5) == " NTLM") {
+ filterResponseReturn.push_back(std::pair<std::string, std::string>("Proxy-Authorization", "NTLM TlRMTVNTUAABAAAAt7II4gkACQAxAAAACQAJACgAAAVNTUAADAAFASgKAAAAD0xBQlNNT0tFM1dPUktHUk9VUA=="));
+ return filterResponseReturn;
+ }
+ }
+ }
+
+ return filterResponseReturn;
+ }
+ else {
+ return std::vector<std::pair<std::string, std::string> >();
+ }
+ }
+ };
}
class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(HTTPConnectProxiedConnectionTest);
- CPPUNIT_TEST(testConnect_CreatesConnectionToProxy);
- CPPUNIT_TEST(testConnect_SendsConnectRequest);
- CPPUNIT_TEST(testConnect_ReceiveConnectResponse);
- CPPUNIT_TEST(testConnect_ReceiveConnectChunkedResponse);
- CPPUNIT_TEST(testConnect_ReceiveMalformedConnectResponse);
- CPPUNIT_TEST(testConnect_ReceiveErrorConnectResponse);
- CPPUNIT_TEST(testConnect_ReceiveDataAfterConnect);
- CPPUNIT_TEST(testWrite_AfterConnect);
- CPPUNIT_TEST(testDisconnect_AfterConnectRequest);
- CPPUNIT_TEST(testDisconnect_AfterConnect);
- CPPUNIT_TEST(testTrafficFilter);
- CPPUNIT_TEST(testTrafficFilterNoConnectionReuse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- proxyHost = "doo.bah";
- proxyPort = 1234;
- proxyHostAddress = HostAddressPort(HostAddress("1.1.1.1"), proxyPort);
- host = HostAddressPort(HostAddress("2.2.2.2"), 2345);
- eventLoop = new DummyEventLoop();
- resolver = new StaticDomainNameResolver(eventLoop);
- resolver->addAddress(proxyHost, proxyHostAddress.getAddress());
- timerFactory = new DummyTimerFactory();
- connectionFactory = new MockConnectionFactory(eventLoop);
- connectFinished = false;
- connectFinishedWithError = false;
- disconnected = false;
- }
-
- void tearDown() {
- delete timerFactory;
- delete connectionFactory;
- delete resolver;
- delete eventLoop;
- }
-
- void connect(HTTPConnectProxiedConnection::ref connection, const HostAddressPort& to) {
- connection->connect(to);
- eventLoop->processEvents();
- eventLoop->processEvents();
- eventLoop->processEvents();
- }
-
- void testConnect_CreatesConnectionToProxy() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
-
- connect(testling, host);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connectionFactory->connections.size()));
- CPPUNIT_ASSERT(connectionFactory->connections[0]->hostAddressPort);
- CPPUNIT_ASSERT(proxyHostAddress == *connectionFactory->connections[0]->hostAddressPort);
- CPPUNIT_ASSERT(!connectFinished);
- }
-
- void testConnect_SendsConnectRequest() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
-
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n\r\n"), connectionFactory->connections[0]->dataWritten);
- }
-
- void testConnect_ReceiveConnectResponse() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(!connectFinishedWithError);
- CPPUNIT_ASSERT(dataRead.empty());
- }
-
- void testConnect_ReceiveConnectChunkedResponse() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 "));
- eventLoop->processEvents();
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("200 Connection established\r\n\r\n"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(!connectFinishedWithError);
- CPPUNIT_ASSERT(dataRead.empty());
- }
-
-
- void testConnect_ReceiveMalformedConnectResponse() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("FLOOP"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(connectFinishedWithError);
- CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
- }
-
- void testConnect_ReceiveErrorConnectResponse() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 401 Unauthorized\r\n\r\n"));
- eventLoop->processEvents();
-
- CPPUNIT_ASSERT(connectFinished);
- CPPUNIT_ASSERT(connectFinishedWithError);
- CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
- }
+ CPPUNIT_TEST_SUITE(HTTPConnectProxiedConnectionTest);
+ CPPUNIT_TEST(testConnect_CreatesConnectionToProxy);
+ CPPUNIT_TEST(testConnect_SendsConnectRequest);
+ CPPUNIT_TEST(testConnect_ReceiveConnectResponse);
+ CPPUNIT_TEST(testConnect_ReceiveConnectChunkedResponse);
+ CPPUNIT_TEST(testConnect_ReceiveMalformedConnectResponse);
+ CPPUNIT_TEST(testConnect_ReceiveErrorConnectResponse);
+ CPPUNIT_TEST(testConnect_ReceiveDataAfterConnect);
+ CPPUNIT_TEST(testWrite_AfterConnect);
+ CPPUNIT_TEST(testDisconnect_AfterConnectRequest);
+ CPPUNIT_TEST(testDisconnect_AfterConnect);
+ CPPUNIT_TEST(testTrafficFilter);
+ CPPUNIT_TEST(testTrafficFilterNoConnectionReuse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ proxyHost = "doo.bah";
+ proxyPort = 1234;
+ proxyHostAddress = HostAddressPort(HostAddress("1.1.1.1"), proxyPort);
+ host = HostAddressPort(HostAddress("2.2.2.2"), 2345);
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ resolver->addAddress(proxyHost, proxyHostAddress.getAddress());
+ timerFactory = new DummyTimerFactory();
+ connectionFactory = new MockConnectionFactory(eventLoop);
+ connectFinished = false;
+ connectFinishedWithError = false;
+ disconnected = false;
+ }
+
+ void tearDown() {
+ delete timerFactory;
+ delete connectionFactory;
+ delete resolver;
+ delete eventLoop;
+ }
+
+ void connect(HTTPConnectProxiedConnection::ref connection, const HostAddressPort& to) {
+ connection->connect(to);
+ eventLoop->processEvents();
+ eventLoop->processEvents();
+ eventLoop->processEvents();
+ }
+
+ void testConnect_CreatesConnectionToProxy() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+
+ connect(testling, host);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connectionFactory->connections.size()));
+ CPPUNIT_ASSERT(connectionFactory->connections[0]->hostAddressPort);
+ CPPUNIT_ASSERT(proxyHostAddress == *connectionFactory->connections[0]->hostAddressPort);
+ CPPUNIT_ASSERT(!connectFinished);
+ }
+
+ void testConnect_SendsConnectRequest() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n\r\n"), connectionFactory->connections[0]->dataWritten);
+ }
+
+ void testConnect_ReceiveConnectResponse() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(!connectFinishedWithError);
+ CPPUNIT_ASSERT(dataRead.empty());
+ }
+
+ void testConnect_ReceiveConnectChunkedResponse() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 "));
+ eventLoop->processEvents();
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("200 Connection established\r\n\r\n"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(!connectFinishedWithError);
+ CPPUNIT_ASSERT(dataRead.empty());
+ }
+
+
+ void testConnect_ReceiveMalformedConnectResponse() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("FLOOP"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(connectFinishedWithError);
+ CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
+ }
+
+ void testConnect_ReceiveErrorConnectResponse() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 401 Unauthorized\r\n\r\n"));
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(connectFinishedWithError);
+ CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
+ }
- void testConnect_ReceiveDataAfterConnect() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
- eventLoop->processEvents();
-
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("abcdef"));
-
- CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), dataRead);
- }
+ void testConnect_ReceiveDataAfterConnect() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
+ eventLoop->processEvents();
+
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("abcdef"));
+
+ CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), dataRead);
+ }
- void testWrite_AfterConnect() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
- eventLoop->processEvents();
- connectionFactory->connections[0]->dataWritten.clear();
+ void testWrite_AfterConnect() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
+ eventLoop->processEvents();
+ connectionFactory->connections[0]->dataWritten.clear();
- testling->write(createSafeByteArray("abcdef"));
+ testling->write(createSafeByteArray("abcdef"));
- CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), connectionFactory->connections[0]->dataWritten);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), connectionFactory->connections[0]->dataWritten);
+ }
- void testDisconnect_AfterConnectRequest() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+ void testDisconnect_AfterConnectRequest() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
- testling->disconnect();
+ testling->disconnect();
- CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
- CPPUNIT_ASSERT(disconnected);
- CPPUNIT_ASSERT(!disconnectedError);
- }
-
- void testDisconnect_AfterConnect() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
- eventLoop->processEvents();
+ CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
+ CPPUNIT_ASSERT(disconnected);
+ CPPUNIT_ASSERT(!disconnectedError);
+ }
+
+ void testDisconnect_AfterConnect() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
+ eventLoop->processEvents();
- testling->disconnect();
-
- CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
- CPPUNIT_ASSERT(disconnected);
- CPPUNIT_ASSERT(!disconnectedError);
- }
-
- void testTrafficFilter() {
- HTTPConnectProxiedConnection::ref testling(createTestling());
-
- boost::shared_ptr<ExampleHTTPTrafficFilter> httpTrafficFilter = boost::make_shared<ExampleHTTPTrafficFilter>();
-
- testling->setHTTPTrafficFilter(httpTrafficFilter);
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- // set a default response so the server response is answered by the traffic filter
- httpTrafficFilter->filterResponseReturn.clear();
- httpTrafficFilter->filterResponseReturn.push_back(std::pair<std::string, std::string>("Authorization", "Negotiate a87421000492aa874209af8bc028"));
-
- connectionFactory->connections[0]->dataWritten.clear();
-
- // test chunked response
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
- "HTTP/1.0 401 Unauthorized\r\n"));
- eventLoop->processEvents();
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
- "WWW-Authenticate: Negotiate\r\n"
- "\r\n"));
- eventLoop->processEvents();
-
-
- // verify that the traffic filter got called and answered with its response
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), httpTrafficFilter->filterResponses.size());
- CPPUNIT_ASSERT_EQUAL(std::string("WWW-Authenticate"), httpTrafficFilter->filterResponses[0][0].first);
-
- // remove the default response from the traffic filter
- httpTrafficFilter->filterResponseReturn.clear();
- eventLoop->processEvents();
-
- // verify that the traffic filter answer is send over the wire
- CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\nAuthorization: Negotiate a87421000492aa874209af8bc028\r\n\r\n"), connectionFactory->connections[1]->dataWritten);
-
- // verify that after without the default response, the traffic filter is skipped, authentication proceeds and traffic goes right through
- connectionFactory->connections[1]->dataWritten.clear();
- testling->write(createSafeByteArray("abcdef"));
- CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), connectionFactory->connections[1]->dataWritten);
- }
-
- void testTrafficFilterNoConnectionReuse() {
- HTTPConnectProxiedConnection::ref testling = createTestling();
-
- boost::shared_ptr<ProxyAuthenticationHTTPTrafficFilter> httpTrafficFilter = boost::make_shared<ProxyAuthenticationHTTPTrafficFilter>();
- testling->setHTTPTrafficFilter(httpTrafficFilter);
-
- connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
-
- // First HTTP CONNECT request assumes the proxy will work.
- CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
- "\r\n"), connectionFactory->connections[0]->dataWritten);
-
- // First reply presents initiator with authentication options.
- connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
- "HTTP/1.0 407 ProxyAuthentication Required\r\n"
- "proxy-Authenticate: Negotiate\r\n"
- "Proxy-Authenticate: Kerberos\r\n"
- "proxy-Authenticate: NTLM\r\n"
- "\r\n"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(false, connectFinished);
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
-
- // The HTTP proxy responds with code 407, so the traffic filter should inject the authentication response on a new connection.
- CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
- "Proxy-Authorization: NTLM TlRMTVNTUAABAAAAt7II4gkACQAxAAAACQAJACgAAAVNTUAADAAFASgKAAAAD0xBQlNNT0tFM1dPUktHUk9VUA==\r\n"
- "\r\n"), connectionFactory->connections[1]->dataWritten);
-
- // The proxy responds with another authentication step.
- connectionFactory->connections[1]->onDataRead(createSafeByteArrayRef(
- "HTTP/1.0 407 ProxyAuthentication Required\r\n"
- "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAEAAQADgAAAA1goriluCDYHcYI/sAAAAAAAAAAFQAVABIAAAABQLODgAAAA9TAFAASQBSAEkAVAAxAEIAAgAQAFMAUABJAFIASQBUADEAQgABABAAUwBQAEkAUgBJAFQAMQBCAAQAEABzAHAAaQByAGkAdAAxAGIAAwAQAHMAcABpAHIAaQB0ADEAYgAAAAAA\r\n"
- "\r\n"));
- eventLoop->processEvents();
- CPPUNIT_ASSERT_EQUAL(false, connectFinished);
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
-
- // Last HTTP request that should succeed. Further traffic will go over the connection of this request.
- CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
- "Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABIAEgBIAAAABgAGAFoAAAASABIVNTUAADAAYAAAABAAEACiAAAANYKI4gUBKAoAAAAPTABBAEIAUwBNAE8ASwBFADMAXwBxAGEATABBAEIAUwBNAE8ASwBFADMA0NKq8HYYhj8AAAAAAAAAAAAAAAAAAAAAOIiih3mR+AkyM4r99sy1mdFonCu2ILODro1WTTrJ4b4JcXEzUBA2Ig==\r\n"
- "\r\n"), connectionFactory->connections[2]->dataWritten);
-
- connectionFactory->connections[2]->onDataRead(createSafeByteArrayRef(
- "HTTP/1.0 200 OK\r\n"
- "\r\n"));
- eventLoop->processEvents();
-
- // The HTTP CONNECT proxy initialization finished without error.
- CPPUNIT_ASSERT_EQUAL(true, connectFinished);
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
-
- // Further traffic is written directly, without interception of the filter.
- connectionFactory->connections[2]->dataWritten.clear();
- testling->write(createSafeByteArray("This is some basic data traffic."));
- CPPUNIT_ASSERT_EQUAL(createByteArray("This is some basic data traffic."), connectionFactory->connections[2]->dataWritten);
- }
-
- private:
- HTTPConnectProxiedConnection::ref createTestling() {
- boost::shared_ptr<HTTPConnectProxiedConnection> c = HTTPConnectProxiedConnection::create(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, "", "");
- c->onConnectFinished.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleConnectFinished, this, _1));
- c->onDisconnected.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleDisconnected, this, _1));
- c->onDataRead.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleDataRead, this, _1));
- return c;
- }
-
- void handleConnectFinished(bool error) {
- connectFinished = true;
- connectFinishedWithError = error;
- }
-
- void handleDisconnected(const boost::optional<Connection::Error>& e) {
- disconnected = true;
- disconnectedError = e;
- }
-
- void handleDataRead(boost::shared_ptr<SafeByteArray> d) {
- append(dataRead, *d);
- }
-
- struct MockConnection : public Connection {
- public:
- MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false) {
- }
-
- void listen() { assert(false); }
-
- void connect(const HostAddressPort& address) {
- hostAddressPort = address;
- bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
- eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
- }
-
- HostAddressPort getLocalAddress() const { return HostAddressPort(); }
- HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-
- void disconnect() {
- disconnected = true;
- onDisconnected(boost::optional<Connection::Error>());
- }
-
- void write(const SafeByteArray& d) {
- append(dataWritten, d);
- }
-
- EventLoop* eventLoop;
- boost::optional<HostAddressPort> hostAddressPort;
- std::vector<HostAddressPort> failingPorts;
- ByteArray dataWritten;
- bool disconnected;
- };
-
- struct MockConnectionFactory : public ConnectionFactory {
- MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
- }
-
- boost::shared_ptr<Connection> createConnection() {
- boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop);
- connections.push_back(connection);
- SWIFT_LOG(debug) << "new connection created" << std::endl;
- return connection;
- }
-
- EventLoop* eventLoop;
- std::vector< boost::shared_ptr<MockConnection> > connections;
- std::vector<HostAddressPort> failingPorts;
- };
-
- private:
- std::string proxyHost;
- HostAddressPort proxyHostAddress;
- int proxyPort;
- HostAddressPort host;
- DummyEventLoop* eventLoop;
- StaticDomainNameResolver* resolver;
- MockConnectionFactory* connectionFactory;
- TimerFactory* timerFactory;
- bool connectFinished;
- bool connectFinishedWithError;
- bool disconnected;
- boost::optional<Connection::Error> disconnectedError;
- ByteArray dataRead;
+ testling->disconnect();
+
+ CPPUNIT_ASSERT(connectionFactory->connections[0]->disconnected);
+ CPPUNIT_ASSERT(disconnected);
+ CPPUNIT_ASSERT(!disconnectedError);
+ }
+
+ void testTrafficFilter() {
+ HTTPConnectProxiedConnection::ref testling(createTestling());
+
+ boost::shared_ptr<ExampleHTTPTrafficFilter> httpTrafficFilter = boost::make_shared<ExampleHTTPTrafficFilter>();
+
+ testling->setHTTPTrafficFilter(httpTrafficFilter);
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ // set a default response so the server response is answered by the traffic filter
+ httpTrafficFilter->filterResponseReturn.clear();
+ httpTrafficFilter->filterResponseReturn.push_back(std::pair<std::string, std::string>("Authorization", "Negotiate a87421000492aa874209af8bc028"));
+
+ connectionFactory->connections[0]->dataWritten.clear();
+
+ // test chunked response
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
+ "HTTP/1.0 401 Unauthorized\r\n"));
+ eventLoop->processEvents();
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
+ "WWW-Authenticate: Negotiate\r\n"
+ "\r\n"));
+ eventLoop->processEvents();
+
+
+ // verify that the traffic filter got called and answered with its response
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), httpTrafficFilter->filterResponses.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("WWW-Authenticate"), httpTrafficFilter->filterResponses[0][0].first);
+
+ // remove the default response from the traffic filter
+ httpTrafficFilter->filterResponseReturn.clear();
+ eventLoop->processEvents();
+
+ // verify that the traffic filter answer is send over the wire
+ CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\nAuthorization: Negotiate a87421000492aa874209af8bc028\r\n\r\n"), connectionFactory->connections[1]->dataWritten);
+
+ // verify that after without the default response, the traffic filter is skipped, authentication proceeds and traffic goes right through
+ connectionFactory->connections[1]->dataWritten.clear();
+ testling->write(createSafeByteArray("abcdef"));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("abcdef"), connectionFactory->connections[1]->dataWritten);
+ }
+
+ void testTrafficFilterNoConnectionReuse() {
+ HTTPConnectProxiedConnection::ref testling = createTestling();
+
+ boost::shared_ptr<ProxyAuthenticationHTTPTrafficFilter> httpTrafficFilter = boost::make_shared<ProxyAuthenticationHTTPTrafficFilter>();
+ testling->setHTTPTrafficFilter(httpTrafficFilter);
+
+ connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+
+ // First HTTP CONNECT request assumes the proxy will work.
+ CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
+ "\r\n"), connectionFactory->connections[0]->dataWritten);
+
+ // First reply presents initiator with authentication options.
+ connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef(
+ "HTTP/1.0 407 ProxyAuthentication Required\r\n"
+ "proxy-Authenticate: Negotiate\r\n"
+ "Proxy-Authenticate: Kerberos\r\n"
+ "proxy-Authenticate: NTLM\r\n"
+ "\r\n"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(false, connectFinished);
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
+
+ // The HTTP proxy responds with code 407, so the traffic filter should inject the authentication response on a new connection.
+ CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
+ "Proxy-Authorization: NTLM TlRMTVNTUAABAAAAt7II4gkACQAxAAAACQAJACgAAAVNTUAADAAFASgKAAAAD0xBQlNNT0tFM1dPUktHUk9VUA==\r\n"
+ "\r\n"), connectionFactory->connections[1]->dataWritten);
+
+ // The proxy responds with another authentication step.
+ connectionFactory->connections[1]->onDataRead(createSafeByteArrayRef(
+ "HTTP/1.0 407 ProxyAuthentication Required\r\n"
+ "Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAEAAQADgAAAA1goriluCDYHcYI/sAAAAAAAAAAFQAVABIAAAABQLODgAAAA9TAFAASQBSAEkAVAAxAEIAAgAQAFMAUABJAFIASQBUADEAQgABABAAUwBQAEkAUgBJAFQAMQBCAAQAEABzAHAAaQByAGkAdAAxAGIAAwAQAHMAcABpAHIAaQB0ADEAYgAAAAAA\r\n"
+ "\r\n"));
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(false, connectFinished);
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
+
+ // Last HTTP request that should succeed. Further traffic will go over the connection of this request.
+ CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
+ "Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABIAEgBIAAAABgAGAFoAAAASABIVNTUAADAAYAAAABAAEACiAAAANYKI4gUBKAoAAAAPTABBAEIAUwBNAE8ASwBFADMAXwBxAGEATABBAEIAUwBNAE8ASwBFADMA0NKq8HYYhj8AAAAAAAAAAAAAAAAAAAAAOIiih3mR+AkyM4r99sy1mdFonCu2ILODro1WTTrJ4b4JcXEzUBA2Ig==\r\n"
+ "\r\n"), connectionFactory->connections[2]->dataWritten);
+
+ connectionFactory->connections[2]->onDataRead(createSafeByteArrayRef(
+ "HTTP/1.0 200 OK\r\n"
+ "\r\n"));
+ eventLoop->processEvents();
+
+ // The HTTP CONNECT proxy initialization finished without error.
+ CPPUNIT_ASSERT_EQUAL(true, connectFinished);
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError);
+
+ // Further traffic is written directly, without interception of the filter.
+ connectionFactory->connections[2]->dataWritten.clear();
+ testling->write(createSafeByteArray("This is some basic data traffic."));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("This is some basic data traffic."), connectionFactory->connections[2]->dataWritten);
+ }
+
+ private:
+ HTTPConnectProxiedConnection::ref createTestling() {
+ boost::shared_ptr<HTTPConnectProxiedConnection> c = HTTPConnectProxiedConnection::create(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, "", "");
+ c->onConnectFinished.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleConnectFinished, this, _1));
+ c->onDisconnected.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleDisconnected, this, _1));
+ c->onDataRead.connect(boost::bind(&HTTPConnectProxiedConnectionTest::handleDataRead, this, _1));
+ return c;
+ }
+
+ void handleConnectFinished(bool error) {
+ connectFinished = true;
+ connectFinishedWithError = error;
+ }
+
+ void handleDisconnected(const boost::optional<Connection::Error>& e) {
+ disconnected = true;
+ disconnectedError = e;
+ }
+
+ void handleDataRead(boost::shared_ptr<SafeByteArray> d) {
+ append(dataRead, *d);
+ }
+
+ struct MockConnection : public Connection {
+ public:
+ MockConnection(const std::vector<HostAddressPort>& failingPorts, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), disconnected(false) {
+ }
+
+ void listen() { assert(false); }
+
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
+
+ void disconnect() {
+ disconnected = true;
+ onDisconnected(boost::optional<Connection::Error>());
+ }
+
+ void write(const SafeByteArray& d) {
+ append(dataWritten, d);
+ }
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ ByteArray dataWritten;
+ bool disconnected;
+ };
+
+ struct MockConnectionFactory : public ConnectionFactory {
+ MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
+ }
+
+ boost::shared_ptr<Connection> createConnection() {
+ boost::shared_ptr<MockConnection> connection = boost::make_shared<MockConnection>(failingPorts, eventLoop);
+ connections.push_back(connection);
+ SWIFT_LOG(debug) << "new connection created" << std::endl;
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< boost::shared_ptr<MockConnection> > connections;
+ std::vector<HostAddressPort> failingPorts;
+ };
+
+ private:
+ std::string proxyHost;
+ HostAddressPort proxyHostAddress;
+ int proxyPort;
+ HostAddressPort host;
+ DummyEventLoop* eventLoop;
+ StaticDomainNameResolver* resolver;
+ MockConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+ bool connectFinished;
+ bool connectFinishedWithError;
+ bool disconnected;
+ boost::optional<Connection::Error> disconnectedError;
+ ByteArray dataRead;
};
CPPUNIT_TEST_SUITE_REGISTRATION(HTTPConnectProxiedConnectionTest);
diff --git a/Swiften/Network/UnitTest/HostAddressTest.cpp b/Swiften/Network/UnitTest/HostAddressTest.cpp
index 42fb108..aceb9be 100644
--- a/Swiften/Network/UnitTest/HostAddressTest.cpp
+++ b/Swiften/Network/UnitTest/HostAddressTest.cpp
@@ -14,54 +14,54 @@
using namespace Swift;
class HostAddressTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(HostAddressTest);
- CPPUNIT_TEST(testConstructor);
- CPPUNIT_TEST(testConstructor_Invalid);
- CPPUNIT_TEST(testConstructor_InvalidString);
- CPPUNIT_TEST(testToString);
- CPPUNIT_TEST(testToString_IPv6);
- CPPUNIT_TEST(testToString_Invalid);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(HostAddressTest);
+ CPPUNIT_TEST(testConstructor);
+ CPPUNIT_TEST(testConstructor_Invalid);
+ CPPUNIT_TEST(testConstructor_InvalidString);
+ CPPUNIT_TEST(testToString);
+ CPPUNIT_TEST(testToString_IPv6);
+ CPPUNIT_TEST(testToString_Invalid);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testConstructor() {
- HostAddress testling("192.168.1.254");
+ public:
+ void testConstructor() {
+ HostAddress testling("192.168.1.254");
- CPPUNIT_ASSERT_EQUAL(std::string("192.168.1.254"), testling.toString());
- CPPUNIT_ASSERT(testling.isValid());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("192.168.1.254"), testling.toString());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
- void testConstructor_Invalid() {
- HostAddress testling;
+ void testConstructor_Invalid() {
+ HostAddress testling;
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testConstructor_InvalidString() {
- HostAddress testling("invalid");
+ void testConstructor_InvalidString() {
+ HostAddress testling("invalid");
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testToString() {
- unsigned char address[4] = {10, 0, 1, 253};
- HostAddress testling(address, 4);
+ void testToString() {
+ unsigned char address[4] = {10, 0, 1, 253};
+ HostAddress testling(address, 4);
- CPPUNIT_ASSERT_EQUAL(std::string("10.0.1.253"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("10.0.1.253"), testling.toString());
+ }
- void testToString_IPv6() {
- unsigned char address[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17};
- HostAddress testling(address, 16);
+ void testToString_IPv6() {
+ unsigned char address[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17};
+ HostAddress testling(address, 16);
- CPPUNIT_ASSERT_EQUAL(std::string("102:304:506:708:90a:b0c:d0e:f11"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("102:304:506:708:90a:b0c:d0e:f11"), testling.toString());
+ }
- void testToString_Invalid() {
- HostAddress testling;
+ void testToString_Invalid() {
+ HostAddress testling;
- CPPUNIT_ASSERT_EQUAL(std::string("0.0.0.0"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("0.0.0.0"), testling.toString());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(HostAddressTest);
diff --git a/Swiften/Network/UnixNetworkEnvironment.cpp b/Swiften/Network/UnixNetworkEnvironment.cpp
index e1fdc88..3239448 100644
--- a/Swiften/Network/UnixNetworkEnvironment.cpp
+++ b/Swiften/Network/UnixNetworkEnvironment.cpp
@@ -26,38 +26,38 @@
namespace Swift {
std::vector<NetworkInterface> UnixNetworkEnvironment::getNetworkInterfaces() const {
- std::map<std::string, NetworkInterface> interfaces;
+ std::map<std::string, NetworkInterface> interfaces;
#ifndef __ANDROID__
- ifaddrs* addrs = 0;
- int ret = getifaddrs(&addrs);
- if (ret != 0) {
- return std::vector<NetworkInterface>();
- }
-
- for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) {
- std::string name(a->ifa_name);
- boost::optional<HostAddress> address;
- if (a->ifa_addr->sa_family == PF_INET) {
- sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr);
- address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
- }
- else if (a->ifa_addr->sa_family == PF_INET6) {
- sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr);
- address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
- }
- if (address && !address->isLocalhost()) {
- std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first;
- i->second.addAddress(*address);
- }
- }
-
- freeifaddrs(addrs);
+ ifaddrs* addrs = 0;
+ int ret = getifaddrs(&addrs);
+ if (ret != 0) {
+ return std::vector<NetworkInterface>();
+ }
+
+ for (ifaddrs* a = addrs; a != 0; a = a->ifa_next) {
+ std::string name(a->ifa_name);
+ boost::optional<HostAddress> address;
+ if (a->ifa_addr->sa_family == PF_INET) {
+ sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr);
+ address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin_addr)), 4);
+ }
+ else if (a->ifa_addr->sa_family == PF_INET6) {
+ sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr);
+ address = HostAddress(reinterpret_cast<const unsigned char*>(&(sa->sin6_addr)), 16);
+ }
+ if (address && !address->isLocalhost()) {
+ std::map<std::string, NetworkInterface>::iterator i = interfaces.insert(std::make_pair(name, NetworkInterface(name, a->ifa_flags & IFF_LOOPBACK))).first;
+ i->second.addAddress(*address);
+ }
+ }
+
+ freeifaddrs(addrs);
#endif
- std::vector<NetworkInterface> result;
- for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
- result.push_back(i->second);
- }
- return result;
+ std::vector<NetworkInterface> result;
+ for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
+ result.push_back(i->second);
+ }
+ return result;
}
}
diff --git a/Swiften/Network/UnixNetworkEnvironment.h b/Swiften/Network/UnixNetworkEnvironment.h
index ad53f28..4e31e35 100644
--- a/Swiften/Network/UnixNetworkEnvironment.h
+++ b/Swiften/Network/UnixNetworkEnvironment.h
@@ -21,8 +21,8 @@
namespace Swift {
class UnixNetworkEnvironment : public NetworkEnvironment {
- public:
- std::vector<NetworkInterface> getNetworkInterfaces() const;
+ public:
+ std::vector<NetworkInterface> getNetworkInterfaces() const;
};
}
diff --git a/Swiften/Network/UnixProxyProvider.cpp b/Swiften/Network/UnixProxyProvider.cpp
index 4ca9311..aa86c04 100644
--- a/Swiften/Network/UnixProxyProvider.cpp
+++ b/Swiften/Network/UnixProxyProvider.cpp
@@ -17,48 +17,48 @@
namespace Swift {
UnixProxyProvider::UnixProxyProvider() :
- gconfProxyProvider(0),
- environmentProxyProvider()
+ gconfProxyProvider(0),
+ environmentProxyProvider()
{
#if defined(HAVE_GCONF)
- gconfProxyProvider = new GConfProxyProvider();
+ gconfProxyProvider = new GConfProxyProvider();
#endif
}
UnixProxyProvider::~UnixProxyProvider() {
#if defined(HAVE_GCONF)
- delete gconfProxyProvider;
+ delete gconfProxyProvider;
#endif
}
HostAddressPort UnixProxyProvider::getSOCKS5Proxy() const {
- HostAddressPort proxy;
+ HostAddressPort proxy;
#if defined(HAVE_GCONF)
- proxy = gconfProxyProvider->getSOCKS5Proxy();
- if(proxy.isValid()) {
- return proxy;
- }
+ proxy = gconfProxyProvider->getSOCKS5Proxy();
+ if(proxy.isValid()) {
+ return proxy;
+ }
#endif
- proxy = environmentProxyProvider.getSOCKS5Proxy();
- if(proxy.isValid()) {
- return proxy;
- }
- return HostAddressPort(HostAddress(), 0);
+ proxy = environmentProxyProvider.getSOCKS5Proxy();
+ if(proxy.isValid()) {
+ return proxy;
+ }
+ return HostAddressPort(HostAddress(), 0);
}
HostAddressPort UnixProxyProvider::getHTTPConnectProxy() const {
- HostAddressPort proxy;
+ HostAddressPort proxy;
#if defined(HAVE_GCONF)
- proxy = gconfProxyProvider->getHTTPConnectProxy();
- if(proxy.isValid()) {
- return proxy;
- }
+ proxy = gconfProxyProvider->getHTTPConnectProxy();
+ if(proxy.isValid()) {
+ return proxy;
+ }
#endif
- proxy = environmentProxyProvider.getHTTPConnectProxy();
- if(proxy.isValid()) {
- return proxy;
- }
- return HostAddressPort(HostAddress(), 0);
+ proxy = environmentProxyProvider.getHTTPConnectProxy();
+ if(proxy.isValid()) {
+ return proxy;
+ }
+ return HostAddressPort(HostAddress(), 0);
}
diff --git a/Swiften/Network/UnixProxyProvider.h b/Swiften/Network/UnixProxyProvider.h
index 4fc8b27..1721480 100644
--- a/Swiften/Network/UnixProxyProvider.h
+++ b/Swiften/Network/UnixProxyProvider.h
@@ -15,18 +15,18 @@
#include <Swiften/Network/EnvironmentProxyProvider.h>
namespace Swift {
- class GConfProxyProvider;
+ class GConfProxyProvider;
- class UnixProxyProvider : public ProxyProvider {
- public:
- UnixProxyProvider();
- virtual ~UnixProxyProvider();
+ class UnixProxyProvider : public ProxyProvider {
+ public:
+ UnixProxyProvider();
+ virtual ~UnixProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
- private:
- GConfProxyProvider* gconfProxyProvider;
- EnvironmentProxyProvider environmentProxyProvider;
- };
+ private:
+ GConfProxyProvider* gconfProxyProvider;
+ EnvironmentProxyProvider environmentProxyProvider;
+ };
}
diff --git a/Swiften/Network/WindowsNetworkEnvironment.cpp b/Swiften/Network/WindowsNetworkEnvironment.cpp
index 1dd363d..6ce41de 100644
--- a/Swiften/Network/WindowsNetworkEnvironment.cpp
+++ b/Swiften/Network/WindowsNetworkEnvironment.cpp
@@ -29,46 +29,46 @@
namespace Swift {
std::vector<NetworkInterface> WindowsNetworkEnvironment::getNetworkInterfaces() const {
- std::vector<NetworkInterface> result;
+ 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;
- }
+ 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);
- }
- }
- }
+ 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);
- }
- return result;
+ for (std::map<std::string,NetworkInterface>::const_iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
+ result.push_back(i->second);
+ }
+ return result;
}
}
diff --git a/Swiften/Network/WindowsNetworkEnvironment.h b/Swiften/Network/WindowsNetworkEnvironment.h
index 18996ed..2e3a641 100644
--- a/Swiften/Network/WindowsNetworkEnvironment.h
+++ b/Swiften/Network/WindowsNetworkEnvironment.h
@@ -13,8 +13,8 @@
#include <Swiften/Network/NetworkEnvironment.h>
namespace Swift {
- class SWIFTEN_API WindowsNetworkEnvironment : public NetworkEnvironment {
- public:
- std::vector<NetworkInterface> getNetworkInterfaces() const;
- };
+ class SWIFTEN_API WindowsNetworkEnvironment : public NetworkEnvironment {
+ public:
+ std::vector<NetworkInterface> getNetworkInterfaces() const;
+ };
}
diff --git a/Swiften/Network/WindowsProxyProvider.cpp b/Swiften/Network/WindowsProxyProvider.cpp
index f2e91a2..8f90d1e 100644
--- a/Swiften/Network/WindowsProxyProvider.cpp
+++ b/Swiften/Network/WindowsProxyProvider.cpp
@@ -31,92 +31,92 @@ namespace Swift {
WindowsProxyProvider::WindowsProxyProvider()
: ProxyProvider()
{
- HKEY hKey = (HKEY)INVALID_HANDLE_VALUE;
- long result;
-
- result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_READ, &hKey);
- if (result == ERROR_SUCCESS && hKey != INVALID_HANDLE_VALUE && proxyEnabled(hKey)) {
- DWORD dataType = REG_SZ;
- DWORD dataSize = 0;
- ByteArray dataBuffer;
-
- result = RegQueryValueEx(hKey, "ProxyServer", NULL, &dataType, NULL, &dataSize);
- if(result != ERROR_SUCCESS) {
- return;
- }
- dataBuffer.resize(dataSize);
- result = RegQueryValueEx(hKey, "ProxyServer", NULL, &dataType, reinterpret_cast<BYTE*>(vecptr(dataBuffer)), &dataSize);
- if(result == ERROR_SUCCESS) {
- std::vector<std::string> proxies = String::split(byteArrayToString(dataBuffer), ';');
- std::pair<std::string, std::string> protocolAndProxy;
- foreach(std::string proxy, proxies) {
- if(proxy.find('=') != std::string::npos) {
- protocolAndProxy = String::getSplittedAtFirst(proxy, '=');
- SWIFT_LOG(debug) << "Found proxy: " << protocolAndProxy.first << " => " << protocolAndProxy.second << std::endl;
- if(protocolAndProxy.first.compare("socks") == 0) {
- socksProxy = getAsHostAddressPort(protocolAndProxy.second);
- }
- else if (protocolAndProxy.first.compare("http") == 0) {
- httpProxy = getAsHostAddressPort(protocolAndProxy.second);
- }
- }
- }
- }
- }
+ HKEY hKey = (HKEY)INVALID_HANDLE_VALUE;
+ long result;
+
+ result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_READ, &hKey);
+ if (result == ERROR_SUCCESS && hKey != INVALID_HANDLE_VALUE && proxyEnabled(hKey)) {
+ DWORD dataType = REG_SZ;
+ DWORD dataSize = 0;
+ ByteArray dataBuffer;
+
+ result = RegQueryValueEx(hKey, "ProxyServer", NULL, &dataType, NULL, &dataSize);
+ if(result != ERROR_SUCCESS) {
+ return;
+ }
+ dataBuffer.resize(dataSize);
+ result = RegQueryValueEx(hKey, "ProxyServer", NULL, &dataType, reinterpret_cast<BYTE*>(vecptr(dataBuffer)), &dataSize);
+ if(result == ERROR_SUCCESS) {
+ std::vector<std::string> proxies = String::split(byteArrayToString(dataBuffer), ';');
+ std::pair<std::string, std::string> protocolAndProxy;
+ foreach(std::string proxy, proxies) {
+ if(proxy.find('=') != std::string::npos) {
+ protocolAndProxy = String::getSplittedAtFirst(proxy, '=');
+ SWIFT_LOG(debug) << "Found proxy: " << protocolAndProxy.first << " => " << protocolAndProxy.second << std::endl;
+ if(protocolAndProxy.first.compare("socks") == 0) {
+ socksProxy = getAsHostAddressPort(protocolAndProxy.second);
+ }
+ else if (protocolAndProxy.first.compare("http") == 0) {
+ httpProxy = getAsHostAddressPort(protocolAndProxy.second);
+ }
+ }
+ }
+ }
+ }
}
HostAddressPort WindowsProxyProvider::getHTTPConnectProxy() const {
- return httpProxy;
+ return httpProxy;
}
HostAddressPort WindowsProxyProvider::getSOCKS5Proxy() const {
- return socksProxy;
+ return socksProxy;
}
HostAddressPort WindowsProxyProvider::getAsHostAddressPort(std::string proxy) {
- HostAddressPort ret(HostAddress(), 0);
-
- try {
- std::pair<std::string, std::string> tmp;
- int port = 0;
- tmp = String::getSplittedAtFirst(proxy, ':');
- // .c_str() is needed as tmp.second can include a \0 char which will end in an exception of the lexical cast.
- // with .c_str() the \0 will not be part of the string which is to be casted
- port = boost::lexical_cast<int> (tmp.second.c_str());
- ret = HostAddressPort(HostAddress(tmp.first), port);
- }
- catch(...) {
- std::cerr << "Exception occured while parsing windows proxy \"getHostAddressPort\"." << std::endl;
- }
-
- return ret;
+ HostAddressPort ret(HostAddress(), 0);
+
+ try {
+ std::pair<std::string, std::string> tmp;
+ int port = 0;
+ tmp = String::getSplittedAtFirst(proxy, ':');
+ // .c_str() is needed as tmp.second can include a \0 char which will end in an exception of the lexical cast.
+ // with .c_str() the \0 will not be part of the string which is to be casted
+ port = boost::lexical_cast<int> (tmp.second.c_str());
+ ret = HostAddressPort(HostAddress(tmp.first), port);
+ }
+ catch(...) {
+ std::cerr << "Exception occured while parsing windows proxy \"getHostAddressPort\"." << std::endl;
+ }
+
+ return ret;
}
bool WindowsProxyProvider::proxyEnabled(HKEY hKey) const {
- bool ret = false;
- long result;
- DWORD dataType = REG_DWORD;
- DWORD dataSize = 0;
- DWORD data = 0;
- ByteArray dataBuffer;
-
- if(hKey == INVALID_HANDLE_VALUE)
- return ret;
-
- result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, NULL, &dataSize);
- if(result != ERROR_SUCCESS)
- return ret;
-
- dataBuffer.resize(dataSize);
- result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, reinterpret_cast<BYTE*>(vecptr(dataBuffer)), &dataSize);
- if(result != ERROR_SUCCESS)
- return ret;
-
- for(size_t t = 0; t < dataBuffer.size(); t++) {
- data += static_cast<int> (dataBuffer[t]) * pow(256, static_cast<double>(t));
- }
- return (data == 1);
+ bool ret = false;
+ long result;
+ DWORD dataType = REG_DWORD;
+ DWORD dataSize = 0;
+ DWORD data = 0;
+ ByteArray dataBuffer;
+
+ if(hKey == INVALID_HANDLE_VALUE)
+ return ret;
+
+ result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, NULL, &dataSize);
+ if(result != ERROR_SUCCESS)
+ return ret;
+
+ dataBuffer.resize(dataSize);
+ result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, reinterpret_cast<BYTE*>(vecptr(dataBuffer)), &dataSize);
+ if(result != ERROR_SUCCESS)
+ return ret;
+
+ for(size_t t = 0; t < dataBuffer.size(); t++) {
+ data += static_cast<int> (dataBuffer[t]) * pow(256, static_cast<double>(t));
+ }
+ return (data == 1);
}
}
diff --git a/Swiften/Network/WindowsProxyProvider.h b/Swiften/Network/WindowsProxyProvider.h
index 12aa18d..ded5049 100644
--- a/Swiften/Network/WindowsProxyProvider.h
+++ b/Swiften/Network/WindowsProxyProvider.h
@@ -10,15 +10,15 @@
#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
- class SWIFTEN_API WindowsProxyProvider : public ProxyProvider {
- public:
- WindowsProxyProvider();
- virtual HostAddressPort getHTTPConnectProxy() const;
- virtual HostAddressPort getSOCKS5Proxy() const;
- private:
- HostAddressPort getAsHostAddressPort(std::string proxy);
- bool proxyEnabled(HKEY hKey) const;
- HostAddressPort socksProxy;
- HostAddressPort httpProxy;
- };
+ class SWIFTEN_API WindowsProxyProvider : public ProxyProvider {
+ public:
+ WindowsProxyProvider();
+ virtual HostAddressPort getHTTPConnectProxy() const;
+ virtual HostAddressPort getSOCKS5Proxy() const;
+ private:
+ HostAddressPort getAsHostAddressPort(std::string proxy);
+ bool proxyEnabled(HKEY hKey) const;
+ HostAddressPort socksProxy;
+ HostAddressPort httpProxy;
+ };
}
diff --git a/Swiften/Parser/Attribute.h b/Swiften/Parser/Attribute.h
index 1c4ad77..f54317e 100644
--- a/Swiften/Parser/Attribute.h
+++ b/Swiften/Parser/Attribute.h
@@ -9,25 +9,25 @@
#include <string>
namespace Swift {
- class Attribute {
- public:
- Attribute(const std::string& name, const std::string& ns) : name(name), ns(ns) {
- }
+ class Attribute {
+ public:
+ Attribute(const std::string& name, const std::string& ns) : name(name), ns(ns) {
+ }
- const std::string& getName() const {
- return name;
- }
+ const std::string& getName() const {
+ return name;
+ }
- const std::string& getNamespace() const {
- return ns;
- }
+ const std::string& getNamespace() const {
+ return ns;
+ }
- bool operator==(const Attribute& o) const {
- return o.name == name && o.ns == ns;
- }
+ bool operator==(const Attribute& o) const {
+ return o.name == name && o.ns == ns;
+ }
- private:
- std::string name;
- std::string ns;
- };
+ private:
+ std::string name;
+ std::string ns;
+ };
}
diff --git a/Swiften/Parser/AttributeMap.cpp b/Swiften/Parser/AttributeMap.cpp
index 3fb8faf..c112d52 100644
--- a/Swiften/Parser/AttributeMap.cpp
+++ b/Swiften/Parser/AttributeMap.cpp
@@ -19,38 +19,38 @@ AttributeMap::AttributeMap() {
}
std::string AttributeMap::getAttribute(const std::string& attribute, const std::string& ns) const {
- AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
- lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ns));
- if (i == attributes.end()) {
- return "";
- }
- else {
- return i->getValue();
- }
+ AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
+ lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ns));
+ if (i == attributes.end()) {
+ return "";
+ }
+ else {
+ return i->getValue();
+ }
}
bool AttributeMap::getBoolAttribute(const std::string& attribute, bool defaultValue) const {
- AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
- lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ""));
- if (i == attributes.end()) {
- return defaultValue;
- }
- else {
- return i->getValue() == "true" || i->getValue() == "1";
- }
+ AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
+ lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ""));
+ if (i == attributes.end()) {
+ return defaultValue;
+ }
+ else {
+ return i->getValue() == "true" || i->getValue() == "1";
+ }
}
boost::optional<std::string> AttributeMap::getAttributeValue(const std::string& attribute) const {
- AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
- lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ""));
- if (i == attributes.end()) {
- return boost::optional<std::string>();
- }
- else {
- return i->getValue();
- }
+ AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(),
+ lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ""));
+ if (i == attributes.end()) {
+ return boost::optional<std::string>();
+ }
+ else {
+ return i->getValue();
+ }
}
void AttributeMap::addAttribute(const std::string& name, const std::string& ns, const std::string& value) {
- attributes.push_back(Entry(Attribute(name, ns), value));
+ attributes.push_back(Entry(Attribute(name, ns), value));
}
diff --git a/Swiften/Parser/AttributeMap.h b/Swiften/Parser/AttributeMap.h
index 336f4cd..798649a 100644
--- a/Swiften/Parser/AttributeMap.h
+++ b/Swiften/Parser/AttributeMap.h
@@ -16,40 +16,40 @@
#include <Swiften/Parser/Attribute.h>
namespace Swift {
- class SWIFTEN_API AttributeMap {
- public:
- class Entry {
- public:
- Entry(const Attribute& attribute, const std::string& value) : attribute(attribute), value(value) {
- }
-
- const Attribute& getAttribute() const {
- return attribute;
- }
-
- const std::string& getValue() const {
- return value;
- }
-
- private:
- Attribute attribute;
- std::string value;
- };
-
- AttributeMap();
-
- std::string getAttribute(const std::string& attribute, const std::string& ns = "") const;
- bool getBoolAttribute(const std::string& attribute, bool defaultValue = false) const;
- boost::optional<std::string> getAttributeValue(const std::string&) const;
-
- void addAttribute(const std::string& name, const std::string& ns, const std::string& value);
-
- const std::vector<Entry>& getEntries() const {
- return attributes;
- }
-
- private:
- typedef std::vector<Entry> AttributeValueMap;
- AttributeValueMap attributes;
- };
+ class SWIFTEN_API AttributeMap {
+ public:
+ class Entry {
+ public:
+ Entry(const Attribute& attribute, const std::string& value) : attribute(attribute), value(value) {
+ }
+
+ const Attribute& getAttribute() const {
+ return attribute;
+ }
+
+ const std::string& getValue() const {
+ return value;
+ }
+
+ private:
+ Attribute attribute;
+ std::string value;
+ };
+
+ AttributeMap();
+
+ std::string getAttribute(const std::string& attribute, const std::string& ns = "") const;
+ bool getBoolAttribute(const std::string& attribute, bool defaultValue = false) const;
+ boost::optional<std::string> getAttributeValue(const std::string&) const;
+
+ void addAttribute(const std::string& name, const std::string& ns, const std::string& value);
+
+ const std::vector<Entry>& getEntries() const {
+ return attributes;
+ }
+
+ private:
+ typedef std::vector<Entry> AttributeValueMap;
+ AttributeValueMap attributes;
+ };
}
diff --git a/Swiften/Parser/AuthChallengeParser.cpp b/Swiften/Parser/AuthChallengeParser.cpp
index 42f5ca6..cf69672 100644
--- a/Swiften/Parser/AuthChallengeParser.cpp
+++ b/Swiften/Parser/AuthChallengeParser.cpp
@@ -14,18 +14,18 @@ AuthChallengeParser::AuthChallengeParser() : GenericElementParser<AuthChallenge>
}
void AuthChallengeParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++depth;
+ ++depth;
}
void AuthChallengeParser::handleEndElement(const std::string&, const std::string&) {
- --depth;
- if (depth == 0) {
- getElementGeneric()->setValue(Base64::decode(text));
- }
+ --depth;
+ if (depth == 0) {
+ getElementGeneric()->setValue(Base64::decode(text));
+ }
}
void AuthChallengeParser::handleCharacterData(const std::string& text) {
- this->text += text;
+ this->text += text;
}
}
diff --git a/Swiften/Parser/AuthChallengeParser.h b/Swiften/Parser/AuthChallengeParser.h
index 464f0c1..48e2bfb 100644
--- a/Swiften/Parser/AuthChallengeParser.h
+++ b/Swiften/Parser/AuthChallengeParser.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API AuthChallengeParser : public GenericElementParser<AuthChallenge> {
- public:
- AuthChallengeParser();
+ class SWIFTEN_API AuthChallengeParser : public GenericElementParser<AuthChallenge> {
+ public:
+ AuthChallengeParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
- virtual void handleCharacterData(const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleCharacterData(const std::string&);
- private:
- int depth;
- std::string text;
- };
+ private:
+ int depth;
+ std::string text;
+ };
}
diff --git a/Swiften/Parser/AuthFailureParser.h b/Swiften/Parser/AuthFailureParser.h
index 3148222..1706290 100644
--- a/Swiften/Parser/AuthFailureParser.h
+++ b/Swiften/Parser/AuthFailureParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API AuthFailureParser : public GenericElementParser<AuthFailure> {
- public:
- AuthFailureParser() : GenericElementParser<AuthFailure>() {}
- };
+ class SWIFTEN_API AuthFailureParser : public GenericElementParser<AuthFailure> {
+ public:
+ AuthFailureParser() : GenericElementParser<AuthFailure>() {}
+ };
}
diff --git a/Swiften/Parser/AuthRequestParser.cpp b/Swiften/Parser/AuthRequestParser.cpp
index 2fb311c..a24be8d 100644
--- a/Swiften/Parser/AuthRequestParser.cpp
+++ b/Swiften/Parser/AuthRequestParser.cpp
@@ -14,21 +14,21 @@ AuthRequestParser::AuthRequestParser() : GenericElementParser<AuthRequest>(), de
}
void AuthRequestParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attribute) {
- if (depth_ == 0) {
- getElementGeneric()->setMechanism(attribute.getAttribute("mechanism"));
- }
- ++depth_;
+ if (depth_ == 0) {
+ getElementGeneric()->setMechanism(attribute.getAttribute("mechanism"));
+ }
+ ++depth_;
}
void AuthRequestParser::handleEndElement(const std::string&, const std::string&) {
- --depth_;
- if (depth_ == 0) {
- getElementGeneric()->setMessage(createSafeByteArray(Base64::decode(text_)));
- }
+ --depth_;
+ if (depth_ == 0) {
+ getElementGeneric()->setMessage(createSafeByteArray(Base64::decode(text_)));
+ }
}
void AuthRequestParser::handleCharacterData(const std::string& text) {
- text_ += text;
+ text_ += text;
}
}
diff --git a/Swiften/Parser/AuthRequestParser.h b/Swiften/Parser/AuthRequestParser.h
index 005bd48..ac94abf 100644
--- a/Swiften/Parser/AuthRequestParser.h
+++ b/Swiften/Parser/AuthRequestParser.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API AuthRequestParser : public GenericElementParser<AuthRequest> {
- public:
- AuthRequestParser();
+ class SWIFTEN_API AuthRequestParser : public GenericElementParser<AuthRequest> {
+ public:
+ AuthRequestParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
- virtual void handleCharacterData(const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleCharacterData(const std::string&);
- private:
- std::string text_;
- int depth_;
- };
+ private:
+ std::string text_;
+ int depth_;
+ };
}
diff --git a/Swiften/Parser/AuthResponseParser.cpp b/Swiften/Parser/AuthResponseParser.cpp
index 64fe6c8..59f6455 100644
--- a/Swiften/Parser/AuthResponseParser.cpp
+++ b/Swiften/Parser/AuthResponseParser.cpp
@@ -14,18 +14,18 @@ AuthResponseParser::AuthResponseParser() : GenericElementParser<AuthResponse>(),
}
void AuthResponseParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++depth;
+ ++depth;
}
void AuthResponseParser::handleEndElement(const std::string&, const std::string&) {
- --depth;
- if (depth == 0) {
- getElementGeneric()->setValue(createSafeByteArray(Base64::decode(text)));
- }
+ --depth;
+ if (depth == 0) {
+ getElementGeneric()->setValue(createSafeByteArray(Base64::decode(text)));
+ }
}
void AuthResponseParser::handleCharacterData(const std::string& text) {
- this->text += text;
+ this->text += text;
}
}
diff --git a/Swiften/Parser/AuthResponseParser.h b/Swiften/Parser/AuthResponseParser.h
index 1846a41..6cbfa22 100644
--- a/Swiften/Parser/AuthResponseParser.h
+++ b/Swiften/Parser/AuthResponseParser.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API AuthResponseParser : public GenericElementParser<AuthResponse> {
- public:
- AuthResponseParser();
+ class SWIFTEN_API AuthResponseParser : public GenericElementParser<AuthResponse> {
+ public:
+ AuthResponseParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
- virtual void handleCharacterData(const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleCharacterData(const std::string&);
- private:
- int depth;
- std::string text;
- };
+ private:
+ int depth;
+ std::string text;
+ };
}
diff --git a/Swiften/Parser/AuthSuccessParser.cpp b/Swiften/Parser/AuthSuccessParser.cpp
index c50fab3..964fd6c 100644
--- a/Swiften/Parser/AuthSuccessParser.cpp
+++ b/Swiften/Parser/AuthSuccessParser.cpp
@@ -14,18 +14,18 @@ AuthSuccessParser::AuthSuccessParser() : GenericElementParser<AuthSuccess>(), de
}
void AuthSuccessParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++depth;
+ ++depth;
}
void AuthSuccessParser::handleEndElement(const std::string&, const std::string&) {
- --depth;
- if (depth == 0) {
- getElementGeneric()->setValue(Base64::decode(text));
- }
+ --depth;
+ if (depth == 0) {
+ getElementGeneric()->setValue(Base64::decode(text));
+ }
}
void AuthSuccessParser::handleCharacterData(const std::string& text) {
- this->text += text;
+ this->text += text;
}
}
diff --git a/Swiften/Parser/AuthSuccessParser.h b/Swiften/Parser/AuthSuccessParser.h
index a35f61e..cedc8d1 100644
--- a/Swiften/Parser/AuthSuccessParser.h
+++ b/Swiften/Parser/AuthSuccessParser.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API AuthSuccessParser : public GenericElementParser<AuthSuccess> {
- public:
- AuthSuccessParser();
+ class SWIFTEN_API AuthSuccessParser : public GenericElementParser<AuthSuccess> {
+ public:
+ AuthSuccessParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
- virtual void handleCharacterData(const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleCharacterData(const std::string&);
- private:
- int depth;
- std::string text;
- };
+ private:
+ int depth;
+ std::string text;
+ };
}
diff --git a/Swiften/Parser/BOSHBodyExtractor.cpp b/Swiften/Parser/BOSHBodyExtractor.cpp
index e0a37df..c5723be 100644
--- a/Swiften/Parser/BOSHBodyExtractor.cpp
+++ b/Swiften/Parser/BOSHBodyExtractor.cpp
@@ -16,124 +16,124 @@
namespace Swift {
class BOSHBodyParserClient : public XMLParserClient {
- public:
- BOSHBodyParserClient(BOSHBodyExtractor* bodyExtractor) : bodyExtractor(bodyExtractor) {
- }
+ public:
+ BOSHBodyParserClient(BOSHBodyExtractor* bodyExtractor) : bodyExtractor(bodyExtractor) {
+ }
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- bodyExtractor->body->attributes = attributes;
- }
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
+ bodyExtractor->body->attributes = attributes;
+ }
- virtual void handleEndElement(const std::string&, const std::string&) {
- }
+ virtual void handleEndElement(const std::string&, const std::string&) {
+ }
- virtual void handleCharacterData(const std::string&) {
- }
+ virtual void handleCharacterData(const std::string&) {
+ }
- private:
- BOSHBodyExtractor* bodyExtractor;
+ private:
+ BOSHBodyExtractor* bodyExtractor;
};
inline bool isWhitespace(unsigned char c) {
- return c == ' ' || c == '\n' || c == '\t' || c == '\r';
+ return c == ' ' || c == '\n' || c == '\t' || c == '\r';
}
BOSHBodyExtractor::BOSHBodyExtractor(XMLParserFactory* parserFactory, const ByteArray& data) {
- // Look for the opening body element
- ByteArray::const_iterator i = data.begin();
- while (i < data.end() && isWhitespace(*i)) {
- ++i;
- }
- if (std::distance(i, data.end()) < 6 || *i != '<' || *(i+1) != 'b' || *(i+2) != 'o' || *(i+3) != 'd' || *(i+4) != 'y' || !(isWhitespace(*(i+5)) || *(i+5) == '>' || *(i+5) == '/')) {
- return;
- }
- i += 5;
-
- // Parse until end of element
- bool inSingleQuote = false;
- bool inDoubleQuote = false;
- bool endStartTagSeen = false;
- bool endElementSeen = false;
- for (; i != data.end(); ++i) {
- char c = static_cast<char>(*i);
- if (inSingleQuote) {
- if (c == '\'') {
- inSingleQuote = false;
- }
- }
- else if (inDoubleQuote) {
- if (c == '"') {
- inDoubleQuote = false;
- }
- }
- else if (c == '\'') {
- inSingleQuote = true;
- }
- else if (c == '"') {
- inDoubleQuote = true;
- }
- else if (c == '/') {
- if (i + 1 == data.end() || *(i+1) != '>') {
- return;
- }
- else {
- endElementSeen = true;
- endStartTagSeen = true;
- i += 2;
- break;
- }
- }
- else if (c == '>') {
- endStartTagSeen = true;
- i += 1;
- break;
- }
- }
-
- if (!endStartTagSeen) {
- return;
- }
-
- // Look for the end of the element
- ByteArray::const_reverse_iterator j = data.rbegin();
- if (!endElementSeen) {
- while (isWhitespace(*j) && j < data.rend()) {
- ++j;
- }
-
- if (j == data.rend() || *j != '>') {
- return;
- }
- ++j;
-
- while (j < data.rend() && isWhitespace(*j)) {
- ++j;
- }
-
- if (std::distance(j, data.rend()) < 6 || *(j+5) != '<' || *(j+4) != '/' || *(j+3) != 'b' || *(j+2) != 'o' || *(j+1) != 'd' || *j != 'y') {
- return;
- }
- j += 6;
- }
-
- body = BOSHBody();
- if (!endElementSeen) {
- body->content = std::string(
- reinterpret_cast<const char*>(vecptr(data) + std::distance(data.begin(), i)),
- boost::numeric_cast<size_t>(std::distance(i, j.base())));
- }
-
- // Parse the body element
- BOSHBodyParserClient parserClient(this);
- boost::shared_ptr<XMLParser> parser(parserFactory->createXMLParser(&parserClient));
- if (!parser->parse(std::string(
- reinterpret_cast<const char*>(vecptr(data)),
- boost::numeric_cast<size_t>(std::distance(data.begin(), i))))) {
- /* TODO: This needs to be only validating the BOSH <body> element, so that XMPP parsing errors are caught at
- the correct higher layer */
- body = boost::optional<BOSHBody>();
- return;
- }
+ // Look for the opening body element
+ ByteArray::const_iterator i = data.begin();
+ while (i < data.end() && isWhitespace(*i)) {
+ ++i;
+ }
+ if (std::distance(i, data.end()) < 6 || *i != '<' || *(i+1) != 'b' || *(i+2) != 'o' || *(i+3) != 'd' || *(i+4) != 'y' || !(isWhitespace(*(i+5)) || *(i+5) == '>' || *(i+5) == '/')) {
+ return;
+ }
+ i += 5;
+
+ // Parse until end of element
+ bool inSingleQuote = false;
+ bool inDoubleQuote = false;
+ bool endStartTagSeen = false;
+ bool endElementSeen = false;
+ for (; i != data.end(); ++i) {
+ char c = static_cast<char>(*i);
+ if (inSingleQuote) {
+ if (c == '\'') {
+ inSingleQuote = false;
+ }
+ }
+ else if (inDoubleQuote) {
+ if (c == '"') {
+ inDoubleQuote = false;
+ }
+ }
+ else if (c == '\'') {
+ inSingleQuote = true;
+ }
+ else if (c == '"') {
+ inDoubleQuote = true;
+ }
+ else if (c == '/') {
+ if (i + 1 == data.end() || *(i+1) != '>') {
+ return;
+ }
+ else {
+ endElementSeen = true;
+ endStartTagSeen = true;
+ i += 2;
+ break;
+ }
+ }
+ else if (c == '>') {
+ endStartTagSeen = true;
+ i += 1;
+ break;
+ }
+ }
+
+ if (!endStartTagSeen) {
+ return;
+ }
+
+ // Look for the end of the element
+ ByteArray::const_reverse_iterator j = data.rbegin();
+ if (!endElementSeen) {
+ while (isWhitespace(*j) && j < data.rend()) {
+ ++j;
+ }
+
+ if (j == data.rend() || *j != '>') {
+ return;
+ }
+ ++j;
+
+ while (j < data.rend() && isWhitespace(*j)) {
+ ++j;
+ }
+
+ if (std::distance(j, data.rend()) < 6 || *(j+5) != '<' || *(j+4) != '/' || *(j+3) != 'b' || *(j+2) != 'o' || *(j+1) != 'd' || *j != 'y') {
+ return;
+ }
+ j += 6;
+ }
+
+ body = BOSHBody();
+ if (!endElementSeen) {
+ body->content = std::string(
+ reinterpret_cast<const char*>(vecptr(data) + std::distance(data.begin(), i)),
+ boost::numeric_cast<size_t>(std::distance(i, j.base())));
+ }
+
+ // Parse the body element
+ BOSHBodyParserClient parserClient(this);
+ boost::shared_ptr<XMLParser> parser(parserFactory->createXMLParser(&parserClient));
+ if (!parser->parse(std::string(
+ reinterpret_cast<const char*>(vecptr(data)),
+ boost::numeric_cast<size_t>(std::distance(data.begin(), i))))) {
+ /* TODO: This needs to be only validating the BOSH <body> element, so that XMPP parsing errors are caught at
+ the correct higher layer */
+ body = boost::optional<BOSHBody>();
+ return;
+ }
}
}
diff --git a/Swiften/Parser/BOSHBodyExtractor.h b/Swiften/Parser/BOSHBodyExtractor.h
index 2112ff7..ba56b41 100644
--- a/Swiften/Parser/BOSHBodyExtractor.h
+++ b/Swiften/Parser/BOSHBodyExtractor.h
@@ -13,23 +13,23 @@
#include <Swiften/Parser/XMLParserClient.h>
namespace Swift {
- class XMLParserFactory;
-
- class SWIFTEN_API BOSHBodyExtractor {
- friend class BOSHBodyParserClient;
- public:
- struct BOSHBody {
- AttributeMap attributes;
- std::string content;
- };
-
- BOSHBodyExtractor(XMLParserFactory* parserFactory, const ByteArray& data);
-
- const boost::optional<BOSHBody>& getBody() const {
- return body;
- }
-
- private:
- boost::optional<BOSHBody> body;
- };
+ class XMLParserFactory;
+
+ class SWIFTEN_API BOSHBodyExtractor {
+ friend class BOSHBodyParserClient;
+ public:
+ struct BOSHBody {
+ AttributeMap attributes;
+ std::string content;
+ };
+
+ BOSHBodyExtractor(XMLParserFactory* parserFactory, const ByteArray& data);
+
+ const boost::optional<BOSHBody>& getBody() const {
+ return body;
+ }
+
+ private:
+ boost::optional<BOSHBody> body;
+ };
}
diff --git a/Swiften/Parser/ComponentHandshakeParser.cpp b/Swiften/Parser/ComponentHandshakeParser.cpp
index 3899763..f98503d 100644
--- a/Swiften/Parser/ComponentHandshakeParser.cpp
+++ b/Swiften/Parser/ComponentHandshakeParser.cpp
@@ -14,18 +14,18 @@ ComponentHandshakeParser::ComponentHandshakeParser() : GenericElementParser<Comp
}
void ComponentHandshakeParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++depth;
+ ++depth;
}
void ComponentHandshakeParser::handleEndElement(const std::string&, const std::string&) {
- --depth;
- if (depth == 0) {
- getElementGeneric()->setData(text);
- }
+ --depth;
+ if (depth == 0) {
+ getElementGeneric()->setData(text);
+ }
}
void ComponentHandshakeParser::handleCharacterData(const std::string& text) {
- this->text += text;
+ this->text += text;
}
}
diff --git a/Swiften/Parser/ComponentHandshakeParser.h b/Swiften/Parser/ComponentHandshakeParser.h
index b9e4e76..5f4af80 100644
--- a/Swiften/Parser/ComponentHandshakeParser.h
+++ b/Swiften/Parser/ComponentHandshakeParser.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API ComponentHandshakeParser : public GenericElementParser<ComponentHandshake> {
- public:
- ComponentHandshakeParser();
+ class SWIFTEN_API ComponentHandshakeParser : public GenericElementParser<ComponentHandshake> {
+ public:
+ ComponentHandshakeParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
- virtual void handleCharacterData(const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleCharacterData(const std::string&);
- private:
- int depth;
- std::string text;
- };
+ private:
+ int depth;
+ std::string text;
+ };
}
diff --git a/Swiften/Parser/CompressFailureParser.h b/Swiften/Parser/CompressFailureParser.h
index cee6ade..5c171ee 100644
--- a/Swiften/Parser/CompressFailureParser.h
+++ b/Swiften/Parser/CompressFailureParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API CompressFailureParser : public GenericElementParser<CompressFailure> {
- public:
- CompressFailureParser() : GenericElementParser<CompressFailure>() {}
- };
+ class SWIFTEN_API CompressFailureParser : public GenericElementParser<CompressFailure> {
+ public:
+ CompressFailureParser() : GenericElementParser<CompressFailure>() {}
+ };
}
diff --git a/Swiften/Parser/CompressParser.cpp b/Swiften/Parser/CompressParser.cpp
index 1d69af6..00f762f 100644
--- a/Swiften/Parser/CompressParser.cpp
+++ b/Swiften/Parser/CompressParser.cpp
@@ -12,23 +12,23 @@ CompressParser::CompressParser() : GenericElementParser<CompressRequest>(), curr
}
void CompressParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
- if (currentDepth_ == 1 && element == "method") {
- inMethod_ = true;
- currentText_ = "";
- }
- ++currentDepth_;
+ if (currentDepth_ == 1 && element == "method") {
+ inMethod_ = true;
+ currentText_ = "";
+ }
+ ++currentDepth_;
}
void CompressParser::handleEndElement(const std::string&, const std::string&) {
- --currentDepth_;
- if (currentDepth_ == 1 && inMethod_) {
- getElementGeneric()->setMethod(currentText_);
- inMethod_ = false;
- }
+ --currentDepth_;
+ if (currentDepth_ == 1 && inMethod_) {
+ getElementGeneric()->setMethod(currentText_);
+ inMethod_ = false;
+ }
}
void CompressParser::handleCharacterData(const std::string& data) {
- currentText_ += data;
+ currentText_ += data;
}
}
diff --git a/Swiften/Parser/CompressParser.h b/Swiften/Parser/CompressParser.h
index 8a546dc..6f0a0cb 100644
--- a/Swiften/Parser/CompressParser.h
+++ b/Swiften/Parser/CompressParser.h
@@ -13,18 +13,18 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API CompressParser : public GenericElementParser<CompressRequest> {
- public:
- CompressParser();
+ class SWIFTEN_API CompressParser : public GenericElementParser<CompressRequest> {
+ public:
+ CompressParser();
- private:
- void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- void handleEndElement(const std::string& element, const std::string& ns);
- void handleCharacterData(const std::string& data);
+ private:
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
- private:
- int currentDepth_;
- std::string currentText_;
- bool inMethod_;
- };
+ private:
+ int currentDepth_;
+ std::string currentText_;
+ bool inMethod_;
+ };
}
diff --git a/Swiften/Parser/CompressedParser.h b/Swiften/Parser/CompressedParser.h
index a1cf4ea..859b509 100644
--- a/Swiften/Parser/CompressedParser.h
+++ b/Swiften/Parser/CompressedParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API CompressedParser : public GenericElementParser<Compressed> {
- public:
- CompressedParser() : GenericElementParser<Compressed>() {}
- };
+ class SWIFTEN_API CompressedParser : public GenericElementParser<Compressed> {
+ public:
+ CompressedParser() : GenericElementParser<Compressed>() {}
+ };
}
diff --git a/Swiften/Parser/ElementParser.h b/Swiften/Parser/ElementParser.h
index 7653276..12c6c38 100644
--- a/Swiften/Parser/ElementParser.h
+++ b/Swiften/Parser/ElementParser.h
@@ -15,14 +15,14 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
- class SWIFTEN_API ElementParser {
- public:
- virtual ~ElementParser();
+ class SWIFTEN_API ElementParser {
+ public:
+ virtual ~ElementParser();
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
- virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
- virtual void handleCharacterData(const std::string& data) = 0;
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
+ virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
+ virtual void handleCharacterData(const std::string& data) = 0;
- virtual boost::shared_ptr<ToplevelElement> getElement() const = 0;
- };
+ virtual boost::shared_ptr<ToplevelElement> getElement() const = 0;
+ };
}
diff --git a/Swiften/Parser/EnableStreamManagementParser.h b/Swiften/Parser/EnableStreamManagementParser.h
index 7fa8547..b010740 100644
--- a/Swiften/Parser/EnableStreamManagementParser.h
+++ b/Swiften/Parser/EnableStreamManagementParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API EnableStreamManagementParser : public GenericElementParser<EnableStreamManagement> {
- public:
- EnableStreamManagementParser() : GenericElementParser<EnableStreamManagement>() {}
- };
+ class SWIFTEN_API EnableStreamManagementParser : public GenericElementParser<EnableStreamManagement> {
+ public:
+ EnableStreamManagementParser() : GenericElementParser<EnableStreamManagement>() {}
+ };
}
diff --git a/Swiften/Parser/EnumParser.h b/Swiften/Parser/EnumParser.h
index b49d290..cf17ead 100644
--- a/Swiften/Parser/EnumParser.h
+++ b/Swiften/Parser/EnumParser.h
@@ -16,23 +16,23 @@
#include <Swiften/Base/Override.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API EnumParser {
- public:
- EnumParser() {
- }
-
- EnumParser& operator()(T value, const std::string& text) {
- values[text] = value;
- return *this;
- }
-
- boost::optional<T> parse(const std::string& value) {
- typename std::map<std::string, T>::const_iterator i = values.find(value);
- return i == values.end() ? boost::optional<T>() : i->second;
- }
-
- private:
- std::map<std::string, T> values;
- };
+ template<typename T>
+ class SWIFTEN_API EnumParser {
+ public:
+ EnumParser() {
+ }
+
+ EnumParser& operator()(T value, const std::string& text) {
+ values[text] = value;
+ return *this;
+ }
+
+ boost::optional<T> parse(const std::string& value) {
+ typename std::map<std::string, T>::const_iterator i = values.find(value);
+ return i == values.end() ? boost::optional<T>() : i->second;
+ }
+
+ private:
+ std::map<std::string, T> values;
+ };
}
diff --git a/Swiften/Parser/ExpatParser.cpp b/Swiften/Parser/ExpatParser.cpp
index 60ee81e..fba82e2 100644
--- a/Swiften/Parser/ExpatParser.cpp
+++ b/Swiften/Parser/ExpatParser.cpp
@@ -21,75 +21,75 @@ namespace Swift {
static const char NAMESPACE_SEPARATOR = '\x01';
struct ExpatParser::Private {
- XML_Parser parser_;
+ XML_Parser parser_;
};
static void handleStartElement(void* parser, const XML_Char* name, const XML_Char** attributes) {
- std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
- if (nsTagPair.second == "") {
- nsTagPair.second = nsTagPair.first;
- nsTagPair.first = "";
- }
- AttributeMap attributeValues;
- const XML_Char** currentAttribute = attributes;
- while (*currentAttribute) {
- std::pair<std::string,std::string> nsAttributePair = String::getSplittedAtFirst(*currentAttribute, NAMESPACE_SEPARATOR);
- if (nsAttributePair.second == "") {
- nsAttributePair.second = nsAttributePair.first;
- nsAttributePair.first = "";
- }
- attributeValues.addAttribute(nsAttributePair.second, nsAttributePair.first, std::string(*(currentAttribute+1)));
- currentAttribute += 2;
- }
-
- static_cast<XMLParser*>(parser)->getClient()->handleStartElement(nsTagPair.second, nsTagPair.first, attributeValues);
+ std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
+ if (nsTagPair.second == "") {
+ nsTagPair.second = nsTagPair.first;
+ nsTagPair.first = "";
+ }
+ AttributeMap attributeValues;
+ const XML_Char** currentAttribute = attributes;
+ while (*currentAttribute) {
+ std::pair<std::string,std::string> nsAttributePair = String::getSplittedAtFirst(*currentAttribute, NAMESPACE_SEPARATOR);
+ if (nsAttributePair.second == "") {
+ nsAttributePair.second = nsAttributePair.first;
+ nsAttributePair.first = "";
+ }
+ attributeValues.addAttribute(nsAttributePair.second, nsAttributePair.first, std::string(*(currentAttribute+1)));
+ currentAttribute += 2;
+ }
+
+ static_cast<XMLParser*>(parser)->getClient()->handleStartElement(nsTagPair.second, nsTagPair.first, attributeValues);
}
static void handleEndElement(void* parser, const XML_Char* name) {
- std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
- if (nsTagPair.second == "") {
- nsTagPair.second = nsTagPair.first;
- nsTagPair.first = "";
- }
- static_cast<XMLParser*>(parser)->getClient()->handleEndElement(nsTagPair.second, nsTagPair.first);
+ std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
+ if (nsTagPair.second == "") {
+ nsTagPair.second = nsTagPair.first;
+ nsTagPair.first = "";
+ }
+ static_cast<XMLParser*>(parser)->getClient()->handleEndElement(nsTagPair.second, nsTagPair.first);
}
static void handleCharacterData(void* parser, const XML_Char* data, int len) {
- assert(len >= 0);
- static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(data, static_cast<size_t>(len)));
+ assert(len >= 0);
+ static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(data, static_cast<size_t>(len)));
}
static void handleXMLDeclaration(void*, const XML_Char*, const XML_Char*, int) {
}
static void handleEntityDeclaration(void* parser, const XML_Char*, int, const XML_Char*, int, const XML_Char*, const XML_Char*, const XML_Char*, const XML_Char*) {
- static_cast<ExpatParser*>(parser)->stopParser();
+ static_cast<ExpatParser*>(parser)->stopParser();
}
ExpatParser::ExpatParser(XMLParserClient* client) : XMLParser(client), p(new Private()) {
- p->parser_ = XML_ParserCreateNS("UTF-8", NAMESPACE_SEPARATOR);
- XML_SetUserData(p->parser_, this);
- XML_SetElementHandler(p->parser_, handleStartElement, handleEndElement);
- XML_SetCharacterDataHandler(p->parser_, handleCharacterData);
- XML_SetXmlDeclHandler(p->parser_, handleXMLDeclaration);
- XML_SetEntityDeclHandler(p->parser_, handleEntityDeclaration);
+ p->parser_ = XML_ParserCreateNS("UTF-8", NAMESPACE_SEPARATOR);
+ XML_SetUserData(p->parser_, this);
+ XML_SetElementHandler(p->parser_, handleStartElement, handleEndElement);
+ XML_SetCharacterDataHandler(p->parser_, handleCharacterData);
+ XML_SetXmlDeclHandler(p->parser_, handleXMLDeclaration);
+ XML_SetEntityDeclHandler(p->parser_, handleEntityDeclaration);
}
ExpatParser::~ExpatParser() {
- XML_ParserFree(p->parser_);
+ XML_ParserFree(p->parser_);
}
bool ExpatParser::parse(const std::string& data) {
- bool success = XML_Parse(p->parser_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_STATUS_OK;
- /*if (!success) {
- std::cout << "ERROR: " << XML_ErrorString(XML_GetErrorCode(p->parser_)) << " while parsing " << data << std::endl;
- }*/
- return success;
+ bool success = XML_Parse(p->parser_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_STATUS_OK;
+ /*if (!success) {
+ std::cout << "ERROR: " << XML_ErrorString(XML_GetErrorCode(p->parser_)) << " while parsing " << data << std::endl;
+ }*/
+ return success;
}
void ExpatParser::stopParser() {
- XML_StopParser(p->parser_, static_cast<XML_Bool>(0));
+ XML_StopParser(p->parser_, static_cast<XML_Bool>(0));
}
}
diff --git a/Swiften/Parser/ExpatParser.h b/Swiften/Parser/ExpatParser.h
index c0c38c1..581847b 100644
--- a/Swiften/Parser/ExpatParser.h
+++ b/Swiften/Parser/ExpatParser.h
@@ -13,17 +13,17 @@
#include <Swiften/Parser/XMLParser.h>
namespace Swift {
- class SWIFTEN_API ExpatParser : public XMLParser, public boost::noncopyable {
- public:
- ExpatParser(XMLParserClient* client);
- ~ExpatParser();
+ class SWIFTEN_API ExpatParser : public XMLParser, public boost::noncopyable {
+ public:
+ ExpatParser(XMLParserClient* client);
+ ~ExpatParser();
- bool parse(const std::string& data);
+ bool parse(const std::string& data);
- void stopParser();
+ void stopParser();
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Parser/GenericElementParser.h b/Swiften/Parser/GenericElementParser.h
index 9cdec23..7a0f989 100644
--- a/Swiften/Parser/GenericElementParser.h
+++ b/Swiften/Parser/GenericElementParser.h
@@ -13,35 +13,35 @@
#include <Swiften/Parser/ElementParser.h>
namespace Swift {
-
- class PayloadParserFactoryCollection;
- template<typename ElementType>
- class SWIFTEN_API GenericElementParser : public ElementParser {
- public:
- GenericElementParser() {
- stanza_ = boost::make_shared<ElementType>();
- }
+ class PayloadParserFactoryCollection;
- virtual boost::shared_ptr<ToplevelElement> getElement() const {
- return stanza_;
- }
+ template<typename ElementType>
+ class SWIFTEN_API GenericElementParser : public ElementParser {
+ public:
+ GenericElementParser() {
+ stanza_ = boost::make_shared<ElementType>();
+ }
- virtual boost::shared_ptr<ElementType> getElementGeneric() const {
- return stanza_;
- }
+ virtual boost::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
- private:
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- }
+ virtual boost::shared_ptr<ElementType> getElementGeneric() const {
+ return stanza_;
+ }
- virtual void handleEndElement(const std::string&, const std::string&) {
- }
+ private:
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
+ }
- virtual void handleCharacterData(const std::string&) {
- }
+ virtual void handleEndElement(const std::string&, const std::string&) {
+ }
- private:
- boost::shared_ptr<ElementType> stanza_;
- };
+ virtual void handleCharacterData(const std::string&) {
+ }
+
+ private:
+ boost::shared_ptr<ElementType> stanza_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadParser.h b/Swiften/Parser/GenericPayloadParser.h
index b6cd2d7..be0172c 100644
--- a/Swiften/Parser/GenericPayloadParser.h
+++ b/Swiften/Parser/GenericPayloadParser.h
@@ -13,31 +13,31 @@
#include <Swiften/Parser/PayloadParser.h>
namespace Swift {
-
- class FormParser;
-
- /**
- * A generic payload parser for payloads of the given type.
- *
- * This class provides getPayloadInternal() for retrieving the actual
- * payload.
- */
- template<typename PAYLOAD_TYPE>
- class GenericPayloadParser : public PayloadParser {
- public:
- GenericPayloadParser() : PayloadParser() {
- payload_ = boost::make_shared<PAYLOAD_TYPE>();
- }
-
- virtual boost::shared_ptr<Payload> getPayload() const {
- return payload_;
- }
-
- virtual boost::shared_ptr<PAYLOAD_TYPE> getPayloadInternal() const {
- return payload_;
- }
-
- private:
- boost::shared_ptr<PAYLOAD_TYPE> payload_;
- };
+
+ class FormParser;
+
+ /**
+ * A generic payload parser for payloads of the given type.
+ *
+ * This class provides getPayloadInternal() for retrieving the actual
+ * payload.
+ */
+ template<typename PAYLOAD_TYPE>
+ class GenericPayloadParser : public PayloadParser {
+ public:
+ GenericPayloadParser() : PayloadParser() {
+ payload_ = boost::make_shared<PAYLOAD_TYPE>();
+ }
+
+ virtual boost::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ virtual boost::shared_ptr<PAYLOAD_TYPE> getPayloadInternal() const {
+ return payload_;
+ }
+
+ private:
+ boost::shared_ptr<PAYLOAD_TYPE> payload_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadParserFactory.h b/Swiften/Parser/GenericPayloadParserFactory.h
index c980073..fcdec62 100644
--- a/Swiften/Parser/GenericPayloadParserFactory.h
+++ b/Swiften/Parser/GenericPayloadParserFactory.h
@@ -13,27 +13,27 @@
namespace Swift {
- /**
- * A generic class for PayloadParserFactories that parse a specific payload (given as the template parameter of the class).
- */
- template<typename PARSER_TYPE>
- class GenericPayloadParserFactory : public PayloadParserFactory {
- public:
- /**
- * Construct a parser factory that can parse the given top-level tag in the given namespace.
- */
- GenericPayloadParserFactory(const std::string& tag, const std::string& xmlns = "") : tag_(tag), xmlns_(xmlns) {}
-
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return (tag_.empty() ? true : element == tag_) && (xmlns_.empty() ? true : xmlns_ == ns);
- }
-
- virtual PayloadParser* createPayloadParser() {
- return new PARSER_TYPE();
- }
-
- private:
- std::string tag_;
- std::string xmlns_;
- };
+ /**
+ * A generic class for PayloadParserFactories that parse a specific payload (given as the template parameter of the class).
+ */
+ template<typename PARSER_TYPE>
+ class GenericPayloadParserFactory : public PayloadParserFactory {
+ public:
+ /**
+ * Construct a parser factory that can parse the given top-level tag in the given namespace.
+ */
+ GenericPayloadParserFactory(const std::string& tag, const std::string& xmlns = "") : tag_(tag), xmlns_(xmlns) {}
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return (tag_.empty() ? true : element == tag_) && (xmlns_.empty() ? true : xmlns_ == ns);
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new PARSER_TYPE();
+ }
+
+ private:
+ std::string tag_;
+ std::string xmlns_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadParserFactory2.h b/Swiften/Parser/GenericPayloadParserFactory2.h
index 7591897..f55d317 100644
--- a/Swiften/Parser/GenericPayloadParserFactory2.h
+++ b/Swiften/Parser/GenericPayloadParserFactory2.h
@@ -12,30 +12,30 @@
#include <Swiften/Parser/PayloadParserFactory.h>
namespace Swift {
- class PayloadParserFactoryCollection;
-
- /**
- * A generic class for PayloadParserFactories that parse a specific payload (given as the template parameter of the class).
- */
- template<typename PARSER_TYPE>
- class GenericPayloadParserFactory2 : public PayloadParserFactory {
- public:
- /**
- * Construct a parser factory that can parse the given top-level tag in the given namespace.
- */
- GenericPayloadParserFactory2(const std::string& tag, const std::string& xmlns, PayloadParserFactoryCollection* parsers) : tag_(tag), xmlns_(xmlns), parsers_(parsers) {}
-
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return (tag_.empty() ? true : element == tag_) && (xmlns_.empty() ? true : xmlns_ == ns);
- }
-
- virtual PayloadParser* createPayloadParser() {
- return new PARSER_TYPE(parsers_);
- }
-
- private:
- std::string tag_;
- std::string xmlns_;
- PayloadParserFactoryCollection* parsers_;
- };
+ class PayloadParserFactoryCollection;
+
+ /**
+ * A generic class for PayloadParserFactories that parse a specific payload (given as the template parameter of the class).
+ */
+ template<typename PARSER_TYPE>
+ class GenericPayloadParserFactory2 : public PayloadParserFactory {
+ public:
+ /**
+ * Construct a parser factory that can parse the given top-level tag in the given namespace.
+ */
+ GenericPayloadParserFactory2(const std::string& tag, const std::string& xmlns, PayloadParserFactoryCollection* parsers) : tag_(tag), xmlns_(xmlns), parsers_(parsers) {}
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return (tag_.empty() ? true : element == tag_) && (xmlns_.empty() ? true : xmlns_ == ns);
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new PARSER_TYPE(parsers_);
+ }
+
+ private:
+ std::string tag_;
+ std::string xmlns_;
+ PayloadParserFactoryCollection* parsers_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadTreeParser.h b/Swiften/Parser/GenericPayloadTreeParser.h
index 37505ac..2a7e190 100644
--- a/Swiften/Parser/GenericPayloadTreeParser.h
+++ b/Swiften/Parser/GenericPayloadTreeParser.h
@@ -16,39 +16,39 @@
#include <Swiften/Parser/Tree/ParserElement.h>
namespace Swift {
- /**
- * Generic parser offering something a bit like a DOM to work with.
- */
- template<typename PAYLOAD_TYPE>
- class GenericPayloadTreeParser : public GenericPayloadParser<PAYLOAD_TYPE> {
- public:
- virtual void handleStartElement(const std::string& element, const std::string& xmlns, const AttributeMap& attributes) {
- if (!root_) {
- root_ = boost::make_shared<ParserElement>(element, xmlns, attributes);
- elementStack_.push_back(root_);
- }
- else {
- ParserElement::ref current = *elementStack_.rbegin();
- elementStack_.push_back(current->addChild(element, xmlns, attributes));
- }
- }
-
- virtual void handleEndElement(const std::string& /*element*/, const std::string&) {
- elementStack_.pop_back();
- if (elementStack_.empty()) {
- handleTree(root_);
- }
- }
-
- virtual void handleCharacterData(const std::string& data) {
- ParserElement::ref current = *elementStack_.rbegin();
- current->appendCharacterData(data);
- }
-
- virtual void handleTree(ParserElement::ref root) = 0;
-
- private:
- std::deque<ParserElement::ref> elementStack_;
- ParserElement::ref root_;
- };
+ /**
+ * Generic parser offering something a bit like a DOM to work with.
+ */
+ template<typename PAYLOAD_TYPE>
+ class GenericPayloadTreeParser : public GenericPayloadParser<PAYLOAD_TYPE> {
+ public:
+ virtual void handleStartElement(const std::string& element, const std::string& xmlns, const AttributeMap& attributes) {
+ if (!root_) {
+ root_ = boost::make_shared<ParserElement>(element, xmlns, attributes);
+ elementStack_.push_back(root_);
+ }
+ else {
+ ParserElement::ref current = *elementStack_.rbegin();
+ elementStack_.push_back(current->addChild(element, xmlns, attributes));
+ }
+ }
+
+ virtual void handleEndElement(const std::string& /*element*/, const std::string&) {
+ elementStack_.pop_back();
+ if (elementStack_.empty()) {
+ handleTree(root_);
+ }
+ }
+
+ virtual void handleCharacterData(const std::string& data) {
+ ParserElement::ref current = *elementStack_.rbegin();
+ current->appendCharacterData(data);
+ }
+
+ virtual void handleTree(ParserElement::ref root) = 0;
+
+ private:
+ std::deque<ParserElement::ref> elementStack_;
+ ParserElement::ref root_;
+ };
}
diff --git a/Swiften/Parser/GenericStanzaParser.h b/Swiften/Parser/GenericStanzaParser.h
index c9d7f70..7d16a0c 100644
--- a/Swiften/Parser/GenericStanzaParser.h
+++ b/Swiften/Parser/GenericStanzaParser.h
@@ -13,26 +13,26 @@
#include <Swiften/Parser/StanzaParser.h>
namespace Swift {
-
- class PayloadParserFactoryCollection;
-
- template<typename STANZA_TYPE>
- class SWIFTEN_API GenericStanzaParser : public StanzaParser {
- public:
- GenericStanzaParser(PayloadParserFactoryCollection* collection) :
- StanzaParser(collection) {
- stanza_ = boost::make_shared<STANZA_TYPE>();
- }
-
- virtual boost::shared_ptr<ToplevelElement> getElement() const {
- return stanza_;
- }
-
- virtual boost::shared_ptr<STANZA_TYPE> getStanzaGeneric() const {
- return stanza_;
- }
-
- private:
- boost::shared_ptr<STANZA_TYPE> stanza_;
- };
+
+ class PayloadParserFactoryCollection;
+
+ template<typename STANZA_TYPE>
+ class SWIFTEN_API GenericStanzaParser : public StanzaParser {
+ public:
+ GenericStanzaParser(PayloadParserFactoryCollection* collection) :
+ StanzaParser(collection) {
+ stanza_ = boost::make_shared<STANZA_TYPE>();
+ }
+
+ virtual boost::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
+
+ virtual boost::shared_ptr<STANZA_TYPE> getStanzaGeneric() const {
+ return stanza_;
+ }
+
+ private:
+ boost::shared_ptr<STANZA_TYPE> stanza_;
+ };
}
diff --git a/Swiften/Parser/IQParser.cpp b/Swiften/Parser/IQParser.cpp
index ee8f2ff..573ce07 100644
--- a/Swiften/Parser/IQParser.cpp
+++ b/Swiften/Parser/IQParser.cpp
@@ -12,30 +12,30 @@
namespace Swift {
-IQParser::IQParser(PayloadParserFactoryCollection* factories) :
- GenericStanzaParser<IQ>(factories) {
+IQParser::IQParser(PayloadParserFactoryCollection* factories) :
+ GenericStanzaParser<IQ>(factories) {
}
void IQParser::handleStanzaAttributes(const AttributeMap& attributes) {
- boost::optional<std::string> type = attributes.getAttributeValue("type");
- if (type) {
- if (*type == "set") {
- getStanzaGeneric()->setType(IQ::Set);
- }
- else if (*type == "get") {
- getStanzaGeneric()->setType(IQ::Get);
- }
- else if (*type == "result") {
- getStanzaGeneric()->setType(IQ::Result);
- }
- else if (*type == "error") {
- getStanzaGeneric()->setType(IQ::Error);
- }
- else {
- std::cerr << "Unknown IQ type: " << *type << std::endl;
- getStanzaGeneric()->setType(IQ::Get);
- }
- }
+ boost::optional<std::string> type = attributes.getAttributeValue("type");
+ if (type) {
+ if (*type == "set") {
+ getStanzaGeneric()->setType(IQ::Set);
+ }
+ else if (*type == "get") {
+ getStanzaGeneric()->setType(IQ::Get);
+ }
+ else if (*type == "result") {
+ getStanzaGeneric()->setType(IQ::Result);
+ }
+ else if (*type == "error") {
+ getStanzaGeneric()->setType(IQ::Error);
+ }
+ else {
+ std::cerr << "Unknown IQ type: " << *type << std::endl;
+ getStanzaGeneric()->setType(IQ::Get);
+ }
+ }
}
}
diff --git a/Swiften/Parser/IQParser.h b/Swiften/Parser/IQParser.h
index fa1f66e..5250bfb 100644
--- a/Swiften/Parser/IQParser.h
+++ b/Swiften/Parser/IQParser.h
@@ -11,11 +11,11 @@
#include <Swiften/Parser/GenericStanzaParser.h>
namespace Swift {
- class SWIFTEN_API IQParser : public GenericStanzaParser<IQ> {
- public:
- IQParser(PayloadParserFactoryCollection* factories);
+ class SWIFTEN_API IQParser : public GenericStanzaParser<IQ> {
+ public:
+ IQParser(PayloadParserFactoryCollection* factories);
- private:
- virtual void handleStanzaAttributes(const AttributeMap&);
- };
+ private:
+ virtual void handleStanzaAttributes(const AttributeMap&);
+ };
}
diff --git a/Swiften/Parser/LibXMLParser.cpp b/Swiften/Parser/LibXMLParser.cpp
index db14174..62484fa 100644
--- a/Swiften/Parser/LibXMLParser.cpp
+++ b/Swiften/Parser/LibXMLParser.cpp
@@ -20,45 +20,45 @@
namespace Swift {
struct LibXMLParser::Private {
- xmlSAXHandler handler_;
- xmlParserCtxtPtr context_;
+ xmlSAXHandler handler_;
+ xmlParserCtxtPtr context_;
};
static void handleStartElement(void* parser, const xmlChar* name, const xmlChar*, const xmlChar* xmlns, int, const xmlChar**, int nbAttributes, int nbDefaulted, const xmlChar ** attributes) {
- AttributeMap attributeValues;
- if (nbDefaulted != 0) {
- // Just because i don't understand what this means yet :-)
- std::cerr << "Unexpected nbDefaulted on XML element" << std::endl;
- }
- for (int i = 0; i < nbAttributes*5; i += 5) {
- std::string attributeNS = "";
- if (attributes[i+2]) {
- attributeNS = std::string(reinterpret_cast<const char*>(attributes[i+2]));
- }
- attributeValues.addAttribute(
- std::string(reinterpret_cast<const char*>(attributes[i])),
- attributeNS,
- std::string(reinterpret_cast<const char*>(attributes[i+3]),
- boost::numeric_cast<size_t>(attributes[i+4]-attributes[i+3])));
- }
- static_cast<XMLParser*>(parser)->getClient()->handleStartElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()), attributeValues);
+ AttributeMap attributeValues;
+ if (nbDefaulted != 0) {
+ // Just because i don't understand what this means yet :-)
+ std::cerr << "Unexpected nbDefaulted on XML element" << std::endl;
+ }
+ for (int i = 0; i < nbAttributes*5; i += 5) {
+ std::string attributeNS = "";
+ if (attributes[i+2]) {
+ attributeNS = std::string(reinterpret_cast<const char*>(attributes[i+2]));
+ }
+ attributeValues.addAttribute(
+ std::string(reinterpret_cast<const char*>(attributes[i])),
+ attributeNS,
+ std::string(reinterpret_cast<const char*>(attributes[i+3]),
+ boost::numeric_cast<size_t>(attributes[i+4]-attributes[i+3])));
+ }
+ static_cast<XMLParser*>(parser)->getClient()->handleStartElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()), attributeValues);
}
static void handleEndElement(void *parser, const xmlChar* name, const xmlChar*, const xmlChar* xmlns) {
- static_cast<XMLParser*>(parser)->getClient()->handleEndElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()));
+ static_cast<XMLParser*>(parser)->getClient()->handleEndElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()));
}
static void handleCharacterData(void* parser, const xmlChar* data, int len) {
- static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), boost::numeric_cast<size_t>(len)));
+ static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), boost::numeric_cast<size_t>(len)));
}
static void handleError(void*, const char* /*m*/, ... ) {
- /*
- va_list args;
- va_start(args, m);
- vfprintf(stdout, m, args);
- va_end(args);
- */
+ /*
+ va_list args;
+ va_start(args, m);
+ vfprintf(stdout, m, args);
+ va_end(args);
+ */
}
static void handleWarning(void*, const char*, ... ) {
@@ -67,42 +67,42 @@ static void handleWarning(void*, const char*, ... ) {
bool LibXMLParser::initialized = false;
LibXMLParser::LibXMLParser(XMLParserClient* client) : XMLParser(client), p(new Private()) {
- // Initialize libXML for multithreaded applications
- if (!initialized) {
- xmlInitParser();
- initialized = true;
- }
-
- memset(&p->handler_, 0, sizeof(p->handler_) );
- p->handler_.initialized = XML_SAX2_MAGIC;
- p->handler_.startElementNs = &handleStartElement;
- p->handler_.endElementNs = &handleEndElement;
- p->handler_.characters = &handleCharacterData;
- p->handler_.warning = &handleWarning;
- p->handler_.error = &handleError;
-
- p->context_ = xmlCreatePushParserCtxt(&p->handler_, this, 0, 0, 0);
- xmlCtxtUseOptions(p->context_, XML_PARSE_NOENT);
- assert(p->context_);
+ // Initialize libXML for multithreaded applications
+ if (!initialized) {
+ xmlInitParser();
+ initialized = true;
+ }
+
+ memset(&p->handler_, 0, sizeof(p->handler_) );
+ p->handler_.initialized = XML_SAX2_MAGIC;
+ p->handler_.startElementNs = &handleStartElement;
+ p->handler_.endElementNs = &handleEndElement;
+ p->handler_.characters = &handleCharacterData;
+ p->handler_.warning = &handleWarning;
+ p->handler_.error = &handleError;
+
+ p->context_ = xmlCreatePushParserCtxt(&p->handler_, this, 0, 0, 0);
+ xmlCtxtUseOptions(p->context_, XML_PARSE_NOENT);
+ assert(p->context_);
}
LibXMLParser::~LibXMLParser() {
- if (p->context_) {
- xmlFreeParserCtxt(p->context_);
- }
+ if (p->context_) {
+ xmlFreeParserCtxt(p->context_);
+ }
}
bool LibXMLParser::parse(const std::string& data) {
- if (xmlParseChunk(p->context_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_ERR_OK) {
- return true;
- }
- xmlError* error = xmlCtxtGetLastError(p->context_);
- if (error->code == XML_WAR_NS_URI || error->code == XML_WAR_NS_URI_RELATIVE) {
- xmlCtxtResetLastError(p->context_);
- p->context_->errNo = XML_ERR_OK;
- return true;
- }
- return false;
+ if (xmlParseChunk(p->context_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_ERR_OK) {
+ return true;
+ }
+ xmlError* error = xmlCtxtGetLastError(p->context_);
+ if (error->code == XML_WAR_NS_URI || error->code == XML_WAR_NS_URI_RELATIVE) {
+ xmlCtxtResetLastError(p->context_);
+ p->context_->errNo = XML_ERR_OK;
+ return true;
+ }
+ return false;
}
}
diff --git a/Swiften/Parser/LibXMLParser.h b/Swiften/Parser/LibXMLParser.h
index c247548..eb2a038 100644
--- a/Swiften/Parser/LibXMLParser.h
+++ b/Swiften/Parser/LibXMLParser.h
@@ -12,21 +12,21 @@
#include <Swiften/Parser/XMLParser.h>
namespace Swift {
- /**
- * Warning: This constructor is not thread-safe, because it depends on global state to
- * check whether it is initialized.
- */
- class LibXMLParser : public XMLParser, public boost::noncopyable {
- public:
- LibXMLParser(XMLParserClient* client);
- virtual ~LibXMLParser();
+ /**
+ * Warning: This constructor is not thread-safe, because it depends on global state to
+ * check whether it is initialized.
+ */
+ class LibXMLParser : public XMLParser, public boost::noncopyable {
+ public:
+ LibXMLParser(XMLParserClient* client);
+ virtual ~LibXMLParser();
- bool parse(const std::string& data);
+ bool parse(const std::string& data);
- private:
- static bool initialized;
+ private:
+ static bool initialized;
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ struct Private;
+ boost::shared_ptr<Private> p;
+ };
}
diff --git a/Swiften/Parser/MessageParser.cpp b/Swiften/Parser/MessageParser.cpp
index 5de0038..1dd7675 100644
--- a/Swiften/Parser/MessageParser.cpp
+++ b/Swiften/Parser/MessageParser.cpp
@@ -10,30 +10,30 @@
namespace Swift {
-MessageParser::MessageParser(PayloadParserFactoryCollection* factories) :
- GenericStanzaParser<Message>(factories) {
- GenericStanzaParser<Message>::getStanzaGeneric()->setType(Message::Normal);
+MessageParser::MessageParser(PayloadParserFactoryCollection* factories) :
+ GenericStanzaParser<Message>(factories) {
+ GenericStanzaParser<Message>::getStanzaGeneric()->setType(Message::Normal);
}
void MessageParser::handleStanzaAttributes(const AttributeMap& attributes) {
- boost::optional<std::string> type = attributes.getAttributeValue("type");
- if (type) {
- if (*type == "chat") {
- getStanzaGeneric()->setType(Message::Chat);
- }
- else if (*type == "error") {
- getStanzaGeneric()->setType(Message::Error);
- }
- else if (*type == "groupchat") {
- getStanzaGeneric()->setType(Message::Groupchat);
- }
- else if (*type == "headline") {
- getStanzaGeneric()->setType(Message::Headline);
- }
- else {
- getStanzaGeneric()->setType(Message::Normal);
- }
- }
+ boost::optional<std::string> type = attributes.getAttributeValue("type");
+ if (type) {
+ if (*type == "chat") {
+ getStanzaGeneric()->setType(Message::Chat);
+ }
+ else if (*type == "error") {
+ getStanzaGeneric()->setType(Message::Error);
+ }
+ else if (*type == "groupchat") {
+ getStanzaGeneric()->setType(Message::Groupchat);
+ }
+ else if (*type == "headline") {
+ getStanzaGeneric()->setType(Message::Headline);
+ }
+ else {
+ getStanzaGeneric()->setType(Message::Normal);
+ }
+ }
}
}
diff --git a/Swiften/Parser/MessageParser.h b/Swiften/Parser/MessageParser.h
index 05e8b20..cfbfc38 100644
--- a/Swiften/Parser/MessageParser.h
+++ b/Swiften/Parser/MessageParser.h
@@ -11,11 +11,11 @@
#include <Swiften/Parser/GenericStanzaParser.h>
namespace Swift {
- class SWIFTEN_API MessageParser : public GenericStanzaParser<Message> {
- public:
- MessageParser(PayloadParserFactoryCollection* factories);
+ class SWIFTEN_API MessageParser : public GenericStanzaParser<Message> {
+ public:
+ MessageParser(PayloadParserFactoryCollection* factories);
- private:
- virtual void handleStanzaAttributes(const AttributeMap&);
- };
+ private:
+ virtual void handleStanzaAttributes(const AttributeMap&);
+ };
}
diff --git a/Swiften/Parser/PayloadParser.h b/Swiften/Parser/PayloadParser.h
index 815d246..cb50061 100644
--- a/Swiften/Parser/PayloadParser.h
+++ b/Swiften/Parser/PayloadParser.h
@@ -13,38 +13,38 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
-
-
- /**
- * A parser for XMPP stanza payloads.
- *
- * The parser is event driven: handleStartElement, handleEndElement, and handleCharacterData will be called
- * when the parser detects start and end of XML elements, or character data.
- * After the data for the given top-level element is processed, getPayload() will be called to retrieve the
- * payload.
- */
- class SWIFTEN_API PayloadParser {
- public:
- virtual ~PayloadParser();
-
- /**
- * Handle the start of an XML element.
- */
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
-
- /**
- * Handle the end of an XML element.
- */
- virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
-
- /**
- * Handle character data.
- */
- virtual void handleCharacterData(const std::string& data) = 0;
-
- /**
- * Retrieve a pointer to the payload.
- */
- virtual boost::shared_ptr<Payload> getPayload() const = 0;
- };
+
+
+ /**
+ * A parser for XMPP stanza payloads.
+ *
+ * The parser is event driven: handleStartElement, handleEndElement, and handleCharacterData will be called
+ * when the parser detects start and end of XML elements, or character data.
+ * After the data for the given top-level element is processed, getPayload() will be called to retrieve the
+ * payload.
+ */
+ class SWIFTEN_API PayloadParser {
+ public:
+ virtual ~PayloadParser();
+
+ /**
+ * Handle the start of an XML element.
+ */
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
+
+ /**
+ * Handle the end of an XML element.
+ */
+ virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
+
+ /**
+ * Handle character data.
+ */
+ virtual void handleCharacterData(const std::string& data) = 0;
+
+ /**
+ * Retrieve a pointer to the payload.
+ */
+ virtual boost::shared_ptr<Payload> getPayload() const = 0;
+ };
}
diff --git a/Swiften/Parser/PayloadParserFactory.h b/Swiften/Parser/PayloadParserFactory.h
index a73d50d..84f11ff 100644
--- a/Swiften/Parser/PayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParserFactory.h
@@ -10,24 +10,24 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
-
- class PayloadParser;
- /**
- * A factory for PayloadParsers.
- */
- class SWIFTEN_API PayloadParserFactory {
- public:
- virtual ~PayloadParserFactory();
+ class PayloadParser;
- /**
- * Checks whether this factory can parse the given top-level element in the given namespace (with the given attributes).
- */
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap& attributes) const = 0;
+ /**
+ * A factory for PayloadParsers.
+ */
+ class SWIFTEN_API PayloadParserFactory {
+ public:
+ virtual ~PayloadParserFactory();
- /**
- * Creates a new payload parser.
- */
- virtual PayloadParser* createPayloadParser() = 0;
- };
+ /**
+ * Checks whether this factory can parse the given top-level element in the given namespace (with the given attributes).
+ */
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap& attributes) const = 0;
+
+ /**
+ * Creates a new payload parser.
+ */
+ virtual PayloadParser* createPayloadParser() = 0;
+ };
}
diff --git a/Swiften/Parser/PayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParserFactoryCollection.cpp
index 6b86305..f1c1c03 100644
--- a/Swiften/Parser/PayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParserFactoryCollection.cpp
@@ -18,22 +18,22 @@ PayloadParserFactoryCollection::PayloadParserFactoryCollection() : defaultFactor
}
void PayloadParserFactoryCollection::addFactory(PayloadParserFactory* factory) {
- factories_.push_back(factory);
+ factories_.push_back(factory);
}
void PayloadParserFactoryCollection::removeFactory(PayloadParserFactory* factory) {
- factories_.erase(std::remove(factories_.begin(), factories_.end(), factory), factories_.end());
+ factories_.erase(std::remove(factories_.begin(), factories_.end(), factory), factories_.end());
}
void PayloadParserFactoryCollection::setDefaultFactory(PayloadParserFactory* factory) {
- defaultFactory_ = factory;
+ defaultFactory_ = factory;
}
PayloadParserFactory* PayloadParserFactoryCollection::getPayloadParserFactory(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- std::vector<PayloadParserFactory*>::reverse_iterator i = std::find_if(
- factories_.rbegin(), factories_.rend(),
- boost::bind(&PayloadParserFactory::canParse, _1, element, ns, attributes));
- return (i != factories_.rend() ? *i : defaultFactory_);
+ std::vector<PayloadParserFactory*>::reverse_iterator i = std::find_if(
+ factories_.rbegin(), factories_.rend(),
+ boost::bind(&PayloadParserFactory::canParse, _1, element, ns, attributes));
+ return (i != factories_.rend() ? *i : defaultFactory_);
}
}
diff --git a/Swiften/Parser/PayloadParserFactoryCollection.h b/Swiften/Parser/PayloadParserFactoryCollection.h
index 757b4e7..06e334e 100644
--- a/Swiften/Parser/PayloadParserFactoryCollection.h
+++ b/Swiften/Parser/PayloadParserFactoryCollection.h
@@ -12,20 +12,20 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
- class PayloadParserFactory;
+ class PayloadParserFactory;
- class SWIFTEN_API PayloadParserFactoryCollection {
- public:
- PayloadParserFactoryCollection();
+ class SWIFTEN_API PayloadParserFactoryCollection {
+ public:
+ PayloadParserFactoryCollection();
- void addFactory(PayloadParserFactory* factory);
- void removeFactory(PayloadParserFactory* factory);
- void setDefaultFactory(PayloadParserFactory* factory);
+ void addFactory(PayloadParserFactory* factory);
+ void removeFactory(PayloadParserFactory* factory);
+ void setDefaultFactory(PayloadParserFactory* factory);
- PayloadParserFactory* getPayloadParserFactory(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ PayloadParserFactory* getPayloadParserFactory(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- private:
- std::vector<PayloadParserFactory*> factories_;
- PayloadParserFactory* defaultFactory_;
- };
+ private:
+ std::vector<PayloadParserFactory*> factories_;
+ PayloadParserFactory* defaultFactory_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/BlockParser.h b/Swiften/Parser/PayloadParsers/BlockParser.h
index 2e615a5..1724feb 100644
--- a/Swiften/Parser/PayloadParsers/BlockParser.h
+++ b/Swiften/Parser/PayloadParsers/BlockParser.h
@@ -12,30 +12,30 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- template<typename BLOCK_ELEMENT>
- class SWIFTEN_API BlockParser : public GenericPayloadParser<BLOCK_ELEMENT> {
- public:
- BlockParser() : GenericPayloadParser<BLOCK_ELEMENT>(), level(0) {
- }
+ template<typename BLOCK_ELEMENT>
+ class SWIFTEN_API BlockParser : public GenericPayloadParser<BLOCK_ELEMENT> {
+ public:
+ BlockParser() : GenericPayloadParser<BLOCK_ELEMENT>(), level(0) {
+ }
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level == 1 && element == "item") {
- JID jid(attributes.getAttribute("jid"));
- if (jid.isValid()) {
- GenericPayloadParser<BLOCK_ELEMENT>::getPayloadInternal()->addItem(jid);
- }
- }
- ++level;
- }
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (level == 1 && element == "item") {
+ JID jid(attributes.getAttribute("jid"));
+ if (jid.isValid()) {
+ GenericPayloadParser<BLOCK_ELEMENT>::getPayloadInternal()->addItem(jid);
+ }
+ }
+ ++level;
+ }
- virtual void handleEndElement(const std::string&, const std::string&) {
- --level;
- }
+ virtual void handleEndElement(const std::string&, const std::string&) {
+ --level;
+ }
- virtual void handleCharacterData(const std::string&) {
- }
+ virtual void handleCharacterData(const std::string&) {
+ }
- private:
- int level;
- };
+ private:
+ int level;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/BodyParser.cpp b/Swiften/Parser/PayloadParsers/BodyParser.cpp
index 96a7b18..5741c90 100644
--- a/Swiften/Parser/PayloadParsers/BodyParser.cpp
+++ b/Swiften/Parser/PayloadParsers/BodyParser.cpp
@@ -12,18 +12,18 @@ BodyParser::BodyParser() : level_(0) {
}
void BodyParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void BodyParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setText(text_);
- }
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setText(text_);
+ }
}
void BodyParser::handleCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/BodyParser.h b/Swiften/Parser/PayloadParsers/BodyParser.h
index 6b6a206..bcf762b 100644
--- a/Swiften/Parser/PayloadParsers/BodyParser.h
+++ b/Swiften/Parser/PayloadParsers/BodyParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API BodyParser : public GenericPayloadParser<Body> {
- public:
- BodyParser();
+ class SWIFTEN_API BodyParser : public GenericPayloadParser<Body> {
+ public:
+ BodyParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
index 35ee1fd..8a0ecd2 100644
--- a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
@@ -19,26 +19,26 @@ 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;
+ 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;
+ --level;
}
void BytestreamsParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/BytestreamsParser.h b/Swiften/Parser/PayloadParsers/BytestreamsParser.h
index 4180ff9..01cb60f 100644
--- a/Swiften/Parser/PayloadParsers/BytestreamsParser.h
+++ b/Swiften/Parser/PayloadParsers/BytestreamsParser.h
@@ -13,20 +13,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API BytestreamsParser : public GenericPayloadParser<Bytestreams> {
- public:
- BytestreamsParser();
- ~BytestreamsParser();
+ class SWIFTEN_API BytestreamsParser : public GenericPayloadParser<Bytestreams> {
+ public:
+ BytestreamsParser();
+ ~BytestreamsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CapsInfoParser.cpp b/Swiften/Parser/PayloadParsers/CapsInfoParser.cpp
index 7843c78..546df57 100644
--- a/Swiften/Parser/PayloadParsers/CapsInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CapsInfoParser.cpp
@@ -14,16 +14,16 @@ CapsInfoParser::CapsInfoParser() : level(0) {
}
void CapsInfoParser::handleStartElement(const std::string&, const std::string& /*ns*/, const AttributeMap& attributes) {
- if (level == 0) {
- getPayloadInternal()->setHash(attributes.getAttribute("hash"));
- getPayloadInternal()->setNode(attributes.getAttribute("node"));
- getPayloadInternal()->setVersion(attributes.getAttribute("ver"));
- }
- ++level;
+ if (level == 0) {
+ getPayloadInternal()->setHash(attributes.getAttribute("hash"));
+ getPayloadInternal()->setNode(attributes.getAttribute("node"));
+ getPayloadInternal()->setVersion(attributes.getAttribute("ver"));
+ }
+ ++level;
}
void CapsInfoParser::handleEndElement(const std::string&, const std::string&) {
- --level;
+ --level;
}
void CapsInfoParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/CapsInfoParser.h b/Swiften/Parser/PayloadParsers/CapsInfoParser.h
index 6e4610a..9556a4d 100644
--- a/Swiften/Parser/PayloadParsers/CapsInfoParser.h
+++ b/Swiften/Parser/PayloadParsers/CapsInfoParser.h
@@ -11,15 +11,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API CapsInfoParser : public GenericPayloadParser<CapsInfo> {
- public:
- CapsInfoParser();
+ class SWIFTEN_API CapsInfoParser : public GenericPayloadParser<CapsInfo> {
+ public:
+ CapsInfoParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level;
- };
+ private:
+ int level;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsDisableParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsDisableParser.cpp
index 7e26f3b..b8bd4b5 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsDisableParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsDisableParser.cpp
@@ -8,19 +8,19 @@
namespace Swift {
- CarbonsDisableParser::CarbonsDisableParser() : GenericPayloadParser<CarbonsDisable>() {
- }
+ CarbonsDisableParser::CarbonsDisableParser() : GenericPayloadParser<CarbonsDisable>() {
+ }
- CarbonsDisableParser::~CarbonsDisableParser() {
- }
+ CarbonsDisableParser::~CarbonsDisableParser() {
+ }
- void CarbonsDisableParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- }
+ void CarbonsDisableParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
+ }
- void CarbonsDisableParser::handleEndElement(const std::string&, const std::string&) {
- }
+ void CarbonsDisableParser::handleEndElement(const std::string&, const std::string&) {
+ }
+
+ void CarbonsDisableParser::handleCharacterData(const std::string&) {
+ }
- void CarbonsDisableParser::handleCharacterData(const std::string&) {
- }
-
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsDisableParser.h b/Swiften/Parser/PayloadParsers/CarbonsDisableParser.h
index 56f6787..7a5f4a4 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsDisableParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsDisableParser.h
@@ -11,13 +11,13 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API CarbonsDisableParser : public GenericPayloadParser<CarbonsDisable> {
- public:
- CarbonsDisableParser();
- virtual ~CarbonsDisableParser();
+ class SWIFTEN_API CarbonsDisableParser : public GenericPayloadParser<CarbonsDisable> {
+ public:
+ CarbonsDisableParser();
+ virtual ~CarbonsDisableParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
- virtual void handleCharacterData(const std::string&);
- };
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleCharacterData(const std::string&);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsEnableParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsEnableParser.cpp
index 52bf6d7..700f939 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsEnableParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsEnableParser.cpp
@@ -8,19 +8,19 @@
namespace Swift {
- CarbonsEnableParser::CarbonsEnableParser() : GenericPayloadParser<CarbonsEnable>() {
- }
+ CarbonsEnableParser::CarbonsEnableParser() : GenericPayloadParser<CarbonsEnable>() {
+ }
- CarbonsEnableParser::~CarbonsEnableParser() {
- }
+ CarbonsEnableParser::~CarbonsEnableParser() {
+ }
- void CarbonsEnableParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- }
+ void CarbonsEnableParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
+ }
- void CarbonsEnableParser::handleEndElement(const std::string&, const std::string&) {
- }
+ void CarbonsEnableParser::handleEndElement(const std::string&, const std::string&) {
+ }
+
+ void CarbonsEnableParser::handleCharacterData(const std::string&) {
+ }
- void CarbonsEnableParser::handleCharacterData(const std::string&) {
- }
-
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsEnableParser.h b/Swiften/Parser/PayloadParsers/CarbonsEnableParser.h
index d0e5771..0488f97 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsEnableParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsEnableParser.h
@@ -11,12 +11,12 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API CarbonsEnableParser : public GenericPayloadParser<CarbonsEnable> {
- public:
- CarbonsEnableParser();
- virtual ~CarbonsEnableParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
- virtual void handleCharacterData(const std::string&);
- };
+ class SWIFTEN_API CarbonsEnableParser : public GenericPayloadParser<CarbonsEnable> {
+ public:
+ CarbonsEnableParser();
+ virtual ~CarbonsEnableParser();
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleCharacterData(const std::string&);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.cpp
index 888edf1..b2038db 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.cpp
@@ -8,19 +8,19 @@
namespace Swift {
- CarbonsPrivateParser::CarbonsPrivateParser() : GenericPayloadParser<CarbonsPrivate>() {
- }
+ CarbonsPrivateParser::CarbonsPrivateParser() : GenericPayloadParser<CarbonsPrivate>() {
+ }
- CarbonsPrivateParser::~CarbonsPrivateParser() {
- }
+ CarbonsPrivateParser::~CarbonsPrivateParser() {
+ }
- void CarbonsPrivateParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- }
+ void CarbonsPrivateParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
+ }
- void CarbonsPrivateParser::handleEndElement(const std::string&, const std::string&) {
- }
+ void CarbonsPrivateParser::handleEndElement(const std::string&, const std::string&) {
+ }
+
+ void CarbonsPrivateParser::handleCharacterData(const std::string&) {
+ }
- void CarbonsPrivateParser::handleCharacterData(const std::string&) {
- }
-
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h b/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h
index 2797808..2ae3bae 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsPrivateParser.h
@@ -11,12 +11,12 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API CarbonsPrivateParser : public GenericPayloadParser<CarbonsPrivate> {
- public:
- CarbonsPrivateParser();
- virtual ~CarbonsPrivateParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
- virtual void handleCharacterData(const std::string&);
- };
+ class SWIFTEN_API CarbonsPrivateParser : public GenericPayloadParser<CarbonsPrivate> {
+ public:
+ CarbonsPrivateParser();
+ virtual ~CarbonsPrivateParser();
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleCharacterData(const std::string&);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp
index 267c541..d6fb6be 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp
@@ -7,39 +7,39 @@
#include <Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h>
namespace Swift {
- CarbonsReceivedParser::CarbonsReceivedParser(PayloadParserFactoryCollection* factories) : GenericPayloadParser<CarbonsReceived>(), factories_(factories), level_(TopLevel) {
- }
+ CarbonsReceivedParser::CarbonsReceivedParser(PayloadParserFactoryCollection* factories) : GenericPayloadParser<CarbonsReceived>(), factories_(factories), level_(TopLevel) {
+ }
- CarbonsReceivedParser::~CarbonsReceivedParser() {
- }
+ CarbonsReceivedParser::~CarbonsReceivedParser() {
+ }
- void CarbonsReceivedParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == PayloadLevel) {
- if (element == "forwarded") {
- forwardedParser_ = boost::dynamic_pointer_cast<ForwardedParser>(boost::make_shared<ForwardedParser>(factories_));
- }
- }
- if (forwardedParser_) {
- forwardedParser_->handleStartElement(element, ns, attributes);
- }
- ++level_;
- }
+ void CarbonsReceivedParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level_ == PayloadLevel) {
+ if (element == "forwarded") {
+ forwardedParser_ = boost::dynamic_pointer_cast<ForwardedParser>(boost::make_shared<ForwardedParser>(factories_));
+ }
+ }
+ if (forwardedParser_) {
+ forwardedParser_->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
+ }
- void CarbonsReceivedParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (forwardedParser_ && level_ >= PayloadLevel) {
- forwardedParser_->handleEndElement(element, ns);
- }
- if (forwardedParser_ && level_ == PayloadLevel) {
- /* done parsing nested stanza */
- getPayloadInternal()->setForwarded(forwardedParser_->getPayloadInternal());
- forwardedParser_.reset();
- }
- }
+ void CarbonsReceivedParser::handleEndElement(const std::string& element, const std::string& ns) {
+ --level_;
+ if (forwardedParser_ && level_ >= PayloadLevel) {
+ forwardedParser_->handleEndElement(element, ns);
+ }
+ if (forwardedParser_ && level_ == PayloadLevel) {
+ /* done parsing nested stanza */
+ getPayloadInternal()->setForwarded(forwardedParser_->getPayloadInternal());
+ forwardedParser_.reset();
+ }
+ }
- void CarbonsReceivedParser::handleCharacterData(const std::string& data) {
- if (forwardedParser_) {
- forwardedParser_->handleCharacterData(data);
- }
- }
+ void CarbonsReceivedParser::handleCharacterData(const std::string& data) {
+ if (forwardedParser_) {
+ forwardedParser_->handleCharacterData(data);
+ }
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h
index 6aa6326..666f20b 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h
@@ -12,24 +12,24 @@
#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
namespace Swift {
- class SWIFTEN_API CarbonsReceivedParser : public GenericPayloadParser<CarbonsReceived> {
- public:
- CarbonsReceivedParser(PayloadParserFactoryCollection* factories);
- virtual ~CarbonsReceivedParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string&);
+ class SWIFTEN_API CarbonsReceivedParser : public GenericPayloadParser<CarbonsReceived> {
+ public:
+ CarbonsReceivedParser(PayloadParserFactoryCollection* factories);
+ virtual ~CarbonsReceivedParser();
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string&);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
- private:
- PayloadParserFactoryCollection* factories_;
- boost::shared_ptr<ForwardedParser> forwardedParser_;
- int level_;
- };
+ private:
+ PayloadParserFactoryCollection* factories_;
+ boost::shared_ptr<ForwardedParser> forwardedParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
index b430249..e616211 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
@@ -7,39 +7,39 @@
#include <Swiften/Parser/PayloadParsers/CarbonsSentParser.h>
namespace Swift {
- CarbonsSentParser::CarbonsSentParser(PayloadParserFactoryCollection* factories) : GenericPayloadParser<CarbonsSent>(), factories_(factories), level_(TopLevel) {
- }
+ CarbonsSentParser::CarbonsSentParser(PayloadParserFactoryCollection* factories) : GenericPayloadParser<CarbonsSent>(), factories_(factories), level_(TopLevel) {
+ }
- CarbonsSentParser::~CarbonsSentParser() {
- }
+ CarbonsSentParser::~CarbonsSentParser() {
+ }
- void CarbonsSentParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == PayloadLevel) {
- if (element == "forwarded") {
- forwardedParser_ = boost::dynamic_pointer_cast<ForwardedParser>(boost::make_shared<ForwardedParser>(factories_));
- }
- }
- if (forwardedParser_) {
- forwardedParser_->handleStartElement(element, ns, attributes);
- }
- ++level_;
- }
+ void CarbonsSentParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level_ == PayloadLevel) {
+ if (element == "forwarded") {
+ forwardedParser_ = boost::dynamic_pointer_cast<ForwardedParser>(boost::make_shared<ForwardedParser>(factories_));
+ }
+ }
+ if (forwardedParser_) {
+ forwardedParser_->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
+ }
- void CarbonsSentParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (forwardedParser_ && level_ >= PayloadLevel) {
- forwardedParser_->handleEndElement(element, ns);
- }
- if (forwardedParser_ && level_ == PayloadLevel) {
- /* done parsing nested stanza */
- getPayloadInternal()->setForwarded(forwardedParser_->getPayloadInternal());
- forwardedParser_.reset();
- }
- }
+ void CarbonsSentParser::handleEndElement(const std::string& element, const std::string& ns) {
+ --level_;
+ if (forwardedParser_ && level_ >= PayloadLevel) {
+ forwardedParser_->handleEndElement(element, ns);
+ }
+ if (forwardedParser_ && level_ == PayloadLevel) {
+ /* done parsing nested stanza */
+ getPayloadInternal()->setForwarded(forwardedParser_->getPayloadInternal());
+ forwardedParser_.reset();
+ }
+ }
- void CarbonsSentParser::handleCharacterData(const std::string& data) {
- if (forwardedParser_) {
- forwardedParser_->handleCharacterData(data);
- }
- }
+ void CarbonsSentParser::handleCharacterData(const std::string& data) {
+ if (forwardedParser_) {
+ forwardedParser_->handleCharacterData(data);
+ }
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsSentParser.h b/Swiften/Parser/PayloadParsers/CarbonsSentParser.h
index 91c3292..9faf62d 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsSentParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsSentParser.h
@@ -12,24 +12,24 @@
#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
namespace Swift {
- class SWIFTEN_API CarbonsSentParser : public GenericPayloadParser<CarbonsSent> {
- public:
- CarbonsSentParser(PayloadParserFactoryCollection* factories);
- virtual ~CarbonsSentParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string&);
+ class SWIFTEN_API CarbonsSentParser : public GenericPayloadParser<CarbonsSent> {
+ public:
+ CarbonsSentParser(PayloadParserFactoryCollection* factories);
+ virtual ~CarbonsSentParser();
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string&);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
- private:
- PayloadParserFactoryCollection* factories_;
- boost::shared_ptr<ForwardedParser> forwardedParser_;
- int level_;
- };
+ private:
+ PayloadParserFactoryCollection* factories_;
+ boost::shared_ptr<ForwardedParser> forwardedParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ChatStateParser.cpp b/Swiften/Parser/PayloadParsers/ChatStateParser.cpp
index bd5ecbe..75ec699 100644
--- a/Swiften/Parser/PayloadParsers/ChatStateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ChatStateParser.cpp
@@ -12,26 +12,26 @@ ChatStateParser::ChatStateParser() : level_(0) {
}
void ChatStateParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
- if (level_ == 0) {
- ChatState::ChatStateType state = ChatState::Active;
- if (element == "active") {
- state = ChatState::Active;
- } else if (element == "composing") {
- state = ChatState::Composing;
- } else if (element == "inactive") {
- state = ChatState::Inactive;
- } else if (element == "paused") {
- state = ChatState::Paused;
- } else if (element == "gone") {
- state = ChatState::Gone;
- }
- getPayloadInternal()->setChatState(state);
- }
- ++level_;
+ if (level_ == 0) {
+ ChatState::ChatStateType state = ChatState::Active;
+ if (element == "active") {
+ state = ChatState::Active;
+ } else if (element == "composing") {
+ state = ChatState::Composing;
+ } else if (element == "inactive") {
+ state = ChatState::Inactive;
+ } else if (element == "paused") {
+ state = ChatState::Paused;
+ } else if (element == "gone") {
+ state = ChatState::Gone;
+ }
+ getPayloadInternal()->setChatState(state);
+ }
+ ++level_;
}
void ChatStateParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
+ --level_;
}
void ChatStateParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/ChatStateParser.h b/Swiften/Parser/PayloadParsers/ChatStateParser.h
index e18e17b..b932a5c 100644
--- a/Swiften/Parser/PayloadParsers/ChatStateParser.h
+++ b/Swiften/Parser/PayloadParsers/ChatStateParser.h
@@ -11,15 +11,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API ChatStateParser : public GenericPayloadParser<ChatState> {
- public:
- ChatStateParser();
+ class SWIFTEN_API ChatStateParser : public GenericPayloadParser<ChatState> {
+ public:
+ ChatStateParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ChatStateParserFactory.h b/Swiften/Parser/PayloadParsers/ChatStateParserFactory.h
index ac1c14d..cf226cc 100644
--- a/Swiften/Parser/PayloadParsers/ChatStateParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/ChatStateParserFactory.h
@@ -11,22 +11,22 @@
#include <Swiften/Parser/PayloadParsers/ChatStateParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API ChatStateParserFactory : public PayloadParserFactory {
- public:
- ChatStateParserFactory() {
- }
+ class SWIFTEN_API ChatStateParserFactory : public PayloadParserFactory {
+ public:
+ ChatStateParserFactory() {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return ns == "http://jabber.org/protocol/chatstates" &&
- (element == "active" || element == "composing"
- || element == "paused" || element == "inactive" || element == "gone");
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return ns == "http://jabber.org/protocol/chatstates" &&
+ (element == "active" || element == "composing"
+ || element == "paused" || element == "inactive" || element == "gone");
+ }
- virtual PayloadParser* createPayloadParser() {
- return new ChatStateParser();
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new ChatStateParser();
+ }
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CommandParser.cpp b/Swiften/Parser/PayloadParsers/CommandParser.cpp
index 91384db..1d2ddea 100644
--- a/Swiften/Parser/PayloadParsers/CommandParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CommandParser.cpp
@@ -14,130 +14,130 @@
namespace Swift {
CommandParser::CommandParser() : level_(TopLevel), inNote_(false), inActions_(false), noteType_(Command::Note::Info), formParser_(0) {
- formParserFactory_ = new FormParserFactory();
+ formParserFactory_ = new FormParserFactory();
}
CommandParser::~CommandParser() {
- delete formParserFactory_;
+ delete formParserFactory_;
}
void CommandParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- ++level_;
- if (level_ == PayloadLevel) {
- boost::optional<Command::Action> action = parseAction(attributes.getAttribute("action"));
- if (action) {
- getPayloadInternal()->setAction(*action);
- }
+ ++level_;
+ if (level_ == PayloadLevel) {
+ boost::optional<Command::Action> action = parseAction(attributes.getAttribute("action"));
+ if (action) {
+ getPayloadInternal()->setAction(*action);
+ }
- std::string status = attributes.getAttribute("status");
- if (status == "executing") {
- getPayloadInternal()->setStatus(Command::Executing);
- }
- else if (status == "completed") {
- getPayloadInternal()->setStatus(Command::Completed);
- }
- else if (status == "canceled") {
- getPayloadInternal()->setStatus(Command::Canceled);
- }
+ std::string status = attributes.getAttribute("status");
+ if (status == "executing") {
+ getPayloadInternal()->setStatus(Command::Executing);
+ }
+ else if (status == "completed") {
+ getPayloadInternal()->setStatus(Command::Completed);
+ }
+ else if (status == "canceled") {
+ getPayloadInternal()->setStatus(Command::Canceled);
+ }
- getPayloadInternal()->setNode(attributes.getAttribute("node"));
- getPayloadInternal()->setSessionID(attributes.getAttribute("sessionid"));
- }
- else if (level_ == FormOrNoteOrActionsLevel) {
- assert(!formParser_);
- if (formParserFactory_->canParse(element, ns, attributes)) {
- formParser_ = boost::polymorphic_downcast<FormParser*>(formParserFactory_->createPayloadParser());
- assert(formParser_);
- }
- else if (element == "note") {
- inNote_ = true;
- currentText_.clear();
- std::string noteType = attributes.getAttribute("type");
- if (noteType == "info") {
- noteType_ = Command::Note::Info;
- }
- else if (noteType == "warn") {
- noteType_ = Command::Note::Warn;
- }
- else if (noteType == "error") {
- noteType_ = Command::Note::Error;
- }
- else {
- noteType_ = Command::Note::Info;
- }
- }
- else if (element == "actions") {
- inActions_ = true;
- boost::optional<Command::Action> action = parseAction(attributes.getAttribute("execute"));
- if (action) {
- getPayloadInternal()->setExecuteAction(*action);
- }
- }
- }
- else if (level_ == ActionsActionLevel) {
- }
+ getPayloadInternal()->setNode(attributes.getAttribute("node"));
+ getPayloadInternal()->setSessionID(attributes.getAttribute("sessionid"));
+ }
+ else if (level_ == FormOrNoteOrActionsLevel) {
+ assert(!formParser_);
+ if (formParserFactory_->canParse(element, ns, attributes)) {
+ formParser_ = boost::polymorphic_downcast<FormParser*>(formParserFactory_->createPayloadParser());
+ assert(formParser_);
+ }
+ else if (element == "note") {
+ inNote_ = true;
+ currentText_.clear();
+ std::string noteType = attributes.getAttribute("type");
+ if (noteType == "info") {
+ noteType_ = Command::Note::Info;
+ }
+ else if (noteType == "warn") {
+ noteType_ = Command::Note::Warn;
+ }
+ else if (noteType == "error") {
+ noteType_ = Command::Note::Error;
+ }
+ else {
+ noteType_ = Command::Note::Info;
+ }
+ }
+ else if (element == "actions") {
+ inActions_ = true;
+ boost::optional<Command::Action> action = parseAction(attributes.getAttribute("execute"));
+ if (action) {
+ getPayloadInternal()->setExecuteAction(*action);
+ }
+ }
+ }
+ else if (level_ == ActionsActionLevel) {
+ }
- if (formParser_) {
- formParser_->handleStartElement(element, ns, attributes);
- }
+ if (formParser_) {
+ formParser_->handleStartElement(element, ns, attributes);
+ }
}
void CommandParser::handleEndElement(const std::string& element, const std::string& ns) {
- if (formParser_) {
- formParser_->handleEndElement(element, ns);
- }
+ if (formParser_) {
+ formParser_->handleEndElement(element, ns);
+ }
- if (level_ == FormOrNoteOrActionsLevel) {
- if (formParser_) {
- Form::ref form(boost::dynamic_pointer_cast<Form>(formParser_->getPayload()));
- assert(form);
- getPayloadInternal()->setForm(form);
- delete formParser_;
- formParser_ = 0;
- }
- else if (inNote_) {
- inNote_ = false;
- getPayloadInternal()->addNote(Command::Note(currentText_, noteType_));
- }
- else if (inActions_) {
- inActions_ = false;
- }
- }
- else if (level_ == ActionsActionLevel && inActions_) {
- boost::optional<Command::Action> action = parseAction(element);
- if (action) {
- getPayloadInternal()->addAvailableAction(*action);
- }
- }
- --level_;
+ if (level_ == FormOrNoteOrActionsLevel) {
+ if (formParser_) {
+ Form::ref form(boost::dynamic_pointer_cast<Form>(formParser_->getPayload()));
+ assert(form);
+ getPayloadInternal()->setForm(form);
+ delete formParser_;
+ formParser_ = 0;
+ }
+ else if (inNote_) {
+ inNote_ = false;
+ getPayloadInternal()->addNote(Command::Note(currentText_, noteType_));
+ }
+ else if (inActions_) {
+ inActions_ = false;
+ }
+ }
+ else if (level_ == ActionsActionLevel && inActions_) {
+ boost::optional<Command::Action> action = parseAction(element);
+ if (action) {
+ getPayloadInternal()->addAvailableAction(*action);
+ }
+ }
+ --level_;
}
void CommandParser::handleCharacterData(const std::string& data) {
- if (formParser_) {
- formParser_->handleCharacterData(data);
- }
- else {
- currentText_ += data;
- }
+ if (formParser_) {
+ formParser_->handleCharacterData(data);
+ }
+ else {
+ currentText_ += data;
+ }
}
boost::optional<Command::Action> CommandParser::parseAction(const std::string& action) {
- if (action == "execute") {
- return Command::Execute;
- }
- else if (action == "cancel") {
- return Command::Cancel;
- }
- else if (action == "prev") {
- return Command::Prev;
- }
- else if (action == "next") {
- return Command::Next;
- }
- else if (action == "complete") {
- return Command::Complete;
- }
- return boost::optional<Command::Action>();
+ if (action == "execute") {
+ return Command::Execute;
+ }
+ else if (action == "cancel") {
+ return Command::Cancel;
+ }
+ else if (action == "prev") {
+ return Command::Prev;
+ }
+ else if (action == "next") {
+ return Command::Next;
+ }
+ else if (action == "complete") {
+ return Command::Complete;
+ }
+ return boost::optional<Command::Action>();
}
}
diff --git a/Swiften/Parser/PayloadParsers/CommandParser.h b/Swiften/Parser/PayloadParsers/CommandParser.h
index 11badd4..105953a 100644
--- a/Swiften/Parser/PayloadParsers/CommandParser.h
+++ b/Swiften/Parser/PayloadParsers/CommandParser.h
@@ -13,34 +13,34 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class FormParserFactory;
- class FormParser;
-
- class SWIFTEN_API CommandParser : public GenericPayloadParser<Command> {
- public:
- CommandParser();
- ~CommandParser();
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
-
- private:
- static boost::optional<Command::Action> parseAction(const std::string& action);
-
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- FormOrNoteOrActionsLevel = 2,
- ActionsActionLevel = 3
- };
- int level_;
- bool inNote_;
- bool inActions_;
- Command::Note::Type noteType_;
- FormParserFactory* formParserFactory_;
- FormParser* formParser_;
- std::string currentText_;
- };
+ class FormParserFactory;
+ class FormParser;
+
+ class SWIFTEN_API CommandParser : public GenericPayloadParser<Command> {
+ public:
+ CommandParser();
+ ~CommandParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ static boost::optional<Command::Action> parseAction(const std::string& action);
+
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ FormOrNoteOrActionsLevel = 2,
+ ActionsActionLevel = 3
+ };
+ int level_;
+ bool inNote_;
+ bool inActions_;
+ Command::Note::Type noteType_;
+ FormParserFactory* formParserFactory_;
+ FormParser* formParser_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DelayParser.cpp b/Swiften/Parser/PayloadParsers/DelayParser.cpp
index b8e72d8..95371b7 100644
--- a/Swiften/Parser/PayloadParsers/DelayParser.cpp
+++ b/Swiften/Parser/PayloadParsers/DelayParser.cpp
@@ -14,19 +14,19 @@ DelayParser::DelayParser() : level_(0) {
}
void DelayParser::handleStartElement(const std::string& /*element*/, const std::string& /*ns*/, const AttributeMap& attributes) {
- if (level_ == 0) {
- boost::posix_time::ptime stamp = stringToDateTime(attributes.getAttribute("stamp"));
- getPayloadInternal()->setStamp(stamp);
- if (!attributes.getAttribute("from").empty()) {
- std::string from = attributes.getAttribute("from");
- getPayloadInternal()->setFrom(JID(from));
- }
- }
- ++level_;
+ if (level_ == 0) {
+ boost::posix_time::ptime stamp = stringToDateTime(attributes.getAttribute("stamp"));
+ getPayloadInternal()->setStamp(stamp);
+ if (!attributes.getAttribute("from").empty()) {
+ std::string from = attributes.getAttribute("from");
+ getPayloadInternal()->setFrom(JID(from));
+ }
+ }
+ ++level_;
}
void DelayParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
+ --level_;
}
void DelayParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/DelayParser.h b/Swiften/Parser/PayloadParsers/DelayParser.h
index d5fa58f..d9bf44b 100644
--- a/Swiften/Parser/PayloadParsers/DelayParser.h
+++ b/Swiften/Parser/PayloadParsers/DelayParser.h
@@ -11,15 +11,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API DelayParser : public GenericPayloadParser<Delay> {
- public:
- DelayParser();
+ class SWIFTEN_API DelayParser : public GenericPayloadParser<Delay> {
+ public:
+ DelayParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.cpp b/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.cpp
index 347200d..b6f0a86 100644
--- a/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.cpp
+++ b/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.cpp
@@ -14,18 +14,18 @@ DeliveryReceiptParser::DeliveryReceiptParser() : level_(0) {
}
void DeliveryReceiptParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributeMap) {
- if (level_ == 0) {
- if (element == "received") {
- if (attributeMap.getAttributeValue("id").is_initialized()) {
- getPayloadInternal()->setReceivedID(attributeMap.getAttributeValue("id").get());
- }
- }
- }
- ++level_;
+ if (level_ == 0) {
+ if (element == "received") {
+ if (attributeMap.getAttributeValue("id").is_initialized()) {
+ getPayloadInternal()->setReceivedID(attributeMap.getAttributeValue("id").get());
+ }
+ }
+ }
+ ++level_;
}
void DeliveryReceiptParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
+ --level_;
}
void DeliveryReceiptParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h b/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h
index bcb73f3..5cc0009 100644
--- a/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h
+++ b/Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h
@@ -17,15 +17,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API DeliveryReceiptParser : public GenericPayloadParser<DeliveryReceipt> {
- public:
- DeliveryReceiptParser();
+ class SWIFTEN_API DeliveryReceiptParser : public GenericPayloadParser<DeliveryReceipt> {
+ public:
+ DeliveryReceiptParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributeMap);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributeMap);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h b/Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h
index aa5d856..dc0c311 100644
--- a/Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/DeliveryReceiptParserFactory.h
@@ -17,20 +17,20 @@
#include <Swiften/Parser/PayloadParsers/DeliveryReceiptParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API DeliveryReceiptParserFactory : public PayloadParserFactory {
- public:
- DeliveryReceiptParserFactory() {
- }
+ class SWIFTEN_API DeliveryReceiptParserFactory : public PayloadParserFactory {
+ public:
+ DeliveryReceiptParserFactory() {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return ns == "urn:xmpp:receipts" && element == "received";
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return ns == "urn:xmpp:receipts" && element == "received";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new DeliveryReceiptParser();
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new DeliveryReceiptParser();
+ }
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h b/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h
index 5bf27fa..d8a68b0 100644
--- a/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h
+++ b/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h
@@ -17,12 +17,12 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API DeliveryReceiptRequestParser : public GenericPayloadParser<DeliveryReceiptRequest> {
- public:
- DeliveryReceiptRequestParser();
+ class SWIFTEN_API DeliveryReceiptRequestParser : public GenericPayloadParser<DeliveryReceiptRequest> {
+ public:
+ DeliveryReceiptRequestParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
- virtual void handleCharacterData(const std::string& data);
- };
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h b/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h
index 509db63..a858285 100644
--- a/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParserFactory.h
@@ -17,20 +17,20 @@
#include <Swiften/Parser/PayloadParsers/DeliveryReceiptRequestParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API DeliveryReceiptRequestParserFactory : public PayloadParserFactory {
- public:
- DeliveryReceiptRequestParserFactory() {
- }
+ class SWIFTEN_API DeliveryReceiptRequestParserFactory : public PayloadParserFactory {
+ public:
+ DeliveryReceiptRequestParserFactory() {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return ns == "urn:xmpp:receipts" && element == "request";
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return ns == "urn:xmpp:receipts" && element == "request";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new DeliveryReceiptRequestParser();
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new DeliveryReceiptRequestParser();
+ }
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp b/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp
index 9786b37..7dffa88 100644
--- a/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp
@@ -16,45 +16,45 @@ DiscoInfoParser::DiscoInfoParser() : level_(TopLevel), formParser_(NULL) {
}
void DiscoInfoParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- if (attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributes.getAttributeValue("node"));
- }
- }
- else if (level_ == PayloadLevel) {
- if (element == "identity") {
- getPayloadInternal()->addIdentity(DiscoInfo::Identity(attributes.getAttribute("name"), attributes.getAttribute("category"), attributes.getAttribute("type"), attributes.getAttribute("lang", "http://www.w3.org/XML/1998/namespace")));
- }
- else if (element == "feature") {
- getPayloadInternal()->addFeature(attributes.getAttribute("var"));
- }
- else if (element == "x" && ns == "jabber:x:data") {
- assert(!formParser_);
- formParser_ = new FormParser();
- }
- }
- if (formParser_) {
- formParser_->handleStartElement(element, ns, attributes);
- }
- ++level_;
+ if (level_ == TopLevel) {
+ if (attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributes.getAttributeValue("node"));
+ }
+ }
+ else if (level_ == PayloadLevel) {
+ if (element == "identity") {
+ getPayloadInternal()->addIdentity(DiscoInfo::Identity(attributes.getAttribute("name"), attributes.getAttribute("category"), attributes.getAttribute("type"), attributes.getAttribute("lang", "http://www.w3.org/XML/1998/namespace")));
+ }
+ else if (element == "feature") {
+ getPayloadInternal()->addFeature(attributes.getAttribute("var"));
+ }
+ else if (element == "x" && ns == "jabber:x:data") {
+ assert(!formParser_);
+ formParser_ = new FormParser();
+ }
+ }
+ if (formParser_) {
+ formParser_->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
}
void DiscoInfoParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (formParser_) {
- formParser_->handleEndElement(element, ns);
- }
- if (level_ == PayloadLevel && formParser_) {
- getPayloadInternal()->addExtension(formParser_->getPayloadInternal());
- delete formParser_;
- formParser_ = NULL;
- }
+ --level_;
+ if (formParser_) {
+ formParser_->handleEndElement(element, ns);
+ }
+ if (level_ == PayloadLevel && formParser_) {
+ getPayloadInternal()->addExtension(formParser_->getPayloadInternal());
+ delete formParser_;
+ formParser_ = NULL;
+ }
}
void DiscoInfoParser::handleCharacterData(const std::string& data) {
- if (formParser_) {
- formParser_->handleCharacterData(data);
- }
+ if (formParser_) {
+ formParser_->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/DiscoInfoParser.h b/Swiften/Parser/PayloadParsers/DiscoInfoParser.h
index 3d10c4b..28bfff1 100644
--- a/Swiften/Parser/PayloadParsers/DiscoInfoParser.h
+++ b/Swiften/Parser/PayloadParsers/DiscoInfoParser.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API DiscoInfoParser : public GenericPayloadParser<DiscoInfo> {
- public:
- DiscoInfoParser();
+ class SWIFTEN_API DiscoInfoParser : public GenericPayloadParser<DiscoInfo> {
+ public:
+ DiscoInfoParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level_;
- FormParser* formParser_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level_;
+ FormParser* formParser_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/DiscoItemsParser.cpp b/Swiften/Parser/PayloadParsers/DiscoItemsParser.cpp
index 179fb29..a3b9245 100644
--- a/Swiften/Parser/PayloadParsers/DiscoItemsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/DiscoItemsParser.cpp
@@ -12,21 +12,21 @@ DiscoItemsParser::DiscoItemsParser() : level_(TopLevel) {
}
void DiscoItemsParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level_ == PayloadLevel) {
- if (element == "item") {
- getPayloadInternal()->addItem(DiscoItems::Item(attributes.getAttribute("name"), JID(attributes.getAttribute("jid")), attributes.getAttribute("node")));
- }
- }
- else if (level_ == TopLevel) {
- if (element == "query") {
- getPayloadInternal()->setNode(attributes.getAttribute("node"));
- }
- }
- ++level_;
+ if (level_ == PayloadLevel) {
+ if (element == "item") {
+ getPayloadInternal()->addItem(DiscoItems::Item(attributes.getAttribute("name"), JID(attributes.getAttribute("jid")), attributes.getAttribute("node")));
+ }
+ }
+ else if (level_ == TopLevel) {
+ if (element == "query") {
+ getPayloadInternal()->setNode(attributes.getAttribute("node"));
+ }
+ }
+ ++level_;
}
void DiscoItemsParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
+ --level_;
}
void DiscoItemsParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/DiscoItemsParser.h b/Swiften/Parser/PayloadParsers/DiscoItemsParser.h
index b467ca1..3197b79 100644
--- a/Swiften/Parser/PayloadParsers/DiscoItemsParser.h
+++ b/Swiften/Parser/PayloadParsers/DiscoItemsParser.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API DiscoItemsParser : public GenericPayloadParser<DiscoItems> {
- public:
- DiscoItemsParser();
+ class SWIFTEN_API DiscoItemsParser : public GenericPayloadParser<DiscoItems> {
+ public:
+ DiscoItemsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ErrorParser.cpp b/Swiften/Parser/PayloadParsers/ErrorParser.cpp
index ace305b..222bcbd 100644
--- a/Swiften/Parser/PayloadParsers/ErrorParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ErrorParser.cpp
@@ -15,132 +15,132 @@ ErrorParser::ErrorParser(PayloadParserFactoryCollection* factories) : factories(
}
void ErrorParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- std::string type = attributes.getAttribute("type");
- if (type == "continue") {
- getPayloadInternal()->setType(ErrorPayload::Continue);
- }
- else if (type == "modify") {
- getPayloadInternal()->setType(ErrorPayload::Modify);
- }
- else if (type == "auth") {
- getPayloadInternal()->setType(ErrorPayload::Auth);
- }
- else if (type == "wait") {
- getPayloadInternal()->setType(ErrorPayload::Wait);
- }
- else {
- getPayloadInternal()->setType(ErrorPayload::Cancel);
- }
- }
- else if (level_ == PayloadLevel) {
- if (element == "text") {
+ if (level_ == TopLevel) {
+ std::string type = attributes.getAttribute("type");
+ if (type == "continue") {
+ getPayloadInternal()->setType(ErrorPayload::Continue);
+ }
+ else if (type == "modify") {
+ getPayloadInternal()->setType(ErrorPayload::Modify);
+ }
+ else if (type == "auth") {
+ getPayloadInternal()->setType(ErrorPayload::Auth);
+ }
+ else if (type == "wait") {
+ getPayloadInternal()->setType(ErrorPayload::Wait);
+ }
+ else {
+ getPayloadInternal()->setType(ErrorPayload::Cancel);
+ }
+ }
+ else if (level_ == PayloadLevel) {
+ if (element == "text") {
- }
- else if (element == "bad-request") {
- getPayloadInternal()->setCondition(ErrorPayload::BadRequest);
- }
- else if (element == "conflict") {
- getPayloadInternal()->setCondition(ErrorPayload::Conflict);
- }
- else if (element == "feature-not-implemented") {
- getPayloadInternal()->setCondition(ErrorPayload::FeatureNotImplemented);
- }
- else if (element == "forbidden") {
- getPayloadInternal()->setCondition(ErrorPayload::Forbidden);
- }
- else if (element == "gone") {
- getPayloadInternal()->setCondition(ErrorPayload::Gone);
- }
- else if (element == "internal-server-error") {
- getPayloadInternal()->setCondition(ErrorPayload::InternalServerError);
- }
- else if (element == "item-not-found") {
- getPayloadInternal()->setCondition(ErrorPayload::ItemNotFound);
- }
- else if (element == "jid-malformed") {
- getPayloadInternal()->setCondition(ErrorPayload::JIDMalformed);
- }
- else if (element == "not-acceptable") {
- getPayloadInternal()->setCondition(ErrorPayload::NotAcceptable);
- }
- else if (element == "not-allowed") {
- getPayloadInternal()->setCondition(ErrorPayload::NotAllowed);
- }
- else if (element == "not-authorized") {
- getPayloadInternal()->setCondition(ErrorPayload::NotAuthorized);
- }
- else if (element == "payment-required") {
- getPayloadInternal()->setCondition(ErrorPayload::PaymentRequired);
- }
- else if (element == "recipient-unavailable") {
- getPayloadInternal()->setCondition(ErrorPayload::RecipientUnavailable);
- }
- else if (element == "redirect") {
- getPayloadInternal()->setCondition(ErrorPayload::Redirect);
- }
- else if (element == "registration-required") {
- getPayloadInternal()->setCondition(ErrorPayload::RegistrationRequired);
- }
- else if (element == "remote-server-not-found") {
- getPayloadInternal()->setCondition(ErrorPayload::RemoteServerNotFound);
- }
- else if (element == "remote-server-timeout") {
- getPayloadInternal()->setCondition(ErrorPayload::RemoteServerTimeout);
- }
- else if (element == "resource-constraint") {
- getPayloadInternal()->setCondition(ErrorPayload::ResourceConstraint);
- }
- else if (element == "service-unavailable") {
- getPayloadInternal()->setCondition(ErrorPayload::ServiceUnavailable);
- }
- else if (element == "subscription-required") {
- getPayloadInternal()->setCondition(ErrorPayload::SubscriptionRequired);
- }
- else if (element == "unexpected-request") {
- getPayloadInternal()->setCondition(ErrorPayload::UnexpectedRequest);
- }
- else {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- } else {
- getPayloadInternal()->setCondition(ErrorPayload::UndefinedCondition);
- }
- }
- }
- if (level_ >= PayloadLevel && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level_;
+ }
+ else if (element == "bad-request") {
+ getPayloadInternal()->setCondition(ErrorPayload::BadRequest);
+ }
+ else if (element == "conflict") {
+ getPayloadInternal()->setCondition(ErrorPayload::Conflict);
+ }
+ else if (element == "feature-not-implemented") {
+ getPayloadInternal()->setCondition(ErrorPayload::FeatureNotImplemented);
+ }
+ else if (element == "forbidden") {
+ getPayloadInternal()->setCondition(ErrorPayload::Forbidden);
+ }
+ else if (element == "gone") {
+ getPayloadInternal()->setCondition(ErrorPayload::Gone);
+ }
+ else if (element == "internal-server-error") {
+ getPayloadInternal()->setCondition(ErrorPayload::InternalServerError);
+ }
+ else if (element == "item-not-found") {
+ getPayloadInternal()->setCondition(ErrorPayload::ItemNotFound);
+ }
+ else if (element == "jid-malformed") {
+ getPayloadInternal()->setCondition(ErrorPayload::JIDMalformed);
+ }
+ else if (element == "not-acceptable") {
+ getPayloadInternal()->setCondition(ErrorPayload::NotAcceptable);
+ }
+ else if (element == "not-allowed") {
+ getPayloadInternal()->setCondition(ErrorPayload::NotAllowed);
+ }
+ else if (element == "not-authorized") {
+ getPayloadInternal()->setCondition(ErrorPayload::NotAuthorized);
+ }
+ else if (element == "payment-required") {
+ getPayloadInternal()->setCondition(ErrorPayload::PaymentRequired);
+ }
+ else if (element == "recipient-unavailable") {
+ getPayloadInternal()->setCondition(ErrorPayload::RecipientUnavailable);
+ }
+ else if (element == "redirect") {
+ getPayloadInternal()->setCondition(ErrorPayload::Redirect);
+ }
+ else if (element == "registration-required") {
+ getPayloadInternal()->setCondition(ErrorPayload::RegistrationRequired);
+ }
+ else if (element == "remote-server-not-found") {
+ getPayloadInternal()->setCondition(ErrorPayload::RemoteServerNotFound);
+ }
+ else if (element == "remote-server-timeout") {
+ getPayloadInternal()->setCondition(ErrorPayload::RemoteServerTimeout);
+ }
+ else if (element == "resource-constraint") {
+ getPayloadInternal()->setCondition(ErrorPayload::ResourceConstraint);
+ }
+ else if (element == "service-unavailable") {
+ getPayloadInternal()->setCondition(ErrorPayload::ServiceUnavailable);
+ }
+ else if (element == "subscription-required") {
+ getPayloadInternal()->setCondition(ErrorPayload::SubscriptionRequired);
+ }
+ else if (element == "unexpected-request") {
+ getPayloadInternal()->setCondition(ErrorPayload::UnexpectedRequest);
+ }
+ else {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ } else {
+ getPayloadInternal()->setCondition(ErrorPayload::UndefinedCondition);
+ }
+ }
+ }
+ if (level_ >= PayloadLevel && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
}
void ErrorParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (currentPayloadParser) {
- if (level_ >= PayloadLevel) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level_;
+ if (currentPayloadParser) {
+ if (level_ >= PayloadLevel) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level_ == PayloadLevel) {
- getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
- currentPayloadParser.reset();
- }
- }
- else if (level_ == PayloadLevel) {
- if (element == "text") {
- getPayloadInternal()->setText(currentText_);
- }
- }
+ if (level_ == PayloadLevel) {
+ getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
+ currentPayloadParser.reset();
+ }
+ }
+ else if (level_ == PayloadLevel) {
+ if (element == "text") {
+ getPayloadInternal()->setText(currentText_);
+ }
+ }
}
void ErrorParser::handleCharacterData(const std::string& data) {
- if (level_ > PayloadLevel && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
- else {
- currentText_ += data;
- }
+ if (level_ > PayloadLevel && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+ else {
+ currentText_ += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/ErrorParser.h b/Swiften/Parser/PayloadParsers/ErrorParser.h
index fc4a5cb..dd1aa95 100644
--- a/Swiften/Parser/PayloadParsers/ErrorParser.h
+++ b/Swiften/Parser/PayloadParsers/ErrorParser.h
@@ -11,23 +11,23 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class SWIFTEN_API ErrorParser : public GenericPayloadParser<ErrorPayload> {
- public:
- ErrorParser(PayloadParserFactoryCollection* factories);
+ class PayloadParserFactoryCollection;
+ class SWIFTEN_API ErrorParser : public GenericPayloadParser<ErrorPayload> {
+ public:
+ ErrorParser(PayloadParserFactoryCollection* factories);
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- PayloadParserFactoryCollection* factories;
- int level_;
- std::string currentText_;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ PayloadParserFactoryCollection* factories;
+ int level_;
+ std::string currentText_;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ErrorParserFactory.h b/Swiften/Parser/PayloadParsers/ErrorParserFactory.h
index bcced8b..d8f09bf 100644
--- a/Swiften/Parser/PayloadParsers/ErrorParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/ErrorParserFactory.h
@@ -11,23 +11,23 @@
#include <Swiften/Parser/PayloadParsers/ErrorParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API ErrorParserFactory : public PayloadParserFactory {
- public:
- ErrorParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
+ class SWIFTEN_API ErrorParserFactory : public PayloadParserFactory {
+ public:
+ ErrorParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
- virtual bool canParse(const std::string& element, const std::string& /*ns*/, const AttributeMap&) const {
- return element == "error";
- }
+ virtual bool canParse(const std::string& element, const std::string& /*ns*/, const AttributeMap&) const {
+ return element == "error";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new ErrorParser(factories);
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new ErrorParser(factories);
+ }
- private:
- PayloadParserFactoryCollection* factories;
+ private:
+ PayloadParserFactoryCollection* factories;
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/FormParser.cpp b/Swiften/Parser/PayloadParsers/FormParser.cpp
index b66dadc..3a2c880 100644
--- a/Swiften/Parser/PayloadParsers/FormParser.cpp
+++ b/Swiften/Parser/PayloadParsers/FormParser.cpp
@@ -16,240 +16,240 @@ FormParser::FormParser() : level_(TopLevel), parsingItem_(false), parsingReporte
}
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;
- }
- else if (element == "item") {
- parsingItem_ = true;
- }
- else if (element == "page") {
- currentPage_ = boost::make_shared<FormPage>();
- currentPage_->setLabel(attributes.getAttribute("label"));
- }
- }
- else if (level_ == FieldLevel && currentField_) {
- currentText_.clear();
- if (element == "option") {
- currentOptionLabel_ = attributes.getAttribute("label");
- currentOptionValue_ = "";
- parsingOption_ = true;
- }
- }
- if (level_ >= PayloadLevel) {
- if (element == "field") {
- currentField_ = boost::make_shared<FormField>();
- std::string type = attributes.getAttribute("type");
- FormField::Type fieldType = FormField::UnknownType;
- 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") {
- fieldType = FormField::TextSingleType;
- }
- if (type == "jid-single") {
- fieldType = FormField::JIDSingleType;
- }
- if (type == "jid-multi") {
- fieldType = FormField::JIDMultiType;
- }
- if (type == "list-multi") {
- fieldType = FormField::ListMultiType;
- }
- currentField_->setType(fieldType);
- currentField_->setName(attributes.getAttribute("var"));
- currentField_->setLabel(attributes.getAttribute("label"));
- }
- else if (element == "value") {
- currentText_.clear();
- }
- }
- if (level_ > PayloadLevel) {
- if (element == "section") {
- currentSection_ = boost::make_shared<FormSection>();
- currentSection_->setLabel(attributes.getAttribute("label"));
- sectionStack_.push_back(currentSection_);
- currentSections_.push_back(currentSection_);
- }
- if (element == "reportedref") {
- currentReportedRef_ = boost::make_shared<FormReportedRef>();
- }
- if (element == "fieldref") {
- currentText_.clear();
- currentFieldRef_ = attributes.getAttribute("var");
- if (sectionStack_.size() > 0) {
- sectionStack_.at(sectionStack_.size()-1)->addFieldRef(currentFieldRef_);
- } else if (currentPage_) {
- currentPage_->addFieldRef(currentFieldRef_);
- }
- }
- if (element == "text") {
- currentText_.clear();
- currentTextElement_ = boost::make_shared<FormText>();
- }
- }
- ++level_;
+ 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;
+ }
+ else if (element == "item") {
+ parsingItem_ = true;
+ }
+ else if (element == "page") {
+ currentPage_ = boost::make_shared<FormPage>();
+ currentPage_->setLabel(attributes.getAttribute("label"));
+ }
+ }
+ else if (level_ == FieldLevel && currentField_) {
+ currentText_.clear();
+ if (element == "option") {
+ currentOptionLabel_ = attributes.getAttribute("label");
+ currentOptionValue_ = "";
+ parsingOption_ = true;
+ }
+ }
+ if (level_ >= PayloadLevel) {
+ if (element == "field") {
+ currentField_ = boost::make_shared<FormField>();
+ std::string type = attributes.getAttribute("type");
+ FormField::Type fieldType = FormField::UnknownType;
+ 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") {
+ fieldType = FormField::TextSingleType;
+ }
+ if (type == "jid-single") {
+ fieldType = FormField::JIDSingleType;
+ }
+ if (type == "jid-multi") {
+ fieldType = FormField::JIDMultiType;
+ }
+ if (type == "list-multi") {
+ fieldType = FormField::ListMultiType;
+ }
+ currentField_->setType(fieldType);
+ currentField_->setName(attributes.getAttribute("var"));
+ currentField_->setLabel(attributes.getAttribute("label"));
+ }
+ else if (element == "value") {
+ currentText_.clear();
+ }
+ }
+ if (level_ > PayloadLevel) {
+ if (element == "section") {
+ currentSection_ = boost::make_shared<FormSection>();
+ currentSection_->setLabel(attributes.getAttribute("label"));
+ sectionStack_.push_back(currentSection_);
+ currentSections_.push_back(currentSection_);
+ }
+ if (element == "reportedref") {
+ currentReportedRef_ = boost::make_shared<FormReportedRef>();
+ }
+ if (element == "fieldref") {
+ currentText_.clear();
+ currentFieldRef_ = attributes.getAttribute("var");
+ if (sectionStack_.size() > 0) {
+ sectionStack_.at(sectionStack_.size()-1)->addFieldRef(currentFieldRef_);
+ } else if (currentPage_) {
+ currentPage_->addFieldRef(currentFieldRef_);
+ }
+ }
+ if (element == "text") {
+ currentText_.clear();
+ currentTextElement_ = boost::make_shared<FormText>();
+ }
+ }
+ ++level_;
}
void FormParser::handleEndElement(const std::string& element, const std::string&) {
- --level_;
- if (level_ == PayloadLevel) {
- if (element == "title") {
- std::string currentTitle = getPayloadInternal()->getTitle();
- if (currentTitle.empty()) {
- getPayloadInternal()->setTitle(currentText_);
- }
- else {
- getPayloadInternal()->setTitle(currentTitle + "\n" + currentText_);
- }
- }
- else if (element == "instructions") {
- std::string currentInstructions = getPayloadInternal()->getInstructions();
- if (currentInstructions.empty()) {
- getPayloadInternal()->setInstructions(currentText_);
- }
- else {
- getPayloadInternal()->setInstructions(currentInstructions + "\n" + currentText_);
- }
- }
- else if (element == "reported") {
- parsingReported_ = false;
- }
- else if (element == "item") {
- parsingItem_ = false;
- getPayloadInternal()->addItem(currentFields_);
- currentFields_.clear();
- }
- else if (element == "page") {
- getPayloadInternal()->addPage(currentPage_);
- currentPages_.push_back(currentPage_);
- }
- }
- 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 (boost::shared_ptr<FormPage> page, currentPages_) {
- foreach (std::string pageRef, page->getFieldRefs()) {
- if (pageRef == currentField_->getName()) {
- page->addField(currentField_);
- }
- }
- }
- foreach (boost::shared_ptr<FormSection> section, currentSections_) {
- foreach (std::string 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_);
- }
- hasReportedRef_ = true;
- currentReportedRef_.reset();
- }
- if (currentTextElement_) {
- if (element == "text") {
- currentTextElement_->setTextString(currentText_);
- }
- if (sectionStack_.size() > 0) {
- sectionStack_.at(sectionStack_.size()-1)->addTextElement(currentTextElement_);
- } else if (currentPage_) {
- currentPage_->addTextElement(currentTextElement_);
- }
- currentTextElement_.reset();
- }
- }
+ --level_;
+ if (level_ == PayloadLevel) {
+ if (element == "title") {
+ std::string currentTitle = getPayloadInternal()->getTitle();
+ if (currentTitle.empty()) {
+ getPayloadInternal()->setTitle(currentText_);
+ }
+ else {
+ getPayloadInternal()->setTitle(currentTitle + "\n" + currentText_);
+ }
+ }
+ else if (element == "instructions") {
+ std::string currentInstructions = getPayloadInternal()->getInstructions();
+ if (currentInstructions.empty()) {
+ getPayloadInternal()->setInstructions(currentText_);
+ }
+ else {
+ getPayloadInternal()->setInstructions(currentInstructions + "\n" + currentText_);
+ }
+ }
+ else if (element == "reported") {
+ parsingReported_ = false;
+ }
+ else if (element == "item") {
+ parsingItem_ = false;
+ getPayloadInternal()->addItem(currentFields_);
+ currentFields_.clear();
+ }
+ else if (element == "page") {
+ getPayloadInternal()->addPage(currentPage_);
+ currentPages_.push_back(currentPage_);
+ }
+ }
+ 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 (boost::shared_ptr<FormPage> page, currentPages_) {
+ foreach (std::string pageRef, page->getFieldRefs()) {
+ if (pageRef == currentField_->getName()) {
+ page->addField(currentField_);
+ }
+ }
+ }
+ foreach (boost::shared_ptr<FormSection> section, currentSections_) {
+ foreach (std::string 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_);
+ }
+ hasReportedRef_ = true;
+ currentReportedRef_.reset();
+ }
+ if (currentTextElement_) {
+ if (element == "text") {
+ currentTextElement_->setTextString(currentText_);
+ }
+ if (sectionStack_.size() > 0) {
+ sectionStack_.at(sectionStack_.size()-1)->addTextElement(currentTextElement_);
+ } else if (currentPage_) {
+ currentPage_->addTextElement(currentTextElement_);
+ }
+ currentTextElement_.reset();
+ }
+ }
}
void FormParser::handleCharacterData(const std::string& text) {
- currentText_ += text;
+ currentText_ += text;
}
}
diff --git a/Swiften/Parser/PayloadParsers/FormParser.h b/Swiften/Parser/PayloadParsers/FormParser.h
index c8c2294..81032ee 100644
--- a/Swiften/Parser/PayloadParsers/FormParser.h
+++ b/Swiften/Parser/PayloadParsers/FormParser.h
@@ -11,36 +11,36 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API FormParser : public GenericPayloadParser<Form> {
- public:
- FormParser();
+ class SWIFTEN_API FormParser : public GenericPayloadParser<Form> {
+ public:
+ FormParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- FieldLevel = 2
- };
- int level_;
- std::string currentText_;
- std::string currentOptionLabel_;
- std::string currentOptionValue_;
- std::string currentFieldRef_;
- bool parsingItem_;
- bool parsingReported_;
- bool parsingOption_;
- bool hasReportedRef_;
- FormField::ref currentField_;
- std::vector<FormField::ref> currentFields_;
- FormText::text currentTextElement_;
- FormReportedRef::ref currentReportedRef_;
- FormPage::page currentPage_;
- FormSection::section currentSection_;
- std::vector<boost::shared_ptr<FormPage> > currentPages_;
- std::vector<boost::shared_ptr<FormSection> > sectionStack_;
- std::vector<boost::shared_ptr<FormSection> > currentSections_;
- };
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ FieldLevel = 2
+ };
+ int level_;
+ std::string currentText_;
+ std::string currentOptionLabel_;
+ std::string currentOptionValue_;
+ std::string currentFieldRef_;
+ bool parsingItem_;
+ bool parsingReported_;
+ bool parsingOption_;
+ bool hasReportedRef_;
+ FormField::ref currentField_;
+ std::vector<FormField::ref> currentFields_;
+ FormText::text currentTextElement_;
+ FormReportedRef::ref currentReportedRef_;
+ FormPage::page currentPage_;
+ FormSection::section currentSection_;
+ std::vector<boost::shared_ptr<FormPage> > currentPages_;
+ std::vector<boost::shared_ptr<FormSection> > sectionStack_;
+ std::vector<boost::shared_ptr<FormSection> > currentSections_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/FormParserFactory.h b/Swiften/Parser/PayloadParsers/FormParserFactory.h
index 74b2d35..851b302 100644
--- a/Swiften/Parser/PayloadParsers/FormParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/FormParserFactory.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/PayloadParsers/FormParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API FormParserFactory : public PayloadParserFactory {
- public:
- FormParserFactory() {
- }
+ class SWIFTEN_API FormParserFactory : public PayloadParserFactory {
+ public:
+ FormParserFactory() {
+ }
- virtual bool canParse(const std::string& /*element*/, const std::string& ns, const AttributeMap&) const {
- return ns == "jabber:x:data";
- }
+ virtual bool canParse(const std::string& /*element*/, const std::string& ns, const AttributeMap&) const {
+ return ns == "jabber:x:data";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new FormParser();
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new FormParser();
+ }
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ForwardedParser.cpp b/Swiften/Parser/PayloadParsers/ForwardedParser.cpp
index 1e3d339..35d20a9 100644
--- a/Swiften/Parser/PayloadParsers/ForwardedParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ForwardedParser.cpp
@@ -23,51 +23,51 @@ ForwardedParser::ForwardedParser(PayloadParserFactoryCollection* factories) : fa
}
void ForwardedParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == PayloadLevel) {
- if (element == "iq" && ns == "jabber:client") { /* begin parsing a nested stanza? */
- childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<IQParser>(factories_));
- } else if (element == "message" && ns == "jabber:client") {
- childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<MessageParser>(factories_));
- } else if (element == "presence" && ns == "jabber:client") {
- childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<PresenceParser>(factories_));
- } else if (element == "delay" && ns == "urn:xmpp:delay") { /* nested delay payload */
- delayParser_ = boost::make_shared<DelayParser>();
- }
- }
- if (childParser_) { /* parsing a nested stanza? */
- childParser_->handleStartElement(element, ns, attributes);
- }
- if (delayParser_) { /* parsing a nested delay payload? */
- delayParser_->handleStartElement(element, ns, attributes);
- }
- ++level_;
+ if (level_ == PayloadLevel) {
+ if (element == "iq" && ns == "jabber:client") { /* begin parsing a nested stanza? */
+ childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<IQParser>(factories_));
+ } else if (element == "message" && ns == "jabber:client") {
+ childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<MessageParser>(factories_));
+ } else if (element == "presence" && ns == "jabber:client") {
+ childParser_ = boost::dynamic_pointer_cast<StanzaParser>(boost::make_shared<PresenceParser>(factories_));
+ } else if (element == "delay" && ns == "urn:xmpp:delay") { /* nested delay payload */
+ delayParser_ = boost::make_shared<DelayParser>();
+ }
+ }
+ if (childParser_) { /* parsing a nested stanza? */
+ childParser_->handleStartElement(element, ns, attributes);
+ }
+ if (delayParser_) { /* parsing a nested delay payload? */
+ delayParser_->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
}
void ForwardedParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (childParser_ && level_ >= PayloadLevel) {
- childParser_->handleEndElement(element, ns);
- }
- if (childParser_ && level_ == PayloadLevel) {
- /* done parsing nested stanza */
- getPayloadInternal()->setStanza(childParser_->getStanza());
- childParser_.reset();
- }
- if (delayParser_ && level_ >= PayloadLevel) {
- delayParser_->handleEndElement(element, ns);
- }
- if (delayParser_ && level_ == PayloadLevel) {
- /* done parsing nested delay payload */
- getPayloadInternal()->setDelay(boost::dynamic_pointer_cast<Delay>(delayParser_->getPayload()));
- delayParser_.reset();
- }
+ --level_;
+ if (childParser_ && level_ >= PayloadLevel) {
+ childParser_->handleEndElement(element, ns);
+ }
+ if (childParser_ && level_ == PayloadLevel) {
+ /* done parsing nested stanza */
+ getPayloadInternal()->setStanza(childParser_->getStanza());
+ childParser_.reset();
+ }
+ if (delayParser_ && level_ >= PayloadLevel) {
+ delayParser_->handleEndElement(element, ns);
+ }
+ if (delayParser_ && level_ == PayloadLevel) {
+ /* done parsing nested delay payload */
+ getPayloadInternal()->setDelay(boost::dynamic_pointer_cast<Delay>(delayParser_->getPayload()));
+ delayParser_.reset();
+ }
}
void ForwardedParser::handleCharacterData(const std::string& data) {
- if (childParser_) {
- childParser_->handleCharacterData(data);
- }
- if (delayParser_) {
- delayParser_->handleCharacterData(data);
- }
+ if (childParser_) {
+ childParser_->handleCharacterData(data);
+ }
+ if (delayParser_) {
+ delayParser_->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/ForwardedParser.h b/Swiften/Parser/PayloadParsers/ForwardedParser.h
index 6d7b4f5..70eecdf 100644
--- a/Swiften/Parser/PayloadParsers/ForwardedParser.h
+++ b/Swiften/Parser/PayloadParsers/ForwardedParser.h
@@ -14,27 +14,27 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class StanzaParser;
- class DelayParser;
-
- class SWIFTEN_API ForwardedParser : public GenericPayloadParser<Forwarded> {
- public:
- ForwardedParser(PayloadParserFactoryCollection* factories);
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
-
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
-
- private:
- PayloadParserFactoryCollection* factories_;
- boost::shared_ptr<StanzaParser> childParser_;
- boost::shared_ptr<DelayParser> delayParser_;
- int level_;
- };
+ class PayloadParserFactoryCollection;
+ class StanzaParser;
+ class DelayParser;
+
+ class SWIFTEN_API ForwardedParser : public GenericPayloadParser<Forwarded> {
+ public:
+ ForwardedParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+
+ private:
+ PayloadParserFactoryCollection* factories_;
+ boost::shared_ptr<StanzaParser> childParser_;
+ boost::shared_ptr<DelayParser> delayParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
index 7e7123f..0d0c424 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
@@ -94,94 +94,94 @@ using namespace boost;
namespace Swift {
FullPayloadParserFactoryCollection::FullPayloadParserFactoryCollection() {
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<IBBParser> >("", "http://jabber.org/protocol/ibb"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StatusShowParser> >("show"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StatusParser> >("status"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "http://swift.im/protocol/replace"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "urn:xmpp:message-correct:0"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<LastParser> >("query", "jabber:iq:last"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BodyParser> >("body"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SubjectParser> >("subject"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ThreadParser> >("thread"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<PriorityParser> >("priority"));
- factories_.push_back(boost::make_shared<ErrorParserFactory>(this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DelayParser> >("delay", "urn:xmpp:delay"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SoftwareVersionParser> >("query", "jabber:iq:version"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StorageParser> >("storage", "storage:bookmarks"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<RosterItemExchangeParser> >("x", "http://jabber.org/protocol/rosterx"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<RosterParser> >("query", "jabber:iq:roster"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DiscoInfoParser> >("query", "http://jabber.org/protocol/disco#info"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DiscoItemsParser> >("query", "http://jabber.org/protocol/disco#items"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CapsInfoParser> >("c", "http://jabber.org/protocol/caps"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ResourceBindParser> >("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StartSessionParser> >("session", "urn:ietf:params:xml:ns:xmpp-session"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<BlockPayload> > >("block", "urn:xmpp:blocking"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<BlockListPayload> > >("blocklist", "urn:xmpp:blocking"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<UnblockPayload> > >("unblock", "urn:xmpp:blocking"));
- factories_.push_back(boost::make_shared<SecurityLabelParserFactory>());
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SecurityLabelsCatalogParser> >("catalog", "urn:xmpp:sec-label:catalog:2"));
- factories_.push_back(boost::make_shared<FormParserFactory>());
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CommandParser> >("command", "http://jabber.org/protocol/commands"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<InBandRegistrationPayloadParser> >("query", "jabber:iq:register"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SearchPayloadParser> >("query", "jabber:iq:search"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StreamInitiationParser> >("si", "http://jabber.org/protocol/si"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BytestreamsParser> >("query", "http://jabber.org/protocol/bytestreams"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<VCardUpdateParser> >("x", "vcard-temp:x:update"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<VCardParser> >("vCard", "vcard-temp"));
- factories_.push_back(boost::make_shared<PrivateStorageParserFactory>(this));
- factories_.push_back(boost::make_shared<ChatStateParserFactory>());
- factories_.push_back(boost::make_shared<MUCUserPayloadParserFactory>(this));
- factories_.push_back(boost::make_shared<MUCOwnerPayloadParserFactory>(this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCInvitationPayloadParser> >("x", "jabber:x:conference"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCAdminPayloadParser> >("query", "http://jabber.org/protocol/muc#admin"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#user"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#owner"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<NicknameParser> >("nick", "http://jabber.org/protocol/nick"));
- factories_.push_back(boost::make_shared<JingleParserFactory>(this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleReasonParser> >("reason", "urn:xmpp:jingle:1"));
- factories_.push_back(boost::make_shared<JingleContentPayloadParserFactory>(this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleIBBTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:ibb:1"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleS5BTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:s5b:1"));
- factories_.push_back(boost::make_shared<JingleFileTransferDescriptionParserFactory>(this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StreamInitiationFileInfoParser> >("file", "http://jabber.org/protocol/si/profile/file-transfer"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleFileTransferFileInfoParser> >("file", "urn:xmpp:jingle:apps:file-transfer:4"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleFileTransferHashParser> >("checksum"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<S5BProxyRequestParser> >("query", "http://jabber.org/protocol/bytestreams"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<WhiteboardParser> >("wb", "http://swift.im/whiteboard"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<UserLocationParser> >("geoloc", "http://jabber.org/protocol/geoloc"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<UserTuneParser> >("tune", "http://jabber.org/protocol/tune"));
- factories_.push_back(boost::make_shared<DeliveryReceiptParserFactory>());
- factories_.push_back(boost::make_shared<DeliveryReceiptRequestParserFactory>());
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<IdleParser> >("idle", "urn:xmpp:idle:1"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubOwnerPubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub#owner", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubEventParser> >("event", "http://jabber.org/protocol/pubsub#event", this));
- factories_.push_back(boost::make_shared<PubSubErrorParserFactory>());
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ResultSetParser> >("set", "http://jabber.org/protocol/rsm"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<ForwardedParser> >("forwarded", "urn:xmpp:forward:0", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<MAMResultParser> >("result", "urn:xmpp:mam:0", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MAMQueryParser> >("query", "urn:xmpp:mam:0"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MAMFinParser> >("fin", "urn:xmpp:mam:0"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<IsodeIQDelegationParser> >("delegate", "http://isode.com/iq_delegation", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsEnableParser> >("enable", "urn:xmpp:carbons:2"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsDisableParser> >("disable", "urn:xmpp:carbons:2"));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<CarbonsReceivedParser> >("received", "urn:xmpp:carbons:2", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<CarbonsSentParser> >("sent", "urn:xmpp:carbons:2", this));
- factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsPrivateParser> >("private", "urn:xmpp:carbons:2"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<IBBParser> >("", "http://jabber.org/protocol/ibb"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StatusShowParser> >("show"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StatusParser> >("status"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "http://swift.im/protocol/replace"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "urn:xmpp:message-correct:0"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<LastParser> >("query", "jabber:iq:last"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BodyParser> >("body"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SubjectParser> >("subject"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ThreadParser> >("thread"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<PriorityParser> >("priority"));
+ factories_.push_back(boost::make_shared<ErrorParserFactory>(this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DelayParser> >("delay", "urn:xmpp:delay"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SoftwareVersionParser> >("query", "jabber:iq:version"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StorageParser> >("storage", "storage:bookmarks"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<RosterItemExchangeParser> >("x", "http://jabber.org/protocol/rosterx"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<RosterParser> >("query", "jabber:iq:roster"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DiscoInfoParser> >("query", "http://jabber.org/protocol/disco#info"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<DiscoItemsParser> >("query", "http://jabber.org/protocol/disco#items"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CapsInfoParser> >("c", "http://jabber.org/protocol/caps"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ResourceBindParser> >("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StartSessionParser> >("session", "urn:ietf:params:xml:ns:xmpp-session"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<BlockPayload> > >("block", "urn:xmpp:blocking"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<BlockListPayload> > >("blocklist", "urn:xmpp:blocking"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BlockParser<UnblockPayload> > >("unblock", "urn:xmpp:blocking"));
+ factories_.push_back(boost::make_shared<SecurityLabelParserFactory>());
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SecurityLabelsCatalogParser> >("catalog", "urn:xmpp:sec-label:catalog:2"));
+ factories_.push_back(boost::make_shared<FormParserFactory>());
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CommandParser> >("command", "http://jabber.org/protocol/commands"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<InBandRegistrationPayloadParser> >("query", "jabber:iq:register"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<SearchPayloadParser> >("query", "jabber:iq:search"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StreamInitiationParser> >("si", "http://jabber.org/protocol/si"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<BytestreamsParser> >("query", "http://jabber.org/protocol/bytestreams"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<VCardUpdateParser> >("x", "vcard-temp:x:update"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<VCardParser> >("vCard", "vcard-temp"));
+ factories_.push_back(boost::make_shared<PrivateStorageParserFactory>(this));
+ factories_.push_back(boost::make_shared<ChatStateParserFactory>());
+ factories_.push_back(boost::make_shared<MUCUserPayloadParserFactory>(this));
+ factories_.push_back(boost::make_shared<MUCOwnerPayloadParserFactory>(this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCInvitationPayloadParser> >("x", "jabber:x:conference"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCAdminPayloadParser> >("query", "http://jabber.org/protocol/muc#admin"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#user"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#owner"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<NicknameParser> >("nick", "http://jabber.org/protocol/nick"));
+ factories_.push_back(boost::make_shared<JingleParserFactory>(this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleReasonParser> >("reason", "urn:xmpp:jingle:1"));
+ factories_.push_back(boost::make_shared<JingleContentPayloadParserFactory>(this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleIBBTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:ibb:1"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleS5BTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:s5b:1"));
+ factories_.push_back(boost::make_shared<JingleFileTransferDescriptionParserFactory>(this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<StreamInitiationFileInfoParser> >("file", "http://jabber.org/protocol/si/profile/file-transfer"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleFileTransferFileInfoParser> >("file", "urn:xmpp:jingle:apps:file-transfer:4"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<JingleFileTransferHashParser> >("checksum"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<S5BProxyRequestParser> >("query", "http://jabber.org/protocol/bytestreams"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<WhiteboardParser> >("wb", "http://swift.im/whiteboard"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<UserLocationParser> >("geoloc", "http://jabber.org/protocol/geoloc"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<UserTuneParser> >("tune", "http://jabber.org/protocol/tune"));
+ factories_.push_back(boost::make_shared<DeliveryReceiptParserFactory>());
+ factories_.push_back(boost::make_shared<DeliveryReceiptRequestParserFactory>());
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<IdleParser> >("idle", "urn:xmpp:idle:1"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubOwnerPubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub#owner", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<PubSubEventParser> >("event", "http://jabber.org/protocol/pubsub#event", this));
+ factories_.push_back(boost::make_shared<PubSubErrorParserFactory>());
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<ResultSetParser> >("set", "http://jabber.org/protocol/rsm"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<ForwardedParser> >("forwarded", "urn:xmpp:forward:0", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<MAMResultParser> >("result", "urn:xmpp:mam:0", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MAMQueryParser> >("query", "urn:xmpp:mam:0"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<MAMFinParser> >("fin", "urn:xmpp:mam:0"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<IsodeIQDelegationParser> >("delegate", "http://isode.com/iq_delegation", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsEnableParser> >("enable", "urn:xmpp:carbons:2"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsDisableParser> >("disable", "urn:xmpp:carbons:2"));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<CarbonsReceivedParser> >("received", "urn:xmpp:carbons:2", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory2<CarbonsSentParser> >("sent", "urn:xmpp:carbons:2", this));
+ factories_.push_back(boost::make_shared<GenericPayloadParserFactory<CarbonsPrivateParser> >("private", "urn:xmpp:carbons:2"));
- foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
- addFactory(factory.get());
- }
- defaultFactory_ = new RawXMLPayloadParserFactory();
- setDefaultFactory(defaultFactory_);
+ foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
+ addFactory(factory.get());
+ }
+ defaultFactory_ = new RawXMLPayloadParserFactory();
+ setDefaultFactory(defaultFactory_);
}
FullPayloadParserFactoryCollection::~FullPayloadParserFactoryCollection() {
- setDefaultFactory(NULL);
- delete defaultFactory_;
- foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
- removeFactory(factory.get());
- }
+ setDefaultFactory(NULL);
+ delete defaultFactory_;
+ foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
+ removeFactory(factory.get());
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
index 3346e47..210e85e 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
@@ -15,13 +15,13 @@
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
- class SWIFTEN_API FullPayloadParserFactoryCollection : public PayloadParserFactoryCollection {
- public:
- FullPayloadParserFactoryCollection();
- ~FullPayloadParserFactoryCollection();
+ class SWIFTEN_API FullPayloadParserFactoryCollection : public PayloadParserFactoryCollection {
+ public:
+ FullPayloadParserFactoryCollection();
+ ~FullPayloadParserFactoryCollection();
- private:
- std::vector< boost::shared_ptr<PayloadParserFactory> > factories_;
- PayloadParserFactory* defaultFactory_;
- };
+ private:
+ std::vector< boost::shared_ptr<PayloadParserFactory> > factories_;
+ PayloadParserFactory* defaultFactory_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/IBBParser.cpp b/Swiften/Parser/PayloadParsers/IBBParser.cpp
index c04e3cc..3aeb04c 100644
--- a/Swiften/Parser/PayloadParsers/IBBParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IBBParser.cpp
@@ -20,57 +20,57 @@ 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);
- }
- try {
- getPayloadInternal()->setBlockSize(boost::lexical_cast<int>(attributes.getAttribute("block-size")));
- }
- catch (boost::bad_lexical_cast&) {
- }
- }
- else if (element == "close") {
- getPayloadInternal()->setAction(IBB::Close);
- getPayloadInternal()->setStreamID(attributes.getAttribute("sid"));
- }
- }
- ++level;
+ 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);
+ }
+ try {
+ getPayloadInternal()->setBlockSize(boost::lexical_cast<int>(attributes.getAttribute("block-size")));
+ }
+ catch (boost::bad_lexical_cast&) {
+ }
+ }
+ else if (element == "close") {
+ getPayloadInternal()->setAction(IBB::Close);
+ getPayloadInternal()->setStreamID(attributes.getAttribute("sid"));
+ }
+ }
+ ++level;
}
void IBBParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (level == TopLevel) {
- if (element == "data") {
- std::vector<char> data;
- for (size_t i = 0; i < currentText.size(); ++i) {
- char c = currentText[i];
- if ((c >= 48 && c <= 122) || c == 47 || c == 43) {
- data.push_back(c);
- }
- }
- getPayloadInternal()->setData(Base64::decode(std::string(&data[0], data.size())));
- }
- }
+ --level;
+ if (level == TopLevel) {
+ if (element == "data") {
+ std::vector<char> data;
+ for (size_t i = 0; i < currentText.size(); ++i) {
+ char c = currentText[i];
+ if ((c >= 48 && c <= 122) || c == 47 || c == 43) {
+ data.push_back(c);
+ }
+ }
+ getPayloadInternal()->setData(Base64::decode(std::string(&data[0], data.size())));
+ }
+ }
}
void IBBParser::handleCharacterData(const std::string& data) {
- currentText += data;
+ currentText += data;
}
diff --git a/Swiften/Parser/PayloadParsers/IBBParser.h b/Swiften/Parser/PayloadParsers/IBBParser.h
index 95fe61a..7ef3e6f 100644
--- a/Swiften/Parser/PayloadParsers/IBBParser.h
+++ b/Swiften/Parser/PayloadParsers/IBBParser.h
@@ -13,20 +13,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API IBBParser : public GenericPayloadParser<IBB> {
- public:
- IBBParser();
- ~IBBParser();
+ class SWIFTEN_API IBBParser : public GenericPayloadParser<IBB> {
+ public:
+ IBBParser();
+ ~IBBParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0
- };
- int level;
- std::string currentText;
- };
+ private:
+ enum Level {
+ TopLevel = 0
+ };
+ int level;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/IdleParser.cpp b/Swiften/Parser/PayloadParsers/IdleParser.cpp
index 51aa34b..e985576 100644
--- a/Swiften/Parser/PayloadParsers/IdleParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IdleParser.cpp
@@ -14,15 +14,15 @@ IdleParser::IdleParser() : level_(0) {
}
void IdleParser::handleStartElement(const std::string& /*element*/, const std::string& /*ns*/, const AttributeMap& attributes) {
- if (level_ == 0) {
- boost::posix_time::ptime since = stringToDateTime(attributes.getAttribute("since"));
- getPayloadInternal()->setSince(since);
- }
- ++level_;
+ if (level_ == 0) {
+ boost::posix_time::ptime since = stringToDateTime(attributes.getAttribute("since"));
+ getPayloadInternal()->setSince(since);
+ }
+ ++level_;
}
void IdleParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
+ --level_;
}
void IdleParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/IdleParser.h b/Swiften/Parser/PayloadParsers/IdleParser.h
index d8bbd1d..c1922c0 100644
--- a/Swiften/Parser/PayloadParsers/IdleParser.h
+++ b/Swiften/Parser/PayloadParsers/IdleParser.h
@@ -17,15 +17,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API IdleParser : public GenericPayloadParser<Idle> {
- public:
- IdleParser();
+ class SWIFTEN_API IdleParser : public GenericPayloadParser<Idle> {
+ public:
+ IdleParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp b/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp
index d29fa73..b019626 100644
--- a/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp
@@ -14,118 +14,118 @@
namespace Swift {
InBandRegistrationPayloadParser::InBandRegistrationPayloadParser() : level(TopLevel), formParser(NULL) {
- formParserFactory = new FormParserFactory();
+ formParserFactory = new FormParserFactory();
}
InBandRegistrationPayloadParser::~InBandRegistrationPayloadParser() {
- delete formParserFactory;
+ delete formParserFactory;
}
void InBandRegistrationPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == TopLevel) {
- }
- else if (level == PayloadLevel) {
- if (element == "x" && ns == "jabber:x:data") {
- assert(!formParser);
- formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
- }
- else {
- currentText.clear();
- }
- }
+ if (level == TopLevel) {
+ }
+ else if (level == PayloadLevel) {
+ if (element == "x" && ns == "jabber:x:data") {
+ assert(!formParser);
+ formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
+ }
+ else {
+ currentText.clear();
+ }
+ }
- if (formParser) {
- formParser->handleStartElement(element, ns, attributes);
- }
+ if (formParser) {
+ formParser->handleStartElement(element, ns, attributes);
+ }
- ++level;
+ ++level;
}
void InBandRegistrationPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
+ --level;
- if (formParser) {
- formParser->handleEndElement(element, ns);
- }
+ if (formParser) {
+ formParser->handleEndElement(element, ns);
+ }
- if (level == TopLevel) {
- }
- else if (level == PayloadLevel) {
- if (formParser) {
- getPayloadInternal()->setForm(formParser->getPayloadInternal());
- delete formParser;
- formParser = NULL;
- }
- else if (element == "registered") {
- getPayloadInternal()->setRegistered(true);
- }
- else if (element == "remove") {
- getPayloadInternal()->setRemove(true);
- }
- else if (element == "instructions") {
- getPayloadInternal()->setInstructions(currentText);
- }
- else if (element == "username") {
- getPayloadInternal()->setUsername(currentText);
- }
- else if (element == "nick") {
- getPayloadInternal()->setNick(currentText);
- }
- else if (element == "password") {
- getPayloadInternal()->setPassword(currentText);
- }
- else if (element == "name") {
- getPayloadInternal()->setName(currentText);
- }
- else if (element == "first") {
- getPayloadInternal()->setFirst(currentText);
- }
- else if (element == "last") {
- getPayloadInternal()->setLast(currentText);
- }
- else if (element == "email") {
- getPayloadInternal()->setEMail(currentText);
- }
- else if (element == "address") {
- getPayloadInternal()->setAddress(currentText);
- }
- else if (element == "city") {
- getPayloadInternal()->setCity(currentText);
- }
- else if (element == "state") {
- getPayloadInternal()->setState(currentText);
- }
- else if (element == "zip") {
- getPayloadInternal()->setZip(currentText);
- }
- else if (element == "phone") {
- getPayloadInternal()->setPhone(currentText);
- }
- else if (element == "url") {
- getPayloadInternal()->setURL(currentText);
- }
- else if (element == "date") {
- getPayloadInternal()->setDate(currentText);
- }
- else if (element == "misc") {
- getPayloadInternal()->setMisc(currentText);
- }
- else if (element == "text") {
- getPayloadInternal()->setText(currentText);
- }
- else if (element == "key") {
- getPayloadInternal()->setKey(currentText);
- }
- }
+ if (level == TopLevel) {
+ }
+ else if (level == PayloadLevel) {
+ if (formParser) {
+ getPayloadInternal()->setForm(formParser->getPayloadInternal());
+ delete formParser;
+ formParser = NULL;
+ }
+ else if (element == "registered") {
+ getPayloadInternal()->setRegistered(true);
+ }
+ else if (element == "remove") {
+ getPayloadInternal()->setRemove(true);
+ }
+ else if (element == "instructions") {
+ getPayloadInternal()->setInstructions(currentText);
+ }
+ else if (element == "username") {
+ getPayloadInternal()->setUsername(currentText);
+ }
+ else if (element == "nick") {
+ getPayloadInternal()->setNick(currentText);
+ }
+ else if (element == "password") {
+ getPayloadInternal()->setPassword(currentText);
+ }
+ else if (element == "name") {
+ getPayloadInternal()->setName(currentText);
+ }
+ else if (element == "first") {
+ getPayloadInternal()->setFirst(currentText);
+ }
+ else if (element == "last") {
+ getPayloadInternal()->setLast(currentText);
+ }
+ else if (element == "email") {
+ getPayloadInternal()->setEMail(currentText);
+ }
+ else if (element == "address") {
+ getPayloadInternal()->setAddress(currentText);
+ }
+ else if (element == "city") {
+ getPayloadInternal()->setCity(currentText);
+ }
+ else if (element == "state") {
+ getPayloadInternal()->setState(currentText);
+ }
+ else if (element == "zip") {
+ getPayloadInternal()->setZip(currentText);
+ }
+ else if (element == "phone") {
+ getPayloadInternal()->setPhone(currentText);
+ }
+ else if (element == "url") {
+ getPayloadInternal()->setURL(currentText);
+ }
+ else if (element == "date") {
+ getPayloadInternal()->setDate(currentText);
+ }
+ else if (element == "misc") {
+ getPayloadInternal()->setMisc(currentText);
+ }
+ else if (element == "text") {
+ getPayloadInternal()->setText(currentText);
+ }
+ else if (element == "key") {
+ getPayloadInternal()->setKey(currentText);
+ }
+ }
}
void InBandRegistrationPayloadParser::handleCharacterData(const std::string& data) {
- if (formParser) {
- formParser->handleCharacterData(data);
- }
- else {
- currentText += data;
- }
+ if (formParser) {
+ formParser->handleCharacterData(data);
+ }
+ else {
+ currentText += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h b/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h
index cd8c452..7e2a4a4 100644
--- a/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h
@@ -13,26 +13,26 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class FormParserFactory;
- class FormParser;
+ class FormParserFactory;
+ class FormParser;
- class SWIFTEN_API InBandRegistrationPayloadParser : public GenericPayloadParser<InBandRegistrationPayload> {
- public:
- InBandRegistrationPayloadParser();
- ~InBandRegistrationPayloadParser();
+ class SWIFTEN_API InBandRegistrationPayloadParser : public GenericPayloadParser<InBandRegistrationPayload> {
+ public:
+ InBandRegistrationPayloadParser();
+ ~InBandRegistrationPayloadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level;
- FormParserFactory* formParserFactory;
- FormParser* formParser;
- std::string currentText;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level;
+ FormParserFactory* formParserFactory;
+ FormParser* formParser;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp
index 483654a..6bdd517 100644
--- a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp
@@ -24,36 +24,36 @@ IsodeIQDelegationParser::~IsodeIQDelegationParser() {
}
void IsodeIQDelegationParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
-
- if (level == 1) {
- if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
- currentPayloadParser.reset(factory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+
+
+ if (level == 1) {
+ if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
+ currentPayloadParser.reset(factory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void IsodeIQDelegationParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- getPayloadInternal()->setForward(boost::dynamic_pointer_cast<Forwarded>(currentPayloadParser->getPayload()));
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ getPayloadInternal()->setForward(boost::dynamic_pointer_cast<Forwarded>(currentPayloadParser->getPayload()));
+ currentPayloadParser.reset();
+ }
+ }
}
void IsodeIQDelegationParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h
index 6115761..cf86a1a 100644
--- a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h
+++ b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API IsodeIQDelegationParser : public GenericPayloadParser<IsodeIQDelegation> {
- public:
- IsodeIQDelegationParser(PayloadParserFactoryCollection* parsers);
- virtual ~IsodeIQDelegationParser();
+ class SWIFTEN_API IsodeIQDelegationParser : public GenericPayloadParser<IsodeIQDelegation> {
+ public:
+ IsodeIQDelegationParser(PayloadParserFactoryCollection* parsers);
+ virtual ~IsodeIQDelegationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
index e6eecd7..30404f3 100644
--- a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
@@ -18,63 +18,63 @@
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
- JingleContentPayloadParser::JingleContentPayloadParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
-
- }
-
- void JingleContentPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- std::string creator = attributes.getAttributeValue("creator").get_value_or("");
- if (creator == "initiator") {
- getPayloadInternal()->setCreator(JingleContentPayload::InitiatorCreator);
- } else if (creator == "responder") {
- getPayloadInternal()->setCreator(JingleContentPayload::ResponderCreator);
- } else {
- getPayloadInternal()->setCreator(JingleContentPayload::UnknownCreator);
- }
-
- getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
- }
-
- if (level == 1) {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
-
- ++level;
- }
-
- void JingleContentPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
-
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- boost::shared_ptr<JingleTransportPayload> transport = boost::dynamic_pointer_cast<JingleTransportPayload>(currentPayloadParser->getPayload());
- if (transport) {
- getPayloadInternal()->addTransport(transport);
- }
-
- boost::shared_ptr<JingleDescription> description = boost::dynamic_pointer_cast<JingleDescription>(currentPayloadParser->getPayload());
- if (description) {
- getPayloadInternal()->addDescription(description);
- }
- }
- }
- }
-
- void JingleContentPayloadParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
- }
+ JingleContentPayloadParser::JingleContentPayloadParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
+
+ }
+
+ void JingleContentPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level == 0) {
+ std::string creator = attributes.getAttributeValue("creator").get_value_or("");
+ if (creator == "initiator") {
+ getPayloadInternal()->setCreator(JingleContentPayload::InitiatorCreator);
+ } else if (creator == "responder") {
+ getPayloadInternal()->setCreator(JingleContentPayload::ResponderCreator);
+ } else {
+ getPayloadInternal()->setCreator(JingleContentPayload::UnknownCreator);
+ }
+
+ getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
+ }
+
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+ }
+
+ void JingleContentPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
+ --level;
+
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ boost::shared_ptr<JingleTransportPayload> transport = boost::dynamic_pointer_cast<JingleTransportPayload>(currentPayloadParser->getPayload());
+ if (transport) {
+ getPayloadInternal()->addTransport(transport);
+ }
+
+ boost::shared_ptr<JingleDescription> description = boost::dynamic_pointer_cast<JingleDescription>(currentPayloadParser->getPayload());
+ if (description) {
+ getPayloadInternal()->addDescription(description);
+ }
+ }
+ }
+ }
+
+ void JingleContentPayloadParser::handleCharacterData(const std::string& data) {
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
index 977d2eb..eaa8ff6 100644
--- a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
@@ -21,17 +21,17 @@ namespace Swift {
class PayloadParserFactoryCollection;
class SWIFTEN_API JingleContentPayloadParser : public GenericPayloadParser<JingleContentPayload> {
- public:
- JingleContentPayloadParser(PayloadParserFactoryCollection* factories);
+ public:
+ JingleContentPayloadParser(PayloadParserFactoryCollection* factories);
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- PayloadParserFactoryCollection* factories;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h
index b343c24..8e9741d 100644
--- a/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h
@@ -17,26 +17,26 @@
#include <Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h>
namespace Swift {
-
- class PayloadParserFactoryCollection;
-
- class SWIFTEN_API JingleContentPayloadParserFactory : public PayloadParserFactory {
- public:
- JingleContentPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
-
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "content" && ns == "urn:xmpp:jingle:1";
- }
-
- virtual PayloadParser* createPayloadParser() {
- return new JingleContentPayloadParser(factories);
- }
-
- private:
- PayloadParserFactoryCollection* factories;
-
- };
+
+ class PayloadParserFactoryCollection;
+
+ class SWIFTEN_API JingleContentPayloadParserFactory : public PayloadParserFactory {
+ public:
+ JingleContentPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "content" && ns == "urn:xmpp:jingle:1";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleContentPayloadParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
index 0e4e636..32a6e4c 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
@@ -26,37 +26,37 @@ JingleFileTransferDescriptionParser::JingleFileTransferDescriptionParser(Payload
}
void JingleFileTransferDescriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 1) {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void JingleFileTransferDescriptionParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 0) {
- boost::shared_ptr<JingleFileTransferFileInfo> info = boost::dynamic_pointer_cast<JingleFileTransferFileInfo>(currentPayloadParser->getPayload());
- if (info) {
- getPayloadInternal()->setFileInfo(*info);
- }
- }
+ --level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 0) {
+ boost::shared_ptr<JingleFileTransferFileInfo> info = boost::dynamic_pointer_cast<JingleFileTransferFileInfo>(currentPayloadParser->getPayload());
+ if (info) {
+ getPayloadInternal()->setFileInfo(*info);
+ }
+ }
}
void JingleFileTransferDescriptionParser::handleCharacterData(const std::string& data) {
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
index 52dd232..c7f80e1 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
@@ -22,17 +22,17 @@ namespace Swift {
class PayloadParserFactoryCollection;
class SWIFTEN_API JingleFileTransferDescriptionParser : public GenericPayloadParser<JingleFileTransferDescription> {
- public:
- JingleFileTransferDescriptionParser(PayloadParserFactoryCollection* factories);
+ public:
+ JingleFileTransferDescriptionParser(PayloadParserFactoryCollection* factories);
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- PayloadParserFactoryCollection* factories;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h
index f8a340c..c75125f 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h
@@ -17,26 +17,26 @@
#include <Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h>
namespace Swift {
-
- class PayloadParserFactoryCollection;
-
- class SWIFTEN_API JingleFileTransferDescriptionParserFactory : public PayloadParserFactory {
- public:
- JingleFileTransferDescriptionParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
-
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "description" && ns == "urn:xmpp:jingle:apps:file-transfer:4";
- }
-
- virtual PayloadParser* createPayloadParser() {
- return new JingleFileTransferDescriptionParser(factories);
- }
-
- private:
- PayloadParserFactoryCollection* factories;
-
- };
+
+ class PayloadParserFactoryCollection;
+
+ class SWIFTEN_API JingleFileTransferDescriptionParserFactory : public PayloadParserFactory {
+ public:
+ JingleFileTransferDescriptionParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "description" && ns == "urn:xmpp:jingle:apps:file-transfer:4";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleFileTransferDescriptionParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp
index 51c13e9..4f8b9a9 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp
@@ -14,66 +14,66 @@
namespace Swift {
-JingleFileTransferFileInfoParser::JingleFileTransferFileInfoParser() : level(0) {
+JingleFileTransferFileInfoParser::JingleFileTransferFileInfoParser() : level(0) {
}
template<typename T> boost::optional<T> safeLexicalCast(const std::string& str) {
- boost::optional<T> ret;
- try {
- ret = boost::lexical_cast<T>(str);
- } catch (boost::bad_lexical_cast &) {
+ boost::optional<T> ret;
+ try {
+ ret = boost::lexical_cast<T>(str);
+ } catch (boost::bad_lexical_cast &) {
- }
- return ret;
+ }
+ return ret;
}
void JingleFileTransferFileInfoParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- charData.clear();
- if (element == "hash") {
- hashAlg = attributes.getAttributeValue("algo").get_value_or("");
- }
- else if (element == "range") {
- rangeOffset = safeLexicalCast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or(""));
- }
+ charData.clear();
+ if (element == "hash") {
+ hashAlg = attributes.getAttributeValue("algo").get_value_or("");
+ }
+ else if (element == "range") {
+ rangeOffset = safeLexicalCast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or(""));
+ }
- ++level;
+ ++level;
}
void JingleFileTransferFileInfoParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (level == 1) {
- if (element == "date") {
- getPayloadInternal()->setDate(stringToDateTime(charData));
- }
- else if (element == "desc") {
- getPayloadInternal()->setDescription(charData);
- }
- else if (element == "media-type") {
- getPayloadInternal()->setMediaType(charData);
- }
- else if (element == "name") {
- getPayloadInternal()->setName(charData);
- }
- else if (element == "size") {
- boost::optional<boost::uintmax_t> size = safeLexicalCast<boost::uintmax_t>(charData);
- if (size) {
- getPayloadInternal()->setSize(size.get());
- }
- }
- else if (element == "range") {
- getPayloadInternal()->setSupportsRangeRequests(true);
- if (rangeOffset) {
- getPayloadInternal()->setRangeOffset(rangeOffset.get_value_or(0));
- }
- }
- else if (element == "hash") {
- getPayloadInternal()->addHash(HashElement(hashAlg, Base64::decode(charData)));
- }
- }
+ --level;
+ if (level == 1) {
+ if (element == "date") {
+ getPayloadInternal()->setDate(stringToDateTime(charData));
+ }
+ else if (element == "desc") {
+ getPayloadInternal()->setDescription(charData);
+ }
+ else if (element == "media-type") {
+ getPayloadInternal()->setMediaType(charData);
+ }
+ else if (element == "name") {
+ getPayloadInternal()->setName(charData);
+ }
+ else if (element == "size") {
+ boost::optional<boost::uintmax_t> size = safeLexicalCast<boost::uintmax_t>(charData);
+ if (size) {
+ getPayloadInternal()->setSize(size.get());
+ }
+ }
+ else if (element == "range") {
+ getPayloadInternal()->setSupportsRangeRequests(true);
+ if (rangeOffset) {
+ getPayloadInternal()->setRangeOffset(rangeOffset.get_value_or(0));
+ }
+ }
+ else if (element == "hash") {
+ getPayloadInternal()->addHash(HashElement(hashAlg, Base64::decode(charData)));
+ }
+ }
}
void JingleFileTransferFileInfoParser::handleCharacterData(const std::string& data) {
- charData += data;
+ charData += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h
index e49ee69..237f105 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h
@@ -13,18 +13,18 @@
namespace Swift {
class SWIFTEN_API JingleFileTransferFileInfoParser : public GenericPayloadParser<JingleFileTransferFileInfo> {
- public:
- JingleFileTransferFileInfoParser();
+ public:
+ JingleFileTransferFileInfoParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
-
- private:
- int level;
- std::string charData;
- std::string hashAlg;
- boost::optional<boost::uintmax_t> rangeOffset;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ int level;
+ std::string charData;
+ std::string hashAlg;
+ boost::optional<boost::uintmax_t> rangeOffset;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
index 7c6c0d4..a890a99 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
@@ -23,36 +23,36 @@ namespace Swift {
JingleFileTransferHashParser::JingleFileTransferHashParser() : level(0) {
}
-
+
void JingleFileTransferHashParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 1 && element == "file") {
- currentPayloadParser = boost::make_shared<JingleFileTransferFileInfoParser>();
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1 && element == "file") {
+ currentPayloadParser = boost::make_shared<JingleFileTransferFileInfoParser>();
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void JingleFileTransferHashParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- boost::shared_ptr<JingleFileTransferFileInfo> info = boost::dynamic_pointer_cast<JingleFileTransferFileInfo>(currentPayloadParser->getPayload());
- if (info) {
- getPayloadInternal()->setFileInfo(*info);
- }
- }
+ --level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ boost::shared_ptr<JingleFileTransferFileInfo> info = boost::dynamic_pointer_cast<JingleFileTransferFileInfo>(currentPayloadParser->getPayload());
+ if (info) {
+ getPayloadInternal()->setFileInfo(*info);
+ }
+ }
}
void JingleFileTransferHashParser::handleCharacterData(const std::string& data) {
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
index 15d3294..8a28d5a 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
@@ -20,15 +20,15 @@ namespace Swift {
class SWIFTEN_API JingleFileTransferHashParser : public GenericPayloadParser<JingleFileTransferHash> {
public:
- JingleFileTransferHashParser();
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
-
+ JingleFileTransferHashParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
private:
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
index e446575..438420b 100644
--- a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
@@ -18,30 +18,30 @@
#include <Swiften/Base/Log.h>
namespace Swift {
- JingleIBBTransportMethodPayloadParser::JingleIBBTransportMethodPayloadParser() : level(0) {
-
- }
-
- void JingleIBBTransportMethodPayloadParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- try {
- boost::optional<std::string> blockSize = attributes.getAttributeValue("block-size");
- if (blockSize) {
- getPayloadInternal()->setBlockSize(boost::lexical_cast<unsigned int>(*blockSize));
- }
- }
- catch (boost::bad_lexical_cast &) {
- }
- getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
- ++level;
- }
-
- void JingleIBBTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
- --level;
-
-
- }
-
- void JingleIBBTransportMethodPayloadParser::handleCharacterData(const std::string&) {
-
- }
+ JingleIBBTransportMethodPayloadParser::JingleIBBTransportMethodPayloadParser() : level(0) {
+
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
+ try {
+ boost::optional<std::string> blockSize = attributes.getAttributeValue("block-size");
+ if (blockSize) {
+ getPayloadInternal()->setBlockSize(boost::lexical_cast<unsigned int>(*blockSize));
+ }
+ }
+ catch (boost::bad_lexical_cast &) {
+ }
+ getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ ++level;
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
+ --level;
+
+
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleCharacterData(const std::string&) {
+
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h
index 4e22943..e406b9f 100644
--- a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h
@@ -19,15 +19,15 @@
namespace Swift {
class SWIFTEN_API JingleIBBTransportMethodPayloadParser : public GenericPayloadParser<JingleIBBTransportPayload> {
- public:
- JingleIBBTransportMethodPayloadParser();
+ public:
+ JingleIBBTransportMethodPayloadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level;
+ private:
+ int level;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleParser.cpp b/Swiften/Parser/PayloadParsers/JingleParser.cpp
index 21f415b..48507af 100644
--- a/Swiften/Parser/PayloadParsers/JingleParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleParser.cpp
@@ -21,100 +21,100 @@
namespace Swift {
- JingleParser::JingleParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
-
- }
-
- void JingleParser::handleStartElement(const std::string& element, const std::string &ns, const AttributeMap& attributes) {
- if (level == 0) {
- // <jingle > tag
- JinglePayload::ref payload = getPayloadInternal();
- payload->setAction(stringToAction(attributes.getAttributeValue("action").get_value_or("")));
- payload->setInitiator(JID(attributes.getAttributeValue("initiator").get_value_or("")));
- payload->setResponder(JID(attributes.getAttributeValue("responder").get_value_or("")));
- payload->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
- }
-
- if (level == 1) {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
-
- ++level;
- }
-
- void JingleParser::handleEndElement(const std::string& element, const std::string &ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- boost::shared_ptr<JinglePayload::Reason> reason = boost::dynamic_pointer_cast<JinglePayload::Reason>(currentPayloadParser->getPayload());
- if (reason) {
- getPayloadInternal()->setReason(*reason);
- }
-
- boost::shared_ptr<JingleContentPayload> payload = boost::dynamic_pointer_cast<JingleContentPayload>(currentPayloadParser->getPayload());
- if (payload) {
- getPayloadInternal()->addContent(payload);
- }
-
- boost::shared_ptr<JingleFileTransferHash> hash = boost::dynamic_pointer_cast<JingleFileTransferHash>(currentPayloadParser->getPayload());
- if (hash) {
- getPayloadInternal()->addPayload(hash);
- }
- }
- }
- }
-
- void JingleParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
- }
-
- JinglePayload::Action JingleParser::stringToAction(const std::string &str) const {
- if (str == "content-accept") {
- return JinglePayload::ContentAccept;
- } else if (str == "content-add") {
- return JinglePayload::ContentAdd;
- } else if (str == "content-modify") {
- return JinglePayload::ContentModify;
- } else if (str == "content-reject") {
- return JinglePayload::ContentReject;
- } else if (str == "content-remove") {
- return JinglePayload::ContentRemove;
- } else if (str == "description-info") {
- return JinglePayload::DescriptionInfo;
- } else if (str == "security-info") {
- return JinglePayload::SecurityInfo;
- } else if (str == "session-accept") {
- return JinglePayload::SessionAccept;
- } else if (str == "session-info") {
- return JinglePayload::SessionInfo;
- } else if (str == "session-initiate") {
- return JinglePayload::SessionInitiate;
- } else if (str == "session-terminate") {
- return JinglePayload::SessionTerminate;
- } else if (str == "transport-accept") {
- return JinglePayload::TransportAccept;
- } else if (str == "transport-info") {
- return JinglePayload::TransportInfo;
- } else if (str == "transport-reject") {
- return JinglePayload::TransportReject;
- } else if (str == "transport-replace") {
- return JinglePayload::TransportReplace;
- } else {
- return JinglePayload::UnknownAction;
- }
-
- }
+ JingleParser::JingleParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
+
+ }
+
+ void JingleParser::handleStartElement(const std::string& element, const std::string &ns, const AttributeMap& attributes) {
+ if (level == 0) {
+ // <jingle > tag
+ JinglePayload::ref payload = getPayloadInternal();
+ payload->setAction(stringToAction(attributes.getAttributeValue("action").get_value_or("")));
+ payload->setInitiator(JID(attributes.getAttributeValue("initiator").get_value_or("")));
+ payload->setResponder(JID(attributes.getAttributeValue("responder").get_value_or("")));
+ payload->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ }
+
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+ }
+
+ void JingleParser::handleEndElement(const std::string& element, const std::string &ns) {
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ boost::shared_ptr<JinglePayload::Reason> reason = boost::dynamic_pointer_cast<JinglePayload::Reason>(currentPayloadParser->getPayload());
+ if (reason) {
+ getPayloadInternal()->setReason(*reason);
+ }
+
+ boost::shared_ptr<JingleContentPayload> payload = boost::dynamic_pointer_cast<JingleContentPayload>(currentPayloadParser->getPayload());
+ if (payload) {
+ getPayloadInternal()->addContent(payload);
+ }
+
+ boost::shared_ptr<JingleFileTransferHash> hash = boost::dynamic_pointer_cast<JingleFileTransferHash>(currentPayloadParser->getPayload());
+ if (hash) {
+ getPayloadInternal()->addPayload(hash);
+ }
+ }
+ }
+ }
+
+ void JingleParser::handleCharacterData(const std::string& data) {
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+ }
+
+ JinglePayload::Action JingleParser::stringToAction(const std::string &str) const {
+ if (str == "content-accept") {
+ return JinglePayload::ContentAccept;
+ } else if (str == "content-add") {
+ return JinglePayload::ContentAdd;
+ } else if (str == "content-modify") {
+ return JinglePayload::ContentModify;
+ } else if (str == "content-reject") {
+ return JinglePayload::ContentReject;
+ } else if (str == "content-remove") {
+ return JinglePayload::ContentRemove;
+ } else if (str == "description-info") {
+ return JinglePayload::DescriptionInfo;
+ } else if (str == "security-info") {
+ return JinglePayload::SecurityInfo;
+ } else if (str == "session-accept") {
+ return JinglePayload::SessionAccept;
+ } else if (str == "session-info") {
+ return JinglePayload::SessionInfo;
+ } else if (str == "session-initiate") {
+ return JinglePayload::SessionInitiate;
+ } else if (str == "session-terminate") {
+ return JinglePayload::SessionTerminate;
+ } else if (str == "transport-accept") {
+ return JinglePayload::TransportAccept;
+ } else if (str == "transport-info") {
+ return JinglePayload::TransportInfo;
+ } else if (str == "transport-reject") {
+ return JinglePayload::TransportReject;
+ } else if (str == "transport-replace") {
+ return JinglePayload::TransportReplace;
+ } else {
+ return JinglePayload::UnknownAction;
+ }
+
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/JingleParser.h b/Swiften/Parser/PayloadParsers/JingleParser.h
index ad49e96..28850e2 100644
--- a/Swiften/Parser/PayloadParsers/JingleParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleParser.h
@@ -20,20 +20,20 @@
namespace Swift {
class SWIFTEN_API JingleParser : public GenericPayloadParser<JinglePayload> {
- public:
- JingleParser(PayloadParserFactoryCollection* factories);
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
-
- private:
- JinglePayload::Action stringToAction(const std::string &str) const;
-
- private:
- PayloadParserFactoryCollection* factories;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
+ public:
+ JingleParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ JinglePayload::Action stringToAction(const std::string &str) const;
+
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleParserFactory.h b/Swiften/Parser/PayloadParsers/JingleParserFactory.h
index 73395fc..5f9b45b 100644
--- a/Swiften/Parser/PayloadParsers/JingleParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/JingleParserFactory.h
@@ -17,26 +17,26 @@
#include <Swiften/Parser/PayloadParsers/JingleParser.h>
namespace Swift {
-
- class PayloadParserFactoryCollection;
-
- class SWIFTEN_API JingleParserFactory : public PayloadParserFactory {
- public:
- JingleParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
-
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "jingle" && ns == "urn:xmpp:jingle:1";
- }
-
- virtual PayloadParser* createPayloadParser() {
- return new JingleParser(factories);
- }
-
- private:
- PayloadParserFactoryCollection* factories;
-
- };
+
+ class PayloadParserFactoryCollection;
+
+ class SWIFTEN_API JingleParserFactory : public PayloadParserFactory {
+ public:
+ JingleParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "jingle" && ns == "urn:xmpp:jingle:1";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp b/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
index d144cbd..9a81e5f 100644
--- a/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
@@ -15,73 +15,73 @@
#include <Swiften/Base/Log.h>
namespace Swift {
- JingleReasonParser::JingleReasonParser() : level(0), parseText(false) {
-
- }
-
- void JingleReasonParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
- if (level == 1) {
- if (element == "text") {
- parseText = true;
- } else {
- // reason type
- getPayloadInternal()->type = stringToReasonType(element);
- }
- }
- ++level;
- }
-
- void JingleReasonParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (element == "text") {
- parseText = false;
- getPayloadInternal()->text = text;
- }
- }
-
- void JingleReasonParser::handleCharacterData(const std::string& data) {
- if (parseText) {
- text += data;
- }
- }
-
- JinglePayload::Reason::Type JingleReasonParser::stringToReasonType(const std::string& type) const {
- if (type == "alternative-session") {
- return JinglePayload::Reason::AlternativeSession;
- } else if (type == "busy") {
- return JinglePayload::Reason::Busy;
- } else if (type == "cancel") {
- return JinglePayload::Reason::Cancel;
- } else if (type == "connectivity-error") {
- return JinglePayload::Reason::ConnectivityError;
- } else if (type == "decline") {
- return JinglePayload::Reason::Decline;
- } else if (type == "expired") {
- return JinglePayload::Reason::Expired;
- } else if (type == "failed-application") {
- return JinglePayload::Reason::FailedApplication;
- } else if (type == "failed-transport") {
- return JinglePayload::Reason::FailedTransport;
- } else if (type == "general-error") {
- return JinglePayload::Reason::GeneralError;
- } else if (type == "gone") {
- return JinglePayload::Reason::Gone;
- } else if (type == "incompatible-parameters") {
- return JinglePayload::Reason::IncompatibleParameters;
- } else if (type == "media-error") {
- return JinglePayload::Reason::MediaError;
- } else if (type == "security-error") {
- return JinglePayload::Reason::SecurityError;
- } else if (type == "success") {
- return JinglePayload::Reason::Success;
- } else if (type == "timeout") {
- return JinglePayload::Reason::Timeout;
- } else if (type == "unsupported-applications") {
- return JinglePayload::Reason::UnsupportedApplications;
- } else if (type == "unsupported-transports") {
- return JinglePayload::Reason::UnsupportedTransports;
- } else {
- return JinglePayload::Reason::UnknownType;
- }
- }
+ JingleReasonParser::JingleReasonParser() : level(0), parseText(false) {
+
+ }
+
+ void JingleReasonParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
+ if (level == 1) {
+ if (element == "text") {
+ parseText = true;
+ } else {
+ // reason type
+ getPayloadInternal()->type = stringToReasonType(element);
+ }
+ }
+ ++level;
+ }
+
+ void JingleReasonParser::handleEndElement(const std::string& element, const std::string&) {
+ --level;
+ if (element == "text") {
+ parseText = false;
+ getPayloadInternal()->text = text;
+ }
+ }
+
+ void JingleReasonParser::handleCharacterData(const std::string& data) {
+ if (parseText) {
+ text += data;
+ }
+ }
+
+ JinglePayload::Reason::Type JingleReasonParser::stringToReasonType(const std::string& type) const {
+ if (type == "alternative-session") {
+ return JinglePayload::Reason::AlternativeSession;
+ } else if (type == "busy") {
+ return JinglePayload::Reason::Busy;
+ } else if (type == "cancel") {
+ return JinglePayload::Reason::Cancel;
+ } else if (type == "connectivity-error") {
+ return JinglePayload::Reason::ConnectivityError;
+ } else if (type == "decline") {
+ return JinglePayload::Reason::Decline;
+ } else if (type == "expired") {
+ return JinglePayload::Reason::Expired;
+ } else if (type == "failed-application") {
+ return JinglePayload::Reason::FailedApplication;
+ } else if (type == "failed-transport") {
+ return JinglePayload::Reason::FailedTransport;
+ } else if (type == "general-error") {
+ return JinglePayload::Reason::GeneralError;
+ } else if (type == "gone") {
+ return JinglePayload::Reason::Gone;
+ } else if (type == "incompatible-parameters") {
+ return JinglePayload::Reason::IncompatibleParameters;
+ } else if (type == "media-error") {
+ return JinglePayload::Reason::MediaError;
+ } else if (type == "security-error") {
+ return JinglePayload::Reason::SecurityError;
+ } else if (type == "success") {
+ return JinglePayload::Reason::Success;
+ } else if (type == "timeout") {
+ return JinglePayload::Reason::Timeout;
+ } else if (type == "unsupported-applications") {
+ return JinglePayload::Reason::UnsupportedApplications;
+ } else if (type == "unsupported-transports") {
+ return JinglePayload::Reason::UnsupportedTransports;
+ } else {
+ return JinglePayload::Reason::UnknownType;
+ }
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/JingleReasonParser.h b/Swiften/Parser/PayloadParsers/JingleReasonParser.h
index 4fe334e..a445448 100644
--- a/Swiften/Parser/PayloadParsers/JingleReasonParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleReasonParser.h
@@ -19,19 +19,19 @@
namespace Swift {
class SWIFTEN_API JingleReasonParser : public GenericPayloadParser<JinglePayload::Reason> {
- public:
- JingleReasonParser();
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
- private:
- JinglePayload::Reason::Type stringToReasonType(const std::string& type) const;
-
- private:
- int level;
- bool parseText;
- std::string text;
+ public:
+ JingleReasonParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+ private:
+ JinglePayload::Reason::Type stringToReasonType(const std::string& type) const;
+
+ private:
+ int level;
+ bool parseText;
+ std::string text;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
index 4a7e6c1..859dcec 100644
--- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
@@ -18,78 +18,78 @@
#include <Swiften/Base/Log.h>
namespace Swift {
- JingleS5BTransportMethodPayloadParser::JingleS5BTransportMethodPayloadParser() : level(0) {
-
- }
-
- void JingleS5BTransportMethodPayloadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level == 0) {
- getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
- std::string mode = attributes.getAttributeValue("mode").get_value_or("tcp");
- if (mode == "tcp") {
- getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
- } else if(mode == "udp") {
- getPayloadInternal()->setMode(JingleS5BTransportPayload::UDPMode);
- } else {
- SWIFT_LOG(warning) << "Unknown S5B mode; falling back to defaul!";
- getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
- }
- getPayloadInternal()->setDstAddr(attributes.getAttributeValue("dstaddr").get_value_or(""));
- } else if (level == 1) {
- if (element == "candidate") {
- JingleS5BTransportPayload::Candidate candidate;
- candidate.cid = attributes.getAttributeValue("cid").get_value_or("");
-
- int port = -1;
- try {
- port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1"));
- } catch(boost::bad_lexical_cast &) { }
- candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port);
- candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or(""));
- int priority = -1;
- try {
- priority = boost::lexical_cast<int>(attributes.getAttributeValue("priority").get_value_or("-1"));
- } catch(boost::bad_lexical_cast &) { }
- candidate.priority = priority;
- candidate.type = stringToType(attributes.getAttributeValue("type").get_value_or("direct"));
-
- getPayloadInternal()->addCandidate(candidate);
- } else if (element == "candidate-used") {
- getPayloadInternal()->setCandidateUsed(attributes.getAttributeValue("cid").get_value_or(""));
- } else if (element == "candidate-error") {
- getPayloadInternal()->setCandidateError(true);
- } else if (element == "activated") {
- getPayloadInternal()->setActivated(attributes.getAttributeValue("cid").get_value_or(""));
- } else if (element == "proxy-error") {
- getPayloadInternal()->setProxyError(true);
- }
- }
-
- ++level;
- }
-
- void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
- --level;
-
-
- }
-
- void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) {
-
- }
-
- JingleS5BTransportPayload::Candidate::Type JingleS5BTransportMethodPayloadParser::stringToType(const std::string &str) const {
- if (str == "direct") {
- return JingleS5BTransportPayload::Candidate::DirectType;
- } else if (str == "assisted") {
- return JingleS5BTransportPayload::Candidate::AssistedType;
- } else if (str == "tunnel") {
- return JingleS5BTransportPayload::Candidate::TunnelType;
- } else if (str == "proxy") {
- return JingleS5BTransportPayload::Candidate::ProxyType;
- } else {
- SWIFT_LOG(warning) << "Unknown candidate type; falling back to default!";
- return JingleS5BTransportPayload::Candidate::DirectType;
- }
- }
+ JingleS5BTransportMethodPayloadParser::JingleS5BTransportMethodPayloadParser() : level(0) {
+
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (level == 0) {
+ getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ std::string mode = attributes.getAttributeValue("mode").get_value_or("tcp");
+ if (mode == "tcp") {
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
+ } else if(mode == "udp") {
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::UDPMode);
+ } else {
+ SWIFT_LOG(warning) << "Unknown S5B mode; falling back to defaul!";
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
+ }
+ getPayloadInternal()->setDstAddr(attributes.getAttributeValue("dstaddr").get_value_or(""));
+ } else if (level == 1) {
+ if (element == "candidate") {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.cid = attributes.getAttributeValue("cid").get_value_or("");
+
+ int port = -1;
+ try {
+ port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1"));
+ } catch(boost::bad_lexical_cast &) { }
+ candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port);
+ candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or(""));
+ int priority = -1;
+ try {
+ priority = boost::lexical_cast<int>(attributes.getAttributeValue("priority").get_value_or("-1"));
+ } catch(boost::bad_lexical_cast &) { }
+ candidate.priority = priority;
+ candidate.type = stringToType(attributes.getAttributeValue("type").get_value_or("direct"));
+
+ getPayloadInternal()->addCandidate(candidate);
+ } else if (element == "candidate-used") {
+ getPayloadInternal()->setCandidateUsed(attributes.getAttributeValue("cid").get_value_or(""));
+ } else if (element == "candidate-error") {
+ getPayloadInternal()->setCandidateError(true);
+ } else if (element == "activated") {
+ getPayloadInternal()->setActivated(attributes.getAttributeValue("cid").get_value_or(""));
+ } else if (element == "proxy-error") {
+ getPayloadInternal()->setProxyError(true);
+ }
+ }
+
+ ++level;
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
+ --level;
+
+
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) {
+
+ }
+
+ JingleS5BTransportPayload::Candidate::Type JingleS5BTransportMethodPayloadParser::stringToType(const std::string &str) const {
+ if (str == "direct") {
+ return JingleS5BTransportPayload::Candidate::DirectType;
+ } else if (str == "assisted") {
+ return JingleS5BTransportPayload::Candidate::AssistedType;
+ } else if (str == "tunnel") {
+ return JingleS5BTransportPayload::Candidate::TunnelType;
+ } else if (str == "proxy") {
+ return JingleS5BTransportPayload::Candidate::ProxyType;
+ } else {
+ SWIFT_LOG(warning) << "Unknown candidate type; falling back to default!";
+ return JingleS5BTransportPayload::Candidate::DirectType;
+ }
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h
index ccf0b1b..f48c4b5 100644
--- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h
@@ -19,18 +19,18 @@
namespace Swift {
class SWIFTEN_API JingleS5BTransportMethodPayloadParser : public GenericPayloadParser<JingleS5BTransportPayload> {
- public:
- JingleS5BTransportMethodPayloadParser();
+ public:
+ JingleS5BTransportMethodPayloadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- JingleS5BTransportPayload::Candidate::Type stringToType(const std::string &str) const;
+ private:
+ JingleS5BTransportPayload::Candidate::Type stringToType(const std::string &str) const;
- private:
- int level;
+ private:
+ int level;
};
}
diff --git a/Swiften/Parser/PayloadParsers/LastParser.cpp b/Swiften/Parser/PayloadParsers/LastParser.cpp
index 896a554..89d39ac 100644
--- a/Swiften/Parser/PayloadParsers/LastParser.cpp
+++ b/Swiften/Parser/PayloadParsers/LastParser.cpp
@@ -14,16 +14,16 @@ LastParser::LastParser() : level_(0) {
}
void LastParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (level_ == 0) {
- int seconds = 0;
- try {
- seconds = boost::lexical_cast<int>(attributes.getAttribute("seconds"));
- }
- catch (boost::bad_lexical_cast&) {
- }
- getPayloadInternal()->setSeconds(seconds);
- }
- ++level_;
+ if (level_ == 0) {
+ int seconds = 0;
+ try {
+ seconds = boost::lexical_cast<int>(attributes.getAttribute("seconds"));
+ }
+ catch (boost::bad_lexical_cast&) {
+ }
+ getPayloadInternal()->setSeconds(seconds);
+ }
+ ++level_;
}
diff --git a/Swiften/Parser/PayloadParsers/LastParser.h b/Swiften/Parser/PayloadParsers/LastParser.h
index 58cde22..70bfdcb 100644
--- a/Swiften/Parser/PayloadParsers/LastParser.h
+++ b/Swiften/Parser/PayloadParsers/LastParser.h
@@ -11,15 +11,15 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API LastParser : public GenericPayloadParser<Last> {
- public:
- LastParser();
+ class SWIFTEN_API LastParser : public GenericPayloadParser<Last> {
+ public:
+ LastParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MAMFinParser.cpp b/Swiften/Parser/PayloadParsers/MAMFinParser.cpp
index e972381..a29a7c4 100644
--- a/Swiften/Parser/PayloadParsers/MAMFinParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMFinParser.cpp
@@ -20,42 +20,42 @@ MAMFinParser::MAMFinParser() : level_(TopLevel) {
}
void MAMFinParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- getPayloadInternal()->setComplete(attributes.getBoolAttribute("complete", false));
- getPayloadInternal()->setStable(attributes.getBoolAttribute("stable", true));
- boost::optional<std::string> attributeValue;
- if ((attributeValue = attributes.getAttributeValue("queryid"))) {
- getPayloadInternal()->setQueryID(*attributeValue);
- }
- }
- else if (level_ == PayloadLevel) {
- if (element == "set" && ns == "http://jabber.org/protocol/rsm") {
- resultSetParser_ = boost::make_shared<ResultSetParser>();
- }
- }
-
- if (resultSetParser_) { /* parsing a nested ResultSet */
- resultSetParser_->handleStartElement(element, ns, attributes);
- }
-
- ++level_;
+ if (level_ == TopLevel) {
+ getPayloadInternal()->setComplete(attributes.getBoolAttribute("complete", false));
+ getPayloadInternal()->setStable(attributes.getBoolAttribute("stable", true));
+ boost::optional<std::string> attributeValue;
+ if ((attributeValue = attributes.getAttributeValue("queryid"))) {
+ getPayloadInternal()->setQueryID(*attributeValue);
+ }
+ }
+ else if (level_ == PayloadLevel) {
+ if (element == "set" && ns == "http://jabber.org/protocol/rsm") {
+ resultSetParser_ = boost::make_shared<ResultSetParser>();
+ }
+ }
+
+ if (resultSetParser_) { /* parsing a nested ResultSet */
+ resultSetParser_->handleStartElement(element, ns, attributes);
+ }
+
+ ++level_;
}
void MAMFinParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
-
- if (resultSetParser_ && level_ >= PayloadLevel) {
- resultSetParser_->handleEndElement(element, ns);
- }
- if (resultSetParser_ && level_ == PayloadLevel) {
- /* done parsing nested ResultSet */
- getPayloadInternal()->setResultSet(boost::dynamic_pointer_cast<ResultSet>(resultSetParser_->getPayload()));
- resultSetParser_.reset();
- }
+ --level_;
+
+ if (resultSetParser_ && level_ >= PayloadLevel) {
+ resultSetParser_->handleEndElement(element, ns);
+ }
+ if (resultSetParser_ && level_ == PayloadLevel) {
+ /* done parsing nested ResultSet */
+ getPayloadInternal()->setResultSet(boost::dynamic_pointer_cast<ResultSet>(resultSetParser_->getPayload()));
+ resultSetParser_.reset();
+ }
}
void MAMFinParser::handleCharacterData(const std::string& data) {
- if (resultSetParser_) {
- resultSetParser_->handleCharacterData(data);
- }
+ if (resultSetParser_) {
+ resultSetParser_->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/MAMFinParser.h b/Swiften/Parser/PayloadParsers/MAMFinParser.h
index 6f2d942..2e805ad 100644
--- a/Swiften/Parser/PayloadParsers/MAMFinParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMFinParser.h
@@ -14,23 +14,23 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class ResultSetParser;
+ class ResultSetParser;
- class SWIFTEN_API MAMFinParser : public GenericPayloadParser<MAMFin> {
- public:
- MAMFinParser();
+ class SWIFTEN_API MAMFinParser : public GenericPayloadParser<MAMFin> {
+ public:
+ MAMFinParser();
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
- private:
- boost::shared_ptr<ResultSetParser> resultSetParser_;
- int level_;
- };
+ private:
+ boost::shared_ptr<ResultSetParser> resultSetParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp b/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
index 3be997b..41fbbb7 100644
--- a/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
@@ -19,60 +19,60 @@ MAMQueryParser::MAMQueryParser() : level_(TopLevel) {
}
void MAMQueryParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- boost::optional<std::string> attributeValue;
- if ((attributeValue = attributes.getAttributeValue("queryid"))) {
- getPayloadInternal()->setQueryID(*attributeValue);
- }
- if ((attributeValue = attributes.getAttributeValue("node"))) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- } else if (level_ == PayloadLevel) {
- if (element == "x" && ns == "jabber:x:data") {
- formParser_ = boost::make_shared<FormParser>();
- } else if (element == "set" && ns == "http://jabber.org/protocol/rsm") {
- resultSetParser_ = boost::make_shared<ResultSetParser>();
- }
- }
+ if (level_ == TopLevel) {
+ boost::optional<std::string> attributeValue;
+ if ((attributeValue = attributes.getAttributeValue("queryid"))) {
+ getPayloadInternal()->setQueryID(*attributeValue);
+ }
+ if ((attributeValue = attributes.getAttributeValue("node"))) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ } else if (level_ == PayloadLevel) {
+ if (element == "x" && ns == "jabber:x:data") {
+ formParser_ = boost::make_shared<FormParser>();
+ } else if (element == "set" && ns == "http://jabber.org/protocol/rsm") {
+ resultSetParser_ = boost::make_shared<ResultSetParser>();
+ }
+ }
- if (formParser_) { /* parsing a nested Form */
- formParser_->handleStartElement(element, ns, attributes);
- }
+ if (formParser_) { /* parsing a nested Form */
+ formParser_->handleStartElement(element, ns, attributes);
+ }
- if (resultSetParser_) { /* parsing a nested ResultSet */
- resultSetParser_->handleStartElement(element, ns, attributes);
- }
+ if (resultSetParser_) { /* parsing a nested ResultSet */
+ resultSetParser_->handleStartElement(element, ns, attributes);
+ }
- ++level_;
+ ++level_;
}
void MAMQueryParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
+ --level_;
- if (formParser_ && level_ >= PayloadLevel) {
- formParser_->handleEndElement(element, ns);
- }
- if (formParser_ && level_ == PayloadLevel) {
- /* done parsing nested Form */
- getPayloadInternal()->setForm(boost::dynamic_pointer_cast<Form>(formParser_->getPayload()));
- formParser_.reset();
- }
+ if (formParser_ && level_ >= PayloadLevel) {
+ formParser_->handleEndElement(element, ns);
+ }
+ if (formParser_ && level_ == PayloadLevel) {
+ /* done parsing nested Form */
+ getPayloadInternal()->setForm(boost::dynamic_pointer_cast<Form>(formParser_->getPayload()));
+ formParser_.reset();
+ }
- if (resultSetParser_ && level_ >= PayloadLevel) {
- resultSetParser_->handleEndElement(element, ns);
- }
- if (resultSetParser_ && level_ == PayloadLevel) {
- /* done parsing nested ResultSet */
- getPayloadInternal()->setResultSet(boost::dynamic_pointer_cast<ResultSet>(resultSetParser_->getPayload()));
- resultSetParser_.reset();
- }
+ if (resultSetParser_ && level_ >= PayloadLevel) {
+ resultSetParser_->handleEndElement(element, ns);
+ }
+ if (resultSetParser_ && level_ == PayloadLevel) {
+ /* done parsing nested ResultSet */
+ getPayloadInternal()->setResultSet(boost::dynamic_pointer_cast<ResultSet>(resultSetParser_->getPayload()));
+ resultSetParser_.reset();
+ }
}
void MAMQueryParser::handleCharacterData(const std::string& data) {
- if (formParser_) {
- formParser_->handleCharacterData(data);
- }
- if (resultSetParser_) {
- resultSetParser_->handleCharacterData(data);
- }
+ if (formParser_) {
+ formParser_->handleCharacterData(data);
+ }
+ if (resultSetParser_) {
+ resultSetParser_->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/MAMQueryParser.h b/Swiften/Parser/PayloadParsers/MAMQueryParser.h
index 119f956..4f5bd47 100644
--- a/Swiften/Parser/PayloadParsers/MAMQueryParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMQueryParser.h
@@ -16,25 +16,25 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class ResultSetParser;
- class FormParser;
-
- class SWIFTEN_API MAMQueryParser : public GenericPayloadParser<MAMQuery> {
- public:
- MAMQueryParser();
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
-
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
-
- private:
- boost::shared_ptr<FormParser> formParser_;
- boost::shared_ptr<ResultSetParser> resultSetParser_;
- int level_;
- };
+ class ResultSetParser;
+ class FormParser;
+
+ class SWIFTEN_API MAMQueryParser : public GenericPayloadParser<MAMQuery> {
+ public:
+ MAMQueryParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+
+ private:
+ boost::shared_ptr<FormParser> formParser_;
+ boost::shared_ptr<ResultSetParser> resultSetParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MAMResultParser.cpp b/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
index ac32100..e39ed94 100644
--- a/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
@@ -18,42 +18,42 @@ MAMResultParser::MAMResultParser(PayloadParserFactoryCollection* factories) : fa
}
void MAMResultParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- boost::optional<std::string> attributeValue;
- if ((attributeValue = attributes.getAttributeValue("id"))) {
- getPayloadInternal()->setID(*attributeValue);
- }
- if ((attributeValue = attributes.getAttributeValue("queryid"))) {
- getPayloadInternal()->setQueryID(*attributeValue);
- }
- } else if (level_ == PayloadLevel) {
- if (element == "forwarded" && ns == "urn:xmpp:forward:0") {
- payloadParser_ = boost::make_shared<ForwardedParser>(factories_);
- }
- }
-
- if (payloadParser_) {
- /* parsing a nested payload */
- payloadParser_->handleStartElement(element, ns, attributes);
- }
-
- ++level_;
+ if (level_ == TopLevel) {
+ boost::optional<std::string> attributeValue;
+ if ((attributeValue = attributes.getAttributeValue("id"))) {
+ getPayloadInternal()->setID(*attributeValue);
+ }
+ if ((attributeValue = attributes.getAttributeValue("queryid"))) {
+ getPayloadInternal()->setQueryID(*attributeValue);
+ }
+ } else if (level_ == PayloadLevel) {
+ if (element == "forwarded" && ns == "urn:xmpp:forward:0") {
+ payloadParser_ = boost::make_shared<ForwardedParser>(factories_);
+ }
+ }
+
+ if (payloadParser_) {
+ /* parsing a nested payload */
+ payloadParser_->handleStartElement(element, ns, attributes);
+ }
+
+ ++level_;
}
void MAMResultParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (payloadParser_ && level_ >= PayloadLevel) {
- payloadParser_->handleEndElement(element, ns);
- }
- if (payloadParser_ && level_ == PayloadLevel) {
- /* done parsing nested stanza */
- getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<Forwarded>(payloadParser_->getPayload()));
- payloadParser_.reset();
- }
+ --level_;
+ if (payloadParser_ && level_ >= PayloadLevel) {
+ payloadParser_->handleEndElement(element, ns);
+ }
+ if (payloadParser_ && level_ == PayloadLevel) {
+ /* done parsing nested stanza */
+ getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<Forwarded>(payloadParser_->getPayload()));
+ payloadParser_.reset();
+ }
}
void MAMResultParser::handleCharacterData(const std::string& data) {
- if (payloadParser_) {
- payloadParser_->handleCharacterData(data);
- }
+ if (payloadParser_) {
+ payloadParser_->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/MAMResultParser.h b/Swiften/Parser/PayloadParsers/MAMResultParser.h
index e1b0b8e..5177f8b 100644
--- a/Swiften/Parser/PayloadParsers/MAMResultParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMResultParser.h
@@ -16,25 +16,25 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class ForwardedParser;
-
- class SWIFTEN_API MAMResultParser : public GenericPayloadParser<MAMResult> {
- public:
- MAMResultParser(PayloadParserFactoryCollection* factories);
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
-
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
-
- private:
- boost::shared_ptr<ForwardedParser> payloadParser_;
- PayloadParserFactoryCollection* factories_;
- int level_;
- };
+ class PayloadParserFactoryCollection;
+ class ForwardedParser;
+
+ class SWIFTEN_API MAMResultParser : public GenericPayloadParser<MAMResult> {
+ public:
+ MAMResultParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+
+ private:
+ boost::shared_ptr<ForwardedParser> payloadParser_;
+ PayloadParserFactoryCollection* factories_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
index 717fc60..1fbff1c 100644
--- a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
@@ -14,10 +14,10 @@
namespace Swift {
void MUCAdminPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref itemElement, root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
- MUCItem item = MUCItemParser::itemFromTree(itemElement);
- getPayloadInternal()->addItem(item);
- }
+ foreach (ParserElement::ref itemElement, root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
+ MUCItem item = MUCItemParser::itemFromTree(itemElement);
+ getPayloadInternal()->addItem(item);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h
index 9174c7d..de46690 100644
--- a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h
@@ -14,8 +14,8 @@
#include <Swiften/Parser/PayloadParsers/MUCItemParser.h>
namespace Swift {
- class SWIFTEN_API MUCAdminPayloadParser : public GenericPayloadTreeParser<MUCAdminPayload> {
- public:
- virtual void handleTree(ParserElement::ref root);
- };
+ class SWIFTEN_API MUCAdminPayloadParser : public GenericPayloadTreeParser<MUCAdminPayload> {
+ public:
+ virtual void handleTree(ParserElement::ref root);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
index b70c1d4..95ff8c5 100644
--- a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
@@ -11,12 +11,12 @@
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());
+ 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/MUCDestroyPayloadParser.h b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h
index 1e5d545..e79d9a6 100644
--- a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h
@@ -13,8 +13,8 @@
#include <Swiften/Parser/GenericPayloadTreeParser.h>
namespace Swift {
- class SWIFTEN_API MUCDestroyPayloadParser : public GenericPayloadTreeParser<MUCDestroyPayload> {
- public:
- virtual void handleTree(ParserElement::ref root);
- };
+ class SWIFTEN_API MUCDestroyPayloadParser : public GenericPayloadTreeParser<MUCDestroyPayload> {
+ public:
+ virtual void handleTree(ParserElement::ref root);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp
index 376353d..20e5f2b 100644
--- a/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp
@@ -11,14 +11,14 @@
namespace Swift {
void MUCInvitationPayloadParser::handleTree(ParserElement::ref root) {
- MUCInvitationPayload::ref invite = getPayloadInternal();
- invite->setIsContinuation(root->getAttributes().getBoolAttribute("continue", false));
- invite->setJID(JID(root->getAttributes().getAttribute("jid")));
- invite->setPassword(root->getAttributes().getAttribute("password"));
- invite->setReason(root->getAttributes().getAttribute("reason"));
- invite->setThread(root->getAttributes().getAttribute("thread"));
- ParserElement::ref impromptuNode = root->getChild("impromptu", "http://swift.im/impromptu");
- invite->setIsImpromptu(!boost::dynamic_pointer_cast<NullParserElement>(impromptuNode));
+ MUCInvitationPayload::ref invite = getPayloadInternal();
+ invite->setIsContinuation(root->getAttributes().getBoolAttribute("continue", false));
+ invite->setJID(JID(root->getAttributes().getAttribute("jid")));
+ invite->setPassword(root->getAttributes().getAttribute("password"));
+ invite->setReason(root->getAttributes().getAttribute("reason"));
+ invite->setThread(root->getAttributes().getAttribute("thread"));
+ ParserElement::ref impromptuNode = root->getChild("impromptu", "http://swift.im/impromptu");
+ invite->setIsImpromptu(!boost::dynamic_pointer_cast<NullParserElement>(impromptuNode));
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h b/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h
index f79c971..7b76166 100644
--- a/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericPayloadTreeParser.h>
namespace Swift {
- class SWIFTEN_API MUCInvitationPayloadParser : public GenericPayloadTreeParser<MUCInvitationPayload> {
- public:
- virtual void handleTree(ParserElement::ref root);
- };
+ class SWIFTEN_API MUCInvitationPayloadParser : public GenericPayloadTreeParser<MUCInvitationPayload> {
+ public:
+ virtual void handleTree(ParserElement::ref root);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCItemParser.cpp b/Swiften/Parser/PayloadParsers/MUCItemParser.cpp
index 332df11..0486cb4 100644
--- a/Swiften/Parser/PayloadParsers/MUCItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCItemParser.cpp
@@ -16,65 +16,65 @@
namespace Swift {
MUCItem MUCItemParser::itemFromTree(ParserElement::ref root) {
- MUCItem item;
- std::string affiliation = root->getAttributes().getAttribute("affiliation");
- std::string role = root->getAttributes().getAttribute("role");
- std::string nick = root->getAttributes().getAttribute("nick");
- std::string jid = root->getAttributes().getAttribute("jid");
- item.affiliation = parseAffiliation(affiliation);
- item.role = parseRole(role);
- if (!jid.empty()) {
- item.realJID = JID(jid);
- }
- if (!nick.empty()) {
- item.nick = nick;
- }
- std::string xmlns = root->getNamespace();
- std::string reason = root->getChild("reason", xmlns)->getText();
- std::string actor = root->getChild("actor", xmlns)->getAttributes().getAttribute("jid");
- if (!reason.empty()) {
- item.reason = reason;
- }
- if (!actor.empty()) {
- item.actor = JID(actor);
- }
+ MUCItem item;
+ std::string affiliation = root->getAttributes().getAttribute("affiliation");
+ std::string role = root->getAttributes().getAttribute("role");
+ std::string nick = root->getAttributes().getAttribute("nick");
+ std::string jid = root->getAttributes().getAttribute("jid");
+ item.affiliation = parseAffiliation(affiliation);
+ item.role = parseRole(role);
+ if (!jid.empty()) {
+ item.realJID = JID(jid);
+ }
+ if (!nick.empty()) {
+ item.nick = nick;
+ }
+ std::string xmlns = root->getNamespace();
+ std::string reason = root->getChild("reason", xmlns)->getText();
+ std::string actor = root->getChild("actor", xmlns)->getAttributes().getAttribute("jid");
+ if (!reason.empty()) {
+ item.reason = reason;
+ }
+ if (!actor.empty()) {
+ item.actor = JID(actor);
+ }
- return item;
+ return item;
}
boost::optional<MUCOccupant::Role> MUCItemParser::parseRole(const std::string& roleString) {
- if (roleString == "moderator") {
- return MUCOccupant::Moderator;
- }
- if (roleString == "participant") {
- return MUCOccupant::Participant;
- }
- if (roleString == "visitor") {
- return MUCOccupant::Visitor;
- }
- if (roleString == "none") {
- return MUCOccupant::NoRole;
- }
- return boost::optional<MUCOccupant::Role>();
+ if (roleString == "moderator") {
+ return MUCOccupant::Moderator;
+ }
+ if (roleString == "participant") {
+ return MUCOccupant::Participant;
+ }
+ if (roleString == "visitor") {
+ return MUCOccupant::Visitor;
+ }
+ if (roleString == "none") {
+ return MUCOccupant::NoRole;
+ }
+ return boost::optional<MUCOccupant::Role>();
}
boost::optional<MUCOccupant::Affiliation> MUCItemParser::parseAffiliation(const std::string& affiliationString) {
- if (affiliationString == "owner") {
- return MUCOccupant::Owner;
- }
- if (affiliationString == "admin") {
- return MUCOccupant::Admin;
- }
- if (affiliationString == "member") {
- return MUCOccupant::Member;
- }
- if (affiliationString == "outcast") {
- return MUCOccupant::Outcast;
- }
- if (affiliationString == "none") {
- return MUCOccupant::NoAffiliation;
- }
- return boost::optional<MUCOccupant::Affiliation>();
+ if (affiliationString == "owner") {
+ return MUCOccupant::Owner;
+ }
+ if (affiliationString == "admin") {
+ return MUCOccupant::Admin;
+ }
+ if (affiliationString == "member") {
+ return MUCOccupant::Member;
+ }
+ if (affiliationString == "outcast") {
+ return MUCOccupant::Outcast;
+ }
+ if (affiliationString == "none") {
+ return MUCOccupant::NoAffiliation;
+ }
+ return boost::optional<MUCOccupant::Affiliation>();
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCItemParser.h b/Swiften/Parser/PayloadParsers/MUCItemParser.h
index fc5d657..6f80d54 100644
--- a/Swiften/Parser/PayloadParsers/MUCItemParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCItemParser.h
@@ -11,11 +11,11 @@
#include <Swiften/Parser/GenericPayloadTreeParser.h>
namespace Swift {
- class SWIFTEN_API MUCItemParser {
- public:
- static MUCItem itemFromTree(ParserElement::ref root);
- private:
- static boost::optional<MUCOccupant::Role> parseRole(const std::string& itemString);
- static boost::optional<MUCOccupant::Affiliation> parseAffiliation(const std::string& statusString);
- };
+ class SWIFTEN_API MUCItemParser {
+ public:
+ static MUCItem itemFromTree(ParserElement::ref root);
+ private:
+ static boost::optional<MUCOccupant::Role> parseRole(const std::string& itemString);
+ static boost::optional<MUCOccupant::Affiliation> parseAffiliation(const std::string& statusString);
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp
index b4cc7b6..7e7c0d4 100644
--- a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp
@@ -15,36 +15,36 @@ MUCOwnerPayloadParser::MUCOwnerPayloadParser(PayloadParserFactoryCollection* fac
}
void MUCOwnerPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 1) {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void MUCOwnerPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
+ }
+ }
}
void MUCOwnerPayloadParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h
index 85db82f..6502512 100644
--- a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h
@@ -13,20 +13,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API MUCOwnerPayloadParser : public GenericPayloadParser<MUCOwnerPayload> {
- public:
- MUCOwnerPayloadParser(PayloadParserFactoryCollection* factories);
+ class SWIFTEN_API MUCOwnerPayloadParser : public GenericPayloadParser<MUCOwnerPayload> {
+ public:
+ MUCOwnerPayloadParser(PayloadParserFactoryCollection* factories);
- private:
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ private:
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- PayloadParserFactoryCollection* factories;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h
index 9270dc7..d6399e7 100644
--- a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h
@@ -11,23 +11,23 @@
#include <Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API MUCOwnerPayloadParserFactory : public PayloadParserFactory {
- public:
- MUCOwnerPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
+ class SWIFTEN_API MUCOwnerPayloadParserFactory : public PayloadParserFactory {
+ public:
+ MUCOwnerPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "query" && ns == "http://jabber.org/protocol/muc#owner";
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "query" && ns == "http://jabber.org/protocol/muc#owner";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new MUCOwnerPayloadParser(factories);
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new MUCOwnerPayloadParser(factories);
+ }
- private:
- PayloadParserFactoryCollection* factories;
+ private:
+ PayloadParserFactoryCollection* factories;
- };
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
index 39e216c..00a5d4f 100644
--- a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
@@ -17,42 +17,42 @@
namespace Swift {
void MUCUserPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref 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&) {
- }
- }
- else {
- getPayloadInternal()->setPayload(TreeReparser::parseTree(child, factories));
- }
- }
+ foreach (ParserElement::ref 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&) {
+ }
+ }
+ else {
+ getPayloadInternal()->setPayload(TreeReparser::parseTree(child, factories));
+ }
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h
index 3d7a53b..3d6dbab 100644
--- a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h
@@ -14,12 +14,12 @@
#include <Swiften/Parser/PayloadParsers/MUCItemParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class SWIFTEN_API MUCUserPayloadParser : public GenericPayloadTreeParser<MUCUserPayload> {
- public:
- MUCUserPayloadParser(PayloadParserFactoryCollection* collection) : factories(collection) {}
- virtual void handleTree(ParserElement::ref root);
- private:
- PayloadParserFactoryCollection* factories;
- };
+ class PayloadParserFactoryCollection;
+ class SWIFTEN_API MUCUserPayloadParser : public GenericPayloadTreeParser<MUCUserPayload> {
+ public:
+ MUCUserPayloadParser(PayloadParserFactoryCollection* collection) : factories(collection) {}
+ virtual void handleTree(ParserElement::ref root);
+ private:
+ PayloadParserFactoryCollection* factories;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h
index 4cc9134..4a0380d 100644
--- a/Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h>
namespace Swift {
- class SWIFTEN_API MUCUserPayloadParserFactory : public PayloadParserFactory {
- public:
- MUCUserPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
+ class SWIFTEN_API MUCUserPayloadParserFactory : public PayloadParserFactory {
+ public:
+ MUCUserPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "x" && ns == "http://jabber.org/protocol/muc#user";
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "x" && ns == "http://jabber.org/protocol/muc#user";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new MUCUserPayloadParser(factories);
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new MUCUserPayloadParser(factories);
+ }
- private:
- PayloadParserFactoryCollection* factories;
- };
+ private:
+ PayloadParserFactoryCollection* factories;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/NicknameParser.cpp b/Swiften/Parser/PayloadParsers/NicknameParser.cpp
index a3ce952..331355a 100644
--- a/Swiften/Parser/PayloadParsers/NicknameParser.cpp
+++ b/Swiften/Parser/PayloadParsers/NicknameParser.cpp
@@ -12,18 +12,18 @@ NicknameParser::NicknameParser() : level(0) {
}
void NicknameParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level;
+ ++level;
}
void NicknameParser::handleEndElement(const std::string&, const std::string&) {
- --level;
- if (level == 0) {
- getPayloadInternal()->setNickname(text);
- }
+ --level;
+ if (level == 0) {
+ getPayloadInternal()->setNickname(text);
+ }
}
void NicknameParser::handleCharacterData(const std::string& data) {
- text += data;
+ text += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/NicknameParser.h b/Swiften/Parser/PayloadParsers/NicknameParser.h
index d8ac5b5..1bdd600 100644
--- a/Swiften/Parser/PayloadParsers/NicknameParser.h
+++ b/Swiften/Parser/PayloadParsers/NicknameParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API NicknameParser : public GenericPayloadParser<Nickname> {
- public:
- NicknameParser();
+ class SWIFTEN_API NicknameParser : public GenericPayloadParser<Nickname> {
+ public:
+ NicknameParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level;
- std::string text;
- };
+ private:
+ int level;
+ std::string text;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PriorityParser.cpp b/Swiften/Parser/PayloadParsers/PriorityParser.cpp
index 862d219..88eef0d 100644
--- a/Swiften/Parser/PayloadParsers/PriorityParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PriorityParser.cpp
@@ -14,24 +14,24 @@ PriorityParser::PriorityParser() : level_(0) {
}
void PriorityParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void PriorityParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- int priority = 0;
- try {
- priority = boost::lexical_cast<int>(text_);
- }
- catch (boost::bad_lexical_cast&) {
- }
- getPayloadInternal()->setPriority(priority);
- }
+ --level_;
+ if (level_ == 0) {
+ int priority = 0;
+ try {
+ priority = boost::lexical_cast<int>(text_);
+ }
+ catch (boost::bad_lexical_cast&) {
+ }
+ getPayloadInternal()->setPriority(priority);
+ }
}
void PriorityParser::handleCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/PriorityParser.h b/Swiften/Parser/PayloadParsers/PriorityParser.h
index 6c34e3b..e6bf059 100644
--- a/Swiften/Parser/PayloadParsers/PriorityParser.h
+++ b/Swiften/Parser/PayloadParsers/PriorityParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API PriorityParser : public GenericPayloadParser<Priority> {
- public:
- PriorityParser();
+ class SWIFTEN_API PriorityParser : public GenericPayloadParser<Priority> {
+ public:
+ PriorityParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp b/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp
index 0dca7b1..e40249a 100644
--- a/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp
@@ -15,36 +15,36 @@ PrivateStorageParser::PrivateStorageParser(PayloadParserFactoryCollection* facto
}
void PrivateStorageParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 1) {
- PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PrivateStorageParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ getPayloadInternal()->setPayload(currentPayloadParser->getPayload());
+ }
+ }
}
void PrivateStorageParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/PrivateStorageParser.h b/Swiften/Parser/PayloadParsers/PrivateStorageParser.h
index 57e4136..761a019 100644
--- a/Swiften/Parser/PayloadParsers/PrivateStorageParser.h
+++ b/Swiften/Parser/PayloadParsers/PrivateStorageParser.h
@@ -13,20 +13,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API PrivateStorageParser : public GenericPayloadParser<PrivateStorage> {
- public:
- PrivateStorageParser(PayloadParserFactoryCollection* factories);
+ class SWIFTEN_API PrivateStorageParser : public GenericPayloadParser<PrivateStorage> {
+ public:
+ PrivateStorageParser(PayloadParserFactoryCollection* factories);
- private:
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ private:
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- PayloadParserFactoryCollection* factories;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h b/Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h
index e8db9af..550177c 100644
--- a/Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h
@@ -11,23 +11,23 @@
#include <Swiften/Parser/PayloadParsers/PrivateStorageParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API PrivateStorageParserFactory : public PayloadParserFactory {
- public:
- PrivateStorageParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
- }
+ class SWIFTEN_API PrivateStorageParserFactory : public PayloadParserFactory {
+ public:
+ PrivateStorageParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
- virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
- return element == "query" && ns == "jabber:iq:private";
- }
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "query" && ns == "jabber:iq:private";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new PrivateStorageParser(factories);
- }
+ virtual PayloadParser* createPayloadParser() {
+ return new PrivateStorageParser(factories);
+ }
- private:
- PayloadParserFactoryCollection* factories;
-
- };
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp
index 9a470a4..cba3816 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp
@@ -24,41 +24,41 @@ PubSubAffiliationParser::~PubSubAffiliationParser() {
}
void PubSubAffiliationParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("affiliation")) {
- if (boost::optional<PubSubAffiliation::Type> value = EnumParser<PubSubAffiliation::Type>()(PubSubAffiliation::None, "none")(PubSubAffiliation::Member, "member")(PubSubAffiliation::Outcast, "outcast")(PubSubAffiliation::Owner, "owner")(PubSubAffiliation::Publisher, "publisher")(PubSubAffiliation::PublishOnly, "publish-only").parse(*attributeValue)) {
- getPayloadInternal()->setType(*value);
- }
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("affiliation")) {
+ if (boost::optional<PubSubAffiliation::Type> value = EnumParser<PubSubAffiliation::Type>()(PubSubAffiliation::None, "none")(PubSubAffiliation::Member, "member")(PubSubAffiliation::Outcast, "outcast")(PubSubAffiliation::Owner, "owner")(PubSubAffiliation::Publisher, "publisher")(PubSubAffiliation::PublishOnly, "publish-only").parse(*attributeValue)) {
+ getPayloadInternal()->setType(*value);
+ }
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubAffiliationParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubAffiliationParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h
index 08cddea..1d3f4fd 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubAffiliationParser : public GenericPayloadParser<PubSubAffiliation> {
- public:
- PubSubAffiliationParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubAffiliationParser();
+ class SWIFTEN_API PubSubAffiliationParser : public GenericPayloadParser<PubSubAffiliation> {
+ public:
+ PubSubAffiliationParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubAffiliationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
index b316134..8a11553 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
@@ -24,42 +24,42 @@ PubSubAffiliationsParser::~PubSubAffiliationsParser() {
}
void PubSubAffiliationsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubAffiliationParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubAffiliationParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubAffiliationsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addAffiliation(boost::dynamic_pointer_cast<PubSubAffiliation>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addAffiliation(boost::dynamic_pointer_cast<PubSubAffiliation>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubAffiliationsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h
index a52e1c1..a26942f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubAffiliationsParser : public GenericPayloadParser<PubSubAffiliations> {
- public:
- PubSubAffiliationsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubAffiliationsParser();
+ class SWIFTEN_API PubSubAffiliationsParser : public GenericPayloadParser<PubSubAffiliations> {
+ public:
+ PubSubAffiliationsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubAffiliationsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
index cac9924..f3af12f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
@@ -24,38 +24,38 @@ PubSubConfigureParser::~PubSubConfigureParser() {
}
void PubSubConfigureParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
-
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- currentPayloadParser = boost::make_shared<FormParser>();
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = boost::make_shared<FormParser>();
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubConfigureParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubConfigureParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h
index 0364ed4..33a3da5 100644
--- a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubConfigureParser : public GenericPayloadParser<PubSubConfigure> {
- public:
- PubSubConfigureParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubConfigureParser();
+ class SWIFTEN_API PubSubConfigureParser : public GenericPayloadParser<PubSubConfigure> {
+ public:
+ PubSubConfigureParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubConfigureParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp b/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
index fbf2eba..e299ddb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
@@ -24,36 +24,36 @@ PubSubCreateParser::~PubSubCreateParser() {
}
void PubSubCreateParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubCreateParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubCreateParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubCreateParser.h b/Swiften/Parser/PayloadParsers/PubSubCreateParser.h
index b4f82a0..3f277ed 100644
--- a/Swiften/Parser/PayloadParsers/PubSubCreateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubCreateParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubCreateParser : public GenericPayloadParser<PubSubCreate> {
- public:
- PubSubCreateParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubCreateParser();
+ class SWIFTEN_API PubSubCreateParser : public GenericPayloadParser<PubSubCreate> {
+ public:
+ PubSubCreateParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubCreateParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
index bf5a210..78c6d0b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
@@ -24,41 +24,41 @@ PubSubDefaultParser::~PubSubDefaultParser() {
}
void PubSubDefaultParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("type")) {
- if (boost::optional<PubSubDefault::Type> value = EnumParser<PubSubDefault::Type>()(PubSubDefault::None, "none")(PubSubDefault::Collection, "collection")(PubSubDefault::Leaf, "leaf").parse(*attributeValue)) {
- getPayloadInternal()->setType(*value);
- }
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("type")) {
+ if (boost::optional<PubSubDefault::Type> value = EnumParser<PubSubDefault::Type>()(PubSubDefault::None, "none")(PubSubDefault::Collection, "collection")(PubSubDefault::Leaf, "leaf").parse(*attributeValue)) {
+ getPayloadInternal()->setType(*value);
+ }
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubDefaultParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubDefaultParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h
index e3596d6..b0f0e25 100644
--- a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubDefaultParser : public GenericPayloadParser<PubSubDefault> {
- public:
- PubSubDefaultParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubDefaultParser();
+ class SWIFTEN_API PubSubDefaultParser : public GenericPayloadParser<PubSubDefault> {
+ public:
+ PubSubDefaultParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubDefaultParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp b/Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp
index f399717..99a306d 100644
--- a/Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp
@@ -9,95 +9,95 @@
using namespace Swift;
PubSubErrorParser::PubSubErrorParser() : level(0) {
- typeParser
- (PubSubError::ClosedNode, "closed-node")
- (PubSubError::ConfigurationRequired, "configuration-required")
- (PubSubError::InvalidJID, "invalid-jid")
- (PubSubError::InvalidOptions, "invalid-options")
- (PubSubError::InvalidPayload, "invalid-payload")
- (PubSubError::InvalidSubscriptionID, "invalid-subid")
- (PubSubError::ItemForbidden, "item-forbidden")
- (PubSubError::ItemRequired, "item-required")
- (PubSubError::JIDRequired, "jid-required")
- (PubSubError::MaximumItemsExceeded, "max-items-exceeded")
- (PubSubError::MaximumNodesExceeded, "max-nodes-exceeded")
- (PubSubError::NodeIDRequired, "nodeid-required")
- (PubSubError::NotInRosterGroup, "not-in-roster-group")
- (PubSubError::NotSubscribed, "not-subscribed")
- (PubSubError::PayloadTooBig, "payload-too-big")
- (PubSubError::PayloadRequired, "payload-required")
- (PubSubError::PendingSubscription, "pending-subscription")
- (PubSubError::PresenceSubscriptionRequired, "presence-subscription-required")
- (PubSubError::SubscriptionIDRequired, "subid-required")
- (PubSubError::TooManySubscriptions, "too-many-subscriptions")
- (PubSubError::Unsupported, "unsupported")
- (PubSubError::UnsupportedAccessModel, "unsupported-access-model");
- unsupportedTypeParser
- (PubSubError::AccessAuthorize, "access-authorize")
- (PubSubError::AccessOpen, "access-open")
- (PubSubError::AccessPresence, "access-presence")
- (PubSubError::AccessRoster, "access-roster")
- (PubSubError::AccessWhitelist, "access-whitelist")
- (PubSubError::AutoCreate, "auto-create")
- (PubSubError::AutoSubscribe, "auto-subscribe")
- (PubSubError::Collections, "collections")
- (PubSubError::ConfigNode, "config-node")
- (PubSubError::CreateAndConfigure, "create-and-configure")
- (PubSubError::CreateNodes, "create-nodes")
- (PubSubError::DeleteItems, "delete-items")
- (PubSubError::DeleteNodes, "delete-nodes")
- (PubSubError::FilteredNotifications, "filtered-notifications")
- (PubSubError::GetPending, "get-pending")
- (PubSubError::InstantNodes, "instant-nodes")
- (PubSubError::ItemIDs, "item-ids")
- (PubSubError::LastPublished, "last-published")
- (PubSubError::LeasedSubscription, "leased-subscription")
- (PubSubError::ManageSubscriptions, "manage-subscriptions")
- (PubSubError::MemberAffiliation, "member-affiliation")
- (PubSubError::MetaData, "meta-data")
- (PubSubError::ModifyAffiliations, "modify-affiliations")
- (PubSubError::MultiCollection, "multi-collection")
- (PubSubError::MultiSubscribe, "multi-subscribe")
- (PubSubError::OutcastAffiliation, "outcast-affiliation")
- (PubSubError::PersistentItems, "persistent-items")
- (PubSubError::PresenceNotifications, "presence-notifications")
- (PubSubError::PresenceSubscribe, "presence-subscribe")
- (PubSubError::Publish, "publish")
- (PubSubError::PublishOptions, "publish-options")
- (PubSubError::PublishOnlyAffiliation, "publish-only-affiliation")
- (PubSubError::PublisherAffiliation, "publisher-affiliation")
- (PubSubError::PurgeNodes, "purge-nodes")
- (PubSubError::RetractItems, "retract-items")
- (PubSubError::RetrieveAffiliations, "retrieve-affiliations")
- (PubSubError::RetrieveDefault, "retrieve-default")
- (PubSubError::RetrieveItems, "retrieve-items")
- (PubSubError::RetrieveSubscriptions, "retrieve-subscriptions")
- (PubSubError::Subscribe, "subscribe")
- (PubSubError::SubscriptionOptions, "subscription-options")
- (PubSubError::SubscriptionNotifications, "subscription-notifications");
+ typeParser
+ (PubSubError::ClosedNode, "closed-node")
+ (PubSubError::ConfigurationRequired, "configuration-required")
+ (PubSubError::InvalidJID, "invalid-jid")
+ (PubSubError::InvalidOptions, "invalid-options")
+ (PubSubError::InvalidPayload, "invalid-payload")
+ (PubSubError::InvalidSubscriptionID, "invalid-subid")
+ (PubSubError::ItemForbidden, "item-forbidden")
+ (PubSubError::ItemRequired, "item-required")
+ (PubSubError::JIDRequired, "jid-required")
+ (PubSubError::MaximumItemsExceeded, "max-items-exceeded")
+ (PubSubError::MaximumNodesExceeded, "max-nodes-exceeded")
+ (PubSubError::NodeIDRequired, "nodeid-required")
+ (PubSubError::NotInRosterGroup, "not-in-roster-group")
+ (PubSubError::NotSubscribed, "not-subscribed")
+ (PubSubError::PayloadTooBig, "payload-too-big")
+ (PubSubError::PayloadRequired, "payload-required")
+ (PubSubError::PendingSubscription, "pending-subscription")
+ (PubSubError::PresenceSubscriptionRequired, "presence-subscription-required")
+ (PubSubError::SubscriptionIDRequired, "subid-required")
+ (PubSubError::TooManySubscriptions, "too-many-subscriptions")
+ (PubSubError::Unsupported, "unsupported")
+ (PubSubError::UnsupportedAccessModel, "unsupported-access-model");
+ unsupportedTypeParser
+ (PubSubError::AccessAuthorize, "access-authorize")
+ (PubSubError::AccessOpen, "access-open")
+ (PubSubError::AccessPresence, "access-presence")
+ (PubSubError::AccessRoster, "access-roster")
+ (PubSubError::AccessWhitelist, "access-whitelist")
+ (PubSubError::AutoCreate, "auto-create")
+ (PubSubError::AutoSubscribe, "auto-subscribe")
+ (PubSubError::Collections, "collections")
+ (PubSubError::ConfigNode, "config-node")
+ (PubSubError::CreateAndConfigure, "create-and-configure")
+ (PubSubError::CreateNodes, "create-nodes")
+ (PubSubError::DeleteItems, "delete-items")
+ (PubSubError::DeleteNodes, "delete-nodes")
+ (PubSubError::FilteredNotifications, "filtered-notifications")
+ (PubSubError::GetPending, "get-pending")
+ (PubSubError::InstantNodes, "instant-nodes")
+ (PubSubError::ItemIDs, "item-ids")
+ (PubSubError::LastPublished, "last-published")
+ (PubSubError::LeasedSubscription, "leased-subscription")
+ (PubSubError::ManageSubscriptions, "manage-subscriptions")
+ (PubSubError::MemberAffiliation, "member-affiliation")
+ (PubSubError::MetaData, "meta-data")
+ (PubSubError::ModifyAffiliations, "modify-affiliations")
+ (PubSubError::MultiCollection, "multi-collection")
+ (PubSubError::MultiSubscribe, "multi-subscribe")
+ (PubSubError::OutcastAffiliation, "outcast-affiliation")
+ (PubSubError::PersistentItems, "persistent-items")
+ (PubSubError::PresenceNotifications, "presence-notifications")
+ (PubSubError::PresenceSubscribe, "presence-subscribe")
+ (PubSubError::Publish, "publish")
+ (PubSubError::PublishOptions, "publish-options")
+ (PubSubError::PublishOnlyAffiliation, "publish-only-affiliation")
+ (PubSubError::PublisherAffiliation, "publisher-affiliation")
+ (PubSubError::PurgeNodes, "purge-nodes")
+ (PubSubError::RetractItems, "retract-items")
+ (PubSubError::RetrieveAffiliations, "retrieve-affiliations")
+ (PubSubError::RetrieveDefault, "retrieve-default")
+ (PubSubError::RetrieveItems, "retrieve-items")
+ (PubSubError::RetrieveSubscriptions, "retrieve-subscriptions")
+ (PubSubError::Subscribe, "subscribe")
+ (PubSubError::SubscriptionOptions, "subscription-options")
+ (PubSubError::SubscriptionNotifications, "subscription-notifications");
}
PubSubErrorParser::~PubSubErrorParser() {
}
void PubSubErrorParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level == 1) {
- if (boost::optional<PubSubError::Type> type = typeParser.parse(element)) {
- getPayloadInternal()->setType(*type);
- if (type == PubSubError::Unsupported) {
- if (boost::optional<std::string> feature = attributes.getAttributeValue("feature")) {
- if (boost::optional<PubSubError::UnsupportedFeatureType> unsupportedType = unsupportedTypeParser.parse(*feature)) {
- getPayloadInternal()->setUnsupportedFeatureType(*unsupportedType);
- }
- }
- }
- }
- }
- ++level;
+ if (level == 1) {
+ if (boost::optional<PubSubError::Type> type = typeParser.parse(element)) {
+ getPayloadInternal()->setType(*type);
+ if (type == PubSubError::Unsupported) {
+ if (boost::optional<std::string> feature = attributes.getAttributeValue("feature")) {
+ if (boost::optional<PubSubError::UnsupportedFeatureType> unsupportedType = unsupportedTypeParser.parse(*feature)) {
+ getPayloadInternal()->setUnsupportedFeatureType(*unsupportedType);
+ }
+ }
+ }
+ }
+ }
+ ++level;
}
void PubSubErrorParser::handleEndElement(const std::string&, const std::string&) {
- --level;
+ --level;
}
void PubSubErrorParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/PubSubErrorParser.h b/Swiften/Parser/PayloadParsers/PubSubErrorParser.h
index 73f4207..749fb1a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubErrorParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubErrorParser.h
@@ -15,21 +15,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubErrorParser : public GenericPayloadParser<PubSubError> {
- public:
- PubSubErrorParser();
- virtual ~PubSubErrorParser();
+ class SWIFTEN_API PubSubErrorParser : public GenericPayloadParser<PubSubError> {
+ public:
+ PubSubErrorParser();
+ virtual ~PubSubErrorParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- int level;
- EnumParser<PubSubError::Type> typeParser;
- EnumParser<PubSubError::UnsupportedFeatureType> unsupportedTypeParser;
- };
+ private:
+ int level;
+ EnumParser<PubSubError::Type> typeParser;
+ EnumParser<PubSubError::UnsupportedFeatureType> unsupportedTypeParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h b/Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h
index e421581..c7a3614 100644
--- a/Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/PayloadParsers/PubSubErrorParser.h>
namespace Swift {
- class SWIFTEN_API PubSubErrorParserFactory : public PayloadParserFactory {
- public:
- PubSubErrorParserFactory() {
- }
- ~PubSubErrorParserFactory();
+ class SWIFTEN_API PubSubErrorParserFactory : public PayloadParserFactory {
+ public:
+ PubSubErrorParserFactory() {
+ }
+ ~PubSubErrorParserFactory();
- virtual bool canParse(const std::string&, const std::string& ns, const AttributeMap&) const {
- return ns == "http://jabber.org/protocol/pubsub#errors";
- }
+ virtual bool canParse(const std::string&, const std::string& ns, const AttributeMap&) const {
+ return ns == "http://jabber.org/protocol/pubsub#errors";
+ }
- virtual PayloadParser* createPayloadParser() {
- return new PubSubErrorParser();
- }
- };
+ virtual PayloadParser* createPayloadParser() {
+ return new PubSubErrorParser();
+ }
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp
index dd740b3..c5d8959 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp
@@ -24,36 +24,36 @@ PubSubEventAssociateParser::~PubSubEventAssociateParser() {
}
void PubSubEventAssociateParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventAssociateParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventAssociateParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h
index 3e87523..c2cc9f6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventAssociateParser : public GenericPayloadParser<PubSubEventAssociate> {
- public:
- PubSubEventAssociateParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventAssociateParser();
+ class SWIFTEN_API PubSubEventAssociateParser : public GenericPayloadParser<PubSubEventAssociate> {
+ public:
+ PubSubEventAssociateParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventAssociateParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
index 373d971..bb167e3 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
@@ -25,48 +25,48 @@ PubSubEventCollectionParser::~PubSubEventCollectionParser() {
}
void PubSubEventCollectionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "disassociate" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventDisassociateParser>(parsers);
- }
- if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventAssociateParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "disassociate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventDisassociateParser>(parsers);
+ }
+ if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventAssociateParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventCollectionParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "disassociate" && ns == "http://jabber.org/protocol/pubsub#event") {
- getPayloadInternal()->setDisassociate(boost::dynamic_pointer_cast<PubSubEventDisassociate>(currentPayloadParser->getPayload()));
- }
- if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
- getPayloadInternal()->setAssociate(boost::dynamic_pointer_cast<PubSubEventAssociate>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "disassociate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->setDisassociate(boost::dynamic_pointer_cast<PubSubEventDisassociate>(currentPayloadParser->getPayload()));
+ }
+ if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->setAssociate(boost::dynamic_pointer_cast<PubSubEventAssociate>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventCollectionParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h
index 26d580b..a2b1663 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventCollectionParser : public GenericPayloadParser<PubSubEventCollection> {
- public:
- PubSubEventCollectionParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventCollectionParser();
+ class SWIFTEN_API PubSubEventCollectionParser : public GenericPayloadParser<PubSubEventCollection> {
+ public:
+ PubSubEventCollectionParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventCollectionParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
index 97e5ad9..d118ab8 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
@@ -24,42 +24,42 @@ PubSubEventConfigurationParser::~PubSubEventConfigurationParser() {
}
void PubSubEventConfigurationParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- currentPayloadParser = boost::make_shared<FormParser>();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = boost::make_shared<FormParser>();
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventConfigurationParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventConfigurationParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h
index f1f07b2..e3fcab6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventConfigurationParser : public GenericPayloadParser<PubSubEventConfiguration> {
- public:
- PubSubEventConfigurationParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventConfigurationParser();
+ class SWIFTEN_API PubSubEventConfigurationParser : public GenericPayloadParser<PubSubEventConfiguration> {
+ public:
+ PubSubEventConfigurationParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventConfigurationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
index 9641a03..167a682 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
@@ -24,42 +24,42 @@ PubSubEventDeleteParser::~PubSubEventDeleteParser() {
}
void PubSubEventDeleteParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventRedirectParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventRedirectParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventDeleteParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#event") {
- getPayloadInternal()->setRedirects(boost::dynamic_pointer_cast<PubSubEventRedirect>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->setRedirects(boost::dynamic_pointer_cast<PubSubEventRedirect>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventDeleteParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h
index 8a6f0eb..24d6b6b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventDeleteParser : public GenericPayloadParser<PubSubEventDelete> {
- public:
- PubSubEventDeleteParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventDeleteParser();
+ class SWIFTEN_API PubSubEventDeleteParser : public GenericPayloadParser<PubSubEventDelete> {
+ public:
+ PubSubEventDeleteParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventDeleteParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
index 25ec3a9..d0da109 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
@@ -24,36 +24,36 @@ PubSubEventDisassociateParser::~PubSubEventDisassociateParser() {
}
void PubSubEventDisassociateParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventDisassociateParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventDisassociateParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h
index a5dae6b..6835602 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventDisassociateParser : public GenericPayloadParser<PubSubEventDisassociate> {
- public:
- PubSubEventDisassociateParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventDisassociateParser();
+ class SWIFTEN_API PubSubEventDisassociateParser : public GenericPayloadParser<PubSubEventDisassociate> {
+ public:
+ PubSubEventDisassociateParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventDisassociateParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
index e245e63..fca2df8 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
@@ -24,46 +24,46 @@ PubSubEventItemParser::~PubSubEventItemParser() {
}
void PubSubEventItemParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("publisher")) {
- getPayloadInternal()->setPublisher(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
- getPayloadInternal()->setID(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("publisher")) {
+ getPayloadInternal()->setPublisher(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
+ getPayloadInternal()->setID(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
- currentPayloadParser.reset(factory->createPayloadParser());
- }
- }
+ if (level == 1) {
+ if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
+ currentPayloadParser.reset(factory->createPayloadParser());
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventItemParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- getPayloadInternal()->addData(currentPayloadParser->getPayload());
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ getPayloadInternal()->addData(currentPayloadParser->getPayload());
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventItemParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h
index faee9d3..4b34a26 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventItemParser : public GenericPayloadParser<PubSubEventItem> {
- public:
- PubSubEventItemParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventItemParser();
+ class SWIFTEN_API PubSubEventItemParser : public GenericPayloadParser<PubSubEventItem> {
+ public:
+ PubSubEventItemParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventItemParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
index 2aafb74..90d3fe8 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
@@ -25,48 +25,48 @@ PubSubEventItemsParser::~PubSubEventItemsParser() {
}
void PubSubEventItemsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventItemParser>(parsers);
- }
- if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventRetractParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventItemParser>(parsers);
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventRetractParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventItemsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub#event") {
- getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubEventItem>(currentPayloadParser->getPayload()));
- }
- if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
- getPayloadInternal()->addRetract(boost::dynamic_pointer_cast<PubSubEventRetract>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubEventItem>(currentPayloadParser->getPayload()));
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->addRetract(boost::dynamic_pointer_cast<PubSubEventRetract>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventItemsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h
index 1847be5..6cb0148 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventItemsParser : public GenericPayloadParser<PubSubEventItems> {
- public:
- PubSubEventItemsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventItemsParser();
+ class SWIFTEN_API PubSubEventItemsParser : public GenericPayloadParser<PubSubEventItems> {
+ public:
+ PubSubEventItemsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventItemsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
index 34db2f8..ae0439c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
@@ -29,53 +29,53 @@ PubSubEventParser::~PubSubEventParser() {
}
void PubSubEventParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
- if (level == 1) {
- if (element == "items" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventItemsParser>(parsers);
- }
- if (element == "collection" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventCollectionParser>(parsers);
- }
- if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventPurgeParser>(parsers);
- }
- if (element == "configuration" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventConfigurationParser>(parsers);
- }
- if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventDeleteParser>(parsers);
- }
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#event") {
- currentPayloadParser = boost::make_shared<PubSubEventSubscriptionParser>(parsers);
- }
- }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1) {
+ if (element == "items" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventItemsParser>(parsers);
+ }
+ if (element == "collection" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventCollectionParser>(parsers);
+ }
+ if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventPurgeParser>(parsers);
+ }
+ if (element == "configuration" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventConfigurationParser>(parsers);
+ }
+ if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventDeleteParser>(parsers);
+ }
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = boost::make_shared<PubSubEventSubscriptionParser>(parsers);
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (currentPayloadParser) {
- getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubEventPayload>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (currentPayloadParser) {
+ getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubEventPayload>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventParser.h b/Swiften/Parser/PayloadParsers/PubSubEventParser.h
index fc63528..a4fc5a6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventParser : public GenericPayloadParser<PubSubEvent> {
- public:
- PubSubEventParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventParser();
+ class SWIFTEN_API PubSubEventParser : public GenericPayloadParser<PubSubEvent> {
+ public:
+ PubSubEventParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
index cdd3808..09ceeea 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
@@ -24,36 +24,36 @@ PubSubEventPurgeParser::~PubSubEventPurgeParser() {
}
void PubSubEventPurgeParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventPurgeParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventPurgeParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h
index c174d5b..7afc754 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventPurgeParser : public GenericPayloadParser<PubSubEventPurge> {
- public:
- PubSubEventPurgeParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventPurgeParser();
+ class SWIFTEN_API PubSubEventPurgeParser : public GenericPayloadParser<PubSubEventPurge> {
+ public:
+ PubSubEventPurgeParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventPurgeParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
index 8ea236e..899c039 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
@@ -24,36 +24,36 @@ PubSubEventRedirectParser::~PubSubEventRedirectParser() {
}
void PubSubEventRedirectParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("uri")) {
- getPayloadInternal()->setURI(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("uri")) {
+ getPayloadInternal()->setURI(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventRedirectParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventRedirectParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h
index 3905285..ecdeca5 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventRedirectParser : public GenericPayloadParser<PubSubEventRedirect> {
- public:
- PubSubEventRedirectParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventRedirectParser();
+ class SWIFTEN_API PubSubEventRedirectParser : public GenericPayloadParser<PubSubEventRedirect> {
+ public:
+ PubSubEventRedirectParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventRedirectParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
index 7a4df14..32d88b4 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
@@ -24,36 +24,36 @@ PubSubEventRetractParser::~PubSubEventRetractParser() {
}
void PubSubEventRetractParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
- getPayloadInternal()->setID(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
+ getPayloadInternal()->setID(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventRetractParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventRetractParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h
index 99cc164..8bc6a9c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventRetractParser : public GenericPayloadParser<PubSubEventRetract> {
- public:
- PubSubEventRetractParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventRetractParser();
+ class SWIFTEN_API PubSubEventRetractParser : public GenericPayloadParser<PubSubEventRetract> {
+ public:
+ PubSubEventRetractParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventRetractParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
index 9308101..92d1a0c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
@@ -25,52 +25,52 @@ PubSubEventSubscriptionParser::~PubSubEventSubscriptionParser() {
}
void PubSubEventSubscriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
- if (boost::optional<PubSubEventSubscription::SubscriptionType> value = EnumParser<PubSubEventSubscription::SubscriptionType>()(PubSubEventSubscription::None, "none")(PubSubEventSubscription::Pending, "pending")(PubSubEventSubscription::Subscribed, "subscribed")(PubSubEventSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
- getPayloadInternal()->setSubscription(*value);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
- getPayloadInternal()->setSubscriptionID(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("expiry")) {
- getPayloadInternal()->setExpiry(stringToDateTime(*attributeValue));
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
+ if (boost::optional<PubSubEventSubscription::SubscriptionType> value = EnumParser<PubSubEventSubscription::SubscriptionType>()(PubSubEventSubscription::None, "none")(PubSubEventSubscription::Pending, "pending")(PubSubEventSubscription::Subscribed, "subscribed")(PubSubEventSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
+ getPayloadInternal()->setSubscription(*value);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
+ getPayloadInternal()->setSubscriptionID(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("expiry")) {
+ getPayloadInternal()->setExpiry(stringToDateTime(*attributeValue));
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubEventSubscriptionParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubEventSubscriptionParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h
index 24ce22a..b43e64a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubEventSubscriptionParser : public GenericPayloadParser<PubSubEventSubscription> {
- public:
- PubSubEventSubscriptionParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubEventSubscriptionParser();
+ class SWIFTEN_API PubSubEventSubscriptionParser : public GenericPayloadParser<PubSubEventSubscription> {
+ public:
+ PubSubEventSubscriptionParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubEventSubscriptionParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp b/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
index a2b22ac..8537ecb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
@@ -24,40 +24,40 @@ PubSubItemParser::~PubSubItemParser() {
}
void PubSubItemParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
- getPayloadInternal()->setID(*attributeValue);
- }
- }
-
- if (level == 1) {
- if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
- currentPayloadParser.reset(factory->createPayloadParser());
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("id")) {
+ getPayloadInternal()->setID(*attributeValue);
+ }
+ }
+
+ if (level == 1) {
+ if (PayloadParserFactory* factory = parsers->getPayloadParserFactory(element, ns, attributes)) {
+ currentPayloadParser.reset(factory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubItemParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- getPayloadInternal()->addData(currentPayloadParser->getPayload());
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ getPayloadInternal()->addData(currentPayloadParser->getPayload());
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubItemParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemParser.h b/Swiften/Parser/PayloadParsers/PubSubItemParser.h
index e584797..39d24bc 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubItemParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubItemParser : public GenericPayloadParser<PubSubItem> {
- public:
- PubSubItemParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubItemParser();
+ class SWIFTEN_API PubSubItemParser : public GenericPayloadParser<PubSubItem> {
+ public:
+ PubSubItemParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubItemParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
index f07b6fa..643eb85 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
@@ -24,52 +24,52 @@ PubSubItemsParser::~PubSubItemsParser() {
}
void PubSubItemsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("max_items")) {
- try {
- getPayloadInternal()->setMaximumItems(boost::lexical_cast<unsigned int>(*attributeValue));
- }
- catch (boost::bad_lexical_cast&) {
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
- getPayloadInternal()->setSubscriptionID(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("max_items")) {
+ try {
+ getPayloadInternal()->setMaximumItems(boost::lexical_cast<unsigned int>(*attributeValue));
+ }
+ catch (boost::bad_lexical_cast&) {
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
+ getPayloadInternal()->setSubscriptionID(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubItemsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubItemsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemsParser.h b/Swiften/Parser/PayloadParsers/PubSubItemsParser.h
index 5f3afd3..84c8f79 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubItemsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubItemsParser : public GenericPayloadParser<PubSubItems> {
- public:
- PubSubItemsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubItemsParser();
+ class SWIFTEN_API PubSubItemsParser : public GenericPayloadParser<PubSubItems> {
+ public:
+ PubSubItemsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubItemsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
index 438d728..2683ae6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
@@ -24,50 +24,50 @@ PubSubOptionsParser::~PubSubOptionsParser() {
}
void PubSubOptionsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
- getPayloadInternal()->setSubscriptionID(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
+ getPayloadInternal()->setSubscriptionID(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- currentPayloadParser = boost::make_shared<FormParser>();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = boost::make_shared<FormParser>();
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOptionsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOptionsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h
index 3070cec..52d374c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOptionsParser : public GenericPayloadParser<PubSubOptions> {
- public:
- PubSubOptionsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOptionsParser();
+ class SWIFTEN_API PubSubOptionsParser : public GenericPayloadParser<PubSubOptions> {
+ public:
+ PubSubOptionsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOptionsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
index 3a8ceb8..eb63696 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
@@ -24,43 +24,43 @@ PubSubOwnerAffiliationParser::~PubSubOwnerAffiliationParser() {
}
void PubSubOwnerAffiliationParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("affiliation")) {
- if (boost::optional<PubSubOwnerAffiliation::Type> value = EnumParser<PubSubOwnerAffiliation::Type>()(PubSubOwnerAffiliation::None, "none")(PubSubOwnerAffiliation::Member, "member")(PubSubOwnerAffiliation::Outcast, "outcast")(PubSubOwnerAffiliation::Owner, "owner")(PubSubOwnerAffiliation::Publisher, "publisher")(PubSubOwnerAffiliation::PublishOnly, "publish-only").parse(*attributeValue)) {
- getPayloadInternal()->setType(*value);
- }
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("affiliation")) {
+ if (boost::optional<PubSubOwnerAffiliation::Type> value = EnumParser<PubSubOwnerAffiliation::Type>()(PubSubOwnerAffiliation::None, "none")(PubSubOwnerAffiliation::Member, "member")(PubSubOwnerAffiliation::Outcast, "outcast")(PubSubOwnerAffiliation::Owner, "owner")(PubSubOwnerAffiliation::Publisher, "publisher")(PubSubOwnerAffiliation::PublishOnly, "publish-only").parse(*attributeValue)) {
+ getPayloadInternal()->setType(*value);
+ }
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerAffiliationParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerAffiliationParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h
index f412ab5..972930c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerAffiliationParser : public GenericPayloadParser<PubSubOwnerAffiliation> {
- public:
- PubSubOwnerAffiliationParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerAffiliationParser();
+ class SWIFTEN_API PubSubOwnerAffiliationParser : public GenericPayloadParser<PubSubOwnerAffiliation> {
+ public:
+ PubSubOwnerAffiliationParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerAffiliationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
index df3813e..247bf4c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
@@ -24,42 +24,42 @@ PubSubOwnerAffiliationsParser::~PubSubOwnerAffiliationsParser() {
}
void PubSubOwnerAffiliationsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerAffiliationParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerAffiliationParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerAffiliationsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub#owner") {
- getPayloadInternal()->addAffiliation(boost::dynamic_pointer_cast<PubSubOwnerAffiliation>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ getPayloadInternal()->addAffiliation(boost::dynamic_pointer_cast<PubSubOwnerAffiliation>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerAffiliationsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h
index c1cc4a0..870d809 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerAffiliationsParser : public GenericPayloadParser<PubSubOwnerAffiliations> {
- public:
- PubSubOwnerAffiliationsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerAffiliationsParser();
+ class SWIFTEN_API PubSubOwnerAffiliationsParser : public GenericPayloadParser<PubSubOwnerAffiliations> {
+ public:
+ PubSubOwnerAffiliationsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerAffiliationsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
index 1cc8660..62dd1ac 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
@@ -24,42 +24,42 @@ PubSubOwnerConfigureParser::~PubSubOwnerConfigureParser() {
}
void PubSubOwnerConfigureParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- currentPayloadParser = boost::make_shared<FormParser>();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = boost::make_shared<FormParser>();
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerConfigureParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerConfigureParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h
index 0a96aa7..914a309 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerConfigureParser : public GenericPayloadParser<PubSubOwnerConfigure> {
- public:
- PubSubOwnerConfigureParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerConfigureParser();
+ class SWIFTEN_API PubSubOwnerConfigureParser : public GenericPayloadParser<PubSubOwnerConfigure> {
+ public:
+ PubSubOwnerConfigureParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerConfigureParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
index a704411..36ccbaf 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
@@ -24,38 +24,38 @@ PubSubOwnerDefaultParser::~PubSubOwnerDefaultParser() {
}
void PubSubOwnerDefaultParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
-
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- currentPayloadParser = boost::make_shared<FormParser>();
- }
- }
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = boost::make_shared<FormParser>();
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerDefaultParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- if (element == "x" && ns == "jabber:x:data") {
- getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ getPayloadInternal()->setData(boost::dynamic_pointer_cast<Form>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerDefaultParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h
index 5ab8f8f..3106854 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerDefaultParser : public GenericPayloadParser<PubSubOwnerDefault> {
- public:
- PubSubOwnerDefaultParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerDefaultParser();
+ class SWIFTEN_API PubSubOwnerDefaultParser : public GenericPayloadParser<PubSubOwnerDefault> {
+ public:
+ PubSubOwnerDefaultParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerDefaultParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
index 9817793..047fe8b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
@@ -24,42 +24,42 @@ PubSubOwnerDeleteParser::~PubSubOwnerDeleteParser() {
}
void PubSubOwnerDeleteParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerRedirectParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerRedirectParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerDeleteParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#owner") {
- getPayloadInternal()->setRedirect(boost::dynamic_pointer_cast<PubSubOwnerRedirect>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "redirect" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ getPayloadInternal()->setRedirect(boost::dynamic_pointer_cast<PubSubOwnerRedirect>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerDeleteParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h
index 25a1f03..f56ae3c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerDeleteParser : public GenericPayloadParser<PubSubOwnerDelete> {
- public:
- PubSubOwnerDeleteParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerDeleteParser();
+ class SWIFTEN_API PubSubOwnerDeleteParser : public GenericPayloadParser<PubSubOwnerDelete> {
+ public:
+ PubSubOwnerDeleteParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerDeleteParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
index 71b1c16..aa7310e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
@@ -29,53 +29,53 @@ PubSubOwnerPubSubParser::~PubSubOwnerPubSubParser() {
}
void PubSubOwnerPubSubParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
- if (level == 1) {
- if (element == "configure" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerConfigureParser>(parsers);
- }
- if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerSubscriptionsParser>(parsers);
- }
- if (element == "default" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerDefaultParser>(parsers);
- }
- if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerPurgeParser>(parsers);
- }
- if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerAffiliationsParser>(parsers);
- }
- if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerDeleteParser>(parsers);
- }
- }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 1) {
+ if (element == "configure" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerConfigureParser>(parsers);
+ }
+ if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerSubscriptionsParser>(parsers);
+ }
+ if (element == "default" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerDefaultParser>(parsers);
+ }
+ if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerPurgeParser>(parsers);
+ }
+ if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerAffiliationsParser>(parsers);
+ }
+ if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerDeleteParser>(parsers);
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerPubSubParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (currentPayloadParser) {
- getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubOwnerPayload>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (currentPayloadParser) {
+ getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubOwnerPayload>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerPubSubParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h
index bd6f3a5..d4d67f9 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerPubSubParser : public GenericPayloadParser<PubSubOwnerPubSub> {
- public:
- PubSubOwnerPubSubParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerPubSubParser();
+ class SWIFTEN_API PubSubOwnerPubSubParser : public GenericPayloadParser<PubSubOwnerPubSub> {
+ public:
+ PubSubOwnerPubSubParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerPubSubParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
index f417ec2..68224f6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
@@ -24,36 +24,36 @@ PubSubOwnerPurgeParser::~PubSubOwnerPurgeParser() {
}
void PubSubOwnerPurgeParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerPurgeParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerPurgeParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h
index baccb9a..364de29 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerPurgeParser : public GenericPayloadParser<PubSubOwnerPurge> {
- public:
- PubSubOwnerPurgeParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerPurgeParser();
+ class SWIFTEN_API PubSubOwnerPurgeParser : public GenericPayloadParser<PubSubOwnerPurge> {
+ public:
+ PubSubOwnerPurgeParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerPurgeParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
index e4ad149..72c19dd 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
@@ -24,36 +24,36 @@ PubSubOwnerRedirectParser::~PubSubOwnerRedirectParser() {
}
void PubSubOwnerRedirectParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("uri")) {
- getPayloadInternal()->setURI(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("uri")) {
+ getPayloadInternal()->setURI(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerRedirectParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerRedirectParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h
index b277af9..fd48dbb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerRedirectParser : public GenericPayloadParser<PubSubOwnerRedirect> {
- public:
- PubSubOwnerRedirectParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerRedirectParser();
+ class SWIFTEN_API PubSubOwnerRedirectParser : public GenericPayloadParser<PubSubOwnerRedirect> {
+ public:
+ PubSubOwnerRedirectParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerRedirectParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
index 9e2fdee..ee4c34f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
@@ -24,43 +24,43 @@ PubSubOwnerSubscriptionParser::~PubSubOwnerSubscriptionParser() {
}
void PubSubOwnerSubscriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
- if (boost::optional<PubSubOwnerSubscription::SubscriptionType> value = EnumParser<PubSubOwnerSubscription::SubscriptionType>()(PubSubOwnerSubscription::None, "none")(PubSubOwnerSubscription::Pending, "pending")(PubSubOwnerSubscription::Subscribed, "subscribed")(PubSubOwnerSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
- getPayloadInternal()->setSubscription(*value);
- }
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
+ if (boost::optional<PubSubOwnerSubscription::SubscriptionType> value = EnumParser<PubSubOwnerSubscription::SubscriptionType>()(PubSubOwnerSubscription::None, "none")(PubSubOwnerSubscription::Pending, "pending")(PubSubOwnerSubscription::Subscribed, "subscribed")(PubSubOwnerSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
+ getPayloadInternal()->setSubscription(*value);
+ }
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerSubscriptionParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerSubscriptionParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h
index c76734f..46df820 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerSubscriptionParser : public GenericPayloadParser<PubSubOwnerSubscription> {
- public:
- PubSubOwnerSubscriptionParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerSubscriptionParser();
+ class SWIFTEN_API PubSubOwnerSubscriptionParser : public GenericPayloadParser<PubSubOwnerSubscription> {
+ public:
+ PubSubOwnerSubscriptionParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerSubscriptionParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
index 857bd87..e08d782 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
@@ -24,42 +24,42 @@ PubSubOwnerSubscriptionsParser::~PubSubOwnerSubscriptionsParser() {
}
void PubSubOwnerSubscriptionsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#owner") {
- currentPayloadParser = boost::make_shared<PubSubOwnerSubscriptionParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = boost::make_shared<PubSubOwnerSubscriptionParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubOwnerSubscriptionsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#owner") {
- getPayloadInternal()->addSubscription(boost::dynamic_pointer_cast<PubSubOwnerSubscription>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ getPayloadInternal()->addSubscription(boost::dynamic_pointer_cast<PubSubOwnerSubscription>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubOwnerSubscriptionsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h
index 35a18fb..10c11e4 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubOwnerSubscriptionsParser : public GenericPayloadParser<PubSubOwnerSubscriptions> {
- public:
- PubSubOwnerSubscriptionsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubOwnerSubscriptionsParser();
+ class SWIFTEN_API PubSubOwnerSubscriptionsParser : public GenericPayloadParser<PubSubOwnerSubscriptions> {
+ public:
+ PubSubOwnerSubscriptionsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubOwnerSubscriptionsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubParser.cpp b/Swiften/Parser/PayloadParsers/PubSubParser.cpp
index c6574a8..9c86c21 100644
--- a/Swiften/Parser/PayloadParsers/PubSubParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubParser.cpp
@@ -36,90 +36,90 @@ PubSubParser::~PubSubParser() {
}
void PubSubParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 1) {
- if (element == "items" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubItemsParser>(parsers);
- }
- if (element == "create" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubCreateParser>(parsers);
- }
- if (element == "publish" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubPublishParser>(parsers);
- }
- if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubAffiliationsParser>(parsers);
- }
- if (element == "retract" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubRetractParser>(parsers);
- }
- if (element == "options" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubOptionsParser>(parsers);
- }
- if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubConfigureParser>(parsers);
- }
- if (element == "default" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubDefaultParser>(parsers);
- }
- if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubSubscriptionsParser>(parsers);
- }
- if (element == "subscribe" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubSubscribeParser>(parsers);
- }
- if (element == "unsubscribe" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubUnsubscribeParser>(parsers);
- }
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubSubscriptionParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "items" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubItemsParser>(parsers);
+ }
+ if (element == "create" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubCreateParser>(parsers);
+ }
+ if (element == "publish" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubPublishParser>(parsers);
+ }
+ if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubAffiliationsParser>(parsers);
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubRetractParser>(parsers);
+ }
+ if (element == "options" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubOptionsParser>(parsers);
+ }
+ if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubConfigureParser>(parsers);
+ }
+ if (element == "default" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubDefaultParser>(parsers);
+ }
+ if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubSubscriptionsParser>(parsers);
+ }
+ if (element == "subscribe" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubSubscribeParser>(parsers);
+ }
+ if (element == "unsubscribe" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubUnsubscribeParser>(parsers);
+ }
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubSubscriptionParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (currentPayloadParser) {
- if (element == "options" && ns == "http://jabber.org/protocol/pubsub") {
- optionsPayload = boost::dynamic_pointer_cast<PubSubOptions>(currentPayloadParser->getPayload());
- }
- else if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
- configurePayload = boost::dynamic_pointer_cast<PubSubConfigure>(currentPayloadParser->getPayload());
- }
- else {
- getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubPayload>(currentPayloadParser->getPayload()));
- }
- }
- currentPayloadParser.reset();
- }
+ if (level == 1) {
+ if (currentPayloadParser) {
+ if (element == "options" && ns == "http://jabber.org/protocol/pubsub") {
+ optionsPayload = boost::dynamic_pointer_cast<PubSubOptions>(currentPayloadParser->getPayload());
+ }
+ else if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
+ configurePayload = boost::dynamic_pointer_cast<PubSubConfigure>(currentPayloadParser->getPayload());
+ }
+ else {
+ getPayloadInternal()->setPayload(boost::dynamic_pointer_cast<PubSubPayload>(currentPayloadParser->getPayload()));
+ }
+ }
+ currentPayloadParser.reset();
+ }
- if (level == 0) {
- if (boost::shared_ptr<PubSubCreate> create = boost::dynamic_pointer_cast<PubSubCreate>(getPayloadInternal()->getPayload())) {
- if (configurePayload) {
- create->setConfigure(configurePayload);
- }
- }
- if (boost::shared_ptr<PubSubSubscribe> subscribe = boost::dynamic_pointer_cast<PubSubSubscribe>(getPayloadInternal()->getPayload())) {
- if (optionsPayload) {
- subscribe->setOptions(optionsPayload);
- }
- }
- }
- }
+ if (level == 0) {
+ if (boost::shared_ptr<PubSubCreate> create = boost::dynamic_pointer_cast<PubSubCreate>(getPayloadInternal()->getPayload())) {
+ if (configurePayload) {
+ create->setConfigure(configurePayload);
+ }
+ }
+ if (boost::shared_ptr<PubSubSubscribe> subscribe = boost::dynamic_pointer_cast<PubSubSubscribe>(getPayloadInternal()->getPayload())) {
+ if (optionsPayload) {
+ subscribe->setOptions(optionsPayload);
+ }
+ }
+ }
+ }
}
void PubSubParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubParser.h b/Swiften/Parser/PayloadParsers/PubSubParser.h
index 1ccae54..a8043fc 100644
--- a/Swiften/Parser/PayloadParsers/PubSubParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubParser.h
@@ -14,25 +14,25 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
- class PubSubOptions;
- class PubSubConfigure;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
+ class PubSubOptions;
+ class PubSubConfigure;
- class SWIFTEN_API PubSubParser : public GenericPayloadParser<PubSub> {
- public:
- PubSubParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubParser();
+ class SWIFTEN_API PubSubParser : public GenericPayloadParser<PubSub> {
+ public:
+ PubSubParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- boost::shared_ptr<PubSubConfigure> configurePayload;
- boost::shared_ptr<PubSubOptions> optionsPayload;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ boost::shared_ptr<PubSubConfigure> configurePayload;
+ boost::shared_ptr<PubSubOptions> optionsPayload;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp b/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
index 2b52edc..3bd3ac0 100644
--- a/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
@@ -24,42 +24,42 @@ PubSubPublishParser::~PubSubPublishParser() {
}
void PubSubPublishParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubPublishParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubPublishParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubPublishParser.h b/Swiften/Parser/PayloadParsers/PubSubPublishParser.h
index 6b60457..1df7c6f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubPublishParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubPublishParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubPublishParser : public GenericPayloadParser<PubSubPublish> {
- public:
- PubSubPublishParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubPublishParser();
+ class SWIFTEN_API PubSubPublishParser : public GenericPayloadParser<PubSubPublish> {
+ public:
+ PubSubPublishParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubPublishParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp b/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
index 909e82f..e710fad 100644
--- a/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
@@ -24,45 +24,45 @@ PubSubRetractParser::~PubSubRetractParser() {
}
void PubSubRetractParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("notify")) {
- getPayloadInternal()->setNotify(*attributeValue == "true" ? true : false);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("notify")) {
+ getPayloadInternal()->setNotify(*attributeValue == "true" ? true : false);
+ }
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubItemParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubRetractParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "item" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addItem(boost::dynamic_pointer_cast<PubSubItem>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubRetractParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubRetractParser.h b/Swiften/Parser/PayloadParsers/PubSubRetractParser.h
index 9b1a052..ece2a52 100644
--- a/Swiften/Parser/PayloadParsers/PubSubRetractParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubRetractParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubRetractParser : public GenericPayloadParser<PubSubRetract> {
- public:
- PubSubRetractParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubRetractParser();
+ class SWIFTEN_API PubSubRetractParser : public GenericPayloadParser<PubSubRetract> {
+ public:
+ PubSubRetractParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubRetractParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
index 64bea49..120d704 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
@@ -24,34 +24,34 @@ PubSubSubscribeOptionsParser::~PubSubSubscribeOptionsParser() {
}
void PubSubSubscribeOptionsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubSubscribeOptionsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
- if (element == "required") {
- getPayloadInternal()->setRequired(true);
- }
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ if (element == "required") {
+ getPayloadInternal()->setRequired(true);
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubSubscribeOptionsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h
index 7fb140a..9136f44 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubSubscribeOptionsParser : public GenericPayloadParser<PubSubSubscribeOptions> {
- public:
- PubSubSubscribeOptionsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubSubscribeOptionsParser();
+ class SWIFTEN_API PubSubSubscribeOptionsParser : public GenericPayloadParser<PubSubSubscribeOptions> {
+ public:
+ PubSubSubscribeOptionsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubSubscribeOptionsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
index 3f34fc7..f049642 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
@@ -24,41 +24,41 @@ PubSubSubscribeParser::~PubSubSubscribeParser() {
}
void PubSubSubscribeParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubSubscribeParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubSubscribeParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h
index 72d0233..823c086 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubSubscribeParser : public GenericPayloadParser<PubSubSubscribe> {
- public:
- PubSubSubscribeParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubSubscribeParser();
+ class SWIFTEN_API PubSubSubscribeParser : public GenericPayloadParser<PubSubSubscribe> {
+ public:
+ PubSubSubscribeParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubSubscribeParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
index b78c841..5954bf1 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
@@ -25,55 +25,55 @@ PubSubSubscriptionParser::~PubSubSubscriptionParser() {
}
void PubSubSubscriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
- getPayloadInternal()->setSubscriptionID(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
- if (boost::optional<PubSubSubscription::SubscriptionType> value = EnumParser<PubSubSubscription::SubscriptionType>()(PubSubSubscription::None, "none")(PubSubSubscription::Pending, "pending")(PubSubSubscription::Subscribed, "subscribed")(PubSubSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
- getPayloadInternal()->setSubscription(*value);
- }
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
+ getPayloadInternal()->setSubscriptionID(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subscription")) {
+ if (boost::optional<PubSubSubscription::SubscriptionType> value = EnumParser<PubSubSubscription::SubscriptionType>()(PubSubSubscription::None, "none")(PubSubSubscription::Pending, "pending")(PubSubSubscription::Subscribed, "subscribed")(PubSubSubscription::Unconfigured, "unconfigured").parse(*attributeValue)) {
+ getPayloadInternal()->setSubscription(*value);
+ }
+ }
+ }
- if (level == 1) {
- if (element == "subscribe-options" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubSubscribeOptionsParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "subscribe-options" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubSubscribeOptionsParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubSubscriptionParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "subscribe-options" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->setOptions(boost::dynamic_pointer_cast<PubSubSubscribeOptions>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "subscribe-options" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->setOptions(boost::dynamic_pointer_cast<PubSubSubscribeOptions>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubSubscriptionParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h
index b5eeb5a..771a74a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubSubscriptionParser : public GenericPayloadParser<PubSubSubscription> {
- public:
- PubSubSubscriptionParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubSubscriptionParser();
+ class SWIFTEN_API PubSubSubscriptionParser : public GenericPayloadParser<PubSubSubscription> {
+ public:
+ PubSubSubscriptionParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubSubscriptionParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
index 85929a4..30198a5 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
@@ -24,42 +24,42 @@ PubSubSubscriptionsParser::~PubSubSubscriptionsParser() {
}
void PubSubSubscriptionsParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- }
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
- if (level == 1) {
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
- currentPayloadParser = boost::make_shared<PubSubSubscriptionParser>(parsers);
- }
- }
+ if (level == 1) {
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = boost::make_shared<PubSubSubscriptionParser>(parsers);
+ }
+ }
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubSubscriptionsParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
- if (level == 1) {
- if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addSubscription(boost::dynamic_pointer_cast<PubSubSubscription>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ if (level == 1) {
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addSubscription(boost::dynamic_pointer_cast<PubSubSubscription>(currentPayloadParser->getPayload()));
+ }
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubSubscriptionsParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h
index 0b5378e..9f18376 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubSubscriptionsParser : public GenericPayloadParser<PubSubSubscriptions> {
- public:
- PubSubSubscriptionsParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubSubscriptionsParser();
+ class SWIFTEN_API PubSubSubscriptionsParser : public GenericPayloadParser<PubSubSubscriptions> {
+ public:
+ PubSubSubscriptionsParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubSubscriptionsParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
index 1b1808e..e3e7d23 100644
--- a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
@@ -24,44 +24,44 @@ PubSubUnsubscribeParser::~PubSubUnsubscribeParser() {
}
void PubSubUnsubscribeParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
- getPayloadInternal()->setNode(*attributeValue);
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
- if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
- getPayloadInternal()->setJID(*jid);
- }
- }
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
- getPayloadInternal()->setSubscriptionID(*attributeValue);
- }
- }
-
-
-
- if (level >= 1 && currentPayloadParser) {
- currentPayloadParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (level == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) {
+ if (boost::optional<JID> jid = JID::parse(*attributeValue)) {
+ getPayloadInternal()->setJID(*jid);
+ }
+ }
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("subid")) {
+ getPayloadInternal()->setSubscriptionID(*attributeValue);
+ }
+ }
+
+
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+ ++level;
}
void PubSubUnsubscribeParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (currentPayloadParser) {
- if (level >= 1) {
- currentPayloadParser->handleEndElement(element, ns);
- }
-
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+
+ currentPayloadParser.reset();
+ }
+ }
}
void PubSubUnsubscribeParser::handleCharacterData(const std::string& data) {
- if (level > 1 && currentPayloadParser) {
- currentPayloadParser->handleCharacterData(data);
- }
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h
index 0de1fab..d33d33c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h
@@ -14,21 +14,21 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class PayloadParser;
+ class PayloadParserFactoryCollection;
+ class PayloadParser;
- class SWIFTEN_API PubSubUnsubscribeParser : public GenericPayloadParser<PubSubUnsubscribe> {
- public:
- PubSubUnsubscribeParser(PayloadParserFactoryCollection* parsers);
- virtual ~PubSubUnsubscribeParser();
+ class SWIFTEN_API PubSubUnsubscribeParser : public GenericPayloadParser<PubSubUnsubscribe> {
+ public:
+ PubSubUnsubscribeParser(PayloadParserFactoryCollection* parsers);
+ virtual ~PubSubUnsubscribeParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- PayloadParserFactoryCollection* parsers;
- int level;
- boost::shared_ptr<PayloadParser> currentPayloadParser;
- };
+ private:
+ PayloadParserFactoryCollection* parsers;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
index 700624f..97abce3 100644
--- a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
@@ -14,20 +14,20 @@ RawXMLPayloadParser::RawXMLPayloadParser() : level_(0) {
}
void RawXMLPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- ++level_;
- serializingParser_.handleStartElement(element, ns, attributes);
+ ++level_;
+ serializingParser_.handleStartElement(element, ns, attributes);
}
void RawXMLPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
- serializingParser_.handleEndElement(element, ns);
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setRawXML(serializingParser_.getResult());
- }
+ serializingParser_.handleEndElement(element, ns);
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setRawXML(serializingParser_.getResult());
+ }
}
void RawXMLPayloadParser::handleCharacterData(const std::string& data) {
- serializingParser_.handleCharacterData(data);
+ serializingParser_.handleCharacterData(data);
}
}
diff --git a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h
index e3c5993..1f20105 100644
--- a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h
@@ -12,18 +12,18 @@
#include <Swiften/Parser/SerializingParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API RawXMLPayloadParser : public GenericPayloadParser<RawXMLPayload> {
- public:
- RawXMLPayloadParser();
+ class SWIFTEN_API RawXMLPayloadParser : public GenericPayloadParser<RawXMLPayload> {
+ public:
+ RawXMLPayloadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- SerializingParser serializingParser_;
- };
+ private:
+ int level_;
+ SerializingParser serializingParser_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h
index c7bae9d..f7b7601 100644
--- a/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h
@@ -13,16 +13,16 @@
#include <Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h>
namespace Swift {
- class SWIFTEN_API RawXMLPayloadParserFactory : public PayloadParserFactory {
- public:
- RawXMLPayloadParserFactory() {}
+ class SWIFTEN_API RawXMLPayloadParserFactory : public PayloadParserFactory {
+ public:
+ RawXMLPayloadParserFactory() {}
- virtual bool canParse(const std::string&, const std::string&, const AttributeMap&) const {
- return true;
- }
+ virtual bool canParse(const std::string&, const std::string&, const AttributeMap&) const {
+ return true;
+ }
- virtual PayloadParser* createPayloadParser() {
- return new RawXMLPayloadParser();
- }
- };
+ virtual PayloadParser* createPayloadParser() {
+ return new RawXMLPayloadParser();
+ }
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ReplaceParser.cpp b/Swiften/Parser/PayloadParsers/ReplaceParser.cpp
index f3483be..66e219a 100644
--- a/Swiften/Parser/PayloadParsers/ReplaceParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ReplaceParser.cpp
@@ -16,22 +16,22 @@
namespace Swift {
- ReplaceParser::ReplaceParser() : level_(0) {
- }
-
- void ReplaceParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (level_ == 0) {
- std::string id = attributes.getAttribute("id");
- getPayloadInternal()->setID(id);
- }
- level_++;
- }
-
- void ReplaceParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- }
-
- void ReplaceParser::handleCharacterData(const std::string&) {
- }
+ ReplaceParser::ReplaceParser() : level_(0) {
+ }
+
+ void ReplaceParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
+ if (level_ == 0) {
+ std::string id = attributes.getAttribute("id");
+ getPayloadInternal()->setID(id);
+ }
+ level_++;
+ }
+
+ void ReplaceParser::handleEndElement(const std::string&, const std::string&) {
+ --level_;
+ }
+
+ void ReplaceParser::handleCharacterData(const std::string&) {
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/ReplaceParser.h b/Swiften/Parser/PayloadParsers/ReplaceParser.h
index 3c1fbbc..21d7322 100644
--- a/Swiften/Parser/PayloadParsers/ReplaceParser.h
+++ b/Swiften/Parser/PayloadParsers/ReplaceParser.h
@@ -17,14 +17,14 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API ReplaceParser : public GenericPayloadParser<Replace> {
- public:
- ReplaceParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ class SWIFTEN_API ReplaceParser : public GenericPayloadParser<Replace> {
+ public:
+ ReplaceParser();
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- };
+ private:
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ResourceBindParser.cpp b/Swiften/Parser/PayloadParsers/ResourceBindParser.cpp
index c49f9a4..2965d66 100644
--- a/Swiften/Parser/PayloadParsers/ResourceBindParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ResourceBindParser.cpp
@@ -12,32 +12,32 @@ ResourceBindParser::ResourceBindParser() : level_(0), inJID_(false), inResource_
}
void ResourceBindParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
- if (level_ == 1) {
- text_ = "";
- if (element == "resource") {
- inResource_ = true;
- }
- if (element == "jid") {
- inJID_ = true;
- }
- }
- ++level_;
+ if (level_ == 1) {
+ text_ = "";
+ if (element == "resource") {
+ inResource_ = true;
+ }
+ if (element == "jid") {
+ inJID_ = true;
+ }
+ }
+ ++level_;
}
void ResourceBindParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 1) {
- if (inJID_) {
- getPayloadInternal()->setJID(JID(text_));
- }
- else if (inResource_) {
- getPayloadInternal()->setResource(text_);
- }
- }
+ --level_;
+ if (level_ == 1) {
+ if (inJID_) {
+ getPayloadInternal()->setJID(JID(text_));
+ }
+ else if (inResource_) {
+ getPayloadInternal()->setResource(text_);
+ }
+ }
}
void ResourceBindParser::handleCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/ResourceBindParser.h b/Swiften/Parser/PayloadParsers/ResourceBindParser.h
index 134bf14..3619c0b 100644
--- a/Swiften/Parser/PayloadParsers/ResourceBindParser.h
+++ b/Swiften/Parser/PayloadParsers/ResourceBindParser.h
@@ -11,18 +11,18 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API ResourceBindParser : public GenericPayloadParser<ResourceBind> {
- public:
- ResourceBindParser();
+ class SWIFTEN_API ResourceBindParser : public GenericPayloadParser<ResourceBind> {
+ public:
+ ResourceBindParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- bool inJID_;
- bool inResource_;
- std::string text_;
- };
+ private:
+ int level_;
+ bool inJID_;
+ bool inResource_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ResultSetParser.cpp b/Swiften/Parser/PayloadParsers/ResultSetParser.cpp
index c6cb964..80d89d7 100644
--- a/Swiften/Parser/PayloadParsers/ResultSetParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ResultSetParser.cpp
@@ -18,50 +18,50 @@ ResultSetParser::ResultSetParser() : level_(TopLevel) {
}
void ResultSetParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- currentText_ = "";
- if (level_ == PayloadLevel) {
- if (element == "first" && ns == "http://jabber.org/protocol/rsm") {
- if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("index")) {
- try {
- getPayloadInternal()->setFirstIDIndex(boost::lexical_cast<int>(*attributeValue));
- } catch(boost::bad_lexical_cast&) {
- }
- }
- }
- }
- ++level_;
+ currentText_ = "";
+ if (level_ == PayloadLevel) {
+ if (element == "first" && ns == "http://jabber.org/protocol/rsm") {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("index")) {
+ try {
+ getPayloadInternal()->setFirstIDIndex(boost::lexical_cast<int>(*attributeValue));
+ } catch(boost::bad_lexical_cast&) {
+ }
+ }
+ }
+ }
+ ++level_;
}
void ResultSetParser::handleEndElement(const std::string& element, const std::string&) {
- --level_;
- if (level_ == PayloadLevel) {
- if (element == "max") {
- try {
- getPayloadInternal()->setMaxItems(boost::lexical_cast<int>(currentText_));
- } catch(boost::bad_lexical_cast&) {
- }
- } else if (element == "count") {
- try {
- getPayloadInternal()->setCount(boost::lexical_cast<int>(currentText_));
- } catch(boost::bad_lexical_cast&) {
- }
- } else if (element == "index") {
- try {
- getPayloadInternal()->setIndex(boost::lexical_cast<int>(currentText_));
- } catch(boost::bad_lexical_cast&) {
- }
- } else if (element == "first") {
- getPayloadInternal()->setFirstID(currentText_);
- } else if (element == "last") {
- getPayloadInternal()->setLastID(currentText_);
- } else if (element == "before") {
- getPayloadInternal()->setBefore(currentText_);
- } else if (element == "after") {
- getPayloadInternal()->setAfter(currentText_);
- }
- }
+ --level_;
+ if (level_ == PayloadLevel) {
+ if (element == "max") {
+ try {
+ getPayloadInternal()->setMaxItems(boost::lexical_cast<int>(currentText_));
+ } catch(boost::bad_lexical_cast&) {
+ }
+ } else if (element == "count") {
+ try {
+ getPayloadInternal()->setCount(boost::lexical_cast<int>(currentText_));
+ } catch(boost::bad_lexical_cast&) {
+ }
+ } else if (element == "index") {
+ try {
+ getPayloadInternal()->setIndex(boost::lexical_cast<int>(currentText_));
+ } catch(boost::bad_lexical_cast&) {
+ }
+ } else if (element == "first") {
+ getPayloadInternal()->setFirstID(currentText_);
+ } else if (element == "last") {
+ getPayloadInternal()->setLastID(currentText_);
+ } else if (element == "before") {
+ getPayloadInternal()->setBefore(currentText_);
+ } else if (element == "after") {
+ getPayloadInternal()->setAfter(currentText_);
+ }
+ }
}
void ResultSetParser::handleCharacterData(const std::string& data) {
- currentText_ += data;
+ currentText_ += data;
}
diff --git a/Swiften/Parser/PayloadParsers/ResultSetParser.h b/Swiften/Parser/PayloadParsers/ResultSetParser.h
index 1066375..335a798 100644
--- a/Swiften/Parser/PayloadParsers/ResultSetParser.h
+++ b/Swiften/Parser/PayloadParsers/ResultSetParser.h
@@ -14,23 +14,23 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API ResultSetParser : public GenericPayloadParser<ResultSet> {
- public:
- ResultSetParser();
+ class SWIFTEN_API ResultSetParser : public GenericPayloadParser<ResultSet> {
+ public:
+ ResultSetParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
- private:
- std::string currentText_;
- int level_;
- };
+ private:
+ std::string currentText_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp b/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp
index de6caa1..f99f592 100644
--- a/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp
@@ -20,56 +20,56 @@ RosterItemExchangeParser::RosterItemExchangeParser() : level_(TopLevel), inItem_
}
void RosterItemExchangeParser::handleStartElement(const std::string& element, const std::string& /*ns*/, const AttributeMap& attributes) {
- if (level_ == PayloadLevel) {
- if (element == "item") {
- inItem_ = true;
+ if (level_ == PayloadLevel) {
+ if (element == "item") {
+ inItem_ = true;
- currentItem_ = RosterItemExchangePayload::Item();
+ currentItem_ = RosterItemExchangePayload::Item();
- currentItem_.setJID(JID(attributes.getAttribute("jid")));
- currentItem_.setName(attributes.getAttribute("name"));
+ currentItem_.setJID(JID(attributes.getAttribute("jid")));
+ currentItem_.setName(attributes.getAttribute("name"));
- std::string action = attributes.getAttribute("action");
- if (action == "add") {
- currentItem_.setAction(RosterItemExchangePayload::Item::Add);
- }
- else if (action == "modify") {
- currentItem_.setAction(RosterItemExchangePayload::Item::Modify);
- }
- else if (action == "delete") {
- currentItem_.setAction(RosterItemExchangePayload::Item::Delete);
- }
- else {
- // Add is default action according to XEP
- currentItem_.setAction(RosterItemExchangePayload::Item::Add);
- }
- }
- }
- else if (level_ == ItemLevel) {
- if (element == "group") {
- currentText_ = "";
- }
- }
- ++level_;
+ std::string action = attributes.getAttribute("action");
+ if (action == "add") {
+ currentItem_.setAction(RosterItemExchangePayload::Item::Add);
+ }
+ else if (action == "modify") {
+ currentItem_.setAction(RosterItemExchangePayload::Item::Modify);
+ }
+ else if (action == "delete") {
+ currentItem_.setAction(RosterItemExchangePayload::Item::Delete);
+ }
+ else {
+ // Add is default action according to XEP
+ currentItem_.setAction(RosterItemExchangePayload::Item::Add);
+ }
+ }
+ }
+ else if (level_ == ItemLevel) {
+ if (element == "group") {
+ currentText_ = "";
+ }
+ }
+ ++level_;
}
void RosterItemExchangeParser::handleEndElement(const std::string& element, const std::string& /*ns*/) {
- --level_;
- if (level_ == PayloadLevel) {
- if (inItem_) {
- getPayloadInternal()->addItem(currentItem_);
- inItem_ = false;
- }
- }
- else if (level_ == ItemLevel) {
- if (element == "group") {
- currentItem_.addGroup(currentText_);
- }
- }
+ --level_;
+ if (level_ == PayloadLevel) {
+ if (inItem_) {
+ getPayloadInternal()->addItem(currentItem_);
+ inItem_ = false;
+ }
+ }
+ else if (level_ == ItemLevel) {
+ if (element == "group") {
+ currentItem_.addGroup(currentText_);
+ }
+ }
}
void RosterItemExchangeParser::handleCharacterData(const std::string& data) {
- currentText_ += data;
+ currentText_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h b/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h
index bf3dace..40e010a 100644
--- a/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h
+++ b/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h
@@ -17,25 +17,25 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API RosterItemExchangeParser : public GenericPayloadParser<RosterItemExchangePayload> {
- public:
- RosterItemExchangeParser();
+ class SWIFTEN_API RosterItemExchangeParser : public GenericPayloadParser<RosterItemExchangePayload> {
+ public:
+ RosterItemExchangeParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- ItemLevel = 2
- };
- int level_;
- bool inItem_;
- RosterItemExchangePayload::Item currentItem_;
- std::string currentText_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ ItemLevel = 2
+ };
+ int level_;
+ bool inItem_;
+ RosterItemExchangePayload::Item currentItem_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/RosterParser.cpp b/Swiften/Parser/PayloadParsers/RosterParser.cpp
index b35d598..0cb47d3 100644
--- a/Swiften/Parser/PayloadParsers/RosterParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RosterParser.cpp
@@ -16,89 +16,89 @@ RosterParser::RosterParser() : level_(TopLevel), inItem_(false), unknownContentP
}
void RosterParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- boost::optional<std::string> ver = attributes.getAttributeValue("ver");
- if (ver) {
- getPayloadInternal()->setVersion(*ver);
- }
- }
- else if (level_ == PayloadLevel) {
- if (element == "item") {
- inItem_ = true;
- currentItem_ = RosterItemPayload();
+ if (level_ == TopLevel) {
+ boost::optional<std::string> ver = attributes.getAttributeValue("ver");
+ if (ver) {
+ getPayloadInternal()->setVersion(*ver);
+ }
+ }
+ else if (level_ == PayloadLevel) {
+ if (element == "item") {
+ inItem_ = true;
+ currentItem_ = RosterItemPayload();
- currentItem_.setJID(JID(attributes.getAttribute("jid")));
- currentItem_.setName(attributes.getAttribute("name"));
+ currentItem_.setJID(JID(attributes.getAttribute("jid")));
+ currentItem_.setName(attributes.getAttribute("name"));
- std::string subscription = attributes.getAttribute("subscription");
- if (subscription == "both") {
- currentItem_.setSubscription(RosterItemPayload::Both);
- }
- else if (subscription == "to") {
- currentItem_.setSubscription(RosterItemPayload::To);
- }
- else if (subscription == "from") {
- currentItem_.setSubscription(RosterItemPayload::From);
- }
- else if (subscription == "remove") {
- currentItem_.setSubscription(RosterItemPayload::Remove);
- }
- else {
- currentItem_.setSubscription(RosterItemPayload::None);
- }
+ std::string subscription = attributes.getAttribute("subscription");
+ if (subscription == "both") {
+ currentItem_.setSubscription(RosterItemPayload::Both);
+ }
+ else if (subscription == "to") {
+ currentItem_.setSubscription(RosterItemPayload::To);
+ }
+ else if (subscription == "from") {
+ currentItem_.setSubscription(RosterItemPayload::From);
+ }
+ else if (subscription == "remove") {
+ currentItem_.setSubscription(RosterItemPayload::Remove);
+ }
+ else {
+ currentItem_.setSubscription(RosterItemPayload::None);
+ }
- if (attributes.getAttribute("ask") == "subscribe") {
- currentItem_.setSubscriptionRequested();
- }
- }
- }
- else if (level_ == ItemLevel) {
- if (element == "group") {
- currentText_ = "";
- }
- else {
- assert(!unknownContentParser_);
- unknownContentParser_ = new SerializingParser();
- unknownContentParser_->handleStartElement(element, ns, attributes);
- }
- }
- else if (unknownContentParser_) {
- unknownContentParser_->handleStartElement(element, ns, attributes);
- }
- ++level_;
+ if (attributes.getAttribute("ask") == "subscribe") {
+ currentItem_.setSubscriptionRequested();
+ }
+ }
+ }
+ else if (level_ == ItemLevel) {
+ if (element == "group") {
+ currentText_ = "";
+ }
+ else {
+ assert(!unknownContentParser_);
+ unknownContentParser_ = new SerializingParser();
+ unknownContentParser_->handleStartElement(element, ns, attributes);
+ }
+ }
+ else if (unknownContentParser_) {
+ unknownContentParser_->handleStartElement(element, ns, attributes);
+ }
+ ++level_;
}
void RosterParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level_;
- if (level_ == PayloadLevel) {
- if (inItem_) {
- getPayloadInternal()->addItem(currentItem_);
- inItem_ = false;
- }
- }
- else if (level_ == ItemLevel) {
- if (unknownContentParser_) {
- unknownContentParser_->handleEndElement(element, ns);
- currentItem_.addUnknownContent(unknownContentParser_->getResult());
- delete unknownContentParser_;
- unknownContentParser_ = NULL;
- }
- else if (element == "group") {
- currentItem_.addGroup(currentText_);
- }
- }
- else if (unknownContentParser_) {
- unknownContentParser_->handleEndElement(element, ns);
- }
+ --level_;
+ if (level_ == PayloadLevel) {
+ if (inItem_) {
+ getPayloadInternal()->addItem(currentItem_);
+ inItem_ = false;
+ }
+ }
+ else if (level_ == ItemLevel) {
+ if (unknownContentParser_) {
+ unknownContentParser_->handleEndElement(element, ns);
+ currentItem_.addUnknownContent(unknownContentParser_->getResult());
+ delete unknownContentParser_;
+ unknownContentParser_ = NULL;
+ }
+ else if (element == "group") {
+ currentItem_.addGroup(currentText_);
+ }
+ }
+ else if (unknownContentParser_) {
+ unknownContentParser_->handleEndElement(element, ns);
+ }
}
void RosterParser::handleCharacterData(const std::string& data) {
- if (unknownContentParser_) {
- unknownContentParser_->handleCharacterData(data);
- }
- else {
- currentText_ += data;
- }
+ if (unknownContentParser_) {
+ unknownContentParser_->handleCharacterData(data);
+ }
+ else {
+ currentText_ += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/RosterParser.h b/Swiften/Parser/PayloadParsers/RosterParser.h
index 3440825..2989f46 100644
--- a/Swiften/Parser/PayloadParsers/RosterParser.h
+++ b/Swiften/Parser/PayloadParsers/RosterParser.h
@@ -11,26 +11,26 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API RosterParser : public GenericPayloadParser<RosterPayload> {
- public:
- RosterParser();
+ class SWIFTEN_API RosterParser : public GenericPayloadParser<RosterPayload> {
+ public:
+ RosterParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- ItemLevel = 2
- };
- int level_;
- bool inItem_;
- RosterItemPayload currentItem_;
- std::string currentText_;
- SerializingParser* unknownContentParser_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ ItemLevel = 2
+ };
+ int level_;
+ bool inItem_;
+ RosterItemPayload currentItem_;
+ std::string currentText_;
+ SerializingParser* unknownContentParser_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
index e0b0a95..502f400 100644
--- a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
+++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
@@ -24,48 +24,48 @@ S5BProxyRequestParser::~S5BProxyRequestParser() {
}
void S5BProxyRequestParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (element == "streamhost") {
- if (attributes.getAttributeValue("host") && attributes.getAttributeValue("jid") && attributes.getAttributeValue("port")) {
- std::string host = attributes.getAttributeValue("host").get_value_or("");
- int port = -1;
- JID jid = attributes.getAttributeValue("jid").get_value_or("");
+ if (element == "streamhost") {
+ if (attributes.getAttributeValue("host") && attributes.getAttributeValue("jid") && attributes.getAttributeValue("port")) {
+ std::string host = attributes.getAttributeValue("host").get_value_or("");
+ int port = -1;
+ JID jid = attributes.getAttributeValue("jid").get_value_or("");
- try {
- port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get());
- } catch (boost::bad_lexical_cast &) {
- port = -1;
- }
- if (!host.empty() && port != -1 && jid.isValid()) {
- S5BProxyRequest::StreamHost streamHost;
- streamHost.host = host;
- streamHost.port = port;
- streamHost.jid = jid;
- getPayloadInternal()->setStreamHost(streamHost);
- }
- }
- } else if (element == "activate") {
- parseActivate = true;
- } else if (element == "query") {
- if (attributes.getAttributeValue("sid")) {
- getPayloadInternal()->setSID(attributes.getAttributeValue("sid").get());
- }
- }
+ try {
+ port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get());
+ } catch (boost::bad_lexical_cast &) {
+ port = -1;
+ }
+ if (!host.empty() && port != -1 && jid.isValid()) {
+ S5BProxyRequest::StreamHost streamHost;
+ streamHost.host = host;
+ streamHost.port = port;
+ streamHost.jid = jid;
+ getPayloadInternal()->setStreamHost(streamHost);
+ }
+ }
+ } else if (element == "activate") {
+ parseActivate = true;
+ } else if (element == "query") {
+ if (attributes.getAttributeValue("sid")) {
+ getPayloadInternal()->setSID(attributes.getAttributeValue("sid").get());
+ }
+ }
}
void S5BProxyRequestParser::handleEndElement(const std::string& element, const std::string&) {
- if (element == "activate") {
- JID activate = JID(activateJID);
- if (activate.isValid()) {
- getPayloadInternal()->setActivate(activate);
- }
- parseActivate = false;
- }
+ if (element == "activate") {
+ JID activate = JID(activateJID);
+ if (activate.isValid()) {
+ getPayloadInternal()->setActivate(activate);
+ }
+ parseActivate = false;
+ }
}
void S5BProxyRequestParser::handleCharacterData(const std::string& data) {
- if (parseActivate) {
- activateJID = activateJID + data;
- }
+ if (parseActivate) {
+ activateJID = activateJID + data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h
index 408bb5a..1d5fd64 100644
--- a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h
+++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h
@@ -22,16 +22,16 @@ namespace Swift {
class SWIFTEN_API S5BProxyRequestParser : public GenericPayloadParser<S5BProxyRequest> {
public:
- S5BProxyRequestParser();
- virtual ~S5BProxyRequestParser();
+ S5BProxyRequestParser();
+ virtual ~S5BProxyRequestParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
private:
- bool parseActivate;
- std::string activateJID;
+ bool parseActivate;
+ std::string activateJID;
};
}
diff --git a/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp b/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp
index 532ee83..5322b4c 100644
--- a/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp
@@ -14,100 +14,100 @@
namespace Swift {
SearchPayloadParser::SearchPayloadParser() : level(TopLevel), formParser(NULL) {
- formParserFactory = new FormParserFactory();
+ formParserFactory = new FormParserFactory();
}
SearchPayloadParser::~SearchPayloadParser() {
- delete formParserFactory;
+ delete formParserFactory;
}
void SearchPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == TopLevel) {
- }
- else if (level == PayloadLevel) {
- if (element == "x" && ns == "jabber:x:data") {
- assert(!formParser);
- formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
- }
- else if (element == "item") {
- assert(!currentItem);
- currentItem.reset(SearchPayload::Item());
- currentItem->jid = JID(attributes.getAttribute("jid"));
- }
- else {
- currentText.clear();
- }
- }
- else if (level == ItemLevel && currentItem) {
- currentText.clear();
- }
+ if (level == TopLevel) {
+ }
+ else if (level == PayloadLevel) {
+ if (element == "x" && ns == "jabber:x:data") {
+ assert(!formParser);
+ formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
+ }
+ else if (element == "item") {
+ assert(!currentItem);
+ currentItem.reset(SearchPayload::Item());
+ currentItem->jid = JID(attributes.getAttribute("jid"));
+ }
+ else {
+ currentText.clear();
+ }
+ }
+ else if (level == ItemLevel && currentItem) {
+ currentText.clear();
+ }
- if (formParser) {
- formParser->handleStartElement(element, ns, attributes);
- }
+ if (formParser) {
+ formParser->handleStartElement(element, ns, attributes);
+ }
- ++level;
+ ++level;
}
void SearchPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
+ --level;
- if (formParser) {
- formParser->handleEndElement(element, ns);
- }
+ if (formParser) {
+ formParser->handleEndElement(element, ns);
+ }
- if (level == TopLevel) {
- }
- else if (level == PayloadLevel) {
- if (formParser) {
- getPayloadInternal()->setForm(formParser->getPayloadInternal());
- delete formParser;
- formParser = NULL;
- }
- else if (element == "item") {
- assert(currentItem);
- getPayloadInternal()->addItem(*currentItem);
- currentItem.reset();
- }
- else if (element == "instructions") {
- getPayloadInternal()->setInstructions(currentText);
- }
- else if (element == "nick") {
- getPayloadInternal()->setNick(currentText);
- }
- else if (element == "first") {
- getPayloadInternal()->setFirst(currentText);
- }
- else if (element == "last") {
- getPayloadInternal()->setLast(currentText);
- }
- else if (element == "email") {
- getPayloadInternal()->setEMail(currentText);
- }
- }
- else if (level == ItemLevel && currentItem) {
- if (element == "nick") {
- currentItem->nick = currentText;
- }
- else if (element == "first") {
- currentItem->first = currentText;
- }
- else if (element == "last") {
- currentItem->last = currentText;
- }
- else if (element == "email") {
- currentItem->email = currentText;
- }
- }
+ if (level == TopLevel) {
+ }
+ else if (level == PayloadLevel) {
+ if (formParser) {
+ getPayloadInternal()->setForm(formParser->getPayloadInternal());
+ delete formParser;
+ formParser = NULL;
+ }
+ else if (element == "item") {
+ assert(currentItem);
+ getPayloadInternal()->addItem(*currentItem);
+ currentItem.reset();
+ }
+ else if (element == "instructions") {
+ getPayloadInternal()->setInstructions(currentText);
+ }
+ else if (element == "nick") {
+ getPayloadInternal()->setNick(currentText);
+ }
+ else if (element == "first") {
+ getPayloadInternal()->setFirst(currentText);
+ }
+ else if (element == "last") {
+ getPayloadInternal()->setLast(currentText);
+ }
+ else if (element == "email") {
+ getPayloadInternal()->setEMail(currentText);
+ }
+ }
+ else if (level == ItemLevel && currentItem) {
+ if (element == "nick") {
+ currentItem->nick = currentText;
+ }
+ else if (element == "first") {
+ currentItem->first = currentText;
+ }
+ else if (element == "last") {
+ currentItem->last = currentText;
+ }
+ else if (element == "email") {
+ currentItem->email = currentText;
+ }
+ }
}
void SearchPayloadParser::handleCharacterData(const std::string& data) {
- if (formParser) {
- formParser->handleCharacterData(data);
- }
- else {
- currentText += data;
- }
+ if (formParser) {
+ formParser->handleCharacterData(data);
+ }
+ else {
+ currentText += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/SearchPayloadParser.h b/Swiften/Parser/PayloadParsers/SearchPayloadParser.h
index bfcb86d..aa0cf4a 100644
--- a/Swiften/Parser/PayloadParsers/SearchPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/SearchPayloadParser.h
@@ -13,28 +13,28 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class FormParserFactory;
- class FormParser;
+ class FormParserFactory;
+ class FormParser;
- class SWIFTEN_API SearchPayloadParser : public GenericPayloadParser<SearchPayload> {
- public:
- SearchPayloadParser();
- ~SearchPayloadParser();
+ class SWIFTEN_API SearchPayloadParser : public GenericPayloadParser<SearchPayload> {
+ public:
+ SearchPayloadParser();
+ ~SearchPayloadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- ItemLevel = 2
- };
- int level;
- FormParserFactory* formParserFactory;
- FormParser* formParser;
- std::string currentText;
- boost::optional<SearchPayload::Item> currentItem;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ ItemLevel = 2
+ };
+ int level;
+ FormParserFactory* formParserFactory;
+ FormParser* formParser;
+ std::string currentText;
+ boost::optional<SearchPayload::Item> currentItem;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp b/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp
index 7176403..43b8043 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp
@@ -14,57 +14,57 @@ SecurityLabelParser::SecurityLabelParser() : level_(TopLevel), labelParser_(0) {
}
void SecurityLabelParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- ++level_;
- if (level_ == DisplayMarkingOrLabelLevel) {
- if (element == "displaymarking") {
- currentText_ = "";
- getPayloadInternal()->setBackgroundColor(attributes.getAttribute("bgcolor"));
- getPayloadInternal()->setForegroundColor(attributes.getAttribute("fgcolor"));
- }
- else if (element == "label" || element == "equivalentlabel") {
- assert(!labelParser_);
- labelParser_ = new SerializingParser();
- }
- }
- else if (level_ >= SecurityLabelLevel && labelParser_) {
- labelParser_->handleStartElement(element, ns, attributes);
- }
+ ++level_;
+ if (level_ == DisplayMarkingOrLabelLevel) {
+ if (element == "displaymarking") {
+ currentText_ = "";
+ getPayloadInternal()->setBackgroundColor(attributes.getAttribute("bgcolor"));
+ getPayloadInternal()->setForegroundColor(attributes.getAttribute("fgcolor"));
+ }
+ else if (element == "label" || element == "equivalentlabel") {
+ assert(!labelParser_);
+ labelParser_ = new SerializingParser();
+ }
+ }
+ else if (level_ >= SecurityLabelLevel && labelParser_) {
+ labelParser_->handleStartElement(element, ns, attributes);
+ }
}
void SecurityLabelParser::handleEndElement(const std::string& element, const std::string& ns) {
- if (level_ == DisplayMarkingOrLabelLevel) {
- if (element == "displaymarking") {
- getPayloadInternal()->setDisplayMarking(currentText_);
- }
- else if (labelParser_) {
- if (element == "label") {
- getPayloadInternal()->setLabel(labelParser_->getResult());
- }
- else {
- getPayloadInternal()->addEquivalentLabel(labelParser_->getResult());
- }
- delete labelParser_;
- labelParser_ = 0;
- }
- }
- else if (labelParser_ && level_ >= SecurityLabelLevel) {
- labelParser_->handleEndElement(element, ns);
- }
- --level_;
+ if (level_ == DisplayMarkingOrLabelLevel) {
+ if (element == "displaymarking") {
+ getPayloadInternal()->setDisplayMarking(currentText_);
+ }
+ else if (labelParser_) {
+ if (element == "label") {
+ getPayloadInternal()->setLabel(labelParser_->getResult());
+ }
+ else {
+ getPayloadInternal()->addEquivalentLabel(labelParser_->getResult());
+ }
+ delete labelParser_;
+ labelParser_ = 0;
+ }
+ }
+ else if (labelParser_ && level_ >= SecurityLabelLevel) {
+ labelParser_->handleEndElement(element, ns);
+ }
+ --level_;
}
void SecurityLabelParser::handleCharacterData(const std::string& data) {
- if (labelParser_) {
- labelParser_->handleCharacterData(data);
- }
- else {
- currentText_ += data;
- }
+ if (labelParser_) {
+ labelParser_->handleCharacterData(data);
+ }
+ else {
+ currentText_ += data;
+ }
}
boost::shared_ptr<SecurityLabel> SecurityLabelParser::getLabelPayload() const {
- return getPayloadInternal();
+ return getPayloadInternal();
}
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelParser.h b/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
index 857df6a..d5b0466 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
@@ -11,25 +11,25 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API SecurityLabelParser : public GenericPayloadParser<SecurityLabel> {
- public:
- SecurityLabelParser();
+ class SWIFTEN_API SecurityLabelParser : public GenericPayloadParser<SecurityLabel> {
+ public:
+ SecurityLabelParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
- boost::shared_ptr<SecurityLabel> getLabelPayload() const;
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- DisplayMarkingOrLabelLevel = 2,
- SecurityLabelLevel = 3
- };
- int level_;
- SerializingParser* labelParser_;
- std::string currentText_;
- };
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+ boost::shared_ptr<SecurityLabel> getLabelPayload() const;
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ DisplayMarkingOrLabelLevel = 2,
+ SecurityLabelLevel = 3
+ };
+ int level_;
+ SerializingParser* labelParser_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h b/Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h
index 1eabb07..7e6d4fd 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/PayloadParsers/SecurityLabelParser.h>
namespace Swift {
- class SWIFTEN_API SecurityLabelParserFactory : public GenericPayloadParserFactory<SecurityLabelParser> {
- public:
- SecurityLabelParserFactory() : GenericPayloadParserFactory<SecurityLabelParser>("securitylabel", "urn:xmpp:sec-label:0") {}
- };
+ class SWIFTEN_API SecurityLabelParserFactory : public GenericPayloadParserFactory<SecurityLabelParser> {
+ public:
+ SecurityLabelParserFactory() : GenericPayloadParserFactory<SecurityLabelParser>("securitylabel", "urn:xmpp:sec-label:0") {}
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
index 715929a..0aa4100 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
@@ -14,62 +14,62 @@
namespace Swift {
SecurityLabelsCatalogParser::SecurityLabelsCatalogParser() : level_(TopLevel), labelParser_(0) {
- labelParserFactory_ = new SecurityLabelParserFactory();
+ labelParserFactory_ = new SecurityLabelParserFactory();
}
SecurityLabelsCatalogParser::~SecurityLabelsCatalogParser() {
- delete labelParserFactory_;
+ delete labelParserFactory_;
}
void SecurityLabelsCatalogParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- ++level_;
- if (level_ == PayloadLevel) {
- getPayloadInternal()->setTo(JID(attributes.getAttribute("to")));
- getPayloadInternal()->setName(attributes.getAttribute("name"));
- getPayloadInternal()->setDescription(attributes.getAttribute("desc"));
- }
- else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
- currentItem_ = boost::make_shared<SecurityLabelsCatalog::Item>();
- currentItem_->setSelector(attributes.getAttribute("selector"));
- currentItem_->setIsDefault(attributes.getBoolAttribute("default", false));
- }
- else if (level_ == LabelLevel) {
- assert(!labelParser_);
- if (labelParserFactory_->canParse(element, ns, attributes)) {
- labelParser_ = dynamic_cast<SecurityLabelParser*>(labelParserFactory_->createPayloadParser());
- assert(labelParser_);
- }
- }
+ ++level_;
+ if (level_ == PayloadLevel) {
+ getPayloadInternal()->setTo(JID(attributes.getAttribute("to")));
+ getPayloadInternal()->setName(attributes.getAttribute("name"));
+ getPayloadInternal()->setDescription(attributes.getAttribute("desc"));
+ }
+ else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
+ currentItem_ = boost::make_shared<SecurityLabelsCatalog::Item>();
+ currentItem_->setSelector(attributes.getAttribute("selector"));
+ currentItem_->setIsDefault(attributes.getBoolAttribute("default", false));
+ }
+ else if (level_ == LabelLevel) {
+ assert(!labelParser_);
+ if (labelParserFactory_->canParse(element, ns, attributes)) {
+ labelParser_ = dynamic_cast<SecurityLabelParser*>(labelParserFactory_->createPayloadParser());
+ assert(labelParser_);
+ }
+ }
- if (labelParser_) {
- labelParser_->handleStartElement(element, ns, attributes);
- }
+ if (labelParser_) {
+ labelParser_->handleStartElement(element, ns, attributes);
+ }
}
void SecurityLabelsCatalogParser::handleEndElement(const std::string& element, const std::string& ns) {
- if (labelParser_) {
- labelParser_->handleEndElement(element, ns);
- }
- if (level_ == LabelLevel && labelParser_ && currentItem_) {
- boost::shared_ptr<SecurityLabel> currentLabel = labelParser_->getLabelPayload();
- assert(currentLabel);
- currentItem_->setLabel(currentLabel);
- delete labelParser_;
- labelParser_ = 0;
- }
- else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
- if (currentItem_) {
- getPayloadInternal()->addItem(SecurityLabelsCatalog::Item(*currentItem_));
- currentItem_.reset();
- }
- }
- --level_;
+ if (labelParser_) {
+ labelParser_->handleEndElement(element, ns);
+ }
+ if (level_ == LabelLevel && labelParser_ && currentItem_) {
+ boost::shared_ptr<SecurityLabel> currentLabel = labelParser_->getLabelPayload();
+ assert(currentLabel);
+ currentItem_->setLabel(currentLabel);
+ delete labelParser_;
+ labelParser_ = 0;
+ }
+ else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
+ if (currentItem_) {
+ getPayloadInternal()->addItem(SecurityLabelsCatalog::Item(*currentItem_));
+ currentItem_.reset();
+ }
+ }
+ --level_;
}
void SecurityLabelsCatalogParser::handleCharacterData(const std::string& data) {
- if (labelParser_) {
- labelParser_->handleCharacterData(data);
- }
+ if (labelParser_) {
+ labelParser_->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h
index 689ebb8..bb44369 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h
@@ -11,28 +11,28 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SecurityLabelParserFactory;
- class SecurityLabelParser;
+ class SecurityLabelParserFactory;
+ class SecurityLabelParser;
- class SWIFTEN_API SecurityLabelsCatalogParser : public GenericPayloadParser<SecurityLabelsCatalog> {
- public:
- SecurityLabelsCatalogParser();
- ~SecurityLabelsCatalogParser();
+ class SWIFTEN_API SecurityLabelsCatalogParser : public GenericPayloadParser<SecurityLabelsCatalog> {
+ public:
+ SecurityLabelsCatalogParser();
+ ~SecurityLabelsCatalogParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- ItemLevel = 2,
- LabelLevel = 3
- };
- int level_;
- SecurityLabelParserFactory* labelParserFactory_;
- SecurityLabelParser* labelParser_;
- boost::shared_ptr<SecurityLabelsCatalog::Item> currentItem_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ ItemLevel = 2,
+ LabelLevel = 3
+ };
+ int level_;
+ SecurityLabelParserFactory* labelParserFactory_;
+ SecurityLabelParser* labelParser_;
+ boost::shared_ptr<SecurityLabelsCatalog::Item> currentItem_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/SoftwareVersionParser.cpp b/Swiften/Parser/PayloadParsers/SoftwareVersionParser.cpp
index c0122fa..56b62c8 100644
--- a/Swiften/Parser/PayloadParsers/SoftwareVersionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SoftwareVersionParser.cpp
@@ -12,27 +12,27 @@ SoftwareVersionParser::SoftwareVersionParser() : level_(TopLevel) {
}
void SoftwareVersionParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void SoftwareVersionParser::handleEndElement(const std::string& element, const std::string&) {
- --level_;
- if (level_ == PayloadLevel) {
- if (element == "name") {
- getPayloadInternal()->setName(currentText_);
- }
- else if (element == "version") {
- getPayloadInternal()->setVersion(currentText_);
- }
- else if (element == "os") {
- getPayloadInternal()->setOS(currentText_);
- }
- currentText_ = "";
- }
+ --level_;
+ if (level_ == PayloadLevel) {
+ if (element == "name") {
+ getPayloadInternal()->setName(currentText_);
+ }
+ else if (element == "version") {
+ getPayloadInternal()->setVersion(currentText_);
+ }
+ else if (element == "os") {
+ getPayloadInternal()->setOS(currentText_);
+ }
+ currentText_ = "";
+ }
}
void SoftwareVersionParser::handleCharacterData(const std::string& data) {
- currentText_ += data;
+ currentText_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/SoftwareVersionParser.h b/Swiften/Parser/PayloadParsers/SoftwareVersionParser.h
index a66dd1a..29f700c 100644
--- a/Swiften/Parser/PayloadParsers/SoftwareVersionParser.h
+++ b/Swiften/Parser/PayloadParsers/SoftwareVersionParser.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API SoftwareVersionParser : public GenericPayloadParser<SoftwareVersion> {
- public:
- SoftwareVersionParser();
+ class SWIFTEN_API SoftwareVersionParser : public GenericPayloadParser<SoftwareVersion> {
+ public:
+ SoftwareVersionParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level_;
- std::string currentText_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/StartSessionParser.h b/Swiften/Parser/PayloadParsers/StartSessionParser.h
index d5a9c2e..e0013af 100644
--- a/Swiften/Parser/PayloadParsers/StartSessionParser.h
+++ b/Swiften/Parser/PayloadParsers/StartSessionParser.h
@@ -11,12 +11,12 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API StartSessionParser : public GenericPayloadParser<StartSession> {
- public:
- StartSessionParser() {}
+ class SWIFTEN_API StartSessionParser : public GenericPayloadParser<StartSession> {
+ public:
+ StartSessionParser() {}
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
- virtual void handleEndElement(const std::string&, const std::string&) {}
- virtual void handleCharacterData(const std::string&) {}
- };
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
+ virtual void handleEndElement(const std::string&, const std::string&) {}
+ virtual void handleCharacterData(const std::string&) {}
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/StatusParser.cpp b/Swiften/Parser/PayloadParsers/StatusParser.cpp
index a8b49f4..128a675 100644
--- a/Swiften/Parser/PayloadParsers/StatusParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StatusParser.cpp
@@ -12,18 +12,18 @@ StatusParser::StatusParser() : level_(0) {
}
void StatusParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void StatusParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setText(text_);
- }
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setText(text_);
+ }
}
void StatusParser::handleCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/StatusParser.h b/Swiften/Parser/PayloadParsers/StatusParser.h
index 689897b..cebf0cd 100644
--- a/Swiften/Parser/PayloadParsers/StatusParser.h
+++ b/Swiften/Parser/PayloadParsers/StatusParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API StatusParser : public GenericPayloadParser<Status> {
- public:
- StatusParser();
+ class SWIFTEN_API StatusParser : public GenericPayloadParser<Status> {
+ public:
+ StatusParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/StatusShowParser.cpp b/Swiften/Parser/PayloadParsers/StatusShowParser.cpp
index 5fac74c..761a411 100644
--- a/Swiften/Parser/PayloadParsers/StatusShowParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StatusShowParser.cpp
@@ -12,32 +12,32 @@ StatusShowParser::StatusShowParser() : level_(0) {
}
void StatusShowParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void StatusShowParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- if (text_ == "away") {
- getPayloadInternal()->setType(StatusShow::Away);
- }
- else if (text_ == "chat") {
- getPayloadInternal()->setType(StatusShow::FFC);
- }
- else if (text_ == "xa") {
- getPayloadInternal()->setType(StatusShow::XA);
- }
- else if (text_ == "dnd") {
- getPayloadInternal()->setType(StatusShow::DND);
- }
- else {
- getPayloadInternal()->setType(StatusShow::Online);
- }
- }
+ --level_;
+ if (level_ == 0) {
+ if (text_ == "away") {
+ getPayloadInternal()->setType(StatusShow::Away);
+ }
+ else if (text_ == "chat") {
+ getPayloadInternal()->setType(StatusShow::FFC);
+ }
+ else if (text_ == "xa") {
+ getPayloadInternal()->setType(StatusShow::XA);
+ }
+ else if (text_ == "dnd") {
+ getPayloadInternal()->setType(StatusShow::DND);
+ }
+ else {
+ getPayloadInternal()->setType(StatusShow::Online);
+ }
+ }
}
void StatusShowParser::handleCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/StatusShowParser.h b/Swiften/Parser/PayloadParsers/StatusShowParser.h
index 2bdcd56..8cbb365 100644
--- a/Swiften/Parser/PayloadParsers/StatusShowParser.h
+++ b/Swiften/Parser/PayloadParsers/StatusShowParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API StatusShowParser : public GenericPayloadParser<StatusShow> {
- public:
- StatusShowParser();
+ class SWIFTEN_API StatusShowParser : public GenericPayloadParser<StatusShow> {
+ public:
+ StatusShowParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/StorageParser.cpp b/Swiften/Parser/PayloadParsers/StorageParser.cpp
index 1a131a9..9628ea8 100644
--- a/Swiften/Parser/PayloadParsers/StorageParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StorageParser.cpp
@@ -14,53 +14,53 @@ StorageParser::StorageParser() : level(TopLevel) {
}
void StorageParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level == BookmarkLevel) {
- if (element == "conference") {
- assert(!room);
- room = Storage::Room();
- room->autoJoin = attributes.getBoolAttribute("autojoin", false);
- room->jid = JID(attributes.getAttribute("jid"));
- room->name = attributes.getAttribute("name");
- }
- else if (element == "url") {
- assert(!url);
- url = Storage::URL();
- url->name = attributes.getAttribute("name");
- url->url = attributes.getAttribute("url");
- }
- }
- else if (level == DetailLevel) {
- currentText = "";
- }
- ++level;
+ if (level == BookmarkLevel) {
+ if (element == "conference") {
+ assert(!room);
+ room = Storage::Room();
+ room->autoJoin = attributes.getBoolAttribute("autojoin", false);
+ room->jid = JID(attributes.getAttribute("jid"));
+ room->name = attributes.getAttribute("name");
+ }
+ else if (element == "url") {
+ assert(!url);
+ url = Storage::URL();
+ url->name = attributes.getAttribute("name");
+ url->url = attributes.getAttribute("url");
+ }
+ }
+ else if (level == DetailLevel) {
+ currentText = "";
+ }
+ ++level;
}
void StorageParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (level == BookmarkLevel) {
- if (element == "conference") {
- assert(room);
- getPayloadInternal()->addRoom(*room);
- room.reset();
- }
- else if (element == "url") {
- assert(url);
- getPayloadInternal()->addURL(*url);
- url.reset();
- }
- }
- else if (level == DetailLevel && room) {
- if (element == "nick") {
- room->nick = currentText;
- }
- else if (element == "password") {
- room->password = currentText;
- }
- }
+ --level;
+ if (level == BookmarkLevel) {
+ if (element == "conference") {
+ assert(room);
+ getPayloadInternal()->addRoom(*room);
+ room.reset();
+ }
+ else if (element == "url") {
+ assert(url);
+ getPayloadInternal()->addURL(*url);
+ url.reset();
+ }
+ }
+ else if (level == DetailLevel && room) {
+ if (element == "nick") {
+ room->nick = currentText;
+ }
+ else if (element == "password") {
+ room->password = currentText;
+ }
+ }
}
void StorageParser::handleCharacterData(const std::string& data) {
- currentText += data;
+ currentText += data;
}
}
diff --git a/Swiften/Parser/PayloadParsers/StorageParser.h b/Swiften/Parser/PayloadParsers/StorageParser.h
index 0fea4c9..92417c2 100644
--- a/Swiften/Parser/PayloadParsers/StorageParser.h
+++ b/Swiften/Parser/PayloadParsers/StorageParser.h
@@ -13,23 +13,23 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API StorageParser : public GenericPayloadParser<Storage> {
- public:
- StorageParser();
+ class SWIFTEN_API StorageParser : public GenericPayloadParser<Storage> {
+ public:
+ StorageParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- BookmarkLevel = 1,
- DetailLevel = 2
- };
- int level;
- std::string currentText;
- boost::optional<Storage::Room> room;
- boost::optional<Storage::URL> url;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ BookmarkLevel = 1,
+ DetailLevel = 2
+ };
+ int level;
+ std::string currentText;
+ boost::optional<Storage::Room> room;
+ boost::optional<Storage::URL> url;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
index da5aa79..ab5dbbe 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
@@ -21,55 +21,55 @@
namespace Swift {
StreamInitiationFileInfoParser::StreamInitiationFileInfoParser() : level(0), parseDescription(false) {
-
+
}
void StreamInitiationFileInfoParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level == 0) {
- getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
- getPayloadInternal()->setHash(attributes.getAttributeValue("hash").get_value_or(""));
- getPayloadInternal()->setAlgo(attributes.getAttributeValue("algo").get_value_or("md5"));
- try {
- getPayloadInternal()->setSize(boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("size").get_value_or("0")));
- } catch (boost::bad_lexical_cast &) {
- getPayloadInternal()->setSize(0);
- }
- getPayloadInternal()->setDate(stringToDateTime(attributes.getAttributeValue("date").get_value_or("")));
- } else if (level == 1) {
- if (element == "desc") {
- parseDescription = true;
- } else {
- parseDescription = false;
- if (element == "range") {
- boost::uintmax_t offset = 0;
- try {
- offset = boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or("0"));
- } catch (boost::bad_lexical_cast &) {
- offset = 0;
- }
- if (offset == 0) {
- getPayloadInternal()->setSupportsRangeRequests(true);
- } else {
- getPayloadInternal()->setRangeOffset(offset);
- }
- }
- }
- }
- ++level;
+ if (level == 0) {
+ getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
+ getPayloadInternal()->setHash(attributes.getAttributeValue("hash").get_value_or(""));
+ getPayloadInternal()->setAlgo(attributes.getAttributeValue("algo").get_value_or("md5"));
+ try {
+ getPayloadInternal()->setSize(boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("size").get_value_or("0")));
+ } catch (boost::bad_lexical_cast &) {
+ getPayloadInternal()->setSize(0);
+ }
+ getPayloadInternal()->setDate(stringToDateTime(attributes.getAttributeValue("date").get_value_or("")));
+ } else if (level == 1) {
+ if (element == "desc") {
+ parseDescription = true;
+ } else {
+ parseDescription = false;
+ if (element == "range") {
+ boost::uintmax_t offset = 0;
+ try {
+ offset = boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or("0"));
+ } catch (boost::bad_lexical_cast &) {
+ offset = 0;
+ }
+ if (offset == 0) {
+ getPayloadInternal()->setSupportsRangeRequests(true);
+ } else {
+ getPayloadInternal()->setRangeOffset(offset);
+ }
+ }
+ }
+ }
+ ++level;
}
void StreamInitiationFileInfoParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (parseDescription && element == "desc") {
- parseDescription = false;
- getPayloadInternal()->setDescription(desc);
- }
+ --level;
+ if (parseDescription && element == "desc") {
+ parseDescription = false;
+ getPayloadInternal()->setDescription(desc);
+ }
}
void StreamInitiationFileInfoParser::handleCharacterData(const std::string& data) {
- if (parseDescription) {
- desc += data;
- }
+ if (parseDescription) {
+ desc += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h
index 722797d..a1e386c 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h
@@ -19,17 +19,17 @@
namespace Swift {
class SWIFTEN_API StreamInitiationFileInfoParser : public GenericPayloadParser<StreamInitiationFileInfo> {
- public:
- StreamInitiationFileInfoParser();
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
-
- private:
- int level;
- bool parseDescription;
- std::string desc;
+ public:
+ StreamInitiationFileInfoParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ int level;
+ bool parseDescription;
+ std::string desc;
};
}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
index 32c85a3..8be93c4 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
@@ -20,101 +20,101 @@
namespace Swift {
StreamInitiationParser::StreamInitiationParser() : level(TopLevel), formParser(0), inFile(false), inFeature(false) {
- formParserFactory = new FormParserFactory();
+ formParserFactory = new FormParserFactory();
}
StreamInitiationParser::~StreamInitiationParser() {
- delete formParserFactory;
+ 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&) {
- }
- }
- else if (element == "feature" && ns == FEATURE_NEG_NS) {
- inFeature = true;
- }
- }
- else if (level == FileOrFeatureLevel) {
- if (inFile && element == "desc") {
- currentText.clear();
- }
- else if (inFeature && formParserFactory->canParse(element, ns, attributes)) {
- assert(!formParser);
- formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
- }
- }
+ 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&) {
+ }
+ }
+ else if (element == "feature" && ns == FEATURE_NEG_NS) {
+ inFeature = true;
+ }
+ }
+ else if (level == FileOrFeatureLevel) {
+ if (inFile && element == "desc") {
+ currentText.clear();
+ }
+ else if (inFeature && formParserFactory->canParse(element, ns, attributes)) {
+ assert(!formParser);
+ formParser = boost::polymorphic_downcast<FormParser*>(formParserFactory->createPayloadParser());
+ }
+ }
- if (formParser) {
- formParser->handleStartElement(element, ns, attributes);
- }
- ++level;
+ if (formParser) {
+ formParser->handleStartElement(element, ns, attributes);
+ }
+ ++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 = boost::dynamic_pointer_cast<FormField>(form->getField("stream-method"));
- if (field) {
- if (form->getType() == Form::FormType) {
- foreach (const FormField::Option& 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 = NULL;
- }
- }
+ --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 = boost::dynamic_pointer_cast<FormField>(form->getField("stream-method"));
+ if (field) {
+ if (form->getType() == Form::FormType) {
+ foreach (const FormField::Option& 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 = NULL;
+ }
+ }
}
void StreamInitiationParser::handleCharacterData(const std::string& data) {
- if (formParser) {
- formParser->handleCharacterData(data);
- }
- else {
- currentText += data;
- }
+ if (formParser) {
+ formParser->handleCharacterData(data);
+ }
+ else {
+ currentText += data;
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationParser.h b/Swiften/Parser/PayloadParsers/StreamInitiationParser.h
index 66ce778..42de8ba 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.h
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.h
@@ -13,31 +13,31 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class FormParserFactory;
- class FormParser;
+ class FormParserFactory;
+ class FormParser;
- class SWIFTEN_API StreamInitiationParser : public GenericPayloadParser<StreamInitiation> {
- public:
- StreamInitiationParser();
- ~StreamInitiationParser();
+ class SWIFTEN_API StreamInitiationParser : public GenericPayloadParser<StreamInitiation> {
+ public:
+ StreamInitiationParser();
+ ~StreamInitiationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1,
- FileOrFeatureLevel = 2,
- FormOrDescriptionLevel = 3
- };
- int level;
- FormParserFactory* formParserFactory;
- FormParser* formParser;
- bool inFile;
- bool inFeature;
- StreamInitiationFileInfo currentFile;
- std::string currentText;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1,
+ FileOrFeatureLevel = 2,
+ FormOrDescriptionLevel = 3
+ };
+ int level;
+ FormParserFactory* formParserFactory;
+ FormParser* formParser;
+ bool inFile;
+ bool inFeature;
+ StreamInitiationFileInfo currentFile;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/SubjectParser.cpp b/Swiften/Parser/PayloadParsers/SubjectParser.cpp
index 7b2d885..19a5488 100644
--- a/Swiften/Parser/PayloadParsers/SubjectParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SubjectParser.cpp
@@ -12,20 +12,20 @@ SubjectParser::SubjectParser() : level_(0) {
}
void SubjectParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level_;
+ ++level_;
}
void SubjectParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setText(text_);
- }
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setText(text_);
+ }
}
void SubjectParser::handleCharacterData(const std::string& data) {
- if (level_ == 1) {
- text_ += data;
- }
+ if (level_ == 1) {
+ text_ += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/SubjectParser.h b/Swiften/Parser/PayloadParsers/SubjectParser.h
index 804c50b..a400283 100644
--- a/Swiften/Parser/PayloadParsers/SubjectParser.h
+++ b/Swiften/Parser/PayloadParsers/SubjectParser.h
@@ -11,16 +11,16 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API SubjectParser : public GenericPayloadParser<Subject> {
- public:
- SubjectParser();
+ class SWIFTEN_API SubjectParser : public GenericPayloadParser<Subject> {
+ public:
+ SubjectParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/ThreadParser.cpp b/Swiften/Parser/PayloadParsers/ThreadParser.cpp
index 0d0aca8..f416d32 100644
--- a/Swiften/Parser/PayloadParsers/ThreadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ThreadParser.cpp
@@ -17,23 +17,23 @@ ThreadParser::~ThreadParser() {
}
void ThreadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- ++level_;
- if (element == "thread") {
- getPayloadInternal()->setParent(attributes.getAttributeValue("parent").get_value_or(""));
- }
+ ++level_;
+ if (element == "thread") {
+ getPayloadInternal()->setParent(attributes.getAttributeValue("parent").get_value_or(""));
+ }
}
void ThreadParser::handleEndElement(const std::string&, const std::string&) {
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setText(text_);
- }
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setText(text_);
+ }
}
void ThreadParser::handleCharacterData(const std::string& data) {
- if (level_ == 1) {
- text_ += data;
- }
+ if (level_ == 1) {
+ text_ += data;
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/ThreadParser.h b/Swiften/Parser/PayloadParsers/ThreadParser.h
index 270ea99..371c535 100644
--- a/Swiften/Parser/PayloadParsers/ThreadParser.h
+++ b/Swiften/Parser/PayloadParsers/ThreadParser.h
@@ -11,17 +11,17 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API ThreadParser : public GenericPayloadParser<Thread> {
- public:
- ThreadParser();
- virtual ~ThreadParser();
+ class SWIFTEN_API ThreadParser : public GenericPayloadParser<Thread> {
+ public:
+ ThreadParser();
+ virtual ~ThreadParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- int level_;
- std::string text_;
- };
+ private:
+ int level_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp
index 4a104c8..17a800e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp
@@ -23,55 +23,55 @@ using namespace Swift;
class BlockParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(BlockParserTest);
- CPPUNIT_TEST(testExample4);
- CPPUNIT_TEST(testExample6);
- CPPUNIT_TEST(testExample10);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- BlockParserTest() {}
-
- void testExample4() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<blocklist xmlns='urn:xmpp:blocking'>"
- "<item jid='romeo@montague.net'/>"
- "<item jid='iago@shakespeare.lit'/>"
- "</blocklist>"));
-
- BlockListPayload* payload = dynamic_cast<BlockListPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(2 == payload->getItems().size());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
- CPPUNIT_ASSERT_EQUAL(JID("iago@shakespeare.lit"), payload->getItems()[1]);
- }
-
- void testExample6() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<block xmlns='urn:xmpp:blocking'>"
- "<item jid='romeo@montague.net'/>"
- "</block>"));
-
- BlockPayload* payload = dynamic_cast<BlockPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(1 == payload->getItems().size());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
- }
-
- void testExample10() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<unblock xmlns='urn:xmpp:blocking'>"
- "<item jid='romeo@montague.net'/>"
- "</unblock>"));
-
- UnblockPayload* payload = dynamic_cast<UnblockPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(1 == payload->getItems().size());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
- }
+ CPPUNIT_TEST_SUITE(BlockParserTest);
+ CPPUNIT_TEST(testExample4);
+ CPPUNIT_TEST(testExample6);
+ CPPUNIT_TEST(testExample10);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ BlockParserTest() {}
+
+ void testExample4() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<blocklist xmlns='urn:xmpp:blocking'>"
+ "<item jid='romeo@montague.net'/>"
+ "<item jid='iago@shakespeare.lit'/>"
+ "</blocklist>"));
+
+ BlockListPayload* payload = dynamic_cast<BlockListPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(2 == payload->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
+ CPPUNIT_ASSERT_EQUAL(JID("iago@shakespeare.lit"), payload->getItems()[1]);
+ }
+
+ void testExample6() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<block xmlns='urn:xmpp:blocking'>"
+ "<item jid='romeo@montague.net'/>"
+ "</block>"));
+
+ BlockPayload* payload = dynamic_cast<BlockPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(1 == payload->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
+ }
+
+ void testExample10() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<unblock xmlns='urn:xmpp:blocking'>"
+ "<item jid='romeo@montague.net'/>"
+ "</unblock>"));
+
+ UnblockPayload* payload = dynamic_cast<UnblockPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(1 == payload->getItems().size());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), payload->getItems()[0]);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(BlockParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp
index b409ed4..002da16 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp
@@ -14,21 +14,21 @@ using namespace Swift;
class BodyParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(BodyParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(BodyParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
- public:
- BodyParserTest() {}
+ public:
+ BodyParserTest() {}
- void testParse() {
- PayloadsParserTester parser;
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<body>foo<baz>bar</baz>fum</body>"));
+ CPPUNIT_ASSERT(parser.parse("<body>foo<baz>bar</baz>fum</body>"));
- Body* payload = dynamic_cast<Body*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("foobarfum"), payload->getText());
- }
+ Body* payload = dynamic_cast<Body*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("foobarfum"), payload->getText());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(BodyParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp
index 7700a5c..f85efb2 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp
@@ -20,108 +20,108 @@
using namespace Swift;
class CarbonsParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CarbonsParserTest);
- CPPUNIT_TEST(testParseExample3);
- CPPUNIT_TEST(testParseExample6);
- CPPUNIT_TEST(testParseExample12);
- CPPUNIT_TEST(testParseExample14);
- CPPUNIT_TEST(testParseExample15);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- CarbonsParserTest() {}
-
- /*
- * Test parsing of example 3 in XEP-0280.
- */
- void testParseExample3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<enable xmlns='urn:xmpp:carbons:2' />"));
-
- CarbonsEnable::ref enable = parser.getPayload<CarbonsEnable>();
- CPPUNIT_ASSERT(enable);
- }
-
- /*
- * Test parsing of example 6 in XEP-0280.
- */
- void testParseExample6() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<disable xmlns='urn:xmpp:carbons:2' />"));
-
- CarbonsDisable::ref disable = parser.getPayload<CarbonsDisable>();
- CPPUNIT_ASSERT(disable);
- }
-
- /*
- * Test parsing of example 12 in XEP-0280.
- */
- void testParseExample12() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<received xmlns='urn:xmpp:carbons:2'>"
- "<forwarded xmlns='urn:xmpp:forward:0'>"
- "<message xmlns='jabber:client'"
- " from='juliet@capulet.example/balcony'"
- " to='romeo@montague.example/garden'"
- " type='chat'>"
- "<body>What man art thou that, thus bescreen'd in night, so stumblest on my counsel?</body>"
- "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
- "</message>"
- "</forwarded>"
- "</received>"));
-
- CarbonsReceived::ref received = parser.getPayload<CarbonsReceived>();
- CPPUNIT_ASSERT(received);
-
- boost::shared_ptr<Forwarded> forwarded = received->getForwarded();
- CPPUNIT_ASSERT(forwarded);
-
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
- CPPUNIT_ASSERT(message);
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.example/balcony"), message->getFrom());
-
- boost::shared_ptr<Thread> thread = message->getPayload<Thread>();
- CPPUNIT_ASSERT(thread);
- CPPUNIT_ASSERT_EQUAL(std::string("0e3141cd80894871a68e6fe6b1ec56fa"), thread->getText());
- }
-
- /*
- * Test parsing of example 14 in XEP-0280.
- */
- void testParseExample14() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<sent xmlns='urn:xmpp:carbons:2'>"
- "<forwarded xmlns='urn:xmpp:forward:0'>"
- "<message xmlns='jabber:client'"
- " to='juliet@capulet.example/balcony'"
- " from='romeo@montague.example/home'"
- " type='chat'>"
- "<body>Neither, fair saint, if either thee dislike.</body>"
- "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
- "</message>"
- "</forwarded>"
- "</sent>"));
-
- CarbonsSent::ref sent = parser.getPayload<CarbonsSent>();
- CPPUNIT_ASSERT(sent);
-
- boost::shared_ptr<Forwarded> forwarded = sent->getForwarded();
- CPPUNIT_ASSERT(forwarded);
-
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
- CPPUNIT_ASSERT(message);
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.example/balcony"), message->getTo());
- }
-
- /*
- * Test parsing of example 15 in XEP-0280.
- */
- void testParseExample15() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<private xmlns='urn:xmpp:carbons:2'/>"));
-
- CPPUNIT_ASSERT(parser.getPayload<CarbonsPrivate>());
- }
+ CPPUNIT_TEST_SUITE(CarbonsParserTest);
+ CPPUNIT_TEST(testParseExample3);
+ CPPUNIT_TEST(testParseExample6);
+ CPPUNIT_TEST(testParseExample12);
+ CPPUNIT_TEST(testParseExample14);
+ CPPUNIT_TEST(testParseExample15);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ CarbonsParserTest() {}
+
+ /*
+ * Test parsing of example 3 in XEP-0280.
+ */
+ void testParseExample3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<enable xmlns='urn:xmpp:carbons:2' />"));
+
+ CarbonsEnable::ref enable = parser.getPayload<CarbonsEnable>();
+ CPPUNIT_ASSERT(enable);
+ }
+
+ /*
+ * Test parsing of example 6 in XEP-0280.
+ */
+ void testParseExample6() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<disable xmlns='urn:xmpp:carbons:2' />"));
+
+ CarbonsDisable::ref disable = parser.getPayload<CarbonsDisable>();
+ CPPUNIT_ASSERT(disable);
+ }
+
+ /*
+ * Test parsing of example 12 in XEP-0280.
+ */
+ void testParseExample12() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<received xmlns='urn:xmpp:carbons:2'>"
+ "<forwarded xmlns='urn:xmpp:forward:0'>"
+ "<message xmlns='jabber:client'"
+ " from='juliet@capulet.example/balcony'"
+ " to='romeo@montague.example/garden'"
+ " type='chat'>"
+ "<body>What man art thou that, thus bescreen'd in night, so stumblest on my counsel?</body>"
+ "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
+ "</message>"
+ "</forwarded>"
+ "</received>"));
+
+ CarbonsReceived::ref received = parser.getPayload<CarbonsReceived>();
+ CPPUNIT_ASSERT(received);
+
+ boost::shared_ptr<Forwarded> forwarded = received->getForwarded();
+ CPPUNIT_ASSERT(forwarded);
+
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.example/balcony"), message->getFrom());
+
+ boost::shared_ptr<Thread> thread = message->getPayload<Thread>();
+ CPPUNIT_ASSERT(thread);
+ CPPUNIT_ASSERT_EQUAL(std::string("0e3141cd80894871a68e6fe6b1ec56fa"), thread->getText());
+ }
+
+ /*
+ * Test parsing of example 14 in XEP-0280.
+ */
+ void testParseExample14() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<sent xmlns='urn:xmpp:carbons:2'>"
+ "<forwarded xmlns='urn:xmpp:forward:0'>"
+ "<message xmlns='jabber:client'"
+ " to='juliet@capulet.example/balcony'"
+ " from='romeo@montague.example/home'"
+ " type='chat'>"
+ "<body>Neither, fair saint, if either thee dislike.</body>"
+ "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
+ "</message>"
+ "</forwarded>"
+ "</sent>"));
+
+ CarbonsSent::ref sent = parser.getPayload<CarbonsSent>();
+ CPPUNIT_ASSERT(sent);
+
+ boost::shared_ptr<Forwarded> forwarded = sent->getForwarded();
+ CPPUNIT_ASSERT(forwarded);
+
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.example/balcony"), message->getTo());
+ }
+
+ /*
+ * Test parsing of example 15 in XEP-0280.
+ */
+ void testParseExample15() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<private xmlns='urn:xmpp:carbons:2'/>"));
+
+ CPPUNIT_ASSERT(parser.getPayload<CarbonsPrivate>());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(CarbonsParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp
index c47682c..fa8d014 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp
@@ -13,74 +13,74 @@
using namespace Swift;
class CommandParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CommandParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Result);
- CPPUNIT_TEST(testParse_Form);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(CommandParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Result);
+ CPPUNIT_TEST(testParse_Form);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse() {
- PayloadsParserTester parser;
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<command xmlns='http://jabber.org/protocol/commands' node='list' action='prev' sessionid='myid'/>"
- ));
+ CPPUNIT_ASSERT(parser.parse(
+ "<command xmlns='http://jabber.org/protocol/commands' node='list' action='prev' sessionid='myid'/>"
+ ));
- Command::ref payload = parser.getPayload<Command>();
- CPPUNIT_ASSERT_EQUAL(Command::Prev, payload->getAction());
- CPPUNIT_ASSERT_EQUAL(std::string("list"), payload->getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), payload->getSessionID());
- }
+ Command::ref payload = parser.getPayload<Command>();
+ CPPUNIT_ASSERT_EQUAL(Command::Prev, payload->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("list"), payload->getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), payload->getSessionID());
+ }
- void testParse_Result() {
- PayloadsParserTester parser;
+ void testParse_Result() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<command xmlns='http://jabber.org/protocol/commands' node='config' status='completed' sessionid='myid'>"
- "<note type='warn'>Service 'httpd' has been configured.</note>"
- "<note type='error'>I lied.</note>"
- "<actions execute='next'>"
- "<prev/>"
- "<next/>"
- "</actions>"
- "</command>"
- ));
+ CPPUNIT_ASSERT(parser.parse(
+ "<command xmlns='http://jabber.org/protocol/commands' node='config' status='completed' sessionid='myid'>"
+ "<note type='warn'>Service 'httpd' has been configured.</note>"
+ "<note type='error'>I lied.</note>"
+ "<actions execute='next'>"
+ "<prev/>"
+ "<next/>"
+ "</actions>"
+ "</command>"
+ ));
- Command::ref payload = parser.getPayload<Command>();
- CPPUNIT_ASSERT_EQUAL(Command::Completed, payload->getStatus());
- std::vector<Command::Note> notes = payload->getNotes();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(notes.size()));
- CPPUNIT_ASSERT_EQUAL(Command::Note::Warn, notes[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("Service 'httpd' has been configured."), notes[0].note);
- CPPUNIT_ASSERT_EQUAL(Command::Note::Error, notes[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("I lied."), notes[1].note);
- std::vector<Command::Action> actions = payload->getAvailableActions();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(actions.size()));
- CPPUNIT_ASSERT_EQUAL(Command::Prev, actions[0]);
- CPPUNIT_ASSERT_EQUAL(Command::Next, actions[1]);
- CPPUNIT_ASSERT_EQUAL(Command::Next, payload->getExecuteAction());
- }
+ Command::ref payload = parser.getPayload<Command>();
+ CPPUNIT_ASSERT_EQUAL(Command::Completed, payload->getStatus());
+ std::vector<Command::Note> notes = payload->getNotes();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(notes.size()));
+ CPPUNIT_ASSERT_EQUAL(Command::Note::Warn, notes[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("Service 'httpd' has been configured."), notes[0].note);
+ CPPUNIT_ASSERT_EQUAL(Command::Note::Error, notes[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("I lied."), notes[1].note);
+ std::vector<Command::Action> actions = payload->getAvailableActions();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(actions.size()));
+ CPPUNIT_ASSERT_EQUAL(Command::Prev, actions[0]);
+ CPPUNIT_ASSERT_EQUAL(Command::Next, actions[1]);
+ CPPUNIT_ASSERT_EQUAL(Command::Next, payload->getExecuteAction());
+ }
- void testParse_Form() {
- PayloadsParserTester parser;
+ void testParse_Form() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<command xmlns='http://jabber.org/protocol/commands' node='config' status='completed'>"
- "<x type=\"result\" xmlns=\"jabber:x:data\">"
- "<title>Bot Configuration</title>"
- "<instructions>Hello!</instructions>"
- "<instructions>Fill out this form to configure your new bot!</instructions>"
- "</x>"
- "</command>"
- ));
+ CPPUNIT_ASSERT(parser.parse(
+ "<command xmlns='http://jabber.org/protocol/commands' node='config' status='completed'>"
+ "<x type=\"result\" xmlns=\"jabber:x:data\">"
+ "<title>Bot Configuration</title>"
+ "<instructions>Hello!</instructions>"
+ "<instructions>Fill out this form to configure your new bot!</instructions>"
+ "</x>"
+ "</command>"
+ ));
- Command::ref payload = parser.getPayload<Command>();
- Form::ref form = payload->getForm();
- CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), form->getTitle());
- CPPUNIT_ASSERT_EQUAL(std::string("Hello!\nFill out this form to configure your new bot!"), form->getInstructions());
- CPPUNIT_ASSERT_EQUAL(Form::ResultType, form->getType());
- }
+ Command::ref payload = parser.getPayload<Command>();
+ Form::ref form = payload->getForm();
+ CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), form->getTitle());
+ CPPUNIT_ASSERT_EQUAL(std::string("Hello!\nFill out this form to configure your new bot!"), form->getInstructions());
+ CPPUNIT_ASSERT_EQUAL(Form::ResultType, form->getType());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(CommandParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp
index 919c342..d18e1b4 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp
@@ -15,29 +15,29 @@
using namespace Swift;
class DeliveryReceiptParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DeliveryReceiptParserTest);
- CPPUNIT_TEST(testParseXEP0184Example3);
- CPPUNIT_TEST(testParseXEP0184Example4);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DeliveryReceiptParserTest);
+ CPPUNIT_TEST(testParseXEP0184Example3);
+ CPPUNIT_TEST(testParseXEP0184Example4);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParseXEP0184Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<request xmlns='urn:xmpp:receipts'/>"));
+ public:
+ void testParseXEP0184Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<request xmlns='urn:xmpp:receipts'/>"));
- DeliveryReceiptRequest::ref request = boost::dynamic_pointer_cast<DeliveryReceiptRequest>(parser.getPayload());
+ DeliveryReceiptRequest::ref request = boost::dynamic_pointer_cast<DeliveryReceiptRequest>(parser.getPayload());
- CPPUNIT_ASSERT(request);
- }
+ CPPUNIT_ASSERT(request);
+ }
- void testParseXEP0184Example4() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<received xmlns='urn:xmpp:receipts' id='richard2-4.1.247'/>"));
+ void testParseXEP0184Example4() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<received xmlns='urn:xmpp:receipts' id='richard2-4.1.247'/>"));
- DeliveryReceipt::ref receipt = boost::dynamic_pointer_cast<DeliveryReceipt>(parser.getPayload());
+ DeliveryReceipt::ref receipt = boost::dynamic_pointer_cast<DeliveryReceipt>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(std::string("richard2-4.1.247"), receipt->getReceivedID());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("richard2-4.1.247"), receipt->getReceivedID());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DeliveryReceiptParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp
index 35995c9..c23b1d0 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp
@@ -13,91 +13,91 @@
using namespace Swift;
class DiscoInfoParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DiscoInfoParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Node);
- CPPUNIT_TEST(testParse_Form);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DiscoInfoParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Node);
+ CPPUNIT_TEST(testParse_Form);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse() {
- PayloadsParserTester parser;
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
- "<identity name=\"Swift\" category=\"client\" type=\"pc\" xml:lang=\"en\"/>"
- "<identity name=\"Vlug\" category=\"client\" type=\"pc\" xml:lang=\"nl\"/>"
- "<feature var=\"foo-feature\"/>"
- "<feature var=\"bar-feature\"/>"
- "<feature var=\"baz-feature\"/>"
- "</query>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
+ "<identity name=\"Swift\" category=\"client\" type=\"pc\" xml:lang=\"en\"/>"
+ "<identity name=\"Vlug\" category=\"client\" type=\"pc\" xml:lang=\"nl\"/>"
+ "<feature var=\"foo-feature\"/>"
+ "<feature var=\"bar-feature\"/>"
+ "<feature var=\"baz-feature\"/>"
+ "</query>"));
- DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getIdentities().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Swift"), payload->getIdentities()[0].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[0].getType());
- CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[0].getCategory());
- CPPUNIT_ASSERT_EQUAL(std::string("en"), payload->getIdentities()[0].getLanguage());
- CPPUNIT_ASSERT_EQUAL(std::string("Vlug"), payload->getIdentities()[1].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[1].getType());
- CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[1].getCategory());
- CPPUNIT_ASSERT_EQUAL(std::string("nl"), payload->getIdentities()[1].getLanguage());
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getFeatures().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("baz-feature"), payload->getFeatures()[2]);
- CPPUNIT_ASSERT(payload->getNode().empty());
- }
+ DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getIdentities().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Swift"), payload->getIdentities()[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[0].getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[0].getCategory());
+ CPPUNIT_ASSERT_EQUAL(std::string("en"), payload->getIdentities()[0].getLanguage());
+ CPPUNIT_ASSERT_EQUAL(std::string("Vlug"), payload->getIdentities()[1].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[1].getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[1].getCategory());
+ CPPUNIT_ASSERT_EQUAL(std::string("nl"), payload->getIdentities()[1].getLanguage());
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getFeatures().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("baz-feature"), payload->getFeatures()[2]);
+ CPPUNIT_ASSERT(payload->getNode().empty());
+ }
- void testParse_Node() {
- PayloadsParserTester parser;
+ void testParse_Node() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"http://jabber.org/protocol/disco#info\" node=\"blahblah\">"
- "<identity name=\"Swift\" category=\"client\" type=\"pc\" xml:lang=\"en\"/>"
- "<identity name=\"Vlug\" category=\"client\" type=\"pc\" xml:lang=\"nl\"/>"
- "<feature var=\"foo-feature\"/>"
- "<feature var=\"bar-feature\"/>"
- "<feature var=\"baz-feature\"/>"
- "</query>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"http://jabber.org/protocol/disco#info\" node=\"blahblah\">"
+ "<identity name=\"Swift\" category=\"client\" type=\"pc\" xml:lang=\"en\"/>"
+ "<identity name=\"Vlug\" category=\"client\" type=\"pc\" xml:lang=\"nl\"/>"
+ "<feature var=\"foo-feature\"/>"
+ "<feature var=\"bar-feature\"/>"
+ "<feature var=\"baz-feature\"/>"
+ "</query>"));
- DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getIdentities().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Swift"), payload->getIdentities()[0].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[0].getType());
- CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[0].getCategory());
- CPPUNIT_ASSERT_EQUAL(std::string("en"), payload->getIdentities()[0].getLanguage());
- CPPUNIT_ASSERT_EQUAL(std::string("Vlug"), payload->getIdentities()[1].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[1].getType());
- CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[1].getCategory());
- CPPUNIT_ASSERT_EQUAL(std::string("nl"), payload->getIdentities()[1].getLanguage());
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getFeatures().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("baz-feature"), payload->getFeatures()[2]);
- CPPUNIT_ASSERT_EQUAL(std::string("blahblah"), payload->getNode());
- }
+ DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getIdentities().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Swift"), payload->getIdentities()[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[0].getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[0].getCategory());
+ CPPUNIT_ASSERT_EQUAL(std::string("en"), payload->getIdentities()[0].getLanguage());
+ CPPUNIT_ASSERT_EQUAL(std::string("Vlug"), payload->getIdentities()[1].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("pc"), payload->getIdentities()[1].getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("client"), payload->getIdentities()[1].getCategory());
+ CPPUNIT_ASSERT_EQUAL(std::string("nl"), payload->getIdentities()[1].getLanguage());
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getFeatures().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("baz-feature"), payload->getFeatures()[2]);
+ CPPUNIT_ASSERT_EQUAL(std::string("blahblah"), payload->getNode());
+ }
- void testParse_Form() {
- PayloadsParserTester parser;
+ void testParse_Form() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
- "<feature var=\"foo-feature\"/>"
- "<x type=\"submit\" xmlns=\"jabber:x:data\">"
- "<title>Bot Configuration</title>"
- "<instructions>Hello!</instructions>"
- "</x>"
- "<feature var=\"bar-feature\"/>"
- "</query>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
+ "<feature var=\"foo-feature\"/>"
+ "<x type=\"submit\" xmlns=\"jabber:x:data\">"
+ "<title>Bot Configuration</title>"
+ "<instructions>Hello!</instructions>"
+ "</x>"
+ "<feature var=\"bar-feature\"/>"
+ "</query>"));
- DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getExtensions().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), payload->getExtensions()[0]->getTitle());
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getFeatures().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
- }
+ DiscoInfo::ref payload = boost::dynamic_pointer_cast<DiscoInfo>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getExtensions().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), payload->getExtensions()[0]->getTitle());
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getFeatures().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo-feature"), payload->getFeatures()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar-feature"), payload->getFeatures()[1]);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DiscoInfoParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp
index ee234ad..01db978 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp
@@ -13,30 +13,30 @@
using namespace Swift;
class DiscoItemsParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DiscoItemsParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='http://jabber.org/protocol/disco#items' node='http://jabber.org/protocol/commands'>"
- "<item jid='responder@domain' node='list' name='List Service Configurations'/>"
- "<item jid='responder@domain' node='config' name='Configure Service'/>"
- "</query>"));
-
- boost::shared_ptr<DiscoItems> payload = boost::dynamic_pointer_cast<DiscoItems>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getItems().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("List Service Configurations"), payload->getItems()[0].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("list"), payload->getItems()[0].getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("responder@domain"), payload->getItems()[0].getJID().toString());
- CPPUNIT_ASSERT_EQUAL(std::string("Configure Service"), payload->getItems()[1].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("config"), payload->getItems()[1].getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("responder@domain"), payload->getItems()[1].getJID().toString());
- CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/commands"), payload->getNode());
- }
+ CPPUNIT_TEST_SUITE(DiscoItemsParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='http://jabber.org/protocol/disco#items' node='http://jabber.org/protocol/commands'>"
+ "<item jid='responder@domain' node='list' name='List Service Configurations'/>"
+ "<item jid='responder@domain' node='config' name='Configure Service'/>"
+ "</query>"));
+
+ boost::shared_ptr<DiscoItems> payload = boost::dynamic_pointer_cast<DiscoItems>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getItems().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("List Service Configurations"), payload->getItems()[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("list"), payload->getItems()[0].getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("responder@domain"), payload->getItems()[0].getJID().toString());
+ CPPUNIT_ASSERT_EQUAL(std::string("Configure Service"), payload->getItems()[1].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("config"), payload->getItems()[1].getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("responder@domain"), payload->getItems()[1].getJID().toString());
+ CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/commands"), payload->getNode());
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp
index 6b0391d..529d573 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp
@@ -14,44 +14,44 @@
using namespace Swift;
class ErrorParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ErrorParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParseWithPayload);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<error type=\"modify\">"
- "<bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
- "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">boo</text>"
- "</error>"));
-
- ErrorPayload::ref payload = boost::dynamic_pointer_cast<ErrorPayload>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, payload->getCondition());
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, payload->getType());
- CPPUNIT_ASSERT_EQUAL(std::string("boo"), payload->getText());
- CPPUNIT_ASSERT(!payload->getPayload());
- }
-
- void testParseWithPayload() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<error type=\"modify\">"
- "<bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
- "<delay xmlns='urn:xmpp:delay' from='juliet@capulet.com/balcony' stamp='2002-09-10T23:41:07Z'/>"
- "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">boo</text>"
- "</error>"));
-
- ErrorPayload::ref payload = boost::dynamic_pointer_cast<ErrorPayload>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, payload->getCondition());
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, payload->getType());
- CPPUNIT_ASSERT_EQUAL(std::string("boo"), payload->getText());
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Delay>(payload->getPayload()));
- }
+ CPPUNIT_TEST_SUITE(ErrorParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParseWithPayload);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<error type=\"modify\">"
+ "<bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
+ "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">boo</text>"
+ "</error>"));
+
+ ErrorPayload::ref payload = boost::dynamic_pointer_cast<ErrorPayload>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, payload->getCondition());
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, payload->getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("boo"), payload->getText());
+ CPPUNIT_ASSERT(!payload->getPayload());
+ }
+
+ void testParseWithPayload() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<error type=\"modify\">"
+ "<bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
+ "<delay xmlns='urn:xmpp:delay' from='juliet@capulet.com/balcony' stamp='2002-09-10T23:41:07Z'/>"
+ "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">boo</text>"
+ "</error>"));
+
+ ErrorPayload::ref payload = boost::dynamic_pointer_cast<ErrorPayload>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::BadRequest, payload->getCondition());
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::Modify, payload->getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("boo"), payload->getText());
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Delay>(payload->getPayload()));
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
index 0c70b5c..4ffc776 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
@@ -13,216 +13,216 @@
using namespace Swift;
class FormParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FormParserTest);
- CPPUNIT_TEST(testParse_FormInformation);
- CPPUNIT_TEST(testParse_FormLayout);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_FormItems);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse_FormInformation() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<x type=\"submit\" xmlns=\"jabber:x:data\">"
- "<title>Bot Configuration</title>"
- "<instructions>Hello!</instructions>"
- "<instructions>Fill out this form to configure your new bot!</instructions>"
- "</x>"
- ));
-
- Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), payload->getTitle());
- CPPUNIT_ASSERT_EQUAL(std::string("Hello!\nFill out this form to configure your new bot!"), payload->getInstructions());
- CPPUNIT_ASSERT_EQUAL(Form::SubmitType, payload->getType());
- }
-
- void testParse_FormLayout() {
- PayloadsParserTester parser;
-
- // P1 = page one, S1 = section one, F1 = field one, T1 = text one
- CPPUNIT_ASSERT(parser.parse(
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<page label=\"P1\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
- "<reportedref/>"
- "<text>P1T1</text>"
- "<fieldref var=\"P1F1\"/>"
- "<section label=\"P1S1\">"
- "<text>P1S1T1</text>"
- "<fieldref var=\"P1S1F1\"/>"
- "</section>"
- "</page>"
- "<page label=\"P2\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
- "<section label=\"P2S1\">"
- "<section label=\"P2S2\">"
- "<section label=\"P2S3\"/>"
- "</section>"
- "</section>"
- "</page>"
- "<field label=\"field one\" type=\"text-single\" var=\"P1F1\"/>"
- "<field label=\"field two\" type=\"text-single\" var=\"P1S1F1\"/>"
- "</x>"));
-
- Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(payload->getFields().size()));
- // PAGE ONE - parsing of element types
- CPPUNIT_ASSERT_EQUAL(std::string("P1"), payload->getPages()[0]->getLabel());
- CPPUNIT_ASSERT(payload->getPages()[0]->getReportedRefs()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("P1T1"), payload->getPages()[0]->getTextElements()[0]->getTextString());
- CPPUNIT_ASSERT_EQUAL(std::string("P1F1"), payload->getPages()[0]->getFields()[0]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("P1S1"), payload->getPages()[0]->getChildSections()[0]->getLabel());
- CPPUNIT_ASSERT_EQUAL(std::string("P1S1T1"), payload->getPages()[0]->getChildSections()[0]->getTextElements()[0]->getTextString());
- CPPUNIT_ASSERT_EQUAL(std::string("P1S1F1"), payload->getPages()[0]->getChildSections()[0]->getFields()[0]->getName());
- // PAGE TWO - parsing of nested elements
- CPPUNIT_ASSERT_EQUAL(std::string("P2"), payload->getPages()[1]->getLabel());
- CPPUNIT_ASSERT_EQUAL(std::string("P2S1"), payload->getPages()[1]->getChildSections()[0]->getLabel());
- CPPUNIT_ASSERT_EQUAL(std::string("P2S2"), payload->getPages()[1]->getChildSections()[0]->getChildSections()[0]->getLabel());
- CPPUNIT_ASSERT_EQUAL(std::string("P2S3"), payload->getPages()[1]->getChildSections()[0]->getChildSections()[0]->getChildSections()[0]->getLabel());
- }
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:bot</value>"
- "</field>"
- "<field type=\"fixed\"><value>Section 1: Bot Info</value></field>"
- "<field label=\"The name of your bot\" type=\"text-single\" var=\"botname\"/>"
- "<field label=\"Helpful description of your bot\" type=\"text-multi\" var=\"description\"><value>This is a bot.</value><value>A quite good one actually</value></field>"
- "<field label=\"Public bot?\" type=\"boolean\" var=\"public\">"
- "<required/>"
- "<value>1</value>"
- "</field>"
- "<field label=\"Password for special access\" type=\"text-private\" var=\"password\"/>"
- "<field label=\"What features will the bot support?\" type=\"list-multi\" var=\"features\">"
- "<option label=\"Contests\"><value>contests</value></option>"
- "<option label=\"News\"><value>news</value></option>"
- "<option label=\"Polls\"><value>polls</value></option>"
- "<option label=\"Reminders\"><value>reminders</value></option>"
- "<option label=\"Search\"><value>search</value></option>"
- "<value>news</value>"
- "<value>search</value>"
- "</field>"
- "<field label=\"Maximum number of subscribers\" type=\"list-single\" var=\"maxsubs\">"
- "<value>20</value>"
- "<option label=\"10\"><value>10</value></option>"
- "<option label=\"20\"><value>20</value></option>"
- "<option label=\"30\"><value>30</value></option>"
- "<option label=\"50\"><value>50</value></option>"
- "<option label=\"100\"><value>100</value></option>"
- "<option label=\"None\"><value>none</value></option>"
- "</field>"
- "<field label=\"People to invite\" type=\"jid-multi\" var=\"invitelist\">"
- "<desc>Tell all your friends about your new bot!</desc>"
- "<value>foo@bar.com</value>"
- "<value>baz@fum.org</value>"
- "</field>"
- "<field var=\"untyped\">"
- "<value>foo</value>"
- "</field>"
- "</x>"));
-
- Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
-
- CPPUNIT_ASSERT_EQUAL(10, static_cast<int>(payload->getFields().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), payload->getFields()[0]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("FORM_TYPE"), payload->getFields()[0]->getName());
- CPPUNIT_ASSERT(!payload->getFields()[0]->getRequired());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Section 1: Bot Info"), payload->getFields()[1]->getValues()[0]);
-
- CPPUNIT_ASSERT_EQUAL(std::string("The name of your bot"), payload->getFields()[2]->getLabel());
-
- CPPUNIT_ASSERT_EQUAL(std::string("This is a bot.\nA quite good one actually"), payload->getFields()[3]->getTextMultiValue());
-
- CPPUNIT_ASSERT_EQUAL(true, payload->getFields()[4]->getBoolValue());
- CPPUNIT_ASSERT(payload->getFields()[4]->getRequired());
- CPPUNIT_ASSERT_EQUAL(std::string("1"), payload->getFields()[4]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getFields()[6]->getValues().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("news"), payload->getFields()[6]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("search"), payload->getFields()[6]->getValues()[1]);
- CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(payload->getFields()[6]->getOptions().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Contests"), payload->getFields()[6]->getOptions()[0].label);
- CPPUNIT_ASSERT_EQUAL(std::string("contests"), payload->getFields()[6]->getOptions()[0].value);
- CPPUNIT_ASSERT_EQUAL(std::string("News"), payload->getFields()[6]->getOptions()[1].label);
- CPPUNIT_ASSERT_EQUAL(std::string("news"), payload->getFields()[6]->getOptions()[1].value);
-
- CPPUNIT_ASSERT_EQUAL(std::string("20"), payload->getFields()[7]->getValues()[0]);
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), payload->getFields()[8]->getJIDMultiValue(0));
- CPPUNIT_ASSERT_EQUAL(JID("baz@fum.org"), payload->getFields()[8]->getJIDMultiValue(1));
- CPPUNIT_ASSERT_EQUAL(std::string("Tell all your friends about your new bot!"), payload->getFields()[8]->getDescription());
-
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->getFields()[9]->getValues()[0]);
- }
-
- void testParse_FormItems() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<x xmlns='jabber:x:data' type='result'>"
- "<field type='hidden' var='FORM_TYPE'>"
- "<value>jabber:iq:search</value>"
- "</field>"
- "<reported>"
- "<field var='first' label='Given Name' type='text-single'/>"
- "<field var='last' label='Family Name' type='text-single'/>"
- "<field var='jid' label='Jabber ID' type='jid-single'/>"
- "<field var='x-gender' label='Gender' type='list-single'/>"
- "</reported>"
- "<item>"
- "<field var='first'><value>Benvolio</value></field>"
- "<field var='last'><value>Montague</value></field>"
- "<field var='jid'><value>benvolio@montague.net</value></field>"
- "<field var='x-gender'><value>male</value></field>"
- "</item>"
- "<item>"
- "<field var='first'><value>Romeo</value></field>"
- "<field var='last'><value>Montague</value></field>"
- "<field var='jid'><value>romeo@montague.net</value></field>"
- "<field var='x-gender'><value>male</value></field>"
- "</item>"
- "</x>"));
-
- Form* dataForm = dynamic_cast<Form*>(parser.getPayload().get());
- CPPUNIT_ASSERT(dataForm);
-
- Form::FormItem reported = dataForm->getReportedFields();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), reported.size());
-
- std::vector<Form::FormItem> items = dataForm->getItems();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
-
- Form::FormItem item = items[0];
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Benvolio"), item[0]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
- boost::shared_ptr<FormField> jidField = item[2];
- CPPUNIT_ASSERT_EQUAL(JID("benvolio@montague.net"), jidField->getJIDSingleValue());
- CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
-
- item = items[1];
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Romeo"), item[0]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
- jidField = item[2];
- CPPUNIT_ASSERT(jidField);
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), jidField->getJIDSingleValue());
- CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
- }
+ CPPUNIT_TEST_SUITE(FormParserTest);
+ CPPUNIT_TEST(testParse_FormInformation);
+ CPPUNIT_TEST(testParse_FormLayout);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_FormItems);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse_FormInformation() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<x type=\"submit\" xmlns=\"jabber:x:data\">"
+ "<title>Bot Configuration</title>"
+ "<instructions>Hello!</instructions>"
+ "<instructions>Fill out this form to configure your new bot!</instructions>"
+ "</x>"
+ ));
+
+ Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Bot Configuration"), payload->getTitle());
+ CPPUNIT_ASSERT_EQUAL(std::string("Hello!\nFill out this form to configure your new bot!"), payload->getInstructions());
+ CPPUNIT_ASSERT_EQUAL(Form::SubmitType, payload->getType());
+ }
+
+ void testParse_FormLayout() {
+ PayloadsParserTester parser;
+
+ // P1 = page one, S1 = section one, F1 = field one, T1 = text one
+ CPPUNIT_ASSERT(parser.parse(
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<page label=\"P1\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
+ "<reportedref/>"
+ "<text>P1T1</text>"
+ "<fieldref var=\"P1F1\"/>"
+ "<section label=\"P1S1\">"
+ "<text>P1S1T1</text>"
+ "<fieldref var=\"P1S1F1\"/>"
+ "</section>"
+ "</page>"
+ "<page label=\"P2\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
+ "<section label=\"P2S1\">"
+ "<section label=\"P2S2\">"
+ "<section label=\"P2S3\"/>"
+ "</section>"
+ "</section>"
+ "</page>"
+ "<field label=\"field one\" type=\"text-single\" var=\"P1F1\"/>"
+ "<field label=\"field two\" type=\"text-single\" var=\"P1S1F1\"/>"
+ "</x>"));
+
+ Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(payload->getFields().size()));
+ // PAGE ONE - parsing of element types
+ CPPUNIT_ASSERT_EQUAL(std::string("P1"), payload->getPages()[0]->getLabel());
+ CPPUNIT_ASSERT(payload->getPages()[0]->getReportedRefs()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("P1T1"), payload->getPages()[0]->getTextElements()[0]->getTextString());
+ CPPUNIT_ASSERT_EQUAL(std::string("P1F1"), payload->getPages()[0]->getFields()[0]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("P1S1"), payload->getPages()[0]->getChildSections()[0]->getLabel());
+ CPPUNIT_ASSERT_EQUAL(std::string("P1S1T1"), payload->getPages()[0]->getChildSections()[0]->getTextElements()[0]->getTextString());
+ CPPUNIT_ASSERT_EQUAL(std::string("P1S1F1"), payload->getPages()[0]->getChildSections()[0]->getFields()[0]->getName());
+ // PAGE TWO - parsing of nested elements
+ CPPUNIT_ASSERT_EQUAL(std::string("P2"), payload->getPages()[1]->getLabel());
+ CPPUNIT_ASSERT_EQUAL(std::string("P2S1"), payload->getPages()[1]->getChildSections()[0]->getLabel());
+ CPPUNIT_ASSERT_EQUAL(std::string("P2S2"), payload->getPages()[1]->getChildSections()[0]->getChildSections()[0]->getLabel());
+ CPPUNIT_ASSERT_EQUAL(std::string("P2S3"), payload->getPages()[1]->getChildSections()[0]->getChildSections()[0]->getChildSections()[0]->getLabel());
+ }
+
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:bot</value>"
+ "</field>"
+ "<field type=\"fixed\"><value>Section 1: Bot Info</value></field>"
+ "<field label=\"The name of your bot\" type=\"text-single\" var=\"botname\"/>"
+ "<field label=\"Helpful description of your bot\" type=\"text-multi\" var=\"description\"><value>This is a bot.</value><value>A quite good one actually</value></field>"
+ "<field label=\"Public bot?\" type=\"boolean\" var=\"public\">"
+ "<required/>"
+ "<value>1</value>"
+ "</field>"
+ "<field label=\"Password for special access\" type=\"text-private\" var=\"password\"/>"
+ "<field label=\"What features will the bot support?\" type=\"list-multi\" var=\"features\">"
+ "<option label=\"Contests\"><value>contests</value></option>"
+ "<option label=\"News\"><value>news</value></option>"
+ "<option label=\"Polls\"><value>polls</value></option>"
+ "<option label=\"Reminders\"><value>reminders</value></option>"
+ "<option label=\"Search\"><value>search</value></option>"
+ "<value>news</value>"
+ "<value>search</value>"
+ "</field>"
+ "<field label=\"Maximum number of subscribers\" type=\"list-single\" var=\"maxsubs\">"
+ "<value>20</value>"
+ "<option label=\"10\"><value>10</value></option>"
+ "<option label=\"20\"><value>20</value></option>"
+ "<option label=\"30\"><value>30</value></option>"
+ "<option label=\"50\"><value>50</value></option>"
+ "<option label=\"100\"><value>100</value></option>"
+ "<option label=\"None\"><value>none</value></option>"
+ "</field>"
+ "<field label=\"People to invite\" type=\"jid-multi\" var=\"invitelist\">"
+ "<desc>Tell all your friends about your new bot!</desc>"
+ "<value>foo@bar.com</value>"
+ "<value>baz@fum.org</value>"
+ "</field>"
+ "<field var=\"untyped\">"
+ "<value>foo</value>"
+ "</field>"
+ "</x>"));
+
+ Form* payload = dynamic_cast<Form*>(parser.getPayload().get());
+
+ CPPUNIT_ASSERT_EQUAL(10, static_cast<int>(payload->getFields().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:bot"), payload->getFields()[0]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("FORM_TYPE"), payload->getFields()[0]->getName());
+ CPPUNIT_ASSERT(!payload->getFields()[0]->getRequired());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Section 1: Bot Info"), payload->getFields()[1]->getValues()[0]);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("The name of your bot"), payload->getFields()[2]->getLabel());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("This is a bot.\nA quite good one actually"), payload->getFields()[3]->getTextMultiValue());
+
+ CPPUNIT_ASSERT_EQUAL(true, payload->getFields()[4]->getBoolValue());
+ CPPUNIT_ASSERT(payload->getFields()[4]->getRequired());
+ CPPUNIT_ASSERT_EQUAL(std::string("1"), payload->getFields()[4]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getFields()[6]->getValues().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("news"), payload->getFields()[6]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("search"), payload->getFields()[6]->getValues()[1]);
+ CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(payload->getFields()[6]->getOptions().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Contests"), payload->getFields()[6]->getOptions()[0].label);
+ CPPUNIT_ASSERT_EQUAL(std::string("contests"), payload->getFields()[6]->getOptions()[0].value);
+ CPPUNIT_ASSERT_EQUAL(std::string("News"), payload->getFields()[6]->getOptions()[1].label);
+ CPPUNIT_ASSERT_EQUAL(std::string("news"), payload->getFields()[6]->getOptions()[1].value);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("20"), payload->getFields()[7]->getValues()[0]);
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), payload->getFields()[8]->getJIDMultiValue(0));
+ CPPUNIT_ASSERT_EQUAL(JID("baz@fum.org"), payload->getFields()[8]->getJIDMultiValue(1));
+ CPPUNIT_ASSERT_EQUAL(std::string("Tell all your friends about your new bot!"), payload->getFields()[8]->getDescription());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->getFields()[9]->getValues()[0]);
+ }
+
+ void testParse_FormItems() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<x xmlns='jabber:x:data' type='result'>"
+ "<field type='hidden' var='FORM_TYPE'>"
+ "<value>jabber:iq:search</value>"
+ "</field>"
+ "<reported>"
+ "<field var='first' label='Given Name' type='text-single'/>"
+ "<field var='last' label='Family Name' type='text-single'/>"
+ "<field var='jid' label='Jabber ID' type='jid-single'/>"
+ "<field var='x-gender' label='Gender' type='list-single'/>"
+ "</reported>"
+ "<item>"
+ "<field var='first'><value>Benvolio</value></field>"
+ "<field var='last'><value>Montague</value></field>"
+ "<field var='jid'><value>benvolio@montague.net</value></field>"
+ "<field var='x-gender'><value>male</value></field>"
+ "</item>"
+ "<item>"
+ "<field var='first'><value>Romeo</value></field>"
+ "<field var='last'><value>Montague</value></field>"
+ "<field var='jid'><value>romeo@montague.net</value></field>"
+ "<field var='x-gender'><value>male</value></field>"
+ "</item>"
+ "</x>"));
+
+ Form* dataForm = dynamic_cast<Form*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(dataForm);
+
+ Form::FormItem reported = dataForm->getReportedFields();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), reported.size());
+
+ std::vector<Form::FormItem> items = dataForm->getItems();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
+
+ Form::FormItem item = items[0];
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Benvolio"), item[0]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
+ boost::shared_ptr<FormField> jidField = item[2];
+ CPPUNIT_ASSERT_EQUAL(JID("benvolio@montague.net"), jidField->getJIDSingleValue());
+ CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
+
+ item = items[1];
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Romeo"), item[0]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
+ jidField = item[2];
+ CPPUNIT_ASSERT(jidField);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.net"), jidField->getJIDSingleValue());
+ CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(FormParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp
index fae259f..30af3ec 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp
@@ -19,100 +19,100 @@ using namespace Swift;
class ForwardedParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ForwardedParserTest);
- CPPUNIT_TEST(testParseIQ);
- CPPUNIT_TEST(testParseMessage);
- CPPUNIT_TEST(testParseMessageNoDelay);
- CPPUNIT_TEST(testParsePresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParseIQ() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
- "<iq xmlns=\"jabber:client\" type=\"get\" from=\"kindanormal@example.com/IM\" to=\"stupidnewbie@example.com\" id=\"id0\"/>"
- "</forwarded>"));
-
- boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getDelay());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
-
- boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(payload->getStanza());
- CPPUNIT_ASSERT(!!iq);
- CPPUNIT_ASSERT_EQUAL(JID("stupidnewbie@example.com"), iq->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("kindanormal@example.com/IM"), iq->getFrom());
- CPPUNIT_ASSERT_EQUAL(std::string("id0"), iq->getID());
- CPPUNIT_ASSERT_EQUAL(IQ::Get, iq->getType());
- }
-
- void testParseMessage() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
- "<message xmlns=\"jabber:client\" to=\"juliet@capulet.lit/balcony\" from=\"romeo@montague.lit/orchard\" type=\"chat\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"));
-
- boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getDelay());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
-
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(payload->getStanza());
- CPPUNIT_ASSERT(!!message);
- const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
- CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
- }
-
- void testParseMessageNoDelay() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<message xmlns=\"jabber:client\" to=\"juliet@capulet.lit/balcony\" from=\"romeo@montague.lit/orchard\" type=\"chat\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"));
-
- boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(!payload->getDelay());
-
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(payload->getStanza());
- CPPUNIT_ASSERT(!!message);
- const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
- CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
- }
-
- void testParsePresence() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
- "<presence xmlns=\"jabber:client\" from=\"alice@wonderland.lit/rabbithole\" to=\"madhatter@wonderland.lit\" type=\"unavailable\"/>"
- "</forwarded>"));
-
- boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getDelay());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
-
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(payload->getStanza());
- CPPUNIT_ASSERT(!!presence);
- CPPUNIT_ASSERT_EQUAL(JID("madhatter@wonderland.lit"), presence->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/rabbithole"), presence->getFrom());
- CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presence->getType());
- }
+ CPPUNIT_TEST_SUITE(ForwardedParserTest);
+ CPPUNIT_TEST(testParseIQ);
+ CPPUNIT_TEST(testParseMessage);
+ CPPUNIT_TEST(testParseMessageNoDelay);
+ CPPUNIT_TEST(testParsePresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParseIQ() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
+ "<iq xmlns=\"jabber:client\" type=\"get\" from=\"kindanormal@example.com/IM\" to=\"stupidnewbie@example.com\" id=\"id0\"/>"
+ "</forwarded>"));
+
+ boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getDelay());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
+
+ boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(payload->getStanza());
+ CPPUNIT_ASSERT(!!iq);
+ CPPUNIT_ASSERT_EQUAL(JID("stupidnewbie@example.com"), iq->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("kindanormal@example.com/IM"), iq->getFrom());
+ CPPUNIT_ASSERT_EQUAL(std::string("id0"), iq->getID());
+ CPPUNIT_ASSERT_EQUAL(IQ::Get, iq->getType());
+ }
+
+ void testParseMessage() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
+ "<message xmlns=\"jabber:client\" to=\"juliet@capulet.lit/balcony\" from=\"romeo@montague.lit/orchard\" type=\"chat\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"));
+
+ boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getDelay());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
+
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(payload->getStanza());
+ CPPUNIT_ASSERT(!!message);
+ const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
+ CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
+ }
+
+ void testParseMessageNoDelay() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<message xmlns=\"jabber:client\" to=\"juliet@capulet.lit/balcony\" from=\"romeo@montague.lit/orchard\" type=\"chat\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"));
+
+ boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(!payload->getDelay());
+
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(payload->getStanza());
+ CPPUNIT_ASSERT(!!message);
+ const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
+ CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
+ }
+
+ void testParsePresence() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay xmlns=\"urn:xmpp:delay\" stamp=\"2010-07-10T23:08:25Z\"/>"
+ "<presence xmlns=\"jabber:client\" from=\"alice@wonderland.lit/rabbithole\" to=\"madhatter@wonderland.lit\" type=\"unavailable\"/>"
+ "</forwarded>"));
+
+ boost::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getDelay());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(payload->getDelay()->getStamp()));
+
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(payload->getStanza());
+ CPPUNIT_ASSERT(!!presence);
+ CPPUNIT_ASSERT_EQUAL(JID("madhatter@wonderland.lit"), presence->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/rabbithole"), presence->getFrom());
+ CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presence->getType());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ForwardedParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp
index b7adead..782cb32 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp
@@ -14,26 +14,26 @@
using namespace Swift;
class IBBParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IBBParserTest);
- CPPUNIT_TEST(testParse_Data);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse_Data() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<data xmlns='http://jabber.org/protocol/ibb' seq='4'>\n"
- "\t YWJjZGVmZ2loamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjEyMzQ1\n"
- "\t Njc4OTAK\n"
- "</data>"
- ));
-
- IBB::ref ibb = parser.getPayload<IBB>();
- CPPUNIT_ASSERT(ibb->getAction() == IBB::Data);
- CPPUNIT_ASSERT(createByteArray("abcdefgihjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\x0a") == ibb->getData());
- CPPUNIT_ASSERT_EQUAL(4, ibb->getSequenceNumber());
- }
+ CPPUNIT_TEST_SUITE(IBBParserTest);
+ CPPUNIT_TEST(testParse_Data);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse_Data() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<data xmlns='http://jabber.org/protocol/ibb' seq='4'>\n"
+ "\t YWJjZGVmZ2loamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjEyMzQ1\n"
+ "\t Njc4OTAK\n"
+ "</data>"
+ ));
+
+ IBB::ref ibb = parser.getPayload<IBB>();
+ CPPUNIT_ASSERT(ibb->getAction() == IBB::Data);
+ CPPUNIT_ASSERT(createByteArray("abcdefgihjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\x0a") == ibb->getData());
+ CPPUNIT_ASSERT_EQUAL(4, ibb->getSequenceNumber());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(IBBParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp
index 7975352..462247a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp
@@ -21,24 +21,24 @@
using namespace Swift;
class IdleParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IdleParserTest);
- CPPUNIT_TEST(testParse_XepWhatever_Example1);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IdleParserTest);
+ CPPUNIT_TEST(testParse_XepWhatever_Example1);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse_XepWhatever_Example1() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<presence from='juliet@capulet.com/balcony'>\n"
- "<show>away</show>\n"
- "<idle xmlns='urn:xmpp:idle:1' since='1969-07-21T02:56:15Z'/>\n"
- "</presence>\n"
- ));
+ public:
+ void testParse_XepWhatever_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<presence from='juliet@capulet.com/balcony'>\n"
+ "<show>away</show>\n"
+ "<idle xmlns='urn:xmpp:idle:1' since='1969-07-21T02:56:15Z'/>\n"
+ "</presence>\n"
+ ));
- Presence::ref presence = parser.getPayload<Presence>();
- CPPUNIT_ASSERT(presence);
- Idle::ref idle = presence->getPayload<Idle>();
- CPPUNIT_ASSERT(idle);
- CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == idle->getSince());
- }
+ Presence::ref presence = parser.getPayload<Presence>();
+ CPPUNIT_ASSERT(presence);
+ Idle::ref idle = presence->getPayload<Idle>();
+ CPPUNIT_ASSERT(idle);
+ CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == idle->getSince());
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp
index ea33e82..6d08812 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp
@@ -14,7 +14,7 @@
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Elements/Form.h>
-#include <Swiften/Elements/InBandRegistrationPayload.h>
+#include <Swiften/Elements/InBandRegistrationPayload.h>
#include <Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
@@ -22,53 +22,53 @@ using namespace Swift;
class InBandRegistrationPayloadParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(InBandRegistrationPayloadParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Form);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(InBandRegistrationPayloadParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Form);
+ CPPUNIT_TEST_SUITE_END();
- public:
- InBandRegistrationPayloadParserTest() {}
+ public:
+ InBandRegistrationPayloadParserTest() {}
- void testParse() {
- PayloadsParserTester parser;
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"jabber:iq:register\">"
- "<registered/>"
- "</query>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"jabber:iq:register\">"
+ "<registered/>"
+ "</query>"));
- InBandRegistrationPayload* payload = dynamic_cast<InBandRegistrationPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(payload->isRegistered());
- }
+ InBandRegistrationPayload* payload = dynamic_cast<InBandRegistrationPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(payload->isRegistered());
+ }
- void testParse_Form() {
- PayloadsParserTester parser;
+ void testParse_Form() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"jabber:iq:register\">"
- "<instructions>Use the enclosed form to register.</instructions>"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<title>Contest Registration</title>"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:iq:register</value>"
- "</field>"
- "</x>"
- "</query>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"jabber:iq:register\">"
+ "<instructions>Use the enclosed form to register.</instructions>"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<title>Contest Registration</title>"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:iq:register</value>"
+ "</field>"
+ "</x>"
+ "</query>"));
- InBandRegistrationPayload* payload = dynamic_cast<InBandRegistrationPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- boost::optional<std::string> instruction = payload->getInstructions();
- CPPUNIT_ASSERT(instruction);
- CPPUNIT_ASSERT_EQUAL(std::string("Use the enclosed form to register."), instruction.get());
+ InBandRegistrationPayload* payload = dynamic_cast<InBandRegistrationPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ boost::optional<std::string> instruction = payload->getInstructions();
+ CPPUNIT_ASSERT(instruction);
+ CPPUNIT_ASSERT_EQUAL(std::string("Use the enclosed form to register."), instruction.get());
- Form::ref form = payload->getForm();
- CPPUNIT_ASSERT(form);
- CPPUNIT_ASSERT_EQUAL(std::string("Contest Registration"), form->getTitle());
- CPPUNIT_ASSERT_EQUAL(Form::FormType, form->getType());
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:register"), form->getFormType());
- }
+ Form::ref form = payload->getForm();
+ CPPUNIT_ASSERT(form);
+ CPPUNIT_ASSERT_EQUAL(std::string("Contest Registration"), form->getTitle());
+ CPPUNIT_ASSERT_EQUAL(Form::FormType, form->getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:register"), form->getFormType());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(InBandRegistrationPayloadParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
index 56143ef..3bf79a5 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
@@ -26,592 +26,592 @@
using namespace Swift;
class JingleParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(JingleParserTest);
- CPPUNIT_TEST(testParse_Xep0166_Example3);
- CPPUNIT_TEST(testParse_Xep0166_Example8);
-
- CPPUNIT_TEST(testParse_Xep0261_Example1);
- CPPUNIT_TEST(testParse_Xep0261_Example3);
- CPPUNIT_TEST(testParse_Xep0261_Example9);
- CPPUNIT_TEST(testParse_Xep0261_Example13);
-
- CPPUNIT_TEST(testParse_Xep0234_Example1);
- CPPUNIT_TEST(testParse_Xep0234_Example3);
- CPPUNIT_TEST(testParse_Xep0234_Example5);
- CPPUNIT_TEST(testParse_Xep0234_Example8);
- CPPUNIT_TEST(testParse_Xep0234_Example10);
-
- CPPUNIT_TEST(testParse_Xep0260_Example1);
- CPPUNIT_TEST(testParse_Xep0260_Example3);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- //http://xmpp.org/extensions/xep-0166.html#example-3
- void testParse_Xep0166_Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-terminate'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <reason>\n"
- " <success/>\n"
- " </reason>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
- CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
- jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
- }
-
- //http://xmpp.org/extensions/xep-0166.html#example-8
- void testParse_Xep0166_Example8() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-terminate'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <reason>\n"
- " <success/>\n"
- " <text>Sorry, gotta go!</text>\n"
- " </reason>\n"
- "</jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
- CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
- jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
- CPPUNIT_ASSERT_EQUAL(std::string("Sorry, gotta go!"),
- jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).text);
- }
-
- // IBB Transport Method Examples
-
- // http://xmpp.org/extensions/xep-0261.html#example-1
- void testParse_Xep0261_Example1() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-initiate'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <description xmlns='urn:xmpp:example'/>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
- " block-size='4096'\n"
- " sid='ch3d9s71'/>\n"
- " </content>\n"
- "</jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
- JingleContentPayload::ref payload = payloads[0];
- CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
- CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
-
- JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
- CPPUNIT_ASSERT(transportPaylod);
- CPPUNIT_ASSERT_EQUAL(4096U, *transportPaylod->getBlockSize());
- CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
- }
-
- // http://xmpp.org/extensions/xep-0261.html#example-1
- void testParse_Xep0261_Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-accept'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " responder='juliet@capulet.lit/balcony'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <description xmlns='urn:xmpp:example'/>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
- " block-size='2048'\n"
- " sid='ch3d9s71'/>\n"
- " </content>\n"
- " </jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), jingle->getResponder());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
- JingleContentPayload::ref payload = payloads[0];
- CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
- CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
-
- JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
- CPPUNIT_ASSERT(transportPaylod);
- CPPUNIT_ASSERT_EQUAL(2048U, *transportPaylod->getBlockSize());
- CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
- }
-
- // http://xmpp.org/extensions/xep-0261.html#example-9
- void testParse_Xep0261_Example9() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='transport-info'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
- " block-size='2048'\n"
- " sid='bt8a71h6'/>\n"
- " </content>\n"
- "</jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
- JingleContentPayload::ref payload = payloads[0];
- CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
- CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
-
- JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
- CPPUNIT_ASSERT(transportPaylod);
- CPPUNIT_ASSERT_EQUAL(2048U, *transportPaylod->getBlockSize());
- CPPUNIT_ASSERT_EQUAL(std::string("bt8a71h6"), transportPaylod->getSessionID());
- }
-
- // http://xmpp.org/extensions/xep-0261.html#example-13
- void testParse_Xep0261_Example13() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-terminate'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <reason><success/></reason>\n"
- " </jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
- CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success, jingle->getReason().get_value_or(JinglePayload::Reason()).type);
-
- }
-
- // Jingle File Transfer Examples
-
- // http://xmpp.org/extensions/xep-0234.html#example-1
- void testParse_Xep0234_Example1() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-initiate'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='851ba2'>\n"
- "<content creator='initiator' name='a-file-offer'>\n"
- "<description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
- "<file>\n"
- "<date>1969-07-21T02:56:15Z</date>\n"
- "<desc>This is a test. If this were a real file...</desc>\n"
- "<media-type>text/plain</media-type>\n"
- "<name>test.txt</name>\n"
- "<range/>\n"
- "<size>1022</size>\n"
- "<hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
- "</file>\n"
- "</description>\n"
- "<transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " mode='tcp'\n"
- " sid='vj3hs98y'>\n"
- "<candidate cid='hft54dqy'\n"
- " host='192.168.4.1'\n"
- " jid='romeo@montague.lit/orchard'\n"
- " port='5086'\n"
- " priority='8257636'\n"
- " type='direct'/>\n"
- "<candidate cid='hutr46fe'\n"
- " host='24.24.24.1'\n"
- " jid='romeo@montague.lit/orchard'\n"
- " port='5087'\n"
- " priority='8258636'\n"
- " type='direct'/>\n"
- "</transport>\n"
- "</content>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> contents = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
-
- JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
-
- CPPUNIT_ASSERT(description);
- JingleFileTransferFileInfo fileInfo = description->getFileInfo();
- CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), fileInfo.getName());
- CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), fileInfo.getHashes().begin()->first);
- CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(fileInfo.getHashes().begin()->second));
- CPPUNIT_ASSERT(1022 == fileInfo.getSize());
- CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), fileInfo.getDescription());
- CPPUNIT_ASSERT_EQUAL(true, fileInfo.getSupportsRangeRequests());
- CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == fileInfo.getDate());
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-3
- void testParse_Xep0234_Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-accept'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='851ba2'>\n"
- "<content creator='initiator' name='a-file-offer'>\n"
- "<description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
- "<file>\n"
- "<date>1969-07-21T02:56:15Z</date>\n"
- "<desc>This is a test. If this were a real file...</desc>\n"
- "<media-type>text/plain</media-type>\n"
- "<name>test.txt</name>\n"
- "<range/>\n"
- "<size>1022</size>\n"
- "<hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
- "</file>\n"
- "</description>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " mode='tcp'\n"
- " sid='vj3hs98y'>\n"
- " <candidate cid='ht567dq'\n"
- " host='192.169.1.10'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257636'\n"
- " type='direct'/>\n"
- " <candidate cid='hr65dqyd'\n"
- " host='134.102.201.180'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='16453'\n"
- " priority='7929856'\n"
- " type='assisted'/>\n"
- " <candidate cid='grt654q2'\n"
- " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257606'\n"
- " type='direct'/>\n"
- " </transport>\n"
- " </content>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> contents = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
-
- JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
-
- CPPUNIT_ASSERT(description);
-
- JingleFileTransferFileInfo fileInfo = description->getFileInfo();
- CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), fileInfo.getName());
- CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), fileInfo.getHashes().begin()->first);
- CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(fileInfo.getHashes().begin()->second));
- CPPUNIT_ASSERT(1022 == fileInfo.getSize());
- CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), fileInfo.getDescription());
- CPPUNIT_ASSERT_EQUAL(true, fileInfo.getSupportsRangeRequests());
- CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == fileInfo.getDate());
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-5
- void testParse_Xep0234_Example5() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='transport-info'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " sid='vj3hs98y'>\n"
- " <candidate-used cid='hr65dqyd'/>\n"
- " </transport>\n"
- " </content>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- std::vector<JingleContentPayload::ref> contents = jingle->getContents();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
-
- JingleS5BTransportPayload::ref transport = contents[0]->getTransport<JingleS5BTransportPayload>();
- CPPUNIT_ASSERT(transport);
-
- CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), transport->getSessionID());
- CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), transport->getCandidateUsed());
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-8
- void testParse_Xep0234_Example8() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-info'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <checksum xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
- " <file>\n"
- " <hash xmlns='urn:xmpp:hashes:0' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
- " </file>\n"
- " </checksum>\n"
- "</jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInfo, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- JingleFileTransferHash::ref hash = jingle->getPayload<JingleFileTransferHash>();
- CPPUNIT_ASSERT(hash);
- CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(hash->getFileInfo().getHash("sha-1").get()));
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-10
- void testParse_Xep0234_Example10() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-initiate'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='uj3b2'>\n"
- " <content creator='initiator' name='a-file-request'>\n"
- " <description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
- " <file>\n"
- " <hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
- " <range offset='270336'/>\n"
- " </file>\n"
- " </description>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " mode='tcp'\n"
- " sid='xig361fj'>\n"
- " <candidate cid='ht567dq'\n"
- " host='192.169.1.10'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257636'\n"
- " type='direct'/>\n"
- " <candidate cid='hr65dqyd'\n"
- " host='134.102.201.180'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='16453'\n"
- " priority='7929856'\n"
- " type='assisted'/>\n"
- " <candidate cid='grt654q2'\n"
- " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257606'\n"
- " type='direct'/>\n"
- " </transport>\n"
- " </content>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("uj3b2"), jingle->getSessionID());
-
- JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
- CPPUNIT_ASSERT(content);
-
- JingleFileTransferFileInfo file = content->getDescription<JingleFileTransferDescription>()->getFileInfo();
- CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), file.getHashes().begin()->first);
- CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(file.getHashes().begin()->second));
- CPPUNIT_ASSERT_EQUAL(static_cast<boost::uintmax_t>(270336), file.getRangeOffset());
- CPPUNIT_ASSERT_EQUAL(true, file.getSupportsRangeRequests());
- }
-
- // http://xmpp.org/extensions/xep-0260.html#example-1
- void testParse_Xep0260_Example1() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-initiate'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <description xmlns='urn:xmpp:example'/>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " mode='tcp'\n"
- " sid='vj3hs98y'>\n"
- " <candidate cid='hft54dqy'\n"
- " host='192.168.4.1'\n"
- " jid='romeo@montague.lit/orchard'\n"
- " port='5086'\n"
- " priority='8257636'\n"
- " type='direct'/>\n"
- " <candidate cid='hutr46fe'\n"
- " host='24.24.24.1'\n"
- " jid='romeo@montague.lit/orchard'\n"
- " port='5087'\n"
- " priority='8258636'\n"
- " type='direct'/>\n"
- " </transport>\n"
- " </content>\n"
- "</jingle>\n"
- ));
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
- CPPUNIT_ASSERT(content);
-
- JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
- CPPUNIT_ASSERT(s5bPayload);
-
- CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
- CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
- CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
- CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
- CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), s5bPayload->getCandidates().size());
-
- JingleS5BTransportPayload::Candidate candidate;
- candidate = s5bPayload->getCandidates()[0];
- CPPUNIT_ASSERT_EQUAL(std::string("hft54dqy"), candidate.cid);
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
- CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.168.4.1"), 5086) == candidate.hostPort);
- CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
-
- candidate = s5bPayload->getCandidates()[1];
- CPPUNIT_ASSERT_EQUAL(std::string("hutr46fe"), candidate.cid);
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
- CPPUNIT_ASSERT(HostAddressPort(HostAddress("24.24.24.1"), 5087) == candidate.hostPort);
- CPPUNIT_ASSERT_EQUAL(8258636, candidate.priority);
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
- }
-
- // http://xmpp.org/extensions/xep-0260.html#example-3
- void testParse_Xep0260_Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<jingle xmlns='urn:xmpp:jingle:1'\n"
- " action='session-accept'\n"
- " initiator='romeo@montague.lit/orchard'\n"
- " sid='a73sjjvkla37jfea'>\n"
- " <content creator='initiator' name='ex'>\n"
- " <description xmlns='urn:xmpp:example'/>\n"
- " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
- " dstaddr='1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba'\n"
- " mode='tcp'\n"
- " sid='vj3hs98y'>\n"
- " <candidate cid='ht567dq'\n"
- " host='192.169.1.10'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257636'\n"
- " type='direct'/>\n"
- " <candidate cid='hr65dqyd'\n"
- " host='134.102.201.180'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='16453'\n"
- " priority='7929856'\n"
- " type='assisted'/>\n"
- " <candidate cid='grt654q2'\n"
- " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
- " jid='juliet@capulet.lit/balcony'\n"
- " port='6539'\n"
- " priority='8257606'\n"
- " type='direct'/>\n"
- " </transport>\n"
- " </content>\n"
- "</jingle>\n"
- ));
-
- JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
- CPPUNIT_ASSERT(jingle);
- CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
- CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
-
- JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
- CPPUNIT_ASSERT(content);
-
- JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
- CPPUNIT_ASSERT(s5bPayload);
-
- CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
- CPPUNIT_ASSERT_EQUAL(std::string("1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba"), s5bPayload->getDstAddr());
- CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
- CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
- CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
- CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), s5bPayload->getCandidates().size());
-
- JingleS5BTransportPayload::Candidate candidate;
- candidate = s5bPayload->getCandidates()[0];
- CPPUNIT_ASSERT_EQUAL(std::string("ht567dq"), candidate.cid);
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
- CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.169.1.10"), 6539) == candidate.hostPort);
- CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
-
- candidate = s5bPayload->getCandidates()[1];
- CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), candidate.cid);
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
- CPPUNIT_ASSERT(HostAddressPort(HostAddress("134.102.201.180"), 16453) == candidate.hostPort);
- CPPUNIT_ASSERT_EQUAL(7929856, candidate.priority);
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::AssistedType, candidate.type);
-
- candidate = s5bPayload->getCandidates()[2];
- CPPUNIT_ASSERT_EQUAL(std::string("grt654q2"), candidate.cid);
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
- CPPUNIT_ASSERT(HostAddressPort(HostAddress("2001:638:708:30c9:219:d1ff:fea4:a17d"), 6539) == candidate.hostPort);
- CPPUNIT_ASSERT_EQUAL(8257606, candidate.priority);
- CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
- }
+ CPPUNIT_TEST_SUITE(JingleParserTest);
+ CPPUNIT_TEST(testParse_Xep0166_Example3);
+ CPPUNIT_TEST(testParse_Xep0166_Example8);
+
+ CPPUNIT_TEST(testParse_Xep0261_Example1);
+ CPPUNIT_TEST(testParse_Xep0261_Example3);
+ CPPUNIT_TEST(testParse_Xep0261_Example9);
+ CPPUNIT_TEST(testParse_Xep0261_Example13);
+
+ CPPUNIT_TEST(testParse_Xep0234_Example1);
+ CPPUNIT_TEST(testParse_Xep0234_Example3);
+ CPPUNIT_TEST(testParse_Xep0234_Example5);
+ CPPUNIT_TEST(testParse_Xep0234_Example8);
+ CPPUNIT_TEST(testParse_Xep0234_Example10);
+
+ CPPUNIT_TEST(testParse_Xep0260_Example1);
+ CPPUNIT_TEST(testParse_Xep0260_Example3);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ //http://xmpp.org/extensions/xep-0166.html#example-3
+ void testParse_Xep0166_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason>\n"
+ " <success/>\n"
+ " </reason>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
+ }
+
+ //http://xmpp.org/extensions/xep-0166.html#example-8
+ void testParse_Xep0166_Example8() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason>\n"
+ " <success/>\n"
+ " <text>Sorry, gotta go!</text>\n"
+ " </reason>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
+ CPPUNIT_ASSERT_EQUAL(std::string("Sorry, gotta go!"),
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).text);
+ }
+
+ // IBB Transport Method Examples
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testParse_Xep0261_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='4096'\n"
+ " sid='ch3d9s71'/>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(4096U, *transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testParse_Xep0261_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " responder='juliet@capulet.lit/balcony'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='2048'\n"
+ " sid='ch3d9s71'/>\n"
+ " </content>\n"
+ " </jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), jingle->getResponder());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(2048U, *transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-9
+ void testParse_Xep0261_Example9() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='transport-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='2048'\n"
+ " sid='bt8a71h6'/>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(2048U, *transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("bt8a71h6"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-13
+ void testParse_Xep0261_Example13() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason><success/></reason>\n"
+ " </jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success, jingle->getReason().get_value_or(JinglePayload::Reason()).type);
+
+ }
+
+ // Jingle File Transfer Examples
+
+ // http://xmpp.org/extensions/xep-0234.html#example-1
+ void testParse_Xep0234_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='851ba2'>\n"
+ "<content creator='initiator' name='a-file-offer'>\n"
+ "<description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
+ "<file>\n"
+ "<date>1969-07-21T02:56:15Z</date>\n"
+ "<desc>This is a test. If this were a real file...</desc>\n"
+ "<media-type>text/plain</media-type>\n"
+ "<name>test.txt</name>\n"
+ "<range/>\n"
+ "<size>1022</size>\n"
+ "<hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
+ "</file>\n"
+ "</description>\n"
+ "<transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ "<candidate cid='hft54dqy'\n"
+ " host='192.168.4.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5086'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ "<candidate cid='hutr46fe'\n"
+ " host='24.24.24.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5087'\n"
+ " priority='8258636'\n"
+ " type='direct'/>\n"
+ "</transport>\n"
+ "</content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
+
+ CPPUNIT_ASSERT(description);
+ JingleFileTransferFileInfo fileInfo = description->getFileInfo();
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), fileInfo.getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), fileInfo.getHashes().begin()->first);
+ CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(fileInfo.getHashes().begin()->second));
+ CPPUNIT_ASSERT(1022 == fileInfo.getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), fileInfo.getDescription());
+ CPPUNIT_ASSERT_EQUAL(true, fileInfo.getSupportsRangeRequests());
+ CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == fileInfo.getDate());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-3
+ void testParse_Xep0234_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='851ba2'>\n"
+ "<content creator='initiator' name='a-file-offer'>\n"
+ "<description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
+ "<file>\n"
+ "<date>1969-07-21T02:56:15Z</date>\n"
+ "<desc>This is a test. If this were a real file...</desc>\n"
+ "<media-type>text/plain</media-type>\n"
+ "<name>test.txt</name>\n"
+ "<range/>\n"
+ "<size>1022</size>\n"
+ "<hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
+ "</file>\n"
+ "</description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
+
+ CPPUNIT_ASSERT(description);
+
+ JingleFileTransferFileInfo fileInfo = description->getFileInfo();
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), fileInfo.getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), fileInfo.getHashes().begin()->first);
+ CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(fileInfo.getHashes().begin()->second));
+ CPPUNIT_ASSERT(1022 == fileInfo.getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), fileInfo.getDescription());
+ CPPUNIT_ASSERT_EQUAL(true, fileInfo.getSupportsRangeRequests());
+ CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == fileInfo.getDate());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-5
+ void testParse_Xep0234_Example5() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='transport-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate-used cid='hr65dqyd'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleS5BTransportPayload::ref transport = contents[0]->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(transport);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), transport->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), transport->getCandidateUsed());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-8
+ void testParse_Xep0234_Example8() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <checksum xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
+ " <file>\n"
+ " <hash xmlns='urn:xmpp:hashes:0' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
+ " </file>\n"
+ " </checksum>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleFileTransferHash::ref hash = jingle->getPayload<JingleFileTransferHash>();
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(hash->getFileInfo().getHash("sha-1").get()));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-10
+ void testParse_Xep0234_Example10() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='uj3b2'>\n"
+ " <content creator='initiator' name='a-file-request'>\n"
+ " <description xmlns='urn:xmpp:jingle:apps:file-transfer:4'>\n"
+ " <file>\n"
+ " <hash xmlns='urn:xmpp:hashes:1' algo='sha-1'>VS2nSZMIUsaa5dIUHTdmsQ==</hash>\n"
+ " <range offset='270336'/>\n"
+ " </file>\n"
+ " </description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='xig361fj'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("uj3b2"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ JingleFileTransferFileInfo file = content->getDescription<JingleFileTransferDescription>()->getFileInfo();
+ CPPUNIT_ASSERT_EQUAL(std::string("sha-1"), file.getHashes().begin()->first);
+ CPPUNIT_ASSERT_EQUAL(std::string("VS2nSZMIUsaa5dIUHTdmsQ=="), Base64::encode(file.getHashes().begin()->second));
+ CPPUNIT_ASSERT_EQUAL(static_cast<boost::uintmax_t>(270336), file.getRangeOffset());
+ CPPUNIT_ASSERT_EQUAL(true, file.getSupportsRangeRequests());
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-1
+ void testParse_Xep0260_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='hft54dqy'\n"
+ " host='192.168.4.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5086'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hutr46fe'\n"
+ " host='24.24.24.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5087'\n"
+ " priority='8258636'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(s5bPayload);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), s5bPayload->getCandidates().size());
+
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate = s5bPayload->getCandidates()[0];
+ CPPUNIT_ASSERT_EQUAL(std::string("hft54dqy"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.168.4.1"), 5086) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[1];
+ CPPUNIT_ASSERT_EQUAL(std::string("hutr46fe"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("24.24.24.1"), 5087) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8258636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-3
+ void testParse_Xep0260_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " dstaddr='1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(s5bPayload);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
+ CPPUNIT_ASSERT_EQUAL(std::string("1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba"), s5bPayload->getDstAddr());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), s5bPayload->getCandidates().size());
+
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate = s5bPayload->getCandidates()[0];
+ CPPUNIT_ASSERT_EQUAL(std::string("ht567dq"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.169.1.10"), 6539) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[1];
+ CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("134.102.201.180"), 16453) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(7929856, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::AssistedType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[2];
+ CPPUNIT_ASSERT_EQUAL(std::string("grt654q2"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("2001:638:708:30c9:219:d1ff:fea4:a17d"), 6539) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257606, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(JingleParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp
index dd6263d..b045ca5 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp
@@ -14,46 +14,46 @@ using namespace Swift;
class MAMFinParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MAMFinParserTest);
- CPPUNIT_TEST(testParse_XEP0313_Exmaple1);
- CPPUNIT_TEST(testParse_XEP0313_Exmaple9);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse_XEP0313_Exmaple1() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<fin xmlns='urn:xmpp:mam:0' queryid='f27' />"));
-
- boost::shared_ptr<MAMFin> payload = parser.getPayload<MAMFin>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT_EQUAL(false, payload->isComplete());
- CPPUNIT_ASSERT_EQUAL(true, payload->isStable());
-
- boost::optional<std::string> queryID = payload->getQueryID();
- CPPUNIT_ASSERT(queryID);
- CPPUNIT_ASSERT_EQUAL(std::string("f27"), queryID.get());
- }
-
- void testParse_XEP0313_Exmaple9() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<fin xmlns='urn:xmpp:mam:0' complete='true'>"
- "<set xmlns='http://jabber.org/protocol/rsm'>"
- "<first index='0'>23452-4534-1</first>"
- "<last>390-2342-22</last>"
- "<count>16</count>"
- "</set>"
- "</fin>"));
-
- boost::shared_ptr<MAMFin> payload = parser.getPayload<MAMFin>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT_EQUAL(true, payload->isComplete());
- CPPUNIT_ASSERT_EQUAL(true, payload->isStable());
-
- CPPUNIT_ASSERT(!!payload->getResultSet());
- boost::shared_ptr<ResultSet> resultSet = payload->getResultSet();
- }
+ CPPUNIT_TEST_SUITE(MAMFinParserTest);
+ CPPUNIT_TEST(testParse_XEP0313_Exmaple1);
+ CPPUNIT_TEST(testParse_XEP0313_Exmaple9);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse_XEP0313_Exmaple1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<fin xmlns='urn:xmpp:mam:0' queryid='f27' />"));
+
+ boost::shared_ptr<MAMFin> payload = parser.getPayload<MAMFin>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT_EQUAL(false, payload->isComplete());
+ CPPUNIT_ASSERT_EQUAL(true, payload->isStable());
+
+ boost::optional<std::string> queryID = payload->getQueryID();
+ CPPUNIT_ASSERT(queryID);
+ CPPUNIT_ASSERT_EQUAL(std::string("f27"), queryID.get());
+ }
+
+ void testParse_XEP0313_Exmaple9() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<fin xmlns='urn:xmpp:mam:0' complete='true'>"
+ "<set xmlns='http://jabber.org/protocol/rsm'>"
+ "<first index='0'>23452-4534-1</first>"
+ "<last>390-2342-22</last>"
+ "<count>16</count>"
+ "</set>"
+ "</fin>"));
+
+ boost::shared_ptr<MAMFin> payload = parser.getPayload<MAMFin>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT_EQUAL(true, payload->isComplete());
+ CPPUNIT_ASSERT_EQUAL(true, payload->isStable());
+
+ CPPUNIT_ASSERT(!!payload->getResultSet());
+ boost::shared_ptr<ResultSet> resultSet = payload->getResultSet();
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(MAMFinParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp
index ff89ed1..8bdefc1 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp
@@ -15,108 +15,108 @@ using namespace Swift;
class MAMQueryParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MAMQueryParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_XEP0313_Example3);
- CPPUNIT_TEST(testParse_XEP0313_Example4);
- CPPUNIT_TEST(testParseEmpty);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\" node=\"node1\">"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<field type=\"text-single\" var=\"FORM_TYPE\">"
- "<value>urn:xmpp:mam:0</value>"
- "</field>"
- "<field type=\"text-single\" var=\"start\">"
- "<value>2010-08-07T00:00:00Z</value>"
- "</field>"
- "</x>"
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<max>10</max>"
- "</set>"
- "</query>"));
-
-
- boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getQueryID());
- CPPUNIT_ASSERT_EQUAL(std::string("id0"), *payload->getQueryID());
- CPPUNIT_ASSERT_EQUAL(std::string("node1"), *payload->getNode());
-
- CPPUNIT_ASSERT(payload->getForm());
- boost::shared_ptr<FormField> fieldType = payload->getForm()->getField("FORM_TYPE");
- CPPUNIT_ASSERT(fieldType);
- CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), fieldType->getTextSingleValue());
- boost::shared_ptr<FormField> fieldStart = payload->getForm()->getField("start");
- CPPUNIT_ASSERT(fieldStart);
- CPPUNIT_ASSERT_EQUAL(std::string("2010-08-07T00:00:00Z"), fieldStart->getTextSingleValue());
-
- CPPUNIT_ASSERT(payload->getResultSet());
- boost::shared_ptr<ResultSet> resultSet = payload->getResultSet();
- CPPUNIT_ASSERT(resultSet->getMaxItems());
- CPPUNIT_ASSERT_EQUAL(*resultSet->getMaxItems(), 10);
- }
-
- void testParse_XEP0313_Example3() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='urn:xmpp:mam:0'>"
- "<x xmlns='jabber:x:data'>"
- "<field var='FORM_TYPE'>"
- "<value>urn:xmpp:mam:0</value>"
- "</field>"
- "<field var='with'>"
- "<value>juliet@capulet.lit</value>"
- "</field>"
- "</x>"
- "</query>"));
-
- boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
- CPPUNIT_ASSERT(!!payload && !!payload->getForm() && !!payload->getForm()->getField("FORM_TYPE") && !!payload->getForm()->getField("with"));
- CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), payload->getForm()->getField("FORM_TYPE")->getTextSingleValue());
- CPPUNIT_ASSERT_EQUAL(std::string("juliet@capulet.lit"), payload->getForm()->getField("with")->getTextSingleValue());
- }
-
- void testParse_XEP0313_Example4() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='urn:xmpp:mam:0'>"
- "<x xmlns='jabber:x:data'>"
- "<field var='FORM_TYPE'>"
- "<value>urn:xmpp:mam:0</value>"
- "</field>"
- "<field var='start'>"
- "<value>2010-06-07T00:00:00Z</value>"
- "</field>"
- "<field var='end'>"
- "<value>2010-07-07T13:23:54Z</value>"
- "</field>"
- "</x>"
- "</query>"));
- boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
- CPPUNIT_ASSERT(!!payload && !!payload->getForm() && !!payload->getForm()->getField("FORM_TYPE") && !!payload->getForm()->getField("start") && !!payload->getForm()->getField("start"));
- CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), payload->getForm()->getField("FORM_TYPE")->getTextSingleValue());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-06-07T00:00:00Z"), payload->getForm()->getField("start")->getTextSingleValue());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-07-07T13:23:54Z"), payload->getForm()->getField("end")->getTextSingleValue());
- }
-
- void testParseEmpty() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\">"
- "</query>"));
-
- boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getQueryID());
- CPPUNIT_ASSERT_EQUAL(std::string("id0"), *payload->getQueryID());
- CPPUNIT_ASSERT(!payload->getForm());
- CPPUNIT_ASSERT(!payload->getResultSet());
- }
+ CPPUNIT_TEST_SUITE(MAMQueryParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_XEP0313_Example3);
+ CPPUNIT_TEST(testParse_XEP0313_Example4);
+ CPPUNIT_TEST(testParseEmpty);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\" node=\"node1\">"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<field type=\"text-single\" var=\"FORM_TYPE\">"
+ "<value>urn:xmpp:mam:0</value>"
+ "</field>"
+ "<field type=\"text-single\" var=\"start\">"
+ "<value>2010-08-07T00:00:00Z</value>"
+ "</field>"
+ "</x>"
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<max>10</max>"
+ "</set>"
+ "</query>"));
+
+
+ boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getQueryID());
+ CPPUNIT_ASSERT_EQUAL(std::string("id0"), *payload->getQueryID());
+ CPPUNIT_ASSERT_EQUAL(std::string("node1"), *payload->getNode());
+
+ CPPUNIT_ASSERT(payload->getForm());
+ boost::shared_ptr<FormField> fieldType = payload->getForm()->getField("FORM_TYPE");
+ CPPUNIT_ASSERT(fieldType);
+ CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), fieldType->getTextSingleValue());
+ boost::shared_ptr<FormField> fieldStart = payload->getForm()->getField("start");
+ CPPUNIT_ASSERT(fieldStart);
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-08-07T00:00:00Z"), fieldStart->getTextSingleValue());
+
+ CPPUNIT_ASSERT(payload->getResultSet());
+ boost::shared_ptr<ResultSet> resultSet = payload->getResultSet();
+ CPPUNIT_ASSERT(resultSet->getMaxItems());
+ CPPUNIT_ASSERT_EQUAL(*resultSet->getMaxItems(), 10);
+ }
+
+ void testParse_XEP0313_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='urn:xmpp:mam:0'>"
+ "<x xmlns='jabber:x:data'>"
+ "<field var='FORM_TYPE'>"
+ "<value>urn:xmpp:mam:0</value>"
+ "</field>"
+ "<field var='with'>"
+ "<value>juliet@capulet.lit</value>"
+ "</field>"
+ "</x>"
+ "</query>"));
+
+ boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
+ CPPUNIT_ASSERT(!!payload && !!payload->getForm() && !!payload->getForm()->getField("FORM_TYPE") && !!payload->getForm()->getField("with"));
+ CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), payload->getForm()->getField("FORM_TYPE")->getTextSingleValue());
+ CPPUNIT_ASSERT_EQUAL(std::string("juliet@capulet.lit"), payload->getForm()->getField("with")->getTextSingleValue());
+ }
+
+ void testParse_XEP0313_Example4() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='urn:xmpp:mam:0'>"
+ "<x xmlns='jabber:x:data'>"
+ "<field var='FORM_TYPE'>"
+ "<value>urn:xmpp:mam:0</value>"
+ "</field>"
+ "<field var='start'>"
+ "<value>2010-06-07T00:00:00Z</value>"
+ "</field>"
+ "<field var='end'>"
+ "<value>2010-07-07T13:23:54Z</value>"
+ "</field>"
+ "</x>"
+ "</query>"));
+ boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
+ CPPUNIT_ASSERT(!!payload && !!payload->getForm() && !!payload->getForm()->getField("FORM_TYPE") && !!payload->getForm()->getField("start") && !!payload->getForm()->getField("start"));
+ CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), payload->getForm()->getField("FORM_TYPE")->getTextSingleValue());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-06-07T00:00:00Z"), payload->getForm()->getField("start")->getTextSingleValue());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-07T13:23:54Z"), payload->getForm()->getField("end")->getTextSingleValue());
+ }
+
+ void testParseEmpty() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\">"
+ "</query>"));
+
+ boost::shared_ptr<MAMQuery> payload = parser.getPayload<MAMQuery>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getQueryID());
+ CPPUNIT_ASSERT_EQUAL(std::string("id0"), *payload->getQueryID());
+ CPPUNIT_ASSERT(!payload->getForm());
+ CPPUNIT_ASSERT(!payload->getResultSet());
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp
index a4c2f08..7393630 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp
@@ -18,41 +18,41 @@ using namespace Swift;
class MAMResultParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MAMResultParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<result id=\"28482-98726-73623\" queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<message xmlns=\"jabber:client\" from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"
- "</result>"));
-
- boost::shared_ptr<MAMResult> payload = parser.getPayload<MAMResult>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT_EQUAL(std::string("28482-98726-73623"), payload->getID());
- CPPUNIT_ASSERT(payload->getQueryID());
- CPPUNIT_ASSERT_EQUAL(std::string("f27"), *payload->getQueryID());
-
- boost::shared_ptr<Forwarded> forwarded = payload->getPayload();
- CPPUNIT_ASSERT(forwarded->getDelay());
- CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(forwarded->getDelay()->getStamp()));
-
- boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
- CPPUNIT_ASSERT(!!message);
- const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
- CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
- CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
- }
+ CPPUNIT_TEST_SUITE(MAMResultParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<result id=\"28482-98726-73623\" queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<message xmlns=\"jabber:client\" from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"
+ "</result>"));
+
+ boost::shared_ptr<MAMResult> payload = parser.getPayload<MAMResult>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("28482-98726-73623"), payload->getID());
+ CPPUNIT_ASSERT(payload->getQueryID());
+ CPPUNIT_ASSERT_EQUAL(std::string("f27"), *payload->getQueryID());
+
+ boost::shared_ptr<Forwarded> forwarded = payload->getPayload();
+ CPPUNIT_ASSERT(forwarded->getDelay());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(forwarded->getDelay()->getStamp()));
+
+ boost::shared_ptr<Message> message = boost::dynamic_pointer_cast<Message>(forwarded->getStanza());
+ CPPUNIT_ASSERT(!!message);
+ const std::string expectedBody = "Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.";
+ CPPUNIT_ASSERT_EQUAL(expectedBody, message->getBody().get());
+ CPPUNIT_ASSERT_EQUAL(Message::Chat, message->getType());
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), message->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), message->getFrom());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(MAMResultParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp
index f49ca19..495aefe 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp
@@ -14,25 +14,25 @@ using namespace Swift;
class MUCAdminPayloadParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MUCAdminPayloadParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(MUCAdminPayloadParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
- public:
- MUCAdminPayloadParserTest() {}
+ public:
+ MUCAdminPayloadParserTest() {}
- void testParse() {
- PayloadsParserTester parser;
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<query xmlns=\"http://jabber.org/protocol/muc#admin\"><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item></query>"));
+ CPPUNIT_ASSERT(parser.parse("<query xmlns=\"http://jabber.org/protocol/muc#admin\"><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item></query>"));
- MUCAdminPayload::ref payload = boost::dynamic_pointer_cast<MUCAdminPayload>(parser.getPayload());
- 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());
- }
+ MUCAdminPayload::ref payload = boost::dynamic_pointer_cast<MUCAdminPayload>(parser.getPayload());
+ 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_TEST_SUITE_REGISTRATION(MUCAdminPayloadParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
index 89c51d8..a8cf246 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
@@ -16,78 +16,78 @@ 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 = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
-
- foreach (MUCUserPayload::StatusCode 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 = boost::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 = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
- CPPUNIT_ASSERT(payload);
- MUCDestroyPayload::ref destroy = boost::dynamic_pointer_cast<MUCDestroyPayload>(payload->getPayload());
- CPPUNIT_ASSERT(destroy);
- CPPUNIT_ASSERT_EQUAL(std::string("bert"), destroy->getReason());
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit"), destroy->getNewVenue());
- }
-
- void testParseInvite() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><invite from='crone1@shakespeare.lit/desktop' to='alice@wonderland.lit/xxx'> <reason>Hey Hecate, this is the place for all good witches!</reason> </invite> <password>cauldronburn</password></x>"));
-
- MUCUserPayload::ref payload = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(payload->getInvite());
- CPPUNIT_ASSERT(payload->getPassword());
- CPPUNIT_ASSERT_EQUAL(std::string("cauldronburn"), *payload->getPassword());
- MUCUserPayload::Invite invite = *payload->getInvite();
- CPPUNIT_ASSERT_EQUAL(std::string("Hey Hecate, this is the place for all good witches!"), invite.reason);
- CPPUNIT_ASSERT_EQUAL(JID("crone1@shakespeare.lit/desktop"), invite.from);
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/xxx"), invite.to);
- }
+ 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 = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+
+ foreach (MUCUserPayload::StatusCode 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 = boost::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 = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ MUCDestroyPayload::ref destroy = boost::dynamic_pointer_cast<MUCDestroyPayload>(payload->getPayload());
+ CPPUNIT_ASSERT(destroy);
+ CPPUNIT_ASSERT_EQUAL(std::string("bert"), destroy->getReason());
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit"), destroy->getNewVenue());
+ }
+
+ void testParseInvite() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><invite from='crone1@shakespeare.lit/desktop' to='alice@wonderland.lit/xxx'> <reason>Hey Hecate, this is the place for all good witches!</reason> </invite> <password>cauldronburn</password></x>"));
+
+ MUCUserPayload::ref payload = boost::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(payload->getInvite());
+ CPPUNIT_ASSERT(payload->getPassword());
+ CPPUNIT_ASSERT_EQUAL(std::string("cauldronburn"), *payload->getPassword());
+ MUCUserPayload::Invite invite = *payload->getInvite();
+ CPPUNIT_ASSERT_EQUAL(std::string("Hey Hecate, this is the place for all good witches!"), invite.reason);
+ CPPUNIT_ASSERT_EQUAL(JID("crone1@shakespeare.lit/desktop"), invite.from);
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/xxx"), invite.to);
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h b/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h
index bb6450f..a85a692 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h
@@ -10,5 +10,5 @@
#include <Swiften/Parser/UnitTest/ParserTester.h>
namespace Swift {
- typedef ParserTester<PayloadParser> PayloadParserTester;
+ typedef ParserTester<PayloadParser> PayloadParserTester;
}
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h b/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
index ca33d48..8e871b2 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
@@ -14,53 +14,53 @@
#include <Swiften/Parser/XMLParserClient.h>
namespace Swift {
- class PayloadsParserTester : public XMLParserClient {
- public:
- PayloadsParserTester() : level(0) {
- xmlParser = PlatformXMLParserFactory().createXMLParser(this);
- }
+ class PayloadsParserTester : public XMLParserClient {
+ public:
+ PayloadsParserTester() : level(0) {
+ xmlParser = PlatformXMLParserFactory().createXMLParser(this);
+ }
- ~PayloadsParserTester() {
- delete xmlParser;
- }
+ ~PayloadsParserTester() {
+ delete xmlParser;
+ }
- bool parse(const std::string& data) {
- return xmlParser->parse(data);
- }
+ bool parse(const std::string& data) {
+ return xmlParser->parse(data);
+ }
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (level == 0) {
- assert(!payloadParser.get());
- PayloadParserFactory* payloadParserFactory = factories.getPayloadParserFactory(element, ns, attributes);
- assert(payloadParserFactory);
- payloadParser.reset(payloadParserFactory->createPayloadParser());
- }
- payloadParser->handleStartElement(element, ns, attributes);
- level++;
- }
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level == 0) {
+ assert(!payloadParser.get());
+ PayloadParserFactory* payloadParserFactory = factories.getPayloadParserFactory(element, ns, attributes);
+ assert(payloadParserFactory);
+ payloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ payloadParser->handleStartElement(element, ns, attributes);
+ level++;
+ }
- virtual void handleEndElement(const std::string& element, const std::string& ns) {
- level--;
- payloadParser->handleEndElement(element, ns);
- }
+ virtual void handleEndElement(const std::string& element, const std::string& ns) {
+ level--;
+ payloadParser->handleEndElement(element, ns);
+ }
- virtual void handleCharacterData(const std::string& data) {
- payloadParser->handleCharacterData(data);
- }
+ virtual void handleCharacterData(const std::string& data) {
+ payloadParser->handleCharacterData(data);
+ }
- boost::shared_ptr<Payload> getPayload() const {
- return payloadParser->getPayload();
- }
+ boost::shared_ptr<Payload> getPayload() const {
+ return payloadParser->getPayload();
+ }
- template<typename T>
- boost::shared_ptr<T> getPayload() const {
- return boost::dynamic_pointer_cast<T>(payloadParser->getPayload());
- }
+ template<typename T>
+ boost::shared_ptr<T> getPayload() const {
+ return boost::dynamic_pointer_cast<T>(payloadParser->getPayload());
+ }
- private:
- XMLParser* xmlParser;
- FullPayloadParserFactoryCollection factories;
- boost::shared_ptr<PayloadParser> payloadParser;
- int level;
- };
+ private:
+ XMLParser* xmlParser;
+ FullPayloadParserFactoryCollection factories;
+ boost::shared_ptr<PayloadParser> payloadParser;
+ int level;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
index 285ac56..e724090 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
@@ -13,29 +13,29 @@
using namespace Swift;
class PriorityParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PriorityParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Invalid);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PriorityParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Invalid);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse() {
- PayloadsParserTester parser;
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<priority>-120</priority>"));
+ CPPUNIT_ASSERT(parser.parse("<priority>-120</priority>"));
- boost::shared_ptr<Priority> payload = boost::dynamic_pointer_cast<Priority>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(-120, payload->getPriority());
- }
+ boost::shared_ptr<Priority> payload = boost::dynamic_pointer_cast<Priority>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(-120, payload->getPriority());
+ }
- void testParse_Invalid() {
- PayloadsParserTester parser;
+ void testParse_Invalid() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<priority>invalid</priority>"));
+ CPPUNIT_ASSERT(parser.parse("<priority>invalid</priority>"));
- boost::shared_ptr<Priority> payload = boost::dynamic_pointer_cast<Priority>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(0, payload->getPriority());
- }
+ boost::shared_ptr<Priority> payload = boost::dynamic_pointer_cast<Priority>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(0, payload->getPriority());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PriorityParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp
index f38a0bd..2975485 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp
@@ -15,81 +15,81 @@
using namespace Swift;
class PrivateStorageParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PrivateStorageParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_NoPayload);
- CPPUNIT_TEST(testParse_MultiplePayloads);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- PrivateStorageParserTest() {}
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:private'>"
- "<storage xmlns='storage:bookmarks'>"
- "<conference name='Swift' jid='swift@rooms.swift.im'>"
- "<nick>Alice</nick>"
- "</conference>"
- "</storage>"
- "</query>"));
-
- boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
- CPPUNIT_ASSERT(payload);
- boost::shared_ptr<Storage> storage = boost::dynamic_pointer_cast<Storage>(payload->getPayload());
- CPPUNIT_ASSERT(storage);
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), storage->getRooms()[0].nick);
- CPPUNIT_ASSERT_EQUAL(JID("swift@rooms.swift.im"), storage->getRooms()[0].jid);
- }
-
- void testParse_NoPayload() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:private'/>"));
-
- boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(!payload->getPayload());
- }
-
- void testParse_MultiplePayloads() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:private'>"
- "<storage xmlns='storage:bookmarks'>"
- "<conference name='Swift' jid='swift@rooms.swift.im'>"
- "<nick>Alice</nick>"
- "</conference>"
- "</storage>"
- "<storage xmlns='storage:bookmarks'>"
- "<conference name='Swift' jid='swift@rooms.swift.im'>"
- "<nick>Rabbit</nick>"
- "</conference>"
- "</storage>"
- "</query>"));
-
- boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
- CPPUNIT_ASSERT(payload);
- boost::shared_ptr<Storage> storage = boost::dynamic_pointer_cast<Storage>(payload->getPayload());
- CPPUNIT_ASSERT(storage);
- CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), storage->getRooms()[0].nick);
- }
-
- void testParse_UnsupportedPayload() {
- PayloadParserFactoryCollection factories;
- PrivateStorageParser testling(&factories);
- PayloadParserTester parser(&testling);
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:private'>"
- "<foo>Bar</foo>"
- "</query>"));
-
- CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<PrivateStorage>(testling.getPayload())->getPayload());
- }
+ CPPUNIT_TEST_SUITE(PrivateStorageParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_NoPayload);
+ CPPUNIT_TEST(testParse_MultiplePayloads);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ PrivateStorageParserTest() {}
+
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:private'>"
+ "<storage xmlns='storage:bookmarks'>"
+ "<conference name='Swift' jid='swift@rooms.swift.im'>"
+ "<nick>Alice</nick>"
+ "</conference>"
+ "</storage>"
+ "</query>"));
+
+ boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ boost::shared_ptr<Storage> storage = boost::dynamic_pointer_cast<Storage>(payload->getPayload());
+ CPPUNIT_ASSERT(storage);
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), storage->getRooms()[0].nick);
+ CPPUNIT_ASSERT_EQUAL(JID("swift@rooms.swift.im"), storage->getRooms()[0].jid);
+ }
+
+ void testParse_NoPayload() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:private'/>"));
+
+ boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(!payload->getPayload());
+ }
+
+ void testParse_MultiplePayloads() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:private'>"
+ "<storage xmlns='storage:bookmarks'>"
+ "<conference name='Swift' jid='swift@rooms.swift.im'>"
+ "<nick>Alice</nick>"
+ "</conference>"
+ "</storage>"
+ "<storage xmlns='storage:bookmarks'>"
+ "<conference name='Swift' jid='swift@rooms.swift.im'>"
+ "<nick>Rabbit</nick>"
+ "</conference>"
+ "</storage>"
+ "</query>"));
+
+ boost::shared_ptr<PrivateStorage> payload = boost::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ boost::shared_ptr<Storage> storage = boost::dynamic_pointer_cast<Storage>(payload->getPayload());
+ CPPUNIT_ASSERT(storage);
+ CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), storage->getRooms()[0].nick);
+ }
+
+ void testParse_UnsupportedPayload() {
+ PayloadParserFactoryCollection factories;
+ PrivateStorageParser testling(&factories);
+ PayloadParserTester parser(&testling);
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:private'>"
+ "<foo>Bar</foo>"
+ "</query>"));
+
+ CPPUNIT_ASSERT(!boost::dynamic_pointer_cast<PrivateStorage>(testling.getPayload())->getPayload());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PrivateStorageParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp
index 800f48c..2deca6e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp
@@ -14,27 +14,27 @@ using namespace Swift;
class RawXMLPayloadParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(RawXMLPayloadParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- RawXMLPayloadParserTest() {}
-
- void testParse() {
- RawXMLPayloadParser testling;
- PayloadParserTester parser(&testling);
-
- std::string xml =
- "<foo foo-attr=\"foo-val\" xmlns=\"ns:foo\">"
- "<bar bar-attr=\"bar-val\" xmlns=\"ns:bar\"/>"
- "<baz baz-attr=\"baz-val\" xmlns=\"ns:baz\"/>"
- "</foo>";
- CPPUNIT_ASSERT(parser.parse(xml));
-
- RawXMLPayload* payload = dynamic_cast<RawXMLPayload*>(testling.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(xml, payload->getRawXML());
- }
+ CPPUNIT_TEST_SUITE(RawXMLPayloadParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ RawXMLPayloadParserTest() {}
+
+ void testParse() {
+ RawXMLPayloadParser testling;
+ PayloadParserTester parser(&testling);
+
+ std::string xml =
+ "<foo foo-attr=\"foo-val\" xmlns=\"ns:foo\">"
+ "<bar bar-attr=\"bar-val\" xmlns=\"ns:bar\"/>"
+ "<baz baz-attr=\"baz-val\" xmlns=\"ns:baz\"/>"
+ "</foo>";
+ CPPUNIT_ASSERT(parser.parse(xml));
+
+ RawXMLPayload* payload = dynamic_cast<RawXMLPayload*>(testling.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(xml, payload->getRawXML());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(RawXMLPayloadParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp
index c3f410f..3e42788 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp
@@ -13,24 +13,24 @@
using namespace Swift;
class ReplaceParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ReplaceParserTest);
- CPPUNIT_TEST(testParseTrivial);
- CPPUNIT_TEST(testParseChild);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ReplaceParserTest);
+ CPPUNIT_TEST(testParseTrivial);
+ CPPUNIT_TEST(testParseChild);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParseTrivial() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<replace id='bad1' xmlns='http://swift.im/protocol/replace'/>"));
- Replace::ref payload = boost::dynamic_pointer_cast <Replace>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(std::string("bad1"), payload->getID());
- }
- void testParseChild() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<replace id='bad1' xmlns='http://swift.im/protocol/replace' ><child xmlns='blah' id=\"hi\"/></replace>"));
- Replace::ref payload = boost::dynamic_pointer_cast <Replace>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(std::string("bad1"), payload->getID());
- }
+ public:
+ void testParseTrivial() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<replace id='bad1' xmlns='http://swift.im/protocol/replace'/>"));
+ Replace::ref payload = boost::dynamic_pointer_cast <Replace>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(std::string("bad1"), payload->getID());
+ }
+ void testParseChild() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<replace id='bad1' xmlns='http://swift.im/protocol/replace' ><child xmlns='blah' id=\"hi\"/></replace>"));
+ Replace::ref payload = boost::dynamic_pointer_cast <Replace>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(std::string("bad1"), payload->getID());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ReplaceParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp
index 4c2b377..5c786c5 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp
@@ -14,31 +14,31 @@ using namespace Swift;
class ResourceBindParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ResourceBindParserTest);
- CPPUNIT_TEST(testParse_JID);
- CPPUNIT_TEST(testParse_Resource);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ResourceBindParserTest);
+ CPPUNIT_TEST(testParse_JID);
+ CPPUNIT_TEST(testParse_Resource);
+ CPPUNIT_TEST_SUITE_END();
- public:
- ResourceBindParserTest() {}
+ public:
+ ResourceBindParserTest() {}
- void testParse_JID() {
- PayloadsParserTester parser;
+ void testParse_JID() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><jid>somenode@example.com/someresource</jid></bind>"));
+ CPPUNIT_ASSERT(parser.parse("<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><jid>somenode@example.com/someresource</jid></bind>"));
- ResourceBind* payload = dynamic_cast<ResourceBind*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(JID("somenode@example.com/someresource"), payload->getJID());
- }
+ ResourceBind* payload = dynamic_cast<ResourceBind*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(JID("somenode@example.com/someresource"), payload->getJID());
+ }
- void testParse_Resource() {
- PayloadsParserTester parser;
+ void testParse_Resource() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>someresource</resource></bind>"));
+ CPPUNIT_ASSERT(parser.parse("<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>someresource</resource></bind>"));
- ResourceBind* payload = dynamic_cast<ResourceBind*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("someresource"), payload->getResource());
- }
+ ResourceBind* payload = dynamic_cast<ResourceBind*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("someresource"), payload->getResource());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResourceBindParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp
index e01a811..7924e05 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp
@@ -14,58 +14,58 @@ using namespace Swift;
class ResultSetParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ResultSetParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParseFirstNoIndex);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ResultSetParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParseFirstNoIndex);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<max>100</max>"
- "<count>800</count>"
- "<index>0</index>"
- "<first index=\"123\">stpeter@jabber.org</first>"
- "<last>peterpan@neverland.lit</last>"
- "<before>decaf-badba-dbad1</before>"
- "<after>09af3-cc343-b409f</after>"
- "</set>"));
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<max>100</max>"
+ "<count>800</count>"
+ "<index>0</index>"
+ "<first index=\"123\">stpeter@jabber.org</first>"
+ "<last>peterpan@neverland.lit</last>"
+ "<before>decaf-badba-dbad1</before>"
+ "<after>09af3-cc343-b409f</after>"
+ "</set>"));
- boost::shared_ptr<ResultSet> payload = parser.getPayload<ResultSet>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getMaxItems());
- CPPUNIT_ASSERT_EQUAL(100, *payload->getMaxItems());
- CPPUNIT_ASSERT(payload->getCount());
- CPPUNIT_ASSERT_EQUAL(800, *payload->getCount());
- CPPUNIT_ASSERT(payload->getIndex());
- CPPUNIT_ASSERT_EQUAL(0, *payload->getIndex());
- CPPUNIT_ASSERT(payload->getFirstID());
- CPPUNIT_ASSERT_EQUAL(std::string("stpeter@jabber.org"), *payload->getFirstID());
- CPPUNIT_ASSERT(payload->getFirstIDIndex());
- CPPUNIT_ASSERT_EQUAL(123, *payload->getFirstIDIndex());
- CPPUNIT_ASSERT(payload->getLastID());
- CPPUNIT_ASSERT_EQUAL(std::string("peterpan@neverland.lit"), *payload->getLastID());
- CPPUNIT_ASSERT(payload->getBefore());
- CPPUNIT_ASSERT_EQUAL(std::string("decaf-badba-dbad1"), *payload->getBefore());
- CPPUNIT_ASSERT(payload->getAfter());
- CPPUNIT_ASSERT_EQUAL(std::string("09af3-cc343-b409f"), *payload->getAfter());
- }
+ boost::shared_ptr<ResultSet> payload = parser.getPayload<ResultSet>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getMaxItems());
+ CPPUNIT_ASSERT_EQUAL(100, *payload->getMaxItems());
+ CPPUNIT_ASSERT(payload->getCount());
+ CPPUNIT_ASSERT_EQUAL(800, *payload->getCount());
+ CPPUNIT_ASSERT(payload->getIndex());
+ CPPUNIT_ASSERT_EQUAL(0, *payload->getIndex());
+ CPPUNIT_ASSERT(payload->getFirstID());
+ CPPUNIT_ASSERT_EQUAL(std::string("stpeter@jabber.org"), *payload->getFirstID());
+ CPPUNIT_ASSERT(payload->getFirstIDIndex());
+ CPPUNIT_ASSERT_EQUAL(123, *payload->getFirstIDIndex());
+ CPPUNIT_ASSERT(payload->getLastID());
+ CPPUNIT_ASSERT_EQUAL(std::string("peterpan@neverland.lit"), *payload->getLastID());
+ CPPUNIT_ASSERT(payload->getBefore());
+ CPPUNIT_ASSERT_EQUAL(std::string("decaf-badba-dbad1"), *payload->getBefore());
+ CPPUNIT_ASSERT(payload->getAfter());
+ CPPUNIT_ASSERT_EQUAL(std::string("09af3-cc343-b409f"), *payload->getAfter());
+ }
- void testParseFirstNoIndex() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<first>stpeter@jabber.org</first>"
- "</set>"));
+ void testParseFirstNoIndex() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<first>stpeter@jabber.org</first>"
+ "</set>"));
- boost::shared_ptr<ResultSet> payload = parser.getPayload<ResultSet>();
- CPPUNIT_ASSERT(!!payload);
- CPPUNIT_ASSERT(payload->getFirstID());
- CPPUNIT_ASSERT_EQUAL(std::string("stpeter@jabber.org"), *payload->getFirstID());
- CPPUNIT_ASSERT(!payload->getFirstIDIndex());
- }
+ boost::shared_ptr<ResultSet> payload = parser.getPayload<ResultSet>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(payload->getFirstID());
+ CPPUNIT_ASSERT_EQUAL(std::string("stpeter@jabber.org"), *payload->getFirstID());
+ CPPUNIT_ASSERT(!payload->getFirstIDIndex());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResultSetParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp
index 1a18d6d..a94a6fe 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp
@@ -14,39 +14,39 @@ using namespace Swift;
class RosterItemExchangeParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(RosterItemExchangeParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<x xmlns=\"http://jabber.org/protocol/rosterx\">"
- "<item action=\"add\" jid=\"foo@bar.com\" name=\"Foo @ Bar\">"
- "<group>Group 1</group>"
- "<group>Group 2</group>"
- "</item>"
- "<item action=\"modify\" jid=\"baz@blo.com\" name=\"Baz\"/>"
- "</x>"));
-
- RosterItemExchangePayload* payload = dynamic_cast<RosterItemExchangePayload*>(parser.getPayload().get());
- const RosterItemExchangePayload::RosterItemExchangePayloadItems& items = payload->getItems();
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), items[0].getJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Foo @ Bar"), items[0].getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemExchangePayload::Item::Add, items[0].getAction());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items[0].getGroups().size());
- CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
-
- CPPUNIT_ASSERT_EQUAL(JID("baz@blo.com"), items[1].getJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Baz"), items[1].getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemExchangePayload::Item::Modify, items[1].getAction());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), items[1].getGroups().size());
- }
+ CPPUNIT_TEST_SUITE(RosterItemExchangeParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<x xmlns=\"http://jabber.org/protocol/rosterx\">"
+ "<item action=\"add\" jid=\"foo@bar.com\" name=\"Foo @ Bar\">"
+ "<group>Group 1</group>"
+ "<group>Group 2</group>"
+ "</item>"
+ "<item action=\"modify\" jid=\"baz@blo.com\" name=\"Baz\"/>"
+ "</x>"));
+
+ RosterItemExchangePayload* payload = dynamic_cast<RosterItemExchangePayload*>(parser.getPayload().get());
+ const RosterItemExchangePayload::RosterItemExchangePayloadItems& items = payload->getItems();
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), items[0].getJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo @ Bar"), items[0].getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemExchangePayload::Item::Add, items[0].getAction());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items[0].getGroups().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
+
+ CPPUNIT_ASSERT_EQUAL(JID("baz@blo.com"), items[1].getJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Baz"), items[1].getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemExchangePayload::Item::Modify, items[1].getAction());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), items[1].getGroups().size());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterItemExchangeParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/RosterParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/RosterParserTest.cpp
index d1e1b45..261dad2 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/RosterParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/RosterParserTest.cpp
@@ -14,88 +14,88 @@ using namespace Swift;
class RosterParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(RosterParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_ItemWithUnknownContent);
- CPPUNIT_TEST(testParse_WithVersion);
- CPPUNIT_TEST(testParse_WithEmptyVersion);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:roster'>"
- " <item jid='foo@bar.com' name='Foo @ Bar' subscription='from' ask='subscribe'>"
- " <group>Group 1</group>"
- " <group>Group 2</group>"
- " </item>"
- " <item jid='baz@blo.com' name='Baz'/>"
- "</query>"));
-
- RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
-
- CPPUNIT_ASSERT(!payload->getVersion());
- const RosterPayload::RosterItemPayloads& items = payload->getItems();
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), items[0].getJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Foo @ Bar"), items[0].getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::From, items[0].getSubscription());
- CPPUNIT_ASSERT(items[0].getSubscriptionRequested());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items[0].getGroups().size());
- CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
-
- CPPUNIT_ASSERT_EQUAL(JID("baz@blo.com"), items[1].getJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Baz"), items[1].getName());
- CPPUNIT_ASSERT_EQUAL(RosterItemPayload::None, items[1].getSubscription());
- CPPUNIT_ASSERT(!items[1].getSubscriptionRequested());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), items[1].getGroups().size());
- }
-
- void testParse_ItemWithUnknownContent() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:roster'>"
- " <item jid='foo@bar.com' name='Foo @ Bar' subscription='from' ask='subscribe'>"
- " <group>Group 1</group>"
- " <foo xmlns=\"http://example.com\"><bar>Baz</bar></foo>"
- " <group>Group 2</group>"
- " <baz><fum>foo</fum></baz>"
- " </item>"
- "</query>"));
-
- RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
- const RosterPayload::RosterItemPayloads& items = payload->getItems();
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), items.size());
- CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
- "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"
- ), items[0].getUnknownContent());
- }
-
- void testParse_WithVersion() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:roster' ver='ver10'/>"));
-
- RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("ver10"), *payload->getVersion());
- }
-
- void testParse_WithEmptyVersion() {
- PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:roster' ver=''/>"));
-
- RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string(""), *payload->getVersion());
- }
+ CPPUNIT_TEST_SUITE(RosterParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_ItemWithUnknownContent);
+ CPPUNIT_TEST(testParse_WithVersion);
+ CPPUNIT_TEST(testParse_WithEmptyVersion);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:roster'>"
+ " <item jid='foo@bar.com' name='Foo @ Bar' subscription='from' ask='subscribe'>"
+ " <group>Group 1</group>"
+ " <group>Group 2</group>"
+ " </item>"
+ " <item jid='baz@blo.com' name='Baz'/>"
+ "</query>"));
+
+ RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
+
+ CPPUNIT_ASSERT(!payload->getVersion());
+ const RosterPayload::RosterItemPayloads& items = payload->getItems();
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), items[0].getJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo @ Bar"), items[0].getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::From, items[0].getSubscription());
+ CPPUNIT_ASSERT(items[0].getSubscriptionRequested());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items[0].getGroups().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
+
+ CPPUNIT_ASSERT_EQUAL(JID("baz@blo.com"), items[1].getJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Baz"), items[1].getName());
+ CPPUNIT_ASSERT_EQUAL(RosterItemPayload::None, items[1].getSubscription());
+ CPPUNIT_ASSERT(!items[1].getSubscriptionRequested());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), items[1].getGroups().size());
+ }
+
+ void testParse_ItemWithUnknownContent() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:roster'>"
+ " <item jid='foo@bar.com' name='Foo @ Bar' subscription='from' ask='subscribe'>"
+ " <group>Group 1</group>"
+ " <foo xmlns=\"http://example.com\"><bar>Baz</bar></foo>"
+ " <group>Group 2</group>"
+ " <baz><fum>foo</fum></baz>"
+ " </item>"
+ "</query>"));
+
+ RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
+ const RosterPayload::RosterItemPayloads& items = payload->getItems();
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), items.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 1"), items[0].getGroups()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("Group 2"), items[0].getGroups()[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
+ "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"
+ ), items[0].getUnknownContent());
+ }
+
+ void testParse_WithVersion() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:roster' ver='ver10'/>"));
+
+ RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("ver10"), *payload->getVersion());
+ }
+
+ void testParse_WithEmptyVersion() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:roster' ver=''/>"));
+
+ RosterPayload* payload = dynamic_cast<RosterPayload*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *payload->getVersion());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp
index 4b903e0..5fe4168 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp
@@ -13,169 +13,169 @@
using namespace Swift;
class SearchPayloadParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SearchPayloadParserTest);
- CPPUNIT_TEST(testParse_FormRequestResponse);
- CPPUNIT_TEST(testParse_Results);
- CPPUNIT_TEST(testParse_FormRequestResponse_XDATA);
- CPPUNIT_TEST(testParse_Results_XDATA);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse_FormRequestResponse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"jabber:iq:search\">"
- "<instructions>Foo</instructions>"
- "<first/>"
- "<last/>"
- "</query>"
- ));
-
- SearchPayload::ref payload = parser.getPayload<SearchPayload>();
- CPPUNIT_ASSERT_EQUAL(std::string("Foo"), *payload->getInstructions());
- CPPUNIT_ASSERT(payload->getFirst());
- CPPUNIT_ASSERT(payload->getLast());
- CPPUNIT_ASSERT(!payload->getNick());
- }
-
- void testParse_Results() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"jabber:iq:search\">"
- "<item jid=\"juliet@capulet.com\">"
- "<first>Juliet</first>"
- "<last>Capulet</last>"
- "<nick>JuliC</nick>"
- "<email>juliet@shakespeare.lit</email>"
- "</item>"
- "<item jid=\"tybalt@shakespeare.lit\">"
- "<first>Tybalt</first>"
- "<last>Capulet</last>"
- "<nick>ty</nick>"
- "<email>tybalt@shakespeare.lit</email>"
- "</item>"
- "</query>"
- ));
-
- SearchPayload::ref payload = parser.getPayload<SearchPayload>();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getItems().size()));
- CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.com"), payload->getItems()[0].jid);
- CPPUNIT_ASSERT_EQUAL(std::string("Juliet"), payload->getItems()[0].first);
- CPPUNIT_ASSERT_EQUAL(std::string("Capulet"), payload->getItems()[0].last);
- CPPUNIT_ASSERT_EQUAL(std::string("JuliC"), payload->getItems()[0].nick);
- CPPUNIT_ASSERT_EQUAL(std::string("juliet@shakespeare.lit"), payload->getItems()[0].email);
- CPPUNIT_ASSERT_EQUAL(JID("tybalt@shakespeare.lit"), payload->getItems()[1].jid);
- }
-
- void testParse_FormRequestResponse_XDATA() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns='jabber:iq:search'>"
- "<instructions>"
- "Use the enclosed form to search. If your Jabber client does not"
- " support Data Forms, visit http://shakespeare.lit/"
- "</instructions>"
- "<x xmlns='jabber:x:data' type='form'>"
- "<title>User Directory Search</title>"
- "<instructions>"
- "Please provide the following information"
- " to search for Shakespearean characters."
- "</instructions>"
- "<field type='hidden'"
- " var='FORM_TYPE'>"
- "<value>jabber:iq:search</value>"
- "</field>"
- "<field type='text-single'"
- " label='Given Name'"
- " var='first'/>"
- "<field type='text-single'"
- " label='Family Name'"
- " var='last'/>"
- "<field type='list-single'"
- " label='Gender'"
- " var='x-gender'>"
- "<option label='Male'><value>male</value></option>"
- "<option label='Female'><value>female</value></option>"
- "</field>"
- "</x>"
- "</query>"
- ));
-
- SearchPayload::ref payload = parser.getPayload<SearchPayload>();
- CPPUNIT_ASSERT_EQUAL(std::string("Use the enclosed form to search. If your Jabber client does not"
- " support Data Forms, visit http://shakespeare.lit/"), *payload->getInstructions());
- CPPUNIT_ASSERT(payload->getForm());
- CPPUNIT_ASSERT_EQUAL(std::string("Please provide the following information"
- " to search for Shakespearean characters."), payload->getForm()->getInstructions());
- }
-
- void testParse_Results_XDATA() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:search'>"
- " <x xmlns='jabber:x:data' type='result'>"
- " <field type='hidden' var='FORM_TYPE'>"
- " <value>jabber:iq:search</value>"
- " </field>"
- " <reported>"
- " <field var='first' label='Given Name' type='text-single'/>"
- " <field var='last' label='Family Name' type='text-single'/>"
- " <field var='jid' label='Jabber ID' type='jid-single'/>"
- " <field var='x-gender' label='Gender' type='list-single'/>"
- " </reported>"
- " <item>"
- " <field var='first'><value>Benvolio</value></field>"
- " <field var='last'><value>Montague</value></field>"
- " <field var='jid'><value>benvolio@montague.net</value></field>"
- " <field var='x-gender'><value>male</value></field>"
- " </item>"
- " <item>"
- " <field var='first'><value>Romeo</value></field>"
- " <field var='last'><value>Montague</value></field>"
- " <field var='jid'><value>romeo@montague.net</value></field>"
- " <field var='x-gender'><value>male</value></field>"
- " </item>"
- " </x>"
- "</query>"));
- SearchPayload::ref payload = parser.getPayload<SearchPayload>();
- CPPUNIT_ASSERT(payload);
-
- Form::ref dataForm = payload->getForm();
- CPPUNIT_ASSERT(dataForm);
-
- Form::FormItem reported = dataForm->getReportedFields();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), reported.size());
-
- std::vector<Form::FormItem> items = dataForm->getItems();
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
-
- Form::FormItem item = items[0];
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Benvolio"), item[0]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("benvolio@montague.net"), item[2]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
-
- item = items[1];
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Romeo"), item[0]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("romeo@montague.net"), item[2]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
- }
+ CPPUNIT_TEST_SUITE(SearchPayloadParserTest);
+ CPPUNIT_TEST(testParse_FormRequestResponse);
+ CPPUNIT_TEST(testParse_Results);
+ CPPUNIT_TEST(testParse_FormRequestResponse_XDATA);
+ CPPUNIT_TEST(testParse_Results_XDATA);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse_FormRequestResponse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"jabber:iq:search\">"
+ "<instructions>Foo</instructions>"
+ "<first/>"
+ "<last/>"
+ "</query>"
+ ));
+
+ SearchPayload::ref payload = parser.getPayload<SearchPayload>();
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo"), *payload->getInstructions());
+ CPPUNIT_ASSERT(payload->getFirst());
+ CPPUNIT_ASSERT(payload->getLast());
+ CPPUNIT_ASSERT(!payload->getNick());
+ }
+
+ void testParse_Results() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"jabber:iq:search\">"
+ "<item jid=\"juliet@capulet.com\">"
+ "<first>Juliet</first>"
+ "<last>Capulet</last>"
+ "<nick>JuliC</nick>"
+ "<email>juliet@shakespeare.lit</email>"
+ "</item>"
+ "<item jid=\"tybalt@shakespeare.lit\">"
+ "<first>Tybalt</first>"
+ "<last>Capulet</last>"
+ "<nick>ty</nick>"
+ "<email>tybalt@shakespeare.lit</email>"
+ "</item>"
+ "</query>"
+ ));
+
+ SearchPayload::ref payload = parser.getPayload<SearchPayload>();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getItems().size()));
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.com"), payload->getItems()[0].jid);
+ CPPUNIT_ASSERT_EQUAL(std::string("Juliet"), payload->getItems()[0].first);
+ CPPUNIT_ASSERT_EQUAL(std::string("Capulet"), payload->getItems()[0].last);
+ CPPUNIT_ASSERT_EQUAL(std::string("JuliC"), payload->getItems()[0].nick);
+ CPPUNIT_ASSERT_EQUAL(std::string("juliet@shakespeare.lit"), payload->getItems()[0].email);
+ CPPUNIT_ASSERT_EQUAL(JID("tybalt@shakespeare.lit"), payload->getItems()[1].jid);
+ }
+
+ void testParse_FormRequestResponse_XDATA() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns='jabber:iq:search'>"
+ "<instructions>"
+ "Use the enclosed form to search. If your Jabber client does not"
+ " support Data Forms, visit http://shakespeare.lit/"
+ "</instructions>"
+ "<x xmlns='jabber:x:data' type='form'>"
+ "<title>User Directory Search</title>"
+ "<instructions>"
+ "Please provide the following information"
+ " to search for Shakespearean characters."
+ "</instructions>"
+ "<field type='hidden'"
+ " var='FORM_TYPE'>"
+ "<value>jabber:iq:search</value>"
+ "</field>"
+ "<field type='text-single'"
+ " label='Given Name'"
+ " var='first'/>"
+ "<field type='text-single'"
+ " label='Family Name'"
+ " var='last'/>"
+ "<field type='list-single'"
+ " label='Gender'"
+ " var='x-gender'>"
+ "<option label='Male'><value>male</value></option>"
+ "<option label='Female'><value>female</value></option>"
+ "</field>"
+ "</x>"
+ "</query>"
+ ));
+
+ SearchPayload::ref payload = parser.getPayload<SearchPayload>();
+ CPPUNIT_ASSERT_EQUAL(std::string("Use the enclosed form to search. If your Jabber client does not"
+ " support Data Forms, visit http://shakespeare.lit/"), *payload->getInstructions());
+ CPPUNIT_ASSERT(payload->getForm());
+ CPPUNIT_ASSERT_EQUAL(std::string("Please provide the following information"
+ " to search for Shakespearean characters."), payload->getForm()->getInstructions());
+ }
+
+ void testParse_Results_XDATA() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<query xmlns='jabber:iq:search'>"
+ " <x xmlns='jabber:x:data' type='result'>"
+ " <field type='hidden' var='FORM_TYPE'>"
+ " <value>jabber:iq:search</value>"
+ " </field>"
+ " <reported>"
+ " <field var='first' label='Given Name' type='text-single'/>"
+ " <field var='last' label='Family Name' type='text-single'/>"
+ " <field var='jid' label='Jabber ID' type='jid-single'/>"
+ " <field var='x-gender' label='Gender' type='list-single'/>"
+ " </reported>"
+ " <item>"
+ " <field var='first'><value>Benvolio</value></field>"
+ " <field var='last'><value>Montague</value></field>"
+ " <field var='jid'><value>benvolio@montague.net</value></field>"
+ " <field var='x-gender'><value>male</value></field>"
+ " </item>"
+ " <item>"
+ " <field var='first'><value>Romeo</value></field>"
+ " <field var='last'><value>Montague</value></field>"
+ " <field var='jid'><value>romeo@montague.net</value></field>"
+ " <field var='x-gender'><value>male</value></field>"
+ " </item>"
+ " </x>"
+ "</query>"));
+ SearchPayload::ref payload = parser.getPayload<SearchPayload>();
+ CPPUNIT_ASSERT(payload);
+
+ Form::ref dataForm = payload->getForm();
+ CPPUNIT_ASSERT(dataForm);
+
+ Form::FormItem reported = dataForm->getReportedFields();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), reported.size());
+
+ std::vector<Form::FormItem> items = dataForm->getItems();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), items.size());
+
+ Form::FormItem item = items[0];
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Benvolio"), item[0]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("benvolio@montague.net"), item[2]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
+
+ item = items[1];
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), item.size());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Romeo"), item[0]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("first"), item[0]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Montague"), item[1]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("last"), item[1]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("romeo@montague.net"), item[2]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("jid"), item[2]->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("male"), item[3]->getValues()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("x-gender"), item[3]->getName());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SearchPayloadParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp
index 14f1f17..c27b716 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp
@@ -14,38 +14,38 @@ using namespace Swift;
class SecurityLabelParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SecurityLabelParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- SecurityLabelParserTest() {}
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking fgcolor=\"black\" bgcolor=\"red\">SECRET</displaymarking>"
- "<label>"
- "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"
- "</label>"
- "<equivalentlabel>"
- "<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>"
- "</equivalentlabel>"
- "<equivalentlabel>"
- "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"
- "</equivalentlabel>"
- "</securitylabel>"));
-
- SecurityLabel* payload = dynamic_cast<SecurityLabel*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("SECRET"), payload->getDisplayMarking());
- CPPUNIT_ASSERT_EQUAL(std::string("black"), payload->getForegroundColor());
- CPPUNIT_ASSERT_EQUAL(std::string("red"), payload->getBackgroundColor());
- CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"), payload->getLabel());
- CPPUNIT_ASSERT_EQUAL(std::string("<icismlabel classification=\"S\" disseminationControls=\"FOUO\" ownerProducer=\"USA\" xmlns=\"http://example.gov/IC-ISM/0\"/>"), payload->getEquivalentLabels()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"), payload->getEquivalentLabels()[1]);
- }
+ CPPUNIT_TEST_SUITE(SecurityLabelParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ SecurityLabelParserTest() {}
+
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking fgcolor=\"black\" bgcolor=\"red\">SECRET</displaymarking>"
+ "<label>"
+ "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"
+ "</label>"
+ "<equivalentlabel>"
+ "<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>"
+ "</equivalentlabel>"
+ "<equivalentlabel>"
+ "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"
+ "</equivalentlabel>"
+ "</securitylabel>"));
+
+ SecurityLabel* payload = dynamic_cast<SecurityLabel*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("SECRET"), payload->getDisplayMarking());
+ CPPUNIT_ASSERT_EQUAL(std::string("black"), payload->getForegroundColor());
+ CPPUNIT_ASSERT_EQUAL(std::string("red"), payload->getBackgroundColor());
+ CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"), payload->getLabel());
+ CPPUNIT_ASSERT_EQUAL(std::string("<icismlabel classification=\"S\" disseminationControls=\"FOUO\" ownerProducer=\"USA\" xmlns=\"http://example.gov/IC-ISM/0\"/>"), payload->getEquivalentLabels()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"), payload->getEquivalentLabels()[1]);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SecurityLabelParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp
index f1745d0..2b992b1 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp
@@ -14,50 +14,50 @@ using namespace Swift;
class SecurityLabelsCatalogParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SecurityLabelsCatalogParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- SecurityLabelsCatalogParserTest() {}
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<catalog desc=\"an example set of labels\" name=\"Default\" to=\"example.com\" xmlns=\"urn:xmpp:sec-label:catalog:2\">"
- "<item selector='Classified|SECRET'>"
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
- "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel></label>"
- "</securitylabel>"
- "</item>"
- "<item selector='Classified|CONFIDENTIAL' default='true'>"
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking bgcolor=\"navy\" fgcolor=\"black\">CONFIDENTIAL</displaymarking>"
- "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel></label>"
- "</securitylabel>"
- "</item>"
- "<item selector='Unclassified|UNCLASSIFIED'/>"
- "</catalog>"));
-
- SecurityLabelsCatalog* payload = dynamic_cast<SecurityLabelsCatalog*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Default"), payload->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("an example set of labels"), payload->getDescription());
- CPPUNIT_ASSERT_EQUAL(JID("example.com"), payload->getTo());
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getItems().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("SECRET"), payload->getItems()[0].getLabel()->getDisplayMarking());
- CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"), payload->getItems()[0].getLabel()->getLabel());
- CPPUNIT_ASSERT_EQUAL(false, payload->getItems()[0].getIsDefault());
- CPPUNIT_ASSERT_EQUAL(std::string("Classified|SECRET"), payload->getItems()[0].getSelector());
- CPPUNIT_ASSERT_EQUAL(std::string("CONFIDENTIAL"), payload->getItems()[1].getLabel()->getDisplayMarking());
- CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel>"), payload->getItems()[1].getLabel()->getLabel());
- CPPUNIT_ASSERT_EQUAL(true, payload->getItems()[1].getIsDefault());
- CPPUNIT_ASSERT_EQUAL(std::string("Classified|CONFIDENTIAL"), payload->getItems()[1].getSelector());
- CPPUNIT_ASSERT_EQUAL(false, payload->getItems()[2].getIsDefault());
- CPPUNIT_ASSERT_EQUAL(std::string("Unclassified|UNCLASSIFIED"), payload->getItems()[2].getSelector());
- CPPUNIT_ASSERT(!payload->getItems()[2].getLabel());
- }
+ CPPUNIT_TEST_SUITE(SecurityLabelsCatalogParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ SecurityLabelsCatalogParserTest() {}
+
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<catalog desc=\"an example set of labels\" name=\"Default\" to=\"example.com\" xmlns=\"urn:xmpp:sec-label:catalog:2\">"
+ "<item selector='Classified|SECRET'>"
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
+ "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel></label>"
+ "</securitylabel>"
+ "</item>"
+ "<item selector='Classified|CONFIDENTIAL' default='true'>"
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking bgcolor=\"navy\" fgcolor=\"black\">CONFIDENTIAL</displaymarking>"
+ "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel></label>"
+ "</securitylabel>"
+ "</item>"
+ "<item selector='Unclassified|UNCLASSIFIED'/>"
+ "</catalog>"));
+
+ SecurityLabelsCatalog* payload = dynamic_cast<SecurityLabelsCatalog*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Default"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("an example set of labels"), payload->getDescription());
+ CPPUNIT_ASSERT_EQUAL(JID("example.com"), payload->getTo());
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(payload->getItems().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("SECRET"), payload->getItems()[0].getLabel()->getDisplayMarking());
+ CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"), payload->getItems()[0].getLabel()->getLabel());
+ CPPUNIT_ASSERT_EQUAL(false, payload->getItems()[0].getIsDefault());
+ CPPUNIT_ASSERT_EQUAL(std::string("Classified|SECRET"), payload->getItems()[0].getSelector());
+ CPPUNIT_ASSERT_EQUAL(std::string("CONFIDENTIAL"), payload->getItems()[1].getLabel()->getDisplayMarking());
+ CPPUNIT_ASSERT_EQUAL(std::string("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel>"), payload->getItems()[1].getLabel()->getLabel());
+ CPPUNIT_ASSERT_EQUAL(true, payload->getItems()[1].getIsDefault());
+ CPPUNIT_ASSERT_EQUAL(std::string("Classified|CONFIDENTIAL"), payload->getItems()[1].getSelector());
+ CPPUNIT_ASSERT_EQUAL(false, payload->getItems()[2].getIsDefault());
+ CPPUNIT_ASSERT_EQUAL(std::string("Unclassified|UNCLASSIFIED"), payload->getItems()[2].getSelector());
+ CPPUNIT_ASSERT(!payload->getItems()[2].getLabel());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SecurityLabelsCatalogParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp
index 6650cb7..7471856 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp
@@ -14,28 +14,28 @@ using namespace Swift;
class SoftwareVersionParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SoftwareVersionParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- SoftwareVersionParserTest() {}
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<query xmlns=\"jabber:iq:version\">"
- "<name>myclient</name>"
- "<version>1.0</version>"
- "<os>Mac OS X</os>"
- "</query>"));
-
- SoftwareVersion* payload = dynamic_cast<SoftwareVersion*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("myclient"), payload->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("1.0"), payload->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("Mac OS X"), payload->getOS());
- }
+ CPPUNIT_TEST_SUITE(SoftwareVersionParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ SoftwareVersionParserTest() {}
+
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<query xmlns=\"jabber:iq:version\">"
+ "<name>myclient</name>"
+ "<version>1.0</version>"
+ "<os>Mac OS X</os>"
+ "</query>"));
+
+ SoftwareVersion* payload = dynamic_cast<SoftwareVersion*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("myclient"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("1.0"), payload->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("Mac OS X"), payload->getOS());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SoftwareVersionParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/StatusParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/StatusParserTest.cpp
index 5c7f467..6b93637 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StatusParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StatusParserTest.cpp
@@ -14,21 +14,21 @@ using namespace Swift;
class StatusParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StatusParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StatusParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
- public:
- StatusParserTest() {}
+ public:
+ StatusParserTest() {}
- void testParse() {
- PayloadsParserTester parser;
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse("<status>foo<baz>bar</baz>fum</status>"));
+ CPPUNIT_ASSERT(parser.parse("<status>foo<baz>bar</baz>fum</status>"));
- Status* payload = dynamic_cast<Status*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("foobarfum"), payload->getText());
- }
+ Status* payload = dynamic_cast<Status*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("foobarfum"), payload->getText());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StatusParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp
index 98653ef..94f14c6 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp
@@ -14,61 +14,61 @@ using namespace Swift;
class StatusShowParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StatusShowParserTest);
- CPPUNIT_TEST(testParse_Invalid);
- CPPUNIT_TEST(testParse_Away);
- CPPUNIT_TEST(testParse_FFC);
- CPPUNIT_TEST(testParse_XA);
- CPPUNIT_TEST(testParse_DND);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- StatusShowParserTest() {}
-
- void testParse_Invalid() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<show>invalid</show>"));
-
- StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
- CPPUNIT_ASSERT(StatusShow::Online == payload->getType());
- }
-
- void testParse_Away() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<show>away</show>"));
-
- StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
- CPPUNIT_ASSERT(StatusShow::Away == payload->getType());
- }
-
- void testParse_FFC() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<show>chat</show>"));
-
- StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
- CPPUNIT_ASSERT(StatusShow::FFC == payload->getType());
- }
-
- void testParse_XA() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<show>xa</show>"));
-
- StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
- CPPUNIT_ASSERT(StatusShow::XA == payload->getType());
- }
-
- void testParse_DND() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<show>dnd</show>"));
-
- StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
- CPPUNIT_ASSERT(StatusShow::DND == payload->getType());
- }
+ CPPUNIT_TEST_SUITE(StatusShowParserTest);
+ CPPUNIT_TEST(testParse_Invalid);
+ CPPUNIT_TEST(testParse_Away);
+ CPPUNIT_TEST(testParse_FFC);
+ CPPUNIT_TEST(testParse_XA);
+ CPPUNIT_TEST(testParse_DND);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ StatusShowParserTest() {}
+
+ void testParse_Invalid() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<show>invalid</show>"));
+
+ StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(StatusShow::Online == payload->getType());
+ }
+
+ void testParse_Away() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<show>away</show>"));
+
+ StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(StatusShow::Away == payload->getType());
+ }
+
+ void testParse_FFC() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<show>chat</show>"));
+
+ StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(StatusShow::FFC == payload->getType());
+ }
+
+ void testParse_XA() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<show>xa</show>"));
+
+ StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(StatusShow::XA == payload->getType());
+ }
+
+ void testParse_DND() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<show>dnd</show>"));
+
+ StatusShow* payload = dynamic_cast<StatusShow*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(StatusShow::DND == payload->getType());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StatusShowParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/StorageParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/StorageParserTest.cpp
index 9797b6a..4430668 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StorageParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StorageParserTest.cpp
@@ -13,74 +13,74 @@
using namespace Swift;
class StorageParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StorageParserTest);
- CPPUNIT_TEST(testParse_Room);
- CPPUNIT_TEST(testParse_MultipleRooms);
- CPPUNIT_TEST(testParse_URL);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- StorageParserTest() {}
-
- void testParse_Room() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<storage xmlns='storage:bookmarks'>"
- "<conference "
- "name='Council of Oberon' "
- "autojoin='true' jid='council@conference.underhill.org'>"
- "<nick>Puck</nick>"
- "<password>MyPass</password>"
- "</conference>"
- "</storage>"));
-
- Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
- std::vector<Storage::Room> rooms = payload->getRooms();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rooms.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Council of Oberon"), rooms[0].name);
- CPPUNIT_ASSERT_EQUAL(JID("council@conference.underhill.org"), rooms[0].jid);
- CPPUNIT_ASSERT(rooms[0].autoJoin);
- CPPUNIT_ASSERT_EQUAL(std::string("Puck"), rooms[0].nick);
- CPPUNIT_ASSERT_EQUAL(std::string("MyPass"), *rooms[0].password);
- }
-
- void testParse_MultipleRooms() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<storage xmlns='storage:bookmarks'>"
- "<conference "
- "name='Council of Oberon' "
- "jid='council@conference.underhill.org' />"
- "<conference "
- "name='Tea &amp; jam party' "
- "jid='teaparty@wonderland.lit' />"
- "</storage>"));
-
- Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
- std::vector<Storage::Room> rooms = payload->getRooms();
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rooms.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Council of Oberon"), rooms[0].name);
- CPPUNIT_ASSERT_EQUAL(JID("council@conference.underhill.org"), rooms[0].jid);
- CPPUNIT_ASSERT_EQUAL(std::string("Tea & jam party"), rooms[1].name);
- CPPUNIT_ASSERT_EQUAL(JID("teaparty@wonderland.lit"), rooms[1].jid);
- }
-
- void testParse_URL() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<storage xmlns='storage:bookmarks'>"
- "<url name='Complete Works of Shakespeare' url='http://the-tech.mit.edu/Shakespeare/'/>"
- "</storage>"));
-
- Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
- std::vector<Storage::URL> urls = payload->getURLs();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(urls.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Complete Works of Shakespeare"), urls[0].name);
- CPPUNIT_ASSERT_EQUAL(std::string("http://the-tech.mit.edu/Shakespeare/"), urls[0].url);
- }
+ CPPUNIT_TEST_SUITE(StorageParserTest);
+ CPPUNIT_TEST(testParse_Room);
+ CPPUNIT_TEST(testParse_MultipleRooms);
+ CPPUNIT_TEST(testParse_URL);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ StorageParserTest() {}
+
+ void testParse_Room() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<storage xmlns='storage:bookmarks'>"
+ "<conference "
+ "name='Council of Oberon' "
+ "autojoin='true' jid='council@conference.underhill.org'>"
+ "<nick>Puck</nick>"
+ "<password>MyPass</password>"
+ "</conference>"
+ "</storage>"));
+
+ Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
+ std::vector<Storage::Room> rooms = payload->getRooms();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rooms.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Council of Oberon"), rooms[0].name);
+ CPPUNIT_ASSERT_EQUAL(JID("council@conference.underhill.org"), rooms[0].jid);
+ CPPUNIT_ASSERT(rooms[0].autoJoin);
+ CPPUNIT_ASSERT_EQUAL(std::string("Puck"), rooms[0].nick);
+ CPPUNIT_ASSERT_EQUAL(std::string("MyPass"), *rooms[0].password);
+ }
+
+ void testParse_MultipleRooms() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<storage xmlns='storage:bookmarks'>"
+ "<conference "
+ "name='Council of Oberon' "
+ "jid='council@conference.underhill.org' />"
+ "<conference "
+ "name='Tea &amp; jam party' "
+ "jid='teaparty@wonderland.lit' />"
+ "</storage>"));
+
+ Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
+ std::vector<Storage::Room> rooms = payload->getRooms();
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rooms.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Council of Oberon"), rooms[0].name);
+ CPPUNIT_ASSERT_EQUAL(JID("council@conference.underhill.org"), rooms[0].jid);
+ CPPUNIT_ASSERT_EQUAL(std::string("Tea & jam party"), rooms[1].name);
+ CPPUNIT_ASSERT_EQUAL(JID("teaparty@wonderland.lit"), rooms[1].jid);
+ }
+
+ void testParse_URL() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<storage xmlns='storage:bookmarks'>"
+ "<url name='Complete Works of Shakespeare' url='http://the-tech.mit.edu/Shakespeare/'/>"
+ "</storage>"));
+
+ Storage* payload = dynamic_cast<Storage*>(parser.getPayload().get());
+ std::vector<Storage::URL> urls = payload->getURLs();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(urls.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Complete Works of Shakespeare"), urls[0].name);
+ CPPUNIT_ASSERT_EQUAL(std::string("http://the-tech.mit.edu/Shakespeare/"), urls[0].url);
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
index dbbaca8..9b0679d 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
@@ -13,63 +13,63 @@
using namespace Swift;
class StreamInitiationParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StreamInitiationParserTest);
- CPPUNIT_TEST(testParse_Request);
- CPPUNIT_TEST(testParse_Response);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StreamInitiationParserTest);
+ CPPUNIT_TEST(testParse_Request);
+ CPPUNIT_TEST(testParse_Response);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse_Request() {
- PayloadsParserTester parser;
+ public:
+ void testParse_Request() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<si xmlns='http://jabber.org/protocol/si' id='a0' mime-type='text/plain' profile='http://jabber.org/protocol/si/profile/file-transfer'>"
- "<file xmlns='http://jabber.org/protocol/si/profile/file-transfer' name='test.txt' size='1022'>"
- "<desc>This is info about the file.</desc>"
- "</file>"
- "<feature xmlns='http://jabber.org/protocol/feature-neg'>"
- "<x xmlns='jabber:x:data' type='form'>"
- "<field var='stream-method' type='list-single'>"
- "<option><value>http://jabber.org/protocol/bytestreams</value></option>"
- "<option><value>jabber:iq:oob</value></option>"
- "<option><value>http://jabber.org/protocol/ibb</value></option>"
- "</field>"
- "</x>"
- "</feature>"
- "</si>"
- ));
+ CPPUNIT_ASSERT(parser.parse(
+ "<si xmlns='http://jabber.org/protocol/si' id='a0' mime-type='text/plain' profile='http://jabber.org/protocol/si/profile/file-transfer'>"
+ "<file xmlns='http://jabber.org/protocol/si/profile/file-transfer' name='test.txt' size='1022'>"
+ "<desc>This is info about the file.</desc>"
+ "</file>"
+ "<feature xmlns='http://jabber.org/protocol/feature-neg'>"
+ "<x xmlns='jabber:x:data' type='form'>"
+ "<field var='stream-method' type='list-single'>"
+ "<option><value>http://jabber.org/protocol/bytestreams</value></option>"
+ "<option><value>jabber:iq:oob</value></option>"
+ "<option><value>http://jabber.org/protocol/ibb</value></option>"
+ "</field>"
+ "</x>"
+ "</feature>"
+ "</si>"
+ ));
- StreamInitiation::ref si = parser.getPayload<StreamInitiation>();
- CPPUNIT_ASSERT(si->getIsFileTransfer());
- CPPUNIT_ASSERT(si->getFileInfo());
- CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), si->getFileInfo()->getName());
- CPPUNIT_ASSERT(1022 == si->getFileInfo()->getSize());
- CPPUNIT_ASSERT_EQUAL(std::string("This is info about the file."), si->getFileInfo()->getDescription());
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(si->getProvidedMethods().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/bytestreams"), si->getProvidedMethods()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:oob"), si->getProvidedMethods()[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/ibb"), si->getProvidedMethods()[2]);
- }
+ StreamInitiation::ref si = parser.getPayload<StreamInitiation>();
+ CPPUNIT_ASSERT(si->getIsFileTransfer());
+ CPPUNIT_ASSERT(si->getFileInfo());
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), si->getFileInfo()->getName());
+ CPPUNIT_ASSERT(1022 == si->getFileInfo()->getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is info about the file."), si->getFileInfo()->getDescription());
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(si->getProvidedMethods().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/bytestreams"), si->getProvidedMethods()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:oob"), si->getProvidedMethods()[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/ibb"), si->getProvidedMethods()[2]);
+ }
- void testParse_Response() {
- PayloadsParserTester parser;
+ void testParse_Response() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<si xmlns='http://jabber.org/protocol/si'>"
- "<feature xmlns='http://jabber.org/protocol/feature-neg'>"
- "<x xmlns='jabber:x:data' type='submit'>"
- "<field var='stream-method'>"
- "<value>http://jabber.org/protocol/bytestreams</value>"
- "</field>"
- "</x>"
- "</feature>"
- "</si>"
- ));
+ CPPUNIT_ASSERT(parser.parse(
+ "<si xmlns='http://jabber.org/protocol/si'>"
+ "<feature xmlns='http://jabber.org/protocol/feature-neg'>"
+ "<x xmlns='jabber:x:data' type='submit'>"
+ "<field var='stream-method'>"
+ "<value>http://jabber.org/protocol/bytestreams</value>"
+ "</field>"
+ "</x>"
+ "</feature>"
+ "</si>"
+ ));
- StreamInitiation::ref si = parser.getPayload<StreamInitiation>();
- CPPUNIT_ASSERT(si->getIsFileTransfer());
- CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/bytestreams"), si->getRequestedMethod());
- }
+ StreamInitiation::ref si = parser.getPayload<StreamInitiation>();
+ CPPUNIT_ASSERT(si->getIsFileTransfer());
+ CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/bytestreams"), si->getRequestedMethod());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StreamInitiationParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp
index d3bf378..6d16377 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp
@@ -13,7 +13,7 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserLocation.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Parser/PayloadParsers/UserLocationParser.h>
@@ -22,89 +22,89 @@ using namespace Swift;
class UserLocationParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(UserLocationParserTest);
- CPPUNIT_TEST(testParse_with_all_variables);
- CPPUNIT_TEST(testParse_with_Some_variables);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(UserLocationParserTest);
+ CPPUNIT_TEST(testParse_with_all_variables);
+ CPPUNIT_TEST(testParse_with_Some_variables);
+ CPPUNIT_TEST_SUITE_END();
- public:
- UserLocationParserTest() {}
+ public:
+ UserLocationParserTest() {}
- void testParse_with_all_variables() {
- PayloadsParserTester parser;
+ void testParse_with_all_variables() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
- "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
- "<lat>1.67</lat><accuracy>0.95</accuracy><description>Nice</description>"
- "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
- "<building>First</building><room>E315</room><country>USA</country>"
- "<region>NewSode</region><uri>URIs</uri><lon>6.7578</lon><error>5.66</error>"
- "<postalcode>67</postalcode><bearing>12.89</bearing><text>Hello</text>"
- "<datum>Datee</datum><street>Highway</street><speed>56.77</speed></geoloc>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
+ "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
+ "<lat>1.67</lat><accuracy>0.95</accuracy><description>Nice</description>"
+ "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
+ "<building>First</building><room>E315</room><country>USA</country>"
+ "<region>NewSode</region><uri>URIs</uri><lon>6.7578</lon><error>5.66</error>"
+ "<postalcode>67</postalcode><bearing>12.89</bearing><text>Hello</text>"
+ "<datum>Datee</datum><street>Highway</street><speed>56.77</speed></geoloc>"));
- UserLocation* payload = dynamic_cast<UserLocation*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("Barbaric"), payload->getArea().get());
- CPPUNIT_ASSERT_EQUAL(5.75F, payload->getAltitude().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
- CPPUNIT_ASSERT_EQUAL(1.670F, payload->getLatitude().get());
- CPPUNIT_ASSERT_EQUAL(0.95F, payload->getAccuracy().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Nice"), payload->getDescription().get());
- CPPUNIT_ASSERT_EQUAL(std::string("+91"), payload->getCountryCode().get());
- CPPUNIT_ASSERT_EQUAL(std::string("2015-06-11T20:55:50Z"), dateTimeToString(payload->getTimestamp().get()));
- CPPUNIT_ASSERT_EQUAL(std::string("3"), payload->getFloor().get());
- CPPUNIT_ASSERT_EQUAL(std::string("First"), payload->getBuilding().get());
- CPPUNIT_ASSERT_EQUAL(std::string("E315"), payload->getRoom().get());
- CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getCountry().get());
- CPPUNIT_ASSERT_EQUAL(std::string("NewSode"), payload->getRegion().get());
- CPPUNIT_ASSERT_EQUAL(std::string("URIs"), payload->getURI().get());
- CPPUNIT_ASSERT_EQUAL(6.7578F, payload->getLongitude().get());
- CPPUNIT_ASSERT_EQUAL(5.66F, payload->getError().get());
- CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
- CPPUNIT_ASSERT_EQUAL(12.89F, payload->getBearing().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Hello"), payload->getText().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Datee"), payload->getDatum().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Highway"), payload->getStreet().get());
- CPPUNIT_ASSERT_EQUAL(56.77F, payload->getSpeed().get());
- }
+ UserLocation* payload = dynamic_cast<UserLocation*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("Barbaric"), payload->getArea().get());
+ CPPUNIT_ASSERT_EQUAL(5.75F, payload->getAltitude().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
+ CPPUNIT_ASSERT_EQUAL(1.670F, payload->getLatitude().get());
+ CPPUNIT_ASSERT_EQUAL(0.95F, payload->getAccuracy().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Nice"), payload->getDescription().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("+91"), payload->getCountryCode().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("2015-06-11T20:55:50Z"), dateTimeToString(payload->getTimestamp().get()));
+ CPPUNIT_ASSERT_EQUAL(std::string("3"), payload->getFloor().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("First"), payload->getBuilding().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("E315"), payload->getRoom().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getCountry().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewSode"), payload->getRegion().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("URIs"), payload->getURI().get());
+ CPPUNIT_ASSERT_EQUAL(6.7578F, payload->getLongitude().get());
+ CPPUNIT_ASSERT_EQUAL(5.66F, payload->getError().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
+ CPPUNIT_ASSERT_EQUAL(12.89F, payload->getBearing().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Hello"), payload->getText().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Datee"), payload->getDatum().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Highway"), payload->getStreet().get());
+ CPPUNIT_ASSERT_EQUAL(56.77F, payload->getSpeed().get());
+ }
- void testParse_with_Some_variables() {
- PayloadsParserTester parser;
+ void testParse_with_Some_variables() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
- "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
- "<accuracy>0.95</accuracy><description>Nice</description>"
- "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
- "<region>NewSode</region><uri>URIs</uri><lon>6.7578</lon><error>5.66</error>"
- "<postalcode>67</postalcode><bearing>12.89</bearing><text>Hello</text></geoloc>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
+ "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
+ "<accuracy>0.95</accuracy><description>Nice</description>"
+ "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
+ "<region>NewSode</region><uri>URIs</uri><lon>6.7578</lon><error>5.66</error>"
+ "<postalcode>67</postalcode><bearing>12.89</bearing><text>Hello</text></geoloc>"));
- UserLocation* payload = dynamic_cast<UserLocation*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("Barbaric"), payload->getArea().get());
- CPPUNIT_ASSERT_EQUAL(5.75F, payload->getAltitude().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
- CPPUNIT_ASSERT(!payload->getLatitude());
- CPPUNIT_ASSERT_EQUAL(0.95F, payload->getAccuracy().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Nice"), payload->getDescription().get());
- CPPUNIT_ASSERT_EQUAL(std::string("+91"), payload->getCountryCode().get());
- CPPUNIT_ASSERT_EQUAL(std::string("2015-06-11T20:55:50Z"), dateTimeToString(payload->getTimestamp().get()));
- CPPUNIT_ASSERT_EQUAL(std::string("3"), payload->getFloor().get());
- CPPUNIT_ASSERT(!payload->getBuilding());
- CPPUNIT_ASSERT(!payload->getRoom());
- CPPUNIT_ASSERT(!payload->getCountry());
- CPPUNIT_ASSERT_EQUAL(std::string("NewSode"), payload->getRegion().get());
- CPPUNIT_ASSERT_EQUAL(std::string("URIs"), payload->getURI().get());
- CPPUNIT_ASSERT_EQUAL(6.7578F, payload->getLongitude().get());
- CPPUNIT_ASSERT_EQUAL(5.66F, payload->getError().get());
- CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
- CPPUNIT_ASSERT_EQUAL(12.89F, payload->getBearing().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Hello"), payload->getText().get());
- CPPUNIT_ASSERT(!payload->getDatum());
- CPPUNIT_ASSERT(!payload->getStreet());
- CPPUNIT_ASSERT(!payload->getSpeed());
- }
+ UserLocation* payload = dynamic_cast<UserLocation*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("Barbaric"), payload->getArea().get());
+ CPPUNIT_ASSERT_EQUAL(5.75F, payload->getAltitude().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
+ CPPUNIT_ASSERT(!payload->getLatitude());
+ CPPUNIT_ASSERT_EQUAL(0.95F, payload->getAccuracy().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Nice"), payload->getDescription().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("+91"), payload->getCountryCode().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("2015-06-11T20:55:50Z"), dateTimeToString(payload->getTimestamp().get()));
+ CPPUNIT_ASSERT_EQUAL(std::string("3"), payload->getFloor().get());
+ CPPUNIT_ASSERT(!payload->getBuilding());
+ CPPUNIT_ASSERT(!payload->getRoom());
+ CPPUNIT_ASSERT(!payload->getCountry());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewSode"), payload->getRegion().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("URIs"), payload->getURI().get());
+ CPPUNIT_ASSERT_EQUAL(6.7578F, payload->getLongitude().get());
+ CPPUNIT_ASSERT_EQUAL(5.66F, payload->getError().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
+ CPPUNIT_ASSERT_EQUAL(12.89F, payload->getBearing().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Hello"), payload->getText().get());
+ CPPUNIT_ASSERT(!payload->getDatum());
+ CPPUNIT_ASSERT(!payload->getStreet());
+ CPPUNIT_ASSERT(!payload->getSpeed());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(UserLocationParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp
index b1070c5..3783231 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp
@@ -13,7 +13,7 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserTune.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Parser/PayloadParsers/UserTuneParser.h>
@@ -22,49 +22,49 @@ using namespace Swift;
class UserTuneParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(UserTuneParserTest);
- CPPUNIT_TEST(testParse_with_all_variables);
- CPPUNIT_TEST(testParse_with_Some_variables);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(UserTuneParserTest);
+ CPPUNIT_TEST(testParse_with_all_variables);
+ CPPUNIT_TEST(testParse_with_Some_variables);
+ CPPUNIT_TEST_SUITE_END();
- public:
- UserTuneParserTest() {}
+ public:
+ UserTuneParserTest() {}
- void testParse_with_all_variables() {
- PayloadsParserTester parser;
+ void testParse_with_all_variables() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<tune xmlns=\"http://jabber.org/protocol/tune\">"
- "<rating>5</rating><title>Minion</title><track>Yellow</track><artist>Ice</artist><URI>Fire</URI><source>Origin</source><length>226</length></tune>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<tune xmlns=\"http://jabber.org/protocol/tune\">"
+ "<rating>5</rating><title>Minion</title><track>Yellow</track><artist>Ice</artist><URI>Fire</URI><source>Origin</source><length>226</length></tune>"));
- UserTune* payload = dynamic_cast<UserTune*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(5), payload->getRating().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Minion"), payload->getTitle().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Yellow"), payload->getTrack().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Ice"), payload->getArtist().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Fire"), payload->getURI().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Origin"), payload->getSource().get());
- CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(226), payload->getLength().get());
- }
+ UserTune* payload = dynamic_cast<UserTune*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(5), payload->getRating().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Minion"), payload->getTitle().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Yellow"), payload->getTrack().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Ice"), payload->getArtist().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Fire"), payload->getURI().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Origin"), payload->getSource().get());
+ CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(226), payload->getLength().get());
+ }
- void testParse_with_Some_variables() {
- PayloadsParserTester parser;
+ void testParse_with_Some_variables() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<tune xmlns=\"http://jabber.org/protocol/tune\">"
- "<title>Minion</title><track>Yellow</track><source>Origin</source><length>226</length></tune>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<tune xmlns=\"http://jabber.org/protocol/tune\">"
+ "<title>Minion</title><track>Yellow</track><source>Origin</source><length>226</length></tune>"));
- UserTune* payload = dynamic_cast<UserTune*>(parser.getPayload().get());
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT(!payload->getRating());
- CPPUNIT_ASSERT_EQUAL(std::string("Minion"), payload->getTitle().get());
- CPPUNIT_ASSERT_EQUAL(std::string("Yellow"), payload->getTrack().get());
- CPPUNIT_ASSERT(!payload->getArtist());
- CPPUNIT_ASSERT(!payload->getURI());
- CPPUNIT_ASSERT_EQUAL(std::string("Origin"), payload->getSource().get());
- CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(226), payload->getLength().get());
- }
+ UserTune* payload = dynamic_cast<UserTune*>(parser.getPayload().get());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(!payload->getRating());
+ CPPUNIT_ASSERT_EQUAL(std::string("Minion"), payload->getTitle().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Yellow"), payload->getTrack().get());
+ CPPUNIT_ASSERT(!payload->getArtist());
+ CPPUNIT_ASSERT(!payload->getURI());
+ CPPUNIT_ASSERT_EQUAL(std::string("Origin"), payload->getSource().get());
+ CPPUNIT_ASSERT_EQUAL(static_cast<unsigned int>(226), payload->getLength().get());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(UserTuneParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp
index 9e841a7..e02eb7a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp
@@ -18,190 +18,190 @@
using namespace Swift;
class VCardParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(VCardParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Photo);
- CPPUNIT_TEST(testParse_NewlinedPhoto);
- CPPUNIT_TEST(testParse_Nickname);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<vCard xmlns=\"vcard-temp\">"
- "<VERSION>2.0</VERSION>"
- "<FN>Alice In Wonderland</FN>"
- "<N>"
- "<FAMILY>Wonderland</FAMILY>"
- "<GIVEN>Alice</GIVEN>"
- "<MIDDLE>In</MIDDLE>"
- "<PREFIX>Mrs</PREFIX>"
- "<SUFFIX>PhD</SUFFIX>"
- "</N>"
- "<EMAIL>"
- "<USERID>alice@wonderland.lit</USERID>"
- "<HOME/>"
- "<INTERNET/>"
- "<PREF/>"
- "</EMAIL>"
- "<EMAIL>"
- "<USERID>alice@teaparty.lit</USERID>"
- "<WORK/>"
- "<X400/>"
- "</EMAIL>"
- "<TEL>"
- "<NUMBER>555-6273</NUMBER>"
- "<HOME/>"
- "<VOICE/>"
- "</TEL>"
- "<ADR>"
- "<LOCALITY>Any Town</LOCALITY>"
- "<STREET>Fake Street 123</STREET>"
- "<PCODE>12345</PCODE>"
- "<CTRY>USA</CTRY>"
- "<HOME/>"
- "</ADR>"
- "<LABEL>"
- "<LINE>Fake Street 123</LINE>"
- "<LINE>12345 Any Town</LINE>"
- "<LINE>USA</LINE>"
- "<HOME/>"
- "</LABEL>"
- "<NICKNAME>DreamGirl</NICKNAME>"
- "<BDAY>1865-05-04</BDAY>"
- "<JID>alice@teaparty.lit</JID>"
- "<JID>alice@wonderland.lit</JID>"
- "<DESC>I once fell down a rabbit hole.</DESC>"
- "<ORG>"
- "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>"
- "</ORG>"
- "<TITLE>Some Title</TITLE>"
- "<ROLE>Main Character</ROLE>"
- "<URL>http://wonderland.lit/~alice</URL>"
- "<URL>http://teaparty.lit/~alice2</URL>"
- "<MAILER>mutt</MAILER>"
- "</vCard>"));
-
- boost::shared_ptr<VCard> payload = boost::dynamic_pointer_cast<VCard>(parser.getPayload());
- CPPUNIT_ASSERT_EQUAL(std::string("2.0"), payload->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), payload->getFullName());
- CPPUNIT_ASSERT_EQUAL(std::string("Alice"), payload->getGivenName());
- CPPUNIT_ASSERT_EQUAL(std::string("In"), payload->getMiddleName());
- CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), payload->getFamilyName());
- CPPUNIT_ASSERT_EQUAL(std::string("Mrs"), payload->getPrefix());
- CPPUNIT_ASSERT_EQUAL(std::string("PhD"), payload->getSuffix());
- CPPUNIT_ASSERT_EQUAL(std::string("DreamGirl"), payload->getNickname());
- CPPUNIT_ASSERT_EQUAL(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4)), payload->getBirthday());
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getEMailAddresses().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland.lit"), payload->getEMailAddresses()[0].address);
- CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isHome);
- CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isInternet);
- CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isPreferred);
- CPPUNIT_ASSERT(!payload->getEMailAddresses()[0].isWork);
- CPPUNIT_ASSERT(!payload->getEMailAddresses()[0].isX400);
- CPPUNIT_ASSERT_EQUAL(std::string("alice@teaparty.lit"), payload->getEMailAddresses()[1].address);
- CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isHome);
- CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isInternet);
- CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isPreferred);
- CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isWork);
- CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isX400);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTelephones().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("555-6273"), payload->getTelephones()[0].number);
- CPPUNIT_ASSERT(payload->getTelephones()[0].isHome);
- CPPUNIT_ASSERT(payload->getTelephones()[0].isVoice);
- CPPUNIT_ASSERT(!payload->getTelephones()[0].isPreferred);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddresses().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Any Town"), payload->getAddresses()[0].locality);
- CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddresses()[0].street);
- CPPUNIT_ASSERT_EQUAL(std::string("12345"), payload->getAddresses()[0].postalCode);
- CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddresses()[0].country);
- CPPUNIT_ASSERT(payload->getAddresses()[0].isHome);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddressLabels().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddressLabels()[0].lines[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("12345 Any Town"), payload->getAddressLabels()[0].lines[1]);
- CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddressLabels()[0].lines[2]);
- CPPUNIT_ASSERT(payload->getAddressLabels()[0].isHome);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getJIDs().size()));
- CPPUNIT_ASSERT_EQUAL(JID("alice@teaparty.lit"), payload->getJIDs()[0]);
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit"), payload->getJIDs()[1]);
-
- CPPUNIT_ASSERT_EQUAL(std::string("I once fell down a rabbit hole."), payload->getDescription());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getOrganizations().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland Inc."), payload->getOrganizations()[0].name);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(payload->getOrganizations()[0].units.size()));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTitles().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Some Title"), payload->getTitles()[0]);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getRoles().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Main Character"), payload->getRoles()[0]);
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getURLs().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("http://wonderland.lit/~alice"), payload->getURLs()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("http://teaparty.lit/~alice2"), payload->getURLs()[1]);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<MAILER xmlns=\"vcard-temp\">mutt</MAILER>"), payload->getUnknownContent());
- }
-
- void testParse_Photo() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<vCard xmlns='vcard-temp'>"
- "<PHOTO>"
- "<TYPE>image/jpeg</TYPE>"
- "<BINVAL>"
- "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ej"
- "EyMzQ1Njc4OTA="
- "</BINVAL>"
- "</PHOTO>"
- "</vCard>"));
-
- VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("image/jpeg"), payload->getPhotoType());
- CPPUNIT_ASSERT_EQUAL(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"), payload->getPhoto());
- }
-
- void testParse_NewlinedPhoto() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<vCard xmlns='vcard-temp'>"
- "<PHOTO>"
- "<TYPE>image/jpeg</TYPE>"
- "<BINVAL>"
- "dTsETKSAskgu2/BqVO+ogcu3DJy4QATGJqpsa6znWwNGiLnVElVVB6PtS+mTiHUXsrOlKvRjtvzV\n"
- "VDknNaRF58Elmu5EC6VoCllBEEB/lFf0emYn2gkp0X1khNi75dl+rOj95Ar6XuwLh+ZoSStqwOWj\n"
- "pIpxmZmVw7E69qr0FY0oI3zcaxXwzHw7Lx9Qf4sH7ufQvIN88ga+hwp8MiXevh3Ac8pN00kgINlq\n"
- "9AY/bYJL418Y/6wWsJbgmrJ/N78wSMpC7VVszLBZVv8uFnupubyi8Ophd/1wIWWzPPwAbBhepWVb\n"
- "1oPiFEBT5MNKCMTPEi0npXtedVz0HQbbPNIVwmo="
- "</BINVAL>"
- "</PHOTO>"
- "</vCard>"));
-
- VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("image/jpeg"), payload->getPhotoType());
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x75\x3B\x04\x4C\xA4\x80\xB2\x48\x2E\xDB\xF0\x6A\x54\xEF\xA8\x81\xCB\xB7\x0C\x9C\xB8\x40\x04\xC6\x26\xAA\x6C\x6B\xAC\xE7\x5B\x03\x46\x88\xB9\xD5\x12\x55\x55\x07\xA3\xED\x4B\xE9\x93\x88\x75\x17\xB2\xB3\xA5\x2A\xF4\x63\xB6\xFC\xD5\x54\x39\x27\x35\xA4\x45\xE7\xC1\x25\x9A\xEE\x44\x0B\xA5\x68\x0A\x59\x41\x10\x40\x7F\x94\x57\xF4\x7A\x66\x27\xDA\x09\x29\xD1\x7D\x64\x84\xD8\xBB\xE5\xD9\x7E\xAC\xE8\xFD\xE4\x0A\xFA\x5E\xEC\x0B\x87\xE6\x68\x49\x2B\x6A\xC0\xE5\xA3\xA4\x8A\x71\x99\x99\x95\xC3\xB1\x3A\xF6\xAA\xF4\x15\x8D\x28\x23\x7C\xDC\x6B\x15\xF0\xCC\x7C\x3B\x2F\x1F\x50\x7F\x8B\x07\xEE\xE7\xD0\xBC\x83\x7C\xF2\x06\xBE\x87\x0A\x7C\x32\x25\xDE\xBE\x1D\xC0\x73\xCA\x4D\xD3\x49\x20\x20\xD9\x6A\xF4\x06\x3F\x6D\x82\x4B\xE3\x5F\x18\xFF\xAC\x16\xB0\x96\xE0\x9A\xB2\x7F\x37\xBF\x30\x48\xCA\x42\xED\x55\x6C\xCC\xB0\x59\x56\xFF\x2E\x16\x7B\xA9\xB9\xBC\xA2\xF0\xEA\x61\x77\xFD\x70\x21\x65\xB3\x3C\xFC\x00\x6C\x18\x5E\xA5\x65\x5B\xD6\x83\xE2\x14\x40\x53\xE4\xC3\x4A\x08\xC4\xCF\x12\x2D\x27\xA5\x7B\x5E\x75\x5C\xF4\x1D\x06\xDB\x3C\xD2\x15\xC2\x6A", 257), payload->getPhoto());
- }
-
-
-
- void testParse_Nickname() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse(
- "<vCard xmlns='vcard-temp'>"
- "<NICKNAME>mynick</NICKNAME>"
- "</vCard>"));
-
- VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("mynick"), payload->getNickname());
- }
+ CPPUNIT_TEST_SUITE(VCardParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Photo);
+ CPPUNIT_TEST(testParse_NewlinedPhoto);
+ CPPUNIT_TEST(testParse_Nickname);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<vCard xmlns=\"vcard-temp\">"
+ "<VERSION>2.0</VERSION>"
+ "<FN>Alice In Wonderland</FN>"
+ "<N>"
+ "<FAMILY>Wonderland</FAMILY>"
+ "<GIVEN>Alice</GIVEN>"
+ "<MIDDLE>In</MIDDLE>"
+ "<PREFIX>Mrs</PREFIX>"
+ "<SUFFIX>PhD</SUFFIX>"
+ "</N>"
+ "<EMAIL>"
+ "<USERID>alice@wonderland.lit</USERID>"
+ "<HOME/>"
+ "<INTERNET/>"
+ "<PREF/>"
+ "</EMAIL>"
+ "<EMAIL>"
+ "<USERID>alice@teaparty.lit</USERID>"
+ "<WORK/>"
+ "<X400/>"
+ "</EMAIL>"
+ "<TEL>"
+ "<NUMBER>555-6273</NUMBER>"
+ "<HOME/>"
+ "<VOICE/>"
+ "</TEL>"
+ "<ADR>"
+ "<LOCALITY>Any Town</LOCALITY>"
+ "<STREET>Fake Street 123</STREET>"
+ "<PCODE>12345</PCODE>"
+ "<CTRY>USA</CTRY>"
+ "<HOME/>"
+ "</ADR>"
+ "<LABEL>"
+ "<LINE>Fake Street 123</LINE>"
+ "<LINE>12345 Any Town</LINE>"
+ "<LINE>USA</LINE>"
+ "<HOME/>"
+ "</LABEL>"
+ "<NICKNAME>DreamGirl</NICKNAME>"
+ "<BDAY>1865-05-04</BDAY>"
+ "<JID>alice@teaparty.lit</JID>"
+ "<JID>alice@wonderland.lit</JID>"
+ "<DESC>I once fell down a rabbit hole.</DESC>"
+ "<ORG>"
+ "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>"
+ "</ORG>"
+ "<TITLE>Some Title</TITLE>"
+ "<ROLE>Main Character</ROLE>"
+ "<URL>http://wonderland.lit/~alice</URL>"
+ "<URL>http://teaparty.lit/~alice2</URL>"
+ "<MAILER>mutt</MAILER>"
+ "</vCard>"));
+
+ boost::shared_ptr<VCard> payload = boost::dynamic_pointer_cast<VCard>(parser.getPayload());
+ CPPUNIT_ASSERT_EQUAL(std::string("2.0"), payload->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), payload->getFullName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice"), payload->getGivenName());
+ CPPUNIT_ASSERT_EQUAL(std::string("In"), payload->getMiddleName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), payload->getFamilyName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Mrs"), payload->getPrefix());
+ CPPUNIT_ASSERT_EQUAL(std::string("PhD"), payload->getSuffix());
+ CPPUNIT_ASSERT_EQUAL(std::string("DreamGirl"), payload->getNickname());
+ CPPUNIT_ASSERT_EQUAL(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4)), payload->getBirthday());
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getEMailAddresses().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("alice@wonderland.lit"), payload->getEMailAddresses()[0].address);
+ CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isHome);
+ CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isInternet);
+ CPPUNIT_ASSERT(payload->getEMailAddresses()[0].isPreferred);
+ CPPUNIT_ASSERT(!payload->getEMailAddresses()[0].isWork);
+ CPPUNIT_ASSERT(!payload->getEMailAddresses()[0].isX400);
+ CPPUNIT_ASSERT_EQUAL(std::string("alice@teaparty.lit"), payload->getEMailAddresses()[1].address);
+ CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isHome);
+ CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isInternet);
+ CPPUNIT_ASSERT(!payload->getEMailAddresses()[1].isPreferred);
+ CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isWork);
+ CPPUNIT_ASSERT(payload->getEMailAddresses()[1].isX400);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTelephones().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("555-6273"), payload->getTelephones()[0].number);
+ CPPUNIT_ASSERT(payload->getTelephones()[0].isHome);
+ CPPUNIT_ASSERT(payload->getTelephones()[0].isVoice);
+ CPPUNIT_ASSERT(!payload->getTelephones()[0].isPreferred);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddresses().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Any Town"), payload->getAddresses()[0].locality);
+ CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddresses()[0].street);
+ CPPUNIT_ASSERT_EQUAL(std::string("12345"), payload->getAddresses()[0].postalCode);
+ CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddresses()[0].country);
+ CPPUNIT_ASSERT(payload->getAddresses()[0].isHome);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getAddressLabels().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Fake Street 123"), payload->getAddressLabels()[0].lines[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("12345 Any Town"), payload->getAddressLabels()[0].lines[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("USA"), payload->getAddressLabels()[0].lines[2]);
+ CPPUNIT_ASSERT(payload->getAddressLabels()[0].isHome);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getJIDs().size()));
+ CPPUNIT_ASSERT_EQUAL(JID("alice@teaparty.lit"), payload->getJIDs()[0]);
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit"), payload->getJIDs()[1]);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("I once fell down a rabbit hole."), payload->getDescription());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getOrganizations().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland Inc."), payload->getOrganizations()[0].name);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(payload->getOrganizations()[0].units.size()));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getTitles().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Some Title"), payload->getTitles()[0]);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(payload->getRoles().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Main Character"), payload->getRoles()[0]);
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(payload->getURLs().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("http://wonderland.lit/~alice"), payload->getURLs()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("http://teaparty.lit/~alice2"), payload->getURLs()[1]);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<MAILER xmlns=\"vcard-temp\">mutt</MAILER>"), payload->getUnknownContent());
+ }
+
+ void testParse_Photo() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<vCard xmlns='vcard-temp'>"
+ "<PHOTO>"
+ "<TYPE>image/jpeg</TYPE>"
+ "<BINVAL>"
+ "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ej"
+ "EyMzQ1Njc4OTA="
+ "</BINVAL>"
+ "</PHOTO>"
+ "</vCard>"));
+
+ VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("image/jpeg"), payload->getPhotoType());
+ CPPUNIT_ASSERT_EQUAL(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"), payload->getPhoto());
+ }
+
+ void testParse_NewlinedPhoto() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<vCard xmlns='vcard-temp'>"
+ "<PHOTO>"
+ "<TYPE>image/jpeg</TYPE>"
+ "<BINVAL>"
+ "dTsETKSAskgu2/BqVO+ogcu3DJy4QATGJqpsa6znWwNGiLnVElVVB6PtS+mTiHUXsrOlKvRjtvzV\n"
+ "VDknNaRF58Elmu5EC6VoCllBEEB/lFf0emYn2gkp0X1khNi75dl+rOj95Ar6XuwLh+ZoSStqwOWj\n"
+ "pIpxmZmVw7E69qr0FY0oI3zcaxXwzHw7Lx9Qf4sH7ufQvIN88ga+hwp8MiXevh3Ac8pN00kgINlq\n"
+ "9AY/bYJL418Y/6wWsJbgmrJ/N78wSMpC7VVszLBZVv8uFnupubyi8Ophd/1wIWWzPPwAbBhepWVb\n"
+ "1oPiFEBT5MNKCMTPEi0npXtedVz0HQbbPNIVwmo="
+ "</BINVAL>"
+ "</PHOTO>"
+ "</vCard>"));
+
+ VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("image/jpeg"), payload->getPhotoType());
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x75\x3B\x04\x4C\xA4\x80\xB2\x48\x2E\xDB\xF0\x6A\x54\xEF\xA8\x81\xCB\xB7\x0C\x9C\xB8\x40\x04\xC6\x26\xAA\x6C\x6B\xAC\xE7\x5B\x03\x46\x88\xB9\xD5\x12\x55\x55\x07\xA3\xED\x4B\xE9\x93\x88\x75\x17\xB2\xB3\xA5\x2A\xF4\x63\xB6\xFC\xD5\x54\x39\x27\x35\xA4\x45\xE7\xC1\x25\x9A\xEE\x44\x0B\xA5\x68\x0A\x59\x41\x10\x40\x7F\x94\x57\xF4\x7A\x66\x27\xDA\x09\x29\xD1\x7D\x64\x84\xD8\xBB\xE5\xD9\x7E\xAC\xE8\xFD\xE4\x0A\xFA\x5E\xEC\x0B\x87\xE6\x68\x49\x2B\x6A\xC0\xE5\xA3\xA4\x8A\x71\x99\x99\x95\xC3\xB1\x3A\xF6\xAA\xF4\x15\x8D\x28\x23\x7C\xDC\x6B\x15\xF0\xCC\x7C\x3B\x2F\x1F\x50\x7F\x8B\x07\xEE\xE7\xD0\xBC\x83\x7C\xF2\x06\xBE\x87\x0A\x7C\x32\x25\xDE\xBE\x1D\xC0\x73\xCA\x4D\xD3\x49\x20\x20\xD9\x6A\xF4\x06\x3F\x6D\x82\x4B\xE3\x5F\x18\xFF\xAC\x16\xB0\x96\xE0\x9A\xB2\x7F\x37\xBF\x30\x48\xCA\x42\xED\x55\x6C\xCC\xB0\x59\x56\xFF\x2E\x16\x7B\xA9\xB9\xBC\xA2\xF0\xEA\x61\x77\xFD\x70\x21\x65\xB3\x3C\xFC\x00\x6C\x18\x5E\xA5\x65\x5B\xD6\x83\xE2\x14\x40\x53\xE4\xC3\x4A\x08\xC4\xCF\x12\x2D\x27\xA5\x7B\x5E\x75\x5C\xF4\x1D\x06\xDB\x3C\xD2\x15\xC2\x6A", 257), payload->getPhoto());
+ }
+
+
+
+ void testParse_Nickname() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<vCard xmlns='vcard-temp'>"
+ "<NICKNAME>mynick</NICKNAME>"
+ "</vCard>"));
+
+ VCard* payload = dynamic_cast<VCard*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("mynick"), payload->getNickname());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp
index 7cf975a..11e8ded 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp
@@ -14,24 +14,24 @@ using namespace Swift;
class VCardUpdateParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(VCardUpdateParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(VCardUpdateParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
- public:
- VCardUpdateParserTest() {}
+ public:
+ VCardUpdateParserTest() {}
- void testParse() {
- PayloadsParserTester parser;
+ void testParse() {
+ PayloadsParserTester parser;
- CPPUNIT_ASSERT(parser.parse(
- "<x xmlns='vcard-temp:x:update'>"
- "<photo>sha1-hash-of-image</photo>"
- "</x>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<x xmlns='vcard-temp:x:update'>"
+ "<photo>sha1-hash-of-image</photo>"
+ "</x>"));
- VCardUpdate* payload = dynamic_cast<VCardUpdate*>(parser.getPayload().get());
- CPPUNIT_ASSERT_EQUAL(std::string("sha1-hash-of-image"), payload->getPhotoHash());
- }
+ VCardUpdate* payload = dynamic_cast<VCardUpdate*>(parser.getPayload().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("sha1-hash-of-image"), payload->getPhotoHash());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardUpdateParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UserLocationParser.cpp b/Swiften/Parser/PayloadParsers/UserLocationParser.cpp
index 4e98910..77a0fa1 100644
--- a/Swiften/Parser/PayloadParsers/UserLocationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/UserLocationParser.cpp
@@ -19,88 +19,88 @@ UserLocationParser::~UserLocationParser() {
}
void UserLocationParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- if (level == 1) {
- currentText = "";
- }
- ++level;
+ if (level == 1) {
+ currentText = "";
+ }
+ ++level;
}
void UserLocationParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (level == 1) {
- try {
- if (element == "accuracy") {
- getPayloadInternal()->setAccuracy(boost::lexical_cast<float>(currentText));
- }
- else if (element == "alt") {
- getPayloadInternal()->setAltitude(boost::lexical_cast<float>(currentText));
- }
- else if (element == "area") {
- getPayloadInternal()->setArea(currentText);
- }
- else if (element == "bearing") {
- getPayloadInternal()->setBearing(boost::lexical_cast<float>(currentText));
- }
- else if (element == "building") {
- getPayloadInternal()->setBuilding(currentText);
- }
- else if (element == "country") {
- getPayloadInternal()->setCountry(currentText);
- }
- else if (element == "countrycode") {
- getPayloadInternal()->setCountryCode(currentText);
- }
- else if (element == "datum") {
- getPayloadInternal()->setDatum(currentText);
- }
- else if (element == "description") {
- getPayloadInternal()->setDescription(currentText);
- }
- else if (element == "error") {
- getPayloadInternal()->setError(boost::lexical_cast<float>(currentText));
- }
- else if (element == "floor") {
- getPayloadInternal()->setFloor(currentText);
- }
- else if (element == "lat") {
- getPayloadInternal()->setLatitude(boost::lexical_cast<float>(currentText));
- }
- else if (element == "locality") {
- getPayloadInternal()->setLocality(currentText);
- }
- else if (element == "lon") {
- getPayloadInternal()->setLongitude(boost::lexical_cast<float>(currentText));
- }
- else if (element == "postalcode") {
- getPayloadInternal()->setPostalCode(currentText);
- }
- else if (element == "region") {
- getPayloadInternal()->setRegion(currentText);
- }
- else if (element == "room") {
- getPayloadInternal()->setRoom(currentText);
- }
- else if (element == "speed") {
- getPayloadInternal()->setSpeed(boost::lexical_cast<float>(currentText));
- }
- else if (element == "street") {
- getPayloadInternal()->setStreet(currentText);
- }
- else if (element == "text") {
- getPayloadInternal()->setText(currentText);
- }
- else if (element == "timestamp") {
- getPayloadInternal()->setTimestamp(stringToDateTime(currentText));
- }
- else if (element == "uri") {
- getPayloadInternal()->setURI(currentText);
- }
- }
- catch (const boost::bad_lexical_cast&) {
- }
- }
+ --level;
+ if (level == 1) {
+ try {
+ if (element == "accuracy") {
+ getPayloadInternal()->setAccuracy(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "alt") {
+ getPayloadInternal()->setAltitude(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "area") {
+ getPayloadInternal()->setArea(currentText);
+ }
+ else if (element == "bearing") {
+ getPayloadInternal()->setBearing(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "building") {
+ getPayloadInternal()->setBuilding(currentText);
+ }
+ else if (element == "country") {
+ getPayloadInternal()->setCountry(currentText);
+ }
+ else if (element == "countrycode") {
+ getPayloadInternal()->setCountryCode(currentText);
+ }
+ else if (element == "datum") {
+ getPayloadInternal()->setDatum(currentText);
+ }
+ else if (element == "description") {
+ getPayloadInternal()->setDescription(currentText);
+ }
+ else if (element == "error") {
+ getPayloadInternal()->setError(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "floor") {
+ getPayloadInternal()->setFloor(currentText);
+ }
+ else if (element == "lat") {
+ getPayloadInternal()->setLatitude(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "locality") {
+ getPayloadInternal()->setLocality(currentText);
+ }
+ else if (element == "lon") {
+ getPayloadInternal()->setLongitude(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "postalcode") {
+ getPayloadInternal()->setPostalCode(currentText);
+ }
+ else if (element == "region") {
+ getPayloadInternal()->setRegion(currentText);
+ }
+ else if (element == "room") {
+ getPayloadInternal()->setRoom(currentText);
+ }
+ else if (element == "speed") {
+ getPayloadInternal()->setSpeed(boost::lexical_cast<float>(currentText));
+ }
+ else if (element == "street") {
+ getPayloadInternal()->setStreet(currentText);
+ }
+ else if (element == "text") {
+ getPayloadInternal()->setText(currentText);
+ }
+ else if (element == "timestamp") {
+ getPayloadInternal()->setTimestamp(stringToDateTime(currentText));
+ }
+ else if (element == "uri") {
+ getPayloadInternal()->setURI(currentText);
+ }
+ }
+ catch (const boost::bad_lexical_cast&) {
+ }
+ }
}
void UserLocationParser::handleCharacterData(const std::string& data) {
- currentText += data;
+ currentText += data;
}
diff --git a/Swiften/Parser/PayloadParsers/UserLocationParser.h b/Swiften/Parser/PayloadParsers/UserLocationParser.h
index 5782dc0..c2a226e 100644
--- a/Swiften/Parser/PayloadParsers/UserLocationParser.h
+++ b/Swiften/Parser/PayloadParsers/UserLocationParser.h
@@ -16,17 +16,17 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API UserLocationParser : public GenericPayloadParser<UserLocation> {
- public:
- UserLocationParser();
- virtual ~UserLocationParser();
+ class SWIFTEN_API UserLocationParser : public GenericPayloadParser<UserLocation> {
+ public:
+ UserLocationParser();
+ virtual ~UserLocationParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- int level;
- std::string currentText;
- };
+ private:
+ int level;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/UserTuneParser.cpp b/Swiften/Parser/PayloadParsers/UserTuneParser.cpp
index f3f42ef..f030f8f 100644
--- a/Swiften/Parser/PayloadParsers/UserTuneParser.cpp
+++ b/Swiften/Parser/PayloadParsers/UserTuneParser.cpp
@@ -17,43 +17,43 @@ UserTuneParser::~UserTuneParser() {
}
void UserTuneParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- if (level == 1) {
- currentText = "";
- }
- ++level;
+ if (level == 1) {
+ currentText = "";
+ }
+ ++level;
}
void UserTuneParser::handleEndElement(const std::string& element, const std::string&) {
- --level;
- if (level == 1) {
- try {
- if (element == "artist") {
- getPayloadInternal()->setArtist(currentText);
- }
- else if (element == "length") {
- getPayloadInternal()->setLength(boost::lexical_cast<unsigned int>(currentText));
- }
- else if (element == "rating") {
- getPayloadInternal()->setRating(boost::lexical_cast<unsigned int>(currentText));
- }
- else if (element == "source") {
- getPayloadInternal()->setSource(currentText);
- }
- else if (element == "title") {
- getPayloadInternal()->setTitle(currentText);
- }
- else if (element == "track") {
- getPayloadInternal()->setTrack(currentText);
- }
- else if (element == "URI") {
- getPayloadInternal()->setURI(currentText);
- }
- }
- catch (const boost::bad_lexical_cast&) {
- }
- }
+ --level;
+ if (level == 1) {
+ try {
+ if (element == "artist") {
+ getPayloadInternal()->setArtist(currentText);
+ }
+ else if (element == "length") {
+ getPayloadInternal()->setLength(boost::lexical_cast<unsigned int>(currentText));
+ }
+ else if (element == "rating") {
+ getPayloadInternal()->setRating(boost::lexical_cast<unsigned int>(currentText));
+ }
+ else if (element == "source") {
+ getPayloadInternal()->setSource(currentText);
+ }
+ else if (element == "title") {
+ getPayloadInternal()->setTitle(currentText);
+ }
+ else if (element == "track") {
+ getPayloadInternal()->setTrack(currentText);
+ }
+ else if (element == "URI") {
+ getPayloadInternal()->setURI(currentText);
+ }
+ }
+ catch (const boost::bad_lexical_cast&) {
+ }
+ }
}
void UserTuneParser::handleCharacterData(const std::string& data) {
- currentText += data;
+ currentText += data;
}
diff --git a/Swiften/Parser/PayloadParsers/UserTuneParser.h b/Swiften/Parser/PayloadParsers/UserTuneParser.h
index b208784..5c35074 100644
--- a/Swiften/Parser/PayloadParsers/UserTuneParser.h
+++ b/Swiften/Parser/PayloadParsers/UserTuneParser.h
@@ -16,17 +16,17 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API UserTuneParser : public GenericPayloadParser<UserTune> {
- public:
- UserTuneParser();
- virtual ~UserTuneParser();
+ class SWIFTEN_API UserTuneParser : public GenericPayloadParser<UserTune> {
+ public:
+ UserTuneParser();
+ virtual ~UserTuneParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
- virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
- virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE;
+ virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE;
- private:
- int level;
- std::string currentText;
- };
+ private:
+ int level;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/VCardParser.cpp b/Swiften/Parser/PayloadParsers/VCardParser.cpp
index faf29d2..9f22c23 100644
--- a/Swiften/Parser/PayloadParsers/VCardParser.cpp
+++ b/Swiften/Parser/PayloadParsers/VCardParser.cpp
@@ -17,273 +17,273 @@ VCardParser::VCardParser() : unknownContentParser_(NULL) {
}
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);
- }
- else if (unknownContentParser_) {
- unknownContentParser_->handleStartElement(element, ns, 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);
+ }
+ else if (unknownContentParser_) {
+ unknownContentParser_->handleStartElement(element, ns, attributes);
+ }
- currentText_ = "";
+ currentText_ = "";
}
void VCardParser::handleEndElement(const std::string& element, const std::string& ns) {
- if (unknownContentParser_) {
- unknownContentParser_->handleEndElement(element, ns);
- }
+ if (unknownContentParser_) {
+ unknownContentParser_->handleEndElement(element, ns);
+ }
- std::string elementHierarchy = getElementHierarchy();
- if (elementHierarchy == "/vCard/VERSION") {
- getPayloadInternal()->setVersion(currentText_);
- }
- else if (elementHierarchy == "/vCard/FN") {
- getPayloadInternal()->setFullName(currentText_);
- }
- else if (elementHierarchy == "/vCard/N/FAMILY") {
- getPayloadInternal()->setFamilyName(currentText_);
- }
- else if (elementHierarchy == "/vCard/N/GIVEN") {
- getPayloadInternal()->setGivenName(currentText_);
- }
- else if (elementHierarchy == "/vCard/N/MIDDLE") {
- getPayloadInternal()->setMiddleName(currentText_);
- }
- else if (elementHierarchy == "/vCard/N/PREFIX") {
- getPayloadInternal()->setPrefix(currentText_);
- }
- else if (elementHierarchy == "/vCard/N/SUFFIX") {
- getPayloadInternal()->setSuffix(currentText_);
- }
- else if (elementHierarchy == "/vCard/N") {
- }
- else if (elementHierarchy == "/vCard/NICKNAME") {
- getPayloadInternal()->setNickname(currentText_);
- }
- else if (elementHierarchy == "/vCard/PHOTO/TYPE") {
- getPayloadInternal()->setPhotoType(currentText_);
- }
- else if (elementHierarchy == "/vCard/PHOTO/BINVAL") {
- currentText_.erase(std::remove(currentText_.begin(), currentText_.end(), '\n'), currentText_.end());
- currentText_.erase(std::remove(currentText_.begin(), currentText_.end(), '\r'), currentText_.end());
- getPayloadInternal()->setPhoto(Base64::decode(currentText_));
- }
- else if (elementHierarchy == "/vCard/PHOTO") {
- }
- else if (elementHierarchy == "/vCard/EMAIL/USERID") {
- currentEMailAddress_.address = currentText_;
- }
- else if (elementHierarchy == "/vCard/EMAIL/HOME") {
- currentEMailAddress_.isHome = true;
- }
- else if (elementHierarchy == "/vCard/EMAIL/WORK") {
- currentEMailAddress_.isWork = true;
- }
- else if (elementHierarchy == "/vCard/EMAIL/INTERNET") {
- currentEMailAddress_.isInternet = true;
- }
- else if (elementHierarchy == "/vCard/EMAIL/X400") {
- currentEMailAddress_.isX400 = true;
- }
- else if (elementHierarchy == "/vCard/EMAIL/PREF") {
- currentEMailAddress_.isPreferred = true;
- }
- else if (elementHierarchy == "/vCard/EMAIL" && !currentEMailAddress_.address.empty()) {
- getPayloadInternal()->addEMailAddress(currentEMailAddress_);
- }
- else if (elementHierarchy == "/vCard/BDAY" && !currentText_.empty()) {
- getPayloadInternal()->setBirthday(stringToDateTime(currentText_));
- }
- else if (elementHierarchy == "/vCard/TEL/NUMBER") {
- currentTelephone_.number = currentText_;
- }
- else if (elementHierarchy == "/vCard/TEL/HOME") {
- currentTelephone_.isHome = true;
- }
- else if (elementHierarchy == "/vCard/TEL/WORK") {
- currentTelephone_.isWork = true;
- }
- else if (elementHierarchy == "/vCard/TEL/VOICE") {
- currentTelephone_.isVoice = true;
- }
- else if (elementHierarchy == "/vCard/TEL/FAX") {
- currentTelephone_.isFax = true;
- }
- else if (elementHierarchy == "/vCard/TEL/PAGER") {
- currentTelephone_.isPager = true;
- }
- else if (elementHierarchy == "/vCard/TEL/MSG") {
- currentTelephone_.isMSG = true;
- }
- else if (elementHierarchy == "/vCard/TEL/CELL") {
- currentTelephone_.isCell = true;
- }
- else if (elementHierarchy == "/vCard/TEL/VIDEO") {
- currentTelephone_.isVideo = true;
- }
- else if (elementHierarchy == "/vCard/TEL/BBS") {
- currentTelephone_.isBBS = true;
- }
- else if (elementHierarchy == "/vCard/TEL/MODEM") {
- currentTelephone_.isModem = true;
- }
- else if (elementHierarchy == "/vCard/TEL/ISDN") {
- currentTelephone_.isISDN = true;
- }
- else if (elementHierarchy == "/vCard/TEL/PCS") {
- currentTelephone_.isPCS = true;
- }
- else if (elementHierarchy == "/vCard/TEL/PREF") {
- currentTelephone_.isPreferred = true;
- }
- else if (elementHierarchy == "/vCard/TEL" && !currentTelephone_.number.empty()) {
- getPayloadInternal()->addTelephone(currentTelephone_);
- }
- else if (elementHierarchy == "/vCard/ADR/HOME") {
- currentAddress_.isHome = true;
- }
- else if (elementHierarchy == "/vCard/ADR/WORK") {
- currentAddress_.isWork = true;
- }
- else if (elementHierarchy == "/vCard/ADR/POSTAL") {
- currentAddress_.isPostal = true;
- }
- else if (elementHierarchy == "/vCard/ADR/PARCEL") {
- currentAddress_.isParcel = true;
- }
- else if (elementHierarchy == "/vCard/ADR/DOM") {
- currentAddress_.deliveryType = VCard::DomesticDelivery;
- }
- else if (elementHierarchy == "/vCard/ADR/INTL") {
- currentAddress_.deliveryType = VCard::InternationalDelivery;
- }
- else if (elementHierarchy == "/vCard/ADR/PREF") {
- currentAddress_.isPreferred = true;
- }
- else if (elementHierarchy == "/vCard/ADR/POBOX") {
- currentAddress_.poBox = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/EXTADD") {
- currentAddress_.addressExtension = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/STREET") {
- currentAddress_.street = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/LOCALITY") {
- currentAddress_.locality = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/REGION") {
- currentAddress_.region = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/PCODE") {
- currentAddress_.postalCode = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR/CTRY") {
- currentAddress_.country = currentText_;
- }
- else if (elementHierarchy == "/vCard/ADR") {
- if (!currentAddress_.poBox.empty() || !currentAddress_.addressExtension.empty() ||
- !currentAddress_.street.empty() || !currentAddress_.locality.empty() ||
- !currentAddress_.region.empty() || !currentAddress_.region.empty() ||
- !currentAddress_.postalCode.empty() || !currentAddress_.country.empty()) {
- getPayloadInternal()->addAddress(currentAddress_);
- }
- }
- else if (elementHierarchy == "/vCard/LABEL/HOME") {
- currentAddressLabel_.isHome = true;
- }
- else if (elementHierarchy == "/vCard/LABEL/WORK") {
- currentAddressLabel_.isWork = true;
- }
- else if (elementHierarchy == "/vCard/LABEL/POSTAL") {
- currentAddressLabel_.isPostal = true;
- }
- else if (elementHierarchy == "/vCard/LABEL/PARCEL") {
- currentAddressLabel_.isParcel = true;
- }
- else if (elementHierarchy == "/vCard/LABEL/DOM") {
- currentAddressLabel_.deliveryType = VCard::DomesticDelivery;
- }
- else if (elementHierarchy == "/vCard/LABEL/INTL") {
- currentAddressLabel_.deliveryType = VCard::InternationalDelivery;
- }
- else if (elementHierarchy == "/vCard/LABEL/PREF") {
- currentAddressLabel_.isPreferred = true;
- }
- else if (elementHierarchy == "/vCard/LABEL/LINE") {
- currentAddressLabel_.lines.push_back(currentText_);
- }
- else if (elementHierarchy == "/vCard/LABEL") {
- getPayloadInternal()->addAddressLabel(currentAddressLabel_);
- }
- else if (elementHierarchy == "/vCard/JID" && !currentText_.empty()) {
- getPayloadInternal()->addJID(JID(currentText_));
- }
- else if (elementHierarchy == "/vCard/DESC") {
- getPayloadInternal()->setDescription(currentText_);
- }
- else if (elementHierarchy == "/vCard/ORG/ORGNAME") {
- currentOrganization_.name = currentText_;
- }
- else if (elementHierarchy == "/vCard/ORG/ORGUNIT" && !currentText_.empty()) {
- currentOrganization_.units.push_back(currentText_);
- }
- else if (elementHierarchy == "/vCard/ORG") {
- if (!currentOrganization_.name.empty() || !currentOrganization_.units.empty()) {
- getPayloadInternal()->addOrganization(currentOrganization_);
- }
- }
- 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());
- }
+ std::string elementHierarchy = getElementHierarchy();
+ if (elementHierarchy == "/vCard/VERSION") {
+ getPayloadInternal()->setVersion(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/FN") {
+ getPayloadInternal()->setFullName(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N/FAMILY") {
+ getPayloadInternal()->setFamilyName(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N/GIVEN") {
+ getPayloadInternal()->setGivenName(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N/MIDDLE") {
+ getPayloadInternal()->setMiddleName(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N/PREFIX") {
+ getPayloadInternal()->setPrefix(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N/SUFFIX") {
+ getPayloadInternal()->setSuffix(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/N") {
+ }
+ else if (elementHierarchy == "/vCard/NICKNAME") {
+ getPayloadInternal()->setNickname(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/PHOTO/TYPE") {
+ getPayloadInternal()->setPhotoType(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/PHOTO/BINVAL") {
+ currentText_.erase(std::remove(currentText_.begin(), currentText_.end(), '\n'), currentText_.end());
+ currentText_.erase(std::remove(currentText_.begin(), currentText_.end(), '\r'), currentText_.end());
+ getPayloadInternal()->setPhoto(Base64::decode(currentText_));
+ }
+ else if (elementHierarchy == "/vCard/PHOTO") {
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/USERID") {
+ currentEMailAddress_.address = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/HOME") {
+ currentEMailAddress_.isHome = true;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/WORK") {
+ currentEMailAddress_.isWork = true;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/INTERNET") {
+ currentEMailAddress_.isInternet = true;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/X400") {
+ currentEMailAddress_.isX400 = true;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL/PREF") {
+ currentEMailAddress_.isPreferred = true;
+ }
+ else if (elementHierarchy == "/vCard/EMAIL" && !currentEMailAddress_.address.empty()) {
+ getPayloadInternal()->addEMailAddress(currentEMailAddress_);
+ }
+ else if (elementHierarchy == "/vCard/BDAY" && !currentText_.empty()) {
+ getPayloadInternal()->setBirthday(stringToDateTime(currentText_));
+ }
+ else if (elementHierarchy == "/vCard/TEL/NUMBER") {
+ currentTelephone_.number = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/TEL/HOME") {
+ currentTelephone_.isHome = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/WORK") {
+ currentTelephone_.isWork = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/VOICE") {
+ currentTelephone_.isVoice = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/FAX") {
+ currentTelephone_.isFax = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/PAGER") {
+ currentTelephone_.isPager = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/MSG") {
+ currentTelephone_.isMSG = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/CELL") {
+ currentTelephone_.isCell = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/VIDEO") {
+ currentTelephone_.isVideo = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/BBS") {
+ currentTelephone_.isBBS = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/MODEM") {
+ currentTelephone_.isModem = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/ISDN") {
+ currentTelephone_.isISDN = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/PCS") {
+ currentTelephone_.isPCS = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL/PREF") {
+ currentTelephone_.isPreferred = true;
+ }
+ else if (elementHierarchy == "/vCard/TEL" && !currentTelephone_.number.empty()) {
+ getPayloadInternal()->addTelephone(currentTelephone_);
+ }
+ else if (elementHierarchy == "/vCard/ADR/HOME") {
+ currentAddress_.isHome = true;
+ }
+ else if (elementHierarchy == "/vCard/ADR/WORK") {
+ currentAddress_.isWork = true;
+ }
+ else if (elementHierarchy == "/vCard/ADR/POSTAL") {
+ currentAddress_.isPostal = true;
+ }
+ else if (elementHierarchy == "/vCard/ADR/PARCEL") {
+ currentAddress_.isParcel = true;
+ }
+ else if (elementHierarchy == "/vCard/ADR/DOM") {
+ currentAddress_.deliveryType = VCard::DomesticDelivery;
+ }
+ else if (elementHierarchy == "/vCard/ADR/INTL") {
+ currentAddress_.deliveryType = VCard::InternationalDelivery;
+ }
+ else if (elementHierarchy == "/vCard/ADR/PREF") {
+ currentAddress_.isPreferred = true;
+ }
+ else if (elementHierarchy == "/vCard/ADR/POBOX") {
+ currentAddress_.poBox = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/EXTADD") {
+ currentAddress_.addressExtension = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/STREET") {
+ currentAddress_.street = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/LOCALITY") {
+ currentAddress_.locality = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/REGION") {
+ currentAddress_.region = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/PCODE") {
+ currentAddress_.postalCode = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR/CTRY") {
+ currentAddress_.country = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ADR") {
+ if (!currentAddress_.poBox.empty() || !currentAddress_.addressExtension.empty() ||
+ !currentAddress_.street.empty() || !currentAddress_.locality.empty() ||
+ !currentAddress_.region.empty() || !currentAddress_.region.empty() ||
+ !currentAddress_.postalCode.empty() || !currentAddress_.country.empty()) {
+ getPayloadInternal()->addAddress(currentAddress_);
+ }
+ }
+ else if (elementHierarchy == "/vCard/LABEL/HOME") {
+ currentAddressLabel_.isHome = true;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/WORK") {
+ currentAddressLabel_.isWork = true;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/POSTAL") {
+ currentAddressLabel_.isPostal = true;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/PARCEL") {
+ currentAddressLabel_.isParcel = true;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/DOM") {
+ currentAddressLabel_.deliveryType = VCard::DomesticDelivery;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/INTL") {
+ currentAddressLabel_.deliveryType = VCard::InternationalDelivery;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/PREF") {
+ currentAddressLabel_.isPreferred = true;
+ }
+ else if (elementHierarchy == "/vCard/LABEL/LINE") {
+ currentAddressLabel_.lines.push_back(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/LABEL") {
+ getPayloadInternal()->addAddressLabel(currentAddressLabel_);
+ }
+ else if (elementHierarchy == "/vCard/JID" && !currentText_.empty()) {
+ getPayloadInternal()->addJID(JID(currentText_));
+ }
+ else if (elementHierarchy == "/vCard/DESC") {
+ getPayloadInternal()->setDescription(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/ORG/ORGNAME") {
+ currentOrganization_.name = currentText_;
+ }
+ else if (elementHierarchy == "/vCard/ORG/ORGUNIT" && !currentText_.empty()) {
+ currentOrganization_.units.push_back(currentText_);
+ }
+ else if (elementHierarchy == "/vCard/ORG") {
+ if (!currentOrganization_.name.empty() || !currentOrganization_.units.empty()) {
+ getPayloadInternal()->addOrganization(currentOrganization_);
+ }
+ }
+ 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_ = NULL;
- }
- elementStack_.pop_back();
+ if (elementStack_.size() == 2 && unknownContentParser_) {
+ delete unknownContentParser_;
+ unknownContentParser_ = NULL;
+ }
+ elementStack_.pop_back();
}
void VCardParser::handleCharacterData(const std::string& text) {
- if (unknownContentParser_) {
- unknownContentParser_->handleCharacterData(text);
- }
- currentText_ += text;
+ if (unknownContentParser_) {
+ unknownContentParser_->handleCharacterData(text);
+ }
+ currentText_ += text;
}
std::string VCardParser::getElementHierarchy() const {
- std::string result;
- foreach(const std::string& element, elementStack_) {
- result += "/" + element;
- }
- return result;
+ std::string result;
+ foreach(const std::string& element, elementStack_) {
+ result += "/" + element;
+ }
+ return result;
}
}
diff --git a/Swiften/Parser/PayloadParsers/VCardParser.h b/Swiften/Parser/PayloadParsers/VCardParser.h
index f0dbf06..5a47cbf 100644
--- a/Swiften/Parser/PayloadParsers/VCardParser.h
+++ b/Swiften/Parser/PayloadParsers/VCardParser.h
@@ -11,27 +11,27 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API VCardParser : public GenericPayloadParser<VCard> {
- public:
- VCardParser();
+ class SWIFTEN_API VCardParser : public GenericPayloadParser<VCard> {
+ public:
+ VCardParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- std::string getElementHierarchy() const;
+ private:
+ std::string getElementHierarchy() const;
- private:
- std::vector<std::string> elementStack_;
- VCard::EMailAddress currentEMailAddress_;
- VCard::Telephone currentTelephone_;
- VCard::Address currentAddress_;
- VCard::AddressLabel currentAddressLabel_;
- VCard::Organization currentOrganization_;
- SerializingParser* unknownContentParser_;
- std::string currentText_;
- };
+ private:
+ std::vector<std::string> elementStack_;
+ VCard::EMailAddress currentEMailAddress_;
+ VCard::Telephone currentTelephone_;
+ VCard::Address currentAddress_;
+ VCard::AddressLabel currentAddressLabel_;
+ VCard::Organization currentOrganization_;
+ SerializingParser* unknownContentParser_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp b/Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp
index 4e0cd47..64559ae 100644
--- a/Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp
@@ -12,21 +12,21 @@ VCardUpdateParser::VCardUpdateParser() : level_(TopLevel) {
}
void VCardUpdateParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- if (level_ == PayloadLevel) {
- currentText_ = "";
- }
- ++level_;
+ if (level_ == PayloadLevel) {
+ currentText_ = "";
+ }
+ ++level_;
}
void VCardUpdateParser::handleEndElement(const std::string& element, const std::string&) {
- --level_;
- if (level_ == PayloadLevel && element == "photo") {
- getPayloadInternal()->setPhotoHash(currentText_);
- }
+ --level_;
+ if (level_ == PayloadLevel && element == "photo") {
+ getPayloadInternal()->setPhotoHash(currentText_);
+ }
}
void VCardUpdateParser::handleCharacterData(const std::string& text) {
- currentText_ += text;
+ currentText_ += text;
}
}
diff --git a/Swiften/Parser/PayloadParsers/VCardUpdateParser.h b/Swiften/Parser/PayloadParsers/VCardUpdateParser.h
index cbd08e7..914f138 100644
--- a/Swiften/Parser/PayloadParsers/VCardUpdateParser.h
+++ b/Swiften/Parser/PayloadParsers/VCardUpdateParser.h
@@ -11,22 +11,22 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SerializingParser;
+ class SerializingParser;
- class SWIFTEN_API VCardUpdateParser : public GenericPayloadParser<VCardUpdate> {
- public:
- VCardUpdateParser();
+ class SWIFTEN_API VCardUpdateParser : public GenericPayloadParser<VCardUpdate> {
+ public:
+ VCardUpdateParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- PayloadLevel = 1
- };
- int level_;
- std::string currentText_;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ PayloadLevel = 1
+ };
+ int level_;
+ std::string currentText_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp b/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp
index 09f09e3..b9786c9 100644
--- a/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp
+++ b/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp
@@ -28,296 +28,296 @@
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
namespace Swift {
- WhiteboardParser::WhiteboardParser() : actualIsText(false), level_(0) {
- }
+ WhiteboardParser::WhiteboardParser() : actualIsText(false), level_(0) {
+ }
- void WhiteboardParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level_ == 0) {
- getPayloadInternal()->setType(stringToType(attributes.getAttributeValue("type").get_value_or("")));
- } else if (level_ == 1) {
- std::string type = attributes.getAttributeValue("type").get_value_or("");
- if (type == "insert") {
- WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
- operation = insertOp;
- } else if (type == "update") {
- WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
- std::string move = attributes.getAttributeValue("newpos").get_value_or("0");
- updateOp->setNewPos(boost::lexical_cast<int>(attributes.getAttributeValue("newpos").get_value_or("0")));
- operation = updateOp;
- } else if (type == "delete") {
- WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
- deleteOp->setElementID(attributes.getAttributeValue("elementid").get_value_or(""));
- operation = deleteOp;
- }
- if (operation) {
- try {
- operation->setID(attributes.getAttributeValue("id").get_value_or(""));
- operation->setParentID(attributes.getAttributeValue("parentid").get_value_or(""));
- operation->setPos(boost::lexical_cast<int>(attributes.getAttributeValue("pos").get_value_or("0")));
- } catch (boost::bad_lexical_cast&) {
- }
- }
+ void WhiteboardParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (level_ == 0) {
+ getPayloadInternal()->setType(stringToType(attributes.getAttributeValue("type").get_value_or("")));
+ } else if (level_ == 1) {
+ std::string type = attributes.getAttributeValue("type").get_value_or("");
+ if (type == "insert") {
+ WhiteboardInsertOperation::ref insertOp = boost::make_shared<WhiteboardInsertOperation>();
+ operation = insertOp;
+ } else if (type == "update") {
+ WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>();
+ std::string move = attributes.getAttributeValue("newpos").get_value_or("0");
+ updateOp->setNewPos(boost::lexical_cast<int>(attributes.getAttributeValue("newpos").get_value_or("0")));
+ operation = updateOp;
+ } else if (type == "delete") {
+ WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
+ deleteOp->setElementID(attributes.getAttributeValue("elementid").get_value_or(""));
+ operation = deleteOp;
+ }
+ if (operation) {
+ try {
+ operation->setID(attributes.getAttributeValue("id").get_value_or(""));
+ operation->setParentID(attributes.getAttributeValue("parentid").get_value_or(""));
+ operation->setPos(boost::lexical_cast<int>(attributes.getAttributeValue("pos").get_value_or("0")));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
- } else if (level_ == 2) {
- if (element == "line") {
- int x1 = 0;
- int y1 = 0;
- int x2 = 0;
- int y2 = 0;
- try {
- x1 = boost::lexical_cast<int>(attributes.getAttributeValue("x1").get_value_or("0"));
- y1 = boost::lexical_cast<int>(attributes.getAttributeValue("y1").get_value_or("0"));
- x2 = boost::lexical_cast<int>(attributes.getAttributeValue("x2").get_value_or("0"));
- y2 = boost::lexical_cast<int>(attributes.getAttributeValue("y2").get_value_or("0"));
- } catch (boost::bad_lexical_cast&) {
- }
- WhiteboardLineElement::ref whiteboardElement = boost::make_shared<WhiteboardLineElement>(x1, y1, x2, y2);
+ } else if (level_ == 2) {
+ if (element == "line") {
+ int x1 = 0;
+ int y1 = 0;
+ int x2 = 0;
+ int y2 = 0;
+ try {
+ x1 = boost::lexical_cast<int>(attributes.getAttributeValue("x1").get_value_or("0"));
+ y1 = boost::lexical_cast<int>(attributes.getAttributeValue("y1").get_value_or("0"));
+ x2 = boost::lexical_cast<int>(attributes.getAttributeValue("x2").get_value_or("0"));
+ y2 = boost::lexical_cast<int>(attributes.getAttributeValue("y2").get_value_or("0"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ WhiteboardLineElement::ref whiteboardElement = boost::make_shared<WhiteboardLineElement>(x1, y1, x2, y2);
- WhiteboardColor color(attributes.getAttributeValue("stroke").get_value_or("#000000"));
- color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- whiteboardElement->setColor(color);
+ WhiteboardColor color(attributes.getAttributeValue("stroke").get_value_or("#000000"));
+ color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ whiteboardElement->setColor(color);
- int penWidth = 1;
- try {
- penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setPenWidth(penWidth);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- } else if (element == "path") {
- WhiteboardFreehandPathElement::ref whiteboardElement = boost::make_shared<WhiteboardFreehandPathElement>();
- std::string pathData = attributes.getAttributeValue("d").get_value_or("");
- std::vector<std::pair<int, int> > points;
- if (pathData[0] == 'M') {
- size_t pos = 1;
- size_t npos;
- int x, y;
- if (pathData[pos] == ' ') {
- pos++;
- }
- try {
- npos = pathData.find(' ', pos);
- x = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
- pos = npos+1;
- npos = pathData.find('L', pos);
- y = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
- pos = npos+1;
- if (pathData[pos] == ' ') {
- pos++;
- }
- points.push_back(std::pair<int, int>(x, y));
- while (pos < pathData.size()) {
- npos = pathData.find(' ', pos);
- x = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
- pos = npos+1;
- npos = pathData.find(' ', pos);
- y = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
- pos = npos+1;
- points.push_back(std::pair<int, int>(x, y));
- }
- } catch (boost::bad_lexical_cast&) {
- }
- }
- whiteboardElement->setPoints(points);
+ int penWidth = 1;
+ try {
+ penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setPenWidth(penWidth);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ } else if (element == "path") {
+ WhiteboardFreehandPathElement::ref whiteboardElement = boost::make_shared<WhiteboardFreehandPathElement>();
+ std::string pathData = attributes.getAttributeValue("d").get_value_or("");
+ std::vector<std::pair<int, int> > points;
+ if (pathData[0] == 'M') {
+ size_t pos = 1;
+ size_t npos;
+ int x, y;
+ if (pathData[pos] == ' ') {
+ pos++;
+ }
+ try {
+ npos = pathData.find(' ', pos);
+ x = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
+ pos = npos+1;
+ npos = pathData.find('L', pos);
+ y = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
+ pos = npos+1;
+ if (pathData[pos] == ' ') {
+ pos++;
+ }
+ points.push_back(std::pair<int, int>(x, y));
+ while (pos < pathData.size()) {
+ npos = pathData.find(' ', pos);
+ x = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
+ pos = npos+1;
+ npos = pathData.find(' ', pos);
+ y = boost::lexical_cast<int>(pathData.substr(pos, npos-pos));
+ pos = npos+1;
+ points.push_back(std::pair<int, int>(x, y));
+ }
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+ whiteboardElement->setPoints(points);
- int penWidth = 1;
- try {
- penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setPenWidth(penWidth);
+ int penWidth = 1;
+ try {
+ penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setPenWidth(penWidth);
- WhiteboardColor color(attributes.getAttributeValue("stroke").get_value_or("#000000"));
- color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- whiteboardElement->setColor(color);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- } else if (element == "rect") {
- int x = 0;
- int y = 0;
- int width = 0;
- int height = 0;
- try {
- x = boost::lexical_cast<int>(attributes.getAttributeValue("x").get_value_or("0"));
- y = boost::lexical_cast<int>(attributes.getAttributeValue("y").get_value_or("0"));
- width = boost::lexical_cast<int>(attributes.getAttributeValue("width").get_value_or("0"));
- height = boost::lexical_cast<int>(attributes.getAttributeValue("height").get_value_or("0"));
- } catch (boost::bad_lexical_cast&) {
- }
+ WhiteboardColor color(attributes.getAttributeValue("stroke").get_value_or("#000000"));
+ color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ whiteboardElement->setColor(color);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ } else if (element == "rect") {
+ int x = 0;
+ int y = 0;
+ int width = 0;
+ int height = 0;
+ try {
+ x = boost::lexical_cast<int>(attributes.getAttributeValue("x").get_value_or("0"));
+ y = boost::lexical_cast<int>(attributes.getAttributeValue("y").get_value_or("0"));
+ width = boost::lexical_cast<int>(attributes.getAttributeValue("width").get_value_or("0"));
+ height = boost::lexical_cast<int>(attributes.getAttributeValue("height").get_value_or("0"));
+ } catch (boost::bad_lexical_cast&) {
+ }
- WhiteboardRectElement::ref whiteboardElement = boost::make_shared<WhiteboardRectElement>(x, y, width, height);
+ WhiteboardRectElement::ref whiteboardElement = boost::make_shared<WhiteboardRectElement>(x, y, width, height);
- int penWidth = 1;
- try {
- penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setPenWidth(penWidth);
+ int penWidth = 1;
+ try {
+ penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setPenWidth(penWidth);
- WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
- WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
- penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
- whiteboardElement->setPenColor(penColor);
- whiteboardElement->setBrushColor(brushColor);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- } else if (element == "polygon") {
- WhiteboardPolygonElement::ref whiteboardElement = boost::make_shared<WhiteboardPolygonElement>();
+ WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
+ WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
+ penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
+ whiteboardElement->setPenColor(penColor);
+ whiteboardElement->setBrushColor(brushColor);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ } else if (element == "polygon") {
+ WhiteboardPolygonElement::ref whiteboardElement = boost::make_shared<WhiteboardPolygonElement>();
- std::string pointsData = attributes.getAttributeValue("points").get_value_or("");
- std::vector<std::pair<int, int> > points;
- size_t pos = 0;
- size_t npos;
- int x, y;
- try {
- while (pos < pointsData.size()) {
- npos = pointsData.find(',', pos);
- x = boost::lexical_cast<int>(pointsData.substr(pos, npos-pos));
- pos = npos+1;
- npos = pointsData.find(' ', pos);
- y = boost::lexical_cast<int>(pointsData.substr(pos, npos-pos));
- pos = npos+1;
- points.push_back(std::pair<int, int>(x, y));
- }
- } catch (boost::bad_lexical_cast&) {
- }
+ std::string pointsData = attributes.getAttributeValue("points").get_value_or("");
+ std::vector<std::pair<int, int> > points;
+ size_t pos = 0;
+ size_t npos;
+ int x, y;
+ try {
+ while (pos < pointsData.size()) {
+ npos = pointsData.find(',', pos);
+ x = boost::lexical_cast<int>(pointsData.substr(pos, npos-pos));
+ pos = npos+1;
+ npos = pointsData.find(' ', pos);
+ y = boost::lexical_cast<int>(pointsData.substr(pos, npos-pos));
+ pos = npos+1;
+ points.push_back(std::pair<int, int>(x, y));
+ }
+ } catch (boost::bad_lexical_cast&) {
+ }
- whiteboardElement->setPoints(points);
+ whiteboardElement->setPoints(points);
- int penWidth = 1;
- try {
- penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setPenWidth(penWidth);
+ int penWidth = 1;
+ try {
+ penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setPenWidth(penWidth);
- WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
- WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
- penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
- whiteboardElement->setPenColor(penColor);
- whiteboardElement->setBrushColor(brushColor);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- } else if (element == "text") {
- int x = 0;
- int y = 0;
- try {
- x = boost::lexical_cast<int>(attributes.getAttributeValue("x").get_value_or("0"));
- y = boost::lexical_cast<int>(attributes.getAttributeValue("y").get_value_or("0"));
- } catch (boost::bad_lexical_cast&) {
- }
+ WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
+ WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
+ penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
+ whiteboardElement->setPenColor(penColor);
+ whiteboardElement->setBrushColor(brushColor);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ } else if (element == "text") {
+ int x = 0;
+ int y = 0;
+ try {
+ x = boost::lexical_cast<int>(attributes.getAttributeValue("x").get_value_or("0"));
+ y = boost::lexical_cast<int>(attributes.getAttributeValue("y").get_value_or("0"));
+ } catch (boost::bad_lexical_cast&) {
+ }
- WhiteboardTextElement::ref whiteboardElement = boost::make_shared<WhiteboardTextElement>(x, y);
+ WhiteboardTextElement::ref whiteboardElement = boost::make_shared<WhiteboardTextElement>(x, y);
- actualIsText = true;
- WhiteboardColor color(attributes.getAttributeValue("fill").get_value_or("#000000"));
- color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- whiteboardElement->setColor(color);
+ actualIsText = true;
+ WhiteboardColor color(attributes.getAttributeValue("fill").get_value_or("#000000"));
+ color.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ whiteboardElement->setColor(color);
- int fontSize = 1;
- try {
- fontSize = boost::lexical_cast<int>(attributes.getAttributeValue("font-size").get_value_or("12"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setSize(fontSize);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- } else if (element == "ellipse") {
- int cx = 0;
- int cy = 0;
- int rx = 0;
- int ry = 0;
- try {
- cx = boost::lexical_cast<int>(attributes.getAttributeValue("cx").get_value_or("0"));
- cy = boost::lexical_cast<int>(attributes.getAttributeValue("cy").get_value_or("0"));
- rx = boost::lexical_cast<int>(attributes.getAttributeValue("rx").get_value_or("0"));
- ry = boost::lexical_cast<int>(attributes.getAttributeValue("ry").get_value_or("0"));
- } catch (boost::bad_lexical_cast&) {
- }
+ int fontSize = 1;
+ try {
+ fontSize = boost::lexical_cast<int>(attributes.getAttributeValue("font-size").get_value_or("12"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setSize(fontSize);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ } else if (element == "ellipse") {
+ int cx = 0;
+ int cy = 0;
+ int rx = 0;
+ int ry = 0;
+ try {
+ cx = boost::lexical_cast<int>(attributes.getAttributeValue("cx").get_value_or("0"));
+ cy = boost::lexical_cast<int>(attributes.getAttributeValue("cy").get_value_or("0"));
+ rx = boost::lexical_cast<int>(attributes.getAttributeValue("rx").get_value_or("0"));
+ ry = boost::lexical_cast<int>(attributes.getAttributeValue("ry").get_value_or("0"));
+ } catch (boost::bad_lexical_cast&) {
+ }
- WhiteboardEllipseElement::ref whiteboardElement = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
+ WhiteboardEllipseElement::ref whiteboardElement = boost::make_shared<WhiteboardEllipseElement>(cx, cy, rx, ry);
- int penWidth = 1;
- try {
- penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
- } catch (boost::bad_lexical_cast&) {
- }
- whiteboardElement->setPenWidth(penWidth);
+ int penWidth = 1;
+ try {
+ penWidth = boost::lexical_cast<int>(attributes.getAttributeValue("stroke-width").get_value_or("1"));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ whiteboardElement->setPenWidth(penWidth);
- WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
- WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
- penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
- brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
- whiteboardElement->setPenColor(penColor);
- whiteboardElement->setBrushColor(brushColor);
- whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
- getPayloadInternal()->setElement(whiteboardElement);
- wbElement = whiteboardElement;
- }
- }
- ++level_;
- }
+ WhiteboardColor penColor(attributes.getAttributeValue("stroke").get_value_or("#000000"));
+ WhiteboardColor brushColor(attributes.getAttributeValue("fill").get_value_or("#000000"));
+ penColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("opacity").get_value_or("1")));
+ brushColor.setAlpha(opacityToAlpha(attributes.getAttributeValue("fill-opacity").get_value_or("1")));
+ whiteboardElement->setPenColor(penColor);
+ whiteboardElement->setBrushColor(brushColor);
+ whiteboardElement->setID(attributes.getAttributeValue("id").get_value_or(""));
+ getPayloadInternal()->setElement(whiteboardElement);
+ wbElement = whiteboardElement;
+ }
+ }
+ ++level_;
+ }
- void WhiteboardParser::handleEndElement(const std::string& element, const std::string&) {
- --level_;
- if (level_ == 0) {
- getPayloadInternal()->setData(data_);
- } else if (level_ == 1) {
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- insertOp->setElement(wbElement);
- }
+ void WhiteboardParser::handleEndElement(const std::string& element, const std::string&) {
+ --level_;
+ if (level_ == 0) {
+ getPayloadInternal()->setData(data_);
+ } else if (level_ == 1) {
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ insertOp->setElement(wbElement);
+ }
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- updateOp->setElement(wbElement);
- }
- getPayloadInternal()->setOperation(operation);
- } else if (level_ == 2) {
- if (element == "text") {
- actualIsText = false;
- }
- }
- }
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ updateOp->setElement(wbElement);
+ }
+ getPayloadInternal()->setOperation(operation);
+ } else if (level_ == 2) {
+ if (element == "text") {
+ actualIsText = false;
+ }
+ }
+ }
- void WhiteboardParser::handleCharacterData(const std::string& data) {
- if (level_ == 3 && actualIsText) {
- WhiteboardTextElement::ref element = boost::dynamic_pointer_cast<WhiteboardTextElement>(getPayloadInternal()->getElement());
- element->setText(data);
- }
- }
+ void WhiteboardParser::handleCharacterData(const std::string& data) {
+ if (level_ == 3 && actualIsText) {
+ WhiteboardTextElement::ref element = boost::dynamic_pointer_cast<WhiteboardTextElement>(getPayloadInternal()->getElement());
+ element->setText(data);
+ }
+ }
- WhiteboardPayload::Type WhiteboardParser::stringToType(const std::string& type) const {
- if (type == "data") {
- return WhiteboardPayload::Data;
- } else if (type == "session-request") {
- return WhiteboardPayload::SessionRequest;
- } else if (type == "session-accept") {
- return WhiteboardPayload::SessionAccept;
- } else if (type == "session-terminate") {
- return WhiteboardPayload::SessionTerminate;
- } else {
- return WhiteboardPayload::UnknownType;
- }
- }
+ WhiteboardPayload::Type WhiteboardParser::stringToType(const std::string& type) const {
+ if (type == "data") {
+ return WhiteboardPayload::Data;
+ } else if (type == "session-request") {
+ return WhiteboardPayload::SessionRequest;
+ } else if (type == "session-accept") {
+ return WhiteboardPayload::SessionAccept;
+ } else if (type == "session-terminate") {
+ return WhiteboardPayload::SessionTerminate;
+ } else {
+ return WhiteboardPayload::UnknownType;
+ }
+ }
- int WhiteboardParser::opacityToAlpha(std::string opacity) const {
- int value = 255;
- if (opacity.find('.') != std::string::npos) {
- opacity = opacity.substr(opacity.find('.')+1, 2);
- try {
- value = boost::lexical_cast<int>(opacity)*255/100;
- } catch (boost::bad_lexical_cast&) {
- }
- }
- return value;
- }
+ int WhiteboardParser::opacityToAlpha(std::string opacity) const {
+ int value = 255;
+ if (opacity.find('.') != std::string::npos) {
+ opacity = opacity.substr(opacity.find('.')+1, 2);
+ try {
+ value = boost::lexical_cast<int>(opacity)*255/100;
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+ return value;
+ }
}
diff --git a/Swiften/Parser/PayloadParsers/WhiteboardParser.h b/Swiften/Parser/PayloadParsers/WhiteboardParser.h
index 55a997d..2f22624 100644
--- a/Swiften/Parser/PayloadParsers/WhiteboardParser.h
+++ b/Swiften/Parser/PayloadParsers/WhiteboardParser.h
@@ -19,23 +19,23 @@
#include <Swiften/Parser/GenericPayloadParser.h>
namespace Swift {
- class SWIFTEN_API WhiteboardParser : public Swift::GenericPayloadParser<WhiteboardPayload> {
- public:
- WhiteboardParser();
+ class SWIFTEN_API WhiteboardParser : public Swift::GenericPayloadParser<WhiteboardPayload> {
+ public:
+ WhiteboardParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- WhiteboardPayload::Type stringToType(const std::string& type) const;
- int opacityToAlpha(std::string opacity) const;
+ private:
+ WhiteboardPayload::Type stringToType(const std::string& type) const;
+ int opacityToAlpha(std::string opacity) const;
- private:
- bool actualIsText;
- int level_;
- std::string data_;
- WhiteboardElement::ref wbElement;
- WhiteboardOperation::ref operation;
- };
+ private:
+ bool actualIsText;
+ int level_;
+ std::string data_;
+ WhiteboardElement::ref wbElement;
+ WhiteboardOperation::ref operation;
+ };
}
diff --git a/Swiften/Parser/PlatformXMLParserFactory.cpp b/Swiften/Parser/PlatformXMLParserFactory.cpp
index 924ef59..87f70d1 100644
--- a/Swiften/Parser/PlatformXMLParserFactory.cpp
+++ b/Swiften/Parser/PlatformXMLParserFactory.cpp
@@ -22,9 +22,9 @@ PlatformXMLParserFactory::PlatformXMLParserFactory() {
XMLParser* PlatformXMLParserFactory::createXMLParser(XMLParserClient* client) {
#ifdef HAVE_LIBXML
- return new LibXMLParser(client);
+ return new LibXMLParser(client);
#else
- return new ExpatParser(client);
+ return new ExpatParser(client);
#endif
}
diff --git a/Swiften/Parser/PlatformXMLParserFactory.h b/Swiften/Parser/PlatformXMLParserFactory.h
index 2422ded..82b8573 100644
--- a/Swiften/Parser/PlatformXMLParserFactory.h
+++ b/Swiften/Parser/PlatformXMLParserFactory.h
@@ -10,10 +10,10 @@
#include <Swiften/Parser/XMLParserFactory.h>
namespace Swift {
- class SWIFTEN_API PlatformXMLParserFactory : public XMLParserFactory {
- public:
- PlatformXMLParserFactory();
+ class SWIFTEN_API PlatformXMLParserFactory : public XMLParserFactory {
+ public:
+ PlatformXMLParserFactory();
- virtual XMLParser* createXMLParser(XMLParserClient*);
- };
+ virtual XMLParser* createXMLParser(XMLParserClient*);
+ };
}
diff --git a/Swiften/Parser/PresenceParser.cpp b/Swiften/Parser/PresenceParser.cpp
index 6d6424e..4a27a24 100644
--- a/Swiften/Parser/PresenceParser.cpp
+++ b/Swiften/Parser/PresenceParser.cpp
@@ -12,42 +12,42 @@
namespace Swift {
-PresenceParser::PresenceParser(PayloadParserFactoryCollection* factories) :
- GenericStanzaParser<Presence>(factories) {
+PresenceParser::PresenceParser(PayloadParserFactoryCollection* factories) :
+ GenericStanzaParser<Presence>(factories) {
}
void PresenceParser::handleStanzaAttributes(const AttributeMap& attributes) {
- boost::optional<std::string> type = attributes.getAttributeValue("type");
- if (type) {
- if (*type == "unavailable") {
- getStanzaGeneric()->setType(Presence::Unavailable);
- }
- else if (*type == "probe") {
- getStanzaGeneric()->setType(Presence::Probe);
- }
- else if (*type == "subscribe") {
- getStanzaGeneric()->setType(Presence::Subscribe);
- }
- else if (*type == "subscribed") {
- getStanzaGeneric()->setType(Presence::Subscribed);
- }
- else if (*type == "unsubscribe") {
- getStanzaGeneric()->setType(Presence::Unsubscribe);
- }
- else if (*type == "unsubscribed") {
- getStanzaGeneric()->setType(Presence::Unsubscribed);
- }
- else if (*type == "error") {
- getStanzaGeneric()->setType(Presence::Error);
- }
- else {
- std::cerr << "Unknown Presence type: " << *type << std::endl;
- getStanzaGeneric()->setType(Presence::Available);
- }
- }
- else {
- getStanzaGeneric()->setType(Presence::Available);
- }
+ boost::optional<std::string> type = attributes.getAttributeValue("type");
+ if (type) {
+ if (*type == "unavailable") {
+ getStanzaGeneric()->setType(Presence::Unavailable);
+ }
+ else if (*type == "probe") {
+ getStanzaGeneric()->setType(Presence::Probe);
+ }
+ else if (*type == "subscribe") {
+ getStanzaGeneric()->setType(Presence::Subscribe);
+ }
+ else if (*type == "subscribed") {
+ getStanzaGeneric()->setType(Presence::Subscribed);
+ }
+ else if (*type == "unsubscribe") {
+ getStanzaGeneric()->setType(Presence::Unsubscribe);
+ }
+ else if (*type == "unsubscribed") {
+ getStanzaGeneric()->setType(Presence::Unsubscribed);
+ }
+ else if (*type == "error") {
+ getStanzaGeneric()->setType(Presence::Error);
+ }
+ else {
+ std::cerr << "Unknown Presence type: " << *type << std::endl;
+ getStanzaGeneric()->setType(Presence::Available);
+ }
+ }
+ else {
+ getStanzaGeneric()->setType(Presence::Available);
+ }
}
}
diff --git a/Swiften/Parser/PresenceParser.h b/Swiften/Parser/PresenceParser.h
index 60d5490..76753f8 100644
--- a/Swiften/Parser/PresenceParser.h
+++ b/Swiften/Parser/PresenceParser.h
@@ -11,11 +11,11 @@
#include <Swiften/Parser/GenericStanzaParser.h>
namespace Swift {
- class SWIFTEN_API PresenceParser : public GenericStanzaParser<Presence> {
- public:
- PresenceParser(PayloadParserFactoryCollection* factories);
+ class SWIFTEN_API PresenceParser : public GenericStanzaParser<Presence> {
+ public:
+ PresenceParser(PayloadParserFactoryCollection* factories);
- private:
- virtual void handleStanzaAttributes(const AttributeMap&);
- };
+ private:
+ virtual void handleStanzaAttributes(const AttributeMap&);
+ };
}
diff --git a/Swiften/Parser/SerializingParser.cpp b/Swiften/Parser/SerializingParser.cpp
index e939c9f..b58ccd6 100644
--- a/Swiften/Parser/SerializingParser.cpp
+++ b/Swiften/Parser/SerializingParser.cpp
@@ -17,34 +17,34 @@ SerializingParser::SerializingParser() {
}
void SerializingParser::handleStartElement(const std::string& tag, const std::string& ns, const AttributeMap& attributes) {
- boost::shared_ptr<XMLElement> element = boost::make_shared<XMLElement>(tag, ns);
- // FIXME: Ignoring attribute namespace
- foreach (const AttributeMap::Entry& 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);
+ boost::shared_ptr<XMLElement> element = boost::make_shared<XMLElement>(tag, ns);
+ // FIXME: Ignoring attribute namespace
+ foreach (const AttributeMap::Entry& 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();
+ assert(!elementStack_.empty());
+ elementStack_.pop_back();
}
void SerializingParser::handleCharacterData(const std::string& data) {
- if (!elementStack_.empty()) {
- (*(elementStack_.end()-1))->addNode(boost::make_shared<XMLTextNode>(data));
- }
+ if (!elementStack_.empty()) {
+ (*(elementStack_.end()-1))->addNode(boost::make_shared<XMLTextNode>(data));
+ }
}
std::string SerializingParser::getResult() const {
- return (rootElement_ ? rootElement_->serialize() : "");
+ return (rootElement_ ? rootElement_->serialize() : "");
}
}
diff --git a/Swiften/Parser/SerializingParser.h b/Swiften/Parser/SerializingParser.h
index ba6cc80..b94d2b8 100644
--- a/Swiften/Parser/SerializingParser.h
+++ b/Swiften/Parser/SerializingParser.h
@@ -13,18 +13,18 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API SerializingParser {
- public:
- SerializingParser();
+ class SWIFTEN_API SerializingParser {
+ public:
+ SerializingParser();
- void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- void handleEndElement(const std::string& element, const std::string& ns);
- void handleCharacterData(const std::string& data);
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
- std::string getResult() const;
+ std::string getResult() const;
- private:
- std::vector< boost::shared_ptr<XMLElement> > elementStack_;
- boost::shared_ptr<XMLElement> rootElement_;
- };
+ private:
+ std::vector< boost::shared_ptr<XMLElement> > elementStack_;
+ boost::shared_ptr<XMLElement> rootElement_;
+ };
}
diff --git a/Swiften/Parser/StanzaAckParser.cpp b/Swiften/Parser/StanzaAckParser.cpp
index b4fd1c1..de0287e 100644
--- a/Swiften/Parser/StanzaAckParser.cpp
+++ b/Swiften/Parser/StanzaAckParser.cpp
@@ -14,19 +14,19 @@ StanzaAckParser::StanzaAckParser() : GenericElementParser<StanzaAck>(), depth(0)
}
void StanzaAckParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (depth == 0) {
- std::string handledStanzasString = attributes.getAttribute("h");
- try {
- getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<int>(handledStanzasString));
- }
- catch (const boost::bad_lexical_cast &) {
- }
- }
- ++depth;
+ if (depth == 0) {
+ std::string handledStanzasString = attributes.getAttribute("h");
+ try {
+ getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<int>(handledStanzasString));
+ }
+ catch (const boost::bad_lexical_cast &) {
+ }
+ }
+ ++depth;
}
void StanzaAckParser::handleEndElement(const std::string&, const std::string&) {
- --depth;
+ --depth;
}
}
diff --git a/Swiften/Parser/StanzaAckParser.h b/Swiften/Parser/StanzaAckParser.h
index c0e5d83..7e5a75f 100644
--- a/Swiften/Parser/StanzaAckParser.h
+++ b/Swiften/Parser/StanzaAckParser.h
@@ -11,14 +11,14 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StanzaAckParser : public GenericElementParser<StanzaAck> {
- public:
- StanzaAckParser();
+ class SWIFTEN_API StanzaAckParser : public GenericElementParser<StanzaAck> {
+ public:
+ StanzaAckParser();
- virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string& ns);
+ virtual void handleStartElement(const std::string&, const std::string& ns, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string& ns);
- private:
- int depth;
- };
+ private:
+ int depth;
+ };
}
diff --git a/Swiften/Parser/StanzaAckRequestParser.h b/Swiften/Parser/StanzaAckRequestParser.h
index 603eefc..9766e98 100644
--- a/Swiften/Parser/StanzaAckRequestParser.h
+++ b/Swiften/Parser/StanzaAckRequestParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StanzaAckRequestParser : public GenericElementParser<StanzaAckRequest> {
- public:
- StanzaAckRequestParser() : GenericElementParser<StanzaAckRequest>() {}
- };
+ class SWIFTEN_API StanzaAckRequestParser : public GenericElementParser<StanzaAckRequest> {
+ public:
+ StanzaAckRequestParser() : GenericElementParser<StanzaAckRequest>() {}
+ };
}
diff --git a/Swiften/Parser/StanzaParser.cpp b/Swiften/Parser/StanzaParser.cpp
index 5b06af1..82ddb5c 100644
--- a/Swiften/Parser/StanzaParser.cpp
+++ b/Swiften/Parser/StanzaParser.cpp
@@ -18,69 +18,69 @@
namespace Swift {
-StanzaParser::StanzaParser(PayloadParserFactoryCollection* factories) :
- currentDepth_(0), factories_(factories) {
+StanzaParser::StanzaParser(PayloadParserFactoryCollection* factories) :
+ currentDepth_(0), factories_(factories) {
}
StanzaParser::~StanzaParser() {
}
void StanzaParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (inStanza()) {
- if (!inPayload()) {
- assert(!currentPayloadParser_);
- PayloadParserFactory* payloadParserFactory = factories_->getPayloadParserFactory(element, ns, attributes);
- if (payloadParserFactory) {
- currentPayloadParser_.reset(payloadParserFactory->createPayloadParser());
- }
- else {
- currentPayloadParser_.reset(new UnknownPayloadParser());
- }
- }
- assert(currentPayloadParser_);
- currentPayloadParser_->handleStartElement(element, ns, attributes);
- }
- else {
- boost::optional<std::string> from = attributes.getAttributeValue("from");
- if (from) {
- getStanza()->setFrom(JID(*from));
- }
- boost::optional<std::string> to = attributes.getAttributeValue("to");
- if (to) {
- getStanza()->setTo(JID(*to));
- }
- boost::optional<std::string> id = attributes.getAttributeValue("id");
- if (id) {
- getStanza()->setID(*id);
- }
- handleStanzaAttributes(attributes);
- }
- ++currentDepth_;
+ if (inStanza()) {
+ if (!inPayload()) {
+ assert(!currentPayloadParser_);
+ PayloadParserFactory* payloadParserFactory = factories_->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser_.reset(payloadParserFactory->createPayloadParser());
+ }
+ else {
+ currentPayloadParser_.reset(new UnknownPayloadParser());
+ }
+ }
+ assert(currentPayloadParser_);
+ currentPayloadParser_->handleStartElement(element, ns, attributes);
+ }
+ else {
+ boost::optional<std::string> from = attributes.getAttributeValue("from");
+ if (from) {
+ getStanza()->setFrom(JID(*from));
+ }
+ boost::optional<std::string> to = attributes.getAttributeValue("to");
+ if (to) {
+ getStanza()->setTo(JID(*to));
+ }
+ boost::optional<std::string> id = attributes.getAttributeValue("id");
+ if (id) {
+ getStanza()->setID(*id);
+ }
+ handleStanzaAttributes(attributes);
+ }
+ ++currentDepth_;
}
void StanzaParser::handleEndElement(const std::string& element, const std::string& ns) {
- assert(inStanza());
- if (inPayload()) {
- assert(currentPayloadParser_);
- currentPayloadParser_->handleEndElement(element, ns);
- --currentDepth_;
- if (!inPayload()) {
- boost::shared_ptr<Payload> payload(currentPayloadParser_->getPayload());
- if (payload) {
- getStanza()->addPayload(payload);
- }
- currentPayloadParser_.reset();
- }
- }
- else {
- --currentDepth_;
- }
+ assert(inStanza());
+ if (inPayload()) {
+ assert(currentPayloadParser_);
+ currentPayloadParser_->handleEndElement(element, ns);
+ --currentDepth_;
+ if (!inPayload()) {
+ boost::shared_ptr<Payload> payload(currentPayloadParser_->getPayload());
+ if (payload) {
+ getStanza()->addPayload(payload);
+ }
+ currentPayloadParser_.reset();
+ }
+ }
+ else {
+ --currentDepth_;
+ }
}
void StanzaParser::handleCharacterData(const std::string& data) {
- if (currentPayloadParser_) {
- currentPayloadParser_->handleCharacterData(data);
- }
+ if (currentPayloadParser_) {
+ currentPayloadParser_->handleCharacterData(data);
+ }
}
}
diff --git a/Swiften/Parser/StanzaParser.h b/Swiften/Parser/StanzaParser.h
index 0d8016b..866df04 100644
--- a/Swiften/Parser/StanzaParser.h
+++ b/Swiften/Parser/StanzaParser.h
@@ -17,38 +17,38 @@
#include <Swiften/Parser/ElementParser.h>
namespace Swift {
- class PayloadParser;
- class PayloadParserFactoryCollection;
+ class PayloadParser;
+ class PayloadParserFactoryCollection;
- class SWIFTEN_API StanzaParser : public ElementParser, public boost::noncopyable {
- public:
- StanzaParser(PayloadParserFactoryCollection* factories);
- ~StanzaParser();
+ class SWIFTEN_API StanzaParser : public ElementParser, public boost::noncopyable {
+ public:
+ StanzaParser(PayloadParserFactoryCollection* factories);
+ ~StanzaParser();
- void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- void handleEndElement(const std::string& element, const std::string& ns);
- void handleCharacterData(const std::string& data);
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
- virtual boost::shared_ptr<ToplevelElement> getElement() const = 0;
- virtual void handleStanzaAttributes(const AttributeMap&) {}
+ virtual boost::shared_ptr<ToplevelElement> getElement() const = 0;
+ virtual void handleStanzaAttributes(const AttributeMap&) {}
- virtual boost::shared_ptr<Stanza> getStanza() const {
- return boost::dynamic_pointer_cast<Stanza>(getElement());
- }
+ virtual boost::shared_ptr<Stanza> getStanza() const {
+ return boost::dynamic_pointer_cast<Stanza>(getElement());
+ }
- private:
- bool inPayload() const {
- return currentDepth_ > 1;
- }
+ private:
+ bool inPayload() const {
+ return currentDepth_ > 1;
+ }
- bool inStanza() const {
- return currentDepth_ > 0;
- }
+ bool inStanza() const {
+ return currentDepth_ > 0;
+ }
- private:
- int currentDepth_;
- PayloadParserFactoryCollection* factories_;
- boost::shared_ptr<PayloadParser> currentPayloadParser_;
- };
+ private:
+ int currentDepth_;
+ PayloadParserFactoryCollection* factories_;
+ boost::shared_ptr<PayloadParser> currentPayloadParser_;
+ };
}
diff --git a/Swiften/Parser/StartTLSFailureParser.h b/Swiften/Parser/StartTLSFailureParser.h
index 3ff4b69..2f13e71 100644
--- a/Swiften/Parser/StartTLSFailureParser.h
+++ b/Swiften/Parser/StartTLSFailureParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StartTLSFailureParser : public GenericElementParser<StartTLSFailure> {
- public:
- StartTLSFailureParser() : GenericElementParser<StartTLSFailure>() {}
- };
+ class SWIFTEN_API StartTLSFailureParser : public GenericElementParser<StartTLSFailure> {
+ public:
+ StartTLSFailureParser() : GenericElementParser<StartTLSFailure>() {}
+ };
}
diff --git a/Swiften/Parser/StartTLSParser.h b/Swiften/Parser/StartTLSParser.h
index 997af95..f769d4d 100644
--- a/Swiften/Parser/StartTLSParser.h
+++ b/Swiften/Parser/StartTLSParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StartTLSParser : public GenericElementParser<StartTLSRequest> {
- public:
- StartTLSParser() : GenericElementParser<StartTLSRequest>() {}
- };
+ class SWIFTEN_API StartTLSParser : public GenericElementParser<StartTLSRequest> {
+ public:
+ StartTLSParser() : GenericElementParser<StartTLSRequest>() {}
+ };
}
diff --git a/Swiften/Parser/StreamErrorParser.cpp b/Swiften/Parser/StreamErrorParser.cpp
index d42cf2a..64e0681 100644
--- a/Swiften/Parser/StreamErrorParser.cpp
+++ b/Swiften/Parser/StreamErrorParser.cpp
@@ -12,98 +12,98 @@ StreamErrorParser::StreamErrorParser() : level(TopLevel) {
}
void StreamErrorParser::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- ++level;
+ ++level;
}
void StreamErrorParser::handleEndElement(const std::string& element, const std::string& ns) {
- --level;
- if (level == ElementLevel && ns == "urn:ietf:params:xml:ns:xmpp-streams") {
- if (element == "text") {
- getElementGeneric()->setText(currentText);
- }
- else if (element == "bad-format") {
- getElementGeneric()->setType(StreamError::BadFormat);
- }
- else if(element == "bad-namespace-prefix") {
- getElementGeneric()->setType(StreamError::BadNamespacePrefix);
- }
- else if(element == "conflict") {
- getElementGeneric()->setType(StreamError::Conflict);
- }
- else if(element == "connection-timeout") {
- getElementGeneric()->setType(StreamError::ConnectionTimeout);
- }
- else if(element == "host-gone") {
- getElementGeneric()->setType(StreamError::HostGone);
- }
- else if(element == "host-unknown") {
- getElementGeneric()->setType(StreamError::HostUnknown);
- }
- else if(element == "improper-addressing") {
- getElementGeneric()->setType(StreamError::ImproperAddressing);
- }
- else if(element == "internal-server-error") {
- getElementGeneric()->setType(StreamError::InternalServerError);
- }
- else if(element == "invalid-from") {
- getElementGeneric()->setType(StreamError::InvalidFrom);
- }
- else if(element == "invalid-id") {
- getElementGeneric()->setType(StreamError::InvalidID);
- }
- else if(element == "invalid-namespace") {
- getElementGeneric()->setType(StreamError::InvalidNamespace);
- }
- else if(element == "invalid-xml") {
- getElementGeneric()->setType(StreamError::InvalidXML);
- }
- else if(element == "not-authorized") {
- getElementGeneric()->setType(StreamError::NotAuthorized);
- }
- else if(element == "not-well-formed") {
- getElementGeneric()->setType(StreamError::NotWellFormed);
- }
- else if(element == "policy-violation") {
- getElementGeneric()->setType(StreamError::PolicyViolation);
- }
- else if(element == "remote-connection-failed") {
- getElementGeneric()->setType(StreamError::RemoteConnectionFailed);
- }
- else if(element == "reset") {
- getElementGeneric()->setType(StreamError::Reset);
- }
- else if(element == "resource-constraint") {
- getElementGeneric()->setType(StreamError::ResourceConstraint);
- }
- else if(element == "restricted-xml") {
- getElementGeneric()->setType(StreamError::RestrictedXML);
- }
- else if(element == "see-other-host") {
- getElementGeneric()->setType(StreamError::SeeOtherHost);
- }
- else if(element == "system-shutdown") {
- getElementGeneric()->setType(StreamError::SystemShutdown);
- }
- else if(element == "undefined-condition") {
- getElementGeneric()->setType(StreamError::UndefinedCondition);
- }
- else if(element == "unsupported-encoding") {
- getElementGeneric()->setType(StreamError::UnsupportedEncoding);
- }
- else if(element == "unsupported-stanza-type") {
- getElementGeneric()->setType(StreamError::UnsupportedStanzaType);
- }
- else if(element == "unsupported-version") {
- getElementGeneric()->setType(StreamError::UnsupportedVersion);
- }
- else {
- getElementGeneric()->setType(StreamError::UndefinedCondition);
- }
- }
+ --level;
+ if (level == ElementLevel && ns == "urn:ietf:params:xml:ns:xmpp-streams") {
+ if (element == "text") {
+ getElementGeneric()->setText(currentText);
+ }
+ else if (element == "bad-format") {
+ getElementGeneric()->setType(StreamError::BadFormat);
+ }
+ else if(element == "bad-namespace-prefix") {
+ getElementGeneric()->setType(StreamError::BadNamespacePrefix);
+ }
+ else if(element == "conflict") {
+ getElementGeneric()->setType(StreamError::Conflict);
+ }
+ else if(element == "connection-timeout") {
+ getElementGeneric()->setType(StreamError::ConnectionTimeout);
+ }
+ else if(element == "host-gone") {
+ getElementGeneric()->setType(StreamError::HostGone);
+ }
+ else if(element == "host-unknown") {
+ getElementGeneric()->setType(StreamError::HostUnknown);
+ }
+ else if(element == "improper-addressing") {
+ getElementGeneric()->setType(StreamError::ImproperAddressing);
+ }
+ else if(element == "internal-server-error") {
+ getElementGeneric()->setType(StreamError::InternalServerError);
+ }
+ else if(element == "invalid-from") {
+ getElementGeneric()->setType(StreamError::InvalidFrom);
+ }
+ else if(element == "invalid-id") {
+ getElementGeneric()->setType(StreamError::InvalidID);
+ }
+ else if(element == "invalid-namespace") {
+ getElementGeneric()->setType(StreamError::InvalidNamespace);
+ }
+ else if(element == "invalid-xml") {
+ getElementGeneric()->setType(StreamError::InvalidXML);
+ }
+ else if(element == "not-authorized") {
+ getElementGeneric()->setType(StreamError::NotAuthorized);
+ }
+ else if(element == "not-well-formed") {
+ getElementGeneric()->setType(StreamError::NotWellFormed);
+ }
+ else if(element == "policy-violation") {
+ getElementGeneric()->setType(StreamError::PolicyViolation);
+ }
+ else if(element == "remote-connection-failed") {
+ getElementGeneric()->setType(StreamError::RemoteConnectionFailed);
+ }
+ else if(element == "reset") {
+ getElementGeneric()->setType(StreamError::Reset);
+ }
+ else if(element == "resource-constraint") {
+ getElementGeneric()->setType(StreamError::ResourceConstraint);
+ }
+ else if(element == "restricted-xml") {
+ getElementGeneric()->setType(StreamError::RestrictedXML);
+ }
+ else if(element == "see-other-host") {
+ getElementGeneric()->setType(StreamError::SeeOtherHost);
+ }
+ else if(element == "system-shutdown") {
+ getElementGeneric()->setType(StreamError::SystemShutdown);
+ }
+ else if(element == "undefined-condition") {
+ getElementGeneric()->setType(StreamError::UndefinedCondition);
+ }
+ else if(element == "unsupported-encoding") {
+ getElementGeneric()->setType(StreamError::UnsupportedEncoding);
+ }
+ else if(element == "unsupported-stanza-type") {
+ getElementGeneric()->setType(StreamError::UnsupportedStanzaType);
+ }
+ else if(element == "unsupported-version") {
+ getElementGeneric()->setType(StreamError::UnsupportedVersion);
+ }
+ else {
+ getElementGeneric()->setType(StreamError::UndefinedCondition);
+ }
+ }
}
void StreamErrorParser::handleCharacterData(const std::string& data) {
- currentText += data;
+ currentText += data;
}
}
diff --git a/Swiften/Parser/StreamErrorParser.h b/Swiften/Parser/StreamErrorParser.h
index 74f9127..27efc86 100644
--- a/Swiften/Parser/StreamErrorParser.h
+++ b/Swiften/Parser/StreamErrorParser.h
@@ -11,20 +11,20 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamErrorParser : public GenericElementParser<StreamError> {
- public:
- StreamErrorParser();
+ class SWIFTEN_API StreamErrorParser : public GenericElementParser<StreamError> {
+ public:
+ StreamErrorParser();
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string&);
- virtual void handleCharacterData(const std::string& data);
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
- private:
- enum Level {
- TopLevel = 0,
- ElementLevel = 1
- };
- int level;
- std::string currentText;
- };
+ private:
+ enum Level {
+ TopLevel = 0,
+ ElementLevel = 1
+ };
+ int level;
+ std::string currentText;
+ };
}
diff --git a/Swiften/Parser/StreamFeaturesParser.cpp b/Swiften/Parser/StreamFeaturesParser.cpp
index 913c50d..ce99a1e 100644
--- a/Swiften/Parser/StreamFeaturesParser.cpp
+++ b/Swiften/Parser/StreamFeaturesParser.cpp
@@ -12,71 +12,71 @@ StreamFeaturesParser::StreamFeaturesParser() : GenericElementParser<StreamFeatur
}
void StreamFeaturesParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap&) {
- if (currentDepth_ == 1) {
- if (element == "starttls" && ns == "urn:ietf:params:xml:ns:xmpp-tls") {
- getElementGeneric()->setHasStartTLS();
- }
- else if (element == "session" && ns == "urn:ietf:params:xml:ns:xmpp-session") {
- getElementGeneric()->setHasSession();
- }
- else if (element == "bind" && ns == "urn:ietf:params:xml:ns:xmpp-bind") {
- getElementGeneric()->setHasResourceBind();
- }
- else if (element == "sm" && ns == "urn:xmpp:sm:2") {
- getElementGeneric()->setHasStreamManagement();
- }
- else if (element == "mechanisms" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
- inMechanisms_ = true;
- }
- else if (element == "compression" && ns == "http://jabber.org/features/compress") {
- inCompression_ = true;
- }
- else if (element == "ver" && ns == "urn:xmpp:features:rosterver") {
- getElementGeneric()->setHasRosterVersioning();
- }
- }
- else if (currentDepth_ == 2) {
- if (inCompression_ && element == "method") {
- inCompressionMethod_ = true;
- currentText_ = "";
- }
- else if (inMechanisms_ && element == "mechanism") {
- inMechanism_ = true;
- currentText_ = "";
- }
- else if (inMechanisms_ && element == "hostname" && ns == "urn:xmpp:domain-based-name:1") {
- inAuthenticationHostname_ = true;
- currentText_ = "";
- }
+ if (currentDepth_ == 1) {
+ if (element == "starttls" && ns == "urn:ietf:params:xml:ns:xmpp-tls") {
+ getElementGeneric()->setHasStartTLS();
+ }
+ else if (element == "session" && ns == "urn:ietf:params:xml:ns:xmpp-session") {
+ getElementGeneric()->setHasSession();
+ }
+ else if (element == "bind" && ns == "urn:ietf:params:xml:ns:xmpp-bind") {
+ getElementGeneric()->setHasResourceBind();
+ }
+ else if (element == "sm" && ns == "urn:xmpp:sm:2") {
+ getElementGeneric()->setHasStreamManagement();
+ }
+ else if (element == "mechanisms" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
+ inMechanisms_ = true;
+ }
+ else if (element == "compression" && ns == "http://jabber.org/features/compress") {
+ inCompression_ = true;
+ }
+ else if (element == "ver" && ns == "urn:xmpp:features:rosterver") {
+ getElementGeneric()->setHasRosterVersioning();
+ }
+ }
+ else if (currentDepth_ == 2) {
+ if (inCompression_ && element == "method") {
+ inCompressionMethod_ = true;
+ currentText_ = "";
+ }
+ else if (inMechanisms_ && element == "mechanism") {
+ inMechanism_ = true;
+ currentText_ = "";
+ }
+ else if (inMechanisms_ && element == "hostname" && ns == "urn:xmpp:domain-based-name:1") {
+ inAuthenticationHostname_ = true;
+ currentText_ = "";
+ }
- }
- ++currentDepth_;
+ }
+ ++currentDepth_;
}
void StreamFeaturesParser::handleEndElement(const std::string&, const std::string&) {
- --currentDepth_;
- if (currentDepth_ == 1) {
- inCompression_ = false;
- inMechanisms_ = false;
- }
- else if (currentDepth_ == 2) {
- if (inCompressionMethod_) {
- getElementGeneric()->addCompressionMethod(currentText_);
- inCompressionMethod_ = false;
- }
- else if (inMechanism_) {
- getElementGeneric()->addAuthenticationMechanism(currentText_);
- inMechanism_ = false;
- }
- else if (inAuthenticationHostname_) {
- getElementGeneric()->setAuthenticationHostname(currentText_);
- inAuthenticationHostname_ = false;
- }
- }
+ --currentDepth_;
+ if (currentDepth_ == 1) {
+ inCompression_ = false;
+ inMechanisms_ = false;
+ }
+ else if (currentDepth_ == 2) {
+ if (inCompressionMethod_) {
+ getElementGeneric()->addCompressionMethod(currentText_);
+ inCompressionMethod_ = false;
+ }
+ else if (inMechanism_) {
+ getElementGeneric()->addAuthenticationMechanism(currentText_);
+ inMechanism_ = false;
+ }
+ else if (inAuthenticationHostname_) {
+ getElementGeneric()->setAuthenticationHostname(currentText_);
+ inAuthenticationHostname_ = false;
+ }
+ }
}
void StreamFeaturesParser::handleCharacterData(const std::string& data) {
- currentText_ += data;
+ currentText_ += data;
}
}
diff --git a/Swiften/Parser/StreamFeaturesParser.h b/Swiften/Parser/StreamFeaturesParser.h
index 1a60c3b..5af8de8 100644
--- a/Swiften/Parser/StreamFeaturesParser.h
+++ b/Swiften/Parser/StreamFeaturesParser.h
@@ -13,22 +13,22 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamFeaturesParser : public GenericElementParser<StreamFeatures> {
- public:
- StreamFeaturesParser();
+ class SWIFTEN_API StreamFeaturesParser : public GenericElementParser<StreamFeatures> {
+ public:
+ StreamFeaturesParser();
- private:
- void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
- void handleEndElement(const std::string& element, const std::string& ns);
- void handleCharacterData(const std::string& data);
+ private:
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
- private:
- int currentDepth_;
- std::string currentText_;
- bool inMechanisms_;
- bool inMechanism_;
- bool inAuthenticationHostname_;
- bool inCompression_;
- bool inCompressionMethod_;
- };
+ private:
+ int currentDepth_;
+ std::string currentText_;
+ bool inMechanisms_;
+ bool inMechanism_;
+ bool inAuthenticationHostname_;
+ bool inCompression_;
+ bool inCompressionMethod_;
+ };
}
diff --git a/Swiften/Parser/StreamManagementEnabledParser.cpp b/Swiften/Parser/StreamManagementEnabledParser.cpp
index 5edcc2a..9e87d65 100644
--- a/Swiften/Parser/StreamManagementEnabledParser.cpp
+++ b/Swiften/Parser/StreamManagementEnabledParser.cpp
@@ -15,15 +15,15 @@ StreamManagementEnabledParser::~StreamManagementEnabledParser() {
}
void StreamManagementEnabledParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (level == TopLevel) {
- if (attributes.getBoolAttribute("resume", false)) {
- getElementGeneric()->setResumeSupported();
- }
- getElementGeneric()->setResumeID(attributes.getAttribute("id"));
- }
- ++level;
+ if (level == TopLevel) {
+ if (attributes.getBoolAttribute("resume", false)) {
+ getElementGeneric()->setResumeSupported();
+ }
+ getElementGeneric()->setResumeID(attributes.getAttribute("id"));
+ }
+ ++level;
}
void StreamManagementEnabledParser::handleEndElement(const std::string&, const std::string&) {
- --level;
+ --level;
}
diff --git a/Swiften/Parser/StreamManagementEnabledParser.h b/Swiften/Parser/StreamManagementEnabledParser.h
index e854212..0f75071 100644
--- a/Swiften/Parser/StreamManagementEnabledParser.h
+++ b/Swiften/Parser/StreamManagementEnabledParser.h
@@ -11,18 +11,18 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamManagementEnabledParser : public GenericElementParser<StreamManagementEnabled> {
- public:
- StreamManagementEnabledParser();
- ~StreamManagementEnabledParser();
+ class SWIFTEN_API StreamManagementEnabledParser : public GenericElementParser<StreamManagementEnabled> {
+ public:
+ StreamManagementEnabledParser();
+ ~StreamManagementEnabledParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
- private:
- enum Level {
- TopLevel = 0
- };
- int level;
- };
+ private:
+ enum Level {
+ TopLevel = 0
+ };
+ int level;
+ };
}
diff --git a/Swiften/Parser/StreamManagementFailedParser.h b/Swiften/Parser/StreamManagementFailedParser.h
index b929bb0..c87beee 100644
--- a/Swiften/Parser/StreamManagementFailedParser.h
+++ b/Swiften/Parser/StreamManagementFailedParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamManagementFailedParser : public GenericElementParser<StreamManagementFailed> {
- public:
- StreamManagementFailedParser() : GenericElementParser<StreamManagementFailed>() {}
- };
+ class SWIFTEN_API StreamManagementFailedParser : public GenericElementParser<StreamManagementFailed> {
+ public:
+ StreamManagementFailedParser() : GenericElementParser<StreamManagementFailed>() {}
+ };
}
diff --git a/Swiften/Parser/StreamResumeParser.cpp b/Swiften/Parser/StreamResumeParser.cpp
index 1a9e72f..a6ca444 100644
--- a/Swiften/Parser/StreamResumeParser.cpp
+++ b/Swiften/Parser/StreamResumeParser.cpp
@@ -17,20 +17,20 @@ StreamResumeParser::~StreamResumeParser() {
}
void StreamResumeParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (level == TopLevel) {
- boost::optional<std::string> handledStanzasCount = attributes.getAttributeValue("h");
- if (handledStanzasCount) {
- try {
- getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<unsigned int>(*handledStanzasCount));
- }
- catch (const boost::bad_lexical_cast &) {
- }
- }
- getElementGeneric()->setResumeID(attributes.getAttribute("previd"));
- }
- ++level;
+ if (level == TopLevel) {
+ boost::optional<std::string> handledStanzasCount = attributes.getAttributeValue("h");
+ if (handledStanzasCount) {
+ try {
+ getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<unsigned int>(*handledStanzasCount));
+ }
+ catch (const boost::bad_lexical_cast &) {
+ }
+ }
+ getElementGeneric()->setResumeID(attributes.getAttribute("previd"));
+ }
+ ++level;
}
void StreamResumeParser::handleEndElement(const std::string&, const std::string&) {
- --level;
+ --level;
}
diff --git a/Swiften/Parser/StreamResumeParser.h b/Swiften/Parser/StreamResumeParser.h
index 4d2bd4c..d3d2498 100644
--- a/Swiften/Parser/StreamResumeParser.h
+++ b/Swiften/Parser/StreamResumeParser.h
@@ -11,18 +11,18 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamResumeParser : public GenericElementParser<StreamResume> {
- public:
- StreamResumeParser();
- ~StreamResumeParser();
+ class SWIFTEN_API StreamResumeParser : public GenericElementParser<StreamResume> {
+ public:
+ StreamResumeParser();
+ ~StreamResumeParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
- private:
- enum Level {
- TopLevel = 0
- };
- int level;
- };
+ private:
+ enum Level {
+ TopLevel = 0
+ };
+ int level;
+ };
}
diff --git a/Swiften/Parser/StreamResumedParser.cpp b/Swiften/Parser/StreamResumedParser.cpp
index 9c7be50..f69bad1 100644
--- a/Swiften/Parser/StreamResumedParser.cpp
+++ b/Swiften/Parser/StreamResumedParser.cpp
@@ -17,20 +17,20 @@ StreamResumedParser::~StreamResumedParser() {
}
void StreamResumedParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
- if (level == TopLevel) {
- boost::optional<std::string> handledStanzasCount = attributes.getAttributeValue("h");
- if (handledStanzasCount) {
- try {
- getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<unsigned int>(*handledStanzasCount));
- }
- catch (const boost::bad_lexical_cast &) {
- }
- }
- getElementGeneric()->setResumeID(attributes.getAttribute("previd"));
- }
- ++level;
+ if (level == TopLevel) {
+ boost::optional<std::string> handledStanzasCount = attributes.getAttributeValue("h");
+ if (handledStanzasCount) {
+ try {
+ getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<unsigned int>(*handledStanzasCount));
+ }
+ catch (const boost::bad_lexical_cast &) {
+ }
+ }
+ getElementGeneric()->setResumeID(attributes.getAttribute("previd"));
+ }
+ ++level;
}
void StreamResumedParser::handleEndElement(const std::string&, const std::string&) {
- --level;
+ --level;
}
diff --git a/Swiften/Parser/StreamResumedParser.h b/Swiften/Parser/StreamResumedParser.h
index da67d50..ca89597 100644
--- a/Swiften/Parser/StreamResumedParser.h
+++ b/Swiften/Parser/StreamResumedParser.h
@@ -11,18 +11,18 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API StreamResumedParser : public GenericElementParser<StreamResumed> {
- public:
- StreamResumedParser();
- ~StreamResumedParser();
+ class SWIFTEN_API StreamResumedParser : public GenericElementParser<StreamResumed> {
+ public:
+ StreamResumedParser();
+ ~StreamResumedParser();
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
- virtual void handleEndElement(const std::string&, const std::string&);
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&);
+ virtual void handleEndElement(const std::string&, const std::string&);
- private:
- enum Level {
- TopLevel = 0
- };
- int level;
- };
+ private:
+ enum Level {
+ TopLevel = 0
+ };
+ int level;
+ };
}
diff --git a/Swiften/Parser/TLSProceedParser.h b/Swiften/Parser/TLSProceedParser.h
index 6f587a4..da6cfd1 100644
--- a/Swiften/Parser/TLSProceedParser.h
+++ b/Swiften/Parser/TLSProceedParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API TLSProceedParser : public GenericElementParser<TLSProceed> {
- public:
- TLSProceedParser() : GenericElementParser<TLSProceed>() {}
- };
+ class SWIFTEN_API TLSProceedParser : public GenericElementParser<TLSProceed> {
+ public:
+ TLSProceedParser() : GenericElementParser<TLSProceed>() {}
+ };
}
diff --git a/Swiften/Parser/Tree/NullParserElement.h b/Swiften/Parser/Tree/NullParserElement.h
index dcfcad2..8dae25d 100644
--- a/Swiften/Parser/Tree/NullParserElement.h
+++ b/Swiften/Parser/Tree/NullParserElement.h
@@ -12,12 +12,12 @@
#include <Swiften/Parser/Tree/ParserElement.h>
namespace Swift {
- class SWIFTEN_API NullParserElement : public ParserElement {
- public:
- NullParserElement() : ParserElement("", "", AttributeMap()) {}
+ class SWIFTEN_API NullParserElement : public ParserElement {
+ public:
+ NullParserElement() : ParserElement("", "", AttributeMap()) {}
- virtual operator bool() { return false; }
+ virtual operator bool() { return false; }
- static boost::shared_ptr<NullParserElement> element;
- };
+ static boost::shared_ptr<NullParserElement> element;
+ };
}
diff --git a/Swiften/Parser/Tree/ParserElement.cpp b/Swiften/Parser/Tree/ParserElement.cpp
index 441647c..6bbd93e 100644
--- a/Swiften/Parser/Tree/ParserElement.cpp
+++ b/Swiften/Parser/Tree/ParserElement.cpp
@@ -25,26 +25,26 @@ ParserElement::~ParserElement() {
}
ParserElement::ref ParserElement::addChild(const std::string& name, const std::string& xmlns, const AttributeMap& attributes) {
- ParserElement::ref child = boost::make_shared<ParserElement>(name, xmlns, attributes);
- children_.push_back(child);
- return child;
+ ParserElement::ref child = boost::make_shared<ParserElement>(name, xmlns, attributes);
+ children_.push_back(child);
+ return child;
}
void ParserElement::appendCharacterData(const std::string& data) {
- text_ += data;
+ text_ += data;
}
std::vector<ParserElement::ref> ParserElement::getChildren(const std::string& name, const std::string& xmlns) const {
- std::vector<ParserElement::ref> result;
- std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result),
- lambda::bind(&ParserElement::getName, *lambda::_1) != name || lambda::bind(&ParserElement::getNamespace, *lambda::_1) != xmlns);
- return result;
+ std::vector<ParserElement::ref> result;
+ std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result),
+ lambda::bind(&ParserElement::getName, *lambda::_1) != name || lambda::bind(&ParserElement::getNamespace, *lambda::_1) != xmlns);
+ return result;
}
ParserElement::ref ParserElement::getChild(const std::string& name, const std::string& xmlns) const {
- std::vector<ParserElement::ref> results = getChildren(name, xmlns);
- ParserElement::ref result = results.empty() ? NullParserElement::element : results[0];
- return result;
+ std::vector<ParserElement::ref> results = getChildren(name, xmlns);
+ ParserElement::ref result = results.empty() ? NullParserElement::element : results[0];
+ return result;
}
}
diff --git a/Swiften/Parser/Tree/ParserElement.h b/Swiften/Parser/Tree/ParserElement.h
index f0c895f..dc9f31c 100644
--- a/Swiften/Parser/Tree/ParserElement.h
+++ b/Swiften/Parser/Tree/ParserElement.h
@@ -18,34 +18,34 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
- class SWIFTEN_API ParserElement {
- public:
- typedef boost::shared_ptr<ParserElement> ref;
-
- ParserElement(const std::string& name, const std::string& xmlns, const AttributeMap& attributes);
- virtual ~ParserElement();
-
- const std::string& getText() const { return text_; }
- const std::string& getName() const { return name_; }
- const std::string& getNamespace() const { return xmlns_; }
- const AttributeMap& getAttributes() const { return attributes_; }
-
- ParserElement::ref addChild(const std::string& name, const std::string& xmlns, const AttributeMap& attributes);
- void appendCharacterData(const std::string& data);
-
- std::vector<ParserElement::ref> getChildren(const std::string& name, const std::string& xmlns) const;
- const std::vector<ParserElement::ref>& getAllChildren() const {return children_;}
- ParserElement::ref getChild(const std::string& name, const std::string& xmlns) const;
-
- virtual operator bool() {
- return true;
- }
-
- private:
- std::vector<ParserElement::ref> children_;
- std::string name_;
- std::string xmlns_;
- AttributeMap attributes_;
- std::string text_;
- };
+ class SWIFTEN_API ParserElement {
+ public:
+ typedef boost::shared_ptr<ParserElement> ref;
+
+ ParserElement(const std::string& name, const std::string& xmlns, const AttributeMap& attributes);
+ virtual ~ParserElement();
+
+ const std::string& getText() const { return text_; }
+ const std::string& getName() const { return name_; }
+ const std::string& getNamespace() const { return xmlns_; }
+ const AttributeMap& getAttributes() const { return attributes_; }
+
+ ParserElement::ref addChild(const std::string& name, const std::string& xmlns, const AttributeMap& attributes);
+ void appendCharacterData(const std::string& data);
+
+ std::vector<ParserElement::ref> getChildren(const std::string& name, const std::string& xmlns) const;
+ const std::vector<ParserElement::ref>& getAllChildren() const {return children_;}
+ ParserElement::ref getChild(const std::string& name, const std::string& xmlns) const;
+
+ virtual operator bool() {
+ return true;
+ }
+
+ private:
+ std::vector<ParserElement::ref> children_;
+ std::string name_;
+ std::string xmlns_;
+ AttributeMap attributes_;
+ std::string text_;
+ };
}
diff --git a/Swiften/Parser/Tree/TreeReparser.cpp b/Swiften/Parser/Tree/TreeReparser.cpp
index bc2b6b9..269b2ea 100644
--- a/Swiften/Parser/Tree/TreeReparser.cpp
+++ b/Swiften/Parser/Tree/TreeReparser.cpp
@@ -22,28 +22,28 @@ namespace Swift {
typedef std::pair<ParserElement::ref, bool> ElementState;
boost::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()) {
- stack.push_back(ElementState(child, true));
- }
- } else {
- parser->handleCharacterData(current.first->getText());
- parser->handleEndElement(current.first->getName(), current.first->getNamespace());
- }
-
- }
-
- boost::shared_ptr<Payload> payload = parser->getPayload();
- delete parser;
- return payload;
+ 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()) {
+ stack.push_back(ElementState(child, true));
+ }
+ } else {
+ parser->handleCharacterData(current.first->getText());
+ parser->handleEndElement(current.first->getName(), current.first->getNamespace());
+ }
+
+ }
+
+ boost::shared_ptr<Payload> payload = parser->getPayload();
+ delete parser;
+ return payload;
}
}
diff --git a/Swiften/Parser/Tree/TreeReparser.h b/Swiften/Parser/Tree/TreeReparser.h
index 80a326b..fb96c1b 100644
--- a/Swiften/Parser/Tree/TreeReparser.h
+++ b/Swiften/Parser/Tree/TreeReparser.h
@@ -11,10 +11,10 @@
#include <Swiften/Parser/PayloadParsers/MUCItemParser.h>
namespace Swift {
- class PayloadParserFactoryCollection;
- class SWIFTEN_API TreeReparser {
- public:
- static boost::shared_ptr<Payload> parseTree(ParserElement::ref root, PayloadParserFactoryCollection* collection);
+ class PayloadParserFactoryCollection;
+ class SWIFTEN_API TreeReparser {
+ public:
+ static boost::shared_ptr<Payload> parseTree(ParserElement::ref root, PayloadParserFactoryCollection* collection);
- };
+ };
}
diff --git a/Swiften/Parser/UnitTest/AttributeMapTest.cpp b/Swiften/Parser/UnitTest/AttributeMapTest.cpp
index 55fa964..4529eac 100644
--- a/Swiften/Parser/UnitTest/AttributeMapTest.cpp
+++ b/Swiften/Parser/UnitTest/AttributeMapTest.cpp
@@ -13,73 +13,73 @@ using namespace Swift;
class AttributeMapTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(AttributeMapTest);
- CPPUNIT_TEST(testGetAttribute_Namespaced);
- CPPUNIT_TEST(testGetBoolAttribute_True);
- CPPUNIT_TEST(testGetBoolAttribute_1);
- CPPUNIT_TEST(testGetBoolAttribute_False);
- CPPUNIT_TEST(testGetBoolAttribute_0);
- CPPUNIT_TEST(testGetBoolAttribute_Invalid);
- CPPUNIT_TEST(testGetBoolAttribute_UnknownWithDefaultTrue);
- CPPUNIT_TEST(testGetBoolAttribute_UnknownWithDefaultFalse);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(AttributeMapTest);
+ CPPUNIT_TEST(testGetAttribute_Namespaced);
+ CPPUNIT_TEST(testGetBoolAttribute_True);
+ CPPUNIT_TEST(testGetBoolAttribute_1);
+ CPPUNIT_TEST(testGetBoolAttribute_False);
+ CPPUNIT_TEST(testGetBoolAttribute_0);
+ CPPUNIT_TEST(testGetBoolAttribute_Invalid);
+ CPPUNIT_TEST(testGetBoolAttribute_UnknownWithDefaultTrue);
+ CPPUNIT_TEST(testGetBoolAttribute_UnknownWithDefaultFalse);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetAttribute_Namespaced() {
- AttributeMap testling;
- testling.addAttribute("lang", "", "nl");
- testling.addAttribute("lang", "http://www.w3.org/XML/1998/namespace", "en");
- testling.addAttribute("lang", "", "fr");
+ public:
+ void testGetAttribute_Namespaced() {
+ AttributeMap testling;
+ testling.addAttribute("lang", "", "nl");
+ testling.addAttribute("lang", "http://www.w3.org/XML/1998/namespace", "en");
+ testling.addAttribute("lang", "", "fr");
- CPPUNIT_ASSERT_EQUAL(std::string("en"), testling.getAttribute("lang", "http://www.w3.org/XML/1998/namespace"));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("en"), testling.getAttribute("lang", "http://www.w3.org/XML/1998/namespace"));
+ }
- void testGetBoolAttribute_True() {
- AttributeMap testling;
- testling.addAttribute("foo", "", "true");
+ void testGetBoolAttribute_True() {
+ AttributeMap testling;
+ testling.addAttribute("foo", "", "true");
- CPPUNIT_ASSERT(testling.getBoolAttribute("foo"));
- }
+ CPPUNIT_ASSERT(testling.getBoolAttribute("foo"));
+ }
- void testGetBoolAttribute_1() {
- AttributeMap testling;
- testling.addAttribute("foo", "", "1");
+ void testGetBoolAttribute_1() {
+ AttributeMap testling;
+ testling.addAttribute("foo", "", "1");
- CPPUNIT_ASSERT(testling.getBoolAttribute("foo"));
- }
+ CPPUNIT_ASSERT(testling.getBoolAttribute("foo"));
+ }
- void testGetBoolAttribute_False() {
- AttributeMap testling;
- testling.addAttribute("foo", "", "false");
+ void testGetBoolAttribute_False() {
+ AttributeMap testling;
+ testling.addAttribute("foo", "", "false");
- CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
- }
+ CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
+ }
- void testGetBoolAttribute_0() {
- AttributeMap testling;
- testling.addAttribute("foo", "", "0");
+ void testGetBoolAttribute_0() {
+ AttributeMap testling;
+ testling.addAttribute("foo", "", "0");
- CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
- }
+ CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
+ }
- void testGetBoolAttribute_Invalid() {
- AttributeMap testling;
- testling.addAttribute("foo", "", "bla");
+ void testGetBoolAttribute_Invalid() {
+ AttributeMap testling;
+ testling.addAttribute("foo", "", "bla");
- CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
- }
+ CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", true));
+ }
- void testGetBoolAttribute_UnknownWithDefaultTrue() {
- AttributeMap testling;
+ void testGetBoolAttribute_UnknownWithDefaultTrue() {
+ AttributeMap testling;
- CPPUNIT_ASSERT(testling.getBoolAttribute("foo", true));
- }
+ CPPUNIT_ASSERT(testling.getBoolAttribute("foo", true));
+ }
- void testGetBoolAttribute_UnknownWithDefaultFalse() {
- AttributeMap testling;
+ void testGetBoolAttribute_UnknownWithDefaultFalse() {
+ AttributeMap testling;
- CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", false));
- }
+ CPPUNIT_ASSERT(!testling.getBoolAttribute("foo", false));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(AttributeMapTest);
diff --git a/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp b/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp
index a72f5aa..f7ed80f 100644
--- a/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp
+++ b/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp
@@ -13,92 +13,92 @@
using namespace Swift;
class BOSHBodyExtractorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BOSHBodyExtractorTest);
- CPPUNIT_TEST(testGetBody);
- CPPUNIT_TEST(testGetBody_EmptyContent);
- CPPUNIT_TEST(testGetBody_EmptyContent2);
- CPPUNIT_TEST(testGetBody_EmptyElementEmptyContent);
- CPPUNIT_TEST(testGetBody_InvalidStartTag);
- CPPUNIT_TEST(testGetBody_InvalidStartTag2);
- CPPUNIT_TEST(testGetBody_IncompleteStartTag);
- CPPUNIT_TEST(testGetBody_InvalidEndTag);
- CPPUNIT_TEST(testGetBody_InvalidEndTag2);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testGetBody() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body a1='a\"1' a2=\"a'2\" boo='bar' >"
- "foo <message> <body> bar"
- "</body > "));
-
- CPPUNIT_ASSERT(testling.getBody());
- CPPUNIT_ASSERT_EQUAL(std::string("a\"1"), testling.getBody()->attributes.getAttribute("a1"));
- CPPUNIT_ASSERT_EQUAL(std::string("foo <message> <body> bar"), testling.getBody()->content);
- }
-
- void testGetBody_EmptyContent() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body foo='bar'/>"));
-
- CPPUNIT_ASSERT(testling.getBody());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getBody()->attributes.getAttribute("foo"));
- CPPUNIT_ASSERT(testling.getBody()->content.empty());
- }
-
- void testGetBody_EmptyContent2() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body foo='bar'></body>"));
-
- CPPUNIT_ASSERT(testling.getBody());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getBody()->attributes.getAttribute("foo"));
- CPPUNIT_ASSERT(testling.getBody()->content.empty());
- }
-
- void testGetBody_EmptyElementEmptyContent() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body/>"));
-
- CPPUNIT_ASSERT(testling.getBody());
- }
-
- void testGetBody_InvalidStartTag() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<bodi></body>"));
-
- CPPUNIT_ASSERT(!testling.getBody());
- }
-
- void testGetBody_InvalidStartTag2() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<bodyy></body>"));
-
- CPPUNIT_ASSERT(!testling.getBody());
- }
-
- void testGetBody_IncompleteStartTag() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body"));
-
- CPPUNIT_ASSERT(!testling.getBody());
- }
-
- void testGetBody_InvalidEndTag() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body></bodi>"));
-
- CPPUNIT_ASSERT(!testling.getBody());
- }
-
- void testGetBody_InvalidEndTag2() {
- BOSHBodyExtractor testling(&parserFactory, createByteArray(
- "<body><b/body>"));
-
- CPPUNIT_ASSERT(!testling.getBody());
- }
-
- private:
- PlatformXMLParserFactory parserFactory;
+ CPPUNIT_TEST_SUITE(BOSHBodyExtractorTest);
+ CPPUNIT_TEST(testGetBody);
+ CPPUNIT_TEST(testGetBody_EmptyContent);
+ CPPUNIT_TEST(testGetBody_EmptyContent2);
+ CPPUNIT_TEST(testGetBody_EmptyElementEmptyContent);
+ CPPUNIT_TEST(testGetBody_InvalidStartTag);
+ CPPUNIT_TEST(testGetBody_InvalidStartTag2);
+ CPPUNIT_TEST(testGetBody_IncompleteStartTag);
+ CPPUNIT_TEST(testGetBody_InvalidEndTag);
+ CPPUNIT_TEST(testGetBody_InvalidEndTag2);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testGetBody() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body a1='a\"1' a2=\"a'2\" boo='bar' >"
+ "foo <message> <body> bar"
+ "</body > "));
+
+ CPPUNIT_ASSERT(testling.getBody());
+ CPPUNIT_ASSERT_EQUAL(std::string("a\"1"), testling.getBody()->attributes.getAttribute("a1"));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo <message> <body> bar"), testling.getBody()->content);
+ }
+
+ void testGetBody_EmptyContent() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body foo='bar'/>"));
+
+ CPPUNIT_ASSERT(testling.getBody());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getBody()->attributes.getAttribute("foo"));
+ CPPUNIT_ASSERT(testling.getBody()->content.empty());
+ }
+
+ void testGetBody_EmptyContent2() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body foo='bar'></body>"));
+
+ CPPUNIT_ASSERT(testling.getBody());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getBody()->attributes.getAttribute("foo"));
+ CPPUNIT_ASSERT(testling.getBody()->content.empty());
+ }
+
+ void testGetBody_EmptyElementEmptyContent() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body/>"));
+
+ CPPUNIT_ASSERT(testling.getBody());
+ }
+
+ void testGetBody_InvalidStartTag() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<bodi></body>"));
+
+ CPPUNIT_ASSERT(!testling.getBody());
+ }
+
+ void testGetBody_InvalidStartTag2() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<bodyy></body>"));
+
+ CPPUNIT_ASSERT(!testling.getBody());
+ }
+
+ void testGetBody_IncompleteStartTag() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body"));
+
+ CPPUNIT_ASSERT(!testling.getBody());
+ }
+
+ void testGetBody_InvalidEndTag() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body></bodi>"));
+
+ CPPUNIT_ASSERT(!testling.getBody());
+ }
+
+ void testGetBody_InvalidEndTag2() {
+ BOSHBodyExtractor testling(&parserFactory, createByteArray(
+ "<body><b/body>"));
+
+ CPPUNIT_ASSERT(!testling.getBody());
+ }
+
+ private:
+ PlatformXMLParserFactory parserFactory;
};
CPPUNIT_TEST_SUITE_REGISTRATION(BOSHBodyExtractorTest);
diff --git a/Swiften/Parser/UnitTest/ElementParserTester.h b/Swiften/Parser/UnitTest/ElementParserTester.h
index 4ab44bd..299fb50 100644
--- a/Swiften/Parser/UnitTest/ElementParserTester.h
+++ b/Swiften/Parser/UnitTest/ElementParserTester.h
@@ -9,5 +9,5 @@
#include <Swiften/Parser/UnitTest/ParserTester.h>
namespace Swift {
- typedef ParserTester<ElementParser> ElementParserTester;
+ typedef ParserTester<ElementParser> ElementParserTester;
}
diff --git a/Swiften/Parser/UnitTest/EnumParserTest.cpp b/Swiften/Parser/UnitTest/EnumParserTest.cpp
index fcbf0e9..82b3fa1 100644
--- a/Swiften/Parser/UnitTest/EnumParserTest.cpp
+++ b/Swiften/Parser/UnitTest/EnumParserTest.cpp
@@ -12,25 +12,25 @@
using namespace Swift;
class EnumParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(EnumParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_NoValue);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- enum MyEnum {
- MyValue1,
- MyValue2,
- MyValue3
- };
-
- void testParse() {
- CPPUNIT_ASSERT(MyValue2 == EnumParser<MyEnum>()(MyValue1, "my-value-1")(MyValue2, "my-value-2")(MyValue3, "my-value-3").parse("my-value-2"));
- }
-
- void testParse_NoValue() {
- CPPUNIT_ASSERT(!EnumParser<MyEnum>()(MyValue1, "my-value-1")(MyValue2, "my-value-2")(MyValue3, "my-value-3").parse("my-value-4"));
- }
+ CPPUNIT_TEST_SUITE(EnumParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_NoValue);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ enum MyEnum {
+ MyValue1,
+ MyValue2,
+ MyValue3
+ };
+
+ void testParse() {
+ CPPUNIT_ASSERT(MyValue2 == EnumParser<MyEnum>()(MyValue1, "my-value-1")(MyValue2, "my-value-2")(MyValue3, "my-value-3").parse("my-value-2"));
+ }
+
+ void testParse_NoValue() {
+ CPPUNIT_ASSERT(!EnumParser<MyEnum>()(MyValue1, "my-value-1")(MyValue2, "my-value-2")(MyValue3, "my-value-3").parse("my-value-4"));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(EnumParserTest);
diff --git a/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp b/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp
index 5413e46..cd94ed8 100644
--- a/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp
+++ b/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp
@@ -22,44 +22,44 @@ template class __declspec(dllimport) Swift::GenericPayloadParser<RawXMLPayload>;
#endif
class GenericPayloadTreeParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(GenericPayloadTreeParserTest);
- CPPUNIT_TEST(testTree);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testTree() {
- MyParser testling;
-
- std::string data = "<topLevel xmlns='urn:test:top'><firstLevelInheritedEmpty/><firstLevelInherited><secondLevelMultiChildren num='1'/><secondLevelMultiChildren num='2'/></firstLevelInherited><firstLevelNS xmlns='urn:test:first'/></topLevel>";
-
- PayloadParserTester tester(&testling);
- tester.parse(data);
-
- ParserElement::ref tree = testling.tree;
-
- CPPUNIT_ASSERT_EQUAL(std::string("topLevel"), tree->getName());
- CPPUNIT_ASSERT_EQUAL(std::string("urn:test:top"), tree->getNamespace());
- CPPUNIT_ASSERT(tree->getChild("firstLevelInheritedEmpty", "urn:test:top"));
- CPPUNIT_ASSERT(!*tree->getChild("firstLevelInheritedEmpty", ""));
- CPPUNIT_ASSERT(tree->getChild("firstLevelInherited", "urn:test:top"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top").size());
- CPPUNIT_ASSERT_EQUAL(std::string("1"), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top")[0]->getAttributes().getAttribute("num"));
- CPPUNIT_ASSERT_EQUAL(std::string("2"), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top")[1]->getAttributes().getAttribute("num"));
- CPPUNIT_ASSERT(tree->getChild("firstLevelNS", "urn:test:first"));
- }
-
- private:
-
-
- class MyParser : public GenericPayloadTreeParser<RawXMLPayload>
- {
- public:
- virtual ~MyParser() {}
- virtual void handleTree(ParserElement::ref root) {
- tree = root;
- }
- ParserElement::ref tree;
- };
+ CPPUNIT_TEST_SUITE(GenericPayloadTreeParserTest);
+ CPPUNIT_TEST(testTree);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testTree() {
+ MyParser testling;
+
+ std::string data = "<topLevel xmlns='urn:test:top'><firstLevelInheritedEmpty/><firstLevelInherited><secondLevelMultiChildren num='1'/><secondLevelMultiChildren num='2'/></firstLevelInherited><firstLevelNS xmlns='urn:test:first'/></topLevel>";
+
+ PayloadParserTester tester(&testling);
+ tester.parse(data);
+
+ ParserElement::ref tree = testling.tree;
+
+ CPPUNIT_ASSERT_EQUAL(std::string("topLevel"), tree->getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("urn:test:top"), tree->getNamespace());
+ CPPUNIT_ASSERT(tree->getChild("firstLevelInheritedEmpty", "urn:test:top"));
+ CPPUNIT_ASSERT(!*tree->getChild("firstLevelInheritedEmpty", ""));
+ CPPUNIT_ASSERT(tree->getChild("firstLevelInherited", "urn:test:top"));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top").size());
+ CPPUNIT_ASSERT_EQUAL(std::string("1"), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top")[0]->getAttributes().getAttribute("num"));
+ CPPUNIT_ASSERT_EQUAL(std::string("2"), tree->getChild("firstLevelInherited", "urn:test:top")->getChildren("secondLevelMultiChildren", "urn:test:top")[1]->getAttributes().getAttribute("num"));
+ CPPUNIT_ASSERT(tree->getChild("firstLevelNS", "urn:test:first"));
+ }
+
+ private:
+
+
+ class MyParser : public GenericPayloadTreeParser<RawXMLPayload>
+ {
+ public:
+ virtual ~MyParser() {}
+ virtual void handleTree(ParserElement::ref root) {
+ tree = root;
+ }
+ ParserElement::ref tree;
+ };
};
diff --git a/Swiften/Parser/UnitTest/IQParserTest.cpp b/Swiften/Parser/UnitTest/IQParserTest.cpp
index 95e2d51..5c07757 100644
--- a/Swiften/Parser/UnitTest/IQParserTest.cpp
+++ b/Swiften/Parser/UnitTest/IQParserTest.cpp
@@ -14,60 +14,60 @@
using namespace Swift;
class IQParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IQParserTest);
- CPPUNIT_TEST(testParse_Set);
- CPPUNIT_TEST(testParse_Get);
- CPPUNIT_TEST(testParse_Result);
- CPPUNIT_TEST(testParse_Error);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IQParserTest);
+ CPPUNIT_TEST(testParse_Set);
+ CPPUNIT_TEST(testParse_Get);
+ CPPUNIT_TEST(testParse_Result);
+ CPPUNIT_TEST(testParse_Error);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- factoryCollection_ = new PayloadParserFactoryCollection();
- }
+ public:
+ void setUp() {
+ factoryCollection_ = new PayloadParserFactoryCollection();
+ }
- void tearDown() {
- delete factoryCollection_;
- }
+ void tearDown() {
+ delete factoryCollection_;
+ }
- void testParse_Set() {
- IQParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Set() {
+ IQParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<iq type=\"set\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<iq type=\"set\"/>"));
- CPPUNIT_ASSERT_EQUAL(IQ::Set, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(IQ::Set, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Get() {
- IQParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Get() {
+ IQParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<iq type=\"get\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<iq type=\"get\"/>"));
- CPPUNIT_ASSERT_EQUAL(IQ::Get, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(IQ::Get, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Result() {
- IQParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Result() {
+ IQParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<iq type=\"result\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<iq type=\"result\"/>"));
- CPPUNIT_ASSERT_EQUAL(IQ::Result, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(IQ::Result, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Error() {
- IQParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Error() {
+ IQParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<iq type=\"error\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<iq type=\"error\"/>"));
- CPPUNIT_ASSERT_EQUAL(IQ::Error, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(IQ::Error, testling.getStanzaGeneric()->getType());
+ }
- private:
- PayloadParserFactoryCollection* factoryCollection_;
+ private:
+ PayloadParserFactoryCollection* factoryCollection_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IQParserTest);
diff --git a/Swiften/Parser/UnitTest/MessageParserTest.cpp b/Swiften/Parser/UnitTest/MessageParserTest.cpp
index 19dafc3..dc55711 100644
--- a/Swiften/Parser/UnitTest/MessageParserTest.cpp
+++ b/Swiften/Parser/UnitTest/MessageParserTest.cpp
@@ -14,70 +14,70 @@
using namespace Swift;
class MessageParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MessageParserTest);
- CPPUNIT_TEST(testParse_Normal);
- CPPUNIT_TEST(testParse_Chat);
- CPPUNIT_TEST(testParse_Error);
- CPPUNIT_TEST(testParse_Groupchat);
- CPPUNIT_TEST(testParse_Headline);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(MessageParserTest);
+ CPPUNIT_TEST(testParse_Normal);
+ CPPUNIT_TEST(testParse_Chat);
+ CPPUNIT_TEST(testParse_Error);
+ CPPUNIT_TEST(testParse_Groupchat);
+ CPPUNIT_TEST(testParse_Headline);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- factoryCollection_ = new PayloadParserFactoryCollection();
- }
+ public:
+ void setUp() {
+ factoryCollection_ = new PayloadParserFactoryCollection();
+ }
- void tearDown() {
- delete factoryCollection_;
- }
+ void tearDown() {
+ delete factoryCollection_;
+ }
- void testParse_Chat() {
- MessageParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Chat() {
+ MessageParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<message type=\"chat\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<message type=\"chat\"/>"));
- CPPUNIT_ASSERT_EQUAL(Message::Chat, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Message::Chat, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Groupchat() {
- MessageParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Groupchat() {
+ MessageParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<message type=\"groupchat\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<message type=\"groupchat\"/>"));
- CPPUNIT_ASSERT_EQUAL(Message::Groupchat, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Message::Groupchat, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Error() {
- MessageParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Error() {
+ MessageParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<message type=\"error\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<message type=\"error\"/>"));
- CPPUNIT_ASSERT_EQUAL(Message::Error, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Message::Error, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Headline() {
- MessageParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Headline() {
+ MessageParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<message type=\"headline\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<message type=\"headline\"/>"));
- CPPUNIT_ASSERT_EQUAL(Message::Headline, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Message::Headline, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Normal() {
- MessageParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Normal() {
+ MessageParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<message/>"));
+ CPPUNIT_ASSERT(parser.parse("<message/>"));
- CPPUNIT_ASSERT_EQUAL(Message::Normal, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Message::Normal, testling.getStanzaGeneric()->getType());
+ }
- private:
- PayloadParserFactoryCollection* factoryCollection_;
+ private:
+ PayloadParserFactoryCollection* factoryCollection_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MessageParserTest);
diff --git a/Swiften/Parser/UnitTest/ParserTester.h b/Swiften/Parser/UnitTest/ParserTester.h
index b843c29..a98eb51 100644
--- a/Swiften/Parser/UnitTest/ParserTester.h
+++ b/Swiften/Parser/UnitTest/ParserTester.h
@@ -11,37 +11,37 @@
#include <Swiften/Parser/XMLParserClient.h>
namespace Swift {
- class XMLParser;
-
- template<typename ParserType>
- class ParserTester : public XMLParserClient {
- public:
- ParserTester(ParserType* parser) : parser_(parser) {
- xmlParser_ = PlatformXMLParserFactory().createXMLParser(this);
- }
-
- ~ParserTester() {
- delete xmlParser_;
- }
-
- bool parse(const std::string& data) {
- return xmlParser_->parse(data);
- }
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- parser_->handleStartElement(element, ns, attributes);
- }
-
- virtual void handleEndElement(const std::string& element, const std::string& ns) {
- parser_->handleEndElement(element, ns);
- }
-
- virtual void handleCharacterData(const std::string& data) {
- parser_->handleCharacterData(data);
- }
-
- private:
- XMLParser* xmlParser_;
- ParserType* parser_;
- };
+ class XMLParser;
+
+ template<typename ParserType>
+ class ParserTester : public XMLParserClient {
+ public:
+ ParserTester(ParserType* parser) : parser_(parser) {
+ xmlParser_ = PlatformXMLParserFactory().createXMLParser(this);
+ }
+
+ ~ParserTester() {
+ delete xmlParser_;
+ }
+
+ bool parse(const std::string& data) {
+ return xmlParser_->parse(data);
+ }
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ parser_->handleStartElement(element, ns, attributes);
+ }
+
+ virtual void handleEndElement(const std::string& element, const std::string& ns) {
+ parser_->handleEndElement(element, ns);
+ }
+
+ virtual void handleCharacterData(const std::string& data) {
+ parser_->handleCharacterData(data);
+ }
+
+ private:
+ XMLParser* xmlParser_;
+ ParserType* parser_;
+ };
}
diff --git a/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp b/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp
index cb01d6f..b2279f8 100644
--- a/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp
+++ b/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp
@@ -14,90 +14,90 @@ using namespace Swift;
class PayloadParserFactoryCollectionTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(PayloadParserFactoryCollectionTest);
- CPPUNIT_TEST(testGetPayloadParserFactory);
- CPPUNIT_TEST(testGetPayloadParserFactory_NoMatchingFactory);
- CPPUNIT_TEST(testGetPayloadParserFactory_TwoMatchingFactories);
- CPPUNIT_TEST(testGetPayloadParserFactory_MatchWithDefaultFactory);
- CPPUNIT_TEST(testGetPayloadParserFactory_NoMatchWithDefaultFactory);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- PayloadParserFactoryCollectionTest() {}
-
- void setUp() {
- }
-
- void tearDown() {
- }
-
- void testGetPayloadParserFactory() {
- PayloadParserFactoryCollection testling;
- DummyFactory factory1("foo");
- testling.addFactory(&factory1);
- DummyFactory factory2("bar");
- testling.addFactory(&factory2);
- DummyFactory factory3("baz");
- testling.addFactory(&factory3);
-
- PayloadParserFactory* factory = testling.getPayloadParserFactory("bar", "", AttributeMap());
-
- CPPUNIT_ASSERT(factory == &factory2);
- }
-
- void testGetPayloadParserFactory_NoMatchingFactory() {
- PayloadParserFactoryCollection testling;
- DummyFactory factory("foo");
-
- CPPUNIT_ASSERT(!testling.getPayloadParserFactory("bar", "", AttributeMap()));
- }
-
- void testGetPayloadParserFactory_TwoMatchingFactories() {
- PayloadParserFactoryCollection testling;
- DummyFactory factory1("foo");
- testling.addFactory(&factory1);
- DummyFactory factory2("foo");
- testling.addFactory(&factory2);
-
- PayloadParserFactory* factory = testling.getPayloadParserFactory("foo", "", AttributeMap());
-
- CPPUNIT_ASSERT(factory == &factory2);
- }
-
- void testGetPayloadParserFactory_MatchWithDefaultFactory() {
- PayloadParserFactoryCollection testling;
- DummyFactory factory1("foo");
- testling.addFactory(&factory1);
- DummyFactory factory2;
- testling.setDefaultFactory(&factory2);
-
- PayloadParserFactory* factory = testling.getPayloadParserFactory("foo", "", AttributeMap());
-
- CPPUNIT_ASSERT(factory == &factory1);
- }
-
- void testGetPayloadParserFactory_NoMatchWithDefaultFactory() {
- PayloadParserFactoryCollection testling;
- DummyFactory factory1("foo");
- testling.addFactory(&factory1);
- DummyFactory factory2;
- testling.setDefaultFactory(&factory2);
-
- PayloadParserFactory* factory = testling.getPayloadParserFactory("baz", "", AttributeMap());
-
- CPPUNIT_ASSERT(factory == &factory2);
- }
-
-
- private:
- struct DummyFactory : public PayloadParserFactory {
- DummyFactory(const std::string& element = "") : element(element) {}
- virtual bool canParse(const std::string& e, const std::string&, const AttributeMap&) const {
- return element.empty() ? true : element == e;
- }
- virtual PayloadParser* createPayloadParser() { return NULL; }
- std::string element;
- };
+ CPPUNIT_TEST_SUITE(PayloadParserFactoryCollectionTest);
+ CPPUNIT_TEST(testGetPayloadParserFactory);
+ CPPUNIT_TEST(testGetPayloadParserFactory_NoMatchingFactory);
+ CPPUNIT_TEST(testGetPayloadParserFactory_TwoMatchingFactories);
+ CPPUNIT_TEST(testGetPayloadParserFactory_MatchWithDefaultFactory);
+ CPPUNIT_TEST(testGetPayloadParserFactory_NoMatchWithDefaultFactory);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ PayloadParserFactoryCollectionTest() {}
+
+ void setUp() {
+ }
+
+ void tearDown() {
+ }
+
+ void testGetPayloadParserFactory() {
+ PayloadParserFactoryCollection testling;
+ DummyFactory factory1("foo");
+ testling.addFactory(&factory1);
+ DummyFactory factory2("bar");
+ testling.addFactory(&factory2);
+ DummyFactory factory3("baz");
+ testling.addFactory(&factory3);
+
+ PayloadParserFactory* factory = testling.getPayloadParserFactory("bar", "", AttributeMap());
+
+ CPPUNIT_ASSERT(factory == &factory2);
+ }
+
+ void testGetPayloadParserFactory_NoMatchingFactory() {
+ PayloadParserFactoryCollection testling;
+ DummyFactory factory("foo");
+
+ CPPUNIT_ASSERT(!testling.getPayloadParserFactory("bar", "", AttributeMap()));
+ }
+
+ void testGetPayloadParserFactory_TwoMatchingFactories() {
+ PayloadParserFactoryCollection testling;
+ DummyFactory factory1("foo");
+ testling.addFactory(&factory1);
+ DummyFactory factory2("foo");
+ testling.addFactory(&factory2);
+
+ PayloadParserFactory* factory = testling.getPayloadParserFactory("foo", "", AttributeMap());
+
+ CPPUNIT_ASSERT(factory == &factory2);
+ }
+
+ void testGetPayloadParserFactory_MatchWithDefaultFactory() {
+ PayloadParserFactoryCollection testling;
+ DummyFactory factory1("foo");
+ testling.addFactory(&factory1);
+ DummyFactory factory2;
+ testling.setDefaultFactory(&factory2);
+
+ PayloadParserFactory* factory = testling.getPayloadParserFactory("foo", "", AttributeMap());
+
+ CPPUNIT_ASSERT(factory == &factory1);
+ }
+
+ void testGetPayloadParserFactory_NoMatchWithDefaultFactory() {
+ PayloadParserFactoryCollection testling;
+ DummyFactory factory1("foo");
+ testling.addFactory(&factory1);
+ DummyFactory factory2;
+ testling.setDefaultFactory(&factory2);
+
+ PayloadParserFactory* factory = testling.getPayloadParserFactory("baz", "", AttributeMap());
+
+ CPPUNIT_ASSERT(factory == &factory2);
+ }
+
+
+ private:
+ struct DummyFactory : public PayloadParserFactory {
+ DummyFactory(const std::string& element = "") : element(element) {}
+ virtual bool canParse(const std::string& e, const std::string&, const AttributeMap&) const {
+ return element.empty() ? true : element == e;
+ }
+ virtual PayloadParser* createPayloadParser() { return NULL; }
+ std::string element;
+ };
};
CPPUNIT_TEST_SUITE_REGISTRATION(PayloadParserFactoryCollectionTest);
diff --git a/Swiften/Parser/UnitTest/PresenceParserTest.cpp b/Swiften/Parser/UnitTest/PresenceParserTest.cpp
index 6dfbefd..2b2c242 100644
--- a/Swiften/Parser/UnitTest/PresenceParserTest.cpp
+++ b/Swiften/Parser/UnitTest/PresenceParserTest.cpp
@@ -14,100 +14,100 @@
using namespace Swift;
class PresenceParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PresenceParserTest);
- CPPUNIT_TEST(testParse_Available);
- CPPUNIT_TEST(testParse_Unavailable);
- CPPUNIT_TEST(testParse_Subscribe);
- CPPUNIT_TEST(testParse_Subscribed);
- CPPUNIT_TEST(testParse_Unsubscribe);
- CPPUNIT_TEST(testParse_Unsubscribed);
- CPPUNIT_TEST(testParse_Probe);
- CPPUNIT_TEST(testParse_Error);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PresenceParserTest);
+ CPPUNIT_TEST(testParse_Available);
+ CPPUNIT_TEST(testParse_Unavailable);
+ CPPUNIT_TEST(testParse_Subscribe);
+ CPPUNIT_TEST(testParse_Subscribed);
+ CPPUNIT_TEST(testParse_Unsubscribe);
+ CPPUNIT_TEST(testParse_Unsubscribed);
+ CPPUNIT_TEST(testParse_Probe);
+ CPPUNIT_TEST(testParse_Error);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- factoryCollection_ = new PayloadParserFactoryCollection();
- }
+ public:
+ void setUp() {
+ factoryCollection_ = new PayloadParserFactoryCollection();
+ }
- void tearDown() {
- delete factoryCollection_;
- }
+ void tearDown() {
+ delete factoryCollection_;
+ }
- void testParse_Available() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Available() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Available, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Available, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Unavailable() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Unavailable() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"unavailable\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"unavailable\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Probe() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Probe() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"probe\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"probe\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Probe, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Probe, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Subscribe() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Subscribe() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"subscribe\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"subscribe\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Subscribe, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Subscribe, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Subscribed() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Subscribed() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"subscribed\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"subscribed\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Subscribed, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Subscribed, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Unsubscribe() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Unsubscribe() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"unsubscribe\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"unsubscribe\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Unsubscribe, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Unsubscribe, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Unsubscribed() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Unsubscribed() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"unsubscribed\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"unsubscribed\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Unsubscribed, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Unsubscribed, testling.getStanzaGeneric()->getType());
+ }
- void testParse_Error() {
- PresenceParser testling(factoryCollection_);
- StanzaParserTester parser(&testling);
+ void testParse_Error() {
+ PresenceParser testling(factoryCollection_);
+ StanzaParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<presence type=\"error\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<presence type=\"error\"/>"));
- CPPUNIT_ASSERT_EQUAL(Presence::Error, testling.getStanzaGeneric()->getType());
- }
+ CPPUNIT_ASSERT_EQUAL(Presence::Error, testling.getStanzaGeneric()->getType());
+ }
- private:
- PayloadParserFactoryCollection* factoryCollection_;
+ private:
+ PayloadParserFactoryCollection* factoryCollection_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PresenceParserTest);
diff --git a/Swiften/Parser/UnitTest/SerializingParserTest.cpp b/Swiften/Parser/UnitTest/SerializingParserTest.cpp
index 67567ee..1b4eb57 100644
--- a/Swiften/Parser/UnitTest/SerializingParserTest.cpp
+++ b/Swiften/Parser/UnitTest/SerializingParserTest.cpp
@@ -14,51 +14,51 @@ using namespace Swift;
class SerializingParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SerializingParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Empty);
- CPPUNIT_TEST(testParse_ToplevelCharacterData);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SerializingParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Empty);
+ CPPUNIT_TEST(testParse_ToplevelCharacterData);
+ CPPUNIT_TEST_SUITE_END();
- public:
- SerializingParserTest() {}
+ public:
+ SerializingParserTest() {}
- void testParse() {
- SerializingParser testling;
- ParserTester<SerializingParser> parser(&testling);
+ void testParse() {
+ SerializingParser testling;
+ ParserTester<SerializingParser> parser(&testling);
- CPPUNIT_ASSERT(parser.parse(
- "<message type=\"chat\" to=\"me@foo.com\">"
- "<body>Hello&lt;&amp;World</body>"
- "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
- "foo<b>bar</b>baz"
- "</html>"
- "</message>"));
+ CPPUNIT_ASSERT(parser.parse(
+ "<message type=\"chat\" to=\"me@foo.com\">"
+ "<body>Hello&lt;&amp;World</body>"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "foo<b>bar</b>baz"
+ "</html>"
+ "</message>"));
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<message to=\"me@foo.com\" type=\"chat\">"
- "<body>Hello&lt;&amp;World</body>"
- "<html xmlns=\"http://www.w3.org/1999/xhtml\">foo<b xmlns=\"http://www.w3.org/1999/xhtml\">bar</b>baz</html>"
- "</message>"), testling.getResult());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<message to=\"me@foo.com\" type=\"chat\">"
+ "<body>Hello&lt;&amp;World</body>"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">foo<b xmlns=\"http://www.w3.org/1999/xhtml\">bar</b>baz</html>"
+ "</message>"), testling.getResult());
+ }
- void testParse_Empty() {
- SerializingParser testling;
+ void testParse_Empty() {
+ SerializingParser testling;
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResult());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResult());
+ }
- void testParse_ToplevelCharacterData() {
- SerializingParser testling;
-
- AttributeMap attributes;
- testling.handleCharacterData("foo");
- testling.handleStartElement("message", "", attributes);
- testling.handleEndElement("message", "");
- testling.handleCharacterData("bar");
+ void testParse_ToplevelCharacterData() {
+ SerializingParser testling;
- CPPUNIT_ASSERT_EQUAL(std::string("<message/>"), testling.getResult());
- }
+ AttributeMap attributes;
+ testling.handleCharacterData("foo");
+ testling.handleStartElement("message", "", attributes);
+ testling.handleEndElement("message", "");
+ testling.handleCharacterData("bar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<message/>"), testling.getResult());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SerializingParserTest);
diff --git a/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp b/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp
index 9a9d00c..4591640 100644
--- a/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp
@@ -14,40 +14,40 @@
using namespace Swift;
class StanzaAckParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StanzaAckParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Invalid);
- CPPUNIT_TEST(testParse_Empty);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StanzaAckParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Invalid);
+ CPPUNIT_TEST(testParse_Empty);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse() {
- StanzaAckParser testling;
- ElementParserTester parser(&testling);
+ public:
+ void testParse() {
+ StanzaAckParser testling;
+ ElementParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<a h=\"12\" xmlns=\"urn:xmpp:sm:2\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<a h=\"12\" xmlns=\"urn:xmpp:sm:2\"/>"));
- CPPUNIT_ASSERT(testling.getElementGeneric()->isValid());
- CPPUNIT_ASSERT_EQUAL(12U, testling.getElementGeneric()->getHandledStanzasCount());
- }
+ CPPUNIT_ASSERT(testling.getElementGeneric()->isValid());
+ CPPUNIT_ASSERT_EQUAL(12U, testling.getElementGeneric()->getHandledStanzasCount());
+ }
- void testParse_Invalid() {
- StanzaAckParser testling;
- ElementParserTester parser(&testling);
+ void testParse_Invalid() {
+ StanzaAckParser testling;
+ ElementParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<a h=\"invalid\" xmlns=\"urn:xmpp:sm:2\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<a h=\"invalid\" xmlns=\"urn:xmpp:sm:2\"/>"));
- CPPUNIT_ASSERT(!testling.getElementGeneric()->isValid());
- }
+ CPPUNIT_ASSERT(!testling.getElementGeneric()->isValid());
+ }
- void testParse_Empty() {
- StanzaAckParser testling;
- ElementParserTester parser(&testling);
+ void testParse_Empty() {
+ StanzaAckParser testling;
+ ElementParserTester parser(&testling);
- CPPUNIT_ASSERT(parser.parse("<a xmlns=\"urn:xmpp:sm:2\"/>"));
+ CPPUNIT_ASSERT(parser.parse("<a xmlns=\"urn:xmpp:sm:2\"/>"));
- CPPUNIT_ASSERT(!testling.getElementGeneric()->isValid());
- }
+ CPPUNIT_ASSERT(!testling.getElementGeneric()->isValid());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StanzaAckParserTest);
diff --git a/Swiften/Parser/UnitTest/StanzaParserTest.cpp b/Swiften/Parser/UnitTest/StanzaParserTest.cpp
index d9f39e7..c081b1b 100644
--- a/Swiften/Parser/UnitTest/StanzaParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StanzaParserTest.cpp
@@ -17,196 +17,196 @@
using namespace Swift;
class StanzaParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StanzaParserTest);
- CPPUNIT_TEST(testHandleEndElement_OnePayload);
- CPPUNIT_TEST(testHandleEndElement_MultiplePayloads);
- CPPUNIT_TEST(testHandleEndElement_StrayCharacterData);
- CPPUNIT_TEST(testHandleEndElement_UnknownPayload);
- CPPUNIT_TEST(testHandleParse_BasicAttributes);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- factoryCollection_ = new PayloadParserFactoryCollection();
- factoryCollection_->addFactory(&factory1_);
- factoryCollection_->addFactory(&factory2_);
- }
-
- void tearDown() {
- delete factoryCollection_;
- }
-
- void testHandleEndElement_OnePayload() {
- MyStanzaParser testling(factoryCollection_);
-
- AttributeMap attributes;
- attributes.addAttribute("foo", "", "fum");
- attributes.addAttribute("bar", "", "baz");
- testling.handleStartElement("mystanza", "", attributes);
- testling.handleStartElement("mypayload1", "", attributes);
- testling.handleStartElement("child", "", attributes);
- testling.handleEndElement("child", "");
- testling.handleEndElement("mypayload1", "");
- testling.handleEndElement("mystanza", "");
-
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>()->hasChild);
- }
-
- void testHandleEndElement_MultiplePayloads() {
- MyStanzaParser testling(factoryCollection_);
-
- AttributeMap attributes;
- testling.handleStartElement("mystanza", "", attributes);
- testling.handleStartElement("mypayload1", "", attributes);
- testling.handleEndElement("mypayload1", "");
- testling.handleStartElement("mypayload2", "", attributes);
- testling.handleEndElement("mypayload2", "");
- testling.handleEndElement("mystanza", "");
-
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
- }
-
- void testHandleEndElement_StrayCharacterData() {
- MyStanzaParser testling(factoryCollection_);
-
- AttributeMap attributes;
- testling.handleStartElement("mystanza", "", attributes);
- testling.handleStartElement("mypayload1", "", attributes);
- testling.handleEndElement("mypayload1", "");
- testling.handleCharacterData("bla");
- testling.handleStartElement("mypayload2", "", attributes);
- testling.handleEndElement("mypayload2", "");
- testling.handleEndElement("mystanza", "");
-
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
- }
-
- void testHandleEndElement_UnknownPayload() {
- MyStanzaParser testling(factoryCollection_);
-
- AttributeMap attributes;
- testling.handleStartElement("mystanza", "", attributes);
- testling.handleStartElement("mypayload1", "", attributes);
- testling.handleEndElement("mypayload1", "");
- testling.handleStartElement("unknown-payload", "", attributes);
- testling.handleStartElement("unknown-payload-child", "", attributes);
- testling.handleEndElement("unknown-payload-child", "");
- testling.handleEndElement("unknown-payload", "");
- testling.handleStartElement("mypayload2", "", attributes);
- testling.handleEndElement("mypayload2", "");
- testling.handleEndElement("mystanza", "");
-
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
- CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
- }
-
- void testHandleParse_BasicAttributes() {
- MyStanzaParser testling(factoryCollection_);
-
- AttributeMap attributes;
- attributes.addAttribute("to", "", "foo@example.com/blo");
- attributes.addAttribute("from", "", "bar@example.com/baz");
- attributes.addAttribute("id", "", "id-123");
- testling.handleStartElement("mystanza", "", attributes);
- testling.handleEndElement("mypayload1", "");
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@example.com/blo"), testling.getStanza()->getTo());
- CPPUNIT_ASSERT_EQUAL(JID("bar@example.com/baz"), testling.getStanza()->getFrom());
- CPPUNIT_ASSERT_EQUAL(std::string("id-123"), testling.getStanza()->getID());
- }
-
- private:
- class MyPayload1 : public Payload
- {
- public:
- MyPayload1() : hasChild(false) {}
-
- bool hasChild;
- };
-
- class MyPayload1Parser : public GenericPayloadParser<MyPayload1>
- {
- public:
- MyPayload1Parser() {}
-
- virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
- if (element != "mypayload1") {
- getPayloadInternal()->hasChild = true;
- }
- }
-
- virtual void handleEndElement(const std::string&, const std::string&) {}
- virtual void handleCharacterData(const std::string&) {}
- };
-
- class MyPayload1ParserFactory : public PayloadParserFactory
- {
- public:
- MyPayload1ParserFactory() {}
-
- PayloadParser* createPayloadParser() { return new MyPayload1Parser(); }
-
- bool canParse(const std::string& element, const std::string&, const AttributeMap&) const {
- return element == "mypayload1";
- }
- };
-
- class MyPayload2 : public Payload
- {
- public:
- MyPayload2() {}
- };
-
- class MyPayload2Parser : public GenericPayloadParser<MyPayload2>
- {
- public:
- MyPayload2Parser() {}
-
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
- virtual void handleEndElement(const std::string&, const std::string&) {}
- virtual void handleCharacterData(const std::string&) {}
- };
-
-
- class MyPayload2ParserFactory : public PayloadParserFactory
- {
- public:
- MyPayload2ParserFactory() {}
-
- PayloadParser* createPayloadParser() { return new MyPayload2Parser(); }
- bool canParse(const std::string& element, const std::string&, const AttributeMap&) const {
- return element == "mypayload2";
- }
- };
-
- class MyStanza : public Stanza
- {
- public:
- MyStanza() {}
- };
-
- class MyStanzaParser : public StanzaParser
- {
- public:
- MyStanzaParser(PayloadParserFactoryCollection* collection) : StanzaParser(collection)
- {
- stanza_ = boost::make_shared<MyStanza>();
- }
-
- virtual boost::shared_ptr<ToplevelElement> getElement() const {
- return stanza_;
- }
-
- private:
- boost::shared_ptr<MyStanza> stanza_;
- };
-
- MyPayload1ParserFactory factory1_;
- MyPayload2ParserFactory factory2_;
- PayloadParserFactoryCollection* factoryCollection_;
+ CPPUNIT_TEST_SUITE(StanzaParserTest);
+ CPPUNIT_TEST(testHandleEndElement_OnePayload);
+ CPPUNIT_TEST(testHandleEndElement_MultiplePayloads);
+ CPPUNIT_TEST(testHandleEndElement_StrayCharacterData);
+ CPPUNIT_TEST(testHandleEndElement_UnknownPayload);
+ CPPUNIT_TEST(testHandleParse_BasicAttributes);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ factoryCollection_ = new PayloadParserFactoryCollection();
+ factoryCollection_->addFactory(&factory1_);
+ factoryCollection_->addFactory(&factory2_);
+ }
+
+ void tearDown() {
+ delete factoryCollection_;
+ }
+
+ void testHandleEndElement_OnePayload() {
+ MyStanzaParser testling(factoryCollection_);
+
+ AttributeMap attributes;
+ attributes.addAttribute("foo", "", "fum");
+ attributes.addAttribute("bar", "", "baz");
+ testling.handleStartElement("mystanza", "", attributes);
+ testling.handleStartElement("mypayload1", "", attributes);
+ testling.handleStartElement("child", "", attributes);
+ testling.handleEndElement("child", "");
+ testling.handleEndElement("mypayload1", "");
+ testling.handleEndElement("mystanza", "");
+
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>()->hasChild);
+ }
+
+ void testHandleEndElement_MultiplePayloads() {
+ MyStanzaParser testling(factoryCollection_);
+
+ AttributeMap attributes;
+ testling.handleStartElement("mystanza", "", attributes);
+ testling.handleStartElement("mypayload1", "", attributes);
+ testling.handleEndElement("mypayload1", "");
+ testling.handleStartElement("mypayload2", "", attributes);
+ testling.handleEndElement("mypayload2", "");
+ testling.handleEndElement("mystanza", "");
+
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
+ }
+
+ void testHandleEndElement_StrayCharacterData() {
+ MyStanzaParser testling(factoryCollection_);
+
+ AttributeMap attributes;
+ testling.handleStartElement("mystanza", "", attributes);
+ testling.handleStartElement("mypayload1", "", attributes);
+ testling.handleEndElement("mypayload1", "");
+ testling.handleCharacterData("bla");
+ testling.handleStartElement("mypayload2", "", attributes);
+ testling.handleEndElement("mypayload2", "");
+ testling.handleEndElement("mystanza", "");
+
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
+ }
+
+ void testHandleEndElement_UnknownPayload() {
+ MyStanzaParser testling(factoryCollection_);
+
+ AttributeMap attributes;
+ testling.handleStartElement("mystanza", "", attributes);
+ testling.handleStartElement("mypayload1", "", attributes);
+ testling.handleEndElement("mypayload1", "");
+ testling.handleStartElement("unknown-payload", "", attributes);
+ testling.handleStartElement("unknown-payload-child", "", attributes);
+ testling.handleEndElement("unknown-payload-child", "");
+ testling.handleEndElement("unknown-payload", "");
+ testling.handleStartElement("mypayload2", "", attributes);
+ testling.handleEndElement("mypayload2", "");
+ testling.handleEndElement("mystanza", "");
+
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload1>());
+ CPPUNIT_ASSERT(testling.getStanza()->getPayload<MyPayload2>());
+ }
+
+ void testHandleParse_BasicAttributes() {
+ MyStanzaParser testling(factoryCollection_);
+
+ AttributeMap attributes;
+ attributes.addAttribute("to", "", "foo@example.com/blo");
+ attributes.addAttribute("from", "", "bar@example.com/baz");
+ attributes.addAttribute("id", "", "id-123");
+ testling.handleStartElement("mystanza", "", attributes);
+ testling.handleEndElement("mypayload1", "");
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@example.com/blo"), testling.getStanza()->getTo());
+ CPPUNIT_ASSERT_EQUAL(JID("bar@example.com/baz"), testling.getStanza()->getFrom());
+ CPPUNIT_ASSERT_EQUAL(std::string("id-123"), testling.getStanza()->getID());
+ }
+
+ private:
+ class MyPayload1 : public Payload
+ {
+ public:
+ MyPayload1() : hasChild(false) {}
+
+ bool hasChild;
+ };
+
+ class MyPayload1Parser : public GenericPayloadParser<MyPayload1>
+ {
+ public:
+ MyPayload1Parser() {}
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
+ if (element != "mypayload1") {
+ getPayloadInternal()->hasChild = true;
+ }
+ }
+
+ virtual void handleEndElement(const std::string&, const std::string&) {}
+ virtual void handleCharacterData(const std::string&) {}
+ };
+
+ class MyPayload1ParserFactory : public PayloadParserFactory
+ {
+ public:
+ MyPayload1ParserFactory() {}
+
+ PayloadParser* createPayloadParser() { return new MyPayload1Parser(); }
+
+ bool canParse(const std::string& element, const std::string&, const AttributeMap&) const {
+ return element == "mypayload1";
+ }
+ };
+
+ class MyPayload2 : public Payload
+ {
+ public:
+ MyPayload2() {}
+ };
+
+ class MyPayload2Parser : public GenericPayloadParser<MyPayload2>
+ {
+ public:
+ MyPayload2Parser() {}
+
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
+ virtual void handleEndElement(const std::string&, const std::string&) {}
+ virtual void handleCharacterData(const std::string&) {}
+ };
+
+
+ class MyPayload2ParserFactory : public PayloadParserFactory
+ {
+ public:
+ MyPayload2ParserFactory() {}
+
+ PayloadParser* createPayloadParser() { return new MyPayload2Parser(); }
+ bool canParse(const std::string& element, const std::string&, const AttributeMap&) const {
+ return element == "mypayload2";
+ }
+ };
+
+ class MyStanza : public Stanza
+ {
+ public:
+ MyStanza() {}
+ };
+
+ class MyStanzaParser : public StanzaParser
+ {
+ public:
+ MyStanzaParser(PayloadParserFactoryCollection* collection) : StanzaParser(collection)
+ {
+ stanza_ = boost::make_shared<MyStanza>();
+ }
+
+ virtual boost::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
+
+ private:
+ boost::shared_ptr<MyStanza> stanza_;
+ };
+
+ MyPayload1ParserFactory factory1_;
+ MyPayload2ParserFactory factory2_;
+ PayloadParserFactoryCollection* factoryCollection_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(StanzaParserTest);
diff --git a/Swiften/Parser/UnitTest/StanzaParserTester.h b/Swiften/Parser/UnitTest/StanzaParserTester.h
index 7d8b22b..36f41c9 100644
--- a/Swiften/Parser/UnitTest/StanzaParserTester.h
+++ b/Swiften/Parser/UnitTest/StanzaParserTester.h
@@ -10,5 +10,5 @@
#include <Swiften/Parser/UnitTest/ParserTester.h>
namespace Swift {
- typedef ParserTester<StanzaParser> StanzaParserTester;
+ typedef ParserTester<StanzaParser> StanzaParserTester;
}
diff --git a/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp b/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp
index f6c9336..031f2f3 100644
--- a/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp
@@ -13,96 +13,96 @@
using namespace Swift;
class StreamFeaturesParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StreamFeaturesParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParse_Empty);
- CPPUNIT_TEST(testParse_AuthenticationHostname);
- CPPUNIT_TEST(testParse_AuthenticationHostnameEmpty);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- StreamFeaturesParser testling;
- ElementParserTester parser(&testling);
-
- CPPUNIT_ASSERT(parser.parse(
- "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
- "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
- "<compression xmlns=\"http://jabber.org/features/compress\">"
- "<method>zlib</method>"
- "<method>lzw</method>"
- "</compression>"
- "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "<mechanism>DIGEST-MD5</mechanism>"
- "<mechanism>PLAIN</mechanism>"
- "</mechanisms>"
- "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
- "<sm xmlns='urn:xmpp:sm:2'/>"
- "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
- "<ver xmlns=\"urn:xmpp:features:rosterver\"/>"
- "</stream:features>"));
-
- StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
- CPPUNIT_ASSERT(element->hasStartTLS());
- CPPUNIT_ASSERT(element->hasSession());
- CPPUNIT_ASSERT(element->hasResourceBind());
- CPPUNIT_ASSERT(element->hasCompressionMethod("zlib"));
- CPPUNIT_ASSERT(element->hasCompressionMethod("lzw"));
- CPPUNIT_ASSERT(element->hasAuthenticationMechanisms());
- CPPUNIT_ASSERT(element->hasAuthenticationMechanism("DIGEST-MD5"));
- CPPUNIT_ASSERT(element->hasAuthenticationMechanism("PLAIN"));
- CPPUNIT_ASSERT(!element->getAuthenticationHostname());
- CPPUNIT_ASSERT(element->hasStreamManagement());
- CPPUNIT_ASSERT(element->hasRosterVersioning());
- }
-
- void testParse_Empty() {
- StreamFeaturesParser testling;
- ElementParserTester parser(&testling);
-
- CPPUNIT_ASSERT(parser.parse("<stream:features xmlns:stream='http://etherx.jabber.org/streams'/>"));
-
- StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
- CPPUNIT_ASSERT(!element->hasStartTLS());
- CPPUNIT_ASSERT(!element->hasSession());
- CPPUNIT_ASSERT(!element->hasResourceBind());
- CPPUNIT_ASSERT(!element->hasAuthenticationMechanisms());
- }
-
- void testParse_AuthenticationHostname() {
- StreamFeaturesParser testling;
- ElementParserTester parser(&testling);
- std::string hostname("auth42.us.example.com");
-
- CPPUNIT_ASSERT(parser.parse(
- "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
- "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "<mechanism>GSSAPI</mechanism>"
- "<hostname xmlns=\"urn:xmpp:domain-based-name:1\">auth42.us.example.com</hostname>"
- "</mechanisms>"
- "</stream:features>"));
-
- StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
- CPPUNIT_ASSERT(element->hasAuthenticationMechanism("GSSAPI"));
- CPPUNIT_ASSERT_EQUAL(*element->getAuthenticationHostname(), hostname);
- }
-
- void testParse_AuthenticationHostnameEmpty() {
- StreamFeaturesParser testling;
- ElementParserTester parser(&testling);
-
- CPPUNIT_ASSERT(parser.parse(
- "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
- "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "<mechanism>GSSAPI</mechanism>"
- "<hostname xmlns=\"urn:xmpp:domain-based-name:1\"></hostname>"
- "</mechanisms>"
- "</stream:features>"));
-
- StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
- CPPUNIT_ASSERT(element->hasAuthenticationMechanism("GSSAPI"));
- CPPUNIT_ASSERT(element->getAuthenticationHostname()->empty());
- }
+ CPPUNIT_TEST_SUITE(StreamFeaturesParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParse_Empty);
+ CPPUNIT_TEST(testParse_AuthenticationHostname);
+ CPPUNIT_TEST(testParse_AuthenticationHostnameEmpty);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ StreamFeaturesParser testling;
+ ElementParserTester parser(&testling);
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
+ "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
+ "<compression xmlns=\"http://jabber.org/features/compress\">"
+ "<method>zlib</method>"
+ "<method>lzw</method>"
+ "</compression>"
+ "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "<mechanism>DIGEST-MD5</mechanism>"
+ "<mechanism>PLAIN</mechanism>"
+ "</mechanisms>"
+ "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
+ "<sm xmlns='urn:xmpp:sm:2'/>"
+ "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
+ "<ver xmlns=\"urn:xmpp:features:rosterver\"/>"
+ "</stream:features>"));
+
+ StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
+ CPPUNIT_ASSERT(element->hasStartTLS());
+ CPPUNIT_ASSERT(element->hasSession());
+ CPPUNIT_ASSERT(element->hasResourceBind());
+ CPPUNIT_ASSERT(element->hasCompressionMethod("zlib"));
+ CPPUNIT_ASSERT(element->hasCompressionMethod("lzw"));
+ CPPUNIT_ASSERT(element->hasAuthenticationMechanisms());
+ CPPUNIT_ASSERT(element->hasAuthenticationMechanism("DIGEST-MD5"));
+ CPPUNIT_ASSERT(element->hasAuthenticationMechanism("PLAIN"));
+ CPPUNIT_ASSERT(!element->getAuthenticationHostname());
+ CPPUNIT_ASSERT(element->hasStreamManagement());
+ CPPUNIT_ASSERT(element->hasRosterVersioning());
+ }
+
+ void testParse_Empty() {
+ StreamFeaturesParser testling;
+ ElementParserTester parser(&testling);
+
+ CPPUNIT_ASSERT(parser.parse("<stream:features xmlns:stream='http://etherx.jabber.org/streams'/>"));
+
+ StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
+ CPPUNIT_ASSERT(!element->hasStartTLS());
+ CPPUNIT_ASSERT(!element->hasSession());
+ CPPUNIT_ASSERT(!element->hasResourceBind());
+ CPPUNIT_ASSERT(!element->hasAuthenticationMechanisms());
+ }
+
+ void testParse_AuthenticationHostname() {
+ StreamFeaturesParser testling;
+ ElementParserTester parser(&testling);
+ std::string hostname("auth42.us.example.com");
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
+ "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "<mechanism>GSSAPI</mechanism>"
+ "<hostname xmlns=\"urn:xmpp:domain-based-name:1\">auth42.us.example.com</hostname>"
+ "</mechanisms>"
+ "</stream:features>"));
+
+ StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
+ CPPUNIT_ASSERT(element->hasAuthenticationMechanism("GSSAPI"));
+ CPPUNIT_ASSERT_EQUAL(*element->getAuthenticationHostname(), hostname);
+ }
+
+ void testParse_AuthenticationHostnameEmpty() {
+ StreamFeaturesParser testling;
+ ElementParserTester parser(&testling);
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<stream:features xmlns:stream='http://etherx.jabber.org/streams'>"
+ "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "<mechanism>GSSAPI</mechanism>"
+ "<hostname xmlns=\"urn:xmpp:domain-based-name:1\"></hostname>"
+ "</mechanisms>"
+ "</stream:features>"));
+
+ StreamFeatures::ref element = boost::dynamic_pointer_cast<StreamFeatures>(testling.getElement());
+ CPPUNIT_ASSERT(element->hasAuthenticationMechanism("GSSAPI"));
+ CPPUNIT_ASSERT(element->getAuthenticationHostname()->empty());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StreamFeaturesParserTest);
diff --git a/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp b/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp
index a39dc4b..7b4a9cc 100644
--- a/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp
@@ -13,22 +13,22 @@
using namespace Swift;
class StreamManagementEnabledParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StreamManagementEnabledParserTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- StreamManagementEnabledParser testling;
- ElementParserTester parser(&testling);
-
- CPPUNIT_ASSERT(parser.parse(
- "<enabled xmlns=\"urn:xmpp:sm:3\" id=\"some-long-sm-id\" resume=\"true\"/>"));
-
- boost::shared_ptr<StreamManagementEnabled> element = boost::dynamic_pointer_cast<StreamManagementEnabled>(testling.getElement());
- CPPUNIT_ASSERT(element->getResumeSupported());
- CPPUNIT_ASSERT_EQUAL(std::string("some-long-sm-id"), element->getResumeID());
- }
+ CPPUNIT_TEST_SUITE(StreamManagementEnabledParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ StreamManagementEnabledParser testling;
+ ElementParserTester parser(&testling);
+
+ CPPUNIT_ASSERT(parser.parse(
+ "<enabled xmlns=\"urn:xmpp:sm:3\" id=\"some-long-sm-id\" resume=\"true\"/>"));
+
+ boost::shared_ptr<StreamManagementEnabled> element = boost::dynamic_pointer_cast<StreamManagementEnabled>(testling.getElement());
+ CPPUNIT_ASSERT(element->getResumeSupported());
+ CPPUNIT_ASSERT_EQUAL(std::string("some-long-sm-id"), element->getResumeID());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StreamManagementEnabledParserTest);
diff --git a/Swiften/Parser/UnitTest/XMLParserTest.cpp b/Swiften/Parser/UnitTest/XMLParserTest.cpp
index 6b7aa93..b593aa7 100644
--- a/Swiften/Parser/UnitTest/XMLParserTest.cpp
+++ b/Swiften/Parser/UnitTest/XMLParserTest.cpp
@@ -21,337 +21,337 @@ using namespace Swift;
template <typename ParserType>
class XMLParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMLParserTest);
- CPPUNIT_TEST(testParse_NestedElements);
- CPPUNIT_TEST(testParse_ElementInNamespacedElement);
- CPPUNIT_TEST(testParse_CharacterData);
- CPPUNIT_TEST(testParse_XMLEntity);
- CPPUNIT_TEST(testParse_NamespacePrefix);
- CPPUNIT_TEST(testParse_UnhandledXML);
- CPPUNIT_TEST(testParse_InvalidXML);
- CPPUNIT_TEST(testParse_InErrorState);
- CPPUNIT_TEST(testParse_Incremental);
- CPPUNIT_TEST(testParse_WhitespaceInAttribute);
- CPPUNIT_TEST(testParse_AttributeWithoutNamespace);
- CPPUNIT_TEST(testParse_AttributeWithNamespace);
- CPPUNIT_TEST(testParse_BillionLaughs);
- CPPUNIT_TEST(testParse_InternalEntity);
- //CPPUNIT_TEST(testParse_UndefinedPrefix);
- //CPPUNIT_TEST(testParse_UndefinedAttributePrefix);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(XMLParserTest);
+ CPPUNIT_TEST(testParse_NestedElements);
+ CPPUNIT_TEST(testParse_ElementInNamespacedElement);
+ CPPUNIT_TEST(testParse_CharacterData);
+ CPPUNIT_TEST(testParse_XMLEntity);
+ CPPUNIT_TEST(testParse_NamespacePrefix);
+ CPPUNIT_TEST(testParse_UnhandledXML);
+ CPPUNIT_TEST(testParse_InvalidXML);
+ CPPUNIT_TEST(testParse_InErrorState);
+ CPPUNIT_TEST(testParse_Incremental);
+ CPPUNIT_TEST(testParse_WhitespaceInAttribute);
+ CPPUNIT_TEST(testParse_AttributeWithoutNamespace);
+ CPPUNIT_TEST(testParse_AttributeWithNamespace);
+ CPPUNIT_TEST(testParse_BillionLaughs);
+ CPPUNIT_TEST(testParse_InternalEntity);
+ //CPPUNIT_TEST(testParse_UndefinedPrefix);
+ //CPPUNIT_TEST(testParse_UndefinedAttributePrefix);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testParse_NestedElements() {
- ParserType testling(&client_);
+ public:
+ void testParse_NestedElements() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse(
- "<iq type=\"get\">"
- "<query xmlns='jabber:iq:version'/>"
- "</iq>"));
+ CPPUNIT_ASSERT(testling.parse(
+ "<iq type=\"get\">"
+ "<query xmlns='jabber:iq:version'/>"
+ "</iq>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("get"), client_.events[0].attributes.getAttribute("type"));
- CPPUNIT_ASSERT_EQUAL(std::string(), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("get"), client_.events[0].attributes.getAttribute("type"));
+ CPPUNIT_ASSERT_EQUAL(std::string(), client_.events[0].ns);
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[1].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[1].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[2].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[2].ns);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[3].data);
- CPPUNIT_ASSERT_EQUAL(std::string(), client_.events[3].ns);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[3].data);
+ CPPUNIT_ASSERT_EQUAL(std::string(), client_.events[3].ns);
+ }
- void testParse_ElementInNamespacedElement() {
- ParserType testling(&client_);
+ void testParse_ElementInNamespacedElement() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse(
- "<query xmlns='jabber:iq:version'>"
- "<name>Swift</name>"
- "</query>"));
+ CPPUNIT_ASSERT(testling.parse(
+ "<query xmlns='jabber:iq:version'>"
+ "<name>Swift</name>"
+ "</query>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(5), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(5), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[0].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[0].ns);
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("name"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("name"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("Swift"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("Swift"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("name"), client_.events[3].data);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[3].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("name"), client_.events[3].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[3].ns);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[4].type);
- CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[4].data);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[4].ns);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[4].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[4].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[4].ns);
+ }
- void testParse_CharacterData() {
- ParserType testling(&client_);
+ void testParse_CharacterData() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse("<html>bla<i>bli</i>blo</html>"));
+ CPPUNIT_ASSERT(testling.parse("<html>bla<i>bli</i>blo</html>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(7), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(7), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("i"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("i"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("bli"), client_.events[3].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("bli"), client_.events[3].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[4].type);
- CPPUNIT_ASSERT_EQUAL(std::string("i"), client_.events[4].data);
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[4].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("i"), client_.events[4].data);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[5].type);
- CPPUNIT_ASSERT_EQUAL(std::string("blo"), client_.events[5].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[5].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("blo"), client_.events[5].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[6].type);
- CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[6].data);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[6].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[6].data);
+ }
- void testParse_XMLEntity() {
- ParserType testling(&client_);
+ void testParse_XMLEntity() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse("<html>&lt;&gt;</html>"));
+ CPPUNIT_ASSERT(testling.parse("<html>&lt;&gt;</html>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("<"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("<"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string(">"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string(">"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[3].data);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("html"), client_.events[3].data);
+ }
- void testParse_NamespacePrefix() {
- ParserType testling(&client_);
+ void testParse_NamespacePrefix() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse("<p:x xmlns:p='bla'><p:y/></p:x>"));
+ CPPUNIT_ASSERT(testling.parse("<p:x xmlns:p='bla'><p:y/></p:x>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("x"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("x"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[0].ns);
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("y"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("y"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].ns);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("y"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[2].ns);
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("y"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[2].ns);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("x"), client_.events[3].data);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[3].ns);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("x"), client_.events[3].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[3].ns);
+ }
- void testParse_UnhandledXML() {
- ParserType testling(&client_);
+ void testParse_UnhandledXML() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse("<iq><!-- Testing --></iq>"));
+ CPPUNIT_ASSERT(testling.parse("<iq><!-- Testing --></iq>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[1].data);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[1].data);
+ }
- void testParse_InvalidXML() {
- ParserType testling(&client_);
+ void testParse_InvalidXML() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(!testling.parse("<iq><bla></iq>"));
- }
+ CPPUNIT_ASSERT(!testling.parse("<iq><bla></iq>"));
+ }
- void testParse_InErrorState() {
- ParserType testling(&client_);
+ void testParse_InErrorState() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(!testling.parse("<iq><bla></iq>"));
- CPPUNIT_ASSERT(!testling.parse("<iq/>"));
- }
+ CPPUNIT_ASSERT(!testling.parse("<iq><bla></iq>"));
+ CPPUNIT_ASSERT(!testling.parse("<iq/>"));
+ }
- void testParse_Incremental() {
- ParserType testling(&client_);
+ void testParse_Incremental() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse("<iq"));
- CPPUNIT_ASSERT(testling.parse("></iq>"));
+ CPPUNIT_ASSERT(testling.parse("<iq"));
+ CPPUNIT_ASSERT(testling.parse("></iq>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[1].data);
- }
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("iq"), client_.events[1].data);
+ }
- void testParse_WhitespaceInAttribute() {
- ParserType testling(&client_);
+ void testParse_WhitespaceInAttribute() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse(
- "<query xmlns='http://www.xmpp.org/extensions/xep-0084.html#ns-data '>"));
- CPPUNIT_ASSERT(testling.parse(
- "<presence/>"));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), client_.events.size());
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("presence"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("presence"), client_.events[2].data);
- }
+ CPPUNIT_ASSERT(testling.parse(
+ "<query xmlns='http://www.xmpp.org/extensions/xep-0084.html#ns-data '>"));
+ CPPUNIT_ASSERT(testling.parse(
+ "<presence/>"));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), client_.events.size());
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("presence"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("presence"), client_.events[2].data);
+ }
- void testParse_AttributeWithoutNamespace() {
- ParserType testling(&client_);
+ void testParse_AttributeWithoutNamespace() {
+ ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse(
- "<query xmlns='http://swift.im' attr='3'/>"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
- CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
- }
-
- void testParse_AttributeWithNamespace() {
- ParserType testling(&client_);
-
- CPPUNIT_ASSERT(testling.parse(
- "<query xmlns='http://swift.im' xmlns:f='http://swift.im/f' f:attr='3'/>"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
- CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im/f"), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
- }
-
- void testParse_BillionLaughs() {
- ParserType testling(&client_);
-
- CPPUNIT_ASSERT(!testling.parse(
- "<?xml version=\"1.0\"?>"
- "<!DOCTYPE lolz ["
- " <!ENTITY lol \"lol\">"
- " <!ENTITY lol2 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">"
- " <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">"
- " <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">"
- " <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">"
- " <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">"
- " <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">"
- " <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">"
- " <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">"
- "]>"
- "<lolz>&lol9;</lolz>"
- ));
- }
-
- void testParse_InternalEntity() {
- ParserType testling(&client_);
-
- CPPUNIT_ASSERT(!testling.parse("<!DOCTYPE foo [<!ENTITY bar \"Bar\">]><foo>&bar;</foo>"));
- }
-
- void testParse_UndefinedPrefix() {
- ParserType testling(&client_);
-
- CPPUNIT_ASSERT(testling.parse(
- "<foo:bar><bla/></foo:bar>"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
-
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("foo:bar"), client_.events[0].data);
- CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].ns);
-
- CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].data);
- CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[1].ns);
-
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[2].data);
- CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[2].ns);
-
- CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(std::string("foo:bar"), client_.events[3].data);
- CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[3].ns);
- }
-
- void testParse_UndefinedAttributePrefix() {
- ParserType testling(&client_);
-
- CPPUNIT_ASSERT(testling.parse(
- "<foo bar:baz='bla'/>"));
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
- CPPUNIT_ASSERT_EQUAL(std::string("bar:baz"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
- }
-
- private:
- class Client : public XMLParserClient {
- public:
- enum Type { StartElement, EndElement, CharacterData };
- struct Event {
- Event(
- Type type,
- const std::string& data,
- const std::string& ns,
- const AttributeMap& attributes)
- : type(type), data(data), ns(ns), attributes(attributes) {}
- Event(Type type, const std::string& data, const std::string& ns = std::string())
- : type(type), data(data), ns(ns) {}
-
- Type type;
- std::string data;
- std::string ns;
- AttributeMap attributes;
- };
-
- Client() {}
-
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- events.push_back(Event(StartElement, element, ns, attributes));
- }
-
- virtual void handleEndElement(const std::string& element, const std::string& ns) {
- events.push_back(Event(EndElement, element, ns));
- }
-
- virtual void handleCharacterData(const std::string& data) {
- events.push_back(Event(CharacterData, data));
- }
-
- std::vector<Event> events;
- } client_;
+ CPPUNIT_ASSERT(testling.parse(
+ "<query xmlns='http://swift.im' attr='3'/>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
+ }
+
+ void testParse_AttributeWithNamespace() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(testling.parse(
+ "<query xmlns='http://swift.im' xmlns:f='http://swift.im/f' f:attr='3'/>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im/f"), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
+ }
+
+ void testParse_BillionLaughs() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(!testling.parse(
+ "<?xml version=\"1.0\"?>"
+ "<!DOCTYPE lolz ["
+ " <!ENTITY lol \"lol\">"
+ " <!ENTITY lol2 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">"
+ " <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">"
+ " <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">"
+ " <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">"
+ " <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">"
+ " <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">"
+ " <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">"
+ " <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">"
+ "]>"
+ "<lolz>&lol9;</lolz>"
+ ));
+ }
+
+ void testParse_InternalEntity() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(!testling.parse("<!DOCTYPE foo [<!ENTITY bar \"Bar\">]><foo>&bar;</foo>"));
+ }
+
+ void testParse_UndefinedPrefix() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(testling.parse(
+ "<foo:bar><bla/></foo:bar>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(4), client_.events.size());
+
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo:bar"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].ns);
+
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[1].ns);
+
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[2].data);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[2].ns);
+
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo:bar"), client_.events[3].data);
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[3].ns);
+ }
+
+ void testParse_UndefinedAttributePrefix() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(testling.parse(
+ "<foo bar:baz='bla'/>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar:baz"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
+ }
+
+ private:
+ class Client : public XMLParserClient {
+ public:
+ enum Type { StartElement, EndElement, CharacterData };
+ struct Event {
+ Event(
+ Type type,
+ const std::string& data,
+ const std::string& ns,
+ const AttributeMap& attributes)
+ : type(type), data(data), ns(ns), attributes(attributes) {}
+ Event(Type type, const std::string& data, const std::string& ns = std::string())
+ : type(type), data(data), ns(ns) {}
+
+ Type type;
+ std::string data;
+ std::string ns;
+ AttributeMap attributes;
+ };
+
+ Client() {}
+
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ events.push_back(Event(StartElement, element, ns, attributes));
+ }
+
+ virtual void handleEndElement(const std::string& element, const std::string& ns) {
+ events.push_back(Event(EndElement, element, ns));
+ }
+
+ virtual void handleCharacterData(const std::string& data) {
+ events.push_back(Event(CharacterData, data));
+ }
+
+ std::vector<Event> events;
+ } client_;
};
#ifdef HAVE_EXPAT
diff --git a/Swiften/Parser/UnitTest/XMPPParserTest.cpp b/Swiften/Parser/UnitTest/XMPPParserTest.cpp
index 1266350..a4cb7b8 100644
--- a/Swiften/Parser/UnitTest/XMPPParserTest.cpp
+++ b/Swiften/Parser/UnitTest/XMPPParserTest.cpp
@@ -25,173 +25,173 @@
using namespace Swift;
class XMPPParserTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPParserTest);
- CPPUNIT_TEST(testParse_SimpleSession);
- CPPUNIT_TEST(testParse_SimpleClientFromServerSession);
- CPPUNIT_TEST(testParse_Presence);
- CPPUNIT_TEST(testParse_IQ);
- CPPUNIT_TEST(testParse_Message);
- CPPUNIT_TEST(testParse_StreamFeatures);
- CPPUNIT_TEST(testParse_UnknownElement);
- CPPUNIT_TEST(testParse_StrayCharacterData);
- CPPUNIT_TEST(testParse_InvalidStreamStart);
- CPPUNIT_TEST(testParse_ElementEndAfterInvalidStreamStart);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse_SimpleSession() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<?xml version='1.0'?>"));
- CPPUNIT_ASSERT(testling.parse("<stream:stream to='example.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' >"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
- CPPUNIT_ASSERT(testling.parse("<iq/>"));
- CPPUNIT_ASSERT(testling.parse("</stream:stream>"));
-
- CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::StreamStart, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("example.com"), client_.events[0].header->getTo());
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[3].type);
- CPPUNIT_ASSERT_EQUAL(Client::StreamEnd, client_.events[4].type);
- }
-
- void testParse_SimpleClientFromServerSession() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<?xml version='1.0'?>"));
- CPPUNIT_ASSERT(testling.parse("<stream:stream from='example.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='aeab'>"));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::StreamStart, client_.events[0].type);
- CPPUNIT_ASSERT_EQUAL(std::string("example.com"), client_.events[0].header->getFrom());
- CPPUNIT_ASSERT_EQUAL(std::string("aeab"), client_.events[0].header->getID());
- }
-
-
- void testParse_Presence() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
- CPPUNIT_ASSERT(dynamic_cast<Presence*>(client_.events[1].element.get()));
- }
-
- void testParse_IQ() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<iq/>"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
- CPPUNIT_ASSERT(dynamic_cast<IQ*>(client_.events[1].element.get()));
- }
-
- void testParse_Message() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<message/>"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
- CPPUNIT_ASSERT(dynamic_cast<Message*>(client_.events[1].element.get()));
- }
-
- void testParse_StreamFeatures() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<stream:features/>"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
- CPPUNIT_ASSERT(dynamic_cast<StreamFeatures*>(client_.events[1].element.get()));
- }
-
- void testParse_UnknownElement() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
- CPPUNIT_ASSERT(testling.parse("<foo/>"));
- CPPUNIT_ASSERT(testling.parse("<bar/>"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
- CPPUNIT_ASSERT(dynamic_cast<UnknownElement*>(client_.events[2].element.get()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[3].type);
- CPPUNIT_ASSERT(dynamic_cast<UnknownElement*>(client_.events[3].element.get()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[4].type);
- CPPUNIT_ASSERT(dynamic_cast<Presence*>(client_.events[4].element.get()));
- }
-
- void testParse_StrayCharacterData() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
- CPPUNIT_ASSERT(testling.parse("<presence/>"));
- CPPUNIT_ASSERT(testling.parse("bla"));
- CPPUNIT_ASSERT(testling.parse("<iq/>"));
-
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(client_.events.size()));
- CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
- CPPUNIT_ASSERT(dynamic_cast<IQ*>(client_.events[2].element.get()));
- }
-
- void testParse_InvalidStreamStart() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
-
- CPPUNIT_ASSERT(!testling.parse("<tream>"));
- }
-
- void testParse_ElementEndAfterInvalidStreamStart() {
- XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+ CPPUNIT_TEST_SUITE(XMPPParserTest);
+ CPPUNIT_TEST(testParse_SimpleSession);
+ CPPUNIT_TEST(testParse_SimpleClientFromServerSession);
+ CPPUNIT_TEST(testParse_Presence);
+ CPPUNIT_TEST(testParse_IQ);
+ CPPUNIT_TEST(testParse_Message);
+ CPPUNIT_TEST(testParse_StreamFeatures);
+ CPPUNIT_TEST(testParse_UnknownElement);
+ CPPUNIT_TEST(testParse_StrayCharacterData);
+ CPPUNIT_TEST(testParse_InvalidStreamStart);
+ CPPUNIT_TEST(testParse_ElementEndAfterInvalidStreamStart);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse_SimpleSession() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<?xml version='1.0'?>"));
+ CPPUNIT_ASSERT(testling.parse("<stream:stream to='example.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' >"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+ CPPUNIT_ASSERT(testling.parse("<iq/>"));
+ CPPUNIT_ASSERT(testling.parse("</stream:stream>"));
+
+ CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::StreamStart, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("example.com"), client_.events[0].header->getTo());
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[3].type);
+ CPPUNIT_ASSERT_EQUAL(Client::StreamEnd, client_.events[4].type);
+ }
+
+ void testParse_SimpleClientFromServerSession() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<?xml version='1.0'?>"));
+ CPPUNIT_ASSERT(testling.parse("<stream:stream from='example.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='aeab'>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::StreamStart, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("example.com"), client_.events[0].header->getFrom());
+ CPPUNIT_ASSERT_EQUAL(std::string("aeab"), client_.events[0].header->getID());
+ }
+
+
+ void testParse_Presence() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
+ CPPUNIT_ASSERT(dynamic_cast<Presence*>(client_.events[1].element.get()));
+ }
+
+ void testParse_IQ() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<iq/>"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
+ CPPUNIT_ASSERT(dynamic_cast<IQ*>(client_.events[1].element.get()));
+ }
+
+ void testParse_Message() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<message/>"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
+ CPPUNIT_ASSERT(dynamic_cast<Message*>(client_.events[1].element.get()));
+ }
+
+ void testParse_StreamFeatures() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<stream:features/>"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[1].type);
+ CPPUNIT_ASSERT(dynamic_cast<StreamFeatures*>(client_.events[1].element.get()));
+ }
+
+ void testParse_UnknownElement() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+ CPPUNIT_ASSERT(testling.parse("<foo/>"));
+ CPPUNIT_ASSERT(testling.parse("<bar/>"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(5, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
+ CPPUNIT_ASSERT(dynamic_cast<UnknownElement*>(client_.events[2].element.get()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[3].type);
+ CPPUNIT_ASSERT(dynamic_cast<UnknownElement*>(client_.events[3].element.get()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[4].type);
+ CPPUNIT_ASSERT(dynamic_cast<Presence*>(client_.events[4].element.get()));
+ }
+
+ void testParse_StrayCharacterData() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(testling.parse("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"));
+ CPPUNIT_ASSERT(testling.parse("<presence/>"));
+ CPPUNIT_ASSERT(testling.parse("bla"));
+ CPPUNIT_ASSERT(testling.parse("<iq/>"));
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(client_.events.size()));
+ CPPUNIT_ASSERT_EQUAL(Client::ElementEvent, client_.events[2].type);
+ CPPUNIT_ASSERT(dynamic_cast<IQ*>(client_.events[2].element.get()));
+ }
+
+ void testParse_InvalidStreamStart() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
+
+ CPPUNIT_ASSERT(!testling.parse("<tream>"));
+ }
+
+ void testParse_ElementEndAfterInvalidStreamStart() {
+ XMPPParser testling(&client_, &factories_, &xmlParserFactory_);
- CPPUNIT_ASSERT(!testling.parse("<tream/>"));
- }
+ CPPUNIT_ASSERT(!testling.parse("<tream/>"));
+ }
- private:
- class Client : public XMPPParserClient {
- public:
- enum Type { StreamStart, ElementEvent, StreamEnd };
- struct Event {
- Event(Type type, boost::shared_ptr<ToplevelElement> element)
- : type(type), element(element) {}
- Event(Type type, const ProtocolHeader& header) : type(type), header(header) {}
+ private:
+ class Client : public XMPPParserClient {
+ public:
+ enum Type { StreamStart, ElementEvent, StreamEnd };
+ struct Event {
+ Event(Type type, boost::shared_ptr<ToplevelElement> element)
+ : type(type), element(element) {}
+ Event(Type type, const ProtocolHeader& header) : type(type), header(header) {}
- Event(Type type) : type(type) {}
+ Event(Type type) : type(type) {}
- Type type;
- boost::optional<ProtocolHeader> header;
- boost::shared_ptr<ToplevelElement> element;
- };
+ Type type;
+ boost::optional<ProtocolHeader> header;
+ boost::shared_ptr<ToplevelElement> element;
+ };
- Client() {}
-
- void handleStreamStart(const ProtocolHeader& header) {
- events.push_back(Event(StreamStart, header));
- }
-
- void handleElement(boost::shared_ptr<ToplevelElement> element) {
- events.push_back(Event(ElementEvent, element));
- }
-
- void handleStreamEnd() {
- events.push_back(Event(StreamEnd));
- }
-
- std::vector<Event> events;
- } client_;
- PayloadParserFactoryCollection factories_;
- PlatformXMLParserFactory xmlParserFactory_;
+ Client() {}
+
+ void handleStreamStart(const ProtocolHeader& header) {
+ events.push_back(Event(StreamStart, header));
+ }
+
+ void handleElement(boost::shared_ptr<ToplevelElement> element) {
+ events.push_back(Event(ElementEvent, element));
+ }
+
+ void handleStreamEnd() {
+ events.push_back(Event(StreamEnd));
+ }
+
+ std::vector<Event> events;
+ } client_;
+ PayloadParserFactoryCollection factories_;
+ PlatformXMLParserFactory xmlParserFactory_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPParserTest);
diff --git a/Swiften/Parser/UnknownElementParser.h b/Swiften/Parser/UnknownElementParser.h
index 4c7b360..44c5464 100644
--- a/Swiften/Parser/UnknownElementParser.h
+++ b/Swiften/Parser/UnknownElementParser.h
@@ -11,8 +11,8 @@
#include <Swiften/Parser/GenericElementParser.h>
namespace Swift {
- class SWIFTEN_API UnknownElementParser : public GenericElementParser<UnknownElement> {
- public:
- UnknownElementParser() : GenericElementParser<UnknownElement>() {}
- };
+ class SWIFTEN_API UnknownElementParser : public GenericElementParser<UnknownElement> {
+ public:
+ UnknownElementParser() : GenericElementParser<UnknownElement>() {}
+ };
}
diff --git a/Swiften/Parser/UnknownPayloadParser.h b/Swiften/Parser/UnknownPayloadParser.h
index 96e7b77..ca49269 100644
--- a/Swiften/Parser/UnknownPayloadParser.h
+++ b/Swiften/Parser/UnknownPayloadParser.h
@@ -12,16 +12,16 @@
#include <Swiften/Parser/PayloadParser.h>
namespace Swift {
- class SWIFTEN_API UnknownPayloadParser : public PayloadParser {
- public:
- UnknownPayloadParser() {}
+ class SWIFTEN_API UnknownPayloadParser : public PayloadParser {
+ public:
+ UnknownPayloadParser() {}
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
- virtual void handleEndElement(const std::string&, const std::string&) {}
- virtual void handleCharacterData(const std::string&) {}
+ virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
+ virtual void handleEndElement(const std::string&, const std::string&) {}
+ virtual void handleCharacterData(const std::string&) {}
- virtual boost::shared_ptr<Payload> getPayload() const {
- return boost::shared_ptr<Payload>();
- }
- };
+ virtual boost::shared_ptr<Payload> getPayload() const {
+ return boost::shared_ptr<Payload>();
+ }
+ };
}
diff --git a/Swiften/Parser/XMLParser.h b/Swiften/Parser/XMLParser.h
index e1f2d62..8a73c3f 100644
--- a/Swiften/Parser/XMLParser.h
+++ b/Swiften/Parser/XMLParser.h
@@ -11,20 +11,20 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class XMLParserClient;
+ class XMLParserClient;
- class SWIFTEN_API XMLParser {
- public:
- XMLParser(XMLParserClient* client);
- virtual ~XMLParser();
+ class SWIFTEN_API XMLParser {
+ public:
+ XMLParser(XMLParserClient* client);
+ virtual ~XMLParser();
- virtual bool parse(const std::string& data) = 0;
+ virtual bool parse(const std::string& data) = 0;
- XMLParserClient* getClient() const {
- return client_;
- }
+ XMLParserClient* getClient() const {
+ return client_;
+ }
- private:
- XMLParserClient* client_;
- };
+ private:
+ XMLParserClient* client_;
+ };
}
diff --git a/Swiften/Parser/XMLParserClient.h b/Swiften/Parser/XMLParserClient.h
index b387a82..e4346f6 100644
--- a/Swiften/Parser/XMLParserClient.h
+++ b/Swiften/Parser/XMLParserClient.h
@@ -10,12 +10,12 @@
#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
- class SWIFTEN_API XMLParserClient {
- public:
- virtual ~XMLParserClient();
+ class SWIFTEN_API XMLParserClient {
+ public:
+ virtual ~XMLParserClient();
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
- virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
- virtual void handleCharacterData(const std::string& data) = 0;
- };
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
+ virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
+ virtual void handleCharacterData(const std::string& data) = 0;
+ };
}
diff --git a/Swiften/Parser/XMLParserFactory.h b/Swiften/Parser/XMLParserFactory.h
index 235016a..091f45b 100644
--- a/Swiften/Parser/XMLParserFactory.h
+++ b/Swiften/Parser/XMLParserFactory.h
@@ -9,13 +9,13 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class XMLParser;
- class XMLParserClient;
+ class XMLParser;
+ class XMLParserClient;
- class SWIFTEN_API XMLParserFactory {
- public:
- virtual ~XMLParserFactory();
+ class SWIFTEN_API XMLParserFactory {
+ public:
+ virtual ~XMLParserFactory();
- virtual XMLParser* createXMLParser(XMLParserClient*) = 0;
- };
+ virtual XMLParser* createXMLParser(XMLParserClient*) = 0;
+ };
}
diff --git a/Swiften/Parser/XMPPParser.cpp b/Swiften/Parser/XMPPParser.cpp
index 12f2460..10083ba 100644
--- a/Swiften/Parser/XMPPParser.cpp
+++ b/Swiften/Parser/XMPPParser.cpp
@@ -47,159 +47,159 @@
namespace Swift {
XMPPParser::XMPPParser(
- XMPPParserClient* client,
- PayloadParserFactoryCollection* payloadParserFactories,
- XMLParserFactory* xmlParserFactory) :
- xmlParser_(0),
- client_(client),
- payloadParserFactories_(payloadParserFactories),
- level_(0),
- currentElementParser_(0),
- parseErrorOccurred_(false) {
- xmlParser_ = xmlParserFactory->createXMLParser(this);
+ XMPPParserClient* client,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ XMLParserFactory* xmlParserFactory) :
+ xmlParser_(0),
+ client_(client),
+ payloadParserFactories_(payloadParserFactories),
+ level_(0),
+ currentElementParser_(0),
+ parseErrorOccurred_(false) {
+ xmlParser_ = xmlParserFactory->createXMLParser(this);
}
XMPPParser::~XMPPParser() {
- delete currentElementParser_;
- delete xmlParser_;
+ delete currentElementParser_;
+ delete xmlParser_;
}
bool XMPPParser::parse(const std::string& data) {
- bool xmlParseResult = xmlParser_->parse(data);
- return xmlParseResult && !parseErrorOccurred_;
+ bool xmlParseResult = xmlParser_->parse(data);
+ return xmlParseResult && !parseErrorOccurred_;
}
void XMPPParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- if (!parseErrorOccurred_) {
- if (level_ == TopLevel) {
- if (element == "stream" && ns == "http://etherx.jabber.org/streams") {
- ProtocolHeader header;
- header.setFrom(attributes.getAttribute("from"));
- header.setTo(attributes.getAttribute("to"));
- header.setID(attributes.getAttribute("id"));
- header.setVersion(attributes.getAttribute("version"));
- client_->handleStreamStart(header);
- }
- else {
- parseErrorOccurred_ = true;
- }
- }
- else {
- if (level_ == StreamLevel) {
- assert(!currentElementParser_);
- currentElementParser_ = createElementParser(element, ns);
- }
- currentElementParser_->handleStartElement(element, ns, attributes);
- }
- }
- ++level_;
+ if (!parseErrorOccurred_) {
+ if (level_ == TopLevel) {
+ if (element == "stream" && ns == "http://etherx.jabber.org/streams") {
+ ProtocolHeader header;
+ header.setFrom(attributes.getAttribute("from"));
+ header.setTo(attributes.getAttribute("to"));
+ header.setID(attributes.getAttribute("id"));
+ header.setVersion(attributes.getAttribute("version"));
+ client_->handleStreamStart(header);
+ }
+ else {
+ parseErrorOccurred_ = true;
+ }
+ }
+ else {
+ if (level_ == StreamLevel) {
+ assert(!currentElementParser_);
+ currentElementParser_ = createElementParser(element, ns);
+ }
+ currentElementParser_->handleStartElement(element, ns, attributes);
+ }
+ }
+ ++level_;
}
void XMPPParser::handleEndElement(const std::string& element, const std::string& ns) {
- assert(level_ > TopLevel);
- --level_;
- if (!parseErrorOccurred_) {
- if (level_ == TopLevel) {
- assert(element == "stream");
- client_->handleStreamEnd();
- }
- else {
- assert(currentElementParser_);
- currentElementParser_->handleEndElement(element, ns);
- if (level_ == StreamLevel) {
- client_->handleElement(currentElementParser_->getElement());
- delete currentElementParser_;
- currentElementParser_ = NULL;
- }
- }
- }
+ assert(level_ > TopLevel);
+ --level_;
+ if (!parseErrorOccurred_) {
+ if (level_ == TopLevel) {
+ assert(element == "stream");
+ client_->handleStreamEnd();
+ }
+ else {
+ assert(currentElementParser_);
+ currentElementParser_->handleEndElement(element, ns);
+ if (level_ == StreamLevel) {
+ client_->handleElement(currentElementParser_->getElement());
+ delete currentElementParser_;
+ currentElementParser_ = NULL;
+ }
+ }
+ }
}
void XMPPParser::handleCharacterData(const std::string& data) {
- if (!parseErrorOccurred_) {
- if (currentElementParser_) {
- currentElementParser_->handleCharacterData(data);
- }
- //else {
- // std::cerr << "XMPPParser: Ignoring stray character data: " << data << std::endl;
- //}
- }
+ if (!parseErrorOccurred_) {
+ if (currentElementParser_) {
+ currentElementParser_->handleCharacterData(data);
+ }
+ //else {
+ // std::cerr << "XMPPParser: Ignoring stray character data: " << data << std::endl;
+ //}
+ }
}
ElementParser* XMPPParser::createElementParser(const std::string& element, const std::string& ns) {
- if (element == "presence") {
- return new PresenceParser(payloadParserFactories_);
- }
- else if (element == "iq") {
- return new IQParser(payloadParserFactories_);
- }
- else if (element == "message") {
- return new MessageParser(payloadParserFactories_);
- }
- else if (element == "features" && ns == "http://etherx.jabber.org/streams") {
- return new StreamFeaturesParser();
- }
- else if (element == "error" && ns == "http://etherx.jabber.org/streams") {
- return new StreamErrorParser();
- }
- else if (element == "auth") {
- return new AuthRequestParser();
- }
- else if (element == "success") {
- return new AuthSuccessParser();
- }
- else if (element == "failure" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
- return new AuthFailureParser();
- }
- else if (element == "challenge" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
- return new AuthChallengeParser();
- }
- else if (element == "response" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
- return new AuthResponseParser();
- }
- else if (element == "starttls") {
- return new StartTLSParser();
- }
- else if (element == "failure" && ns == "urn:ietf:params:xml:ns:xmpp-tls") {
- return new StartTLSFailureParser();
- }
- else if (element == "compress") {
- return new CompressParser();
- }
- else if (element == "compressed") {
- return new CompressedParser();
- }
- else if (element == "failure" && ns == "http://jabber.org/protocol/compress") {
- return new CompressFailureParser();
- }
- else if (element == "proceed") {
- return new TLSProceedParser();
- }
- else if (element == "enable" && ns == "urn:xmpp:sm:2") {
- return new EnableStreamManagementParser();
- }
- else if (element == "enabled" && ns == "urn:xmpp:sm:2") {
- return new StreamManagementEnabledParser();
- }
- else if (element == "failed" && ns == "urn:xmpp:sm:2") {
- return new StreamManagementFailedParser();
- }
- else if (element == "resume" && ns == "urn:xmpp:sm:2") {
- return new StreamResumeParser();
- }
- else if (element == "resumed" && ns == "urn:xmpp:sm:2") {
- return new StreamResumedParser();
- }
- else if (element == "a" && ns == "urn:xmpp:sm:2") {
- return new StanzaAckParser();
- }
- else if (element == "r" && ns == "urn:xmpp:sm:2") {
- return new StanzaAckRequestParser();
- }
- else if (element == "handshake") {
- return new ComponentHandshakeParser();
- }
- return new UnknownElementParser();
+ if (element == "presence") {
+ return new PresenceParser(payloadParserFactories_);
+ }
+ else if (element == "iq") {
+ return new IQParser(payloadParserFactories_);
+ }
+ else if (element == "message") {
+ return new MessageParser(payloadParserFactories_);
+ }
+ else if (element == "features" && ns == "http://etherx.jabber.org/streams") {
+ return new StreamFeaturesParser();
+ }
+ else if (element == "error" && ns == "http://etherx.jabber.org/streams") {
+ return new StreamErrorParser();
+ }
+ else if (element == "auth") {
+ return new AuthRequestParser();
+ }
+ else if (element == "success") {
+ return new AuthSuccessParser();
+ }
+ else if (element == "failure" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
+ return new AuthFailureParser();
+ }
+ else if (element == "challenge" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
+ return new AuthChallengeParser();
+ }
+ else if (element == "response" && ns == "urn:ietf:params:xml:ns:xmpp-sasl") {
+ return new AuthResponseParser();
+ }
+ else if (element == "starttls") {
+ return new StartTLSParser();
+ }
+ else if (element == "failure" && ns == "urn:ietf:params:xml:ns:xmpp-tls") {
+ return new StartTLSFailureParser();
+ }
+ else if (element == "compress") {
+ return new CompressParser();
+ }
+ else if (element == "compressed") {
+ return new CompressedParser();
+ }
+ else if (element == "failure" && ns == "http://jabber.org/protocol/compress") {
+ return new CompressFailureParser();
+ }
+ else if (element == "proceed") {
+ return new TLSProceedParser();
+ }
+ else if (element == "enable" && ns == "urn:xmpp:sm:2") {
+ return new EnableStreamManagementParser();
+ }
+ else if (element == "enabled" && ns == "urn:xmpp:sm:2") {
+ return new StreamManagementEnabledParser();
+ }
+ else if (element == "failed" && ns == "urn:xmpp:sm:2") {
+ return new StreamManagementFailedParser();
+ }
+ else if (element == "resume" && ns == "urn:xmpp:sm:2") {
+ return new StreamResumeParser();
+ }
+ else if (element == "resumed" && ns == "urn:xmpp:sm:2") {
+ return new StreamResumedParser();
+ }
+ else if (element == "a" && ns == "urn:xmpp:sm:2") {
+ return new StanzaAckParser();
+ }
+ else if (element == "r" && ns == "urn:xmpp:sm:2") {
+ return new StanzaAckRequestParser();
+ }
+ else if (element == "handshake") {
+ return new ComponentHandshakeParser();
+ }
+ return new UnknownElementParser();
}
}
diff --git a/Swiften/Parser/XMPPParser.h b/Swiften/Parser/XMPPParser.h
index dcc98ca..52b2921 100644
--- a/Swiften/Parser/XMPPParser.h
+++ b/Swiften/Parser/XMPPParser.h
@@ -14,43 +14,43 @@
#include <Swiften/Parser/XMLParserClient.h>
namespace Swift {
- class XMLParser;
- class XMPPParserClient;
- class XMLParserFactory;
- class ElementParser;
- class PayloadParserFactoryCollection;
-
- class SWIFTEN_API XMPPParser : public XMLParserClient, boost::noncopyable {
- public:
- XMPPParser(
- XMPPParserClient* parserClient,
- PayloadParserFactoryCollection* payloadParserFactories,
- XMLParserFactory* xmlParserFactory);
- virtual ~XMPPParser();
-
- bool parse(const std::string&);
-
- private:
- virtual void handleStartElement(
- const std::string& element,
- const std::string& ns,
- const AttributeMap& attributes);
- virtual void handleEndElement(const std::string& element, const std::string& ns);
- virtual void handleCharacterData(const std::string& data);
-
- ElementParser* createElementParser(const std::string& element, const std::string& xmlns);
-
- private:
- XMLParser* xmlParser_;
- XMPPParserClient* client_;
- PayloadParserFactoryCollection* payloadParserFactories_;
- enum Level {
- TopLevel = 0,
- StreamLevel = 1,
- ElementLevel = 2
- };
- int level_;
- ElementParser* currentElementParser_;
- bool parseErrorOccurred_;
- };
+ class XMLParser;
+ class XMPPParserClient;
+ class XMLParserFactory;
+ class ElementParser;
+ class PayloadParserFactoryCollection;
+
+ class SWIFTEN_API XMPPParser : public XMLParserClient, boost::noncopyable {
+ public:
+ XMPPParser(
+ XMPPParserClient* parserClient,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ XMLParserFactory* xmlParserFactory);
+ virtual ~XMPPParser();
+
+ bool parse(const std::string&);
+
+ private:
+ virtual void handleStartElement(
+ const std::string& element,
+ const std::string& ns,
+ const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string& ns);
+ virtual void handleCharacterData(const std::string& data);
+
+ ElementParser* createElementParser(const std::string& element, const std::string& xmlns);
+
+ private:
+ XMLParser* xmlParser_;
+ XMPPParserClient* client_;
+ PayloadParserFactoryCollection* payloadParserFactories_;
+ enum Level {
+ TopLevel = 0,
+ StreamLevel = 1,
+ ElementLevel = 2
+ };
+ int level_;
+ ElementParser* currentElementParser_;
+ bool parseErrorOccurred_;
+ };
}
diff --git a/Swiften/Parser/XMPPParserClient.h b/Swiften/Parser/XMPPParserClient.h
index a3ba54e..73f8119 100644
--- a/Swiften/Parser/XMPPParserClient.h
+++ b/Swiften/Parser/XMPPParserClient.h
@@ -12,15 +12,15 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
-
- class ProtocolHeader;
- class SWIFTEN_API XMPPParserClient {
- public:
- virtual ~XMPPParserClient();
+ class ProtocolHeader;
- virtual void handleStreamStart(const ProtocolHeader&) = 0;
- virtual void handleElement(boost::shared_ptr<ToplevelElement>) = 0;
- virtual void handleStreamEnd() = 0;
- };
+ class SWIFTEN_API XMPPParserClient {
+ public:
+ virtual ~XMPPParserClient();
+
+ virtual void handleStreamStart(const ProtocolHeader&) = 0;
+ virtual void handleElement(boost::shared_ptr<ToplevelElement>) = 0;
+ virtual void handleStreamEnd() = 0;
+ };
}
diff --git a/Swiften/Presence/DirectedPresenceSender.cpp b/Swiften/Presence/DirectedPresenceSender.cpp
index 3d24211..a3deea5 100644
--- a/Swiften/Presence/DirectedPresenceSender.cpp
+++ b/Swiften/Presence/DirectedPresenceSender.cpp
@@ -14,29 +14,29 @@ DirectedPresenceSender::DirectedPresenceSender(PresenceSender* sender) : sender(
}
void DirectedPresenceSender::sendPresence(boost::shared_ptr<Presence> presence) {
- if (!sender->isAvailable()) {
- return;
- }
+ if (!sender->isAvailable()) {
+ return;
+ }
- sender->sendPresence(presence);
+ sender->sendPresence(presence);
- if (!presence->getTo().isValid()) {
- boost::shared_ptr<Presence> presenceCopy(new Presence(*presence));
- foreach(const JID& jid, directedPresenceReceivers) {
- presenceCopy->setTo(jid);
- sender->sendPresence(presenceCopy);
- }
+ if (!presence->getTo().isValid()) {
+ boost::shared_ptr<Presence> presenceCopy(new Presence(*presence));
+ foreach(const JID& jid, directedPresenceReceivers) {
+ presenceCopy->setTo(jid);
+ sender->sendPresence(presenceCopy);
+ }
- lastSentUndirectedPresence = presence;
- }
+ 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;
+ boost::optional<Presence::ref> presenceCopy = lastSentUndirectedPresence ? boost::optional<Presence::ref>((*lastSentUndirectedPresence)->clone()) : boost::optional<Presence::ref>();
+ return presenceCopy;
}
/**
@@ -45,14 +45,14 @@ boost::optional<Presence::ref> DirectedPresenceSender::getLastSentUndirectedPres
* @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) {
- boost::shared_ptr<Presence> presenceCopy((*lastSentUndirectedPresence)->clone());
- presenceCopy->setTo(jid);
- sender->sendPresence(presenceCopy);
- }
- }
+ directedPresenceReceivers.insert(jid);
+ if (sendPresence == AndSendPresence && sender->isAvailable()) {
+ if (lastSentUndirectedPresence && (*lastSentUndirectedPresence)->getType() == Presence::Available) {
+ boost::shared_ptr<Presence> presenceCopy((*lastSentUndirectedPresence)->clone());
+ presenceCopy->setTo(jid);
+ sender->sendPresence(presenceCopy);
+ }
+ }
}
/**
@@ -61,17 +61,17 @@ void DirectedPresenceSender::addDirectedPresenceReceiver(const JID& jid, SendPre
* @param sendPresence Also send presence type=unavailable immediately to jid.
*/
void DirectedPresenceSender::removeDirectedPresenceReceiver(const JID& jid, SendPresence sendPresence) {
- directedPresenceReceivers.erase(jid);
- if (sendPresence == AndSendPresence && sender->isAvailable()) {
- boost::shared_ptr<Presence> presence(new Presence());
- presence->setType(Presence::Unavailable);
- presence->setTo(jid);
- sender->sendPresence(presence);
- }
+ directedPresenceReceivers.erase(jid);
+ if (sendPresence == AndSendPresence && sender->isAvailable()) {
+ boost::shared_ptr<Presence> presence(new Presence());
+ presence->setType(Presence::Unavailable);
+ presence->setTo(jid);
+ sender->sendPresence(presence);
+ }
}
bool DirectedPresenceSender::isAvailable() const {
- return sender->isAvailable();
+ return sender->isAvailable();
}
}
diff --git a/Swiften/Presence/DirectedPresenceSender.h b/Swiften/Presence/DirectedPresenceSender.h
index c8e8043..a397776 100644
--- a/Swiften/Presence/DirectedPresenceSender.h
+++ b/Swiften/Presence/DirectedPresenceSender.h
@@ -15,23 +15,23 @@
#include <Swiften/Presence/PresenceSender.h>
namespace Swift {
- class SWIFTEN_API DirectedPresenceSender : public PresenceSender {
- public:
- enum SendPresence {AndSendPresence, DontSendPresence};
- DirectedPresenceSender(PresenceSender*);
+ class SWIFTEN_API DirectedPresenceSender : public PresenceSender {
+ public:
+ enum SendPresence {AndSendPresence, DontSendPresence};
+ DirectedPresenceSender(PresenceSender*);
- void addDirectedPresenceReceiver(const JID&, SendPresence);
- void removeDirectedPresenceReceiver(const JID&, SendPresence);
+ void addDirectedPresenceReceiver(const JID&, SendPresence);
+ void removeDirectedPresenceReceiver(const JID&, SendPresence);
- void sendPresence(Presence::ref);
+ void sendPresence(Presence::ref);
- boost::optional<Presence::ref> getLastSentUndirectedPresence() const;
+ boost::optional<Presence::ref> getLastSentUndirectedPresence() const;
- bool isAvailable() const;
+ bool isAvailable() const;
- private:
- boost::optional<Presence::ref> lastSentUndirectedPresence;
- PresenceSender* sender;
- std::set<JID> directedPresenceReceivers;
- };
+ private:
+ boost::optional<Presence::ref> lastSentUndirectedPresence;
+ PresenceSender* sender;
+ std::set<JID> directedPresenceReceivers;
+ };
}
diff --git a/Swiften/Presence/PayloadAddingPresenceSender.cpp b/Swiften/Presence/PayloadAddingPresenceSender.cpp
index 750e364..2f55374 100644
--- a/Swiften/Presence/PayloadAddingPresenceSender.cpp
+++ b/Swiften/Presence/PayloadAddingPresenceSender.cpp
@@ -12,37 +12,37 @@ PayloadAddingPresenceSender::PayloadAddingPresenceSender(PresenceSender* sender)
}
void PayloadAddingPresenceSender::sendPresence(Presence::ref presence) {
- if (presence->isAvailable()) {
- if (!presence->getTo().isValid()) {
- lastSentPresence = presence;
- }
- }
- else {
- lastSentPresence.reset();
- }
- if (payload) {
- Presence::ref sentPresence = Presence::create(presence);
- sentPresence->updatePayload(payload);
- sender->sendPresence(sentPresence);
- }
- else {
- sender->sendPresence(presence);
- }
+ if (presence->isAvailable()) {
+ if (!presence->getTo().isValid()) {
+ lastSentPresence = presence;
+ }
+ }
+ else {
+ lastSentPresence.reset();
+ }
+ if (payload) {
+ Presence::ref sentPresence = Presence::create(presence);
+ sentPresence->updatePayload(payload);
+ sender->sendPresence(sentPresence);
+ }
+ else {
+ sender->sendPresence(presence);
+ }
}
bool PayloadAddingPresenceSender::isAvailable() const {
- return sender->isAvailable();
+ return sender->isAvailable();
}
void PayloadAddingPresenceSender::setPayload(boost::shared_ptr<Payload> payload) {
- this->payload = payload;
- if (lastSentPresence) {
- sendPresence(lastSentPresence);
- }
+ this->payload = payload;
+ if (lastSentPresence) {
+ sendPresence(lastSentPresence);
+ }
}
void PayloadAddingPresenceSender::reset() {
- lastSentPresence.reset();
+ lastSentPresence.reset();
}
}
diff --git a/Swiften/Presence/PayloadAddingPresenceSender.h b/Swiften/Presence/PayloadAddingPresenceSender.h
index 37f47c5..edb9484 100644
--- a/Swiften/Presence/PayloadAddingPresenceSender.h
+++ b/Swiften/Presence/PayloadAddingPresenceSender.h
@@ -11,39 +11,39 @@
#include <Swiften/Presence/PresenceSender.h>
namespace Swift {
- class StanzaChannel;
-
- /**
- * This presence sender adds payloads to outgoing presences.
- *
- * This class isn't meant to be used with directed presence.
- */
- class SWIFTEN_API PayloadAddingPresenceSender : public PresenceSender {
- public:
- PayloadAddingPresenceSender(PresenceSender*);
-
- void sendPresence(boost::shared_ptr<Presence>);
- bool isAvailable() const;
-
- /**
- * Sets the payload to be added to outgoing presences.
- * If initial presence has been sent, this will resend the last sent presence
- * with an updated payload. Initial presence is reset when unavailable presence is
- * sent, or when reset() is called.
- */
- void setPayload(boost::shared_ptr<Payload>);
-
- /**
- * Resets the presence sender.
- * This puts the presence sender back in the initial state (before initial
- * presence has been sent).
- * This also resets the chained sender.
- */
- void reset();
-
- private:
- boost::shared_ptr<Presence> lastSentPresence;
- PresenceSender* sender;
- boost::shared_ptr<Payload> payload;
- };
+ class StanzaChannel;
+
+ /**
+ * This presence sender adds payloads to outgoing presences.
+ *
+ * This class isn't meant to be used with directed presence.
+ */
+ class SWIFTEN_API PayloadAddingPresenceSender : public PresenceSender {
+ public:
+ PayloadAddingPresenceSender(PresenceSender*);
+
+ void sendPresence(boost::shared_ptr<Presence>);
+ bool isAvailable() const;
+
+ /**
+ * Sets the payload to be added to outgoing presences.
+ * If initial presence has been sent, this will resend the last sent presence
+ * with an updated payload. Initial presence is reset when unavailable presence is
+ * sent, or when reset() is called.
+ */
+ void setPayload(boost::shared_ptr<Payload>);
+
+ /**
+ * Resets the presence sender.
+ * This puts the presence sender back in the initial state (before initial
+ * presence has been sent).
+ * This also resets the chained sender.
+ */
+ void reset();
+
+ private:
+ boost::shared_ptr<Presence> lastSentPresence;
+ PresenceSender* sender;
+ boost::shared_ptr<Payload> payload;
+ };
}
diff --git a/Swiften/Presence/PresenceOracle.cpp b/Swiften/Presence/PresenceOracle.cpp
index 8623529..c2c1152 100644
--- a/Swiften/Presence/PresenceOracle.cpp
+++ b/Swiften/Presence/PresenceOracle.cpp
@@ -18,202 +18,202 @@
namespace Swift {
PresenceOracle::PresenceOracle(StanzaChannel* stanzaChannel, XMPPRoster* roster) : stanzaChannel_(stanzaChannel), xmppRoster_(roster) {
- stanzaChannel_->onPresenceReceived.connect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
- stanzaChannel_->onAvailableChanged.connect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
- xmppRoster_->onJIDRemoved.connect(boost::bind(&PresenceOracle::handleJIDRemoved, this, _1));
+ stanzaChannel_->onPresenceReceived.connect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
+ stanzaChannel_->onAvailableChanged.connect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
+ xmppRoster_->onJIDRemoved.connect(boost::bind(&PresenceOracle::handleJIDRemoved, this, _1));
}
PresenceOracle::~PresenceOracle() {
- stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
- stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
- xmppRoster_->onJIDRemoved.disconnect(boost::bind(&PresenceOracle::handleJIDRemoved, this, _1));
+ stanzaChannel_->onPresenceReceived.disconnect(boost::bind(&PresenceOracle::handleIncomingPresence, this, _1));
+ stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&PresenceOracle::handleStanzaChannelAvailableChanged, this, _1));
+ xmppRoster_->onJIDRemoved.disconnect(boost::bind(&PresenceOracle::handleJIDRemoved, this, _1));
}
void PresenceOracle::handleStanzaChannelAvailableChanged(bool available) {
- if (available) {
- entries_.clear();
- }
+ if (available) {
+ entries_.clear();
+ }
}
void PresenceOracle::handleIncomingPresence(Presence::ref presence) {
- JID bareJID(presence->getFrom().toBare());
- if (presence->getType() == Presence::Subscribe) {
- }
- else {
- Presence::ref passedPresence = presence;
- if (presence->getType() == Presence::Unsubscribe) {
- /* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
- passedPresence = Presence::ref(new Presence());
- passedPresence->setType(Presence::Unavailable);
- passedPresence->setFrom(bareJID);
- passedPresence->setStatus(presence->getStatus());
- }
- PresenceMap jidMap = entries_[bareJID];
- if (passedPresence->getFrom().isBare() && presence->getType() == Presence::Unavailable) {
- /* Have a bare-JID only presence of offline */
- jidMap.clear();
- } else if (passedPresence->getType() == Presence::Available) {
- /* Don't have a bare-JID only offline presence once there are available presences */
- jidMap.erase(bareJID);
- }
- if (passedPresence->getType() == Presence::Unavailable && jidMap.size() > 1) {
- jidMap.erase(passedPresence->getFrom());
- } else {
- jidMap[passedPresence->getFrom()] = passedPresence;
- }
- entries_[bareJID] = jidMap;
- onPresenceChange(passedPresence);
- }
+ JID bareJID(presence->getFrom().toBare());
+ if (presence->getType() == Presence::Subscribe) {
+ }
+ else {
+ Presence::ref passedPresence = presence;
+ if (presence->getType() == Presence::Unsubscribe) {
+ /* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
+ passedPresence = Presence::ref(new Presence());
+ passedPresence->setType(Presence::Unavailable);
+ passedPresence->setFrom(bareJID);
+ passedPresence->setStatus(presence->getStatus());
+ }
+ PresenceMap jidMap = entries_[bareJID];
+ if (passedPresence->getFrom().isBare() && presence->getType() == Presence::Unavailable) {
+ /* Have a bare-JID only presence of offline */
+ jidMap.clear();
+ } else if (passedPresence->getType() == Presence::Available) {
+ /* Don't have a bare-JID only offline presence once there are available presences */
+ jidMap.erase(bareJID);
+ }
+ if (passedPresence->getType() == Presence::Unavailable && jidMap.size() > 1) {
+ jidMap.erase(passedPresence->getFrom());
+ } else {
+ jidMap[passedPresence->getFrom()] = passedPresence;
+ }
+ entries_[bareJID] = jidMap;
+ onPresenceChange(passedPresence);
+ }
}
void PresenceOracle::handleJIDRemoved(const JID& removedJID) {
- /* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
- Presence::ref unavailablePresence = Presence::ref(new Presence());
- unavailablePresence->setType(Presence::Unavailable);
- unavailablePresence->setFrom(removedJID);
+ /* 3921bis says that we don't follow up with an unavailable, so simulate this ourselves */
+ Presence::ref unavailablePresence = Presence::ref(new Presence());
+ unavailablePresence->setType(Presence::Unavailable);
+ unavailablePresence->setFrom(removedJID);
- if (entries_.find(removedJID) != entries_.end()) {
- entries_[removedJID].clear();
- entries_[removedJID][removedJID] = unavailablePresence;
- }
+ if (entries_.find(removedJID) != entries_.end()) {
+ entries_[removedJID].clear();
+ entries_[removedJID][removedJID] = unavailablePresence;
+ }
- onPresenceChange(unavailablePresence);
+ onPresenceChange(unavailablePresence);
}
Presence::ref PresenceOracle::getLastPresence(const JID& jid) const {
- PresencesMap::const_iterator i = entries_.find(jid.toBare());
- if (i == entries_.end()) {
- return Presence::ref();
- }
- PresenceMap presenceMap = i->second;
- PresenceMap::const_iterator j = presenceMap.find(jid);
- if (j != presenceMap.end()) {
- return j->second;
- }
- else {
- return Presence::ref();
- }
+ PresencesMap::const_iterator i = entries_.find(jid.toBare());
+ if (i == entries_.end()) {
+ return Presence::ref();
+ }
+ PresenceMap presenceMap = i->second;
+ PresenceMap::const_iterator j = presenceMap.find(jid);
+ if (j != presenceMap.end()) {
+ return j->second;
+ }
+ else {
+ return Presence::ref();
+ }
}
std::vector<Presence::ref> PresenceOracle::getAllPresence(const JID& bareJID) const {
- std::vector<Presence::ref> results;
- PresencesMap::const_iterator i = entries_.find(bareJID);
- if (i == entries_.end()) {
- return results;
- }
- PresenceMap presenceMap = i->second;
- PresenceMap::const_iterator j = presenceMap.begin();
- for (; j != presenceMap.end(); ++j) {
- Presence::ref current = j->second;
- results.push_back(current);
- }
- return results;
+ std::vector<Presence::ref> results;
+ PresencesMap::const_iterator i = entries_.find(bareJID);
+ if (i == entries_.end()) {
+ return results;
+ }
+ PresenceMap presenceMap = i->second;
+ PresenceMap::const_iterator j = presenceMap.begin();
+ for (; j != presenceMap.end(); ++j) {
+ Presence::ref current = j->second;
+ results.push_back(current);
+ }
+ return results;
}
struct PresenceAccountCmp {
- static int preferenceFromStatusShow(StatusShow::Type showType) {
- switch (showType) {
- case StatusShow::FFC:
- return 5;
- case StatusShow::Online:
- return 4;
- case StatusShow::DND:
- return 3;
- case StatusShow::Away:
- return 2;
- case StatusShow::XA:
- return 1;
- case StatusShow::None:
- return 0;
- }
- assert(false);
- return -1;
- }
-
- bool operator()(const Presence::ref& a, const Presence::ref& b) {
- int aPreference = preferenceFromStatusShow(a->getShow());
- int bPreference = preferenceFromStatusShow(b->getShow());
-
- if (aPreference != bPreference) {
- return aPreference < bPreference;
- }
- if (a->getPriority() != b->getPriority()) {
- return a->getPriority() < b->getPriority();
- }
- return a->getFrom().getResource() < b->getFrom().getResource();
- }
+ static int preferenceFromStatusShow(StatusShow::Type showType) {
+ switch (showType) {
+ case StatusShow::FFC:
+ return 5;
+ case StatusShow::Online:
+ return 4;
+ case StatusShow::DND:
+ return 3;
+ case StatusShow::Away:
+ return 2;
+ case StatusShow::XA:
+ return 1;
+ case StatusShow::None:
+ return 0;
+ }
+ assert(false);
+ return -1;
+ }
+
+ bool operator()(const Presence::ref& a, const Presence::ref& b) {
+ int aPreference = preferenceFromStatusShow(a->getShow());
+ int bPreference = preferenceFromStatusShow(b->getShow());
+
+ if (aPreference != bPreference) {
+ return aPreference < bPreference;
+ }
+ if (a->getPriority() != b->getPriority()) {
+ return a->getPriority() < b->getPriority();
+ }
+ return a->getFrom().getResource() < b->getFrom().getResource();
+ }
};
typedef std::priority_queue<Presence::ref, std::vector<Presence::ref>, PresenceAccountCmp> PresenceAccountPriorityQueue;
Presence::ref PresenceOracle::getActivePresence(const std::vector<Presence::ref> presences) {
- Presence::ref accountPresence;
-
- PresenceAccountPriorityQueue online;
- PresenceAccountPriorityQueue away;
- PresenceAccountPriorityQueue offline;
-
- foreach(Presence::ref presence, presences) {
- switch (presence->getShow()) {
- case StatusShow::Online:
- online.push(presence);
- break;
- case StatusShow::Away:
- away.push(presence);
- break;
- case StatusShow::FFC:
- online.push(presence);
- break;
- case StatusShow::XA:
- away.push(presence);
- break;
- case StatusShow::DND:
- away.push(presence);
- break;
- case StatusShow::None:
- offline.push(presence);
- break;
- }
- }
-
- if (!online.empty()) {
- accountPresence = online.top();
- }
- else if (!away.empty()) {
- accountPresence = away.top();
- }
- else if (!offline.empty()) {
- accountPresence = offline.top();
- }
- return accountPresence;
+ Presence::ref accountPresence;
+
+ PresenceAccountPriorityQueue online;
+ PresenceAccountPriorityQueue away;
+ PresenceAccountPriorityQueue offline;
+
+ foreach(Presence::ref presence, presences) {
+ switch (presence->getShow()) {
+ case StatusShow::Online:
+ online.push(presence);
+ break;
+ case StatusShow::Away:
+ away.push(presence);
+ break;
+ case StatusShow::FFC:
+ online.push(presence);
+ break;
+ case StatusShow::XA:
+ away.push(presence);
+ break;
+ case StatusShow::DND:
+ away.push(presence);
+ break;
+ case StatusShow::None:
+ offline.push(presence);
+ break;
+ }
+ }
+
+ if (!online.empty()) {
+ accountPresence = online.top();
+ }
+ else if (!away.empty()) {
+ accountPresence = away.top();
+ }
+ else if (!offline.empty()) {
+ accountPresence = offline.top();
+ }
+ return accountPresence;
}
Presence::ref PresenceOracle::getAccountPresence(const JID& jid) const {
- Presence::ref accountPresence;
- std::vector<Presence::ref> allPresences = getAllPresence(jid.toBare());
- accountPresence = getActivePresence(allPresences);
- return accountPresence;
+ Presence::ref accountPresence;
+ std::vector<Presence::ref> allPresences = getAllPresence(jid.toBare());
+ accountPresence = getActivePresence(allPresences);
+ return accountPresence;
}
Presence::ref PresenceOracle::getHighestPriorityPresence(const JID& bareJID) const {
- PresencesMap::const_iterator i = entries_.find(bareJID);
- if (i == entries_.end()) {
- return Presence::ref();
- }
- PresenceMap presenceMap = i->second;
- PresenceMap::const_iterator j = presenceMap.begin();
- Presence::ref highest;
- for (; j != presenceMap.end(); ++j) {
- Presence::ref current = j->second;
- if (!highest
- || current->getPriority() > highest->getPriority()
- || (current->getPriority() == highest->getPriority()
- && StatusShow::typeToAvailabilityOrdering(current->getShow()) > StatusShow::typeToAvailabilityOrdering(highest->getShow()))) {
- highest = current;
- }
-
- }
- return highest;
+ PresencesMap::const_iterator i = entries_.find(bareJID);
+ if (i == entries_.end()) {
+ return Presence::ref();
+ }
+ PresenceMap presenceMap = i->second;
+ PresenceMap::const_iterator j = presenceMap.begin();
+ Presence::ref highest;
+ for (; j != presenceMap.end(); ++j) {
+ Presence::ref current = j->second;
+ if (!highest
+ || current->getPriority() > highest->getPriority()
+ || (current->getPriority() == highest->getPriority()
+ && StatusShow::typeToAvailabilityOrdering(current->getShow()) > StatusShow::typeToAvailabilityOrdering(highest->getShow()))) {
+ highest = current;
+ }
+
+ }
+ return highest;
}
}
diff --git a/Swiften/Presence/PresenceOracle.h b/Swiften/Presence/PresenceOracle.h
index a010e8e..7285a3a 100644
--- a/Swiften/Presence/PresenceOracle.h
+++ b/Swiften/Presence/PresenceOracle.h
@@ -14,65 +14,65 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- class StanzaChannel;
- class XMPPRoster;
+ class StanzaChannel;
+ class XMPPRoster;
- /**
- * The PresenceOracle class observes all received presence stanzas for
- * the \ref StanzaChannel class passed in the constructor and maintains a
- * cache.
- */
- class SWIFTEN_API PresenceOracle {
- public:
- PresenceOracle(StanzaChannel* stanzaChannel, XMPPRoster* roster);
- ~PresenceOracle();
+ /**
+ * The PresenceOracle class observes all received presence stanzas for
+ * the \ref StanzaChannel class passed in the constructor and maintains a
+ * cache.
+ */
+ class SWIFTEN_API PresenceOracle {
+ public:
+ PresenceOracle(StanzaChannel* stanzaChannel, XMPPRoster* roster);
+ ~PresenceOracle();
- Presence::ref getLastPresence(const JID&) const;
- Presence::ref getHighestPriorityPresence(const JID& bareJID) const;
- std::vector<Presence::ref> getAllPresence(const JID& bareJID) const;
+ Presence::ref getLastPresence(const JID&) const;
+ Presence::ref getHighestPriorityPresence(const JID& bareJID) const;
+ std::vector<Presence::ref> getAllPresence(const JID& bareJID) const;
- /**
- * \brief Returns the relevant presence for a list of resource presences.
- *
- * It only takes the presence show type into account. Priorities are
- * ignored as various clients set them to arbitrary values unrelated
- * to actual end point availability.
- *
- * The presences of the resources are group by availablilty and sorted
- * by show type in the following order:
- *
- * -# Online
- * -# Free for Chat
- * -# Available
- * -# Away
- * -# DND
- * -# Extended Away
- * -# Away
- * -# Offline
- * -# Unavailable
- */
- static Presence::ref getActivePresence(const std::vector<Presence::ref> presences);
+ /**
+ * \brief Returns the relevant presence for a list of resource presences.
+ *
+ * It only takes the presence show type into account. Priorities are
+ * ignored as various clients set them to arbitrary values unrelated
+ * to actual end point availability.
+ *
+ * The presences of the resources are group by availablilty and sorted
+ * by show type in the following order:
+ *
+ * -# Online
+ * -# Free for Chat
+ * -# Available
+ * -# Away
+ * -# DND
+ * -# Extended Away
+ * -# Away
+ * -# Offline
+ * -# Unavailable
+ */
+ static Presence::ref getActivePresence(const std::vector<Presence::ref> presences);
- /**
- * \brief This considers all online resources of a bare JID and returns
- * the value returned by \ref getActivePresence when passing this list.
- */
- Presence::ref getAccountPresence(const JID& jid) const;
+ /**
+ * \brief This considers all online resources of a bare JID and returns
+ * the value returned by \ref getActivePresence when passing this list.
+ */
+ Presence::ref getAccountPresence(const JID& jid) const;
- public:
- boost::signal<void (Presence::ref)> onPresenceChange;
+ public:
+ boost::signal<void (Presence::ref)> onPresenceChange;
- private:
- void handleIncomingPresence(Presence::ref presence);
- void handleStanzaChannelAvailableChanged(bool);
- void handleJIDRemoved(const JID& removedJID);
+ private:
+ void handleIncomingPresence(Presence::ref presence);
+ void handleStanzaChannelAvailableChanged(bool);
+ void handleJIDRemoved(const JID& removedJID);
- private:
- typedef std::map<JID, Presence::ref> PresenceMap;
- typedef std::map<JID, PresenceMap> PresencesMap;
- PresencesMap entries_;
- StanzaChannel* stanzaChannel_;
- XMPPRoster* xmppRoster_;
- };
+ private:
+ typedef std::map<JID, Presence::ref> PresenceMap;
+ typedef std::map<JID, PresenceMap> PresencesMap;
+ PresencesMap entries_;
+ StanzaChannel* stanzaChannel_;
+ XMPPRoster* xmppRoster_;
+ };
}
diff --git a/Swiften/Presence/PresenceSender.h b/Swiften/Presence/PresenceSender.h
index 97725cb..9d4e175 100644
--- a/Swiften/Presence/PresenceSender.h
+++ b/Swiften/Presence/PresenceSender.h
@@ -10,12 +10,12 @@
#include <Swiften/Elements/Presence.h>
namespace Swift {
- class SWIFTEN_API PresenceSender {
- public:
- virtual ~PresenceSender();
+ class SWIFTEN_API PresenceSender {
+ public:
+ virtual ~PresenceSender();
- virtual void sendPresence(Presence::ref) = 0;
+ virtual void sendPresence(Presence::ref) = 0;
- virtual bool isAvailable() const = 0;
- };
+ virtual bool isAvailable() const = 0;
+ };
}
diff --git a/Swiften/Presence/StanzaChannelPresenceSender.cpp b/Swiften/Presence/StanzaChannelPresenceSender.cpp
index 33db699..a96f40f 100644
--- a/Swiften/Presence/StanzaChannelPresenceSender.cpp
+++ b/Swiften/Presence/StanzaChannelPresenceSender.cpp
@@ -14,11 +14,11 @@ StanzaChannelPresenceSender::StanzaChannelPresenceSender(StanzaChannel* channel)
}
void StanzaChannelPresenceSender::sendPresence(Presence::ref presence) {
- channel->sendPresence(presence);
+ channel->sendPresence(presence);
}
bool StanzaChannelPresenceSender::isAvailable() const {
- return channel->isAvailable();
+ return channel->isAvailable();
}
}
diff --git a/Swiften/Presence/StanzaChannelPresenceSender.h b/Swiften/Presence/StanzaChannelPresenceSender.h
index 4957456..2112d06 100644
--- a/Swiften/Presence/StanzaChannelPresenceSender.h
+++ b/Swiften/Presence/StanzaChannelPresenceSender.h
@@ -10,17 +10,17 @@
#include <Swiften/Presence/PresenceSender.h>
namespace Swift {
- class StanzaChannel;
+ class StanzaChannel;
- class SWIFTEN_API StanzaChannelPresenceSender : public PresenceSender {
- public:
- StanzaChannelPresenceSender(StanzaChannel*);
+ class SWIFTEN_API StanzaChannelPresenceSender : public PresenceSender {
+ public:
+ StanzaChannelPresenceSender(StanzaChannel*);
- void sendPresence(Presence::ref);
+ void sendPresence(Presence::ref);
- bool isAvailable() const;
+ bool isAvailable() const;
- private:
- StanzaChannel* channel;
- };
+ private:
+ StanzaChannel* channel;
+ };
}
diff --git a/Swiften/Presence/SubscriptionManager.cpp b/Swiften/Presence/SubscriptionManager.cpp
index 8420f00..8de152c 100644
--- a/Swiften/Presence/SubscriptionManager.cpp
+++ b/Swiften/Presence/SubscriptionManager.cpp
@@ -14,43 +14,43 @@
namespace Swift {
SubscriptionManager::SubscriptionManager(StanzaChannel* channel) : stanzaChannel(channel) {
- stanzaChannel->onPresenceReceived.connect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
+ stanzaChannel->onPresenceReceived.connect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
}
SubscriptionManager::~SubscriptionManager() {
- stanzaChannel->onPresenceReceived.disconnect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
+ 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);
+ 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);
+ 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);
- stanza->setTo(jid);
- stanzaChannel->sendPresence(stanza);
+ Presence::ref stanza(new Presence());
+ stanza->setType(Presence::Subscribe);
+ stanza->setTo(jid);
+ stanzaChannel->sendPresence(stanza);
}
void SubscriptionManager::handleIncomingPresence(Presence::ref presence) {
- JID bareJID(presence->getFrom().toBare());
- if (presence->getType() == Presence::Subscribe) {
- onPresenceSubscriptionRequest(bareJID, presence->getStatus(), presence);
- }
- else if (presence->getType() == Presence::Unsubscribe) {
- onPresenceSubscriptionRevoked(bareJID, presence->getStatus());
- }
+ JID bareJID(presence->getFrom().toBare());
+ if (presence->getType() == Presence::Subscribe) {
+ onPresenceSubscriptionRequest(bareJID, presence->getStatus(), presence);
+ }
+ else if (presence->getType() == Presence::Unsubscribe) {
+ onPresenceSubscriptionRevoked(bareJID, presence->getStatus());
+ }
}
diff --git a/Swiften/Presence/SubscriptionManager.h b/Swiften/Presence/SubscriptionManager.h
index 7bedba4..d752820 100644
--- a/Swiften/Presence/SubscriptionManager.h
+++ b/Swiften/Presence/SubscriptionManager.h
@@ -15,33 +15,33 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class StanzaChannel;
-
- class SWIFTEN_API SubscriptionManager {
- public:
- SubscriptionManager(StanzaChannel* stanzaChannel);
- ~SubscriptionManager();
-
- void cancelSubscription(const JID& jid);
- void confirmSubscription(const JID& jid);
- void requestSubscription(const JID& jid);
-
- /**
- * This signal is emitted when a presence subscription request is
- * received.
- *
- * The third parameter of this signal is the original presence stanza
- * received. This is useful when the subscriber adds extensions to
- * the request.
- */
- boost::signal<void (const JID&, const std::string&, Presence::ref)> onPresenceSubscriptionRequest;
-
- boost::signal<void (const JID&, const std::string&)> onPresenceSubscriptionRevoked;
-
- private:
- void handleIncomingPresence(Presence::ref presence);
-
- private:
- StanzaChannel* stanzaChannel;
- };
+ class StanzaChannel;
+
+ class SWIFTEN_API SubscriptionManager {
+ public:
+ SubscriptionManager(StanzaChannel* stanzaChannel);
+ ~SubscriptionManager();
+
+ void cancelSubscription(const JID& jid);
+ void confirmSubscription(const JID& jid);
+ void requestSubscription(const JID& jid);
+
+ /**
+ * This signal is emitted when a presence subscription request is
+ * received.
+ *
+ * The third parameter of this signal is the original presence stanza
+ * received. This is useful when the subscriber adds extensions to
+ * the request.
+ */
+ boost::signal<void (const JID&, const std::string&, Presence::ref)> onPresenceSubscriptionRequest;
+
+ boost::signal<void (const JID&, const std::string&)> onPresenceSubscriptionRevoked;
+
+ private:
+ void handleIncomingPresence(Presence::ref presence);
+
+ private:
+ StanzaChannel* stanzaChannel;
+ };
}
diff --git a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
index e3885ad..37679a9 100644
--- a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
+++ b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
@@ -14,140 +14,140 @@
using namespace Swift;
class DirectedPresenceSenderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DirectedPresenceSenderTest);
- CPPUNIT_TEST(testSendPresence);
- CPPUNIT_TEST(testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers);
- CPPUNIT_TEST(testSendPresence_DirectedPresenceWithDirectedPresenceReceivers);
- CPPUNIT_TEST(testAddDirectedPresenceReceiver);
- CPPUNIT_TEST(testAddDirectedPresenceReceiver_WithoutSendingPresence);
- CPPUNIT_TEST(testAddDirectedPresenceReceiver_AfterSendingDirectedPresence);
- CPPUNIT_TEST(testRemoveDirectedPresenceReceiver);
- CPPUNIT_TEST(testRemoveDirectedPresenceReceiver_WithoutSendingPresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- channel = new DummyStanzaChannel();
- testPresence = boost::make_shared<Presence>();
- testPresence->setStatus("Foo");
- secondTestPresence = boost::make_shared<Presence>();
- secondTestPresence->setStatus("Bar");
- stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel);
- }
-
- void tearDown() {
- delete stanzaChannelPresenceSender;
- delete channel;
- }
-
- void testSendPresence() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->sendPresence(testPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
- CPPUNIT_ASSERT(testPresence == presence);
- }
-
- void testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
-
- testling->sendPresence(testPresence);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
- CPPUNIT_ASSERT(testPresence == presence);
- presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[1]);
- CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
- }
-
- void testSendPresence_DirectedPresenceWithDirectedPresenceReceivers() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
- channel->sentStanzas.clear();
-
- testPresence->setTo(JID("foo@bar.com"));
- testling->sendPresence(testPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
- CPPUNIT_ASSERT(testPresence == presence);
- }
-
- void testAddDirectedPresenceReceiver() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->sendPresence(testPresence);
- channel->sentStanzas.clear();
-
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
- CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
- }
-
- void testAddDirectedPresenceReceiver_WithoutSendingPresence() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->sendPresence(testPresence);
- channel->sentStanzas.clear();
-
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel->sentStanzas.size()));
- }
-
- void testAddDirectedPresenceReceiver_AfterSendingDirectedPresence() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->sendPresence(testPresence);
- secondTestPresence->setTo(JID("foo@bar.com"));
- testling->sendPresence(secondTestPresence);
- channel->sentStanzas.clear();
-
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
- CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
- }
-
- void testRemoveDirectedPresenceReceiver() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
-
- testling->removeDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
- testling->sendPresence(testPresence);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0])->getType(), Presence::Unavailable);
- CPPUNIT_ASSERT(channel->sentStanzas[1] == testPresence);
- }
-
- void testRemoveDirectedPresenceReceiver_WithoutSendingPresence() {
- boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
- testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
- channel->sentStanzas.clear();
-
- testling->removeDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
- testling->sendPresence(testPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
- CPPUNIT_ASSERT(channel->sentStanzas[0] == testPresence);
- }
-
- private:
- DirectedPresenceSender* createPresenceSender() {
- return new DirectedPresenceSender(stanzaChannelPresenceSender);
- }
-
- private:
- DummyStanzaChannel* channel;
- StanzaChannelPresenceSender* stanzaChannelPresenceSender;
- boost::shared_ptr<Presence> testPresence;
- boost::shared_ptr<Presence> secondTestPresence;
+ CPPUNIT_TEST_SUITE(DirectedPresenceSenderTest);
+ CPPUNIT_TEST(testSendPresence);
+ CPPUNIT_TEST(testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers);
+ CPPUNIT_TEST(testSendPresence_DirectedPresenceWithDirectedPresenceReceivers);
+ CPPUNIT_TEST(testAddDirectedPresenceReceiver);
+ CPPUNIT_TEST(testAddDirectedPresenceReceiver_WithoutSendingPresence);
+ CPPUNIT_TEST(testAddDirectedPresenceReceiver_AfterSendingDirectedPresence);
+ CPPUNIT_TEST(testRemoveDirectedPresenceReceiver);
+ CPPUNIT_TEST(testRemoveDirectedPresenceReceiver_WithoutSendingPresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ channel = new DummyStanzaChannel();
+ testPresence = boost::make_shared<Presence>();
+ testPresence->setStatus("Foo");
+ secondTestPresence = boost::make_shared<Presence>();
+ secondTestPresence->setStatus("Bar");
+ stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel);
+ }
+
+ void tearDown() {
+ delete stanzaChannelPresenceSender;
+ delete channel;
+ }
+
+ void testSendPresence() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ }
+
+ void testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[1]);
+ CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
+ }
+
+ void testSendPresence_DirectedPresenceWithDirectedPresenceReceivers() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+ channel->sentStanzas.clear();
+
+ testPresence->setTo(JID("foo@bar.com"));
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ }
+
+ void testAddDirectedPresenceReceiver() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->sendPresence(testPresence);
+ channel->sentStanzas.clear();
+
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
+ }
+
+ void testAddDirectedPresenceReceiver_WithoutSendingPresence() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->sendPresence(testPresence);
+ channel->sentStanzas.clear();
+
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel->sentStanzas.size()));
+ }
+
+ void testAddDirectedPresenceReceiver_AfterSendingDirectedPresence() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->sendPresence(testPresence);
+ secondTestPresence->setTo(JID("foo@bar.com"));
+ testling->sendPresence(secondTestPresence);
+ channel->sentStanzas.clear();
+
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
+ }
+
+ void testRemoveDirectedPresenceReceiver() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
+
+ testling->removeDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0])->getType(), Presence::Unavailable);
+ CPPUNIT_ASSERT(channel->sentStanzas[1] == testPresence);
+ }
+
+ void testRemoveDirectedPresenceReceiver_WithoutSendingPresence() {
+ boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
+ channel->sentStanzas.clear();
+
+ testling->removeDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::DontSendPresence);
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ CPPUNIT_ASSERT(channel->sentStanzas[0] == testPresence);
+ }
+
+ private:
+ DirectedPresenceSender* createPresenceSender() {
+ return new DirectedPresenceSender(stanzaChannelPresenceSender);
+ }
+
+ private:
+ DummyStanzaChannel* channel;
+ StanzaChannelPresenceSender* stanzaChannelPresenceSender;
+ boost::shared_ptr<Presence> testPresence;
+ boost::shared_ptr<Presence> secondTestPresence;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DirectedPresenceSenderTest);
diff --git a/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp b/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
index 32f671e..84c0838 100644
--- a/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
+++ b/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
@@ -19,128 +19,128 @@
using namespace Swift;
class PayloadAddingPresenceSenderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PayloadAddingPresenceSenderTest);
- CPPUNIT_TEST(testSetPayloadAddsPayloadOnPresenceSend);
- CPPUNIT_TEST(testSetNullPayloadDoesNotAddPayloadOnPresenceSend);
- CPPUNIT_TEST(testSendPresenceDoesNotAlterOriginalPayload);
- CPPUNIT_TEST(testSetPayloadAfterInitialPresenceResendsPresence);
- CPPUNIT_TEST(testSetPayloadAfterUnavailablePresenceDoesNotResendPresence);
- CPPUNIT_TEST(testSetPayloadAfterResetDoesNotResendPresence);
- CPPUNIT_TEST(testSendDirectedPresenceIsNotResent);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PayloadAddingPresenceSenderTest);
+ CPPUNIT_TEST(testSetPayloadAddsPayloadOnPresenceSend);
+ CPPUNIT_TEST(testSetNullPayloadDoesNotAddPayloadOnPresenceSend);
+ CPPUNIT_TEST(testSendPresenceDoesNotAlterOriginalPayload);
+ CPPUNIT_TEST(testSetPayloadAfterInitialPresenceResendsPresence);
+ CPPUNIT_TEST(testSetPayloadAfterUnavailablePresenceDoesNotResendPresence);
+ CPPUNIT_TEST(testSetPayloadAfterResetDoesNotResendPresence);
+ CPPUNIT_TEST(testSendDirectedPresenceIsNotResent);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- stanzaChannel = new DummyStanzaChannel();
- presenceSender = new StanzaChannelPresenceSender(stanzaChannel);
- }
+ public:
+ void setUp() {
+ stanzaChannel = new DummyStanzaChannel();
+ presenceSender = new StanzaChannelPresenceSender(stanzaChannel);
+ }
- void tearDown() {
- delete presenceSender;
- delete stanzaChannel;
- }
+ void tearDown() {
+ delete presenceSender;
+ delete stanzaChannel;
+ }
- void testSetPayloadAddsPayloadOnPresenceSend() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSetPayloadAddsPayloadOnPresenceSend() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->setPayload(MyPayload::create("foo"));
- testling->sendPresence(Presence::create("bar"));
+ testling->setPayload(MyPayload::create("foo"));
+ testling->sendPresence(Presence::create("bar"));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(0)->getStatus());
- CPPUNIT_ASSERT(stanzaChannel->getStanzaAtIndex<Presence>(0)->getPayload<MyPayload>());
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(0)->getStatus());
+ CPPUNIT_ASSERT(stanzaChannel->getStanzaAtIndex<Presence>(0)->getPayload<MyPayload>());
+ }
- void testSetNullPayloadDoesNotAddPayloadOnPresenceSend() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSetNullPayloadDoesNotAddPayloadOnPresenceSend() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->setPayload(MyPayload::ref());
- testling->sendPresence(Presence::create("bar"));
+ testling->setPayload(MyPayload::ref());
+ testling->sendPresence(Presence::create("bar"));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(0)->getStatus());
- CPPUNIT_ASSERT(!stanzaChannel->getStanzaAtIndex<Presence>(0)->getPayload<MyPayload>());
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(0)->getStatus());
+ CPPUNIT_ASSERT(!stanzaChannel->getStanzaAtIndex<Presence>(0)->getPayload<MyPayload>());
+ }
- void testSendPresenceDoesNotAlterOriginalPayload() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSendPresenceDoesNotAlterOriginalPayload() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->setPayload(MyPayload::create("foo"));
- Presence::ref presence(Presence::create("bar"));
- testling->sendPresence(presence);
+ testling->setPayload(MyPayload::create("foo"));
+ Presence::ref presence(Presence::create("bar"));
+ testling->sendPresence(presence);
- CPPUNIT_ASSERT(!presence->getPayload<MyPayload>());
- }
+ CPPUNIT_ASSERT(!presence->getPayload<MyPayload>());
+ }
- void testSetPayloadAfterInitialPresenceResendsPresence() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSetPayloadAfterInitialPresenceResendsPresence() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->sendPresence(Presence::create("bar"));
- testling->setPayload(MyPayload::create("foo"));
+ testling->sendPresence(Presence::create("bar"));
+ testling->setPayload(MyPayload::create("foo"));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(1)->getStatus());
- CPPUNIT_ASSERT(stanzaChannel->getStanzaAtIndex<Presence>(1)->getPayload<MyPayload>());
- }
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(1)->getStatus());
+ CPPUNIT_ASSERT(stanzaChannel->getStanzaAtIndex<Presence>(1)->getPayload<MyPayload>());
+ }
- void testSetPayloadAfterUnavailablePresenceDoesNotResendPresence() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSetPayloadAfterUnavailablePresenceDoesNotResendPresence() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->sendPresence(Presence::create("bar"));
+ testling->sendPresence(Presence::create("bar"));
- Presence::ref presence = Presence::create("bar");
- presence->setType(Presence::Unavailable);
- testling->sendPresence(presence);
+ Presence::ref presence = Presence::create("bar");
+ presence->setType(Presence::Unavailable);
+ testling->sendPresence(presence);
- testling->setPayload(MyPayload::create("foo"));
+ testling->setPayload(MyPayload::create("foo"));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
- void testSetPayloadAfterResetDoesNotResendPresence() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->sendPresence(Presence::create("bar"));
+ void testSetPayloadAfterResetDoesNotResendPresence() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ testling->sendPresence(Presence::create("bar"));
- testling->reset();
- testling->setPayload(MyPayload::create("foo"));
+ testling->reset();
+ testling->setPayload(MyPayload::create("foo"));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
- void testSendDirectedPresenceIsNotResent() {
- boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
+ void testSendDirectedPresenceIsNotResent() {
+ boost::shared_ptr<PayloadAddingPresenceSender> testling(createSender());
- testling->sendPresence(Presence::create("bar"));
- Presence::ref directedPresence = Presence::create("baz");
- directedPresence->setTo(JID("foo@bar.com"));
- testling->sendPresence(directedPresence);
- testling->setPayload(MyPayload::create("foo"));
+ testling->sendPresence(Presence::create("bar"));
+ Presence::ref directedPresence = Presence::create("baz");
+ directedPresence->setTo(JID("foo@bar.com"));
+ testling->sendPresence(directedPresence);
+ testling->setPayload(MyPayload::create("foo"));
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(2)->getStatus());
- }
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), stanzaChannel->getStanzaAtIndex<Presence>(2)->getStatus());
+ }
- private:
- boost::shared_ptr<PayloadAddingPresenceSender> createSender() {
- boost::shared_ptr<PayloadAddingPresenceSender> sender(new PayloadAddingPresenceSender(presenceSender));
- return sender;
- }
+ private:
+ boost::shared_ptr<PayloadAddingPresenceSender> createSender() {
+ boost::shared_ptr<PayloadAddingPresenceSender> sender(new PayloadAddingPresenceSender(presenceSender));
+ return sender;
+ }
- struct MyPayload : public Payload {
- typedef boost::shared_ptr<MyPayload> ref;
+ struct MyPayload : public Payload {
+ typedef boost::shared_ptr<MyPayload> ref;
- MyPayload(const std::string& body) : body(body) {}
+ MyPayload(const std::string& body) : body(body) {}
- static ref create(const std::string& body) {
- return ref(new MyPayload(body));
- }
+ static ref create(const std::string& body) {
+ return ref(new MyPayload(body));
+ }
- std::string body;
- };
+ std::string body;
+ };
- private:
- DummyStanzaChannel* stanzaChannel;
- StanzaChannelPresenceSender* presenceSender;
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ StanzaChannelPresenceSender* presenceSender;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PayloadAddingPresenceSenderTest);
diff --git a/Swiften/Presence/UnitTest/PresenceOracleTest.cpp b/Swiften/Presence/UnitTest/PresenceOracleTest.cpp
index 6d16d80..4f066c7 100644
--- a/Swiften/Presence/UnitTest/PresenceOracleTest.cpp
+++ b/Swiften/Presence/UnitTest/PresenceOracleTest.cpp
@@ -19,230 +19,230 @@
using namespace Swift;
class PresenceOracleTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PresenceOracleTest);
- CPPUNIT_TEST(testReceivePresence);
- CPPUNIT_TEST(testReceivePresenceFromDifferentResources);
- CPPUNIT_TEST(testSubscriptionRequest);
- CPPUNIT_TEST(testReconnectResetsPresences);
- CPPUNIT_TEST(testHighestPresenceSingle);
- CPPUNIT_TEST(testHighestPresenceMultiple);
- CPPUNIT_TEST(testHighestPresenceGlobal);
- CPPUNIT_TEST(testHighestPresenceChangePriority);
- CPPUNIT_TEST(testGetActivePresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- stanzaChannel_ = new DummyStanzaChannel();
- xmppRoster_ = new XMPPRosterImpl();
-
- oracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
- oracle_->onPresenceChange.connect(boost::bind(&PresenceOracleTest::handlePresenceChange, this, _1));
- subscriptionManager_ = new SubscriptionManager(stanzaChannel_);
- subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&PresenceOracleTest::handlePresenceSubscriptionRequest, this, _1, _2));
- user1 = JID("user1@foo.com/Foo");
- user1alt = JID("user1@foo.com/Bar");
- user2 = JID("user2@bar.com/Bar");
- }
-
- void tearDown() {
- delete subscriptionManager_;
- delete oracle_;
- delete xmppRoster_;
- delete stanzaChannel_;
- }
-
- void testHighestPresenceSingle() {
- JID bareJID("alice@wonderland.lit");
- Presence::ref fiveOn = makeOnline("blah", 5);
- Presence::ref fiveOff = makeOffline("/blah");
- CPPUNIT_ASSERT_EQUAL(Presence::ref(), oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOn);
- CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOff);
- CPPUNIT_ASSERT_EQUAL(fiveOff, oracle_->getHighestPriorityPresence(bareJID));
- }
-
- void testHighestPresenceMultiple() {
- JID bareJID("alice@wonderland.lit");
- Presence::ref fiveOn = makeOnline("blah", 5);
- Presence::ref fiveOff = makeOffline("/blah");
- Presence::ref tenOn = makeOnline("bert", 10);
- Presence::ref tenOff = makeOffline("/bert");
- stanzaChannel_->onPresenceReceived(fiveOn);
- stanzaChannel_->onPresenceReceived(tenOn);
- CPPUNIT_ASSERT_EQUAL(tenOn, oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOff);
- CPPUNIT_ASSERT_EQUAL(tenOn, oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOn);
- stanzaChannel_->onPresenceReceived(tenOff);
- CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
- }
-
- void testHighestPresenceGlobal() {
- JID bareJID("alice@wonderland.lit");
- Presence::ref fiveOn = makeOnline("blah", 5);
- Presence::ref fiveOff = makeOffline("/blah");
- Presence::ref tenOn = makeOnline("bert", 10);
- Presence::ref allOff = makeOffline("");
- stanzaChannel_->onPresenceReceived(fiveOn);
- stanzaChannel_->onPresenceReceived(tenOn);
- stanzaChannel_->onPresenceReceived(allOff);
- CPPUNIT_ASSERT_EQUAL(allOff, oracle_->getHighestPriorityPresence(bareJID));
- }
-
- void testHighestPresenceChangePriority() {
- JID bareJID("alice@wonderland.lit");
- Presence::ref fiveOn = makeOnline("blah", 5);
- Presence::ref fiveOff = makeOffline("/blah");
- Presence::ref tenOn = makeOnline("bert", 10);
- Presence::ref tenOnThree = makeOnline("bert", 3);
- Presence::ref tenOff = makeOffline("/bert");
- stanzaChannel_->onPresenceReceived(fiveOn);
- stanzaChannel_->onPresenceReceived(tenOn);
- stanzaChannel_->onPresenceReceived(tenOnThree);
- CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOff);
- CPPUNIT_ASSERT_EQUAL(tenOnThree, oracle_->getHighestPriorityPresence(bareJID));
- stanzaChannel_->onPresenceReceived(fiveOn);
- CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
- }
-
- void testReceivePresence() {
- boost::shared_ptr<Presence> sentPresence(createPresence(user1));
- stanzaChannel_->onPresenceReceived(sentPresence);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(subscriptionRequests.size()));
- CPPUNIT_ASSERT_EQUAL(sentPresence, changes[0]);
- CPPUNIT_ASSERT_EQUAL(sentPresence, oracle_->getLastPresence(user1));
- }
-
- void testReceivePresenceFromDifferentResources() {
- boost::shared_ptr<Presence> sentPresence1(createPresence(user1));
- boost::shared_ptr<Presence> sentPresence2(createPresence(user1alt));
- stanzaChannel_->onPresenceReceived(sentPresence1);
- stanzaChannel_->onPresenceReceived(sentPresence2);
-
- CPPUNIT_ASSERT_EQUAL(sentPresence1, oracle_->getLastPresence(user1));
- CPPUNIT_ASSERT_EQUAL(sentPresence2, oracle_->getLastPresence(user1alt));
- }
-
- void testSubscriptionRequest() {
- std::string reasonText = "Because I want to";
- JID sentJID = JID("me@example.com");
-
- boost::shared_ptr<Presence> sentPresence(new Presence());
- sentPresence->setType(Presence::Subscribe);
- sentPresence->setFrom(sentJID);
- sentPresence->setStatus(reasonText);
- stanzaChannel_->onPresenceReceived(sentPresence);
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(subscriptionRequests.size()));
- CPPUNIT_ASSERT_EQUAL(sentJID, subscriptionRequests[0].jid);
- CPPUNIT_ASSERT_EQUAL(reasonText, subscriptionRequests[0].reason);
- }
-
- void testReconnectResetsPresences() {
- boost::shared_ptr<Presence> sentPresence(createPresence(user1));
- stanzaChannel_->onPresenceReceived(sentPresence);
- stanzaChannel_->setAvailable(false);
- stanzaChannel_->setAvailable(true);
-
- CPPUNIT_ASSERT(!oracle_->getLastPresence(user1));
- }
-
- void testGetActivePresence() {
- {
- std::vector<Presence::ref> presenceList;
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 10, Presence::Available, StatusShow::Away));
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 5, Presence::Available, StatusShow::Online));
-
- CPPUNIT_ASSERT_EQUAL(StatusShow::Online, PresenceOracle::getActivePresence(presenceList)->getShow());
- }
-
- {
- std::vector<Presence::ref> presenceList;
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 10, Presence::Available, StatusShow::Away));
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 5, Presence::Available, StatusShow::DND));
-
- CPPUNIT_ASSERT_EQUAL(StatusShow::DND, PresenceOracle::getActivePresence(presenceList)->getShow());
- }
-
- {
- std::vector<Presence::ref> presenceList;
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 0, Presence::Available, StatusShow::Online));
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 0, Presence::Available, StatusShow::DND));
-
- CPPUNIT_ASSERT_EQUAL(StatusShow::Online, PresenceOracle::getActivePresence(presenceList)->getShow());
- }
-
- {
- std::vector<Presence::ref> presenceList;
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 1, Presence::Available, StatusShow::Online));
- presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 0, Presence::Available, StatusShow::Online));
-
- CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/resourceA"), PresenceOracle::getActivePresence(presenceList)->getFrom());
- }
- }
-
- private:
- Presence::ref createPresence(const JID &jid, int priority, Presence::Type type, const StatusShow::Type& statusShow) {
- Presence::ref presence = boost::make_shared<Presence>();
- presence->setFrom(jid);
- presence->setPriority(priority);
- presence->setType(type);
- presence->setShow(statusShow);
- return presence;
- }
-
-
- Presence::ref makeOnline(const std::string& resource, int priority) {
- Presence::ref presence(new Presence());
- presence->setPriority(priority);
- presence->setFrom(JID("alice@wonderland.lit/" + resource));
- return presence;
- }
-
- Presence::ref makeOffline(const std::string& resource) {
- Presence::ref presence(new Presence());
- presence->setFrom(JID("alice@wonderland.lit" + resource));
- presence->setType(Presence::Unavailable);
- return presence;
- }
-
- void handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
- changes.push_back(newPresence);
- }
-
- void handlePresenceSubscriptionRequest(const JID& jid, const std::string& reason) {
- SubscriptionRequestInfo subscriptionRequest;
- subscriptionRequest.jid = jid;
- subscriptionRequest.reason = reason;
- subscriptionRequests.push_back(subscriptionRequest);
- }
-
- boost::shared_ptr<Presence> createPresence(const JID& jid) {
- boost::shared_ptr<Presence> sentPresence(new Presence("blarb"));
- sentPresence->setFrom(jid);
- return sentPresence;
- }
-
- private:
- struct SubscriptionRequestInfo {
- JID jid;
- std::string reason;
- };
- PresenceOracle* oracle_;
- SubscriptionManager* subscriptionManager_;
- DummyStanzaChannel* stanzaChannel_;
- XMPPRoster* xmppRoster_;
- std::vector<Presence::ref> changes;
- std::vector<SubscriptionRequestInfo> subscriptionRequests;
- JID user1;
- JID user1alt;
- JID user2;
+ CPPUNIT_TEST_SUITE(PresenceOracleTest);
+ CPPUNIT_TEST(testReceivePresence);
+ CPPUNIT_TEST(testReceivePresenceFromDifferentResources);
+ CPPUNIT_TEST(testSubscriptionRequest);
+ CPPUNIT_TEST(testReconnectResetsPresences);
+ CPPUNIT_TEST(testHighestPresenceSingle);
+ CPPUNIT_TEST(testHighestPresenceMultiple);
+ CPPUNIT_TEST(testHighestPresenceGlobal);
+ CPPUNIT_TEST(testHighestPresenceChangePriority);
+ CPPUNIT_TEST(testGetActivePresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ stanzaChannel_ = new DummyStanzaChannel();
+ xmppRoster_ = new XMPPRosterImpl();
+
+ oracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
+ oracle_->onPresenceChange.connect(boost::bind(&PresenceOracleTest::handlePresenceChange, this, _1));
+ subscriptionManager_ = new SubscriptionManager(stanzaChannel_);
+ subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&PresenceOracleTest::handlePresenceSubscriptionRequest, this, _1, _2));
+ user1 = JID("user1@foo.com/Foo");
+ user1alt = JID("user1@foo.com/Bar");
+ user2 = JID("user2@bar.com/Bar");
+ }
+
+ void tearDown() {
+ delete subscriptionManager_;
+ delete oracle_;
+ delete xmppRoster_;
+ delete stanzaChannel_;
+ }
+
+ void testHighestPresenceSingle() {
+ JID bareJID("alice@wonderland.lit");
+ Presence::ref fiveOn = makeOnline("blah", 5);
+ Presence::ref fiveOff = makeOffline("/blah");
+ CPPUNIT_ASSERT_EQUAL(Presence::ref(), oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOff);
+ CPPUNIT_ASSERT_EQUAL(fiveOff, oracle_->getHighestPriorityPresence(bareJID));
+ }
+
+ void testHighestPresenceMultiple() {
+ JID bareJID("alice@wonderland.lit");
+ Presence::ref fiveOn = makeOnline("blah", 5);
+ Presence::ref fiveOff = makeOffline("/blah");
+ Presence::ref tenOn = makeOnline("bert", 10);
+ Presence::ref tenOff = makeOffline("/bert");
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ stanzaChannel_->onPresenceReceived(tenOn);
+ CPPUNIT_ASSERT_EQUAL(tenOn, oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOff);
+ CPPUNIT_ASSERT_EQUAL(tenOn, oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ stanzaChannel_->onPresenceReceived(tenOff);
+ CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
+ }
+
+ void testHighestPresenceGlobal() {
+ JID bareJID("alice@wonderland.lit");
+ Presence::ref fiveOn = makeOnline("blah", 5);
+ Presence::ref fiveOff = makeOffline("/blah");
+ Presence::ref tenOn = makeOnline("bert", 10);
+ Presence::ref allOff = makeOffline("");
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ stanzaChannel_->onPresenceReceived(tenOn);
+ stanzaChannel_->onPresenceReceived(allOff);
+ CPPUNIT_ASSERT_EQUAL(allOff, oracle_->getHighestPriorityPresence(bareJID));
+ }
+
+ void testHighestPresenceChangePriority() {
+ JID bareJID("alice@wonderland.lit");
+ Presence::ref fiveOn = makeOnline("blah", 5);
+ Presence::ref fiveOff = makeOffline("/blah");
+ Presence::ref tenOn = makeOnline("bert", 10);
+ Presence::ref tenOnThree = makeOnline("bert", 3);
+ Presence::ref tenOff = makeOffline("/bert");
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ stanzaChannel_->onPresenceReceived(tenOn);
+ stanzaChannel_->onPresenceReceived(tenOnThree);
+ CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOff);
+ CPPUNIT_ASSERT_EQUAL(tenOnThree, oracle_->getHighestPriorityPresence(bareJID));
+ stanzaChannel_->onPresenceReceived(fiveOn);
+ CPPUNIT_ASSERT_EQUAL(fiveOn, oracle_->getHighestPriorityPresence(bareJID));
+ }
+
+ void testReceivePresence() {
+ boost::shared_ptr<Presence> sentPresence(createPresence(user1));
+ stanzaChannel_->onPresenceReceived(sentPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(subscriptionRequests.size()));
+ CPPUNIT_ASSERT_EQUAL(sentPresence, changes[0]);
+ CPPUNIT_ASSERT_EQUAL(sentPresence, oracle_->getLastPresence(user1));
+ }
+
+ void testReceivePresenceFromDifferentResources() {
+ boost::shared_ptr<Presence> sentPresence1(createPresence(user1));
+ boost::shared_ptr<Presence> sentPresence2(createPresence(user1alt));
+ stanzaChannel_->onPresenceReceived(sentPresence1);
+ stanzaChannel_->onPresenceReceived(sentPresence2);
+
+ CPPUNIT_ASSERT_EQUAL(sentPresence1, oracle_->getLastPresence(user1));
+ CPPUNIT_ASSERT_EQUAL(sentPresence2, oracle_->getLastPresence(user1alt));
+ }
+
+ void testSubscriptionRequest() {
+ std::string reasonText = "Because I want to";
+ JID sentJID = JID("me@example.com");
+
+ boost::shared_ptr<Presence> sentPresence(new Presence());
+ sentPresence->setType(Presence::Subscribe);
+ sentPresence->setFrom(sentJID);
+ sentPresence->setStatus(reasonText);
+ stanzaChannel_->onPresenceReceived(sentPresence);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(subscriptionRequests.size()));
+ CPPUNIT_ASSERT_EQUAL(sentJID, subscriptionRequests[0].jid);
+ CPPUNIT_ASSERT_EQUAL(reasonText, subscriptionRequests[0].reason);
+ }
+
+ void testReconnectResetsPresences() {
+ boost::shared_ptr<Presence> sentPresence(createPresence(user1));
+ stanzaChannel_->onPresenceReceived(sentPresence);
+ stanzaChannel_->setAvailable(false);
+ stanzaChannel_->setAvailable(true);
+
+ CPPUNIT_ASSERT(!oracle_->getLastPresence(user1));
+ }
+
+ void testGetActivePresence() {
+ {
+ std::vector<Presence::ref> presenceList;
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 10, Presence::Available, StatusShow::Away));
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 5, Presence::Available, StatusShow::Online));
+
+ CPPUNIT_ASSERT_EQUAL(StatusShow::Online, PresenceOracle::getActivePresence(presenceList)->getShow());
+ }
+
+ {
+ std::vector<Presence::ref> presenceList;
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 10, Presence::Available, StatusShow::Away));
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 5, Presence::Available, StatusShow::DND));
+
+ CPPUNIT_ASSERT_EQUAL(StatusShow::DND, PresenceOracle::getActivePresence(presenceList)->getShow());
+ }
+
+ {
+ std::vector<Presence::ref> presenceList;
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 0, Presence::Available, StatusShow::Online));
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 0, Presence::Available, StatusShow::DND));
+
+ CPPUNIT_ASSERT_EQUAL(StatusShow::Online, PresenceOracle::getActivePresence(presenceList)->getShow());
+ }
+
+ {
+ std::vector<Presence::ref> presenceList;
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceA", 1, Presence::Available, StatusShow::Online));
+ presenceList.push_back(createPresence("alice@wonderland.lit/resourceB", 0, Presence::Available, StatusShow::Online));
+
+ CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/resourceA"), PresenceOracle::getActivePresence(presenceList)->getFrom());
+ }
+ }
+
+ private:
+ Presence::ref createPresence(const JID &jid, int priority, Presence::Type type, const StatusShow::Type& statusShow) {
+ Presence::ref presence = boost::make_shared<Presence>();
+ presence->setFrom(jid);
+ presence->setPriority(priority);
+ presence->setType(type);
+ presence->setShow(statusShow);
+ return presence;
+ }
+
+
+ Presence::ref makeOnline(const std::string& resource, int priority) {
+ Presence::ref presence(new Presence());
+ presence->setPriority(priority);
+ presence->setFrom(JID("alice@wonderland.lit/" + resource));
+ return presence;
+ }
+
+ Presence::ref makeOffline(const std::string& resource) {
+ Presence::ref presence(new Presence());
+ presence->setFrom(JID("alice@wonderland.lit" + resource));
+ presence->setType(Presence::Unavailable);
+ return presence;
+ }
+
+ void handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
+ changes.push_back(newPresence);
+ }
+
+ void handlePresenceSubscriptionRequest(const JID& jid, const std::string& reason) {
+ SubscriptionRequestInfo subscriptionRequest;
+ subscriptionRequest.jid = jid;
+ subscriptionRequest.reason = reason;
+ subscriptionRequests.push_back(subscriptionRequest);
+ }
+
+ boost::shared_ptr<Presence> createPresence(const JID& jid) {
+ boost::shared_ptr<Presence> sentPresence(new Presence("blarb"));
+ sentPresence->setFrom(jid);
+ return sentPresence;
+ }
+
+ private:
+ struct SubscriptionRequestInfo {
+ JID jid;
+ std::string reason;
+ };
+ PresenceOracle* oracle_;
+ SubscriptionManager* subscriptionManager_;
+ DummyStanzaChannel* stanzaChannel_;
+ XMPPRoster* xmppRoster_;
+ std::vector<Presence::ref> changes;
+ std::vector<SubscriptionRequestInfo> subscriptionRequests;
+ JID user1;
+ JID user1alt;
+ JID user2;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PresenceOracleTest);
diff --git a/Swiften/PubSub/PubSubManager.h b/Swiften/PubSub/PubSubManager.h
index 572f244..daed7e5 100644
--- a/Swiften/PubSub/PubSubManager.h
+++ b/Swiften/PubSub/PubSubManager.h
@@ -34,19 +34,19 @@
#include <Swiften/PubSub/PubSubUtil.h>
#include <Swiften/Queries/PubSubRequest.h>
#define SWIFTEN_PUBSUBMANAGER_DECLARE_CREATE_REQUEST(payload, container, response) \
- virtual boost::shared_ptr< PubSubRequest<payload> > \
- createRequest(IQ::Type, const JID&, boost::shared_ptr<payload>) = 0;
+ virtual boost::shared_ptr< PubSubRequest<payload> > \
+ createRequest(IQ::Type, const JID&, boost::shared_ptr<payload>) = 0;
namespace Swift {
- class JID;
+ class JID;
- class SWIFTEN_API PubSubManager {
- public:
- virtual ~PubSubManager();
-
- SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
- SWIFTEN_PUBSUBMANAGER_DECLARE_CREATE_REQUEST)
+ class SWIFTEN_API PubSubManager {
+ public:
+ virtual ~PubSubManager();
- boost::signal<void (const JID&, const boost::shared_ptr<PubSubEventPayload>)> onEvent;
- };
+ SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
+ SWIFTEN_PUBSUBMANAGER_DECLARE_CREATE_REQUEST)
+
+ boost::signal<void (const JID&, const boost::shared_ptr<PubSubEventPayload>)> onEvent;
+ };
}
diff --git a/Swiften/PubSub/PubSubManagerImpl.cpp b/Swiften/PubSub/PubSubManagerImpl.cpp
index 7e73b86..b186a08 100644
--- a/Swiften/PubSub/PubSubManagerImpl.cpp
+++ b/Swiften/PubSub/PubSubManagerImpl.cpp
@@ -14,18 +14,18 @@
using namespace Swift;
-PubSubManagerImpl::PubSubManagerImpl(StanzaChannel* stanzaChannel, IQRouter* router) :
- stanzaChannel(stanzaChannel),
- router(router) {
- stanzaChannel->onMessageReceived.connect(boost::bind(&PubSubManagerImpl::handleMessageRecevied, this, _1));
+PubSubManagerImpl::PubSubManagerImpl(StanzaChannel* stanzaChannel, IQRouter* router) :
+ stanzaChannel(stanzaChannel),
+ router(router) {
+ stanzaChannel->onMessageReceived.connect(boost::bind(&PubSubManagerImpl::handleMessageRecevied, this, _1));
}
PubSubManagerImpl::~PubSubManagerImpl() {
- stanzaChannel->onMessageReceived.disconnect(boost::bind(&PubSubManagerImpl::handleMessageRecevied, this, _1));
+ stanzaChannel->onMessageReceived.disconnect(boost::bind(&PubSubManagerImpl::handleMessageRecevied, this, _1));
}
void PubSubManagerImpl::handleMessageRecevied(boost::shared_ptr<Message> message) {
- if (boost::shared_ptr<PubSubEvent> event = message->getPayload<PubSubEvent>()) {
- onEvent(message->getFrom(), event->getPayload());
- }
+ if (boost::shared_ptr<PubSubEvent> event = message->getPayload<PubSubEvent>()) {
+ onEvent(message->getFrom(), event->getPayload());
+ }
}
diff --git a/Swiften/PubSub/PubSubManagerImpl.h b/Swiften/PubSub/PubSubManagerImpl.h
index dda2920..c752b84 100644
--- a/Swiften/PubSub/PubSubManagerImpl.h
+++ b/Swiften/PubSub/PubSubManagerImpl.h
@@ -12,29 +12,29 @@
#include <Swiften/Base/Override.h>
#include <Swiften/PubSub/PubSubManager.h>
#define SWIFTEN_PUBSUBMANAGERIMPL_DECLARE_CREATE_REQUEST(payload, container, response) \
- virtual boost::shared_ptr< PubSubRequest<payload> > \
- createRequest(IQ::Type type, const JID& receiver, boost::shared_ptr<payload> p) SWIFTEN_OVERRIDE { \
- return boost::make_shared< PubSubRequest<payload> >(type, receiver, p, router); \
- }
+ virtual boost::shared_ptr< PubSubRequest<payload> > \
+ createRequest(IQ::Type type, const JID& receiver, boost::shared_ptr<payload> p) SWIFTEN_OVERRIDE { \
+ return boost::make_shared< PubSubRequest<payload> >(type, receiver, p, router); \
+ }
namespace Swift {
- class JID;
- class StanzaChannel;
- class Message;
+ class JID;
+ class StanzaChannel;
+ class Message;
- class SWIFTEN_API PubSubManagerImpl : public PubSubManager {
- public:
- PubSubManagerImpl(StanzaChannel* stanzaChannel, IQRouter* router);
- virtual ~PubSubManagerImpl();
+ class SWIFTEN_API PubSubManagerImpl : public PubSubManager {
+ public:
+ PubSubManagerImpl(StanzaChannel* stanzaChannel, IQRouter* router);
+ virtual ~PubSubManagerImpl();
- SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
- SWIFTEN_PUBSUBMANAGERIMPL_DECLARE_CREATE_REQUEST)
+ SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
+ SWIFTEN_PUBSUBMANAGERIMPL_DECLARE_CREATE_REQUEST)
- private:
- void handleMessageRecevied(boost::shared_ptr<Message>);
+ private:
+ void handleMessageRecevied(boost::shared_ptr<Message>);
- private:
- StanzaChannel* stanzaChannel;
- IQRouter* router;
- };
+ private:
+ StanzaChannel* stanzaChannel;
+ IQRouter* router;
+ };
}
diff --git a/Swiften/PubSub/PubSubUtil.h b/Swiften/PubSub/PubSubUtil.h
index 17e426b..ac23092 100644
--- a/Swiften/PubSub/PubSubUtil.h
+++ b/Swiften/PubSub/PubSubUtil.h
@@ -6,21 +6,21 @@
#pragma once
#define SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(action) \
- action(PubSubCreate, PubSub, PubSubCreate) \
- action(PubSubAffiliations, PubSub, PubSubAffiliations) \
- action(PubSubDefault, PubSub, PubSubDefault) \
- action(PubSubItems, PubSub, PubSubItems) \
- action(PubSubOptions, PubSub, PubSubOptions) \
- action(PubSubPublish, PubSub, PubSubPublish) \
- action(PubSubRetract, PubSub, PubSubRetract) \
- action(PubSubSubscription, PubSub, PubSubSubscription) \
- action(PubSubSubscriptions, PubSub, PubSubSubscriptions) \
- action(PubSubSubscribe, PubSub, PubSubSubscription) \
- action(PubSubUnsubscribe, PubSub, PubSubUnsubscribe) \
- action(PubSubOwnerAffiliations, PubSubOwnerPubSub, PubSubOwnerAffiliations) \
- action(PubSubOwnerConfigure, PubSubOwnerPubSub, PubSubOwnerConfigure) \
- action(PubSubOwnerDefault, PubSubOwnerPubSub, PubSubOwnerDefault) \
- action(PubSubOwnerDelete, PubSubOwnerPubSub, PubSubOwnerDelete) \
- action(PubSubOwnerPurge, PubSubOwnerPubSub, PubSubOwnerPurge) \
- action(PubSubOwnerSubscriptions, PubSubOwnerPubSub, PubSubOwnerSubscriptions)
+ action(PubSubCreate, PubSub, PubSubCreate) \
+ action(PubSubAffiliations, PubSub, PubSubAffiliations) \
+ action(PubSubDefault, PubSub, PubSubDefault) \
+ action(PubSubItems, PubSub, PubSubItems) \
+ action(PubSubOptions, PubSub, PubSubOptions) \
+ action(PubSubPublish, PubSub, PubSubPublish) \
+ action(PubSubRetract, PubSub, PubSubRetract) \
+ action(PubSubSubscription, PubSub, PubSubSubscription) \
+ action(PubSubSubscriptions, PubSub, PubSubSubscriptions) \
+ action(PubSubSubscribe, PubSub, PubSubSubscription) \
+ action(PubSubUnsubscribe, PubSub, PubSubUnsubscribe) \
+ action(PubSubOwnerAffiliations, PubSubOwnerPubSub, PubSubOwnerAffiliations) \
+ action(PubSubOwnerConfigure, PubSubOwnerPubSub, PubSubOwnerConfigure) \
+ action(PubSubOwnerDefault, PubSubOwnerPubSub, PubSubOwnerDefault) \
+ action(PubSubOwnerDelete, PubSubOwnerPubSub, PubSubOwnerDelete) \
+ action(PubSubOwnerPurge, PubSubOwnerPubSub, PubSubOwnerPurge) \
+ action(PubSubOwnerSubscriptions, PubSubOwnerPubSub, PubSubOwnerSubscriptions)
diff --git a/Swiften/QA/ClientTest/ClientTest.cpp b/Swiften/QA/ClientTest/ClientTest.cpp
index 542af09..3a8f303 100644
--- a/Swiften/QA/ClientTest/ClientTest.cpp
+++ b/Swiften/QA/ClientTest/ClientTest.cpp
@@ -25,75 +25,75 @@ static BoostNetworkFactories networkFactories(&eventLoop);
static Client* client = 0;
static bool rosterReceived = false;
enum TestStage {
- FirstConnect,
- Reconnect
+ FirstConnect,
+ Reconnect
};
static TestStage stage;
static ClientOptions options;
static void handleDisconnected(boost::optional<ClientError> e) {
- std::cout << "Disconnected: " << (e ? e.get().getType() : ClientError::UnknownError) << std::endl;
- if (stage == FirstConnect) {
- stage = Reconnect;
- client->connect(options);
- }
- else {
- eventLoop.stop();
- }
+ std::cout << "Disconnected: " << (e ? e.get().getType() : ClientError::UnknownError) << std::endl;
+ if (stage == FirstConnect) {
+ stage = Reconnect;
+ client->connect(options);
+ }
+ else {
+ eventLoop.stop();
+ }
}
static void handleRosterReceived(boost::shared_ptr<Payload>) {
- rosterReceived = true;
- std::cout << "Disconnecting" << std::endl;
- client->disconnect();
+ rosterReceived = true;
+ std::cout << "Disconnecting" << std::endl;
+ client->disconnect();
}
static void handleConnected() {
- std::cout << "Connected" << std::endl;
- rosterReceived = false;
- GetRosterRequest::ref rosterRequest = GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(boost::bind(&handleRosterReceived, _1));
- rosterRequest->send();
+ std::cout << "Connected" << std::endl;
+ rosterReceived = false;
+ GetRosterRequest::ref rosterRequest = GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(boost::bind(&handleRosterReceived, _1));
+ rosterRequest->send();
}
int main(int, char**) {
- char* jid = getenv("SWIFT_CLIENTTEST_JID");
- if (!jid) {
- std::cerr << "Please set the SWIFT_CLIENTTEST_JID environment variable" << std::endl;
- return -1;
- }
- char* pass = getenv("SWIFT_CLIENTTEST_PASS");
- if (!pass) {
- std::cerr << "Please set the SWIFT_CLIENTTEST_PASS environment variable" << std::endl;
- return -1;
- }
-
- char* boshHost = getenv("SWIFT_CLIENTTEST_BOSH_HOST");
- char* boshPort = getenv("SWIFT_CLIENTTEST_BOSH_PORT");
- char* boshPath = getenv("SWIFT_CLIENTTEST_BOSH_PATH");
-
- if (boshHost && boshPort && boshPath) {
- std::cout << "Using BOSH with URL: http://" << boshHost << ":" << boshPort << boshPath << std::endl;
- options.boshURL = URL("http", boshHost, atoi(boshPort), boshPath);
- }
-
- client = new Swift::Client(JID(jid), std::string(pass), &networkFactories);
- ClientXMLTracer* tracer = new ClientXMLTracer(client, !options.boshURL.isEmpty());
- client->onConnected.connect(&handleConnected);
- client->onDisconnected.connect(boost::bind(&handleDisconnected, _1));
- client->setAlwaysTrustCertificates();
- stage = FirstConnect;
- client->connect(options);
-
- {
- Timer::ref timer = networkFactories.getTimerFactory()->createTimer(60000);
- timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
- timer->start();
-
- eventLoop.run();
- }
-
- delete tracer;
- delete client;
- return !rosterReceived;
+ char* jid = getenv("SWIFT_CLIENTTEST_JID");
+ if (!jid) {
+ std::cerr << "Please set the SWIFT_CLIENTTEST_JID environment variable" << std::endl;
+ return -1;
+ }
+ char* pass = getenv("SWIFT_CLIENTTEST_PASS");
+ if (!pass) {
+ std::cerr << "Please set the SWIFT_CLIENTTEST_PASS environment variable" << std::endl;
+ return -1;
+ }
+
+ char* boshHost = getenv("SWIFT_CLIENTTEST_BOSH_HOST");
+ char* boshPort = getenv("SWIFT_CLIENTTEST_BOSH_PORT");
+ char* boshPath = getenv("SWIFT_CLIENTTEST_BOSH_PATH");
+
+ if (boshHost && boshPort && boshPath) {
+ std::cout << "Using BOSH with URL: http://" << boshHost << ":" << boshPort << boshPath << std::endl;
+ options.boshURL = URL("http", boshHost, atoi(boshPort), boshPath);
+ }
+
+ client = new Swift::Client(JID(jid), std::string(pass), &networkFactories);
+ ClientXMLTracer* tracer = new ClientXMLTracer(client, !options.boshURL.isEmpty());
+ client->onConnected.connect(&handleConnected);
+ client->onDisconnected.connect(boost::bind(&handleDisconnected, _1));
+ client->setAlwaysTrustCertificates();
+ stage = FirstConnect;
+ client->connect(options);
+
+ {
+ Timer::ref timer = networkFactories.getTimerFactory()->createTimer(60000);
+ timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
+ timer->start();
+
+ eventLoop.run();
+ }
+
+ delete tracer;
+ delete client;
+ return !rosterReceived;
}
diff --git a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
index a4f145a..b9ec7b8 100644
--- a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
+++ b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
@@ -42,40 +42,40 @@ static boost::shared_ptr<BoostNetworkFactories> networkFactories;
BoostRandomGenerator randGen;
enum Candidate {
- InBandBytestream = 1,
- S5B_Direct = 2,
- S5B_Proxied = 4,
- S5B_Assisted = 8,
+ InBandBytestream = 1,
+ S5B_Direct = 2,
+ S5B_Proxied = 4,
+ S5B_Assisted = 8,
};
class ConcurrentFileTransferTest {
- public:
- ConcurrentFileTransferTest(int clientACandidates, int clientBCandidates) : clientACandidates_(clientACandidates), clientBCandidates_(clientBCandidates) {
+ public:
+ ConcurrentFileTransferTest(int clientACandidates, int clientBCandidates) : clientACandidates_(clientACandidates), clientBCandidates_(clientBCandidates) {
- }
+ }
- private:
- int clientACandidates_;
- boost::shared_ptr<Client> clientA_;
- std::map<std::string, ByteArray> clientASendFiles_;
+ private:
+ int clientACandidates_;
+ boost::shared_ptr<Client> clientA_;
+ std::map<std::string, ByteArray> clientASendFiles_;
- int clientBCandidates_;
- boost::shared_ptr<Client> clientB_;
+ int clientBCandidates_;
+ boost::shared_ptr<Client> clientB_;
};
/**
- * This program tests the concurrent transfer of multiple file-transfers.
- *
+ * This program tests the concurrent transfer of multiple file-transfers.
+ *
*/
int main(int argc, char** argv) {
- int failedTests = 0;
+ int failedTests = 0;
- if (!env("SWIFT_FILETRANSFERTEST_JID") && !env("SWIFT_FILETRANSFERTEST_PASS") && !env("SWIFT_FILETRANSFERTEST2_JID") && !env("SWIFT_FILETRANSFERTEST2_PASS")) {
+ if (!env("SWIFT_FILETRANSFERTEST_JID") && !env("SWIFT_FILETRANSFERTEST_PASS") && !env("SWIFT_FILETRANSFERTEST2_JID") && !env("SWIFT_FILETRANSFERTEST2_PASS")) {
- return -1;
- }
+ return -1;
+ }
- return failedTests;
+ return failedTests;
}
diff --git a/Swiften/QA/DNSSDTest/DNSSDTest.cpp b/Swiften/QA/DNSSDTest/DNSSDTest.cpp
index bd06445..3b7191d 100644
--- a/Swiften/QA/DNSSDTest/DNSSDTest.cpp
+++ b/Swiften/QA/DNSSDTest/DNSSDTest.cpp
@@ -28,120 +28,120 @@ using namespace Swift;
template <typename DNSSDQuerierType>
class DNSSDTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DNSSDTest);
- CPPUNIT_TEST(testPublish);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop = new DummyEventLoop();
- querier = boost::shared_ptr<DNSSDQuerier>(new DNSSDQuerierType());
- querier->start();
- }
-
- void tearDown() {
- querier->stop();
- querier.reset();
- delete eventLoop;
- }
-
- void testPublish() {
- boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery();
- browseQuery->onServiceAdded.connect(boost::bind(&DNSSDTest::handleServiceAdded, this, _1));
- browseQuery->onServiceRemoved.connect(boost::bind(&DNSSDTest::handleServiceRemoved, this, _1));
- browseQuery->onError.connect(boost::bind(&DNSSDTest::handleBrowseError, this));
- browseQuery->startBrowsing();
- eventLoop->processEvents();
-
- // Publish the service
- LinkLocalServiceInfo info;
- boost::shared_ptr<DNSSDRegisterQuery> registerQuery = querier->createRegisterQuery("DNSSDTest", 1234, info.toTXTRecord());
- registerQuery->onRegisterFinished.connect(boost::bind(&DNSSDTest::handleRegisterFinished, this, _1));
- registerQuery->registerService();
-
- // Wait for a while
- wait();
-
- // Check that our registered queries are correct
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>((registered.size())));
- CPPUNIT_ASSERT_EQUAL(std::string("DNSSDTest"), registered[0].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("local"), registered[0].getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string("_presence._tcp"), registered[0].getType());
-
- // Check that our browse query discovered us
- std::sort(added.begin(), added.end());
- CPPUNIT_ASSERT(added.size() >= 1);
- //for (size_t i = 0; i < added.size(); ++i) {
- for (size_t i = 0; i < added.size(); ++i) {
- CPPUNIT_ASSERT_EQUAL(std::string("DNSSDTest"), added[i].getName());
- CPPUNIT_ASSERT_EQUAL(std::string("local"), added[i].getDomain());
- CPPUNIT_ASSERT_EQUAL(std::string("_presence._tcp"), added[i].getType());
- CPPUNIT_ASSERT(added[i].getNetworkInterfaceID() != 0);
- }
-
- // Resolve all added services
- for (size_t i = 0; i < added.size(); ++i) {
- resolvedServices.clear();
- boost::shared_ptr<DNSSDResolveServiceQuery> resolveServiceQuery = querier->createResolveServiceQuery(added[i]);
- resolveServiceQuery->onServiceResolved.connect(boost::bind(&DNSSDTest::handleResolveFinished, this, _1));
- resolveServiceQuery->start();
- wait();
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(resolvedServices.size()));
- resolveServiceQuery->stop();
- }
-
- // Unregister the service & check if the browse query picks this up
- toRemove.clear();
- toRemove.insert(toRemove.begin(), added.begin(), added.end());
- registerQuery->unregisterService();
- while (!toRemove.empty()) {
- Swift::sleep(100);
- eventLoop->processEvents();
- }
-
- browseQuery->stopBrowsing();
- eventLoop->processEvents();
- }
-
- private:
- void handleServiceAdded(const DNSSDServiceID& id) {
- std::cout << "Service added: " << id.getNetworkInterfaceID() << std::endl;
- added.push_back(id);
- }
-
- void handleServiceRemoved(const DNSSDServiceID& id) {
- CPPUNIT_ASSERT(std::find(toRemove.begin(), toRemove.end(), id) != toRemove.end());
- erase(toRemove, id);
- }
-
- void handleRegisterFinished(boost::optional<DNSSDServiceID> id) {
- if (id) {
- registered.push_back(*id);
- }
- }
-
- void handleBrowseError() {
- }
-
- void wait() {
- for (int i = 0; i < SLEEP_INTERVALS; ++i) {
- Swift::sleep(100);
- eventLoop->processEvents();
- }
- }
-
- void handleResolveFinished(const boost::optional<DNSSDResolveServiceQuery::Result>& result) {
- CPPUNIT_ASSERT(result);
- resolvedServices.push_back(*result);
- }
-
- private:
- DummyEventLoop* eventLoop;
- boost::shared_ptr<DNSSDQuerier> querier;
- std::vector<DNSSDServiceID> added;
- std::vector<DNSSDServiceID> registered;
- std::vector<DNSSDServiceID> toRemove;
- std::vector<DNSSDResolveServiceQuery::Result> resolvedServices;
+ CPPUNIT_TEST_SUITE(DNSSDTest);
+ CPPUNIT_TEST(testPublish);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ querier = boost::shared_ptr<DNSSDQuerier>(new DNSSDQuerierType());
+ querier->start();
+ }
+
+ void tearDown() {
+ querier->stop();
+ querier.reset();
+ delete eventLoop;
+ }
+
+ void testPublish() {
+ boost::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery();
+ browseQuery->onServiceAdded.connect(boost::bind(&DNSSDTest::handleServiceAdded, this, _1));
+ browseQuery->onServiceRemoved.connect(boost::bind(&DNSSDTest::handleServiceRemoved, this, _1));
+ browseQuery->onError.connect(boost::bind(&DNSSDTest::handleBrowseError, this));
+ browseQuery->startBrowsing();
+ eventLoop->processEvents();
+
+ // Publish the service
+ LinkLocalServiceInfo info;
+ boost::shared_ptr<DNSSDRegisterQuery> registerQuery = querier->createRegisterQuery("DNSSDTest", 1234, info.toTXTRecord());
+ registerQuery->onRegisterFinished.connect(boost::bind(&DNSSDTest::handleRegisterFinished, this, _1));
+ registerQuery->registerService();
+
+ // Wait for a while
+ wait();
+
+ // Check that our registered queries are correct
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>((registered.size())));
+ CPPUNIT_ASSERT_EQUAL(std::string("DNSSDTest"), registered[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("local"), registered[0].getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("_presence._tcp"), registered[0].getType());
+
+ // Check that our browse query discovered us
+ std::sort(added.begin(), added.end());
+ CPPUNIT_ASSERT(added.size() >= 1);
+ //for (size_t i = 0; i < added.size(); ++i) {
+ for (size_t i = 0; i < added.size(); ++i) {
+ CPPUNIT_ASSERT_EQUAL(std::string("DNSSDTest"), added[i].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("local"), added[i].getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("_presence._tcp"), added[i].getType());
+ CPPUNIT_ASSERT(added[i].getNetworkInterfaceID() != 0);
+ }
+
+ // Resolve all added services
+ for (size_t i = 0; i < added.size(); ++i) {
+ resolvedServices.clear();
+ boost::shared_ptr<DNSSDResolveServiceQuery> resolveServiceQuery = querier->createResolveServiceQuery(added[i]);
+ resolveServiceQuery->onServiceResolved.connect(boost::bind(&DNSSDTest::handleResolveFinished, this, _1));
+ resolveServiceQuery->start();
+ wait();
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(resolvedServices.size()));
+ resolveServiceQuery->stop();
+ }
+
+ // Unregister the service & check if the browse query picks this up
+ toRemove.clear();
+ toRemove.insert(toRemove.begin(), added.begin(), added.end());
+ registerQuery->unregisterService();
+ while (!toRemove.empty()) {
+ Swift::sleep(100);
+ eventLoop->processEvents();
+ }
+
+ browseQuery->stopBrowsing();
+ eventLoop->processEvents();
+ }
+
+ private:
+ void handleServiceAdded(const DNSSDServiceID& id) {
+ std::cout << "Service added: " << id.getNetworkInterfaceID() << std::endl;
+ added.push_back(id);
+ }
+
+ void handleServiceRemoved(const DNSSDServiceID& id) {
+ CPPUNIT_ASSERT(std::find(toRemove.begin(), toRemove.end(), id) != toRemove.end());
+ erase(toRemove, id);
+ }
+
+ void handleRegisterFinished(boost::optional<DNSSDServiceID> id) {
+ if (id) {
+ registered.push_back(*id);
+ }
+ }
+
+ void handleBrowseError() {
+ }
+
+ void wait() {
+ for (int i = 0; i < SLEEP_INTERVALS; ++i) {
+ Swift::sleep(100);
+ eventLoop->processEvents();
+ }
+ }
+
+ void handleResolveFinished(const boost::optional<DNSSDResolveServiceQuery::Result>& result) {
+ CPPUNIT_ASSERT(result);
+ resolvedServices.push_back(*result);
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ boost::shared_ptr<DNSSDQuerier> querier;
+ std::vector<DNSSDServiceID> added;
+ std::vector<DNSSDServiceID> registered;
+ std::vector<DNSSDServiceID> toRemove;
+ std::vector<DNSSDResolveServiceQuery::Result> resolvedServices;
};
#ifdef HAVE_AVAHI
diff --git a/Swiften/QA/FileTransferTest/FileTransferTest.cpp b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
index 7a50e9f..8017927 100644
--- a/Swiften/QA/FileTransferTest/FileTransferTest.cpp
+++ b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
@@ -41,360 +41,360 @@ static boost::shared_ptr<BoostNetworkFactories> networkFactories;
BoostRandomGenerator randGen;
enum Candidate {
- InBandBytestream = 1,
- S5B_Direct = 2,
- S5B_Proxied = 4,
- S5B_Assisted = 8,
+ InBandBytestream = 1,
+ S5B_Direct = 2,
+ S5B_Proxied = 4,
+ S5B_Assisted = 8,
};
class FileTransferTest {
- public:
- FileTransferTest(int senderCandidates, int receiverCandidates) : senderCandidates_(senderCandidates), senderError_(FileTransferError::UnknownError), senderIsDone_(false), receiverCandidates_(receiverCandidates), receiverError_(FileTransferError::UnknownError), receiverIsDone_(false) {
- sender_ = boost::make_shared<Client>(JID(getenv("SWIFT_FILETRANSFERTEST_JID")), getenv("SWIFT_FILETRANSFERTEST_PASS"), networkFactories.get());
- sender_->onDisconnected.connect(boost::bind(&FileTransferTest::handleSenderDisconnected, this, _1));
- sender_->onConnected.connect(boost::bind(&FileTransferTest::handleSenderConnected, this));
- sender_->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileTransferTest::handleSenderCapsChanged, this, _1));
-
- receiver_ = boost::make_shared<Client>(JID(getenv("SWIFT_FILETRANSFERTEST2_JID")), getenv("SWIFT_FILETRANSFERTEST2_PASS"), networkFactories.get());
- receiver_->onConnected.connect(boost::bind(&FileTransferTest::handleReceiverConnected, this));
- receiver_->onDisconnected.connect(boost::bind(&FileTransferTest::handleReceiverDisconnected, this, _1));
-
- senderTracer_ = new ClientXMLTracer(sender_.get());
- receiverTracer_ = new ClientXMLTracer(receiver_.get());
-
- ClientOptions options;
- options.useTLS = ClientOptions::NeverUseTLS;
- options.useStreamCompression = false;
- options.useStreamResumption = false;
- options.useAcks = false;
-
- sender_->connect(options);
- receiver_->connect(options);
-
- timeOut_ = networkFactories->getTimerFactory()->createTimer(60000);
- timeOut_->onTick.connect(boost::bind(&FileTransferTest::handleTimeOut, this));
-
- // Create randomly sized data to exchange.
- sendFilePath_ = boost::filesystem::unique_path("ft_send_%%%%%%%%%%%%%%%%.bin");
- receiveFilePath_ = boost::filesystem::unique_path("ft_receive_%%%%%%%%%%%%%%%%.bin");
-
- size_t size = 1024 + boost::numeric_cast<size_t>(randGen.generateRandomInteger(1024 * 10));
- sendData_.resize(size);
- for (size_t n = 0; n < sendData_.size(); n++) {
- sendData_[n] = boost::numeric_cast<unsigned char>(randGen.generateRandomInteger(255));
- }
-
- std::ofstream outfile(sendFilePath_.native().c_str(), std::ios::out | std::ios::binary);
- outfile.write(reinterpret_cast<char *>(&sendData_[0]), boost::numeric_cast<ptrdiff_t>(sendData_.size()));
- outfile.close();
- }
-
- ~FileTransferTest() {
- timeOut_->stop();
-
- delete senderTracer_;
- delete receiverTracer_;
-
- // Free file-transfer objects so file handles are closed and files can be removed afterwards.
- assert(!outgoingFileTransfer_ && incomingFileTransfers_.empty());
-
- if(boost::filesystem::exists(sendFilePath_)) {
- boost::filesystem::remove(sendFilePath_);
- }
-
- if(boost::filesystem::exists(receiveFilePath_)) {
- boost::filesystem::remove(receiveFilePath_);
- }
- }
-
- void handleSenderConnected() {
- DiscoInfo discoInfo;
- discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
- discoInfo.addFeature(DiscoInfo::JingleFeature);
- discoInfo.addFeature(DiscoInfo::JingleFTFeature);
- discoInfo.addFeature(DiscoInfo::Bytestream);
- if (senderCandidates_ & InBandBytestream) {
- discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
- }
- if (senderCandidates_ & (S5B_Direct | S5B_Assisted | S5B_Proxied)) {
- discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
- }
- sender_->getDiscoManager()->setCapsNode(CLIENT_NODE);
- sender_->getDiscoManager()->setDiscoInfo(discoInfo);
- sender_->sendPresence(Presence::create());
- }
-
- void handleReceiverConnected() {
- receiver_->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileTransferTest::handleReceiverIncomingFileTransfer, this, _1));
-
- DiscoInfo discoInfo;
- discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
- discoInfo.addFeature(DiscoInfo::JingleFeature);
- discoInfo.addFeature(DiscoInfo::JingleFTFeature);
- discoInfo.addFeature(DiscoInfo::Bytestream);
- if (receiverCandidates_ & InBandBytestream) {
- discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
- }
- if (receiverCandidates_ & (S5B_Direct | S5B_Assisted | S5B_Proxied)) {
- discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
- }
- receiver_->getDiscoManager()->setCapsNode(CLIENT_NODE);
- receiver_->getDiscoManager()->setDiscoInfo(discoInfo);
- receiver_->getPresenceSender()->sendPresence(Presence::create());
- }
-
- void handleReceiverIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
- incomingFileTransfers_.push_back(transfer);
- boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>(receiveFilePath_.native());
- transfer->onFinished.connect(boost::bind(&FileTransferTest::handleReceiverFileTransferFinished, this, _1, out));
-
- FileTransferOptions options;
- options = options.withInBandAllowed(receiverCandidates_ & InBandBytestream);
- options = options.withDirectAllowed(receiverCandidates_ & S5B_Direct);
- options = options.withAssistedAllowed(receiverCandidates_ & S5B_Assisted);
- options = options.withProxiedAllowed(receiverCandidates_ & S5B_Proxied);
-
- std::cout << "Incoming transfer options: " << "IBB (" << options.isInBandAllowed() << ")" << ", ";
- std::cout << "S5B Direct (" << options.isDirectAllowed() << ")" << ", ";
- std::cout << "S5B Assisted (" << options.isAssistedAllowed() << ")" << ", ";
- std::cout << "S5B Proxied (" << options.isProxiedAllowed() << ")" << std::endl;
-
- transfer->accept(out, options);
- }
-
- void handleSenderCapsChanged(const JID &jid) {
- if (receiver_ && (receiver_->getJID().toBare() == jid.toBare())) {
- boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(sendFilePath_);
-
- FileTransferOptions options;
- options = options.withInBandAllowed(senderCandidates_ & InBandBytestream);
- options = options.withDirectAllowed(senderCandidates_ & S5B_Direct);
- options = options.withAssistedAllowed(senderCandidates_ & S5B_Assisted);
- options = options.withProxiedAllowed(senderCandidates_ & S5B_Proxied);
-
- std::cout << "Outgoing transfer options: " << "IBB (" << options.isInBandAllowed() << ")" << ", ";
- std::cout << "S5B Direct (" << options.isDirectAllowed() << ")" << ", ";
- std::cout << "S5B Assisted (" << options.isAssistedAllowed() << ")" << ", ";
- std::cout << "S5B Proxied (" << options.isProxiedAllowed() << ")" << std::endl;
-
- outgoingFileTransfer_ = sender_->getFileTransferManager()->createOutgoingFileTransfer(jid.toBare(), sendFilePath_, "Some File!", fileStream, options);
-
- if (outgoingFileTransfer_) {
- outgoingFileTransfer_->onFinished.connect(boost::bind(&FileTransferTest::handleSenderFileTransferFinished, this, _1));
- outgoingFileTransfer_->start();
- } else {
- std::cout << "ERROR: No outgoing file transfer returned." << std::endl;
- receiverIsDone_ = true;
- senderIsDone_ = true;
- endTest();
- }
- }
- }
-
- void handleReceiverFileTransferFinished(const boost::optional<FileTransferError>& error, boost::shared_ptr<FileWriteBytestream> out) {
- out->close();
- receiverError_ = error;
- receiverIsDone_ = true;
- if (senderIsDone_) {
- timeOut_->stop();
- timeOut_ = networkFactories->getTimerFactory()->createTimer(1000);
- timeOut_->onTick.connect(boost::bind(&FileTransferTest::endTest, this));
- timeOut_->start();
- }
- }
-
- void handleSenderDisconnected(const boost::optional<ClientError>& error) {
- if (error) {
- std::cout << this << " " << "handleSenderDisconnected: error: " << error.get() << std::endl;
- }
-
- // All file-transfers related to a Client instance need to be freed
- // *before* freeing the Client instance.
- outgoingFileTransfer_.reset();
-
- sender_.reset();
- if (!sender_ && !receiver_) {
- eventLoop->stop();
- }
- }
-
- void handleReceiverDisconnected(const boost::optional<ClientError>& error) {
- if (error) {
- std::cout << this << " " << "handleReceiverDisconnected: error: " << error.get() << std::endl;
- }
-
- // All file-transfers related to a Client instance need to be freed
- // *before* freeing the Client instance.
- incomingFileTransfers_.clear();
-
- receiver_.reset();
- if (!sender_ && !receiver_) {
- eventLoop->stop();
- }
- }
-
- void handleSenderFileTransferFinished(const boost::optional<FileTransferError>& error) {
- senderError_ = error;
- senderIsDone_ = true;
- if (receiverIsDone_) {
- timeOut_->stop();
- timeOut_ = networkFactories->getTimerFactory()->createTimer(1000);
- timeOut_->onTick.connect(boost::bind(&FileTransferTest::endTest, this));
- timeOut_->start();
- }
- else if (error) {
- endTest();
- }
- }
-
- void run() {
- timeOut_->start();
- eventLoop->run();
- }
-
- void endTest() {
- if (sender_) {
- sender_->disconnect();
- }
- if (receiver_) {
- receiver_->disconnect();
- }
- }
-
- void handleTimeOut() {
- std::cout << "Test timed out!!!" << std::endl;
- endTest();
- }
-
- bool isDone() const {
- return senderIsDone_ && receiverIsDone_;
- }
-
- bool wasSuccessful() const {
- return !senderError_ && !receiverError_;
- }
-
- private:
- int senderCandidates_;
- boost::shared_ptr<Client> sender_;
- ClientXMLTracer* senderTracer_;
- ByteArray sendData_;
- OutgoingFileTransfer::ref outgoingFileTransfer_;
- boost::filesystem::path sendFilePath_;
- boost::optional<FileTransferError> senderError_;
- bool senderIsDone_;
-
- int receiverCandidates_;
- boost::shared_ptr<Client> receiver_;
- ClientXMLTracer* receiverTracer_;
- ByteArray receiveData_;
- std::vector<IncomingFileTransfer::ref> incomingFileTransfers_;
- boost::filesystem::path receiveFilePath_;
- boost::optional<FileTransferError> receiverError_;
- bool receiverIsDone_;
-
- Timer::ref timeOut_;
+ public:
+ FileTransferTest(int senderCandidates, int receiverCandidates) : senderCandidates_(senderCandidates), senderError_(FileTransferError::UnknownError), senderIsDone_(false), receiverCandidates_(receiverCandidates), receiverError_(FileTransferError::UnknownError), receiverIsDone_(false) {
+ sender_ = boost::make_shared<Client>(JID(getenv("SWIFT_FILETRANSFERTEST_JID")), getenv("SWIFT_FILETRANSFERTEST_PASS"), networkFactories.get());
+ sender_->onDisconnected.connect(boost::bind(&FileTransferTest::handleSenderDisconnected, this, _1));
+ sender_->onConnected.connect(boost::bind(&FileTransferTest::handleSenderConnected, this));
+ sender_->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileTransferTest::handleSenderCapsChanged, this, _1));
+
+ receiver_ = boost::make_shared<Client>(JID(getenv("SWIFT_FILETRANSFERTEST2_JID")), getenv("SWIFT_FILETRANSFERTEST2_PASS"), networkFactories.get());
+ receiver_->onConnected.connect(boost::bind(&FileTransferTest::handleReceiverConnected, this));
+ receiver_->onDisconnected.connect(boost::bind(&FileTransferTest::handleReceiverDisconnected, this, _1));
+
+ senderTracer_ = new ClientXMLTracer(sender_.get());
+ receiverTracer_ = new ClientXMLTracer(receiver_.get());
+
+ ClientOptions options;
+ options.useTLS = ClientOptions::NeverUseTLS;
+ options.useStreamCompression = false;
+ options.useStreamResumption = false;
+ options.useAcks = false;
+
+ sender_->connect(options);
+ receiver_->connect(options);
+
+ timeOut_ = networkFactories->getTimerFactory()->createTimer(60000);
+ timeOut_->onTick.connect(boost::bind(&FileTransferTest::handleTimeOut, this));
+
+ // Create randomly sized data to exchange.
+ sendFilePath_ = boost::filesystem::unique_path("ft_send_%%%%%%%%%%%%%%%%.bin");
+ receiveFilePath_ = boost::filesystem::unique_path("ft_receive_%%%%%%%%%%%%%%%%.bin");
+
+ size_t size = 1024 + boost::numeric_cast<size_t>(randGen.generateRandomInteger(1024 * 10));
+ sendData_.resize(size);
+ for (size_t n = 0; n < sendData_.size(); n++) {
+ sendData_[n] = boost::numeric_cast<unsigned char>(randGen.generateRandomInteger(255));
+ }
+
+ std::ofstream outfile(sendFilePath_.native().c_str(), std::ios::out | std::ios::binary);
+ outfile.write(reinterpret_cast<char *>(&sendData_[0]), boost::numeric_cast<ptrdiff_t>(sendData_.size()));
+ outfile.close();
+ }
+
+ ~FileTransferTest() {
+ timeOut_->stop();
+
+ delete senderTracer_;
+ delete receiverTracer_;
+
+ // Free file-transfer objects so file handles are closed and files can be removed afterwards.
+ assert(!outgoingFileTransfer_ && incomingFileTransfers_.empty());
+
+ if(boost::filesystem::exists(sendFilePath_)) {
+ boost::filesystem::remove(sendFilePath_);
+ }
+
+ if(boost::filesystem::exists(receiveFilePath_)) {
+ boost::filesystem::remove(receiveFilePath_);
+ }
+ }
+
+ void handleSenderConnected() {
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
+ discoInfo.addFeature(DiscoInfo::JingleFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo.addFeature(DiscoInfo::Bytestream);
+ if (senderCandidates_ & InBandBytestream) {
+ discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ }
+ if (senderCandidates_ & (S5B_Direct | S5B_Assisted | S5B_Proxied)) {
+ discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ }
+ sender_->getDiscoManager()->setCapsNode(CLIENT_NODE);
+ sender_->getDiscoManager()->setDiscoInfo(discoInfo);
+ sender_->sendPresence(Presence::create());
+ }
+
+ void handleReceiverConnected() {
+ receiver_->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileTransferTest::handleReceiverIncomingFileTransfer, this, _1));
+
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
+ discoInfo.addFeature(DiscoInfo::JingleFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo.addFeature(DiscoInfo::Bytestream);
+ if (receiverCandidates_ & InBandBytestream) {
+ discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ }
+ if (receiverCandidates_ & (S5B_Direct | S5B_Assisted | S5B_Proxied)) {
+ discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ }
+ receiver_->getDiscoManager()->setCapsNode(CLIENT_NODE);
+ receiver_->getDiscoManager()->setDiscoInfo(discoInfo);
+ receiver_->getPresenceSender()->sendPresence(Presence::create());
+ }
+
+ void handleReceiverIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
+ incomingFileTransfers_.push_back(transfer);
+ boost::shared_ptr<FileWriteBytestream> out = boost::make_shared<FileWriteBytestream>(receiveFilePath_.native());
+ transfer->onFinished.connect(boost::bind(&FileTransferTest::handleReceiverFileTransferFinished, this, _1, out));
+
+ FileTransferOptions options;
+ options = options.withInBandAllowed(receiverCandidates_ & InBandBytestream);
+ options = options.withDirectAllowed(receiverCandidates_ & S5B_Direct);
+ options = options.withAssistedAllowed(receiverCandidates_ & S5B_Assisted);
+ options = options.withProxiedAllowed(receiverCandidates_ & S5B_Proxied);
+
+ std::cout << "Incoming transfer options: " << "IBB (" << options.isInBandAllowed() << ")" << ", ";
+ std::cout << "S5B Direct (" << options.isDirectAllowed() << ")" << ", ";
+ std::cout << "S5B Assisted (" << options.isAssistedAllowed() << ")" << ", ";
+ std::cout << "S5B Proxied (" << options.isProxiedAllowed() << ")" << std::endl;
+
+ transfer->accept(out, options);
+ }
+
+ void handleSenderCapsChanged(const JID &jid) {
+ if (receiver_ && (receiver_->getJID().toBare() == jid.toBare())) {
+ boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(sendFilePath_);
+
+ FileTransferOptions options;
+ options = options.withInBandAllowed(senderCandidates_ & InBandBytestream);
+ options = options.withDirectAllowed(senderCandidates_ & S5B_Direct);
+ options = options.withAssistedAllowed(senderCandidates_ & S5B_Assisted);
+ options = options.withProxiedAllowed(senderCandidates_ & S5B_Proxied);
+
+ std::cout << "Outgoing transfer options: " << "IBB (" << options.isInBandAllowed() << ")" << ", ";
+ std::cout << "S5B Direct (" << options.isDirectAllowed() << ")" << ", ";
+ std::cout << "S5B Assisted (" << options.isAssistedAllowed() << ")" << ", ";
+ std::cout << "S5B Proxied (" << options.isProxiedAllowed() << ")" << std::endl;
+
+ outgoingFileTransfer_ = sender_->getFileTransferManager()->createOutgoingFileTransfer(jid.toBare(), sendFilePath_, "Some File!", fileStream, options);
+
+ if (outgoingFileTransfer_) {
+ outgoingFileTransfer_->onFinished.connect(boost::bind(&FileTransferTest::handleSenderFileTransferFinished, this, _1));
+ outgoingFileTransfer_->start();
+ } else {
+ std::cout << "ERROR: No outgoing file transfer returned." << std::endl;
+ receiverIsDone_ = true;
+ senderIsDone_ = true;
+ endTest();
+ }
+ }
+ }
+
+ void handleReceiverFileTransferFinished(const boost::optional<FileTransferError>& error, boost::shared_ptr<FileWriteBytestream> out) {
+ out->close();
+ receiverError_ = error;
+ receiverIsDone_ = true;
+ if (senderIsDone_) {
+ timeOut_->stop();
+ timeOut_ = networkFactories->getTimerFactory()->createTimer(1000);
+ timeOut_->onTick.connect(boost::bind(&FileTransferTest::endTest, this));
+ timeOut_->start();
+ }
+ }
+
+ void handleSenderDisconnected(const boost::optional<ClientError>& error) {
+ if (error) {
+ std::cout << this << " " << "handleSenderDisconnected: error: " << error.get() << std::endl;
+ }
+
+ // All file-transfers related to a Client instance need to be freed
+ // *before* freeing the Client instance.
+ outgoingFileTransfer_.reset();
+
+ sender_.reset();
+ if (!sender_ && !receiver_) {
+ eventLoop->stop();
+ }
+ }
+
+ void handleReceiverDisconnected(const boost::optional<ClientError>& error) {
+ if (error) {
+ std::cout << this << " " << "handleReceiverDisconnected: error: " << error.get() << std::endl;
+ }
+
+ // All file-transfers related to a Client instance need to be freed
+ // *before* freeing the Client instance.
+ incomingFileTransfers_.clear();
+
+ receiver_.reset();
+ if (!sender_ && !receiver_) {
+ eventLoop->stop();
+ }
+ }
+
+ void handleSenderFileTransferFinished(const boost::optional<FileTransferError>& error) {
+ senderError_ = error;
+ senderIsDone_ = true;
+ if (receiverIsDone_) {
+ timeOut_->stop();
+ timeOut_ = networkFactories->getTimerFactory()->createTimer(1000);
+ timeOut_->onTick.connect(boost::bind(&FileTransferTest::endTest, this));
+ timeOut_->start();
+ }
+ else if (error) {
+ endTest();
+ }
+ }
+
+ void run() {
+ timeOut_->start();
+ eventLoop->run();
+ }
+
+ void endTest() {
+ if (sender_) {
+ sender_->disconnect();
+ }
+ if (receiver_) {
+ receiver_->disconnect();
+ }
+ }
+
+ void handleTimeOut() {
+ std::cout << "Test timed out!!!" << std::endl;
+ endTest();
+ }
+
+ bool isDone() const {
+ return senderIsDone_ && receiverIsDone_;
+ }
+
+ bool wasSuccessful() const {
+ return !senderError_ && !receiverError_;
+ }
+
+ private:
+ int senderCandidates_;
+ boost::shared_ptr<Client> sender_;
+ ClientXMLTracer* senderTracer_;
+ ByteArray sendData_;
+ OutgoingFileTransfer::ref outgoingFileTransfer_;
+ boost::filesystem::path sendFilePath_;
+ boost::optional<FileTransferError> senderError_;
+ bool senderIsDone_;
+
+ int receiverCandidates_;
+ boost::shared_ptr<Client> receiver_;
+ ClientXMLTracer* receiverTracer_;
+ ByteArray receiveData_;
+ std::vector<IncomingFileTransfer::ref> incomingFileTransfers_;
+ boost::filesystem::path receiveFilePath_;
+ boost::optional<FileTransferError> receiverError_;
+ bool receiverIsDone_;
+
+ Timer::ref timeOut_;
};
static bool runTest(int senderCandidates, int receiverCandidates) {
- bool success = false;
+ bool success = false;
- std::cout << "senderCandidates: " << senderCandidates << ", receiverCandidates: " << receiverCandidates << std::endl;
- bool expectSuccess = (senderCandidates & receiverCandidates) > 0;
+ std::cout << "senderCandidates: " << senderCandidates << ", receiverCandidates: " << receiverCandidates << std::endl;
+ bool expectSuccess = (senderCandidates & receiverCandidates) > 0;
- eventLoop = boost::make_shared<SimpleEventLoop>();
- networkFactories = boost::make_shared<BoostNetworkFactories>(eventLoop.get());
+ eventLoop = boost::make_shared<SimpleEventLoop>();
+ networkFactories = boost::make_shared<BoostNetworkFactories>(eventLoop.get());
- boost::shared_ptr<FileTransferTest> testRun = boost::make_shared<FileTransferTest>(senderCandidates, receiverCandidates);
+ boost::shared_ptr<FileTransferTest> testRun = boost::make_shared<FileTransferTest>(senderCandidates, receiverCandidates);
- testRun->run();
+ testRun->run();
- bool wasSuccessful = testRun->wasSuccessful();
- if (expectSuccess == wasSuccessful) {
- success = true;
- }
- else {
- if (!testRun->isDone()) {
- std::cout << "Test did not finish transfer. Sender candidates = " << senderCandidates << ", receiver candidates = " << receiverCandidates << "." << std::endl;
- }
- }
- std::cout << "expected success: " << expectSuccess << ", wasSuccessful: " << wasSuccessful << std::endl;
+ bool wasSuccessful = testRun->wasSuccessful();
+ if (expectSuccess == wasSuccessful) {
+ success = true;
+ }
+ else {
+ if (!testRun->isDone()) {
+ std::cout << "Test did not finish transfer. Sender candidates = " << senderCandidates << ", receiver candidates = " << receiverCandidates << "." << std::endl;
+ }
+ }
+ std::cout << "expected success: " << expectSuccess << ", wasSuccessful: " << wasSuccessful << std::endl;
- testRun.reset();
- networkFactories.reset();
- eventLoop->runUntilEvents();
+ testRun.reset();
+ networkFactories.reset();
+ eventLoop->runUntilEvents();
- eventLoop->stop();
- eventLoop.reset();
+ eventLoop->stop();
+ eventLoop.reset();
- return success;
+ 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.
+ * 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) {
- 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) {
- 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) {
- 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;
+ 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) {
+ 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) {
+ 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) {
+ 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/NetworkTest/BoostConnectionServerTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
index 67b4bfa..a415a0f 100644
--- a/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
@@ -19,198 +19,198 @@
using namespace Swift;
class BoostConnectionServerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BoostConnectionServerTest);
- CPPUNIT_TEST(testConstructor_TwoServersOnSamePort);
- CPPUNIT_TEST(testStart_Conflict);
- CPPUNIT_TEST(testStop);
- CPPUNIT_TEST(testIPv4Server);
- CPPUNIT_TEST(testIPv6Server);
- CPPUNIT_TEST(testIPv4IPv6DualStackServer);
- CPPUNIT_TEST(testIPv6DualStackServerPeerAddress);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop_ = new DummyEventLoop();
- boostIOServiceThread_ = new BoostIOServiceThread();
- stopped_ = false;
- stoppedError_.reset();
- receivedNewConnection_ = false;
- connectFinished_ = false;
- remoteAddress_ = boost::optional<HostAddressPort>();
- }
-
- void tearDown() {
- delete boostIOServiceThread_;
- while (eventLoop_->hasEvents()) {
- eventLoop_->processEvents();
- }
- delete eventLoop_;
- }
-
- void testConstructor_TwoServersOnSamePort() {
- BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- }
-
- void testStart_Conflict() {
- BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- testling->start();
-
- BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- testling2->onStopped.connect(
- boost::bind(&BoostConnectionServerTest::handleStopped_, this, _1));
-
- testling->stop();
- }
-
- void testStop() {
- BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- testling->start();
-
- testling->stop();
-
- BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
- testling2->start();
-
- testling2->stop();
- }
-
- void testIPv4Server() {
- BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("127.0.0.1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
- testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
- testling->start();
-
- BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
-
- testling->stop();
- }
-
- void testIPv6Server() {
- BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
- testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
- testling->start();
-
- BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
-
- testling->stop();
- }
-
- void testIPv4IPv6DualStackServer() {
- BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
- testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
- testling->start();
-
- // Test IPv4.
- BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
-
- receivedNewConnection_ = false;
- connectFinished_ = false;
-
- // Test IPv6.
- clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
-
- testling->stop();
- }
-
- void testIPv6DualStackServerPeerAddress() {
- BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
- testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
- testling->start();
-
- // Test IPv4.
- BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
- // The IPv4 localhost mapped to a IPv6 address is expected here.
- CPPUNIT_ASSERT(HostAddress("::ffff:127.0.0.1") == remoteAddress_.get().getAddress());
-
- receivedNewConnection_ = false;
- connectFinished_ = false;
- remoteAddress_ = boost::optional<HostAddressPort>();
-
- // Test IPv6.
- clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
- clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
- clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
-
- while (!connectFinished_) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
- // The IPv6 local host is expected here.
- CPPUNIT_ASSERT(HostAddress("::1") == remoteAddress_.get().getAddress());
-
- testling->stop();
- }
-
- void handleStopped_(boost::optional<BoostConnectionServer::Error> e) {
- stopped_ = true;
- stoppedError_ = e;
- }
-
- void handleNewConnection(boost::shared_ptr<Connection> connection) {
- receivedNewConnection_ = true;
- remoteAddress_ = connection->getRemoteAddress();
- }
-
- void handleConnectFinished(bool /*error*/) {
- connectFinished_ = true;
- }
-
- private:
- BoostIOServiceThread* boostIOServiceThread_;
- DummyEventLoop* eventLoop_;
- bool stopped_;
- bool receivedNewConnection_;
- bool connectFinished_;
- boost::optional<BoostConnectionServer::Error> stoppedError_;
- boost::optional<HostAddressPort> remoteAddress_;
+ CPPUNIT_TEST_SUITE(BoostConnectionServerTest);
+ CPPUNIT_TEST(testConstructor_TwoServersOnSamePort);
+ CPPUNIT_TEST(testStart_Conflict);
+ CPPUNIT_TEST(testStop);
+ CPPUNIT_TEST(testIPv4Server);
+ CPPUNIT_TEST(testIPv6Server);
+ CPPUNIT_TEST(testIPv4IPv6DualStackServer);
+ CPPUNIT_TEST(testIPv6DualStackServerPeerAddress);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop_ = new DummyEventLoop();
+ boostIOServiceThread_ = new BoostIOServiceThread();
+ stopped_ = false;
+ stoppedError_.reset();
+ receivedNewConnection_ = false;
+ connectFinished_ = false;
+ remoteAddress_ = boost::optional<HostAddressPort>();
+ }
+
+ void tearDown() {
+ delete boostIOServiceThread_;
+ while (eventLoop_->hasEvents()) {
+ eventLoop_->processEvents();
+ }
+ delete eventLoop_;
+ }
+
+ void testConstructor_TwoServersOnSamePort() {
+ BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ }
+
+ void testStart_Conflict() {
+ BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->start();
+
+ BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ testling2->onStopped.connect(
+ boost::bind(&BoostConnectionServerTest::handleStopped_, this, _1));
+
+ testling->stop();
+ }
+
+ void testStop() {
+ BoostConnectionServer::ref testling(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->start();
+
+ testling->stop();
+
+ BoostConnectionServer::ref testling2(BoostConnectionServer::create(9999, boostIOServiceThread_->getIOService(), eventLoop_));
+ testling2->start();
+
+ testling2->stop();
+ }
+
+ void testIPv4Server() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("127.0.0.1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+ testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
+ testling->start();
+
+ BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv6Server() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+ testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
+ testling->start();
+
+ BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv4IPv6DualStackServer() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+ testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
+ testling->start();
+
+ // Test IPv4.
+ BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ receivedNewConnection_ = false;
+ connectFinished_ = false;
+
+ // Test IPv6.
+ clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv6DualStackServerPeerAddress() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+ testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
+ testling->start();
+
+ // Test IPv4.
+ BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+ // The IPv4 localhost mapped to a IPv6 address is expected here.
+ CPPUNIT_ASSERT(HostAddress("::ffff:127.0.0.1") == remoteAddress_.get().getAddress());
+
+ receivedNewConnection_ = false;
+ connectFinished_ = false;
+ remoteAddress_ = boost::optional<HostAddressPort>();
+
+ // Test IPv6.
+ clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
+ clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
+ clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+ // The IPv6 local host is expected here.
+ CPPUNIT_ASSERT(HostAddress("::1") == remoteAddress_.get().getAddress());
+
+ testling->stop();
+ }
+
+ void handleStopped_(boost::optional<BoostConnectionServer::Error> e) {
+ stopped_ = true;
+ stoppedError_ = e;
+ }
+
+ void handleNewConnection(boost::shared_ptr<Connection> connection) {
+ receivedNewConnection_ = true;
+ remoteAddress_ = connection->getRemoteAddress();
+ }
+
+ void handleConnectFinished(bool /*error*/) {
+ connectFinished_ = true;
+ }
+
+ private:
+ BoostIOServiceThread* boostIOServiceThread_;
+ DummyEventLoop* eventLoop_;
+ bool stopped_;
+ bool receivedNewConnection_;
+ bool connectFinished_;
+ boost::optional<BoostConnectionServer::Error> stoppedError_;
+ boost::optional<HostAddressPort> remoteAddress_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(BoostConnectionServerTest);
diff --git a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
index a122686..f09e1a7 100755
--- a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
@@ -24,146 +24,146 @@
using namespace Swift;
class BoostConnectionTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(BoostConnectionTest);
- CPPUNIT_TEST(testDestructor);
- CPPUNIT_TEST(testDestructor_PendingEvents);
- CPPUNIT_TEST(testWrite);
- CPPUNIT_TEST(testWriteMultipleSimultaniouslyQueuesWrites);
+ CPPUNIT_TEST_SUITE(BoostConnectionTest);
+ CPPUNIT_TEST(testDestructor);
+ CPPUNIT_TEST(testDestructor_PendingEvents);
+ CPPUNIT_TEST(testWrite);
+ CPPUNIT_TEST(testWriteMultipleSimultaniouslyQueuesWrites);
#ifdef TEST_IPV6
- CPPUNIT_TEST(testWrite_IPv6);
+ CPPUNIT_TEST(testWrite_IPv6);
#endif
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop_ = new DummyEventLoop();
- boostIOServiceThread_ = new BoostIOServiceThread();
- boostIOService_ = boost::make_shared<boost::asio::io_service>();
- disconnected_ = false;
- connectFinished_ = false;
- }
-
- void tearDown() {
- delete boostIOServiceThread_;
- while (eventLoop_->hasEvents()) {
- eventLoop_->processEvents();
- }
- delete eventLoop_;
- }
-
- void testDestructor() {
- {
- BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
- testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
- }
- }
-
- void testDestructor_PendingEvents() {
- {
- BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
- testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
- while (!eventLoop_->hasEvents()) {
- Swift::sleep(10);
- }
- }
- eventLoop_->processEvents();
- }
-
- void testWrite() {
- using namespace boost::posix_time;
-
- BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
- testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
- testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
- testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
- testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
-
- boost::posix_time::ptime start = second_clock::local_time();
- while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60))) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
- CPPUNIT_ASSERT_EQUAL(false, receivedData_.empty());
- testling->disconnect();
- }
-
- void testWrite_IPv6() {
- using namespace boost::posix_time;
-
- BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
- testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
- testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
- testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
- testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV6")), 5222));
-
- boost::posix_time::ptime start = second_clock::local_time();
- while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60))) {
- Swift::sleep(10);
- eventLoop_->processEvents();
- }
- CPPUNIT_ASSERT_EQUAL(false, receivedData_.empty());
- testling->disconnect();
- }
-
-
- void testWriteMultipleSimultaniouslyQueuesWrites() {
- BoostConnection::ref testling(BoostConnection::create(boostIOService_, eventLoop_));
- testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::handleConnectFinished, this));
- testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
- testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
- testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
- while (!connectFinished_) {
- boostIOService_->run_one();
- eventLoop_->processEvents();
- }
-
- testling->write(createSafeByteArray("<stream:strea"));
- testling->write(createSafeByteArray("m"));
- testling->write(createSafeByteArray(">"));
-
- // Check that we only did one write event, the others are queued
- /*int runHandlers = */boostIOService_->poll();
- // Disabling this test, because poll runns all handlers that are added during poll() as well, so
- // this test doesn't really work any more. We'll have to trust that things are queued.
- //CPPUNIT_ASSERT_EQUAL(1, runHandlers);
- // Process the other events
- while (receivedData_.empty()) {
- boostIOService_->run_one();
- eventLoop_->processEvents();
- }
-
- // Disconnect & clean up
- testling->disconnect();
- while (!disconnected_) {
- boostIOService_->run_one();
- eventLoop_->processEvents();
- }
- }
-
- void doWrite(BoostConnection* connection) {
- connection->write(createSafeByteArray("<stream:stream>"));
- connection->write(createSafeByteArray("\r\n\r\n")); // Temporarily, while we don't have an xmpp server running on ipv6
- }
-
- void handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- append(receivedData_, *data);
- }
-
- void handleDisconnected() {
- disconnected_ = true;
- }
-
- void handleConnectFinished() {
- connectFinished_ = true;
- }
-
- private:
- BoostIOServiceThread* boostIOServiceThread_;
- boost::shared_ptr<boost::asio::io_service> boostIOService_;
- DummyEventLoop* eventLoop_;
- ByteArray receivedData_;
- bool disconnected_;
- bool connectFinished_;
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop_ = new DummyEventLoop();
+ boostIOServiceThread_ = new BoostIOServiceThread();
+ boostIOService_ = boost::make_shared<boost::asio::io_service>();
+ disconnected_ = false;
+ connectFinished_ = false;
+ }
+
+ void tearDown() {
+ delete boostIOServiceThread_;
+ while (eventLoop_->hasEvents()) {
+ eventLoop_->processEvents();
+ }
+ delete eventLoop_;
+ }
+
+ void testDestructor() {
+ {
+ BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+ }
+ }
+
+ void testDestructor_PendingEvents() {
+ {
+ BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+ while (!eventLoop_->hasEvents()) {
+ Swift::sleep(10);
+ }
+ }
+ eventLoop_->processEvents();
+ }
+
+ void testWrite() {
+ using namespace boost::posix_time;
+
+ BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
+ testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
+ testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
+ testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+
+ boost::posix_time::ptime start = second_clock::local_time();
+ while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60))) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+ CPPUNIT_ASSERT_EQUAL(false, receivedData_.empty());
+ testling->disconnect();
+ }
+
+ void testWrite_IPv6() {
+ using namespace boost::posix_time;
+
+ BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
+ testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
+ testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
+ testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
+ testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV6")), 5222));
+
+ boost::posix_time::ptime start = second_clock::local_time();
+ while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60))) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+ CPPUNIT_ASSERT_EQUAL(false, receivedData_.empty());
+ testling->disconnect();
+ }
+
+
+ void testWriteMultipleSimultaniouslyQueuesWrites() {
+ BoostConnection::ref testling(BoostConnection::create(boostIOService_, eventLoop_));
+ testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::handleConnectFinished, this));
+ testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
+ testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
+ testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+ while (!connectFinished_) {
+ boostIOService_->run_one();
+ eventLoop_->processEvents();
+ }
+
+ testling->write(createSafeByteArray("<stream:strea"));
+ testling->write(createSafeByteArray("m"));
+ testling->write(createSafeByteArray(">"));
+
+ // Check that we only did one write event, the others are queued
+ /*int runHandlers = */boostIOService_->poll();
+ // Disabling this test, because poll runns all handlers that are added during poll() as well, so
+ // this test doesn't really work any more. We'll have to trust that things are queued.
+ //CPPUNIT_ASSERT_EQUAL(1, runHandlers);
+ // Process the other events
+ while (receivedData_.empty()) {
+ boostIOService_->run_one();
+ eventLoop_->processEvents();
+ }
+
+ // Disconnect & clean up
+ testling->disconnect();
+ while (!disconnected_) {
+ boostIOService_->run_one();
+ eventLoop_->processEvents();
+ }
+ }
+
+ void doWrite(BoostConnection* connection) {
+ connection->write(createSafeByteArray("<stream:stream>"));
+ connection->write(createSafeByteArray("\r\n\r\n")); // Temporarily, while we don't have an xmpp server running on ipv6
+ }
+
+ void handleDataRead(boost::shared_ptr<SafeByteArray> data) {
+ append(receivedData_, *data);
+ }
+
+ void handleDisconnected() {
+ disconnected_ = true;
+ }
+
+ void handleConnectFinished() {
+ connectFinished_ = true;
+ }
+
+ private:
+ BoostIOServiceThread* boostIOServiceThread_;
+ boost::shared_ptr<boost::asio::io_service> boostIOService_;
+ DummyEventLoop* eventLoop_;
+ ByteArray receivedData_;
+ bool disconnected_;
+ bool connectFinished_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(BoostConnectionTest);
diff --git a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
index baa42f9..05dd3a1 100644
--- a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
+++ b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
@@ -32,223 +32,223 @@
using namespace Swift;
struct CompareHostAddresses {
- bool operator()(const HostAddress& h1, const HostAddress& h2) {
- return h1.toString() < h2.toString();
- }
+ bool operator()(const HostAddress& h1, const HostAddress& h2) {
+ return h1.toString() < h2.toString();
+ }
};
class DomainNameResolverTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DomainNameResolverTest);
- CPPUNIT_TEST(testResolveAddress);
- CPPUNIT_TEST(testResolveAddress_Error);
+ CPPUNIT_TEST_SUITE(DomainNameResolverTest);
+ CPPUNIT_TEST(testResolveAddress);
+ CPPUNIT_TEST(testResolveAddress_Error);
#ifndef USE_UNBOUND
- /**
- * The native DNS resolver of Windows behaves oddly if the system has no global IPv6
- * routed address and no IPv6 reachability. It will not return IPv6 records from DNS
- * requests for an unspecified protocol (IPv6 or IPv4).
- * The following tests are only enabled on Windows if scons is run with the 'test_ipv6=1'
- * argument, indicating working IPv6 on the test machine.
- */
+ /**
+ * The native DNS resolver of Windows behaves oddly if the system has no global IPv6
+ * routed address and no IPv6 reachability. It will not return IPv6 records from DNS
+ * requests for an unspecified protocol (IPv6 or IPv4).
+ * The following tests are only enabled on Windows if scons is run with the 'test_ipv6=1'
+ * argument, indicating working IPv6 on the test machine.
+ */
#if !defined(SWIFTEN_PLATFORM_WINDOWS) || defined(TEST_IPV6)
- CPPUNIT_TEST(testResolveAddress_IPv6);
- CPPUNIT_TEST(testResolveAddress_IPv4and6);
+ CPPUNIT_TEST(testResolveAddress_IPv6);
+ CPPUNIT_TEST(testResolveAddress_IPv4and6);
#endif
- CPPUNIT_TEST(testResolveAddress_International);
+ CPPUNIT_TEST(testResolveAddress_International);
#endif
- CPPUNIT_TEST(testResolveAddress_Localhost);
- CPPUNIT_TEST(testResolveAddress_Parallel);
+ CPPUNIT_TEST(testResolveAddress_Localhost);
+ CPPUNIT_TEST(testResolveAddress_Parallel);
#ifndef USE_UNBOUND
- CPPUNIT_TEST(testResolveService);
+ CPPUNIT_TEST(testResolveService);
#endif
- CPPUNIT_TEST(testResolveService_Error);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- ioServiceThread = new BoostIOServiceThread();
- eventLoop = new DummyEventLoop();
- idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ CPPUNIT_TEST(testResolveService_Error);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ ioServiceThread = new BoostIOServiceThread();
+ eventLoop = new DummyEventLoop();
+ idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
#ifdef USE_UNBOUND
- resolver = new UnboundDomainNameResolver(idnConverter.get(), ioServiceThread->getIOService(), eventLoop);
+ resolver = new UnboundDomainNameResolver(idnConverter.get(), ioServiceThread->getIOService(), eventLoop);
#else
- resolver = new PlatformDomainNameResolver(idnConverter.get(), eventLoop);
+ resolver = new PlatformDomainNameResolver(idnConverter.get(), eventLoop);
#endif
- resultsAvailable = false;
- }
-
- void tearDown() {
- delete ioServiceThread;
- delete resolver;
- delete eventLoop;
- }
-
- void testResolveAddress() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(!addressQueryError);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addressQueryResult.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.0"), addressQueryResult[0].toString());
- }
-
- void testResolveAddress_Error() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("invalid.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(addressQueryError);
- }
-
- void testResolveAddress_IPv6() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp-ipv6.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(!addressQueryError);
- CPPUNIT_ASSERT_EQUAL(std::string("2001:470:1f0e:852::2"), addressQueryResult[0].toString());
- }
-
- void testResolveAddress_IPv4and6() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp-ipv46.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(!addressQueryError);
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(addressQueryResult.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.7"), addressQueryResult[0].toString());
- CPPUNIT_ASSERT_EQUAL(std::string("1234:5678:9abc:def0:fed:cba9:8765:4321"), addressQueryResult[1].toString());
- }
-
- void testResolveAddress_International() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("tron\xc3\xa7on.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(!addressQueryError);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addressQueryResult.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.3"), addressQueryResult[0].toString());
- }
-
- void testResolveAddress_Localhost() {
- boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("localhost"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT(!addressQueryError);
- CPPUNIT_ASSERT(std::find(addressQueryResult.begin(), addressQueryResult.end(), HostAddress("127.0.0.1")) != addressQueryResult.end());
- }
-
- void testResolveAddress_Parallel() {
- std::vector<DomainNameAddressQuery::ref> queries;
- static const size_t numQueries = 100;
- for (size_t i = 0; i < numQueries; ++i) {
- DomainNameAddressQuery::ref query(createAddressQuery("xmpp.test.swift.im"));
- queries.push_back(query);
- query->run();
- }
-
- eventLoop->processEvents();
- int ticks = 0;
- while (allAddressQueryResults.size() < numQueries) {
- ticks++;
- if (ticks > 1000) {
- CPPUNIT_ASSERT(false);
- }
- Swift::sleep(10);
- eventLoop->processEvents();
- }
-
- CPPUNIT_ASSERT_EQUAL(numQueries, allAddressQueryResults.size());
- for (size_t i = 0; i < numQueries; ++i) {
- CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.0"), allAddressQueryResults[i].toString());
- }
- }
-
- void testResolveService() {
- boost::shared_ptr<DomainNameServiceQuery> query(createServiceQuery("_xmpp-client._tcp.", "xmpp-srv.test.swift.im"));
-
- query->run();
- waitForResults();
-
- CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(serviceQueryResult.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("xmpp1.test.swift.im"), serviceQueryResult[0].hostname);
- CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[0].port);
- CPPUNIT_ASSERT_EQUAL(0, serviceQueryResult[0].priority);
- CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[0].weight);
- CPPUNIT_ASSERT_EQUAL(std::string("xmpp-invalid.test.swift.im"), serviceQueryResult[1].hostname);
- CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[1].port);
- CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[1].priority);
- CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[1].weight);
- CPPUNIT_ASSERT_EQUAL(std::string("xmpp3.test.swift.im"), serviceQueryResult[2].hostname);
- CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[2].port);
- CPPUNIT_ASSERT_EQUAL(3, serviceQueryResult[2].priority);
- CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[2].weight);
- CPPUNIT_ASSERT_EQUAL(std::string("xmpp2.test.swift.im"), serviceQueryResult[3].hostname);
- CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[3].port);
- CPPUNIT_ASSERT_EQUAL(5, serviceQueryResult[3].priority);
- CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[3].weight);
- }
-
- void testResolveService_Error() {
- }
-
- private:
- boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& domain) {
- boost::shared_ptr<DomainNameAddressQuery> result = resolver->createAddressQuery(domain);
- result->onResult.connect(boost::bind(&DomainNameResolverTest::handleAddressQueryResult, this, _1, _2));
- return result;
- }
-
- void handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) {
- addressQueryResult = addresses;
- std::sort(addressQueryResult.begin(), addressQueryResult.end(), CompareHostAddresses());
- allAddressQueryResults.insert(allAddressQueryResults.begin(), addresses.begin(), addresses.end());
- addressQueryError = error;
- resultsAvailable = true;
- }
-
- boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
- boost::shared_ptr<DomainNameServiceQuery> result = resolver->createServiceQuery(serviceLookupPrefix, domain);
- result->onResult.connect(boost::bind(&DomainNameResolverTest::handleServiceQueryResult, this, _1));
- return result;
- }
-
- void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result) {
- serviceQueryResult = result;
- resultsAvailable = true;
- }
-
- void waitForResults() {
- eventLoop->processEvents();
- int ticks = 0;
- while (!resultsAvailable) {
- ticks++;
- if (ticks > 1000) {
- CPPUNIT_ASSERT(false);
- }
- Swift::sleep(10);
- eventLoop->processEvents();
- }
- }
-
- private:
- BoostIOServiceThread* ioServiceThread;
- DummyEventLoop* eventLoop;
- boost::shared_ptr<IDNConverter> idnConverter;
- boost::shared_ptr<TimerFactory> timerFactory;
- bool resultsAvailable;
- std::vector<HostAddress> addressQueryResult;
- std::vector<HostAddress> allAddressQueryResults;
- boost::optional<DomainNameResolveError> addressQueryError;
- std::vector<DomainNameServiceQuery::Result> serviceQueryResult;
- DomainNameResolver* resolver;
+ resultsAvailable = false;
+ }
+
+ void tearDown() {
+ delete ioServiceThread;
+ delete resolver;
+ delete eventLoop;
+ }
+
+ void testResolveAddress() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addressQueryResult.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.0"), addressQueryResult[0].toString());
+ }
+
+ void testResolveAddress_Error() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("invalid.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(addressQueryError);
+ }
+
+ void testResolveAddress_IPv6() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp-ipv6.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT_EQUAL(std::string("2001:470:1f0e:852::2"), addressQueryResult[0].toString());
+ }
+
+ void testResolveAddress_IPv4and6() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("xmpp-ipv46.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(addressQueryResult.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.7"), addressQueryResult[0].toString());
+ CPPUNIT_ASSERT_EQUAL(std::string("1234:5678:9abc:def0:fed:cba9:8765:4321"), addressQueryResult[1].toString());
+ }
+
+ void testResolveAddress_International() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("tron\xc3\xa7on.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(addressQueryResult.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.3"), addressQueryResult[0].toString());
+ }
+
+ void testResolveAddress_Localhost() {
+ boost::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("localhost"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT(std::find(addressQueryResult.begin(), addressQueryResult.end(), HostAddress("127.0.0.1")) != addressQueryResult.end());
+ }
+
+ void testResolveAddress_Parallel() {
+ std::vector<DomainNameAddressQuery::ref> queries;
+ static const size_t numQueries = 100;
+ for (size_t i = 0; i < numQueries; ++i) {
+ DomainNameAddressQuery::ref query(createAddressQuery("xmpp.test.swift.im"));
+ queries.push_back(query);
+ query->run();
+ }
+
+ eventLoop->processEvents();
+ int ticks = 0;
+ while (allAddressQueryResults.size() < numQueries) {
+ ticks++;
+ if (ticks > 1000) {
+ CPPUNIT_ASSERT(false);
+ }
+ Swift::sleep(10);
+ eventLoop->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(numQueries, allAddressQueryResults.size());
+ for (size_t i = 0; i < numQueries; ++i) {
+ CPPUNIT_ASSERT_EQUAL(std::string("10.0.0.0"), allAddressQueryResults[i].toString());
+ }
+ }
+
+ void testResolveService() {
+ boost::shared_ptr<DomainNameServiceQuery> query(createServiceQuery("_xmpp-client._tcp.", "xmpp-srv.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(serviceQueryResult.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("xmpp1.test.swift.im"), serviceQueryResult[0].hostname);
+ CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[0].port);
+ CPPUNIT_ASSERT_EQUAL(0, serviceQueryResult[0].priority);
+ CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[0].weight);
+ CPPUNIT_ASSERT_EQUAL(std::string("xmpp-invalid.test.swift.im"), serviceQueryResult[1].hostname);
+ CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[1].port);
+ CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[1].priority);
+ CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[1].weight);
+ CPPUNIT_ASSERT_EQUAL(std::string("xmpp3.test.swift.im"), serviceQueryResult[2].hostname);
+ CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[2].port);
+ CPPUNIT_ASSERT_EQUAL(3, serviceQueryResult[2].priority);
+ CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[2].weight);
+ CPPUNIT_ASSERT_EQUAL(std::string("xmpp2.test.swift.im"), serviceQueryResult[3].hostname);
+ CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[3].port);
+ CPPUNIT_ASSERT_EQUAL(5, serviceQueryResult[3].priority);
+ CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[3].weight);
+ }
+
+ void testResolveService_Error() {
+ }
+
+ private:
+ boost::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& domain) {
+ boost::shared_ptr<DomainNameAddressQuery> result = resolver->createAddressQuery(domain);
+ result->onResult.connect(boost::bind(&DomainNameResolverTest::handleAddressQueryResult, this, _1, _2));
+ return result;
+ }
+
+ void handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) {
+ addressQueryResult = addresses;
+ std::sort(addressQueryResult.begin(), addressQueryResult.end(), CompareHostAddresses());
+ allAddressQueryResults.insert(allAddressQueryResults.begin(), addresses.begin(), addresses.end());
+ addressQueryError = error;
+ resultsAvailable = true;
+ }
+
+ boost::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
+ boost::shared_ptr<DomainNameServiceQuery> result = resolver->createServiceQuery(serviceLookupPrefix, domain);
+ result->onResult.connect(boost::bind(&DomainNameResolverTest::handleServiceQueryResult, this, _1));
+ return result;
+ }
+
+ void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result) {
+ serviceQueryResult = result;
+ resultsAvailable = true;
+ }
+
+ void waitForResults() {
+ eventLoop->processEvents();
+ int ticks = 0;
+ while (!resultsAvailable) {
+ ticks++;
+ if (ticks > 1000) {
+ CPPUNIT_ASSERT(false);
+ }
+ Swift::sleep(10);
+ eventLoop->processEvents();
+ }
+ }
+
+ private:
+ BoostIOServiceThread* ioServiceThread;
+ DummyEventLoop* eventLoop;
+ boost::shared_ptr<IDNConverter> idnConverter;
+ boost::shared_ptr<TimerFactory> timerFactory;
+ bool resultsAvailable;
+ std::vector<HostAddress> addressQueryResult;
+ std::vector<HostAddress> allAddressQueryResults;
+ boost::optional<DomainNameResolveError> addressQueryError;
+ std::vector<DomainNameServiceQuery::Result> serviceQueryResult;
+ DomainNameResolver* resolver;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DomainNameResolverTest);
diff --git a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
index 3a9707b..2b6bfa8 100644
--- a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
+++ b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
@@ -19,23 +19,23 @@ 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;
+ 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/QA/ReconnectTest/ReconnectTest.cpp b/Swiften/QA/ReconnectTest/ReconnectTest.cpp
index fc47312..611c846 100644
--- a/Swiften/QA/ReconnectTest/ReconnectTest.cpp
+++ b/Swiften/QA/ReconnectTest/ReconnectTest.cpp
@@ -26,48 +26,48 @@ SimpleEventLoop eventLoop_;
int count = 0;
void handleTick(boost::shared_ptr<BoostTimer> timer) {
- std::cout << "Count " << count++ << std::endl;
- if (timer) {
- timer->stop();
- }
- if (connecting_) {
- client_->disconnect();
- } else {
- if (count > 60) {
- eventLoop_.stop();
- return;
- }
- client_->connect();
- }
- connecting_ = !connecting_;
-
- int delay = 500;
-// int delay = 0;
- boost::shared_ptr<BoostTimer> newTimer(BoostTimer::create(delay, &MainBoostIOServiceThread::getInstance().getIOService()));
- newTimer->onTick.connect(boost::bind(&handleTick, timer));
- newTimer->start();
+ std::cout << "Count " << count++ << std::endl;
+ if (timer) {
+ timer->stop();
+ }
+ if (connecting_) {
+ client_->disconnect();
+ } else {
+ if (count > 60) {
+ eventLoop_.stop();
+ return;
+ }
+ client_->connect();
+ }
+ connecting_ = !connecting_;
+
+ int delay = 500;
+// int delay = 0;
+ boost::shared_ptr<BoostTimer> newTimer(BoostTimer::create(delay, &MainBoostIOServiceThread::getInstance().getIOService()));
+ newTimer->onTick.connect(boost::bind(&handleTick, timer));
+ newTimer->start();
}
int main(int, char**) {
- char* jidChars = getenv("SWIFT_CLIENTTEST_JID");
- if (!jidChars) {
- std::cerr << "Please set the SWIFT_CLIENTTEST_JID environment variable" << std::endl;
- return -1;
- }
- char* passChars = getenv("SWIFT_CLIENTTEST_PASS");
- if (!passChars) {
- std::cerr << "Please set the SWIFT_CLIENTTEST_PASS environment variable" << std::endl;
- return -1;
- }
-
- JID jid(jidChars);
- std::string pass(passChars);
+ char* jidChars = getenv("SWIFT_CLIENTTEST_JID");
+ if (!jidChars) {
+ std::cerr << "Please set the SWIFT_CLIENTTEST_JID environment variable" << std::endl;
+ return -1;
+ }
+ char* passChars = getenv("SWIFT_CLIENTTEST_PASS");
+ if (!passChars) {
+ std::cerr << "Please set the SWIFT_CLIENTTEST_PASS environment variable" << std::endl;
+ return -1;
+ }
+
+ JID jid(jidChars);
+ std::string pass(passChars);
+
+ client_ = new Swift::Client(jid, pass);
+ handleTick(boost::shared_ptr<BoostTimer>());
+ eventLoop_.run();
- client_ = new Swift::Client(jid, pass);
- handleTick(boost::shared_ptr<BoostTimer>());
- eventLoop_.run();
-
- delete client_;
- return 0;
+ delete client_;
+ return 0;
}
diff --git a/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp b/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp
index d70d9c9..5b3867c 100644
--- a/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp
+++ b/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp
@@ -15,61 +15,61 @@
using namespace Swift;
class FileReadBytestreamTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FileReadBytestreamTest);
- CPPUNIT_TEST(testRead);
- CPPUNIT_TEST(testRead_Twice);
- CPPUNIT_TEST(testIsFinished_NotFinished);
- CPPUNIT_TEST(testIsFinished_IsFinished);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(FileReadBytestreamTest);
+ CPPUNIT_TEST(testRead);
+ CPPUNIT_TEST(testRead_Twice);
+ CPPUNIT_TEST(testIsFinished_NotFinished);
+ CPPUNIT_TEST(testIsFinished_IsFinished);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- pathProvider = new PlatformApplicationPathProvider("FileReadBytestreamTest");
- }
+ public:
+ void setUp() {
+ pathProvider = new PlatformApplicationPathProvider("FileReadBytestreamTest");
+ }
- void tearDown() {
- delete pathProvider;
- }
+ void tearDown() {
+ delete pathProvider;
+ }
- void testRead() {
- boost::shared_ptr<FileReadBytestream> testling(createTestling());
+ void testRead() {
+ boost::shared_ptr<FileReadBytestream> testling(createTestling());
- boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
+ boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
- CPPUNIT_ASSERT(createByteArray("/*\n * Copy") == *result.get());
- }
+ CPPUNIT_ASSERT(createByteArray("/*\n * Copy") == *result.get());
+ }
- void testRead_Twice() {
- boost::shared_ptr<FileReadBytestream> testling(createTestling());
+ void testRead_Twice() {
+ boost::shared_ptr<FileReadBytestream> testling(createTestling());
- testling->read(10);
- boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
+ testling->read(10);
+ boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
- CPPUNIT_ASSERT_EQUAL(std::string("right (c) "), byteArrayToString(*result));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("right (c) "), byteArrayToString(*result));
+ }
- void testIsFinished_NotFinished() {
- boost::shared_ptr<FileReadBytestream> testling(createTestling());
+ void testIsFinished_NotFinished() {
+ boost::shared_ptr<FileReadBytestream> testling(createTestling());
- testling->read(10);
+ testling->read(10);
- CPPUNIT_ASSERT(!testling->isFinished());
- }
+ CPPUNIT_ASSERT(!testling->isFinished());
+ }
- void testIsFinished_IsFinished() {
- boost::shared_ptr<FileReadBytestream> testling(createTestling());
+ void testIsFinished_IsFinished() {
+ boost::shared_ptr<FileReadBytestream> testling(createTestling());
- testling->read(4096);
+ testling->read(4096);
- CPPUNIT_ASSERT(testling->isFinished());
- }
+ CPPUNIT_ASSERT(testling->isFinished());
+ }
- private:
- FileReadBytestream* createTestling() {
- return new FileReadBytestream(pathProvider->getExecutableDir() / "FileReadBytestreamTest.cpp");
- }
+ private:
+ FileReadBytestream* createTestling() {
+ return new FileReadBytestream(pathProvider->getExecutableDir() / "FileReadBytestreamTest.cpp");
+ }
- PlatformApplicationPathProvider* pathProvider;
+ PlatformApplicationPathProvider* pathProvider;
};
CPPUNIT_TEST_SUITE_REGISTRATION(FileReadBytestreamTest);
diff --git a/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp b/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp
index 3686cf9..e847c28 100644
--- a/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp
+++ b/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp
@@ -17,42 +17,42 @@
using namespace Swift;
class FileWriteBytestreamTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FileWriteBytestreamTest);
- CPPUNIT_TEST(testSuccessfulWrite);
- CPPUNIT_TEST(testFailingWrite);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(FileWriteBytestreamTest);
+ CPPUNIT_TEST(testSuccessfulWrite);
+ CPPUNIT_TEST(testFailingWrite);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- onWriteWasCalled = false;
- }
+ public:
+ void setUp() {
+ onWriteWasCalled = false;
+ }
- void testSuccessfulWrite() {
- boost::filesystem::path filename = boost::filesystem::unique_path("write_file_bytestream_test_%%%%%%%%%%%%%%%%.bin");
- boost::shared_ptr<WriteBytestream> writeBytestream = boost::make_shared<FileWriteBytestream>(filename.string());
- writeBytestream->onWrite.connect(boost::bind(&FileWriteBytestreamTest::handleOnWrite, this, _1));
+ void testSuccessfulWrite() {
+ boost::filesystem::path filename = boost::filesystem::unique_path("write_file_bytestream_test_%%%%%%%%%%%%%%%%.bin");
+ boost::shared_ptr<WriteBytestream> writeBytestream = boost::make_shared<FileWriteBytestream>(filename.string());
+ writeBytestream->onWrite.connect(boost::bind(&FileWriteBytestreamTest::handleOnWrite, this, _1));
- CPPUNIT_ASSERT_EQUAL(true, writeBytestream->write(createByteArray("Some data.")));
- CPPUNIT_ASSERT_EQUAL(true, onWriteWasCalled);
+ CPPUNIT_ASSERT_EQUAL(true, writeBytestream->write(createByteArray("Some data.")));
+ CPPUNIT_ASSERT_EQUAL(true, onWriteWasCalled);
- boost::filesystem::remove(filename);
- }
+ boost::filesystem::remove(filename);
+ }
- void testFailingWrite() {
- boost::shared_ptr<WriteBytestream> writeBytestream = boost::make_shared<FileWriteBytestream>("");
- writeBytestream->onWrite.connect(boost::bind(&FileWriteBytestreamTest::handleOnWrite, this, _1));
+ void testFailingWrite() {
+ boost::shared_ptr<WriteBytestream> writeBytestream = boost::make_shared<FileWriteBytestream>("");
+ writeBytestream->onWrite.connect(boost::bind(&FileWriteBytestreamTest::handleOnWrite, this, _1));
- CPPUNIT_ASSERT_EQUAL(false, writeBytestream->write(createByteArray("Some data.")));
- CPPUNIT_ASSERT_EQUAL(false, onWriteWasCalled);
- }
+ CPPUNIT_ASSERT_EQUAL(false, writeBytestream->write(createByteArray("Some data.")));
+ CPPUNIT_ASSERT_EQUAL(false, onWriteWasCalled);
+ }
- void handleOnWrite(const std::vector<unsigned char>& /*data*/) {
- onWriteWasCalled = true;
- }
+ void handleOnWrite(const std::vector<unsigned char>& /*data*/) {
+ onWriteWasCalled = true;
+ }
- private:
- bool onWriteWasCalled;
+ private:
+ bool onWriteWasCalled;
};
CPPUNIT_TEST_SUITE_REGISTRATION(FileWriteBytestreamTest);
diff --git a/Swiften/QA/StorageTest/VCardFileStorageTest.cpp b/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
index 4d639e6..69e5917 100644
--- a/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
+++ b/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
@@ -20,97 +20,97 @@
using namespace Swift;
class VCardFileStorageTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(VCardFileStorageTest);
- CPPUNIT_TEST(testSetVCard);
- // Temporarily disabling this, because it generates error messages on console. Need to figure
- // out something for not showing error messages during tests.
- //CPPUNIT_TEST(testSetVCard_LargeFilename);
- CPPUNIT_TEST(testGetVCard);
- CPPUNIT_TEST(testGetVCard_FileDoesNotExist);
- //CPPUNIT_TEST(testGetVCard_LargeFilename);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- pathProvider = new PlatformApplicationPathProvider("VCardStorageTest");
- vcardsPath = pathProvider->getExecutableDir() / "vcards";
- boost::filesystem::remove_all(vcardsPath);
- }
-
- void tearDown() {
- delete pathProvider;
- boost::filesystem::remove_all(vcardsPath);
- }
-
- void testSetVCard() {
- boost::shared_ptr<VCardFileStorage> testling(createTestling());
- VCard::ref vcard(new VCard());
- vcard->setFullName("Alice In Wonderland");
-
- testling->setVCard(JID("alice@wonderland.lit/TeaRoom"), vcard);
-
- boost::filesystem::path vcardFile(vcardsPath / "alice@wonderland.lit%2fTeaRoom.xml");
- CPPUNIT_ASSERT(boost::filesystem::exists(vcardFile));
- ByteArray data;
- data.readFromFile(vcardFile);
- CPPUNIT_ASSERT(boost::starts_with(data.toString(), "<vCard xmlns=\"vcard-temp\">"));
- }
-
- void testSetVCard_LargeFilename() {
- std::auto_ptr<VCardFileStorage> testling(createTestling());
- VCard::ref vcard(new VCard());
- vcard->setFullName("Alice In Wonderland");
-
- std::ostringstream s;
- for (int i = 0; i < 1000; ++i) {
- s << "_";
- }
-
- JID jid("alice@wonderland.lit/" + s.str());
- testling->setVCard(jid, vcard);
-
- // Just check whether we don't crash
- }
-
- void testGetVCard() {
- boost::shared_ptr<VCardFileStorage> testling(createTestling());
- VCard::ref vcard(new VCard());
- vcard->setFullName("Alice In Wonderland");
- testling->setVCard(JID("alice@wonderland.lit"), vcard);
-
- VCard::ref result = testling->getVCard(JID("alice@wonderland.lit"));
- CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), result->getFullName());
- }
-
- void testGetVCard_LargeFilename() {
- std::auto_ptr<VCardFileStorage> testling(createTestling());
- VCard::ref vcard(new VCard());
- vcard->setFullName("Alice In Wonderland");
-
- std::ostringstream s;
- for (int i = 0; i < 1000; ++i) {
- s << "_";
- }
- JID jid("alice@wonderland.lit/" + s.str());
-
- VCard::ref result = testling->getVCard(jid);
-
- // Just check that we don't have an exception
- }
-
- void testGetVCard_FileDoesNotExist() {
- boost::shared_ptr<VCardFileStorage> testling(createTestling());
- VCard::ref result = testling->getVCard(JID("alice@wonderland.lit"));
- CPPUNIT_ASSERT(!result);
- }
-
- private:
- VCardFileStorage* createTestling() {
- return new VCardFileStorage(vcardsPath);
- }
-
- PlatformApplicationPathProvider* pathProvider;
- boost::filesystem::path vcardsPath;
+ CPPUNIT_TEST_SUITE(VCardFileStorageTest);
+ CPPUNIT_TEST(testSetVCard);
+ // Temporarily disabling this, because it generates error messages on console. Need to figure
+ // out something for not showing error messages during tests.
+ //CPPUNIT_TEST(testSetVCard_LargeFilename);
+ CPPUNIT_TEST(testGetVCard);
+ CPPUNIT_TEST(testGetVCard_FileDoesNotExist);
+ //CPPUNIT_TEST(testGetVCard_LargeFilename);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ pathProvider = new PlatformApplicationPathProvider("VCardStorageTest");
+ vcardsPath = pathProvider->getExecutableDir() / "vcards";
+ boost::filesystem::remove_all(vcardsPath);
+ }
+
+ void tearDown() {
+ delete pathProvider;
+ boost::filesystem::remove_all(vcardsPath);
+ }
+
+ void testSetVCard() {
+ boost::shared_ptr<VCardFileStorage> testling(createTestling());
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Alice In Wonderland");
+
+ testling->setVCard(JID("alice@wonderland.lit/TeaRoom"), vcard);
+
+ boost::filesystem::path vcardFile(vcardsPath / "alice@wonderland.lit%2fTeaRoom.xml");
+ CPPUNIT_ASSERT(boost::filesystem::exists(vcardFile));
+ ByteArray data;
+ data.readFromFile(vcardFile);
+ CPPUNIT_ASSERT(boost::starts_with(data.toString(), "<vCard xmlns=\"vcard-temp\">"));
+ }
+
+ void testSetVCard_LargeFilename() {
+ std::auto_ptr<VCardFileStorage> testling(createTestling());
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Alice In Wonderland");
+
+ std::ostringstream s;
+ for (int i = 0; i < 1000; ++i) {
+ s << "_";
+ }
+
+ JID jid("alice@wonderland.lit/" + s.str());
+ testling->setVCard(jid, vcard);
+
+ // Just check whether we don't crash
+ }
+
+ void testGetVCard() {
+ boost::shared_ptr<VCardFileStorage> testling(createTestling());
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Alice In Wonderland");
+ testling->setVCard(JID("alice@wonderland.lit"), vcard);
+
+ VCard::ref result = testling->getVCard(JID("alice@wonderland.lit"));
+ CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), result->getFullName());
+ }
+
+ void testGetVCard_LargeFilename() {
+ std::auto_ptr<VCardFileStorage> testling(createTestling());
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Alice In Wonderland");
+
+ std::ostringstream s;
+ for (int i = 0; i < 1000; ++i) {
+ s << "_";
+ }
+ JID jid("alice@wonderland.lit/" + s.str());
+
+ VCard::ref result = testling->getVCard(jid);
+
+ // Just check that we don't have an exception
+ }
+
+ void testGetVCard_FileDoesNotExist() {
+ boost::shared_ptr<VCardFileStorage> testling(createTestling());
+ VCard::ref result = testling->getVCard(JID("alice@wonderland.lit"));
+ CPPUNIT_ASSERT(!result);
+ }
+
+ private:
+ VCardFileStorage* createTestling() {
+ return new VCardFileStorage(vcardsPath);
+ }
+
+ PlatformApplicationPathProvider* pathProvider;
+ boost::filesystem::path vcardsPath;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardFileStorageTest);
diff --git a/Swiften/QA/TLSTest/CertificateErrorTest.cpp b/Swiften/QA/TLSTest/CertificateErrorTest.cpp
index ec8c4e3..b928a3f 100644
--- a/Swiften/QA/TLSTest/CertificateErrorTest.cpp
+++ b/Swiften/QA/TLSTest/CertificateErrorTest.cpp
@@ -5,7 +5,7 @@
*/
/*
- This file uses http://www.tls-o-matic.com/ to test the currently configured TLS backend for correct certificate validation behavior.
+ This file uses http://www.tls-o-matic.com/ to test the currently configured TLS backend for correct certificate validation behavior.
*/
#include <cppunit/extensions/HelperMacros.h>
@@ -29,195 +29,195 @@
using namespace Swift;
class CertificateErrorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CertificateErrorTest);
+ CPPUNIT_TEST_SUITE(CertificateErrorTest);
- // These test require the TLS-O-Matic testing CA to be trusted. For more info see https://www.tls-o-matic.com/https/test1 .
- CPPUNIT_TEST(testTLS_O_MaticTrusted);
- CPPUNIT_TEST(testTLS_O_MaticCertificateFromTheFuture);
- CPPUNIT_TEST(testTLS_O_MaticCertificateFromThePast);
- CPPUNIT_TEST(testTLS_O_MaticCertificateFromUnknownCA);
- CPPUNIT_TEST(testTLS_O_MaticCertificateWrongPurpose);
+ // These test require the TLS-O-Matic testing CA to be trusted. For more info see https://www.tls-o-matic.com/https/test1 .
+ CPPUNIT_TEST(testTLS_O_MaticTrusted);
+ CPPUNIT_TEST(testTLS_O_MaticCertificateFromTheFuture);
+ CPPUNIT_TEST(testTLS_O_MaticCertificateFromThePast);
+ CPPUNIT_TEST(testTLS_O_MaticCertificateFromUnknownCA);
+ CPPUNIT_TEST(testTLS_O_MaticCertificateWrongPurpose);
#if !defined(HAVE_OPENSSL)
- // Our OpenSSL backend does not support revocation. We excluded it from the revocation tests.
- CPPUNIT_TEST(testRevokedCertificateRevocationDisabled);
- CPPUNIT_TEST(testRevokedCertificateRevocationEnabled);
+ // Our OpenSSL backend does not support revocation. We excluded it from the revocation tests.
+ CPPUNIT_TEST(testRevokedCertificateRevocationDisabled);
+ CPPUNIT_TEST(testRevokedCertificateRevocationEnabled);
#endif
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- eventLoop_ = new DummyEventLoop();
- boostIOServiceThread_ = new BoostIOServiceThread();
- boostIOService_ = boost::make_shared<boost::asio::io_service>();
- connectionFactory_ = new BoostConnectionFactory(boostIOServiceThread_->getIOService(), eventLoop_);
- idnConverter_ = PlatformIDNConverter::create();
- domainNameResolver_ = new PlatformDomainNameResolver(idnConverter_, eventLoop_);
-
- tlsFactories_ = new PlatformTLSFactories();
- tlsContextFactory_ = tlsFactories_->getTLSContextFactory();
-
- tlsContextFactory_->setCheckCertificateRevocation(false);
-
- tlsConnectionFactory_ = new TLSConnectionFactory(tlsContextFactory_, connectionFactory_, TLSOptions());
-
- connectFinished_ = false;
- connectFinishedWithError_ = false;
- }
-
- void tearDown() {
- delete tlsConnectionFactory_;
- delete tlsFactories_;
-
- delete domainNameResolver_;
- delete idnConverter_;
- delete connectionFactory_;
- delete boostIOServiceThread_;
- while (eventLoop_->hasEvents()) {
- eventLoop_->processEvents();
- }
- delete eventLoop_;
- }
-
- HostAddress resolveName(const std::string& name) {
- boost::shared_ptr<DomainNameAddressQuery> query = domainNameResolver_->createAddressQuery(name);
- query->onResult.connect(boost::bind(&CertificateErrorTest::handleAddressQueryResult, this, _1, _2));
- lastResoverResult_ = HostAddress();
- resolvingDone_ = false;
-
- query->run();
- while(!resolvingDone_) {
- eventLoop_->processEvents();
- }
-
- return lastResoverResult_;
- }
-
- void connectToServer(boost::shared_ptr<TLSConnection> connection, const std::string& hostname, int port) {
- connection->onConnectFinished.connect(boost::bind(&CertificateErrorTest::handleConnectFinished, this, _1));
-
- HostAddress address = resolveName(hostname);
-
- connection->connect(HostAddressPort(address, port));
-
- while (!connectFinished_) {
- eventLoop_->processEvents();
- }
- }
-
- void testTLS_O_MaticTrusted() {
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "test1.tls-o-matic.com", 443);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::ref(), context->getPeerCertificateVerificationError());
- }
-
- void testTLS_O_MaticCertificateFromTheFuture() {
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "test5.tls-o-matic.com", 405);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ eventLoop_ = new DummyEventLoop();
+ boostIOServiceThread_ = new BoostIOServiceThread();
+ boostIOService_ = boost::make_shared<boost::asio::io_service>();
+ connectionFactory_ = new BoostConnectionFactory(boostIOServiceThread_->getIOService(), eventLoop_);
+ idnConverter_ = PlatformIDNConverter::create();
+ domainNameResolver_ = new PlatformDomainNameResolver(idnConverter_, eventLoop_);
+
+ tlsFactories_ = new PlatformTLSFactories();
+ tlsContextFactory_ = tlsFactories_->getTLSContextFactory();
+
+ tlsContextFactory_->setCheckCertificateRevocation(false);
+
+ tlsConnectionFactory_ = new TLSConnectionFactory(tlsContextFactory_, connectionFactory_, TLSOptions());
+
+ connectFinished_ = false;
+ connectFinishedWithError_ = false;
+ }
+
+ void tearDown() {
+ delete tlsConnectionFactory_;
+ delete tlsFactories_;
+
+ delete domainNameResolver_;
+ delete idnConverter_;
+ delete connectionFactory_;
+ delete boostIOServiceThread_;
+ while (eventLoop_->hasEvents()) {
+ eventLoop_->processEvents();
+ }
+ delete eventLoop_;
+ }
+
+ HostAddress resolveName(const std::string& name) {
+ boost::shared_ptr<DomainNameAddressQuery> query = domainNameResolver_->createAddressQuery(name);
+ query->onResult.connect(boost::bind(&CertificateErrorTest::handleAddressQueryResult, this, _1, _2));
+ lastResoverResult_ = HostAddress();
+ resolvingDone_ = false;
+
+ query->run();
+ while(!resolvingDone_) {
+ eventLoop_->processEvents();
+ }
+
+ return lastResoverResult_;
+ }
+
+ void connectToServer(boost::shared_ptr<TLSConnection> connection, const std::string& hostname, int port) {
+ connection->onConnectFinished.connect(boost::bind(&CertificateErrorTest::handleConnectFinished, this, _1));
+
+ HostAddress address = resolveName(hostname);
+
+ connection->connect(HostAddressPort(address, port));
+
+ while (!connectFinished_) {
+ eventLoop_->processEvents();
+ }
+ }
+
+ void testTLS_O_MaticTrusted() {
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "test1.tls-o-matic.com", 443);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::ref(), context->getPeerCertificateVerificationError());
+ }
+
+ void testTLS_O_MaticCertificateFromTheFuture() {
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "test5.tls-o-matic.com", 405);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
#if defined(HAVE_SCHANNEL)
- // Windows SChannel API does not differentiate between expired and not yet valid.
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Expired, context->getPeerCertificateVerificationError()->getType());
+ // Windows SChannel API does not differentiate between expired and not yet valid.
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Expired, context->getPeerCertificateVerificationError()->getType());
#else
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::NotYetValid, context->getPeerCertificateVerificationError()->getType());
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::NotYetValid, context->getPeerCertificateVerificationError()->getType());
#endif
- }
-
- void testTLS_O_MaticCertificateFromThePast() {
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "test6.tls-o-matic.com", 406);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Expired, context->getPeerCertificateVerificationError()->getType());
- }
-
- void testTLS_O_MaticCertificateFromUnknownCA() {
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "test7.tls-o-matic.com", 407);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Untrusted, context->getPeerCertificateVerificationError()->getType());
- }
-
- // test14.tls-o-matic.com:414
- void testTLS_O_MaticCertificateWrongPurpose() {
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "test14.tls-o-matic.com", 414);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidPurpose, context->getPeerCertificateVerificationError()->getType());
- }
-
- void testRevokedCertificateRevocationDisabled() {
- tlsContextFactory_->setCheckCertificateRevocation(false);
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "revoked.grc.com", 443);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(!context->getPeerCertificateVerificationError());
- }
-
- void testRevokedCertificateRevocationEnabled() {
- tlsContextFactory_->setCheckCertificateRevocation(true);
- boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
- TLSContext* context = connection->getTLSContext();
-
- connectToServer(connection, "revoked.grc.com", 443);
-
- CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
- CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
- CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Revoked, context->getPeerCertificateVerificationError()->getType());
- }
-
- private:
- void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> /* error */) {
- if (address.size() > 0) {
- lastResoverResult_ = address[0];
- }
- resolvingDone_ = true;
- }
-
- void handleConnectFinished(bool error) {
- connectFinished_ = true;
- connectFinishedWithError_ = error;
- }
-
- private:
- BoostIOServiceThread* boostIOServiceThread_;
- boost::shared_ptr<boost::asio::io_service> boostIOService_;
- DummyEventLoop* eventLoop_;
- ConnectionFactory* connectionFactory_;
- PlatformTLSFactories* tlsFactories_;
- TLSContextFactory* tlsContextFactory_;
- TLSConnectionFactory* tlsConnectionFactory_;
-
- IDNConverter* idnConverter_;
- DomainNameResolver* domainNameResolver_;
- HostAddress lastResoverResult_;
- bool resolvingDone_;
-
- bool connectFinished_;
- bool connectFinishedWithError_;
+ }
+
+ void testTLS_O_MaticCertificateFromThePast() {
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "test6.tls-o-matic.com", 406);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Expired, context->getPeerCertificateVerificationError()->getType());
+ }
+
+ void testTLS_O_MaticCertificateFromUnknownCA() {
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "test7.tls-o-matic.com", 407);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Untrusted, context->getPeerCertificateVerificationError()->getType());
+ }
+
+ // test14.tls-o-matic.com:414
+ void testTLS_O_MaticCertificateWrongPurpose() {
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "test14.tls-o-matic.com", 414);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidPurpose, context->getPeerCertificateVerificationError()->getType());
+ }
+
+ void testRevokedCertificateRevocationDisabled() {
+ tlsContextFactory_->setCheckCertificateRevocation(false);
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "revoked.grc.com", 443);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(!context->getPeerCertificateVerificationError());
+ }
+
+ void testRevokedCertificateRevocationEnabled() {
+ tlsContextFactory_->setCheckCertificateRevocation(true);
+ boost::shared_ptr<TLSConnection> connection = boost::dynamic_pointer_cast<TLSConnection>(tlsConnectionFactory_->createConnection());
+ TLSContext* context = connection->getTLSContext();
+
+ connectToServer(connection, "revoked.grc.com", 443);
+
+ CPPUNIT_ASSERT_EQUAL(false, connectFinishedWithError_);
+ CPPUNIT_ASSERT(context->getPeerCertificateVerificationError());
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::Revoked, context->getPeerCertificateVerificationError()->getType());
+ }
+
+ private:
+ void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> /* error */) {
+ if (address.size() > 0) {
+ lastResoverResult_ = address[0];
+ }
+ resolvingDone_ = true;
+ }
+
+ void handleConnectFinished(bool error) {
+ connectFinished_ = true;
+ connectFinishedWithError_ = error;
+ }
+
+ private:
+ BoostIOServiceThread* boostIOServiceThread_;
+ boost::shared_ptr<boost::asio::io_service> boostIOService_;
+ DummyEventLoop* eventLoop_;
+ ConnectionFactory* connectionFactory_;
+ PlatformTLSFactories* tlsFactories_;
+ TLSContextFactory* tlsContextFactory_;
+ TLSConnectionFactory* tlsConnectionFactory_;
+
+ IDNConverter* idnConverter_;
+ DomainNameResolver* domainNameResolver_;
+ HostAddress lastResoverResult_;
+ bool resolvingDone_;
+
+ bool connectFinished_;
+ bool connectFinishedWithError_;
};
diff --git a/Swiften/QA/TLSTest/CertificateTest.cpp b/Swiften/QA/TLSTest/CertificateTest.cpp
index c9315d2..ede1063 100644
--- a/Swiften/QA/TLSTest/CertificateTest.cpp
+++ b/Swiften/QA/TLSTest/CertificateTest.cpp
@@ -20,81 +20,81 @@ using namespace Swift;
template<typename CERTIFICATE_FACTORY>
class CertificateTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CertificateTest);
- CPPUNIT_TEST(testConstructFromDER);
- CPPUNIT_TEST(testToDER);
- //CPPUNIT_TEST(testGetSubjectName);
- CPPUNIT_TEST(testGetCommonNames);
- CPPUNIT_TEST(testGetSRVNames);
- CPPUNIT_TEST(testGetDNSNames);
- CPPUNIT_TEST(testGetXMPPAddresses);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- pathProvider = new PlatformApplicationPathProvider("FileReadBytestreamTest");
- readByteArrayFromFile(certificateData, (pathProvider->getExecutableDir() / "jabber_org.crt"));
- certificateFactory = new CERTIFICATE_FACTORY();
- }
-
- void tearDown() {
- delete certificateFactory;
- delete pathProvider;
- }
-
- void testConstructFromDER() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getCommonNames()[0]);
- }
-
- void testToDER() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(certificateData, testling->toDER());
- }
+ CPPUNIT_TEST_SUITE(CertificateTest);
+ CPPUNIT_TEST(testConstructFromDER);
+ CPPUNIT_TEST(testToDER);
+ //CPPUNIT_TEST(testGetSubjectName);
+ CPPUNIT_TEST(testGetCommonNames);
+ CPPUNIT_TEST(testGetSRVNames);
+ CPPUNIT_TEST(testGetDNSNames);
+ CPPUNIT_TEST(testGetXMPPAddresses);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ pathProvider = new PlatformApplicationPathProvider("FileReadBytestreamTest");
+ readByteArrayFromFile(certificateData, (pathProvider->getExecutableDir() / "jabber_org.crt"));
+ certificateFactory = new CERTIFICATE_FACTORY();
+ }
+
+ void tearDown() {
+ delete certificateFactory;
+ delete pathProvider;
+ }
+
+ void testConstructFromDER() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getCommonNames()[0]);
+ }
+
+ void testToDER() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(certificateData, testling->toDER());
+ }
/*
- void testGetSubjectName() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData);
-
- CPPUNIT_ASSERT_EQUAL(std::string("/description=114072-VMk8pdi1aj5kTXxO/C=US/ST=Colorado/L=Denver/O=Peter Saint-Andre/OU=StartCom Trusted Certificate Member/CN=*.jabber.org/emailAddress=hostmaster@jabber.org"), testling->getSubjectName());
- }
- */
-
- void testGetCommonNames() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getCommonNames().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getCommonNames()[0]);
- }
-
- void testGetSRVNames() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getSRVNames().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getSRVNames()[0]);
- }
-
- void testGetDNSNames() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getDNSNames().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getDNSNames()[0]);
- CPPUNIT_ASSERT_EQUAL(std::string("jabber.org"), testling->getDNSNames()[1]);
- }
-
- void testGetXMPPAddresses() {
- Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getXMPPAddresses().size()));
- CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getXMPPAddresses()[0]);
- }
-
- private:
- PlatformApplicationPathProvider* pathProvider;
- ByteArray certificateData;
- CertificateFactory* certificateFactory;
+ void testGetSubjectName() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("/description=114072-VMk8pdi1aj5kTXxO/C=US/ST=Colorado/L=Denver/O=Peter Saint-Andre/OU=StartCom Trusted Certificate Member/CN=*.jabber.org/emailAddress=hostmaster@jabber.org"), testling->getSubjectName());
+ }
+ */
+
+ void testGetCommonNames() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getCommonNames().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getCommonNames()[0]);
+ }
+
+ void testGetSRVNames() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getSRVNames().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getSRVNames()[0]);
+ }
+
+ void testGetDNSNames() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getDNSNames().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getDNSNames()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber.org"), testling->getDNSNames()[1]);
+ }
+
+ void testGetXMPPAddresses() {
+ Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling->getXMPPAddresses().size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getXMPPAddresses()[0]);
+ }
+
+ private:
+ PlatformApplicationPathProvider* pathProvider;
+ ByteArray certificateData;
+ CertificateFactory* certificateFactory;
};
#ifdef HAVE_OPENSSL
diff --git a/Swiften/Queries/DummyIQChannel.h b/Swiften/Queries/DummyIQChannel.h
index 11cc3dc..3f896e0 100644
--- a/Swiften/Queries/DummyIQChannel.h
+++ b/Swiften/Queries/DummyIQChannel.h
@@ -11,22 +11,22 @@
#include <Swiften/Queries/IQChannel.h>
namespace Swift {
- class DummyIQChannel : public IQChannel {
- public:
- DummyIQChannel() {}
+ class DummyIQChannel : public IQChannel {
+ public:
+ DummyIQChannel() {}
- virtual void sendIQ(boost::shared_ptr<IQ> iq) {
- iqs_.push_back(iq);
- }
+ virtual void sendIQ(boost::shared_ptr<IQ> iq) {
+ iqs_.push_back(iq);
+ }
- virtual std::string getNewIQID() {
- return "test-id";
- }
+ virtual std::string getNewIQID() {
+ return "test-id";
+ }
- virtual bool isAvailable() const {
- return true;
- }
+ virtual bool isAvailable() const {
+ return true;
+ }
- std::vector<boost::shared_ptr<IQ> > iqs_;
- };
+ std::vector<boost::shared_ptr<IQ> > iqs_;
+ };
}
diff --git a/Swiften/Queries/GenericRequest.h b/Swiften/Queries/GenericRequest.h
index d6cca1c..ad3ec19 100644
--- a/Swiften/Queries/GenericRequest.h
+++ b/Swiften/Queries/GenericRequest.h
@@ -11,69 +11,69 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- /**
- * GenericRequest is used for managing the sending of, and handling of replies to, iq stanzas that do not have their own Request types.
- *
- * To create an iq stanza, call a constructor with the type of the iq that needs to be sent (either Set or Get), addressing information (clients should use the constructor that doesn't specify a sender), the payload that should be sent in the iq, and the IQRouter for the connection, obtained through the Client or CoreClient object.
- *
- * Having created a GenericRequest, connect to the onResponse signal to be told when a response (either a result or an error) has been received by Swiften.
- *
- * To send the iq, then call send() - onResponse will be called when a reply is received.
- */
- template<typename PAYLOAD_TYPE>
- class SWIFTEN_API GenericRequest : public Request {
- public:
- typedef boost::shared_ptr<GenericRequest<PAYLOAD_TYPE> > ref;
+ /**
+ * GenericRequest is used for managing the sending of, and handling of replies to, iq stanzas that do not have their own Request types.
+ *
+ * To create an iq stanza, call a constructor with the type of the iq that needs to be sent (either Set or Get), addressing information (clients should use the constructor that doesn't specify a sender), the payload that should be sent in the iq, and the IQRouter for the connection, obtained through the Client or CoreClient object.
+ *
+ * Having created a GenericRequest, connect to the onResponse signal to be told when a response (either a result or an error) has been received by Swiften.
+ *
+ * To send the iq, then call send() - onResponse will be called when a reply is received.
+ */
+ template<typename PAYLOAD_TYPE>
+ class SWIFTEN_API GenericRequest : public Request {
+ public:
+ typedef boost::shared_ptr<GenericRequest<PAYLOAD_TYPE> > ref;
- public:
- /**
- * Create a request suitable for client use.
- * @param type Iq type - Get or Set.
- * @param receiver JID to send request to.
- * @param payload Payload to send in stanza.
- * @param router IQRouter instance for current connection.
- */
- GenericRequest(
- IQ::Type type,
- const JID& receiver,
- boost::shared_ptr<Payload> payload,
- IQRouter* router) :
- Request(type, receiver, payload, router) {
- }
+ public:
+ /**
+ * Create a request suitable for client use.
+ * @param type Iq type - Get or Set.
+ * @param receiver JID to send request to.
+ * @param payload Payload to send in stanza.
+ * @param router IQRouter instance for current connection.
+ */
+ GenericRequest(
+ IQ::Type type,
+ const JID& receiver,
+ boost::shared_ptr<Payload> payload,
+ IQRouter* router) :
+ Request(type, receiver, payload, router) {
+ }
- /**
- * Create a request suitable for component or server use. As a client, use the other constructor instead.
- * @param type Iq type - Get or Set.
- * @param sender JID to use in "from" of stanza.
- * @param receiver JID to send request to.
- * @param payload Payload to send in stanza.
- * @param router IQRouter instance for current connection.
- */
- GenericRequest(
- IQ::Type type,
- const JID& sender,
- const JID& receiver,
- boost::shared_ptr<Payload> payload,
- IQRouter* router) :
- Request(type, sender, receiver, payload, router) {
- }
+ /**
+ * Create a request suitable for component or server use. As a client, use the other constructor instead.
+ * @param type Iq type - Get or Set.
+ * @param sender JID to use in "from" of stanza.
+ * @param receiver JID to send request to.
+ * @param payload Payload to send in stanza.
+ * @param router IQRouter instance for current connection.
+ */
+ GenericRequest(
+ IQ::Type type,
+ const JID& sender,
+ const JID& receiver,
+ boost::shared_ptr<Payload> payload,
+ IQRouter* router) :
+ Request(type, sender, receiver, payload, router) {
+ }
- /**
- * Internal method, do not use.
- */
- virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- onResponse(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(payload), error);
- }
+ /**
+ * Internal method, do not use.
+ */
+ virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(payload), error);
+ }
- public:
- boost::shared_ptr<PAYLOAD_TYPE> getPayloadGeneric() const {
- return boost::dynamic_pointer_cast<PAYLOAD_TYPE>(getPayload());
- }
+ public:
+ boost::shared_ptr<PAYLOAD_TYPE> getPayloadGeneric() const {
+ return boost::dynamic_pointer_cast<PAYLOAD_TYPE>(getPayload());
+ }
- public:
- /**
- * Signal emitted when a reply to the iq has been received. Contains a payload if one was present, and an error if one was present.
- */
- boost::signal<void (boost::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
- };
+ public:
+ /**
+ * Signal emitted when a reply to the iq has been received. Contains a payload if one was present, and an error if one was present.
+ */
+ boost::signal<void (boost::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/GetResponder.h b/Swiften/Queries/GetResponder.h
index df08f30..cda23d6 100644
--- a/Swiften/Queries/GetResponder.h
+++ b/Swiften/Queries/GetResponder.h
@@ -10,12 +10,12 @@
#include <Swiften/Queries/Responder.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API GetResponder : public Responder<T> {
- public:
- GetResponder(IQRouter* router) : Responder<T>(router) {}
+ template<typename T>
+ class SWIFTEN_API GetResponder : public Responder<T> {
+ public:
+ GetResponder(IQRouter* router) : Responder<T>(router) {}
- private:
- virtual bool handleSetRequest(const JID&, const JID&, const std::string&, boost::shared_ptr<T>) { return false; }
- };
+ private:
+ virtual bool handleSetRequest(const JID&, const JID&, const std::string&, boost::shared_ptr<T>) { return false; }
+ };
}
diff --git a/Swiften/Queries/IQChannel.h b/Swiften/Queries/IQChannel.h
index 25f499e..d762847 100644
--- a/Swiften/Queries/IQChannel.h
+++ b/Swiften/Queries/IQChannel.h
@@ -15,15 +15,15 @@
#include <Swiften/Elements/IQ.h>
namespace Swift {
- class SWIFTEN_API IQChannel {
- public:
- virtual ~IQChannel();
+ class SWIFTEN_API IQChannel {
+ public:
+ virtual ~IQChannel();
- virtual void sendIQ(boost::shared_ptr<IQ>) = 0;
- virtual std::string getNewIQID() = 0;
-
- virtual bool isAvailable() const = 0;
+ virtual void sendIQ(boost::shared_ptr<IQ>) = 0;
+ virtual std::string getNewIQID() = 0;
- boost::signal<void (boost::shared_ptr<IQ>)> onIQReceived;
- };
+ virtual bool isAvailable() const = 0;
+
+ boost::signal<void (boost::shared_ptr<IQ>)> onIQReceived;
+ };
}
diff --git a/Swiften/Queries/IQHandler.h b/Swiften/Queries/IQHandler.h
index b45e1e6..3581b85 100644
--- a/Swiften/Queries/IQHandler.h
+++ b/Swiften/Queries/IQHandler.h
@@ -12,12 +12,12 @@
#include <Swiften/Elements/IQ.h>
namespace Swift {
- class IQRouter;
+ class IQRouter;
- class SWIFTEN_API IQHandler {
- public:
- virtual ~IQHandler();
+ class SWIFTEN_API IQHandler {
+ public:
+ virtual ~IQHandler();
- virtual bool handleIQ(boost::shared_ptr<IQ>) = 0;
- };
+ virtual bool handleIQ(boost::shared_ptr<IQ>) = 0;
+ };
}
diff --git a/Swiften/Queries/IQRouter.cpp b/Swiften/Queries/IQRouter.cpp
index 25ae3ac..b32cdf1 100644
--- a/Swiften/Queries/IQRouter.cpp
+++ b/Swiften/Queries/IQRouter.cpp
@@ -19,76 +19,76 @@ namespace Swift {
static void noop(IQHandler*) {}
IQRouter::IQRouter(IQChannel* channel) : channel_(channel), queueRemoves_(false) {
- channel->onIQReceived.connect(boost::bind(&IQRouter::handleIQ, this, _1));
+ channel->onIQReceived.connect(boost::bind(&IQRouter::handleIQ, this, _1));
}
IQRouter::~IQRouter() {
- channel_->onIQReceived.disconnect(boost::bind(&IQRouter::handleIQ, this, _1));
+ channel_->onIQReceived.disconnect(boost::bind(&IQRouter::handleIQ, this, _1));
}
bool IQRouter::isAvailable() {
- return channel_->isAvailable();
+ return channel_->isAvailable();
}
void IQRouter::handleIQ(boost::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<boost::shared_ptr<IQHandler> >::const_reverse_iterator i = handlers_.rbegin();
- std::vector<boost::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;
+ queueRemoves_ = true;
+
+ bool handled = false;
+ // Go through the handlers in reverse order, to give precedence to the last added handler
+ std::vector<boost::shared_ptr<IQHandler> >::const_reverse_iterator i = handlers_.rbegin();
+ std::vector<boost::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(boost::shared_ptr<IQHandler> handler, queuedRemoves_) {
- erase(handlers_, handler);
- }
- queuedRemoves_.clear();
+ foreach(boost::shared_ptr<IQHandler> handler, queuedRemoves_) {
+ erase(handlers_, handler);
+ }
+ queuedRemoves_.clear();
}
void IQRouter::addHandler(IQHandler* handler) {
- addHandler(boost::shared_ptr<IQHandler>(handler, noop));
+ addHandler(boost::shared_ptr<IQHandler>(handler, noop));
}
void IQRouter::removeHandler(IQHandler* handler) {
- removeHandler(boost::shared_ptr<IQHandler>(handler, noop));
+ removeHandler(boost::shared_ptr<IQHandler>(handler, noop));
}
void IQRouter::addHandler(boost::shared_ptr<IQHandler> handler) {
- handlers_.push_back(handler);
+ handlers_.push_back(handler);
}
void IQRouter::removeHandler(boost::shared_ptr<IQHandler> handler) {
- if (queueRemoves_) {
- queuedRemoves_.push_back(handler);
- }
- else {
- erase(handlers_, handler);
- }
+ if (queueRemoves_) {
+ queuedRemoves_.push_back(handler);
+ }
+ else {
+ erase(handlers_, handler);
+ }
}
void IQRouter::sendIQ(boost::shared_ptr<IQ> iq) {
- if (from_.isValid() && !iq->getFrom().isValid()) {
- iq->setFrom(from_);
- }
- channel_->sendIQ(iq);
+ if (from_.isValid() && !iq->getFrom().isValid()) {
+ iq->setFrom(from_);
+ }
+ channel_->sendIQ(iq);
}
std::string IQRouter::getNewIQID() {
- return channel_->getNewIQID();
+ return channel_->getNewIQID();
}
}
diff --git a/Swiften/Queries/IQRouter.h b/Swiften/Queries/IQRouter.h
index 2b83526..376fb08 100644
--- a/Swiften/Queries/IQRouter.h
+++ b/Swiften/Queries/IQRouter.h
@@ -15,76 +15,76 @@
#include <Swiften/Elements/IQ.h>
namespace Swift {
- class IQChannel;
- class IQHandler;
+ class IQChannel;
+ class IQHandler;
- class SWIFTEN_API IQRouter {
- public:
- IQRouter(IQChannel* channel);
- ~IQRouter();
+ class SWIFTEN_API IQRouter {
+ public:
+ IQRouter(IQChannel* channel);
+ ~IQRouter();
- /**
- * Sets the JID of this IQ router.
- *
- * This JID is used by requests to check whether incoming
- * results are addressed correctly.
- */
- void setJID(const JID& jid) {
- jid_ = jid;
- }
+ /**
+ * Sets the JID of this IQ router.
+ *
+ * This JID is used by requests to check whether incoming
+ * results are addressed correctly.
+ */
+ void setJID(const JID& jid) {
+ jid_ = jid;
+ }
- const JID& getJID() const {
- return jid_;
- }
+ const JID& getJID() const {
+ return jid_;
+ }
- /**
- * Sets the 'from' JID for all outgoing IQ stanzas.
- *
- * By default, IQRouter does not add a from to IQ stanzas, since
- * this is automatically added by the server. This overrides this
- * default behavior, which is necessary for e.g. components.
- */
- void setFrom(const JID& from) {
- from_ = from;
- }
+ /**
+ * Sets the 'from' JID for all outgoing IQ stanzas.
+ *
+ * By default, IQRouter does not add a from to IQ stanzas, since
+ * this is automatically added by the server. This overrides this
+ * default behavior, which is necessary for e.g. components.
+ */
+ void setFrom(const JID& from) {
+ from_ = from;
+ }
- void addHandler(IQHandler* handler);
- void removeHandler(IQHandler* handler);
- void addHandler(boost::shared_ptr<IQHandler> handler);
- void removeHandler(boost::shared_ptr<IQHandler> handler);
+ void addHandler(IQHandler* handler);
+ void removeHandler(IQHandler* handler);
+ void addHandler(boost::shared_ptr<IQHandler> handler);
+ void removeHandler(boost::shared_ptr<IQHandler> handler);
- /**
- * Sends an IQ stanza.
- *
- * If a JID was specified using setFrom, the JID will
- * be set as the 'from' address on iq before sending
- * it.
- */
- void sendIQ(boost::shared_ptr<IQ> iq);
- std::string getNewIQID();
-
- bool isAvailable();
+ /**
+ * Sends an IQ stanza.
+ *
+ * If a JID was specified using setFrom, the JID will
+ * be set as the 'from' address on iq before sending
+ * it.
+ */
+ void sendIQ(boost::shared_ptr<IQ> iq);
+ std::string getNewIQID();
- /**
- * Checks whether the given jid is the account JID (i.e. it is either
- * the bare JID, or it is the empty JID).
- * Can be used to check whether a stanza is sent by the server on behalf
- * of the user's account.
- */
- bool isAccountJID(const JID& jid) {
- return jid.isValid() ? jid_.toBare().equals(jid, JID::WithResource) : true;
- }
+ bool isAvailable();
- private:
- void handleIQ(boost::shared_ptr<IQ> iq);
- void processPendingRemoves();
+ /**
+ * Checks whether the given jid is the account JID (i.e. it is either
+ * the bare JID, or it is the empty JID).
+ * Can be used to check whether a stanza is sent by the server on behalf
+ * of the user's account.
+ */
+ bool isAccountJID(const JID& jid) {
+ return jid.isValid() ? jid_.toBare().equals(jid, JID::WithResource) : true;
+ }
- private:
- IQChannel* channel_;
- JID jid_;
- JID from_;
- std::vector< boost::shared_ptr<IQHandler> > handlers_;
- std::vector< boost::shared_ptr<IQHandler> > queuedRemoves_;
- bool queueRemoves_;
- };
+ private:
+ void handleIQ(boost::shared_ptr<IQ> iq);
+ void processPendingRemoves();
+
+ private:
+ IQChannel* channel_;
+ JID jid_;
+ JID from_;
+ std::vector< boost::shared_ptr<IQHandler> > handlers_;
+ std::vector< boost::shared_ptr<IQHandler> > queuedRemoves_;
+ bool queueRemoves_;
+ };
}
diff --git a/Swiften/Queries/PubSubRequest.h b/Swiften/Queries/PubSubRequest.h
index c8a1a69..7218f83 100644
--- a/Swiften/Queries/PubSubRequest.h
+++ b/Swiften/Queries/PubSubRequest.h
@@ -33,59 +33,59 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- namespace Detail {
- template<typename T>
- struct PubSubPayloadTraits;
+ namespace Detail {
+ template<typename T>
+ struct PubSubPayloadTraits;
#define SWIFTEN_PUBSUB_DECLARE_PAYLOAD_TRAITS(PAYLOAD, CONTAINER, RESPONSE) \
- template<> struct PubSubPayloadTraits< PAYLOAD > { \
- typedef CONTAINER ContainerType; \
- typedef RESPONSE ResponseType; \
- };
+ template<> struct PubSubPayloadTraits< PAYLOAD > { \
+ typedef CONTAINER ContainerType; \
+ typedef RESPONSE ResponseType; \
+ };
- SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
- SWIFTEN_PUBSUB_DECLARE_PAYLOAD_TRAITS)
- }
+ SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
+ SWIFTEN_PUBSUB_DECLARE_PAYLOAD_TRAITS)
+ }
- template<typename T>
- class SWIFTEN_API PubSubRequest : public Request {
- typedef typename Detail::PubSubPayloadTraits<T>::ContainerType ContainerType;
- typedef typename Detail::PubSubPayloadTraits<T>::ResponseType ResponseType;
+ template<typename T>
+ class SWIFTEN_API PubSubRequest : public Request {
+ typedef typename Detail::PubSubPayloadTraits<T>::ContainerType ContainerType;
+ typedef typename Detail::PubSubPayloadTraits<T>::ResponseType ResponseType;
- public:
- PubSubRequest(
- IQ::Type type,
- const JID& receiver,
- boost::shared_ptr<T> payload,
- IQRouter* router) :
- Request(type, receiver, router) {
- boost::shared_ptr<ContainerType> wrapper = boost::make_shared<ContainerType>();
- wrapper->setPayload(payload);
- setPayload(wrapper);
- }
+ public:
+ PubSubRequest(
+ IQ::Type type,
+ const JID& receiver,
+ boost::shared_ptr<T> payload,
+ IQRouter* router) :
+ Request(type, receiver, router) {
+ boost::shared_ptr<ContainerType> wrapper = boost::make_shared<ContainerType>();
+ wrapper->setPayload(payload);
+ setPayload(wrapper);
+ }
- PubSubRequest(
- IQ::Type type,
- const JID& sender,
- const JID& receiver,
- boost::shared_ptr<T> payload,
- IQRouter* router) :
- Request(type, sender, receiver, router) {
- boost::shared_ptr<ContainerType> wrapper = boost::make_shared<ContainerType>();
- wrapper->setPayload(payload);
- setPayload(wrapper);
- }
+ PubSubRequest(
+ IQ::Type type,
+ const JID& sender,
+ const JID& receiver,
+ boost::shared_ptr<T> payload,
+ IQRouter* router) :
+ Request(type, sender, receiver, router) {
+ boost::shared_ptr<ContainerType> wrapper = boost::make_shared<ContainerType>();
+ wrapper->setPayload(payload);
+ setPayload(wrapper);
+ }
- virtual void handleResponse(
- boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- boost::shared_ptr<ResponseType> result;
- if (boost::shared_ptr<ContainerType> container = boost::dynamic_pointer_cast<ContainerType>(payload)) {
- result = boost::dynamic_pointer_cast<ResponseType>(container->getPayload());
- }
- onResponse(result, error);
- }
+ virtual void handleResponse(
+ boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ boost::shared_ptr<ResponseType> result;
+ if (boost::shared_ptr<ContainerType> container = boost::dynamic_pointer_cast<ContainerType>(payload)) {
+ result = boost::dynamic_pointer_cast<ResponseType>(container->getPayload());
+ }
+ onResponse(result, error);
+ }
- public:
- boost::signal<void (boost::shared_ptr<ResponseType>, ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signal<void (boost::shared_ptr<ResponseType>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/RawRequest.h b/Swiften/Queries/RawRequest.h
index b267f58..c4ab85c 100644
--- a/Swiften/Queries/RawRequest.h
+++ b/Swiften/Queries/RawRequest.h
@@ -20,33 +20,33 @@
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
namespace Swift {
- class SWIFTEN_API RawRequest : public Request {
- public:
- typedef boost::shared_ptr<RawRequest> ref;
-
- static ref create(IQ::Type type, const JID& recipient, const std::string& data, IQRouter* router) {
- return ref(new RawRequest(type, recipient, data, router));
- }
-
- boost::signal<void (const std::string&)> onResponse;
-
- private:
- RawRequest(IQ::Type type, const JID& receiver, const std::string& data, IQRouter* router) : Request(type, receiver, boost::make_shared<RawXMLPayload>(data), router) {
- }
-
- virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- if (error) {
- onResponse(ErrorSerializer(&serializers).serializePayload(error));
- }
- else {
- assert(payload);
- PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
- assert(serializer);
- onResponse(serializer->serialize(payload));
- }
- }
-
- private:
- FullPayloadSerializerCollection serializers;
- };
+ class SWIFTEN_API RawRequest : public Request {
+ public:
+ typedef boost::shared_ptr<RawRequest> ref;
+
+ static ref create(IQ::Type type, const JID& recipient, const std::string& data, IQRouter* router) {
+ return ref(new RawRequest(type, recipient, data, router));
+ }
+
+ boost::signal<void (const std::string&)> onResponse;
+
+ private:
+ RawRequest(IQ::Type type, const JID& receiver, const std::string& data, IQRouter* router) : Request(type, receiver, boost::make_shared<RawXMLPayload>(data), router) {
+ }
+
+ virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ if (error) {
+ onResponse(ErrorSerializer(&serializers).serializePayload(error));
+ }
+ else {
+ assert(payload);
+ PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
+ assert(serializer);
+ onResponse(serializer->serialize(payload));
+ }
+ }
+
+ private:
+ FullPayloadSerializerCollection serializers;
+ };
}
diff --git a/Swiften/Queries/Request.cpp b/Swiften/Queries/Request.cpp
index 8d2c9c4..a8dff24 100644
--- a/Swiften/Queries/Request.cpp
+++ b/Swiften/Queries/Request.cpp
@@ -25,69 +25,69 @@ Request::Request(IQ::Type type, const JID& sender, const JID& receiver, IQRouter
}
std::string Request::send() {
- assert(payload_);
- assert(!sent_);
- sent_ = true;
+ assert(payload_);
+ assert(!sent_);
+ sent_ = true;
- boost::shared_ptr<IQ> iq(new IQ(type_));
- iq->setTo(receiver_);
- iq->setFrom(sender_);
- iq->addPayload(payload_);
- id_ = router_->getNewIQID();
- iq->setID(id_);
+ boost::shared_ptr<IQ> iq(new IQ(type_));
+ iq->setTo(receiver_);
+ iq->setFrom(sender_);
+ iq->addPayload(payload_);
+ id_ = router_->getNewIQID();
+ iq->setID(id_);
- try {
- router_->addHandler(shared_from_this());
- }
- catch (const std::exception&) {
- router_->addHandler(this);
- }
+ try {
+ router_->addHandler(shared_from_this());
+ }
+ catch (const std::exception&) {
+ router_->addHandler(this);
+ }
- router_->sendIQ(iq);
- return id_;
+ router_->sendIQ(iq);
+ return id_;
}
bool Request::handleIQ(boost::shared_ptr<IQ> iq) {
- bool handled = false;
- if (iq->getType() == IQ::Result || iq->getType() == IQ::Error) {
- if (sent_ && iq->getID() == id_) {
- if (isCorrectSender(iq->getFrom())) {
- if (iq->getType() == IQ::Result) {
- boost::shared_ptr<Payload> payload = iq->getPayloadOfSameType(payload_);
- if (!payload && boost::dynamic_pointer_cast<RawXMLPayload>(payload_) && !iq->getPayloads().empty()) {
- payload = iq->getPayloads().front();
- }
- handleResponse(payload, ErrorPayload::ref());
- }
- else {
- ErrorPayload::ref errorPayload = iq->getPayload<ErrorPayload>();
- if (errorPayload) {
- handleResponse(boost::shared_ptr<Payload>(), errorPayload);
- }
- else {
- handleResponse(boost::shared_ptr<Payload>(), ErrorPayload::ref(new ErrorPayload(ErrorPayload::UndefinedCondition)));
- }
- }
- router_->removeHandler(this);
- handled = true;
- }
- }
- }
- return handled;
+ bool handled = false;
+ if (iq->getType() == IQ::Result || iq->getType() == IQ::Error) {
+ if (sent_ && iq->getID() == id_) {
+ if (isCorrectSender(iq->getFrom())) {
+ if (iq->getType() == IQ::Result) {
+ boost::shared_ptr<Payload> payload = iq->getPayloadOfSameType(payload_);
+ if (!payload && boost::dynamic_pointer_cast<RawXMLPayload>(payload_) && !iq->getPayloads().empty()) {
+ payload = iq->getPayloads().front();
+ }
+ handleResponse(payload, ErrorPayload::ref());
+ }
+ else {
+ ErrorPayload::ref errorPayload = iq->getPayload<ErrorPayload>();
+ if (errorPayload) {
+ handleResponse(boost::shared_ptr<Payload>(), errorPayload);
+ }
+ else {
+ handleResponse(boost::shared_ptr<Payload>(), ErrorPayload::ref(new ErrorPayload(ErrorPayload::UndefinedCondition)));
+ }
+ }
+ router_->removeHandler(this);
+ handled = true;
+ }
+ }
+ }
+ return handled;
}
bool Request::isCorrectSender(const JID& jid) {
- if (router_->isAccountJID(receiver_)) {
- if (jid.isValid() && jid.equals(router_->getJID(), JID::WithResource)) {
- // This unspecified behavior seems to happen in ejabberd versions (e.g. 2.0.5)
- SWIFT_LOG(warning) << "Server responded to an account request with a full JID, which is not allowed. Handling it anyway.";
- return true;
- }
- return router_->isAccountJID(jid);
- }
- else {
- return jid.equals(receiver_, JID::WithResource);
- }
+ if (router_->isAccountJID(receiver_)) {
+ if (jid.isValid() && jid.equals(router_->getJID(), JID::WithResource)) {
+ // This unspecified behavior seems to happen in ejabberd versions (e.g. 2.0.5)
+ SWIFT_LOG(warning) << "Server responded to an account request with a full JID, which is not allowed. Handling it anyway.";
+ return true;
+ }
+ return router_->isAccountJID(jid);
+ }
+ else {
+ return jid.equals(receiver_, JID::WithResource);
+ }
}
diff --git a/Swiften/Queries/Request.h b/Swiften/Queries/Request.h
index 71bbef2..7ad0dd6 100644
--- a/Swiften/Queries/Request.h
+++ b/Swiften/Queries/Request.h
@@ -20,88 +20,88 @@
#include <Swiften/Queries/IQHandler.h>
namespace Swift {
- /**
- * An IQ get/set request query.
- */
- class SWIFTEN_API Request : public IQHandler, public boost::enable_shared_from_this<Request> {
- public:
- std::string send();
-
- const JID& getReceiver() const {
- return receiver_;
- }
-
- /**
- * Returns the ID of this request.
- * This will only be set after send() is called.
- */
- const std::string& getID() const {
- return id_;
- }
-
-
- protected:
- /**
- * Constructs a request of a certain type to a specific receiver, and attaches the given
- * payload.
- */
- Request(
- IQ::Type type,
- const JID& receiver,
- boost::shared_ptr<Payload> payload,
- IQRouter* router);
-
- /**
- * Constructs a request of a certain type to a specific receiver from a specific sender, and attaches the given
- * payload.
- */
- Request(
- IQ::Type type,
- const JID& sender,
- const JID& receiver,
- boost::shared_ptr<Payload> payload,
- IQRouter* router);
-
-
- /**
- * Constructs a request of a certain type to a specific receiver.
- */
- Request(
- IQ::Type type,
- const JID& receiver,
- IQRouter* router);
-
- /**
- * Constructs a request of a certain type to a specific receiver from a specific sender.
- */
- Request(
- IQ::Type type,
- const JID& sender,
- const JID& receiver,
- IQRouter* router);
-
-
- virtual void setPayload(boost::shared_ptr<Payload> payload) {
- payload_ = payload;
- }
-
- boost::shared_ptr<Payload> getPayload() const {
- return payload_;
- }
-
- virtual void handleResponse(boost::shared_ptr<Payload>, boost::shared_ptr<ErrorPayload>) = 0;
-
- private:
- bool handleIQ(boost::shared_ptr<IQ>);
- bool isCorrectSender(const JID& jid);
-
- private:
- IQRouter* router_;
- IQ::Type type_;
- JID sender_;
- JID receiver_;
- boost::shared_ptr<Payload> payload_;
- std::string id_;
- bool sent_;
- };
+ /**
+ * An IQ get/set request query.
+ */
+ class SWIFTEN_API Request : public IQHandler, public boost::enable_shared_from_this<Request> {
+ public:
+ std::string send();
+
+ const JID& getReceiver() const {
+ return receiver_;
+ }
+
+ /**
+ * Returns the ID of this request.
+ * This will only be set after send() is called.
+ */
+ const std::string& getID() const {
+ return id_;
+ }
+
+
+ protected:
+ /**
+ * Constructs a request of a certain type to a specific receiver, and attaches the given
+ * payload.
+ */
+ Request(
+ IQ::Type type,
+ const JID& receiver,
+ boost::shared_ptr<Payload> payload,
+ IQRouter* router);
+
+ /**
+ * Constructs a request of a certain type to a specific receiver from a specific sender, and attaches the given
+ * payload.
+ */
+ Request(
+ IQ::Type type,
+ const JID& sender,
+ const JID& receiver,
+ boost::shared_ptr<Payload> payload,
+ IQRouter* router);
+
+
+ /**
+ * Constructs a request of a certain type to a specific receiver.
+ */
+ Request(
+ IQ::Type type,
+ const JID& receiver,
+ IQRouter* router);
+
+ /**
+ * Constructs a request of a certain type to a specific receiver from a specific sender.
+ */
+ Request(
+ IQ::Type type,
+ const JID& sender,
+ const JID& receiver,
+ IQRouter* router);
+
+
+ virtual void setPayload(boost::shared_ptr<Payload> payload) {
+ payload_ = payload;
+ }
+
+ boost::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ virtual void handleResponse(boost::shared_ptr<Payload>, boost::shared_ptr<ErrorPayload>) = 0;
+
+ private:
+ bool handleIQ(boost::shared_ptr<IQ>);
+ bool isCorrectSender(const JID& jid);
+
+ private:
+ IQRouter* router_;
+ IQ::Type type_;
+ JID sender_;
+ JID receiver_;
+ boost::shared_ptr<Payload> payload_;
+ std::string id_;
+ bool sent_;
+ };
}
diff --git a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h b/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
index faea191..ad4caf7 100644
--- a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
+++ b/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
@@ -11,16 +11,16 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetInBandRegistrationFormRequest : public GenericRequest<InBandRegistrationPayload> {
- public:
- typedef boost::shared_ptr<GetInBandRegistrationFormRequest> ref;
+ class SWIFTEN_API GetInBandRegistrationFormRequest : public GenericRequest<InBandRegistrationPayload> {
+ public:
+ typedef boost::shared_ptr<GetInBandRegistrationFormRequest> ref;
- static ref create(const JID& to, IQRouter* router) {
- return ref(new GetInBandRegistrationFormRequest(to, router));
- }
+ static ref create(const JID& to, IQRouter* router) {
+ return ref(new GetInBandRegistrationFormRequest(to, router));
+ }
- private:
- GetInBandRegistrationFormRequest(const JID& to, IQRouter* router) : GenericRequest<InBandRegistrationPayload>(IQ::Get, to, InBandRegistrationPayload::ref(new InBandRegistrationPayload()), router) {
- }
- };
+ private:
+ GetInBandRegistrationFormRequest(const JID& to, IQRouter* router) : GenericRequest<InBandRegistrationPayload>(IQ::Get, to, InBandRegistrationPayload::ref(new InBandRegistrationPayload()), router) {
+ }
+ };
}
diff --git a/Swiften/Queries/Requests/GetPrivateStorageRequest.h b/Swiften/Queries/Requests/GetPrivateStorageRequest.h
index a2e7bde..eecd4d4 100644
--- a/Swiften/Queries/Requests/GetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/GetPrivateStorageRequest.h
@@ -16,30 +16,30 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- template<typename PAYLOAD_TYPE>
- class SWIFTEN_API GetPrivateStorageRequest : public Request {
- public:
- typedef boost::shared_ptr<GetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
-
- static ref create(IQRouter* router) {
- return ref(new GetPrivateStorageRequest(router));
- }
-
- private:
- GetPrivateStorageRequest(IQRouter* router) : Request(IQ::Get, JID(), boost::make_shared<PrivateStorage>(boost::shared_ptr<Payload>(new PAYLOAD_TYPE())), router) {
- }
-
- virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- boost::shared_ptr<PrivateStorage> storage = boost::dynamic_pointer_cast<PrivateStorage>(payload);
- if (storage) {
- onResponse(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(storage->getPayload()), error);
- }
- else {
- onResponse(boost::shared_ptr<PAYLOAD_TYPE>(), error);
- }
- }
-
- public:
- boost::signal<void (boost::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
- };
+ template<typename PAYLOAD_TYPE>
+ class SWIFTEN_API GetPrivateStorageRequest : public Request {
+ public:
+ typedef boost::shared_ptr<GetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
+
+ static ref create(IQRouter* router) {
+ return ref(new GetPrivateStorageRequest(router));
+ }
+
+ private:
+ GetPrivateStorageRequest(IQRouter* router) : Request(IQ::Get, JID(), boost::make_shared<PrivateStorage>(boost::shared_ptr<Payload>(new PAYLOAD_TYPE())), router) {
+ }
+
+ virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ boost::shared_ptr<PrivateStorage> storage = boost::dynamic_pointer_cast<PrivateStorage>(payload);
+ if (storage) {
+ onResponse(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(storage->getPayload()), error);
+ }
+ else {
+ onResponse(boost::shared_ptr<PAYLOAD_TYPE>(), error);
+ }
+ }
+
+ public:
+ boost::signal<void (boost::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
index 34e2cfb..a474be5 100644
--- a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
+++ b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
@@ -13,20 +13,20 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetSecurityLabelsCatalogRequest : public GenericRequest<SecurityLabelsCatalog> {
- public:
- typedef boost::shared_ptr<GetSecurityLabelsCatalogRequest> ref;
+ class SWIFTEN_API GetSecurityLabelsCatalogRequest : public GenericRequest<SecurityLabelsCatalog> {
+ public:
+ typedef boost::shared_ptr<GetSecurityLabelsCatalogRequest> ref;
- static ref create(const JID& recipient, IQRouter* router) {
- return ref(new GetSecurityLabelsCatalogRequest(recipient, router));
- }
+ static ref create(const JID& recipient, IQRouter* router) {
+ return ref(new GetSecurityLabelsCatalogRequest(recipient, router));
+ }
- private:
- GetSecurityLabelsCatalogRequest(
- const JID& recipient,
- IQRouter* router) :
- GenericRequest<SecurityLabelsCatalog>(
- IQ::Get, JID(), boost::make_shared<SecurityLabelsCatalog>(recipient), router) {
- }
- };
+ private:
+ GetSecurityLabelsCatalogRequest(
+ const JID& recipient,
+ IQRouter* router) :
+ GenericRequest<SecurityLabelsCatalog>(
+ IQ::Get, JID(), boost::make_shared<SecurityLabelsCatalog>(recipient), router) {
+ }
+ };
}
diff --git a/Swiften/Queries/Requests/GetSoftwareVersionRequest.h b/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
index b8e568a..9533651 100644
--- a/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
+++ b/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
@@ -13,20 +13,20 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetSoftwareVersionRequest : public GenericRequest<SoftwareVersion> {
- public:
- typedef boost::shared_ptr<GetSoftwareVersionRequest> ref;
+ class SWIFTEN_API GetSoftwareVersionRequest : public GenericRequest<SoftwareVersion> {
+ public:
+ typedef boost::shared_ptr<GetSoftwareVersionRequest> ref;
- static ref create(const JID& recipient, IQRouter* router) {
- return ref(new GetSoftwareVersionRequest(recipient, router));
- }
+ static ref create(const JID& recipient, IQRouter* router) {
+ return ref(new GetSoftwareVersionRequest(recipient, router));
+ }
- private:
- GetSoftwareVersionRequest(
- const JID& recipient,
- IQRouter* router) :
- GenericRequest<SoftwareVersion>(
- IQ::Get, recipient, boost::make_shared<SoftwareVersion>(), router) {
- }
- };
+ private:
+ GetSoftwareVersionRequest(
+ const JID& recipient,
+ IQRouter* router) :
+ GenericRequest<SoftwareVersion>(
+ IQ::Get, recipient, boost::make_shared<SoftwareVersion>(), router) {
+ }
+ };
}
diff --git a/Swiften/Queries/Requests/SetPrivateStorageRequest.h b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
index 46620c3..703b749 100644
--- a/Swiften/Queries/Requests/SetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
@@ -16,24 +16,24 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- template<typename PAYLOAD_TYPE>
- class SWIFTEN_API SetPrivateStorageRequest : public Request {
- public:
- typedef boost::shared_ptr<SetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
-
- static ref create(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) {
- return ref(new SetPrivateStorageRequest<PAYLOAD_TYPE>(payload, router));
- }
-
- private:
- SetPrivateStorageRequest(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) : Request(IQ::Set, JID(), boost::make_shared<PrivateStorage>(payload), router) {
- }
-
- virtual void handleResponse(boost::shared_ptr<Payload>, ErrorPayload::ref error) {
- onResponse(error);
- }
-
- public:
- boost::signal<void (ErrorPayload::ref)> onResponse;
- };
+ template<typename PAYLOAD_TYPE>
+ class SWIFTEN_API SetPrivateStorageRequest : public Request {
+ public:
+ typedef boost::shared_ptr<SetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
+
+ static ref create(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) {
+ return ref(new SetPrivateStorageRequest<PAYLOAD_TYPE>(payload, router));
+ }
+
+ private:
+ SetPrivateStorageRequest(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) : Request(IQ::Set, JID(), boost::make_shared<PrivateStorage>(payload), router) {
+ }
+
+ virtual void handleResponse(boost::shared_ptr<Payload>, ErrorPayload::ref error) {
+ onResponse(error);
+ }
+
+ public:
+ boost::signal<void (ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h b/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
index 220e2ba..94a497b 100644
--- a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
+++ b/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
@@ -14,23 +14,23 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- class SWIFTEN_API SetInBandRegistrationRequest : public Request {
- public:
- typedef boost::shared_ptr<SetInBandRegistrationRequest> ref;
+ class SWIFTEN_API SetInBandRegistrationRequest : public Request {
+ public:
+ typedef boost::shared_ptr<SetInBandRegistrationRequest> ref;
- static ref create(const JID& to, InBandRegistrationPayload::ref payload, IQRouter* router) {
- return ref(new SetInBandRegistrationRequest(to, payload, router));
- }
+ static ref create(const JID& to, InBandRegistrationPayload::ref payload, IQRouter* router) {
+ return ref(new SetInBandRegistrationRequest(to, payload, router));
+ }
- private:
- SetInBandRegistrationRequest(const JID& to, InBandRegistrationPayload::ref payload, IQRouter* router) : Request(IQ::Set, to, InBandRegistrationPayload::ref(payload), router) {
- }
+ private:
+ SetInBandRegistrationRequest(const JID& to, InBandRegistrationPayload::ref payload, IQRouter* router) : Request(IQ::Set, to, InBandRegistrationPayload::ref(payload), router) {
+ }
- virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- onResponse(payload, error);
- }
+ virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(payload, error);
+ }
- public:
- boost::signal<void (boost::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signal<void (boost::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
index 4e3be50..1efe523 100644
--- a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
+++ b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
@@ -18,93 +18,93 @@
using namespace Swift;
class GetPrivateStorageRequestTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(GetPrivateStorageRequestTest);
- CPPUNIT_TEST(testSend);
- CPPUNIT_TEST(testHandleResponse);
- CPPUNIT_TEST(testHandleResponse_Error);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- class MyPayload : public Payload {
- public:
- MyPayload(const std::string& text = "") : text(text) {}
- std::string text;
- };
-
- public:
- void setUp() {
- channel = new DummyIQChannel();
- router = new IQRouter(channel);
- }
-
- void tearDown() {
- delete router;
- delete channel;
- }
-
- void testSend() {
- GetPrivateStorageRequest<MyPayload>::ref request = GetPrivateStorageRequest<MyPayload>::create(router);
- request->send();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->iqs_.size()));
- CPPUNIT_ASSERT_EQUAL(JID(), channel->iqs_[0]->getTo());
- CPPUNIT_ASSERT_EQUAL(IQ::Get, channel->iqs_[0]->getType());
- boost::shared_ptr<PrivateStorage> storage = channel->iqs_[0]->getPayload<PrivateStorage>();
- CPPUNIT_ASSERT(storage);
- boost::shared_ptr<MyPayload> payload = boost::dynamic_pointer_cast<MyPayload>(storage->getPayload());
- CPPUNIT_ASSERT(payload);
- }
-
- void testHandleResponse() {
- GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router);
- testling->onResponse.connect(boost::bind(&GetPrivateStorageRequestTest::handleResponse, this, _1, _2));
- testling->send();
- channel->onIQReceived(createResponse("test-id", "foo"));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(responses.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("foo"), boost::dynamic_pointer_cast<MyPayload>(responses[0])->text);
- }
-
- void testHandleResponse_Error() {
- GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router);
- testling->onResponse.connect(boost::bind(&GetPrivateStorageRequestTest::handleResponse, this, _1, _2));
- testling->send();
- channel->onIQReceived(createError("test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(responses.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(errors.size()));
- }
-
- private:
- void handleResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
- if (e) {
- errors.push_back(*e);
- }
- else {
- responses.push_back(p);
- }
- }
-
- boost::shared_ptr<IQ> createResponse(const std::string& id, const std::string& text) {
- boost::shared_ptr<IQ> iq(new IQ(IQ::Result));
- boost::shared_ptr<PrivateStorage> storage(new PrivateStorage());
- storage->setPayload(boost::shared_ptr<Payload>(new MyPayload(text)));
- iq->addPayload(storage);
- iq->setID(id);
- return iq;
- }
-
- boost::shared_ptr<IQ> createError(const std::string& id) {
- boost::shared_ptr<IQ> iq(new IQ(IQ::Error));
- iq->setID(id);
- return iq;
- }
-
- private:
- IQRouter* router;
- DummyIQChannel* channel;
- std::vector< ErrorPayload > errors;
- std::vector< boost::shared_ptr<Payload> > responses;
+ CPPUNIT_TEST_SUITE(GetPrivateStorageRequestTest);
+ CPPUNIT_TEST(testSend);
+ CPPUNIT_TEST(testHandleResponse);
+ CPPUNIT_TEST(testHandleResponse_Error);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ class MyPayload : public Payload {
+ public:
+ MyPayload(const std::string& text = "") : text(text) {}
+ std::string text;
+ };
+
+ public:
+ void setUp() {
+ channel = new DummyIQChannel();
+ router = new IQRouter(channel);
+ }
+
+ void tearDown() {
+ delete router;
+ delete channel;
+ }
+
+ void testSend() {
+ GetPrivateStorageRequest<MyPayload>::ref request = GetPrivateStorageRequest<MyPayload>::create(router);
+ request->send();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->iqs_.size()));
+ CPPUNIT_ASSERT_EQUAL(JID(), channel->iqs_[0]->getTo());
+ CPPUNIT_ASSERT_EQUAL(IQ::Get, channel->iqs_[0]->getType());
+ boost::shared_ptr<PrivateStorage> storage = channel->iqs_[0]->getPayload<PrivateStorage>();
+ CPPUNIT_ASSERT(storage);
+ boost::shared_ptr<MyPayload> payload = boost::dynamic_pointer_cast<MyPayload>(storage->getPayload());
+ CPPUNIT_ASSERT(payload);
+ }
+
+ void testHandleResponse() {
+ GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router);
+ testling->onResponse.connect(boost::bind(&GetPrivateStorageRequestTest::handleResponse, this, _1, _2));
+ testling->send();
+ channel->onIQReceived(createResponse("test-id", "foo"));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(responses.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), boost::dynamic_pointer_cast<MyPayload>(responses[0])->text);
+ }
+
+ void testHandleResponse_Error() {
+ GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router);
+ testling->onResponse.connect(boost::bind(&GetPrivateStorageRequestTest::handleResponse, this, _1, _2));
+ testling->send();
+ channel->onIQReceived(createError("test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(responses.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(errors.size()));
+ }
+
+ private:
+ void handleResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ if (e) {
+ errors.push_back(*e);
+ }
+ else {
+ responses.push_back(p);
+ }
+ }
+
+ boost::shared_ptr<IQ> createResponse(const std::string& id, const std::string& text) {
+ boost::shared_ptr<IQ> iq(new IQ(IQ::Result));
+ boost::shared_ptr<PrivateStorage> storage(new PrivateStorage());
+ storage->setPayload(boost::shared_ptr<Payload>(new MyPayload(text)));
+ iq->addPayload(storage);
+ iq->setID(id);
+ return iq;
+ }
+
+ boost::shared_ptr<IQ> createError(const std::string& id) {
+ boost::shared_ptr<IQ> iq(new IQ(IQ::Error));
+ iq->setID(id);
+ return iq;
+ }
+
+ private:
+ IQRouter* router;
+ DummyIQChannel* channel;
+ std::vector< ErrorPayload > errors;
+ std::vector< boost::shared_ptr<Payload> > responses;
};
CPPUNIT_TEST_SUITE_REGISTRATION(GetPrivateStorageRequestTest);
diff --git a/Swiften/Queries/Responder.h b/Swiften/Queries/Responder.h
index 836207f..94195f8 100644
--- a/Swiften/Queries/Responder.h
+++ b/Swiften/Queries/Responder.h
@@ -12,125 +12,125 @@
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
- /**
- * A class for handling incoming IQ Get and Set requests of a specific payload type.
- *
- * Concrete subclasses of this class need to implement handleGetRequest() and handleSetRequest() to
- * implement the behavior of the responder.
- *
- * \tparam PAYLOAD_TYPE The type of payload this Responder handles. Only IQ requests containing this
- * payload type will be passed to handleGetRequest() and handleSetRequest()
- */
- template<typename PAYLOAD_TYPE>
- class SWIFTEN_API Responder : public IQHandler {
- public:
- Responder(IQRouter* router) : router_(router), isFinalResonder_(true) {
- }
-
- ~Responder() {
- }
-
- /**
- * Starts the responder.
- *
- * After the responder has started, it will start receiving and responding to requests.
- *
- * \see stop()
- */
- void start() {
- router_->addHandler(this);
- }
-
- /**
- * Stops the responder.
- *
- * When the responder is stopped, it will no longer receive incoming requests.
- *
- * \see start()
- */
- void stop() {
- router_->removeHandler(this);
- }
-
- protected:
- /**
- * Handle an incoming IQ-Get request containing a payload of class PAYLOAD_TYPE.
- *
- * This method is implemented in the concrete subclasses.
- */
- virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) = 0;
-
- /**
- * Handle an incoming IQ-Set request containing a payload of class PAYLOAD_TYPE.
- *
- * This method is implemented in the concrete subclasses.
- */
- virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) = 0;
-
- /**
- * Convenience function for sending an IQ response.
- */
- void sendResponse(const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) {
- router_->sendIQ(IQ::createResult(to, id, payload));
- }
-
- /**
- * Convenience function for sending an IQ response, with a specific from address.
- */
- void sendResponse(const JID& to, const JID& from, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) {
- router_->sendIQ(IQ::createResult(to, from, id, payload));
- }
-
- /**
- * Convenience function for responding with an error.
- */
- void sendError(const JID& to, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, Payload::ref payload = Payload::ref()) {
- router_->sendIQ(IQ::createError(to, id, condition, type, payload));
- }
-
- /**
- * Convenience function for responding with an error from a specific from address.
- */
- void sendError(const JID& to, const JID& from, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, Payload::ref payload = Payload::ref()) {
- router_->sendIQ(IQ::createError(to, from, id, condition, type, payload));
- }
-
- IQRouter* getIQRouter() const {
- return router_;
- }
-
- void setFinal(bool isFinal) {
- isFinalResonder_ = isFinal;
- }
-
- private:
- virtual bool handleIQ(boost::shared_ptr<IQ> iq) {
- if (iq->getType() == IQ::Set || iq->getType() == IQ::Get) {
- boost::shared_ptr<PAYLOAD_TYPE> payload(iq->getPayload<PAYLOAD_TYPE>());
- if (payload) {
- bool result;
- if (iq->getType() == IQ::Set) {
- result = handleSetRequest(iq->getFrom(), iq->getTo(), iq->getID(), payload);
- }
- else {
- result = handleGetRequest(iq->getFrom(), iq->getTo(), iq->getID(), payload);
- }
- if (!result) {
- if (isFinalResonder_) {
- router_->sendIQ(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::NotAllowed, ErrorPayload::Cancel));
- }
- else {
- return false;
- }
- }
- return true;
- }
- }
- return false;
- }
-
- private:
- IQRouter* router_;
- bool isFinalResonder_;
- };
+ /**
+ * A class for handling incoming IQ Get and Set requests of a specific payload type.
+ *
+ * Concrete subclasses of this class need to implement handleGetRequest() and handleSetRequest() to
+ * implement the behavior of the responder.
+ *
+ * \tparam PAYLOAD_TYPE The type of payload this Responder handles. Only IQ requests containing this
+ * payload type will be passed to handleGetRequest() and handleSetRequest()
+ */
+ template<typename PAYLOAD_TYPE>
+ class SWIFTEN_API Responder : public IQHandler {
+ public:
+ Responder(IQRouter* router) : router_(router), isFinalResonder_(true) {
+ }
+
+ ~Responder() {
+ }
+
+ /**
+ * Starts the responder.
+ *
+ * After the responder has started, it will start receiving and responding to requests.
+ *
+ * \see stop()
+ */
+ void start() {
+ router_->addHandler(this);
+ }
+
+ /**
+ * Stops the responder.
+ *
+ * When the responder is stopped, it will no longer receive incoming requests.
+ *
+ * \see start()
+ */
+ void stop() {
+ router_->removeHandler(this);
+ }
+
+ protected:
+ /**
+ * Handle an incoming IQ-Get request containing a payload of class PAYLOAD_TYPE.
+ *
+ * This method is implemented in the concrete subclasses.
+ */
+ virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) = 0;
+
+ /**
+ * Handle an incoming IQ-Set request containing a payload of class PAYLOAD_TYPE.
+ *
+ * This method is implemented in the concrete subclasses.
+ */
+ virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) = 0;
+
+ /**
+ * Convenience function for sending an IQ response.
+ */
+ void sendResponse(const JID& to, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) {
+ router_->sendIQ(IQ::createResult(to, id, payload));
+ }
+
+ /**
+ * Convenience function for sending an IQ response, with a specific from address.
+ */
+ void sendResponse(const JID& to, const JID& from, const std::string& id, boost::shared_ptr<PAYLOAD_TYPE> payload) {
+ router_->sendIQ(IQ::createResult(to, from, id, payload));
+ }
+
+ /**
+ * Convenience function for responding with an error.
+ */
+ void sendError(const JID& to, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, Payload::ref payload = Payload::ref()) {
+ router_->sendIQ(IQ::createError(to, id, condition, type, payload));
+ }
+
+ /**
+ * Convenience function for responding with an error from a specific from address.
+ */
+ void sendError(const JID& to, const JID& from, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, Payload::ref payload = Payload::ref()) {
+ router_->sendIQ(IQ::createError(to, from, id, condition, type, payload));
+ }
+
+ IQRouter* getIQRouter() const {
+ return router_;
+ }
+
+ void setFinal(bool isFinal) {
+ isFinalResonder_ = isFinal;
+ }
+
+ private:
+ virtual bool handleIQ(boost::shared_ptr<IQ> iq) {
+ if (iq->getType() == IQ::Set || iq->getType() == IQ::Get) {
+ boost::shared_ptr<PAYLOAD_TYPE> payload(iq->getPayload<PAYLOAD_TYPE>());
+ if (payload) {
+ bool result;
+ if (iq->getType() == IQ::Set) {
+ result = handleSetRequest(iq->getFrom(), iq->getTo(), iq->getID(), payload);
+ }
+ else {
+ result = handleGetRequest(iq->getFrom(), iq->getTo(), iq->getID(), payload);
+ }
+ if (!result) {
+ if (isFinalResonder_) {
+ router_->sendIQ(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::NotAllowed, ErrorPayload::Cancel));
+ }
+ else {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private:
+ IQRouter* router_;
+ bool isFinalResonder_;
+ };
}
diff --git a/Swiften/Queries/Responders/SoftwareVersionResponder.cpp b/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
index 491f639..df73dc6 100644
--- a/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
+++ b/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
@@ -16,14 +16,14 @@ SoftwareVersionResponder::SoftwareVersionResponder(IQRouter* router) : GetRespon
}
void SoftwareVersionResponder::setVersion(const std::string& client, const std::string& version, const std::string& os) {
- this->client = client;
- this->version = version;
- this->os = os;
+ this->client = client;
+ this->version = version;
+ this->os = os;
}
bool SoftwareVersionResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion>) {
- sendResponse(from, id, boost::make_shared<SoftwareVersion>(client, version, os));
- return true;
+ sendResponse(from, id, boost::make_shared<SoftwareVersion>(client, version, os));
+ return true;
}
}
diff --git a/Swiften/Queries/Responders/SoftwareVersionResponder.h b/Swiften/Queries/Responders/SoftwareVersionResponder.h
index 5684acb..e336341 100644
--- a/Swiften/Queries/Responders/SoftwareVersionResponder.h
+++ b/Swiften/Queries/Responders/SoftwareVersionResponder.h
@@ -11,20 +11,20 @@
#include <Swiften/Queries/GetResponder.h>
namespace Swift {
- class IQRouter;
+ class IQRouter;
- class SWIFTEN_API SoftwareVersionResponder : public GetResponder<SoftwareVersion> {
- public:
- SoftwareVersionResponder(IQRouter* router);
+ class SWIFTEN_API SoftwareVersionResponder : public GetResponder<SoftwareVersion> {
+ public:
+ SoftwareVersionResponder(IQRouter* router);
- void setVersion(const std::string& client, const std::string& version, const std::string& os = "");
+ void setVersion(const std::string& client, const std::string& version, const std::string& os = "");
- private:
- virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<SoftwareVersion> payload);
+ private:
+ virtual bool handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<SoftwareVersion> payload);
- private:
- std::string client;
- std::string version;
- std::string os;
- };
+ private:
+ std::string client;
+ std::string version;
+ std::string os;
+ };
}
diff --git a/Swiften/Queries/SetResponder.h b/Swiften/Queries/SetResponder.h
index 5e7d42d..44d5b66 100644
--- a/Swiften/Queries/SetResponder.h
+++ b/Swiften/Queries/SetResponder.h
@@ -10,12 +10,12 @@
#include <Swiften/Queries/Responder.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API SetResponder : public Responder<T> {
- public:
- SetResponder(IQRouter* router) : Responder<T>(router) {}
+ template<typename T>
+ class SWIFTEN_API SetResponder : public Responder<T> {
+ public:
+ SetResponder(IQRouter* router) : Responder<T>(router) {}
- private:
- virtual bool handleGetRequest(const JID&, const JID&, const std::string&, boost::shared_ptr<T>) { return false; }
- };
+ private:
+ virtual bool handleGetRequest(const JID&, const JID&, const std::string&, boost::shared_ptr<T>) { return false; }
+ };
}
diff --git a/Swiften/Queries/UnitTest/IQRouterTest.cpp b/Swiften/Queries/UnitTest/IQRouterTest.cpp
index 44315c4..d0d4911 100644
--- a/Swiften/Queries/UnitTest/IQRouterTest.cpp
+++ b/Swiften/Queries/UnitTest/IQRouterTest.cpp
@@ -18,161 +18,161 @@
using namespace Swift;
class IQRouterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IQRouterTest);
- CPPUNIT_TEST(testRemoveHandler);
- CPPUNIT_TEST(testRemoveHandler_AfterHandleIQ);
- CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerFirst);
- CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerLast);
- CPPUNIT_TEST(testHandleIQ_NoSuccesfulHandler);
- CPPUNIT_TEST(testHandleIQ_HandlerRemovedDuringHandle);
- CPPUNIT_TEST(testSendIQ_WithFrom);
- CPPUNIT_TEST(testSendIQ_WithoutFrom);
- CPPUNIT_TEST(testHandleIQ_WithFrom);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IQRouterTest);
+ CPPUNIT_TEST(testRemoveHandler);
+ CPPUNIT_TEST(testRemoveHandler_AfterHandleIQ);
+ CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerFirst);
+ CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerLast);
+ CPPUNIT_TEST(testHandleIQ_NoSuccesfulHandler);
+ CPPUNIT_TEST(testHandleIQ_HandlerRemovedDuringHandle);
+ CPPUNIT_TEST(testSendIQ_WithFrom);
+ CPPUNIT_TEST(testSendIQ_WithoutFrom);
+ CPPUNIT_TEST(testHandleIQ_WithFrom);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- channel_ = new DummyIQChannel();
- }
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ }
- void tearDown() {
- delete channel_;
- }
+ void tearDown() {
+ delete channel_;
+ }
- void testRemoveHandler() {
- IQRouter testling(channel_);
- DummyIQHandler handler1(true, &testling);
- DummyIQHandler handler2(true, &testling);
- testling.removeHandler(&handler1);
+ void testRemoveHandler() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler1(true, &testling);
+ DummyIQHandler handler2(true, &testling);
+ testling.removeHandler(&handler1);
- channel_->onIQReceived(boost::make_shared<IQ>());
+ channel_->onIQReceived(boost::make_shared<IQ>());
- CPPUNIT_ASSERT_EQUAL(0, handler1.called);
- CPPUNIT_ASSERT_EQUAL(1, handler2.called);
- }
+ CPPUNIT_ASSERT_EQUAL(0, handler1.called);
+ CPPUNIT_ASSERT_EQUAL(1, handler2.called);
+ }
- void testRemoveHandler_AfterHandleIQ() {
- IQRouter testling(channel_);
- DummyIQHandler handler2(true, &testling);
- DummyIQHandler handler1(true, &testling);
-
- channel_->onIQReceived(boost::make_shared<IQ>());
- testling.removeHandler(&handler1);
- channel_->onIQReceived(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(1, handler1.called);
- CPPUNIT_ASSERT_EQUAL(1, handler2.called);
- }
-
- void testHandleIQ_SuccesfulHandlerFirst() {
- IQRouter testling(channel_);
- DummyIQHandler handler2(false, &testling);
- DummyIQHandler handler1(true, &testling);
-
- channel_->onIQReceived(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(1, handler1.called);
- CPPUNIT_ASSERT_EQUAL(0, handler2.called);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_SuccesfulHandlerLast() {
- IQRouter testling(channel_);
- DummyIQHandler handler2(true, &testling);
- DummyIQHandler handler1(false, &testling);
-
- channel_->onIQReceived(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(1, handler1.called);
- CPPUNIT_ASSERT_EQUAL(1, handler2.called);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_NoSuccesfulHandler() {
- IQRouter testling(channel_);
- DummyIQHandler handler(false, &testling);
-
- channel_->onIQReceived(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- CPPUNIT_ASSERT(channel_->iqs_[0]->getPayload<ErrorPayload>());
- }
-
-
- void testHandleIQ_HandlerRemovedDuringHandle() {
- IQRouter testling(channel_);
- DummyIQHandler handler2(true, &testling);
- RemovingIQHandler handler1(&testling);
-
- channel_->onIQReceived(boost::make_shared<IQ>());
- channel_->onIQReceived(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(1, handler1.called);
- CPPUNIT_ASSERT_EQUAL(2, handler2.called);
- }
-
- void testSendIQ_WithFrom() {
- IQRouter testling(channel_);
- testling.setFrom(JID("foo@bar.com/baz"));
-
- testling.sendIQ(boost::make_shared<IQ>());
-
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
- }
-
- void testSendIQ_WithoutFrom() {
- IQRouter testling(channel_);
+ void testRemoveHandler_AfterHandleIQ() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler2(true, &testling);
+ DummyIQHandler handler1(true, &testling);
+
+ channel_->onIQReceived(boost::make_shared<IQ>());
+ testling.removeHandler(&handler1);
+ channel_->onIQReceived(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(1, handler1.called);
+ CPPUNIT_ASSERT_EQUAL(1, handler2.called);
+ }
+
+ void testHandleIQ_SuccesfulHandlerFirst() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler2(false, &testling);
+ DummyIQHandler handler1(true, &testling);
+
+ channel_->onIQReceived(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(1, handler1.called);
+ CPPUNIT_ASSERT_EQUAL(0, handler2.called);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_SuccesfulHandlerLast() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler2(true, &testling);
+ DummyIQHandler handler1(false, &testling);
+
+ channel_->onIQReceived(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(1, handler1.called);
+ CPPUNIT_ASSERT_EQUAL(1, handler2.called);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_NoSuccesfulHandler() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler(false, &testling);
+
+ channel_->onIQReceived(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ CPPUNIT_ASSERT(channel_->iqs_[0]->getPayload<ErrorPayload>());
+ }
+
+
+ void testHandleIQ_HandlerRemovedDuringHandle() {
+ IQRouter testling(channel_);
+ DummyIQHandler handler2(true, &testling);
+ RemovingIQHandler handler1(&testling);
+
+ channel_->onIQReceived(boost::make_shared<IQ>());
+ channel_->onIQReceived(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(1, handler1.called);
+ CPPUNIT_ASSERT_EQUAL(2, handler2.called);
+ }
+
+ void testSendIQ_WithFrom() {
+ IQRouter testling(channel_);
+ testling.setFrom(JID("foo@bar.com/baz"));
+
+ testling.sendIQ(boost::make_shared<IQ>());
+
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
+ }
+
+ void testSendIQ_WithoutFrom() {
+ IQRouter testling(channel_);
- testling.sendIQ(boost::make_shared<IQ>());
+ testling.sendIQ(boost::make_shared<IQ>());
- CPPUNIT_ASSERT_EQUAL(JID(), channel_->iqs_[0]->getFrom());
- }
+ CPPUNIT_ASSERT_EQUAL(JID(), channel_->iqs_[0]->getFrom());
+ }
- void testHandleIQ_WithFrom() {
- IQRouter testling(channel_);
- testling.setFrom(JID("foo@bar.com/baz"));
- DummyIQHandler handler(false, &testling);
+ void testHandleIQ_WithFrom() {
+ IQRouter testling(channel_);
+ testling.setFrom(JID("foo@bar.com/baz"));
+ DummyIQHandler handler(false, &testling);
- channel_->onIQReceived(boost::make_shared<IQ>());
+ channel_->onIQReceived(boost::make_shared<IQ>());
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
- }
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
+ }
- private:
- struct DummyIQHandler : public IQHandler {
- DummyIQHandler(bool handle, IQRouter* router) : handle(handle), router(router), called(0) {
- router->addHandler(this);
- }
+ private:
+ struct DummyIQHandler : public IQHandler {
+ DummyIQHandler(bool handle, IQRouter* router) : handle(handle), router(router), called(0) {
+ router->addHandler(this);
+ }
- ~DummyIQHandler() {
- router->removeHandler(this);
- }
+ ~DummyIQHandler() {
+ router->removeHandler(this);
+ }
- virtual bool handleIQ(boost::shared_ptr<IQ>) {
- called++;
- return handle;
- }
- bool handle;
- IQRouter* router;
- int called;
- };
+ virtual bool handleIQ(boost::shared_ptr<IQ>) {
+ called++;
+ return handle;
+ }
+ bool handle;
+ IQRouter* router;
+ int called;
+ };
- struct RemovingIQHandler : public IQHandler {
- RemovingIQHandler(IQRouter* router) : router(router), called(0) {
- router->addHandler(this);
- }
+ struct RemovingIQHandler : public IQHandler {
+ RemovingIQHandler(IQRouter* router) : router(router), called(0) {
+ router->addHandler(this);
+ }
- virtual bool handleIQ(boost::shared_ptr<IQ>) {
- called++;
- router->removeHandler(this);
- return false;
- }
- IQRouter* router;
- int called;
- };
+ virtual bool handleIQ(boost::shared_ptr<IQ>) {
+ called++;
+ router->removeHandler(this);
+ return false;
+ }
+ IQRouter* router;
+ int called;
+ };
- DummyIQChannel* channel_;
+ DummyIQChannel* channel_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IQRouterTest);
diff --git a/Swiften/Queries/UnitTest/RequestTest.cpp b/Swiften/Queries/UnitTest/RequestTest.cpp
index 2fd5867..93aa9b1 100644
--- a/Swiften/Queries/UnitTest/RequestTest.cpp
+++ b/Swiften/Queries/UnitTest/RequestTest.cpp
@@ -20,348 +20,348 @@
using namespace Swift;
class RequestTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(RequestTest);
- CPPUNIT_TEST(testSendGet);
- CPPUNIT_TEST(testSendSet);
- CPPUNIT_TEST(testHandleIQ);
- CPPUNIT_TEST(testHandleIQ_InvalidID);
- CPPUNIT_TEST(testHandleIQ_Error);
- CPPUNIT_TEST(testHandleIQ_ErrorWithoutPayload);
- CPPUNIT_TEST(testHandleIQ_BeforeSend);
- CPPUNIT_TEST(testHandleIQ_DifferentPayload);
- CPPUNIT_TEST(testHandleIQ_RawXMLPayload);
- CPPUNIT_TEST(testHandleIQ_GetWithSameID);
- CPPUNIT_TEST(testHandleIQ_SetWithSameID);
- CPPUNIT_TEST(testHandleIQ_IncorrectSender);
- CPPUNIT_TEST(testHandleIQ_IncorrectSenderForServerQuery);
- CPPUNIT_TEST(testHandleIQ_IncorrectOtherResourceSenderForServerQuery);
- CPPUNIT_TEST(testHandleIQ_ServerRespondsWithDomain);
- CPPUNIT_TEST(testHandleIQ_ServerRespondsWithBareJID);
- CPPUNIT_TEST(testHandleIQ_ServerRespondsWithoutFrom);
- CPPUNIT_TEST(testHandleIQ_ServerRespondsWithFullJID);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- class MyPayload : public Payload {
- public:
- MyPayload(const std::string& s = "") : text_(s) {}
- std::string text_;
- };
-
- struct MyOtherPayload : public Payload {
- };
-
- class MyRequest : public Request {
- public:
- MyRequest(
- IQ::Type type,
- const JID& receiver,
- boost::shared_ptr<Payload> payload,
- IQRouter* router) :
- Request(type, receiver, payload, router) {
- }
-
- virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
- onResponse(payload, error);
- }
-
- public:
- boost::signal<void (boost::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
- };
-
- public:
- void setUp() {
- channel_ = new DummyIQChannel();
- router_ = new IQRouter(channel_);
- payload_ = boost::shared_ptr<Payload>(new MyPayload("foo"));
- responsePayload_ = boost::shared_ptr<Payload>(new MyPayload("bar"));
- responsesReceived_ = 0;
- }
-
- void tearDown() {
- delete router_;
- delete channel_;
- }
-
- void testSendSet() {
- MyRequest testling(IQ::Set, JID("foo@bar.com/baz"), payload_, router_);
- testling.send();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getTo());
- CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType());
- CPPUNIT_ASSERT_EQUAL(std::string("test-id"), channel_->iqs_[0]->getID());
- }
-
- void testSendGet() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.send();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- CPPUNIT_ASSERT_EQUAL(IQ::Get, channel_->iqs_[0]->getType());
- }
-
- void testHandleIQ() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- // FIXME: Doesn't test that it didn't handle the payload
- void testHandleIQ_InvalidID() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"different-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_Error() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- boost::shared_ptr<IQ> error = createError(JID("foo@bar.com/baz"),"test-id");
- boost::shared_ptr<Payload> errorPayload = boost::make_shared<ErrorPayload>(ErrorPayload::InternalServerError);
- error->addPayload(errorPayload);
- channel_->onIQReceived(error);
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::InternalServerError, receivedErrors[0].getCondition());
- }
-
- void testHandleIQ_ErrorWithoutPayload() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createError(JID("foo@bar.com/baz"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- CPPUNIT_ASSERT_EQUAL(ErrorPayload::UndefinedCondition, receivedErrors[0].getCondition());
- }
-
- void testHandleIQ_BeforeSend() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_DifferentPayload() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleDifferentResponse, this, _1, _2));
- testling.send();
-
- responsePayload_ = boost::make_shared<MyOtherPayload>();
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_RawXMLPayload() {
- payload_ = boost::make_shared<RawXMLPayload>("<bla/>");
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleRawXMLResponse, this, _1, _2));
- testling.send();
-
- responsePayload_ = boost::make_shared<MyOtherPayload>();
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_GetWithSameID() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- boost::shared_ptr<IQ> response = createResponse(JID("foo@bar.com/baz"),"test-id");
- response->setType(IQ::Get);
- channel_->onIQReceived(response);
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_SetWithSameID() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- boost::shared_ptr<IQ> response = createResponse(JID("foo@bar.com/baz"), "test-id");
- response->setType(IQ::Set);
- channel_->onIQReceived(response);
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_IncorrectSender() {
- MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("anotherfoo@bar.com/baz"), "test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_IncorrectSenderForServerQuery() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"), "test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_IncorrectOtherResourceSenderForServerQuery() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("alice@wonderland.lit/RabbitHole"), "test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_ServerRespondsWithDomain() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("wonderland.lit"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_ServerRespondsWithBareJID() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("alice@wonderland.lit"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- // This tests a bug in ejabberd servers (2.0.5)
- void testHandleIQ_ServerRespondsWithFullJID() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID("alice@wonderland.lit/TeaParty"),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
- void testHandleIQ_ServerRespondsWithoutFrom() {
- MyRequest testling(IQ::Get, JID(), payload_, router_);
- router_->setJID("alice@wonderland.lit/TeaParty");
- testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
- testling.send();
-
- channel_->onIQReceived(createResponse(JID(),"test-id"));
-
- CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
- }
-
-
-
- private:
- void handleResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
- if (e) {
- receivedErrors.push_back(*e);
- }
- else {
- boost::shared_ptr<MyPayload> payload(boost::dynamic_pointer_cast<MyPayload>(p));
- CPPUNIT_ASSERT(payload);
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), payload->text_);
- ++responsesReceived_;
- }
- }
-
- void handleDifferentResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
- CPPUNIT_ASSERT(!e);
- CPPUNIT_ASSERT(!p);
- ++responsesReceived_;
- }
-
- void handleRawXMLResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
- CPPUNIT_ASSERT(!e);
- CPPUNIT_ASSERT(p);
- CPPUNIT_ASSERT(boost::dynamic_pointer_cast<MyOtherPayload>(p));
- ++responsesReceived_;
- }
-
- boost::shared_ptr<IQ> createResponse(const JID& from, const std::string& id) {
- boost::shared_ptr<IQ> iq(new IQ(IQ::Result));
- iq->setFrom(from);
- iq->addPayload(responsePayload_);
- iq->setID(id);
- return iq;
- }
-
- boost::shared_ptr<IQ> createError(const JID& from, const std::string& id) {
- boost::shared_ptr<IQ> iq(new IQ(IQ::Error));
- iq->setFrom(from);
- iq->setID(id);
- return iq;
- }
-
- private:
- IQRouter* router_;
- DummyIQChannel* channel_;
- boost::shared_ptr<Payload> payload_;
- boost::shared_ptr<Payload> responsePayload_;
- int responsesReceived_;
- std::vector<ErrorPayload> receivedErrors;
+ CPPUNIT_TEST_SUITE(RequestTest);
+ CPPUNIT_TEST(testSendGet);
+ CPPUNIT_TEST(testSendSet);
+ CPPUNIT_TEST(testHandleIQ);
+ CPPUNIT_TEST(testHandleIQ_InvalidID);
+ CPPUNIT_TEST(testHandleIQ_Error);
+ CPPUNIT_TEST(testHandleIQ_ErrorWithoutPayload);
+ CPPUNIT_TEST(testHandleIQ_BeforeSend);
+ CPPUNIT_TEST(testHandleIQ_DifferentPayload);
+ CPPUNIT_TEST(testHandleIQ_RawXMLPayload);
+ CPPUNIT_TEST(testHandleIQ_GetWithSameID);
+ CPPUNIT_TEST(testHandleIQ_SetWithSameID);
+ CPPUNIT_TEST(testHandleIQ_IncorrectSender);
+ CPPUNIT_TEST(testHandleIQ_IncorrectSenderForServerQuery);
+ CPPUNIT_TEST(testHandleIQ_IncorrectOtherResourceSenderForServerQuery);
+ CPPUNIT_TEST(testHandleIQ_ServerRespondsWithDomain);
+ CPPUNIT_TEST(testHandleIQ_ServerRespondsWithBareJID);
+ CPPUNIT_TEST(testHandleIQ_ServerRespondsWithoutFrom);
+ CPPUNIT_TEST(testHandleIQ_ServerRespondsWithFullJID);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ class MyPayload : public Payload {
+ public:
+ MyPayload(const std::string& s = "") : text_(s) {}
+ std::string text_;
+ };
+
+ struct MyOtherPayload : public Payload {
+ };
+
+ class MyRequest : public Request {
+ public:
+ MyRequest(
+ IQ::Type type,
+ const JID& receiver,
+ boost::shared_ptr<Payload> payload,
+ IQRouter* router) :
+ Request(type, receiver, payload, router) {
+ }
+
+ virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(payload, error);
+ }
+
+ public:
+ boost::signal<void (boost::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
+ };
+
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ payload_ = boost::shared_ptr<Payload>(new MyPayload("foo"));
+ responsePayload_ = boost::shared_ptr<Payload>(new MyPayload("bar"));
+ responsesReceived_ = 0;
+ }
+
+ void tearDown() {
+ delete router_;
+ delete channel_;
+ }
+
+ void testSendSet() {
+ MyRequest testling(IQ::Set, JID("foo@bar.com/baz"), payload_, router_);
+ testling.send();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getTo());
+ CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType());
+ CPPUNIT_ASSERT_EQUAL(std::string("test-id"), channel_->iqs_[0]->getID());
+ }
+
+ void testSendGet() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.send();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ CPPUNIT_ASSERT_EQUAL(IQ::Get, channel_->iqs_[0]->getType());
+ }
+
+ void testHandleIQ() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ // FIXME: Doesn't test that it didn't handle the payload
+ void testHandleIQ_InvalidID() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"different-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_Error() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ boost::shared_ptr<IQ> error = createError(JID("foo@bar.com/baz"),"test-id");
+ boost::shared_ptr<Payload> errorPayload = boost::make_shared<ErrorPayload>(ErrorPayload::InternalServerError);
+ error->addPayload(errorPayload);
+ channel_->onIQReceived(error);
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::InternalServerError, receivedErrors[0].getCondition());
+ }
+
+ void testHandleIQ_ErrorWithoutPayload() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createError(JID("foo@bar.com/baz"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ CPPUNIT_ASSERT_EQUAL(ErrorPayload::UndefinedCondition, receivedErrors[0].getCondition());
+ }
+
+ void testHandleIQ_BeforeSend() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_DifferentPayload() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleDifferentResponse, this, _1, _2));
+ testling.send();
+
+ responsePayload_ = boost::make_shared<MyOtherPayload>();
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_RawXMLPayload() {
+ payload_ = boost::make_shared<RawXMLPayload>("<bla/>");
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleRawXMLResponse, this, _1, _2));
+ testling.send();
+
+ responsePayload_ = boost::make_shared<MyOtherPayload>();
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_GetWithSameID() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ boost::shared_ptr<IQ> response = createResponse(JID("foo@bar.com/baz"),"test-id");
+ response->setType(IQ::Get);
+ channel_->onIQReceived(response);
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_SetWithSameID() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ boost::shared_ptr<IQ> response = createResponse(JID("foo@bar.com/baz"), "test-id");
+ response->setType(IQ::Set);
+ channel_->onIQReceived(response);
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_IncorrectSender() {
+ MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("anotherfoo@bar.com/baz"), "test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_IncorrectSenderForServerQuery() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"), "test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_IncorrectOtherResourceSenderForServerQuery() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("alice@wonderland.lit/RabbitHole"), "test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_ServerRespondsWithDomain() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("wonderland.lit"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_ServerRespondsWithBareJID() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("alice@wonderland.lit"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ // This tests a bug in ejabberd servers (2.0.5)
+ void testHandleIQ_ServerRespondsWithFullJID() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID("alice@wonderland.lit/TeaParty"),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+ void testHandleIQ_ServerRespondsWithoutFrom() {
+ MyRequest testling(IQ::Get, JID(), payload_, router_);
+ router_->setJID("alice@wonderland.lit/TeaParty");
+ testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
+ testling.send();
+
+ channel_->onIQReceived(createResponse(JID(),"test-id"));
+
+ CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
+ }
+
+
+
+ private:
+ void handleResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ if (e) {
+ receivedErrors.push_back(*e);
+ }
+ else {
+ boost::shared_ptr<MyPayload> payload(boost::dynamic_pointer_cast<MyPayload>(p));
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), payload->text_);
+ ++responsesReceived_;
+ }
+ }
+
+ void handleDifferentResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ CPPUNIT_ASSERT(!e);
+ CPPUNIT_ASSERT(!p);
+ ++responsesReceived_;
+ }
+
+ void handleRawXMLResponse(boost::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ CPPUNIT_ASSERT(!e);
+ CPPUNIT_ASSERT(p);
+ CPPUNIT_ASSERT(boost::dynamic_pointer_cast<MyOtherPayload>(p));
+ ++responsesReceived_;
+ }
+
+ boost::shared_ptr<IQ> createResponse(const JID& from, const std::string& id) {
+ boost::shared_ptr<IQ> iq(new IQ(IQ::Result));
+ iq->setFrom(from);
+ iq->addPayload(responsePayload_);
+ iq->setID(id);
+ return iq;
+ }
+
+ boost::shared_ptr<IQ> createError(const JID& from, const std::string& id) {
+ boost::shared_ptr<IQ> iq(new IQ(IQ::Error));
+ iq->setFrom(from);
+ iq->setID(id);
+ return iq;
+ }
+
+ private:
+ IQRouter* router_;
+ DummyIQChannel* channel_;
+ boost::shared_ptr<Payload> payload_;
+ boost::shared_ptr<Payload> responsePayload_;
+ int responsesReceived_;
+ std::vector<ErrorPayload> receivedErrors;
};
CPPUNIT_TEST_SUITE_REGISTRATION(RequestTest);
diff --git a/Swiften/Queries/UnitTest/ResponderTest.cpp b/Swiften/Queries/UnitTest/ResponderTest.cpp
index 42d8651..c3474f2 100644
--- a/Swiften/Queries/UnitTest/ResponderTest.cpp
+++ b/Swiften/Queries/UnitTest/ResponderTest.cpp
@@ -19,140 +19,140 @@
using namespace Swift;
class ResponderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ResponderTest);
- CPPUNIT_TEST(testConstructor);
- CPPUNIT_TEST(testStart);
- CPPUNIT_TEST(testStop);
- CPPUNIT_TEST(testHandleIQ_Set);
- CPPUNIT_TEST(testHandleIQ_Get);
- CPPUNIT_TEST(testHandleIQ_Error);
- CPPUNIT_TEST(testHandleIQ_Result);
- CPPUNIT_TEST(testHandleIQ_NoPayload);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ResponderTest);
+ CPPUNIT_TEST(testConstructor);
+ CPPUNIT_TEST(testStart);
+ CPPUNIT_TEST(testStop);
+ CPPUNIT_TEST(testHandleIQ_Set);
+ CPPUNIT_TEST(testHandleIQ_Get);
+ CPPUNIT_TEST(testHandleIQ_Error);
+ CPPUNIT_TEST(testHandleIQ_Result);
+ CPPUNIT_TEST(testHandleIQ_NoPayload);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- channel_ = new DummyIQChannel();
- router_ = new IQRouter(channel_);
- payload_ = boost::make_shared<SoftwareVersion>("foo");
- }
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ payload_ = boost::make_shared<SoftwareVersion>("foo");
+ }
- void tearDown() {
- delete router_;
- delete channel_;
- }
-
- void testConstructor() {
- MyResponder testling(router_);
-
- channel_->onIQReceived(createRequest(IQ::Set));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- }
-
- void testStart() {
- MyResponder testling(router_);
-
- testling.start();
- channel_->onIQReceived(createRequest(IQ::Set));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
- }
-
- void testStop() {
- MyResponder testling(router_);
-
- testling.start();
- testling.stop();
- channel_->onIQReceived(createRequest(IQ::Set));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- }
-
- void testHandleIQ_Set() {
- MyResponder testling(router_);
-
- CPPUNIT_ASSERT(dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Set)));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
- CPPUNIT_ASSERT(payload_ == testling.setPayloads_[0]);
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
- }
-
- void testHandleIQ_Get() {
- MyResponder testling(router_);
-
- CPPUNIT_ASSERT(dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Get)));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.getPayloads_.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- CPPUNIT_ASSERT(payload_ == testling.getPayloads_[0]);
- }
-
- void testHandleIQ_Error() {
- MyResponder testling(router_);
-
- CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Error)));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- }
-
- void testHandleIQ_Result() {
- MyResponder testling(router_);
-
- CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Result)));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- }
-
- void testHandleIQ_NoPayload() {
- MyResponder testling(router_);
-
- CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(boost::make_shared<IQ>(IQ::Get)));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
- }
-
- private:
- boost::shared_ptr<IQ> createRequest(IQ::Type type) {
- boost::shared_ptr<IQ> iq(new IQ(type));
- iq->addPayload(payload_);
- iq->setID("myid");
- iq->setFrom(JID("foo@bar.com/baz"));
- return iq;
- }
-
- private:
- class MyResponder : public Responder<SoftwareVersion> {
- public:
- MyResponder(IQRouter* router) : Responder<SoftwareVersion>(router), getRequestResponse_(true), setRequestResponse_(true) {}
+ void tearDown() {
+ delete router_;
+ delete channel_;
+ }
+
+ void testConstructor() {
+ MyResponder testling(router_);
+
+ channel_->onIQReceived(createRequest(IQ::Set));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testStart() {
+ MyResponder testling(router_);
+
+ testling.start();
+ channel_->onIQReceived(createRequest(IQ::Set));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testStop() {
+ MyResponder testling(router_);
+
+ testling.start();
+ testling.stop();
+ channel_->onIQReceived(createRequest(IQ::Set));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testHandleIQ_Set() {
+ MyResponder testling(router_);
+
+ CPPUNIT_ASSERT(dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Set)));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
+ CPPUNIT_ASSERT(payload_ == testling.setPayloads_[0]);
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
+ }
+
+ void testHandleIQ_Get() {
+ MyResponder testling(router_);
+
+ CPPUNIT_ASSERT(dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Get)));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.getPayloads_.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ CPPUNIT_ASSERT(payload_ == testling.getPayloads_[0]);
+ }
+
+ void testHandleIQ_Error() {
+ MyResponder testling(router_);
+
+ CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Error)));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testHandleIQ_Result() {
+ MyResponder testling(router_);
+
+ CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Result)));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testHandleIQ_NoPayload() {
+ MyResponder testling(router_);
+
+ CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(boost::make_shared<IQ>(IQ::Get)));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ private:
+ boost::shared_ptr<IQ> createRequest(IQ::Type type) {
+ boost::shared_ptr<IQ> iq(new IQ(type));
+ iq->addPayload(payload_);
+ iq->setID("myid");
+ iq->setFrom(JID("foo@bar.com/baz"));
+ return iq;
+ }
+
+ private:
+ class MyResponder : public Responder<SoftwareVersion> {
+ public:
+ MyResponder(IQRouter* router) : Responder<SoftwareVersion>(router), getRequestResponse_(true), setRequestResponse_(true) {}
- virtual bool handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
- getPayloads_.push_back(payload);
- return getRequestResponse_;
- }
- virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
- CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
- setPayloads_.push_back(payload);
- return setRequestResponse_;
- }
+ virtual bool handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
+ getPayloads_.push_back(payload);
+ return getRequestResponse_;
+ }
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
+ CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
+ setPayloads_.push_back(payload);
+ return setRequestResponse_;
+ }
- bool getRequestResponse_;
- bool setRequestResponse_;
- std::vector<boost::shared_ptr<SoftwareVersion> > getPayloads_;
- std::vector<boost::shared_ptr<SoftwareVersion> > setPayloads_;
- };
+ bool getRequestResponse_;
+ bool setRequestResponse_;
+ std::vector<boost::shared_ptr<SoftwareVersion> > getPayloads_;
+ std::vector<boost::shared_ptr<SoftwareVersion> > setPayloads_;
+ };
- private:
- IQRouter* router_;
- DummyIQChannel* channel_;
- boost::shared_ptr<SoftwareVersion> payload_;
+ private:
+ IQRouter* router_;
+ DummyIQChannel* channel_;
+ boost::shared_ptr<SoftwareVersion> payload_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResponderTest);
diff --git a/Swiften/Roster/GetRosterRequest.h b/Swiften/Roster/GetRosterRequest.h
index 05863d3..6ca16cb 100644
--- a/Swiften/Roster/GetRosterRequest.h
+++ b/Swiften/Roster/GetRosterRequest.h
@@ -11,23 +11,23 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetRosterRequest : public GenericRequest<RosterPayload> {
- public:
- typedef boost::shared_ptr<GetRosterRequest> ref;
+ class SWIFTEN_API GetRosterRequest : public GenericRequest<RosterPayload> {
+ public:
+ typedef boost::shared_ptr<GetRosterRequest> ref;
- static ref create(IQRouter* router) {
- return ref(new GetRosterRequest(router));
- }
+ static ref create(IQRouter* router) {
+ return ref(new GetRosterRequest(router));
+ }
- static ref create(IQRouter* router, const std::string& version) {
- ref result(new GetRosterRequest(router));
- result->getPayloadGeneric()->setVersion(version);
- return result;
- }
+ static ref create(IQRouter* router, const std::string& version) {
+ ref result(new GetRosterRequest(router));
+ result->getPayloadGeneric()->setVersion(version);
+ return result;
+ }
- private:
- GetRosterRequest(IQRouter* router) :
- GenericRequest<RosterPayload>(IQ::Get, JID(), boost::shared_ptr<Payload>(new RosterPayload()), router) {
- }
- };
+ private:
+ GetRosterRequest(IQRouter* router) :
+ GenericRequest<RosterPayload>(IQ::Get, JID(), boost::shared_ptr<Payload>(new RosterPayload()), router) {
+ }
+ };
}
diff --git a/Swiften/Roster/RosterMemoryStorage.cpp b/Swiften/Roster/RosterMemoryStorage.cpp
index abaac5e..f187116 100644
--- a/Swiften/Roster/RosterMemoryStorage.cpp
+++ b/Swiften/Roster/RosterMemoryStorage.cpp
@@ -14,10 +14,10 @@ RosterMemoryStorage::RosterMemoryStorage() {
}
void RosterMemoryStorage::setRoster(boost::shared_ptr<RosterPayload> r) {
- roster.reset();
- if (r) {
- roster = boost::make_shared<RosterPayload>(*r);
- }
+ roster.reset();
+ if (r) {
+ roster = boost::make_shared<RosterPayload>(*r);
+ }
}
}
diff --git a/Swiften/Roster/RosterMemoryStorage.h b/Swiften/Roster/RosterMemoryStorage.h
index 9e1ca76..4058f84 100644
--- a/Swiften/Roster/RosterMemoryStorage.h
+++ b/Swiften/Roster/RosterMemoryStorage.h
@@ -10,17 +10,17 @@
#include <Swiften/Roster/RosterStorage.h>
namespace Swift {
- class SWIFTEN_API RosterMemoryStorage : public RosterStorage {
- public:
- RosterMemoryStorage();
+ class SWIFTEN_API RosterMemoryStorage : public RosterStorage {
+ public:
+ RosterMemoryStorage();
- virtual boost::shared_ptr<RosterPayload> getRoster() const {
- return roster;
- }
+ virtual boost::shared_ptr<RosterPayload> getRoster() const {
+ return roster;
+ }
- virtual void setRoster(boost::shared_ptr<RosterPayload>);
+ virtual void setRoster(boost::shared_ptr<RosterPayload>);
- private:
- boost::shared_ptr<RosterPayload> roster;
- };
+ private:
+ boost::shared_ptr<RosterPayload> roster;
+ };
}
diff --git a/Swiften/Roster/RosterPushResponder.h b/Swiften/Roster/RosterPushResponder.h
index 1e99bea..06ba797 100644
--- a/Swiften/Roster/RosterPushResponder.h
+++ b/Swiften/Roster/RosterPushResponder.h
@@ -12,23 +12,23 @@
#include <Swiften/Queries/SetResponder.h>
namespace Swift {
- class SWIFTEN_API RosterPushResponder : public SetResponder<RosterPayload> {
- public:
- RosterPushResponder(IQRouter* router) : SetResponder<RosterPayload>(router) {}
+ class SWIFTEN_API RosterPushResponder : public SetResponder<RosterPayload> {
+ public:
+ RosterPushResponder(IQRouter* router) : SetResponder<RosterPayload>(router) {}
- public:
- boost::signal<void (boost::shared_ptr<RosterPayload>)> onRosterReceived;
+ public:
+ boost::signal<void (boost::shared_ptr<RosterPayload>)> onRosterReceived;
- private:
- virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<RosterPayload> payload) {
- if (getIQRouter()->isAccountJID(from)) {
- onRosterReceived(payload);
- sendResponse(from, id, boost::shared_ptr<RosterPayload>());
- }
- else {
- sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
- }
- return true;
- }
- };
+ private:
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<RosterPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ onRosterReceived(payload);
+ sendResponse(from, id, boost::shared_ptr<RosterPayload>());
+ }
+ else {
+ sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
+ }
+ return true;
+ }
+ };
}
diff --git a/Swiften/Roster/RosterStorage.h b/Swiften/Roster/RosterStorage.h
index c7e92d2..92c40f9 100644
--- a/Swiften/Roster/RosterStorage.h
+++ b/Swiften/Roster/RosterStorage.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/RosterPayload.h>
namespace Swift {
- class SWIFTEN_API RosterStorage {
- public:
- virtual ~RosterStorage();
+ class SWIFTEN_API RosterStorage {
+ public:
+ virtual ~RosterStorage();
- virtual boost::shared_ptr<RosterPayload> getRoster() const = 0;
- virtual void setRoster(boost::shared_ptr<RosterPayload>) = 0;
- };
+ virtual boost::shared_ptr<RosterPayload> getRoster() const = 0;
+ virtual void setRoster(boost::shared_ptr<RosterPayload>) = 0;
+ };
}
diff --git a/Swiften/Roster/SetRosterRequest.h b/Swiften/Roster/SetRosterRequest.h
index 4d89836..64c0984 100644
--- a/Swiften/Roster/SetRosterRequest.h
+++ b/Swiften/Roster/SetRosterRequest.h
@@ -14,27 +14,27 @@
#include <Swiften/Queries/Request.h>
namespace Swift {
- class SWIFTEN_API SetRosterRequest : public Request {
- public:
- typedef boost::shared_ptr<SetRosterRequest> ref;
+ class SWIFTEN_API SetRosterRequest : public Request {
+ public:
+ typedef boost::shared_ptr<SetRosterRequest> ref;
- static ref create(RosterPayload::ref payload, IQRouter* router) {
- return ref(new SetRosterRequest(JID(), payload, router));
- }
+ static ref create(RosterPayload::ref payload, IQRouter* router) {
+ return ref(new SetRosterRequest(JID(), payload, router));
+ }
- static ref create(RosterPayload::ref payload, const JID& to, IQRouter* router) {
- return ref(new SetRosterRequest(to, payload, router));
- }
+ static ref create(RosterPayload::ref payload, const JID& to, IQRouter* router) {
+ return ref(new SetRosterRequest(to, payload, router));
+ }
- private:
- SetRosterRequest(const JID& to, boost::shared_ptr<RosterPayload> payload, IQRouter* router) : Request(IQ::Set, to, boost::shared_ptr<RosterPayload>(payload), router) {
- }
+ private:
+ SetRosterRequest(const JID& to, boost::shared_ptr<RosterPayload> payload, IQRouter* router) : Request(IQ::Set, to, boost::shared_ptr<RosterPayload>(payload), router) {
+ }
- virtual void handleResponse(boost::shared_ptr<Payload> /*payload*/, ErrorPayload::ref error) {
- onResponse(error);
- }
+ virtual void handleResponse(boost::shared_ptr<Payload> /*payload*/, ErrorPayload::ref error) {
+ onResponse(error);
+ }
- public:
- boost::signal<void (ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signal<void (ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp b/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
index 3e2f85e..6850c21 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
@@ -22,340 +22,340 @@
using namespace Swift;
class XMPPRosterControllerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPRosterControllerTest);
- CPPUNIT_TEST(testGet_Response);
- CPPUNIT_TEST(testGet_EmptyResponse);
- CPPUNIT_TEST(testGet_NoRosterInStorage);
- CPPUNIT_TEST(testGet_NoVersionInStorage);
- CPPUNIT_TEST(testGet_VersionInStorage);
- CPPUNIT_TEST(testGet_ServerDoesNotSupportVersion);
- CPPUNIT_TEST(testGet_ResponseWithoutNewVersion);
- CPPUNIT_TEST(testGet_ResponseWithNewVersion);
- CPPUNIT_TEST(testAdd);
- CPPUNIT_TEST(testAddFromNonAccount);
- CPPUNIT_TEST(testModify);
- CPPUNIT_TEST(testRemove);
- CPPUNIT_TEST(testRemove_RosterStorageUpdated);
- CPPUNIT_TEST(testMany);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- channel_ = new DummyStanzaChannel();
- router_ = new IQRouter(channel_);
- router_->setJID("me@bla.com");
- xmppRoster_ = new XMPPRosterImpl();
- handler_ = new XMPPRosterSignalHandler(xmppRoster_);
- rosterStorage_ = new RosterMemoryStorage();
- jid1_ = JID("foo@bar.com");
- jid2_ = JID("alice@wonderland.lit");
- jid3_ = JID("jane@austen.lit");
- }
-
- void tearDown() {
- delete rosterStorage_;
- delete handler_;
- delete xmppRoster_;
- delete router_;
- delete channel_;
- }
-
- void testGet_Response() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
-
- testling->requestRoster();
- boost::shared_ptr<RosterPayload> payload = boost::make_shared<RosterPayload>();
- payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- payload->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), payload));
-
- CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid1_));
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
- }
-
- void testGet_EmptyResponse() {
- XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
-
- controller.requestRoster();
-
- channel_->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
- }
-
- void testAdd() {
- XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
-
- boost::shared_ptr<RosterPayload> payload(new RosterPayload());
- payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "eou", payload));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), xmppRoster_->getGroupsForJID(jid1_).size());
- CPPUNIT_ASSERT(xmppRoster_->containsJID(jid1_));
- CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(jid1_));
- }
-
- void testGet_NoRosterInStorage() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
-
- testling->requestRoster();
-
- boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
- CPPUNIT_ASSERT(roster->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
- }
-
- void testGet_NoVersionInStorage() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
- rosterStorage_->setRoster(boost::make_shared<RosterPayload>());
-
- testling->requestRoster();
-
- boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
- CPPUNIT_ASSERT(roster->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
- }
-
- void testGet_VersionInStorage() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
- boost::shared_ptr<RosterPayload> payload(new RosterPayload());
- payload->setVersion("foover");
- rosterStorage_->setRoster(payload);
-
- testling->requestRoster();
-
- boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
- CPPUNIT_ASSERT(roster->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("foover"), *roster->getVersion());
- }
-
- void testGet_ServerDoesNotSupportVersion() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- boost::shared_ptr<RosterPayload> payload(new RosterPayload());
- payload->setVersion("foover");
- rosterStorage_->setRoster(payload);
-
- testling->requestRoster();
-
- boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
- CPPUNIT_ASSERT(!roster->getVersion());
- }
-
- void testGet_ResponseWithoutNewVersion() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
- boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
- storedRoster->setVersion("version10");
- storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- storedRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
- rosterStorage_->setRoster(storedRoster);
- testling->requestRoster();
-
- channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
-
- CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid1_));
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
- CPPUNIT_ASSERT(rosterStorage_->getRoster());
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("version10"), *rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid1_));
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
- }
-
- void testGet_ResponseWithNewVersion() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
- boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
- storedRoster->setVersion("version10");
- storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- rosterStorage_->setRoster(storedRoster);
- testling->requestRoster();
-
- boost::shared_ptr<RosterPayload> serverRoster(new RosterPayload());
- serverRoster->setVersion("version12");
- serverRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
- std::vector<std::string> groups;
- groups.push_back("foo");
- groups.push_back("bar");
- serverRoster->addItem(RosterItemPayload(jid3_, "Rabbit", RosterItemPayload::Both, groups));
- channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), serverRoster));
-
-
- CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
- CPPUNIT_ASSERT(!xmppRoster_->getItem(jid1_));
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
- CPPUNIT_ASSERT(xmppRoster_->getItem(jid3_));
- CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT(rosterStorage_->getRoster());
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("version12"), *rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT(!rosterStorage_->getRoster()->getItem(jid1_));
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid3_));
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rosterStorage_->getRoster()->getItem(jid3_)->getGroups().size()));
- }
-
- void testAddFromNonAccount() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
-
- boost::shared_ptr<RosterPayload> payload(new RosterPayload());
- payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- IQ::ref request = IQ::createRequest(IQ::Set, JID(), "eou", payload);
- request->setFrom(jid2_);
- channel_->onIQReceived(request);
-
- CPPUNIT_ASSERT_EQUAL(None, handler_->getLastEvent());
- }
-
- void testModify() {
- XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
- boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
- payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
- payload2->addItem(RosterItemPayload(jid1_, "Bob2", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
-
- CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
-
- CPPUNIT_ASSERT_EQUAL(std::string("Bob2"), xmppRoster_->getNameForJID(jid1_));
- }
-
- void testRemove() {
- XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
- boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
- payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
- payload2->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
- CPPUNIT_ASSERT(!xmppRoster_->containsJID(jid1_));
- CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
-
- }
-
- void testRemove_RosterStorageUpdated() {
- boost::shared_ptr<XMPPRosterController> testling(createController());
- testling->setUseVersioning(true);
- boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
- storedRoster->setVersion("version10");
- storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- storedRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
- rosterStorage_->setRoster(storedRoster);
- testling->requestRoster();
- channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
-
- boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
- payload2->setVersion("version15");
- payload2->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
-
- CPPUNIT_ASSERT(rosterStorage_->getRoster());
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT_EQUAL(std::string("version15"), *rosterStorage_->getRoster()->getVersion());
- CPPUNIT_ASSERT(!rosterStorage_->getRoster()->getItem(jid1_));
- CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
- }
-
- void testMany() {
- XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
- boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
- payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
- payload2->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload3(new RosterPayload());
- payload3->addItem(RosterItemPayload(jid1_, "Ernie", RosterItemPayload::Both));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id3", payload3));
-
- CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload4(new RosterPayload());
- RosterItemPayload item(jid3_, "Jane", RosterItemPayload::Both);
- std::string janesGroup("Jane's Group");
- item.addGroup(janesGroup);
- payload4->addItem(item);
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id4", payload4));
-
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid3_).size());
- CPPUNIT_ASSERT_EQUAL(janesGroup, xmppRoster_->getGroupsForJID(jid3_)[0]);
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload5(new RosterPayload());
- payload5->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id5", payload5));
- CPPUNIT_ASSERT(!xmppRoster_->containsJID(jid1_));
- CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
-
- boost::shared_ptr<RosterPayload> payload6(new RosterPayload());
- RosterItemPayload item2(jid2_, "Little Alice", RosterItemPayload::Both);
- std::string alicesGroup("Alice's Group");
- item2.addGroup(alicesGroup);
- payload6->addItem(item2);
- channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id6", payload6));
- CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("Little Alice"), xmppRoster_->getNameForJID(jid2_));
- CPPUNIT_ASSERT_EQUAL(std::string("Jane"), xmppRoster_->getNameForJID(jid3_));
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid2_).size());
- CPPUNIT_ASSERT_EQUAL(alicesGroup, xmppRoster_->getGroupsForJID(jid2_)[0]);
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid3_).size());
- CPPUNIT_ASSERT_EQUAL(janesGroup, xmppRoster_->getGroupsForJID(jid3_)[0]);
- handler_->reset();
-
- }
-
- private:
- XMPPRosterController* createController() {
- return new XMPPRosterController(router_, xmppRoster_, rosterStorage_);
- }
-
- private:
- DummyStanzaChannel* channel_;
- IQRouter* router_;
- XMPPRosterImpl* xmppRoster_;
- XMPPRosterSignalHandler* handler_;
- RosterMemoryStorage* rosterStorage_;
- JID jid1_;
- JID jid2_;
- JID jid3_;
+ CPPUNIT_TEST_SUITE(XMPPRosterControllerTest);
+ CPPUNIT_TEST(testGet_Response);
+ CPPUNIT_TEST(testGet_EmptyResponse);
+ CPPUNIT_TEST(testGet_NoRosterInStorage);
+ CPPUNIT_TEST(testGet_NoVersionInStorage);
+ CPPUNIT_TEST(testGet_VersionInStorage);
+ CPPUNIT_TEST(testGet_ServerDoesNotSupportVersion);
+ CPPUNIT_TEST(testGet_ResponseWithoutNewVersion);
+ CPPUNIT_TEST(testGet_ResponseWithNewVersion);
+ CPPUNIT_TEST(testAdd);
+ CPPUNIT_TEST(testAddFromNonAccount);
+ CPPUNIT_TEST(testModify);
+ CPPUNIT_TEST(testRemove);
+ CPPUNIT_TEST(testRemove_RosterStorageUpdated);
+ CPPUNIT_TEST(testMany);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ channel_ = new DummyStanzaChannel();
+ router_ = new IQRouter(channel_);
+ router_->setJID("me@bla.com");
+ xmppRoster_ = new XMPPRosterImpl();
+ handler_ = new XMPPRosterSignalHandler(xmppRoster_);
+ rosterStorage_ = new RosterMemoryStorage();
+ jid1_ = JID("foo@bar.com");
+ jid2_ = JID("alice@wonderland.lit");
+ jid3_ = JID("jane@austen.lit");
+ }
+
+ void tearDown() {
+ delete rosterStorage_;
+ delete handler_;
+ delete xmppRoster_;
+ delete router_;
+ delete channel_;
+ }
+
+ void testGet_Response() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+
+ testling->requestRoster();
+ boost::shared_ptr<RosterPayload> payload = boost::make_shared<RosterPayload>();
+ payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ payload->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), payload));
+
+ CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid1_));
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
+ }
+
+ void testGet_EmptyResponse() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+
+ controller.requestRoster();
+
+ channel_->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
+ }
+
+ void testAdd() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+
+ boost::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "eou", payload));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), xmppRoster_->getGroupsForJID(jid1_).size());
+ CPPUNIT_ASSERT(xmppRoster_->containsJID(jid1_));
+ CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(jid1_));
+ }
+
+ void testGet_NoRosterInStorage() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+
+ testling->requestRoster();
+
+ boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
+ }
+
+ void testGet_NoVersionInStorage() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ rosterStorage_->setRoster(boost::make_shared<RosterPayload>());
+
+ testling->requestRoster();
+
+ boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
+ }
+
+ void testGet_VersionInStorage() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ boost::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->setVersion("foover");
+ rosterStorage_->setRoster(payload);
+
+ testling->requestRoster();
+
+ boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("foover"), *roster->getVersion());
+ }
+
+ void testGet_ServerDoesNotSupportVersion() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ boost::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->setVersion("foover");
+ rosterStorage_->setRoster(payload);
+
+ testling->requestRoster();
+
+ boost::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(!roster->getVersion());
+ }
+
+ void testGet_ResponseWithoutNewVersion() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
+ storedRoster->setVersion("version10");
+ storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ storedRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
+ rosterStorage_->setRoster(storedRoster);
+ testling->requestRoster();
+
+ channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
+
+ CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid1_));
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("version10"), *rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid1_));
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
+ }
+
+ void testGet_ResponseWithNewVersion() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
+ storedRoster->setVersion("version10");
+ storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ rosterStorage_->setRoster(storedRoster);
+ testling->requestRoster();
+
+ boost::shared_ptr<RosterPayload> serverRoster(new RosterPayload());
+ serverRoster->setVersion("version12");
+ serverRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
+ std::vector<std::string> groups;
+ groups.push_back("foo");
+ groups.push_back("bar");
+ serverRoster->addItem(RosterItemPayload(jid3_, "Rabbit", RosterItemPayload::Both, groups));
+ channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), serverRoster));
+
+
+ CPPUNIT_ASSERT_EQUAL(2, handler_->getEventCount());
+ CPPUNIT_ASSERT(!xmppRoster_->getItem(jid1_));
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid2_));
+ CPPUNIT_ASSERT(xmppRoster_->getItem(jid3_));
+ CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("version12"), *rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT(!rosterStorage_->getRoster()->getItem(jid1_));
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid3_));
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(rosterStorage_->getRoster()->getItem(jid3_)->getGroups().size()));
+ }
+
+ void testAddFromNonAccount() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+
+ boost::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ IQ::ref request = IQ::createRequest(IQ::Set, JID(), "eou", payload);
+ request->setFrom(jid2_);
+ channel_->onIQReceived(request);
+
+ CPPUNIT_ASSERT_EQUAL(None, handler_->getLastEvent());
+ }
+
+ void testModify() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+ boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
+ payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
+ payload2->addItem(RosterItemPayload(jid1_, "Bob2", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
+
+ CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Bob2"), xmppRoster_->getNameForJID(jid1_));
+ }
+
+ void testRemove() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+ boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
+ payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
+ payload2->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
+ CPPUNIT_ASSERT(!xmppRoster_->containsJID(jid1_));
+ CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+
+ }
+
+ void testRemove_RosterStorageUpdated() {
+ boost::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ boost::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
+ storedRoster->setVersion("version10");
+ storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ storedRoster->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
+ rosterStorage_->setRoster(storedRoster);
+ testling->requestRoster();
+ channel_->onIQReceived(IQ::createResult("foo@bar.com", channel_->sentStanzas[0]->getID(), boost::shared_ptr<RosterPayload>()));
+
+ boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
+ payload2->setVersion("version15");
+ payload2->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
+
+ CPPUNIT_ASSERT(rosterStorage_->getRoster());
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("version15"), *rosterStorage_->getRoster()->getVersion());
+ CPPUNIT_ASSERT(!rosterStorage_->getRoster()->getItem(jid1_));
+ CPPUNIT_ASSERT(rosterStorage_->getRoster()->getItem(jid2_));
+ }
+
+ void testMany() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+ boost::shared_ptr<RosterPayload> payload1(new RosterPayload());
+ payload1->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id1", payload1));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload2(new RosterPayload());
+ payload2->addItem(RosterItemPayload(jid2_, "Alice", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id2", payload2));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload3(new RosterPayload());
+ payload3->addItem(RosterItemPayload(jid1_, "Ernie", RosterItemPayload::Both));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id3", payload3));
+
+ CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload4(new RosterPayload());
+ RosterItemPayload item(jid3_, "Jane", RosterItemPayload::Both);
+ std::string janesGroup("Jane's Group");
+ item.addGroup(janesGroup);
+ payload4->addItem(item);
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id4", payload4));
+
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid3_).size());
+ CPPUNIT_ASSERT_EQUAL(janesGroup, xmppRoster_->getGroupsForJID(jid3_)[0]);
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload5(new RosterPayload());
+ payload5->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Remove));
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id5", payload5));
+ CPPUNIT_ASSERT(!xmppRoster_->containsJID(jid1_));
+ CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+
+ boost::shared_ptr<RosterPayload> payload6(new RosterPayload());
+ RosterItemPayload item2(jid2_, "Little Alice", RosterItemPayload::Both);
+ std::string alicesGroup("Alice's Group");
+ item2.addGroup(alicesGroup);
+ payload6->addItem(item2);
+ channel_->onIQReceived(IQ::createRequest(IQ::Set, JID(), "id6", payload6));
+ CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("Little Alice"), xmppRoster_->getNameForJID(jid2_));
+ CPPUNIT_ASSERT_EQUAL(std::string("Jane"), xmppRoster_->getNameForJID(jid3_));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid2_).size());
+ CPPUNIT_ASSERT_EQUAL(alicesGroup, xmppRoster_->getGroupsForJID(jid2_)[0]);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), xmppRoster_->getGroupsForJID(jid3_).size());
+ CPPUNIT_ASSERT_EQUAL(janesGroup, xmppRoster_->getGroupsForJID(jid3_)[0]);
+ handler_->reset();
+
+ }
+
+ private:
+ XMPPRosterController* createController() {
+ return new XMPPRosterController(router_, xmppRoster_, rosterStorage_);
+ }
+
+ private:
+ DummyStanzaChannel* channel_;
+ IQRouter* router_;
+ XMPPRosterImpl* xmppRoster_;
+ XMPPRosterSignalHandler* handler_;
+ RosterMemoryStorage* rosterStorage_;
+ JID jid1_;
+ JID jid2_;
+ JID jid3_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPRosterControllerTest);
diff --git a/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp b/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp
index d485596..f611fec 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp
@@ -18,95 +18,95 @@ using namespace Swift;
class XMPPRosterImplTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPRosterImplTest);
- CPPUNIT_TEST(testJIDAdded);
- CPPUNIT_TEST(testJIDRemoved);
- CPPUNIT_TEST(testJIDUpdated);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(XMPPRosterImplTest);
+ CPPUNIT_TEST(testJIDAdded);
+ CPPUNIT_TEST(testJIDRemoved);
+ CPPUNIT_TEST(testJIDUpdated);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- jid1_ = JID("a@b.c");
- jid2_ = JID("b@c.d");
- jid3_ = JID("c@d.e");
- roster_ = new XMPPRosterImpl();
- handler_ = new XMPPRosterSignalHandler(roster_);
- groups1_.push_back("bobs");
- groups1_.push_back("berts");
- groups2_.push_back("ernies");
- }
+ public:
+ void setUp() {
+ jid1_ = JID("a@b.c");
+ jid2_ = JID("b@c.d");
+ jid3_ = JID("c@d.e");
+ roster_ = new XMPPRosterImpl();
+ handler_ = new XMPPRosterSignalHandler(roster_);
+ groups1_.push_back("bobs");
+ groups1_.push_back("berts");
+ groups2_.push_back("ernies");
+ }
- void tearDown() {
- delete handler_;
- delete roster_;
- }
+ void tearDown() {
+ delete handler_;
+ delete roster_;
+ }
- void testJIDAdded() {
- roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
- CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
- handler_->reset();
- roster_->addContact(jid2_, "NameTwo", groups1_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NameTwo"), roster_->getNameForJID(jid2_));
- CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
- CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid2_));
- CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
- handler_->reset();
- roster_->addContact(jid3_, "NewName", groups2_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid3_));
- CPPUNIT_ASSERT(groups2_ == roster_->getGroupsForJID(jid3_));
- }
+ void testJIDAdded() {
+ roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
+ CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
+ handler_->reset();
+ roster_->addContact(jid2_, "NameTwo", groups1_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NameTwo"), roster_->getNameForJID(jid2_));
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
+ CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid2_));
+ CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
+ handler_->reset();
+ roster_->addContact(jid3_, "NewName", groups2_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid3_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid3_));
+ CPPUNIT_ASSERT(groups2_ == roster_->getGroupsForJID(jid3_));
+ }
- void testJIDRemoved() {
- roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
- handler_->reset();
- roster_->removeContact(jid1_);
- CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- handler_->reset();
- roster_->addContact(jid1_, "NewName2", groups1_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NewName2"), roster_->getNameForJID(jid1_));
- roster_->addContact(jid2_, "NewName3", groups1_, RosterItemPayload::Both);
- handler_->reset();
- roster_->removeContact(jid2_);
- CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
- handler_->reset();
- roster_->removeContact(jid1_);
- CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- }
+ void testJIDRemoved() {
+ roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
+ handler_->reset();
+ roster_->removeContact(jid1_);
+ CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ handler_->reset();
+ roster_->addContact(jid1_, "NewName2", groups1_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName2"), roster_->getNameForJID(jid1_));
+ roster_->addContact(jid2_, "NewName3", groups1_, RosterItemPayload::Both);
+ handler_->reset();
+ roster_->removeContact(jid2_);
+ CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid2_, handler_->getLastJID());
+ handler_->reset();
+ roster_->removeContact(jid1_);
+ CPPUNIT_ASSERT_EQUAL(Remove, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ }
- void testJIDUpdated() {
- roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
- CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
- handler_->reset();
- roster_->addContact(jid1_, "NameTwo", groups2_, RosterItemPayload::Both);
- CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
- CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
- CPPUNIT_ASSERT_EQUAL(std::string("NameTwo"), roster_->getNameForJID(jid1_));
- CPPUNIT_ASSERT(groups2_ == roster_->getGroupsForJID(jid1_));
- }
+ void testJIDUpdated() {
+ roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NewName"), roster_->getNameForJID(jid1_));
+ CPPUNIT_ASSERT(groups1_ == roster_->getGroupsForJID(jid1_));
+ handler_->reset();
+ roster_->addContact(jid1_, "NameTwo", groups2_, RosterItemPayload::Both);
+ CPPUNIT_ASSERT_EQUAL(Update, handler_->getLastEvent());
+ CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID());
+ CPPUNIT_ASSERT_EQUAL(std::string("NameTwo"), roster_->getNameForJID(jid1_));
+ CPPUNIT_ASSERT(groups2_ == roster_->getGroupsForJID(jid1_));
+ }
- private:
- XMPPRosterImpl* roster_;
- XMPPRosterSignalHandler* handler_;
- JID jid1_;
- JID jid2_;
- JID jid3_;
- std::vector<std::string> groups1_;
- std::vector<std::string> groups2_;
+ private:
+ XMPPRosterImpl* roster_;
+ XMPPRosterSignalHandler* handler_;
+ JID jid1_;
+ JID jid2_;
+ JID jid3_;
+ std::vector<std::string> groups1_;
+ std::vector<std::string> groups2_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPRosterImplTest);
diff --git a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp
index 102e31b..add34a0 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp
@@ -13,17 +13,17 @@
using namespace Swift;
XMPPRosterSignalHandler::XMPPRosterSignalHandler(Swift::XMPPRoster* roster) : eventCount(0) {
- lastEvent_ = None;
- roster->onJIDAdded.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDAdded, this, _1));
- roster->onJIDRemoved.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDRemoved, this, _1));
- roster->onJIDUpdated.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDUpdated, this, _1, _2, _3));
+ lastEvent_ = None;
+ roster->onJIDAdded.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDAdded, this, _1));
+ roster->onJIDRemoved.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDRemoved, this, _1));
+ roster->onJIDUpdated.connect(boost::bind(&XMPPRosterSignalHandler::handleJIDUpdated, this, _1, _2, _3));
}
void XMPPRosterSignalHandler::handleJIDUpdated(const Swift::JID& jid, const std::string& oldName, const std::vector<std::string>& oldGroups) {
- assert(lastEvent_ == None);
- lastJID_ = jid;
- lastOldName_ = oldName;
- lastOldGroups_ = oldGroups;
- lastEvent_ = Update;
- eventCount++;
+ assert(lastEvent_ == None);
+ lastJID_ = jid;
+ lastOldName_ = oldName;
+ lastOldGroups_ = oldGroups;
+ lastEvent_ = Update;
+ eventCount++;
}
diff --git a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h
index d2beecf..9c9afad 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h
+++ b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h
@@ -16,50 +16,50 @@ enum XMPPRosterEvents {None, Add, Remove, Update};
class XMPPRosterSignalHandler {
public:
- XMPPRosterSignalHandler(Swift::XMPPRoster* roster);
+ XMPPRosterSignalHandler(Swift::XMPPRoster* roster);
- XMPPRosterEvents getLastEvent() {
- return lastEvent_;
- }
+ XMPPRosterEvents getLastEvent() {
+ return lastEvent_;
+ }
- Swift::JID getLastJID() {
- return lastJID_;
- }
+ Swift::JID getLastJID() {
+ return lastJID_;
+ }
- std::string getLastOldName() {
- return lastOldName_;
- }
+ std::string getLastOldName() {
+ return lastOldName_;
+ }
- std::vector<std::string> getLastOldGroups() {
- return lastOldGroups_;
- }
+ std::vector<std::string> getLastOldGroups() {
+ return lastOldGroups_;
+ }
- void reset() {
- lastEvent_ = None;
- }
+ void reset() {
+ lastEvent_ = None;
+ }
- int getEventCount() const {
- return eventCount;
- }
+ int getEventCount() const {
+ return eventCount;
+ }
private:
- void handleJIDAdded(const Swift::JID& jid) {
- lastJID_ = jid;
- lastEvent_ = Add;
- eventCount++;
- }
-
- void handleJIDRemoved(const Swift::JID& jid) {
- lastJID_ = jid;
- lastEvent_ = Remove;
- eventCount++;
- }
-
- void handleJIDUpdated(const Swift::JID& jid, const std::string& oldName, const std::vector<std::string>& oldGroups);
-
- XMPPRosterEvents lastEvent_;
- Swift::JID lastJID_;
- std::string lastOldName_;
- std::vector<std::string> lastOldGroups_;
- int eventCount;
+ void handleJIDAdded(const Swift::JID& jid) {
+ lastJID_ = jid;
+ lastEvent_ = Add;
+ eventCount++;
+ }
+
+ void handleJIDRemoved(const Swift::JID& jid) {
+ lastJID_ = jid;
+ lastEvent_ = Remove;
+ eventCount++;
+ }
+
+ void handleJIDUpdated(const Swift::JID& jid, const std::string& oldName, const std::vector<std::string>& oldGroups);
+
+ XMPPRosterEvents lastEvent_;
+ Swift::JID lastJID_;
+ std::string lastOldName_;
+ std::vector<std::string> lastOldGroups_;
+ int eventCount;
};
diff --git a/Swiften/Roster/XMPPRoster.h b/Swiften/Roster/XMPPRoster.h
index fdd1f9a..5e3a6b1 100644
--- a/Swiften/Roster/XMPPRoster.h
+++ b/Swiften/Roster/XMPPRoster.h
@@ -19,80 +19,80 @@
#include <Swiften/Roster/XMPPRosterItem.h>
namespace Swift {
- /**
- * This class represents the roster of an account, as stored on the XMPP server.
- *
- * Changes to the roster (either due to subscription requests or by going online/offline) are
- * emitted through signals.
- */
- class SWIFTEN_API XMPPRoster {
- public:
- XMPPRoster();
- virtual ~XMPPRoster();
-
- /**
- * Checks whether the bare jid of the given jid is in the roster.
- */
- virtual bool containsJID(const JID& jid) = 0;
-
- /**
- * Retrieves the subscription state for the given jid.
- */
- virtual RosterItemPayload::Subscription getSubscriptionStateForJID(const JID& jid) = 0;
-
- /**
- * Retrieves the stored roster name for the given jid.
- */
- virtual std::string getNameForJID(const JID& jid) const = 0;
-
- /**
- * Returns the list of groups for the given JID.
- */
- virtual std::vector<std::string> getGroupsForJID(const JID& jid) = 0;
-
- /**
- * Retrieve the items in the roster.
- */
- virtual std::vector<XMPPRosterItem> getItems() const = 0;
-
- /**
- * Retrieve the item with the given JID.
- */
- virtual boost::optional<XMPPRosterItem> getItem(const JID&) const = 0;
-
- /**
- * Retrieve the list of (existing) groups.
- */
- virtual std::set<std::string> getGroups() const = 0;
-
- public:
- /**
- * Emitted when the given JID is added to the roster.
- */
- boost::signal<void (const JID&)> onJIDAdded;
-
- /**
- * Emitted when the given JID is removed from the roster.
- */
- boost::signal<void (const JID&)> onJIDRemoved;
-
- /**
- * Emitted when the name or the groups of the roster item with the
- * given JID changes.
- */
- boost::signal<void (const JID&, const std::string&, const std::vector<std::string>&)> onJIDUpdated;
-
- /**
- * Emitted when the roster is reset (e.g. due to logging in/logging out).
- * After this signal is emitted, the roster is empty. It will be repopulated through
- * onJIDAdded and onJIDRemoved events.
- */
- boost::signal<void ()> onRosterCleared;
-
- /**
- * Emitted after the last contact of the initial roster request response
- * was added.
- */
- boost::signal<void ()> onInitialRosterPopulated;
- };
+ /**
+ * This class represents the roster of an account, as stored on the XMPP server.
+ *
+ * Changes to the roster (either due to subscription requests or by going online/offline) are
+ * emitted through signals.
+ */
+ class SWIFTEN_API XMPPRoster {
+ public:
+ XMPPRoster();
+ virtual ~XMPPRoster();
+
+ /**
+ * Checks whether the bare jid of the given jid is in the roster.
+ */
+ virtual bool containsJID(const JID& jid) = 0;
+
+ /**
+ * Retrieves the subscription state for the given jid.
+ */
+ virtual RosterItemPayload::Subscription getSubscriptionStateForJID(const JID& jid) = 0;
+
+ /**
+ * Retrieves the stored roster name for the given jid.
+ */
+ virtual std::string getNameForJID(const JID& jid) const = 0;
+
+ /**
+ * Returns the list of groups for the given JID.
+ */
+ virtual std::vector<std::string> getGroupsForJID(const JID& jid) = 0;
+
+ /**
+ * Retrieve the items in the roster.
+ */
+ virtual std::vector<XMPPRosterItem> getItems() const = 0;
+
+ /**
+ * Retrieve the item with the given JID.
+ */
+ virtual boost::optional<XMPPRosterItem> getItem(const JID&) const = 0;
+
+ /**
+ * Retrieve the list of (existing) groups.
+ */
+ virtual std::set<std::string> getGroups() const = 0;
+
+ public:
+ /**
+ * Emitted when the given JID is added to the roster.
+ */
+ boost::signal<void (const JID&)> onJIDAdded;
+
+ /**
+ * Emitted when the given JID is removed from the roster.
+ */
+ boost::signal<void (const JID&)> onJIDRemoved;
+
+ /**
+ * Emitted when the name or the groups of the roster item with the
+ * given JID changes.
+ */
+ boost::signal<void (const JID&, const std::string&, const std::vector<std::string>&)> onJIDUpdated;
+
+ /**
+ * Emitted when the roster is reset (e.g. due to logging in/logging out).
+ * After this signal is emitted, the roster is empty. It will be repopulated through
+ * onJIDAdded and onJIDRemoved events.
+ */
+ boost::signal<void ()> onRosterCleared;
+
+ /**
+ * Emitted after the last contact of the initial roster request response
+ * was added.
+ */
+ boost::signal<void ()> onInitialRosterPopulated;
+ };
}
diff --git a/Swiften/Roster/XMPPRosterController.cpp b/Swiften/Roster/XMPPRosterController.cpp
index 359e2ce..10803f3 100644
--- a/Swiften/Roster/XMPPRosterController.cpp
+++ b/Swiften/Roster/XMPPRosterController.cpp
@@ -18,76 +18,76 @@
#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, boost::shared_ptr<RosterPayload>()));
- rosterPushResponder_.start();
+ rosterPushResponder_.onRosterReceived.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, false, boost::shared_ptr<RosterPayload>()));
+ rosterPushResponder_.start();
}
XMPPRosterController::~XMPPRosterController() {
- rosterPushResponder_.stop();
+ rosterPushResponder_.stop();
}
void XMPPRosterController::requestRoster() {
- xmppRoster_->clear();
+ xmppRoster_->clear();
- boost::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();
+ boost::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(boost::shared_ptr<RosterPayload> rosterPayload, bool initial, boost::shared_ptr<RosterPayload> previousRoster) {
- if (rosterPayload) {
- foreach(const RosterItemPayload& 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()) {
- if (item.getSubscription() != RosterItemPayload::Remove) {
- xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
- }
- else {
- std::cerr << "ERROR: Stored invalid roster item" << std::endl;
- }
- }
- }
- if (initial) {
- xmppRoster_->onInitialRosterPopulated();
- }
- if (rosterPayload && rosterPayload->getVersion() && useVersioning) {
- saveRoster(*rosterPayload->getVersion());
- }
+ if (rosterPayload) {
+ foreach(const RosterItemPayload& 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()) {
+ if (item.getSubscription() != RosterItemPayload::Remove) {
+ xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
+ }
+ else {
+ std::cerr << "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();
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->setVersion(version);
- foreach(const XMPPRosterItem& item, items) {
- roster->addItem(RosterItemPayload(item.getJID(), item.getName(), item.getSubscription(), item.getGroups()));
- }
- rosterStorage_->setRoster(roster);
+ std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->setVersion(version);
+ foreach(const XMPPRosterItem& item, items) {
+ roster->addItem(RosterItemPayload(item.getJID(), item.getName(), item.getSubscription(), item.getGroups()));
+ }
+ rosterStorage_->setRoster(roster);
}
}
diff --git a/Swiften/Roster/XMPPRosterController.h b/Swiften/Roster/XMPPRosterController.h
index a23ed39..d40ba1e 100644
--- a/Swiften/Roster/XMPPRosterController.h
+++ b/Swiften/Roster/XMPPRosterController.h
@@ -18,31 +18,31 @@
#include <Swiften/Roster/RosterPushResponder.h>
namespace Swift {
- class IQRouter;
- class XMPPRosterImpl;
- class RosterStorage;
-
- class SWIFTEN_API XMPPRosterController {
- public:
- XMPPRosterController(IQRouter *iqRouter, XMPPRosterImpl* xmppRoster, RosterStorage* storage);
- ~XMPPRosterController();
-
- void requestRoster();
-
- void setUseVersioning(bool b) {
- useVersioning = b;
- }
-
- private:
- void handleRosterReceived(boost::shared_ptr<RosterPayload> rosterPayload, bool initial, boost::shared_ptr<RosterPayload> previousRoster);
- void saveRoster(const std::string& version);
-
- private:
- IQRouter* iqRouter_;
- RosterPushResponder rosterPushResponder_;
- XMPPRosterImpl* xmppRoster_;
- RosterStorage* rosterStorage_;
- bool useVersioning;
- };
+ class IQRouter;
+ class XMPPRosterImpl;
+ class RosterStorage;
+
+ class SWIFTEN_API XMPPRosterController {
+ public:
+ XMPPRosterController(IQRouter *iqRouter, XMPPRosterImpl* xmppRoster, RosterStorage* storage);
+ ~XMPPRosterController();
+
+ void requestRoster();
+
+ void setUseVersioning(bool b) {
+ useVersioning = b;
+ }
+
+ private:
+ void handleRosterReceived(boost::shared_ptr<RosterPayload> rosterPayload, bool initial, boost::shared_ptr<RosterPayload> previousRoster);
+ void saveRoster(const std::string& version);
+
+ private:
+ IQRouter* iqRouter_;
+ RosterPushResponder rosterPushResponder_;
+ XMPPRosterImpl* xmppRoster_;
+ RosterStorage* rosterStorage_;
+ bool useVersioning;
+ };
}
diff --git a/Swiften/Roster/XMPPRosterImpl.cpp b/Swiften/Roster/XMPPRosterImpl.cpp
index 96b9949..9a2ea7a 100644
--- a/Swiften/Roster/XMPPRosterImpl.cpp
+++ b/Swiften/Roster/XMPPRosterImpl.cpp
@@ -18,89 +18,89 @@ 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);
- }
+ 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);
+ entries_.erase(JID(jid.toBare()));
+ onJIDRemoved(jid);
}
void XMPPRosterImpl::clear() {
- entries_.clear();
- onRosterCleared();
+ entries_.clear();
+ onRosterCleared();
}
bool XMPPRosterImpl::containsJID(const JID& jid) {
- return entries_.find(JID(jid.toBare())) != entries_.end();
+ return entries_.find(JID(jid.toBare())) != entries_.end();
}
std::string XMPPRosterImpl::getNameForJID(const JID& jid) const {
- std::map<JID, XMPPRosterItem>::const_iterator i = entries_.find(jid.toBare());
- if (i != entries_.end()) {
- return i->second.getName();
- }
- else {
- return "";
- }
+ std::map<JID, XMPPRosterItem>::const_iterator i = entries_.find(jid.toBare());
+ 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>();
- }
+ 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::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_) {
- result.push_back(entry.second);
- }
- return result;
+ std::vector<XMPPRosterItem> result;
+ foreach(const RosterMap::value_type& 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::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_) {
- std::vector<std::string> groups = entry.second.getGroups();
- result.insert(groups.begin(), groups.end());
- }
- return result;
+ std::set<std::string> result;
+ foreach(const RosterMap::value_type& entry, entries_) {
+ std::vector<std::string> groups = entry.second.getGroups();
+ result.insert(groups.begin(), groups.end());
+ }
+ return result;
}
}
diff --git a/Swiften/Roster/XMPPRosterImpl.h b/Swiften/Roster/XMPPRosterImpl.h
index 284b18a..28e3919 100644
--- a/Swiften/Roster/XMPPRosterImpl.h
+++ b/Swiften/Roster/XMPPRosterImpl.h
@@ -13,26 +13,26 @@
#include <Swiften/Roster/XMPPRoster.h>
namespace Swift {
- class SWIFTEN_API XMPPRosterImpl : public XMPPRoster {
- public:
- XMPPRosterImpl();
- virtual ~XMPPRosterImpl();
-
- void addContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, RosterItemPayload::Subscription subscription);
- void removeContact(const JID& jid);
- void clear();
-
- bool containsJID(const JID& jid);
- RosterItemPayload::Subscription getSubscriptionStateForJID(const JID& jid);
- std::string getNameForJID(const JID& jid) const;
- std::vector<std::string> getGroupsForJID(const JID& jid);
-
- virtual std::vector<XMPPRosterItem> getItems() const;
- virtual boost::optional<XMPPRosterItem> getItem(const JID&) const;
- virtual std::set<std::string> getGroups() const;
-
- private:
- typedef std::map<JID, XMPPRosterItem> RosterMap;
- RosterMap entries_;
- };
+ class SWIFTEN_API XMPPRosterImpl : public XMPPRoster {
+ public:
+ XMPPRosterImpl();
+ virtual ~XMPPRosterImpl();
+
+ void addContact(const JID& jid, const std::string& name, const std::vector<std::string>& groups, RosterItemPayload::Subscription subscription);
+ void removeContact(const JID& jid);
+ void clear();
+
+ bool containsJID(const JID& jid);
+ RosterItemPayload::Subscription getSubscriptionStateForJID(const JID& jid);
+ std::string getNameForJID(const JID& jid) const;
+ std::vector<std::string> getGroupsForJID(const JID& jid);
+
+ virtual std::vector<XMPPRosterItem> getItems() const;
+ virtual boost::optional<XMPPRosterItem> getItem(const JID&) const;
+ virtual std::set<std::string> getGroups() const;
+
+ private:
+ typedef std::map<JID, XMPPRosterItem> RosterMap;
+ RosterMap entries_;
+ };
}
diff --git a/Swiften/Roster/XMPPRosterItem.h b/Swiften/Roster/XMPPRosterItem.h
index d46a678..53b3781 100644
--- a/Swiften/Roster/XMPPRosterItem.h
+++ b/Swiften/Roster/XMPPRosterItem.h
@@ -14,40 +14,40 @@
#include <Swiften/JID/JID.h>
namespace Swift {
- class SWIFTEN_API XMPPRosterItem {
- public:
- XMPPRosterItem(const JID& jid, const std::string& name, const std::vector<std::string>& groups, RosterItemPayload::Subscription subscription) : jid(jid), name(name), groups(groups), subscription(subscription) {
- }
-
- const JID& getJID() const {
- return jid;
- }
-
- const std::string& getName() const {
- return name;
- }
-
- void setName(const std::string& name) {
- this->name = name;
- }
-
- const std::vector<std::string>& getGroups() const {
- return groups;
- }
-
- void setGroups(const std::vector<std::string>& groups) {
- this->groups = groups;
- }
-
- RosterItemPayload::Subscription getSubscription() const {
- return subscription;
- }
-
- private:
- JID jid;
- std::string name;
- std::vector<std::string> groups;
- RosterItemPayload::Subscription subscription;
- };
+ class SWIFTEN_API XMPPRosterItem {
+ public:
+ XMPPRosterItem(const JID& jid, const std::string& name, const std::vector<std::string>& groups, RosterItemPayload::Subscription subscription) : jid(jid), name(name), groups(groups), subscription(subscription) {
+ }
+
+ const JID& getJID() const {
+ return jid;
+ }
+
+ const std::string& getName() const {
+ return name;
+ }
+
+ void setName(const std::string& name) {
+ this->name = name;
+ }
+
+ const std::vector<std::string>& getGroups() const {
+ return groups;
+ }
+
+ void setGroups(const std::vector<std::string>& groups) {
+ this->groups = groups;
+ }
+
+ RosterItemPayload::Subscription getSubscription() const {
+ return subscription;
+ }
+
+ private:
+ JID jid;
+ std::string name;
+ std::vector<std::string> groups;
+ RosterItemPayload::Subscription subscription;
+ };
}
diff --git a/Swiften/SASL/ClientAuthenticator.h b/Swiften/SASL/ClientAuthenticator.h
index eebdd8a..b22a81d 100644
--- a/Swiften/SASL/ClientAuthenticator.h
+++ b/Swiften/SASL/ClientAuthenticator.h
@@ -16,40 +16,40 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API ClientAuthenticator {
- public:
- ClientAuthenticator(const std::string& name);
- virtual ~ClientAuthenticator();
-
- const std::string& getName() const {
- return name;
- }
-
- void setCredentials(const std::string& authcid, const SafeByteArray& password, const std::string& authzid = std::string()) {
- this->authcid = authcid;
- this->password = password;
- this->authzid = authzid;
- }
-
- virtual boost::optional<SafeByteArray> getResponse() const = 0;
- virtual bool setChallenge(const boost::optional<ByteArray>&) = 0;
-
- const std::string& getAuthenticationID() const {
- return authcid;
- }
-
- const std::string& getAuthorizationID() const {
- return authzid;
- }
-
- const SafeByteArray& getPassword() const {
- return password;
- }
-
- private:
- std::string name;
- std::string authcid;
- SafeByteArray password;
- std::string authzid;
- };
+ class SWIFTEN_API ClientAuthenticator {
+ public:
+ ClientAuthenticator(const std::string& name);
+ virtual ~ClientAuthenticator();
+
+ const std::string& getName() const {
+ return name;
+ }
+
+ void setCredentials(const std::string& authcid, const SafeByteArray& password, const std::string& authzid = std::string()) {
+ this->authcid = authcid;
+ this->password = password;
+ this->authzid = authzid;
+ }
+
+ virtual boost::optional<SafeByteArray> getResponse() const = 0;
+ virtual bool setChallenge(const boost::optional<ByteArray>&) = 0;
+
+ const std::string& getAuthenticationID() const {
+ return authcid;
+ }
+
+ const std::string& getAuthorizationID() const {
+ return authzid;
+ }
+
+ const SafeByteArray& getPassword() const {
+ return password;
+ }
+
+ private:
+ std::string name;
+ std::string authcid;
+ SafeByteArray password;
+ std::string authzid;
+ };
}
diff --git a/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp b/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp
index 941c600..a736a77 100644
--- a/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp
+++ b/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp
@@ -19,78 +19,78 @@ DIGESTMD5ClientAuthenticator::DIGESTMD5ClientAuthenticator(const std::string& ho
}
boost::optional<SafeByteArray> DIGESTMD5ClientAuthenticator::getResponse() const {
- if (step == Initial) {
- return boost::optional<SafeByteArray>();
- }
- else if (step == Response) {
- std::string realm;
- if (challenge.getValue("realm")) {
- realm = *challenge.getValue("realm");
- }
- std::string qop = "auth";
- std::string digestURI = "xmpp/" + host;
- std::string nc = "00000001";
+ if (step == Initial) {
+ return boost::optional<SafeByteArray>();
+ }
+ else if (step == Response) {
+ std::string realm;
+ if (challenge.getValue("realm")) {
+ realm = *challenge.getValue("realm");
+ }
+ std::string qop = "auth";
+ std::string digestURI = "xmpp/" + host;
+ std::string nc = "00000001";
- // Compute the response value
- ByteArray A1 = concat(
- crypto->getMD5Hash(
- concat(createSafeByteArray(getAuthenticationID().c_str()), createSafeByteArray(":"), createSafeByteArray(realm.c_str()), createSafeByteArray(":"), getPassword())),
- createByteArray(":"), createByteArray(*challenge.getValue("nonce")), createByteArray(":"), createByteArray(cnonce));
- if (!getAuthorizationID().empty()) {
- append(A1, createByteArray(":" + getAuthenticationID()));
- }
- ByteArray A2 = createByteArray("AUTHENTICATE:" + digestURI);
+ // Compute the response value
+ ByteArray A1 = concat(
+ crypto->getMD5Hash(
+ concat(createSafeByteArray(getAuthenticationID().c_str()), createSafeByteArray(":"), createSafeByteArray(realm.c_str()), createSafeByteArray(":"), getPassword())),
+ createByteArray(":"), createByteArray(*challenge.getValue("nonce")), createByteArray(":"), createByteArray(cnonce));
+ if (!getAuthorizationID().empty()) {
+ append(A1, createByteArray(":" + getAuthenticationID()));
+ }
+ ByteArray A2 = createByteArray("AUTHENTICATE:" + digestURI);
- std::string responseValue = Hexify::hexify(crypto->getMD5Hash(createByteArray(
- Hexify::hexify(crypto->getMD5Hash(A1)) + ":"
- + *challenge.getValue("nonce") + ":" + nc + ":" + cnonce + ":" + qop + ":"
- + Hexify::hexify(crypto->getMD5Hash(A2)))));
+ std::string responseValue = Hexify::hexify(crypto->getMD5Hash(createByteArray(
+ Hexify::hexify(crypto->getMD5Hash(A1)) + ":"
+ + *challenge.getValue("nonce") + ":" + nc + ":" + cnonce + ":" + qop + ":"
+ + Hexify::hexify(crypto->getMD5Hash(A2)))));
- DIGESTMD5Properties response;
- response.setValue("username", getAuthenticationID());
- if (!realm.empty()) {
- response.setValue("realm", realm);
- }
- response.setValue("nonce", *challenge.getValue("nonce"));
- response.setValue("cnonce", cnonce);
- response.setValue("nc", "00000001");
- response.setValue("qop", qop);
- response.setValue("digest-uri", digestURI);
- response.setValue("charset", "utf-8");
- response.setValue("response", responseValue);
- if (!getAuthorizationID().empty()) {
- response.setValue("authzid", getAuthorizationID());
- }
- return createSafeByteArray(response.serialize());
- }
- else {
- return boost::optional<SafeByteArray>();
- }
+ DIGESTMD5Properties response;
+ response.setValue("username", getAuthenticationID());
+ if (!realm.empty()) {
+ response.setValue("realm", realm);
+ }
+ response.setValue("nonce", *challenge.getValue("nonce"));
+ response.setValue("cnonce", cnonce);
+ response.setValue("nc", "00000001");
+ response.setValue("qop", qop);
+ response.setValue("digest-uri", digestURI);
+ response.setValue("charset", "utf-8");
+ response.setValue("response", responseValue);
+ if (!getAuthorizationID().empty()) {
+ response.setValue("authzid", getAuthorizationID());
+ }
+ return createSafeByteArray(response.serialize());
+ }
+ else {
+ return boost::optional<SafeByteArray>();
+ }
}
bool DIGESTMD5ClientAuthenticator::setChallenge(const boost::optional<ByteArray>& challengeData) {
- if (step == Initial) {
- if (!challengeData) {
- return false;
- }
- challenge = DIGESTMD5Properties::parse(*challengeData);
+ if (step == Initial) {
+ if (!challengeData) {
+ return false;
+ }
+ challenge = DIGESTMD5Properties::parse(*challengeData);
- // Sanity checks
- if (!challenge.getValue("nonce")) {
- return false;
- }
- if (!challenge.getValue("charset") || *challenge.getValue("charset") != "utf-8") {
- return false;
- }
- step = Response;
- return true;
- }
- else {
- step = Final;
- // TODO: Check RSPAuth
- return true;
- }
+ // Sanity checks
+ if (!challenge.getValue("nonce")) {
+ return false;
+ }
+ if (!challenge.getValue("charset") || *challenge.getValue("charset") != "utf-8") {
+ return false;
+ }
+ step = Response;
+ return true;
+ }
+ else {
+ step = Final;
+ // TODO: Check RSPAuth
+ return true;
+ }
}
}
diff --git a/Swiften/SASL/DIGESTMD5ClientAuthenticator.h b/Swiften/SASL/DIGESTMD5ClientAuthenticator.h
index 6209e40..4a857d3 100644
--- a/Swiften/SASL/DIGESTMD5ClientAuthenticator.h
+++ b/Swiften/SASL/DIGESTMD5ClientAuthenticator.h
@@ -16,24 +16,24 @@
#include <Swiften/SASL/DIGESTMD5Properties.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class SWIFTEN_API DIGESTMD5ClientAuthenticator : public ClientAuthenticator {
- public:
- DIGESTMD5ClientAuthenticator(const std::string& host, const std::string& nonce, CryptoProvider*);
-
- virtual boost::optional<SafeByteArray> getResponse() const;
- virtual bool setChallenge(const boost::optional<std::vector<unsigned char> >&);
+ class SWIFTEN_API DIGESTMD5ClientAuthenticator : public ClientAuthenticator {
+ public:
+ DIGESTMD5ClientAuthenticator(const std::string& host, const std::string& nonce, CryptoProvider*);
- private:
- enum Step {
- Initial,
- Response,
- Final
- } step;
- std::string host;
- std::string cnonce;
- CryptoProvider* crypto;
- DIGESTMD5Properties challenge;
- };
+ virtual boost::optional<SafeByteArray> getResponse() const;
+ virtual bool setChallenge(const boost::optional<std::vector<unsigned char> >&);
+
+ private:
+ enum Step {
+ Initial,
+ Response,
+ Final
+ } step;
+ std::string host;
+ std::string cnonce;
+ CryptoProvider* crypto;
+ DIGESTMD5Properties challenge;
+ };
}
diff --git a/Swiften/SASL/DIGESTMD5Properties.cpp b/Swiften/SASL/DIGESTMD5Properties.cpp
index 157261a..baf0197 100644
--- a/Swiften/SASL/DIGESTMD5Properties.cpp
+++ b/Swiften/SASL/DIGESTMD5Properties.cpp
@@ -11,121 +11,121 @@
namespace Swift {
namespace {
- bool insideQuotes(const ByteArray& v) {
- if (v.empty()) {
- return false;
- }
- else if (v.size() == 1) {
- return v[0] == '"';
- }
- else if (v[0] == '"') {
- return v[v.size() - 1] != '"';
- }
- else {
- return false;
- }
- }
+ bool insideQuotes(const ByteArray& v) {
+ if (v.empty()) {
+ return false;
+ }
+ else if (v.size() == 1) {
+ return v[0] == '"';
+ }
+ else if (v[0] == '"') {
+ return v[v.size() - 1] != '"';
+ }
+ else {
+ return false;
+ }
+ }
- ByteArray stripQuotes(const ByteArray& v) {
- const char* data = reinterpret_cast<const char*>(vecptr(v));
- size_t size = v.size();
- if (v[0] == '"') {
- data++;
- size--;
- }
- if (v[v.size() - 1] == '"') {
- size--;
- }
- return createByteArray(data, size);
- }
+ ByteArray stripQuotes(const ByteArray& v) {
+ const char* data = reinterpret_cast<const char*>(vecptr(v));
+ size_t size = v.size();
+ if (v[0] == '"') {
+ data++;
+ size--;
+ }
+ if (v[v.size() - 1] == '"') {
+ size--;
+ }
+ return createByteArray(data, size);
+ }
}
DIGESTMD5Properties::DIGESTMD5Properties() {
}
DIGESTMD5Properties DIGESTMD5Properties::parse(const ByteArray& data) {
- DIGESTMD5Properties result;
- bool inKey = true;
- ByteArray currentKey;
- ByteArray currentValue;
- for (size_t i = 0; i < data.size(); ++i) {
- char c = static_cast<char>(data[i]);
- if (inKey) {
- if (c == '=') {
- inKey = false;
- }
- else {
- currentKey.push_back(static_cast<unsigned char>(c));
- }
- }
- else {
- if (c == ',' && !insideQuotes(currentValue)) {
- std::string key = byteArrayToString(currentKey);
- if (isQuoted(key)) {
- result.setValue(key, byteArrayToString(stripQuotes(currentValue)));
- }
- else {
- result.setValue(key, byteArrayToString(currentValue));
- }
- inKey = true;
- currentKey = ByteArray();
- currentValue = ByteArray();
- }
- else {
- currentValue.push_back(static_cast<unsigned char>(c));
- }
- }
- }
+ DIGESTMD5Properties result;
+ bool inKey = true;
+ ByteArray currentKey;
+ ByteArray currentValue;
+ for (size_t i = 0; i < data.size(); ++i) {
+ char c = static_cast<char>(data[i]);
+ if (inKey) {
+ if (c == '=') {
+ inKey = false;
+ }
+ else {
+ currentKey.push_back(static_cast<unsigned char>(c));
+ }
+ }
+ else {
+ if (c == ',' && !insideQuotes(currentValue)) {
+ std::string key = byteArrayToString(currentKey);
+ if (isQuoted(key)) {
+ result.setValue(key, byteArrayToString(stripQuotes(currentValue)));
+ }
+ else {
+ result.setValue(key, byteArrayToString(currentValue));
+ }
+ inKey = true;
+ currentKey = ByteArray();
+ currentValue = ByteArray();
+ }
+ else {
+ currentValue.push_back(static_cast<unsigned char>(c));
+ }
+ }
+ }
- if (!currentKey.empty()) {
- std::string key = byteArrayToString(currentKey);
- if (isQuoted(key)) {
- result.setValue(key, byteArrayToString(stripQuotes(currentValue)));
- }
- else {
- result.setValue(key, byteArrayToString(currentValue));
- }
- }
+ if (!currentKey.empty()) {
+ std::string key = byteArrayToString(currentKey);
+ if (isQuoted(key)) {
+ result.setValue(key, byteArrayToString(stripQuotes(currentValue)));
+ }
+ else {
+ result.setValue(key, byteArrayToString(currentValue));
+ }
+ }
- return result;
+ return result;
}
ByteArray DIGESTMD5Properties::serialize() const {
- ByteArray result;
- for(DIGESTMD5PropertiesMap::const_iterator i = properties.begin(); i != properties.end(); ++i) {
- if (i != properties.begin()) {
- result.push_back(',');
- }
- append(result, createByteArray(i->first));
- result.push_back('=');
- if (isQuoted(i->first)) {
- append(result, createByteArray("\""));
- append(result, i->second);
- append(result, createByteArray("\""));
- }
- else {
- append(result, i->second);
- }
- }
- return result;
+ ByteArray result;
+ for(DIGESTMD5PropertiesMap::const_iterator i = properties.begin(); i != properties.end(); ++i) {
+ if (i != properties.begin()) {
+ result.push_back(',');
+ }
+ append(result, createByteArray(i->first));
+ result.push_back('=');
+ if (isQuoted(i->first)) {
+ append(result, createByteArray("\""));
+ append(result, i->second);
+ append(result, createByteArray("\""));
+ }
+ else {
+ append(result, i->second);
+ }
+ }
+ return result;
}
boost::optional<std::string> DIGESTMD5Properties::getValue(const std::string& key) const {
- DIGESTMD5PropertiesMap::const_iterator i = properties.find(key);
- if (i != properties.end()) {
- return byteArrayToString(i->second);
- }
- else {
- return boost::optional<std::string>();
- }
+ DIGESTMD5PropertiesMap::const_iterator i = properties.find(key);
+ if (i != properties.end()) {
+ return byteArrayToString(i->second);
+ }
+ else {
+ return boost::optional<std::string>();
+ }
}
void DIGESTMD5Properties::setValue(const std::string& key, const std::string& value) {
- properties.insert(DIGESTMD5PropertiesMap::value_type(key, createByteArray(value)));
+ properties.insert(DIGESTMD5PropertiesMap::value_type(key, createByteArray(value)));
}
bool DIGESTMD5Properties::isQuoted(const std::string& p) {
- return p == "authzid" || p == "cnonce" || p == "digest-uri" || p == "nonce" || p == "realm" || p == "username";
+ return p == "authzid" || p == "cnonce" || p == "digest-uri" || p == "nonce" || p == "realm" || p == "username";
}
}
diff --git a/Swiften/SASL/DIGESTMD5Properties.h b/Swiften/SASL/DIGESTMD5Properties.h
index 5ab8fd9..a4d2d65 100644
--- a/Swiften/SASL/DIGESTMD5Properties.h
+++ b/Swiften/SASL/DIGESTMD5Properties.h
@@ -15,23 +15,23 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- class SWIFTEN_API DIGESTMD5Properties {
- public:
- DIGESTMD5Properties();
-
- boost::optional<std::string> getValue(const std::string& key) const;
+ class SWIFTEN_API DIGESTMD5Properties {
+ public:
+ DIGESTMD5Properties();
- void setValue(const std::string& key, const std::string& value);
+ boost::optional<std::string> getValue(const std::string& key) const;
- ByteArray serialize() const;
+ void setValue(const std::string& key, const std::string& value);
- static DIGESTMD5Properties parse(const ByteArray&);
+ ByteArray serialize() const;
- private:
- static bool isQuoted(const std::string& property);
+ static DIGESTMD5Properties parse(const ByteArray&);
- private:
- typedef std::multimap<std::string, ByteArray> DIGESTMD5PropertiesMap;
- DIGESTMD5PropertiesMap properties;
- };
+ private:
+ static bool isQuoted(const std::string& property);
+
+ private:
+ typedef std::multimap<std::string, ByteArray> DIGESTMD5PropertiesMap;
+ DIGESTMD5PropertiesMap properties;
+ };
}
diff --git a/Swiften/SASL/EXTERNALClientAuthenticator.cpp b/Swiften/SASL/EXTERNALClientAuthenticator.cpp
index 2dc9cc8..546140f 100644
--- a/Swiften/SASL/EXTERNALClientAuthenticator.cpp
+++ b/Swiften/SASL/EXTERNALClientAuthenticator.cpp
@@ -12,15 +12,15 @@ EXTERNALClientAuthenticator::EXTERNALClientAuthenticator() : ClientAuthenticator
}
boost::optional<SafeByteArray> EXTERNALClientAuthenticator::getResponse() const {
- return boost::optional<SafeByteArray>();
+ return boost::optional<SafeByteArray>();
}
bool EXTERNALClientAuthenticator::setChallenge(const boost::optional<ByteArray>&) {
- if (finished) {
- return false;
- }
- finished = true;
- return true;
+ if (finished) {
+ return false;
+ }
+ finished = true;
+ return true;
}
}
diff --git a/Swiften/SASL/EXTERNALClientAuthenticator.h b/Swiften/SASL/EXTERNALClientAuthenticator.h
index 8ac05bd..e42e3fd 100644
--- a/Swiften/SASL/EXTERNALClientAuthenticator.h
+++ b/Swiften/SASL/EXTERNALClientAuthenticator.h
@@ -11,14 +11,14 @@
#include <Swiften/SASL/ClientAuthenticator.h>
namespace Swift {
- class SWIFTEN_API EXTERNALClientAuthenticator : public ClientAuthenticator {
- public:
- EXTERNALClientAuthenticator();
+ class SWIFTEN_API EXTERNALClientAuthenticator : public ClientAuthenticator {
+ public:
+ EXTERNALClientAuthenticator();
- virtual boost::optional<SafeByteArray> getResponse() const;
- virtual bool setChallenge(const boost::optional<ByteArray>&);
+ virtual boost::optional<SafeByteArray> getResponse() const;
+ virtual bool setChallenge(const boost::optional<ByteArray>&);
- private:
- bool finished;
- };
+ private:
+ bool finished;
+ };
}
diff --git a/Swiften/SASL/PLAINClientAuthenticator.cpp b/Swiften/SASL/PLAINClientAuthenticator.cpp
index 7b8bf09..11bd14c 100644
--- a/Swiften/SASL/PLAINClientAuthenticator.cpp
+++ b/Swiften/SASL/PLAINClientAuthenticator.cpp
@@ -14,11 +14,11 @@ PLAINClientAuthenticator::PLAINClientAuthenticator() : ClientAuthenticator("PLAI
}
boost::optional<SafeByteArray> PLAINClientAuthenticator::getResponse() const {
- return concat(createSafeByteArray(getAuthorizationID()), createSafeByteArray('\0'), createSafeByteArray(getAuthenticationID()), createSafeByteArray('\0'), getPassword());
+ return concat(createSafeByteArray(getAuthorizationID()), createSafeByteArray('\0'), createSafeByteArray(getAuthenticationID()), createSafeByteArray('\0'), getPassword());
}
bool PLAINClientAuthenticator::setChallenge(const boost::optional<ByteArray>&) {
- return true;
+ return true;
}
}
diff --git a/Swiften/SASL/PLAINClientAuthenticator.h b/Swiften/SASL/PLAINClientAuthenticator.h
index bdf5eef..64ef741 100644
--- a/Swiften/SASL/PLAINClientAuthenticator.h
+++ b/Swiften/SASL/PLAINClientAuthenticator.h
@@ -11,11 +11,11 @@
#include <Swiften/SASL/ClientAuthenticator.h>
namespace Swift {
- class SWIFTEN_API PLAINClientAuthenticator : public ClientAuthenticator {
- public:
- PLAINClientAuthenticator();
+ class SWIFTEN_API PLAINClientAuthenticator : public ClientAuthenticator {
+ public:
+ PLAINClientAuthenticator();
- virtual boost::optional<SafeByteArray> getResponse() const;
- virtual bool setChallenge(const boost::optional<ByteArray>&);
- };
+ virtual boost::optional<SafeByteArray> getResponse() const;
+ virtual bool setChallenge(const boost::optional<ByteArray>&);
+ };
}
diff --git a/Swiften/SASL/PLAINMessage.cpp b/Swiften/SASL/PLAINMessage.cpp
index 405f57d..a55f604 100644
--- a/Swiften/SASL/PLAINMessage.cpp
+++ b/Swiften/SASL/PLAINMessage.cpp
@@ -14,32 +14,32 @@ PLAINMessage::PLAINMessage(const std::string& authcid, const SafeByteArray& pass
}
PLAINMessage::PLAINMessage(const SafeByteArray& value) {
- size_t i = 0;
- while (i < value.size() && value[i] != '\0') {
- authzid += static_cast<char>(value[i]);
- ++i;
- }
- if (i == value.size()) {
- return;
- }
- ++i;
- while (i < value.size() && value[i] != '\0') {
- authcid += static_cast<char>(value[i]);
- ++i;
- }
- if (i == value.size()) {
- authcid = "";
- return;
- }
- ++i;
- while (i < value.size()) {
- password.push_back(value[i]);
- ++i;
- }
+ size_t i = 0;
+ while (i < value.size() && value[i] != '\0') {
+ authzid += static_cast<char>(value[i]);
+ ++i;
+ }
+ if (i == value.size()) {
+ return;
+ }
+ ++i;
+ while (i < value.size() && value[i] != '\0') {
+ authcid += static_cast<char>(value[i]);
+ ++i;
+ }
+ if (i == value.size()) {
+ authcid = "";
+ return;
+ }
+ ++i;
+ while (i < value.size()) {
+ password.push_back(value[i]);
+ ++i;
+ }
}
SafeByteArray PLAINMessage::getValue() const {
- return concat(createSafeByteArray(authzid), createSafeByteArray('\0'), createSafeByteArray(authcid), createSafeByteArray('\0'), password);
+ return concat(createSafeByteArray(authzid), createSafeByteArray('\0'), createSafeByteArray(authcid), createSafeByteArray('\0'), password);
}
}
diff --git a/Swiften/SASL/PLAINMessage.h b/Swiften/SASL/PLAINMessage.h
index b7ebbdf..80479f9 100644
--- a/Swiften/SASL/PLAINMessage.h
+++ b/Swiften/SASL/PLAINMessage.h
@@ -14,28 +14,28 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API PLAINMessage {
- public:
- PLAINMessage(const std::string& authcid, const SafeByteArray& password, const std::string& authzid = "");
- PLAINMessage(const SafeByteArray& value);
-
- SafeByteArray getValue() const;
-
- const std::string& getAuthenticationID() const {
- return authcid;
- }
-
- const SafeByteArray& getPassword() const {
- return password;
- }
-
- const std::string& getAuthorizationID() const {
- return authzid;
- }
-
- private:
- std::string authcid;
- std::string authzid;
- SafeByteArray password;
- };
+ class SWIFTEN_API PLAINMessage {
+ public:
+ PLAINMessage(const std::string& authcid, const SafeByteArray& password, const std::string& authzid = "");
+ PLAINMessage(const SafeByteArray& value);
+
+ SafeByteArray getValue() const;
+
+ const std::string& getAuthenticationID() const {
+ return authcid;
+ }
+
+ const SafeByteArray& getPassword() const {
+ return password;
+ }
+
+ const std::string& getAuthorizationID() const {
+ return authzid;
+ }
+
+ private:
+ std::string authcid;
+ std::string authzid;
+ SafeByteArray password;
+ };
}
diff --git a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp
index 88bed0f..2374d15 100644
--- a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp
+++ b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp
@@ -20,19 +20,19 @@
namespace Swift {
static std::string escape(const std::string& s) {
- std::string result;
- for (size_t i = 0; i < s.size(); ++i) {
- if (s[i] == ',') {
- result += "=2C";
- }
- else if (s[i] == '=') {
- result += "=3D";
- }
- else {
- result += s[i];
- }
- }
- return result;
+ std::string result;
+ for (size_t i = 0; i < s.size(); ++i) {
+ if (s[i] == ',') {
+ result += "=2C";
+ }
+ else if (s[i] == '=') {
+ result += "=3D";
+ }
+ else {
+ result += s[i];
+ }
+ }
+ return result;
}
@@ -40,144 +40,144 @@ SCRAMSHA1ClientAuthenticator::SCRAMSHA1ClientAuthenticator(const std::string& no
}
boost::optional<SafeByteArray> SCRAMSHA1ClientAuthenticator::getResponse() const {
- if (step == Initial) {
- return createSafeByteArray(concat(getGS2Header(), getInitialBareClientMessage()));
- }
- else if (step == Proof) {
- ByteArray clientKey = crypto->getHMACSHA1(saltedPassword, createByteArray("Client Key"));
- ByteArray storedKey = crypto->getSHA1Hash(clientKey);
- ByteArray clientSignature = crypto->getHMACSHA1(createSafeByteArray(storedKey), authMessage);
- ByteArray clientProof = clientKey;
- for (unsigned int i = 0; i < clientProof.size(); ++i) {
- clientProof[i] ^= clientSignature[i];
- }
- ByteArray result = concat(getFinalMessageWithoutProof(), createByteArray(",p="), createByteArray(Base64::encode(clientProof)));
- return createSafeByteArray(result);
- }
- else {
- return boost::optional<SafeByteArray>();
- }
+ if (step == Initial) {
+ return createSafeByteArray(concat(getGS2Header(), getInitialBareClientMessage()));
+ }
+ else if (step == Proof) {
+ ByteArray clientKey = crypto->getHMACSHA1(saltedPassword, createByteArray("Client Key"));
+ ByteArray storedKey = crypto->getSHA1Hash(clientKey);
+ ByteArray clientSignature = crypto->getHMACSHA1(createSafeByteArray(storedKey), authMessage);
+ ByteArray clientProof = clientKey;
+ for (unsigned int i = 0; i < clientProof.size(); ++i) {
+ clientProof[i] ^= clientSignature[i];
+ }
+ ByteArray result = concat(getFinalMessageWithoutProof(), createByteArray(",p="), createByteArray(Base64::encode(clientProof)));
+ return createSafeByteArray(result);
+ }
+ else {
+ return boost::optional<SafeByteArray>();
+ }
}
bool SCRAMSHA1ClientAuthenticator::setChallenge(const boost::optional<ByteArray>& challenge) {
- if (step == Initial) {
- if (!challenge) {
- return false;
- }
- initialServerMessage = *challenge;
-
- std::map<char, std::string> keys = parseMap(byteArrayToString(initialServerMessage));
-
- // Extract the salt
- ByteArray salt = Base64::decode(keys['s']);
-
- // Extract the server nonce
- std::string clientServerNonce = keys['r'];
- if (clientServerNonce.size() <= clientnonce.size()) {
- return false;
- }
- std::string receivedClientNonce = clientServerNonce.substr(0, clientnonce.size());
- if (receivedClientNonce != clientnonce) {
- return false;
- }
- serverNonce = createByteArray(clientServerNonce.substr(clientnonce.size(), clientServerNonce.npos));
-
- // Extract the number of iterations
- int iterations = 0;
- try {
- iterations = boost::lexical_cast<int>(keys['i']);
- }
- catch (const boost::bad_lexical_cast&) {
- return false;
- }
- if (iterations <= 0) {
- return false;
- }
-
- // Compute all the values needed for the server signature
- try {
- saltedPassword = PBKDF2::encode(idnConverter->getStringPrepared(getPassword(), IDNConverter::SASLPrep), salt, iterations, crypto);
- }
- catch (const std::exception&) {
- }
- authMessage = concat(getInitialBareClientMessage(), createByteArray(","), initialServerMessage, createByteArray(","), getFinalMessageWithoutProof());
- ByteArray serverKey = crypto->getHMACSHA1(saltedPassword, createByteArray("Server Key"));
- serverSignature = crypto->getHMACSHA1(serverKey, authMessage);
-
- step = Proof;
- return true;
- }
- else if (step == Proof) {
- ByteArray result = concat(createByteArray("v="), createByteArray(Base64::encode(serverSignature)));
- step = Final;
- return challenge && challenge == result;
- }
- else {
- return true;
- }
+ if (step == Initial) {
+ if (!challenge) {
+ return false;
+ }
+ initialServerMessage = *challenge;
+
+ std::map<char, std::string> keys = parseMap(byteArrayToString(initialServerMessage));
+
+ // Extract the salt
+ ByteArray salt = Base64::decode(keys['s']);
+
+ // Extract the server nonce
+ std::string clientServerNonce = keys['r'];
+ if (clientServerNonce.size() <= clientnonce.size()) {
+ return false;
+ }
+ std::string receivedClientNonce = clientServerNonce.substr(0, clientnonce.size());
+ if (receivedClientNonce != clientnonce) {
+ return false;
+ }
+ serverNonce = createByteArray(clientServerNonce.substr(clientnonce.size(), clientServerNonce.npos));
+
+ // Extract the number of iterations
+ int iterations = 0;
+ try {
+ iterations = boost::lexical_cast<int>(keys['i']);
+ }
+ catch (const boost::bad_lexical_cast&) {
+ return false;
+ }
+ if (iterations <= 0) {
+ return false;
+ }
+
+ // Compute all the values needed for the server signature
+ try {
+ saltedPassword = PBKDF2::encode(idnConverter->getStringPrepared(getPassword(), IDNConverter::SASLPrep), salt, iterations, crypto);
+ }
+ catch (const std::exception&) {
+ }
+ authMessage = concat(getInitialBareClientMessage(), createByteArray(","), initialServerMessage, createByteArray(","), getFinalMessageWithoutProof());
+ ByteArray serverKey = crypto->getHMACSHA1(saltedPassword, createByteArray("Server Key"));
+ serverSignature = crypto->getHMACSHA1(serverKey, authMessage);
+
+ step = Proof;
+ return true;
+ }
+ else if (step == Proof) {
+ ByteArray result = concat(createByteArray("v="), createByteArray(Base64::encode(serverSignature)));
+ step = Final;
+ return challenge && challenge == result;
+ }
+ else {
+ return true;
+ }
}
std::map<char, std::string> SCRAMSHA1ClientAuthenticator::parseMap(const std::string& s) {
- std::map<char, std::string> result;
- if (s.size() > 0) {
- char key = 0;
- std::string value;
- size_t i = 0;
- bool expectKey = true;
- while (i < s.size()) {
- if (expectKey) {
- key = s[i];
- expectKey = false;
- i++;
- }
- else if (s[i] == ',') {
- result[key] = value;
- value = "";
- expectKey = true;
- }
- else {
- value += s[i];
- }
- i++;
- }
- result[key] = value;
- }
- return result;
+ std::map<char, std::string> result;
+ if (s.size() > 0) {
+ char key = 0;
+ std::string value;
+ size_t i = 0;
+ bool expectKey = true;
+ while (i < s.size()) {
+ if (expectKey) {
+ key = s[i];
+ expectKey = false;
+ i++;
+ }
+ else if (s[i] == ',') {
+ result[key] = value;
+ value = "";
+ expectKey = true;
+ }
+ else {
+ value += s[i];
+ }
+ i++;
+ }
+ result[key] = value;
+ }
+ return result;
}
ByteArray SCRAMSHA1ClientAuthenticator::getInitialBareClientMessage() const {
- std::string authenticationID;
- try {
- authenticationID = idnConverter->getStringPrepared(getAuthenticationID(), IDNConverter::SASLPrep);
- }
- catch (const std::exception&) {
- }
- return createByteArray(std::string("n=" + escape(authenticationID) + ",r=" + clientnonce));
+ std::string authenticationID;
+ try {
+ authenticationID = idnConverter->getStringPrepared(getAuthenticationID(), IDNConverter::SASLPrep);
+ }
+ catch (const std::exception&) {
+ }
+ return createByteArray(std::string("n=" + escape(authenticationID) + ",r=" + clientnonce));
}
ByteArray SCRAMSHA1ClientAuthenticator::getGS2Header() const {
- ByteArray channelBindingHeader(createByteArray("n"));
- if (tlsChannelBindingData) {
- if (useChannelBinding) {
- channelBindingHeader = createByteArray("p=tls-unique");
- }
- else {
- channelBindingHeader = createByteArray("y");
- }
- }
- return concat(channelBindingHeader, createByteArray(","), (getAuthorizationID().empty() ? ByteArray() : createByteArray("a=" + escape(getAuthorizationID()))), createByteArray(","));
+ ByteArray channelBindingHeader(createByteArray("n"));
+ if (tlsChannelBindingData) {
+ if (useChannelBinding) {
+ channelBindingHeader = createByteArray("p=tls-unique");
+ }
+ else {
+ channelBindingHeader = createByteArray("y");
+ }
+ }
+ return concat(channelBindingHeader, createByteArray(","), (getAuthorizationID().empty() ? ByteArray() : createByteArray("a=" + escape(getAuthorizationID()))), createByteArray(","));
}
void SCRAMSHA1ClientAuthenticator::setTLSChannelBindingData(const ByteArray& channelBindingData) {
- this->tlsChannelBindingData = channelBindingData;
+ this->tlsChannelBindingData = channelBindingData;
}
ByteArray SCRAMSHA1ClientAuthenticator::getFinalMessageWithoutProof() const {
- ByteArray channelBindData;
- if (useChannelBinding && tlsChannelBindingData) {
- channelBindData = *tlsChannelBindingData;
- }
- return concat(createByteArray("c=" + Base64::encode(concat(getGS2Header(), channelBindData)) + ",r=" + clientnonce), serverNonce);
+ ByteArray channelBindData;
+ if (useChannelBinding && tlsChannelBindingData) {
+ channelBindData = *tlsChannelBindingData;
+ }
+ return concat(createByteArray("c=" + Base64::encode(concat(getGS2Header(), channelBindData)) + ",r=" + clientnonce), serverNonce);
}
diff --git a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h
index bc9bd97..5dc169a 100644
--- a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h
+++ b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h
@@ -16,40 +16,40 @@
#include <Swiften/SASL/ClientAuthenticator.h>
namespace Swift {
- class IDNConverter;
- class CryptoProvider;
-
- class SWIFTEN_API SCRAMSHA1ClientAuthenticator : public ClientAuthenticator {
- public:
- SCRAMSHA1ClientAuthenticator(const std::string& nonce, bool useChannelBinding, IDNConverter*, CryptoProvider*);
-
- void setTLSChannelBindingData(const ByteArray& channelBindingData);
-
- virtual boost::optional<SafeByteArray> getResponse() const;
- virtual bool setChallenge(const boost::optional<ByteArray>&);
-
- private:
- ByteArray getInitialBareClientMessage() const;
- ByteArray getGS2Header() const;
- ByteArray getFinalMessageWithoutProof() const;
-
- static std::map<char, std::string> parseMap(const std::string&);
-
- private:
- enum Step {
- Initial,
- Proof,
- Final
- } step;
- std::string clientnonce;
- ByteArray initialServerMessage;
- ByteArray serverNonce;
- ByteArray authMessage;
- ByteArray saltedPassword;
- ByteArray serverSignature;
- bool useChannelBinding;
- IDNConverter* idnConverter;
- CryptoProvider* crypto;
- boost::optional<ByteArray> tlsChannelBindingData;
- };
+ class IDNConverter;
+ class CryptoProvider;
+
+ class SWIFTEN_API SCRAMSHA1ClientAuthenticator : public ClientAuthenticator {
+ public:
+ SCRAMSHA1ClientAuthenticator(const std::string& nonce, bool useChannelBinding, IDNConverter*, CryptoProvider*);
+
+ void setTLSChannelBindingData(const ByteArray& channelBindingData);
+
+ virtual boost::optional<SafeByteArray> getResponse() const;
+ virtual bool setChallenge(const boost::optional<ByteArray>&);
+
+ private:
+ ByteArray getInitialBareClientMessage() const;
+ ByteArray getGS2Header() const;
+ ByteArray getFinalMessageWithoutProof() const;
+
+ static std::map<char, std::string> parseMap(const std::string&);
+
+ private:
+ enum Step {
+ Initial,
+ Proof,
+ Final
+ } step;
+ std::string clientnonce;
+ ByteArray initialServerMessage;
+ ByteArray serverNonce;
+ ByteArray authMessage;
+ ByteArray saltedPassword;
+ ByteArray serverSignature;
+ bool useChannelBinding;
+ IDNConverter* idnConverter;
+ CryptoProvider* crypto;
+ boost::optional<ByteArray> tlsChannelBindingData;
+ };
}
diff --git a/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp b/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
index e8c613f..04e2df5 100644
--- a/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
@@ -17,54 +17,54 @@
using namespace Swift;
class DIGESTMD5ClientAuthenticatorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DIGESTMD5ClientAuthenticatorTest);
- CPPUNIT_TEST(testGetInitialResponse);
- CPPUNIT_TEST(testGetResponse);
- CPPUNIT_TEST(testGetResponse_WithAuthorizationID);
- //CPPUNIT_TEST(testSetChallenge);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
-
- void testGetInitialResponse() {
- DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
-
- CPPUNIT_ASSERT(!testling.getResponse());
- }
-
- void testGetResponse() {
- DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
-
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setChallenge(createByteArray(
- "realm=\"example.com\","
- "nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\","
- "qop=auth,charset=utf-8,algorithm=md5-sess"));
-
- SafeByteArray response = *testling.getResponse();
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("charset=utf-8,cnonce=\"abcdefgh\",digest-uri=\"xmpp/xmpp.example.com\",nc=00000001,nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\",qop=auth,realm=\"example.com\",response=088891c800ecff1b842159ad6459104a,username=\"user\""), response);
- }
-
- void testGetResponse_WithAuthorizationID() {
- DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
-
- testling.setCredentials("user", createSafeByteArray("pass"), "myauthzid");
- testling.setChallenge(createByteArray(
- "realm=\"example.com\","
- "nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\","
- "qop=auth,charset=utf-8,algorithm=md5-sess"));
-
- SafeByteArray response = *testling.getResponse();
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("authzid=\"myauthzid\",charset=utf-8,cnonce=\"abcdefgh\",digest-uri=\"xmpp/xmpp.example.com\",nc=00000001,nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\",qop=auth,realm=\"example.com\",response=4293834432b6e7889a2dee7e8fe7dd06,username=\"user\""), response);
- }
-
- private:
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(DIGESTMD5ClientAuthenticatorTest);
+ CPPUNIT_TEST(testGetInitialResponse);
+ CPPUNIT_TEST(testGetResponse);
+ CPPUNIT_TEST(testGetResponse_WithAuthorizationID);
+ //CPPUNIT_TEST(testSetChallenge);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
+
+ void testGetInitialResponse() {
+ DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
+
+ CPPUNIT_ASSERT(!testling.getResponse());
+ }
+
+ void testGetResponse() {
+ DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
+
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setChallenge(createByteArray(
+ "realm=\"example.com\","
+ "nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\","
+ "qop=auth,charset=utf-8,algorithm=md5-sess"));
+
+ SafeByteArray response = *testling.getResponse();
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("charset=utf-8,cnonce=\"abcdefgh\",digest-uri=\"xmpp/xmpp.example.com\",nc=00000001,nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\",qop=auth,realm=\"example.com\",response=088891c800ecff1b842159ad6459104a,username=\"user\""), response);
+ }
+
+ void testGetResponse_WithAuthorizationID() {
+ DIGESTMD5ClientAuthenticator testling("xmpp.example.com", "abcdefgh", crypto.get());
+
+ testling.setCredentials("user", createSafeByteArray("pass"), "myauthzid");
+ testling.setChallenge(createByteArray(
+ "realm=\"example.com\","
+ "nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\","
+ "qop=auth,charset=utf-8,algorithm=md5-sess"));
+
+ SafeByteArray response = *testling.getResponse();
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("authzid=\"myauthzid\",charset=utf-8,cnonce=\"abcdefgh\",digest-uri=\"xmpp/xmpp.example.com\",nc=00000001,nonce=\"O6skKPuaCZEny3hteI19qXMBXSadoWs840MchORo\",qop=auth,realm=\"example.com\",response=4293834432b6e7889a2dee7e8fe7dd06,username=\"user\""), response);
+ }
+
+ private:
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DIGESTMD5ClientAuthenticatorTest);
diff --git a/Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp b/Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp
index d47a1ee..841f580 100644
--- a/Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp
+++ b/Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp
@@ -12,44 +12,44 @@
using namespace Swift;
class DIGESTMD5PropertiesTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DIGESTMD5PropertiesTest);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testParse() {
- DIGESTMD5Properties properties = DIGESTMD5Properties::parse(createByteArray(
- "realm=\"myrealm1\",realm=\"myrealm2\",nonce=\"mynonce\","
- "algorithm=md5-sess,charset=utf-8"));
-
- CPPUNIT_ASSERT(properties.getValue("realm"));
- CPPUNIT_ASSERT_EQUAL(std::string("myrealm1"), *properties.getValue("realm"));
- CPPUNIT_ASSERT(properties.getValue("nonce"));
- CPPUNIT_ASSERT_EQUAL(std::string("mynonce"), *properties.getValue("nonce"));
- CPPUNIT_ASSERT(properties.getValue("algorithm"));
- CPPUNIT_ASSERT_EQUAL(std::string("md5-sess"), *properties.getValue("algorithm"));
- CPPUNIT_ASSERT(properties.getValue("charset"));
- CPPUNIT_ASSERT_EQUAL(std::string("utf-8"), *properties.getValue("charset"));
- }
-
- void testSerialize() {
- DIGESTMD5Properties properties;
- properties.setValue("authzid", "myauthzid");
- properties.setValue("charset", "utf-8");
- properties.setValue("cnonce", "mycnonce");
- properties.setValue("digest-uri", "mydigesturi");
- properties.setValue("nc", "1");
- properties.setValue("nonce", "mynonce");
- properties.setValue("qop", "auth");
- properties.setValue("realm", "myrealm");
- properties.setValue("response", "myresponse");
- properties.setValue("username", "myuser");
-
- ByteArray result = properties.serialize();
- ByteArray expected(createByteArray("authzid=\"myauthzid\",charset=utf-8,cnonce=\"mycnonce\",digest-uri=\"mydigesturi\",nc=1,nonce=\"mynonce\",qop=auth,realm=\"myrealm\",response=myresponse,username=\"myuser\""));
- CPPUNIT_ASSERT_EQUAL(byteArrayToString(expected), byteArrayToString(result));
- }
+ CPPUNIT_TEST_SUITE(DIGESTMD5PropertiesTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ DIGESTMD5Properties properties = DIGESTMD5Properties::parse(createByteArray(
+ "realm=\"myrealm1\",realm=\"myrealm2\",nonce=\"mynonce\","
+ "algorithm=md5-sess,charset=utf-8"));
+
+ CPPUNIT_ASSERT(properties.getValue("realm"));
+ CPPUNIT_ASSERT_EQUAL(std::string("myrealm1"), *properties.getValue("realm"));
+ CPPUNIT_ASSERT(properties.getValue("nonce"));
+ CPPUNIT_ASSERT_EQUAL(std::string("mynonce"), *properties.getValue("nonce"));
+ CPPUNIT_ASSERT(properties.getValue("algorithm"));
+ CPPUNIT_ASSERT_EQUAL(std::string("md5-sess"), *properties.getValue("algorithm"));
+ CPPUNIT_ASSERT(properties.getValue("charset"));
+ CPPUNIT_ASSERT_EQUAL(std::string("utf-8"), *properties.getValue("charset"));
+ }
+
+ void testSerialize() {
+ DIGESTMD5Properties properties;
+ properties.setValue("authzid", "myauthzid");
+ properties.setValue("charset", "utf-8");
+ properties.setValue("cnonce", "mycnonce");
+ properties.setValue("digest-uri", "mydigesturi");
+ properties.setValue("nc", "1");
+ properties.setValue("nonce", "mynonce");
+ properties.setValue("qop", "auth");
+ properties.setValue("realm", "myrealm");
+ properties.setValue("response", "myresponse");
+ properties.setValue("username", "myuser");
+
+ ByteArray result = properties.serialize();
+ ByteArray expected(createByteArray("authzid=\"myauthzid\",charset=utf-8,cnonce=\"mycnonce\",digest-uri=\"mydigesturi\",nc=1,nonce=\"mynonce\",qop=auth,realm=\"myrealm\",response=myresponse,username=\"myuser\""));
+ CPPUNIT_ASSERT_EQUAL(byteArrayToString(expected), byteArrayToString(result));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DIGESTMD5PropertiesTest);
diff --git a/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp b/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp
index 67e5d75..070b4d9 100644
--- a/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp
@@ -14,27 +14,27 @@
using namespace Swift;
class PLAINClientAuthenticatorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PLAINClientAuthenticatorTest);
- CPPUNIT_TEST(testGetResponse_WithoutAuthzID);
- CPPUNIT_TEST(testGetResponse_WithAuthzID);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PLAINClientAuthenticatorTest);
+ CPPUNIT_TEST(testGetResponse_WithoutAuthzID);
+ CPPUNIT_TEST(testGetResponse_WithAuthzID);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetResponse_WithoutAuthzID() {
- PLAINClientAuthenticator testling;
+ public:
+ void testGetResponse_WithoutAuthzID() {
+ PLAINClientAuthenticator testling;
- testling.setCredentials("user", createSafeByteArray("pass"));
+ testling.setCredentials("user", createSafeByteArray("pass"));
- CPPUNIT_ASSERT_EQUAL(*testling.getResponse(), createSafeByteArray("\0user\0pass", 10));
- }
+ CPPUNIT_ASSERT_EQUAL(*testling.getResponse(), createSafeByteArray("\0user\0pass", 10));
+ }
- void testGetResponse_WithAuthzID() {
- PLAINClientAuthenticator testling;
+ void testGetResponse_WithAuthzID() {
+ PLAINClientAuthenticator testling;
- testling.setCredentials("user", createSafeByteArray("pass"), "authz");
+ testling.setCredentials("user", createSafeByteArray("pass"), "authz");
- CPPUNIT_ASSERT_EQUAL(*testling.getResponse(), createSafeByteArray("authz\0user\0pass", 15));
- }
+ CPPUNIT_ASSERT_EQUAL(*testling.getResponse(), createSafeByteArray("authz\0user\0pass", 15));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PLAINClientAuthenticatorTest);
diff --git a/Swiften/SASL/UnitTest/PLAINMessageTest.cpp b/Swiften/SASL/UnitTest/PLAINMessageTest.cpp
index b885eea..271b827 100644
--- a/Swiften/SASL/UnitTest/PLAINMessageTest.cpp
+++ b/Swiften/SASL/UnitTest/PLAINMessageTest.cpp
@@ -16,55 +16,55 @@ using namespace Swift;
class PLAINMessageTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(PLAINMessageTest);
- CPPUNIT_TEST(testGetValue_WithoutAuthzID);
- CPPUNIT_TEST(testGetValue_WithAuthzID);
- CPPUNIT_TEST(testConstructor_WithoutAuthzID);
- CPPUNIT_TEST(testConstructor_WithAuthzID);
- CPPUNIT_TEST(testConstructor_NoAuthcid);
- CPPUNIT_TEST(testConstructor_NoPassword);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- PLAINMessageTest() {}
-
- void testGetValue_WithoutAuthzID() {
- PLAINMessage message("user", createSafeByteArray("pass"));
- CPPUNIT_ASSERT_EQUAL(message.getValue(), createSafeByteArray("\0user\0pass", 10));
- }
-
- void testGetValue_WithAuthzID() {
- PLAINMessage message("user", createSafeByteArray("pass"), "authz");
- CPPUNIT_ASSERT_EQUAL(message.getValue(), createSafeByteArray("authz\0user\0pass", 15));
- }
-
- void testConstructor_WithoutAuthzID() {
- PLAINMessage message(createSafeByteArray("\0user\0pass", 10));
-
- CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthorizationID());
- CPPUNIT_ASSERT_EQUAL(std::string("user"), message.getAuthenticationID());
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("pass"), message.getPassword());
- }
-
- void testConstructor_WithAuthzID() {
- PLAINMessage message(createSafeByteArray("authz\0user\0pass", 15));
-
- CPPUNIT_ASSERT_EQUAL(std::string("authz"), message.getAuthorizationID());
- CPPUNIT_ASSERT_EQUAL(std::string("user"), message.getAuthenticationID());
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("pass"), message.getPassword());
- }
-
- void testConstructor_NoAuthcid() {
- PLAINMessage message(createSafeByteArray("authzid", 7));
-
- CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthenticationID());
- }
-
- void testConstructor_NoPassword() {
- PLAINMessage message(createSafeByteArray("authzid\0authcid", 15));
-
- CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthenticationID());
- }
+ CPPUNIT_TEST_SUITE(PLAINMessageTest);
+ CPPUNIT_TEST(testGetValue_WithoutAuthzID);
+ CPPUNIT_TEST(testGetValue_WithAuthzID);
+ CPPUNIT_TEST(testConstructor_WithoutAuthzID);
+ CPPUNIT_TEST(testConstructor_WithAuthzID);
+ CPPUNIT_TEST(testConstructor_NoAuthcid);
+ CPPUNIT_TEST(testConstructor_NoPassword);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ PLAINMessageTest() {}
+
+ void testGetValue_WithoutAuthzID() {
+ PLAINMessage message("user", createSafeByteArray("pass"));
+ CPPUNIT_ASSERT_EQUAL(message.getValue(), createSafeByteArray("\0user\0pass", 10));
+ }
+
+ void testGetValue_WithAuthzID() {
+ PLAINMessage message("user", createSafeByteArray("pass"), "authz");
+ CPPUNIT_ASSERT_EQUAL(message.getValue(), createSafeByteArray("authz\0user\0pass", 15));
+ }
+
+ void testConstructor_WithoutAuthzID() {
+ PLAINMessage message(createSafeByteArray("\0user\0pass", 10));
+
+ CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthorizationID());
+ CPPUNIT_ASSERT_EQUAL(std::string("user"), message.getAuthenticationID());
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("pass"), message.getPassword());
+ }
+
+ void testConstructor_WithAuthzID() {
+ PLAINMessage message(createSafeByteArray("authz\0user\0pass", 15));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("authz"), message.getAuthorizationID());
+ CPPUNIT_ASSERT_EQUAL(std::string("user"), message.getAuthenticationID());
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("pass"), message.getPassword());
+ }
+
+ void testConstructor_NoAuthcid() {
+ PLAINMessage message(createSafeByteArray("authzid", 7));
+
+ CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthenticationID());
+ }
+
+ void testConstructor_NoPassword() {
+ PLAINMessage message(createSafeByteArray("authzid\0authcid", 15));
+
+ CPPUNIT_ASSERT_EQUAL(std::string(""), message.getAuthenticationID());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PLAINMessageTest);
diff --git a/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp b/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp
index 8b219af..3d5d161 100644
--- a/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp
@@ -19,215 +19,215 @@
using namespace Swift;
class SCRAMSHA1ClientAuthenticatorTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SCRAMSHA1ClientAuthenticatorTest);
- CPPUNIT_TEST(testGetInitialResponse);
- CPPUNIT_TEST(testGetInitialResponse_UsernameHasSpecialChars);
- CPPUNIT_TEST(testGetInitialResponse_WithAuthorizationID);
- CPPUNIT_TEST(testGetInitialResponse_WithAuthorizationIDWithSpecialChars);
- CPPUNIT_TEST(testGetInitialResponse_WithoutChannelBindingWithTLSChannelBindingData);
- CPPUNIT_TEST(testGetInitialResponse_WithChannelBindingWithTLSChannelBindingData);
- CPPUNIT_TEST(testGetFinalResponse);
- CPPUNIT_TEST(testGetFinalResponse_WithoutChannelBindingWithTLSChannelBindingData);
- CPPUNIT_TEST(testGetFinalResponse_WithChannelBindingWithTLSChannelBindingData);
- CPPUNIT_TEST(testSetChallenge);
- CPPUNIT_TEST(testSetChallenge_InvalidClientNonce);
- CPPUNIT_TEST(testSetChallenge_OnlyClientNonce);
- CPPUNIT_TEST(testSetChallenge_InvalidIterations);
- CPPUNIT_TEST(testSetChallenge_ZeroIterations);
- CPPUNIT_TEST(testSetChallenge_NegativeIterations);
- CPPUNIT_TEST(testSetChallenge_MissingIterations);
- CPPUNIT_TEST(testSetFinalChallenge);
- CPPUNIT_TEST(testSetFinalChallenge_InvalidChallenge);
- CPPUNIT_TEST(testGetResponseAfterFinalChallenge);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SCRAMSHA1ClientAuthenticatorTest);
+ CPPUNIT_TEST(testGetInitialResponse);
+ CPPUNIT_TEST(testGetInitialResponse_UsernameHasSpecialChars);
+ CPPUNIT_TEST(testGetInitialResponse_WithAuthorizationID);
+ CPPUNIT_TEST(testGetInitialResponse_WithAuthorizationIDWithSpecialChars);
+ CPPUNIT_TEST(testGetInitialResponse_WithoutChannelBindingWithTLSChannelBindingData);
+ CPPUNIT_TEST(testGetInitialResponse_WithChannelBindingWithTLSChannelBindingData);
+ CPPUNIT_TEST(testGetFinalResponse);
+ CPPUNIT_TEST(testGetFinalResponse_WithoutChannelBindingWithTLSChannelBindingData);
+ CPPUNIT_TEST(testGetFinalResponse_WithChannelBindingWithTLSChannelBindingData);
+ CPPUNIT_TEST(testSetChallenge);
+ CPPUNIT_TEST(testSetChallenge_InvalidClientNonce);
+ CPPUNIT_TEST(testSetChallenge_OnlyClientNonce);
+ CPPUNIT_TEST(testSetChallenge_InvalidIterations);
+ CPPUNIT_TEST(testSetChallenge_ZeroIterations);
+ CPPUNIT_TEST(testSetChallenge_NegativeIterations);
+ CPPUNIT_TEST(testSetChallenge_MissingIterations);
+ CPPUNIT_TEST(testSetFinalChallenge);
+ CPPUNIT_TEST(testSetFinalChallenge_InvalidChallenge);
+ CPPUNIT_TEST(testGetResponseAfterFinalChallenge);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
+ public:
+ void setUp() {
+ idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
- void testGetInitialResponse() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testGetInitialResponse() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,,n=user,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,,n=user,r=abcdefghABCDEFGH"), response);
+ }
- void testGetInitialResponse_UsernameHasSpecialChars() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
- testling.setCredentials(",us=,er=", createSafeByteArray("pass"), "");
+ void testGetInitialResponse_UsernameHasSpecialChars() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
+ testling.setCredentials(",us=,er=", createSafeByteArray("pass"), "");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,,n==2Cus=3D=2Cer=3D,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,,n==2Cus=3D=2Cer=3D,r=abcdefghABCDEFGH"), response);
+ }
- void testGetInitialResponse_WithAuthorizationID() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "auth");
+ void testGetInitialResponse_WithAuthorizationID() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "auth");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,a=auth,n=user,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,a=auth,n=user,r=abcdefghABCDEFGH"), response);
+ }
- void testGetInitialResponse_WithAuthorizationIDWithSpecialChars() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "a=u,th");
+ void testGetInitialResponse_WithAuthorizationIDWithSpecialChars() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "a=u,th");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,a=a=3Du=2Cth,n=user,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("n,a=a=3Du=2Cth,n=user,r=abcdefghABCDEFGH"), response);
+ }
- void testGetInitialResponse_WithoutChannelBindingWithTLSChannelBindingData() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
- testling.setTLSChannelBindingData(createByteArray("xyza"));
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testGetInitialResponse_WithoutChannelBindingWithTLSChannelBindingData() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", false, idnConverter.get(), crypto.get());
+ testling.setTLSChannelBindingData(createByteArray("xyza"));
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("y,,n=user,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("y,,n=user,r=abcdefghABCDEFGH"), response);
+ }
- void testGetInitialResponse_WithChannelBindingWithTLSChannelBindingData() {
- SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", true, idnConverter.get(), crypto.get());
- testling.setTLSChannelBindingData(createByteArray("xyza"));
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testGetInitialResponse_WithChannelBindingWithTLSChannelBindingData() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefghABCDEFGH", true, idnConverter.get(), crypto.get());
+ testling.setTLSChannelBindingData(createByteArray("xyza"));
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("p=tls-unique,,n=user,r=abcdefghABCDEFGH"), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("p=tls-unique,,n=user,r=abcdefghABCDEFGH"), response);
+ }
- void testGetFinalResponse() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ void testGetFinalResponse() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=biws,r=abcdefghABCDEFGH,p=CZbjGDpIteIJwQNBgO0P8pKkMGY="), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=biws,r=abcdefghABCDEFGH,p=CZbjGDpIteIJwQNBgO0P8pKkMGY="), response);
+ }
- void testGetFinalResponse_WithoutChannelBindingWithTLSChannelBindingData() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setTLSChannelBindingData(createByteArray("xyza"));
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ void testGetFinalResponse_WithoutChannelBindingWithTLSChannelBindingData() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setTLSChannelBindingData(createByteArray("xyza"));
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=eSws,r=abcdefghABCDEFGH,p=JNpsiFEcxZvNZ1+FFBBqrYvYxMk="), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=eSws,r=abcdefghABCDEFGH,p=JNpsiFEcxZvNZ1+FFBBqrYvYxMk="), response);
+ }
- void testGetFinalResponse_WithChannelBindingWithTLSChannelBindingData() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", true, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setTLSChannelBindingData(createByteArray("xyza"));
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ void testGetFinalResponse_WithChannelBindingWithTLSChannelBindingData() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", true, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setTLSChannelBindingData(createByteArray("xyza"));
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- SafeByteArray response = *testling.getResponse();
+ SafeByteArray response = *testling.getResponse();
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=cD10bHMtdW5pcXVlLCx4eXph,r=abcdefghABCDEFGH,p=i6Rghite81P1ype8XxaVAa5l7v0="), response);
- }
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("c=cD10bHMtdW5pcXVlLCx4eXph,r=abcdefghABCDEFGH,p=i6Rghite81P1ype8XxaVAa5l7v0="), response);
+ }
- void testSetFinalChallenge() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ void testSetFinalChallenge() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- bool result = testling.setChallenge(createByteArray("v=Dd+Q20knZs9jeeK0pi1Mx1Se+yo="));
+ bool result = testling.setChallenge(createByteArray("v=Dd+Q20knZs9jeeK0pi1Mx1Se+yo="));
- CPPUNIT_ASSERT(result);
- }
+ CPPUNIT_ASSERT(result);
+ }
- void testSetChallenge() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- CPPUNIT_ASSERT(result);
- }
+ CPPUNIT_ASSERT(result);
+ }
- void testSetChallenge_InvalidClientNonce() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_InvalidClientNonce() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefgiABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefgiABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetChallenge_OnlyClientNonce() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_OnlyClientNonce() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefgh,s=MTIzNDU2NzgK,i=4096"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefgh,s=MTIzNDU2NzgK,i=4096"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetChallenge_InvalidIterations() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_InvalidIterations() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=bla"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=bla"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetChallenge_MissingIterations() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_MissingIterations() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetChallenge_ZeroIterations() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_ZeroIterations() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=0"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=0"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetChallenge_NegativeIterations() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
+ void testSetChallenge_NegativeIterations() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
- bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=-1"));
+ bool result = testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=-1"));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testSetFinalChallenge_InvalidChallenge() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- bool result = testling.setChallenge(createByteArray("v=e26kI69ICb6zosapLLxrER/631A="));
+ void testSetFinalChallenge_InvalidChallenge() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ bool result = testling.setChallenge(createByteArray("v=e26kI69ICb6zosapLLxrER/631A="));
- CPPUNIT_ASSERT(!result);
- }
+ CPPUNIT_ASSERT(!result);
+ }
- void testGetResponseAfterFinalChallenge() {
- SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
- testling.setCredentials("user", createSafeByteArray("pass"), "");
- testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
- testling.setChallenge(createByteArray("v=Dd+Q20knZs9jeeK0pi1Mx1Se+yo="));
+ void testGetResponseAfterFinalChallenge() {
+ SCRAMSHA1ClientAuthenticator testling("abcdefgh", false, idnConverter.get(), crypto.get());
+ testling.setCredentials("user", createSafeByteArray("pass"), "");
+ testling.setChallenge(createByteArray("r=abcdefghABCDEFGH,s=MTIzNDU2NzgK,i=4096"));
+ testling.setChallenge(createByteArray("v=Dd+Q20knZs9jeeK0pi1Mx1Se+yo="));
- CPPUNIT_ASSERT(!testling.getResponse());
- }
+ CPPUNIT_ASSERT(!testling.getResponse());
+ }
- boost::shared_ptr<IDNConverter> idnConverter;
- boost::shared_ptr<CryptoProvider> crypto;
+ boost::shared_ptr<IDNConverter> idnConverter;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SCRAMSHA1ClientAuthenticatorTest);
diff --git a/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp b/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp
index 1b0e6f6..fa07052 100644
--- a/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp
+++ b/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp
@@ -11,151 +11,151 @@
using namespace Swift;
class WindowsServicePrincipalNameTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(WindowsServicePrincipalNameTest);
- CPPUNIT_TEST(testServiceClass);
- CPPUNIT_TEST(testServiceName);
- CPPUNIT_TEST(testInstanceName);
- CPPUNIT_TEST(testInstancePort);
- CPPUNIT_TEST(testReferrer);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testServiceClass() {
- WindowsServicePrincipalName spn("mlink.adlon.isode.net");
-
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net"));
-
- spn.setServiceClass("ldap");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("ldap/mlink.adlon.isode.net"));
-
- spn.setServiceClass("中文");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("中文/mlink.adlon.isode.net"));
-
- try {
- spn.setServiceClass("");
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
-
- try {
- spn.setServiceClass("xm/pp"); /* Foward slash not allowed */
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
- }
-
- void testServiceName() {
- try {
- WindowsServicePrincipalName spn("");
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
-
- try {
- WindowsServicePrincipalName spn2("mlink/adlon.isode.net"); /* Foward slash not allowed */
- spn2.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
-
- WindowsServicePrincipalName spn3("mlinkÄ.adlon.isode.net");
- CPPUNIT_ASSERT_EQUAL(spn3.toString(), std::string("xmpp/mlinkÄ.adlon.isode.net"));
- }
-
- void testInstanceName() {
- WindowsServicePrincipalName spn("adlon.isode.net");
-
- spn.setInstanceName("mlink.adlon.isode.net");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net/adlon.isode.net"));
-
- spn.setInstanceName("127.0.0.1");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1/adlon.isode.net"));
-
- spn.setInstanceName("");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/adlon.isode.net"));
-
- spn.setInstanceName("cañón.adlon.isode.net");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/cañón.adlon.isode.net/adlon.isode.net"));
-
- try {
- spn.setInstanceName("mlink/adlon.isode.net"); /* Foward slash not allowed */
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
- }
-
- void testInstancePort() {
- WindowsServicePrincipalName spn("adlon.isode.net");
-
- spn.setInstanceName("mlink.adlon.isode.net");
- spn.setInstancePort(6222);
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net:6222/adlon.isode.net"));
-
- spn.setInstancePort(0);
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net/adlon.isode.net"));
-
- WindowsServicePrincipalName spn2("mlink.adlon.isode.net");
-
- spn2.setInstancePort(6222);
- CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net:6222"));
-
- spn2.setInstancePort(0);
- CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
- }
-
- void testReferrer() {
- WindowsServicePrincipalName spn("127.0.0.1");
-
- spn.setReferrer("referrer.net");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1/referrer.net"));
-
- spn.setInstancePort(6222);
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1:6222/referrer.net"));
-
- spn.setReferrer("हिन्दी.net");
- CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1:6222/हिन्दी.net"));
-
- try {
- spn.setReferrer("referrer/net"); /* Foward slash not allowed */
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
-
- try {
- spn.setReferrer(""); /* seems like you must have referrer with an IP */
- spn.toString();
- CPPUNIT_ASSERT(false);
- } catch (std::runtime_error) {
- /* expected */
- }
-
- WindowsServicePrincipalName spn2("mlink.adlon.isode.net");
-
- spn2.setReferrer("referrer.net"); /* Referrer ignored if service name is not IP */
- CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
-
- spn2.setReferrer("referrer/net"); /* Referrer ignored if service name is not IP */
- CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
+ CPPUNIT_TEST_SUITE(WindowsServicePrincipalNameTest);
+ CPPUNIT_TEST(testServiceClass);
+ CPPUNIT_TEST(testServiceName);
+ CPPUNIT_TEST(testInstanceName);
+ CPPUNIT_TEST(testInstancePort);
+ CPPUNIT_TEST(testReferrer);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testServiceClass() {
+ WindowsServicePrincipalName spn("mlink.adlon.isode.net");
+
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net"));
+
+ spn.setServiceClass("ldap");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("ldap/mlink.adlon.isode.net"));
+
+ spn.setServiceClass("中文");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("中文/mlink.adlon.isode.net"));
+
+ try {
+ spn.setServiceClass("");
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+
+ try {
+ spn.setServiceClass("xm/pp"); /* Foward slash not allowed */
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+ }
+
+ void testServiceName() {
+ try {
+ WindowsServicePrincipalName spn("");
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+
+ try {
+ WindowsServicePrincipalName spn2("mlink/adlon.isode.net"); /* Foward slash not allowed */
+ spn2.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+
+ WindowsServicePrincipalName spn3("mlinkÄ.adlon.isode.net");
+ CPPUNIT_ASSERT_EQUAL(spn3.toString(), std::string("xmpp/mlinkÄ.adlon.isode.net"));
+ }
+
+ void testInstanceName() {
+ WindowsServicePrincipalName spn("adlon.isode.net");
+
+ spn.setInstanceName("mlink.adlon.isode.net");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net/adlon.isode.net"));
+
+ spn.setInstanceName("127.0.0.1");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1/adlon.isode.net"));
+
+ spn.setInstanceName("");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/adlon.isode.net"));
+
+ spn.setInstanceName("cañón.adlon.isode.net");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/cañón.adlon.isode.net/adlon.isode.net"));
+
+ try {
+ spn.setInstanceName("mlink/adlon.isode.net"); /* Foward slash not allowed */
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+ }
+
+ void testInstancePort() {
+ WindowsServicePrincipalName spn("adlon.isode.net");
+
+ spn.setInstanceName("mlink.adlon.isode.net");
+ spn.setInstancePort(6222);
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net:6222/adlon.isode.net"));
+
+ spn.setInstancePort(0);
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net/adlon.isode.net"));
+
+ WindowsServicePrincipalName spn2("mlink.adlon.isode.net");
+
+ spn2.setInstancePort(6222);
+ CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net:6222"));
+
+ spn2.setInstancePort(0);
+ CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
+ }
+
+ void testReferrer() {
+ WindowsServicePrincipalName spn("127.0.0.1");
+
+ spn.setReferrer("referrer.net");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1/referrer.net"));
+
+ spn.setInstancePort(6222);
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1:6222/referrer.net"));
+
+ spn.setReferrer("हिन्दी.net");
+ CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/127.0.0.1:6222/हिन्दी.net"));
+
+ try {
+ spn.setReferrer("referrer/net"); /* Foward slash not allowed */
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+
+ try {
+ spn.setReferrer(""); /* seems like you must have referrer with an IP */
+ spn.toString();
+ CPPUNIT_ASSERT(false);
+ } catch (std::runtime_error) {
+ /* expected */
+ }
+
+ WindowsServicePrincipalName spn2("mlink.adlon.isode.net");
+
+ spn2.setReferrer("referrer.net"); /* Referrer ignored if service name is not IP */
+ CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
+
+ spn2.setReferrer("referrer/net"); /* Referrer ignored if service name is not IP */
+ CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net"));
- WindowsServicePrincipalName spn3("adlon.isode.net");
+ WindowsServicePrincipalName spn3("adlon.isode.net");
- spn3.setInstanceName("mlink.adlon.isode.net");
- spn3.setInstancePort(6222);
- spn3.setReferrer("referrer.net"); /* Referrer ignored if service name is not IP */
- CPPUNIT_ASSERT_EQUAL(spn3.toString(), std::string("xmpp/mlink.adlon.isode.net:6222/adlon.isode.net"));
+ spn3.setInstanceName("mlink.adlon.isode.net");
+ spn3.setInstancePort(6222);
+ spn3.setReferrer("referrer.net"); /* Referrer ignored if service name is not IP */
+ CPPUNIT_ASSERT_EQUAL(spn3.toString(), std::string("xmpp/mlink.adlon.isode.net:6222/adlon.isode.net"));
- }
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(WindowsServicePrincipalNameTest);
diff --git a/Swiften/SASL/WindowsAuthentication.cpp b/Swiften/SASL/WindowsAuthentication.cpp
index 0244fe1..5917b66 100644
--- a/Swiften/SASL/WindowsAuthentication.cpp
+++ b/Swiften/SASL/WindowsAuthentication.cpp
@@ -15,313 +15,313 @@
#define ASSIGN_ERROR(status, errorCode) \
{ \
- errorCode = boost::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
- SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode->message() << std::endl; \
+ errorCode = boost::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
+ SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode->message() << std::endl; \
}
#define ASSIGN_SEC_ERROR(status, errorCode) \
{ \
- if (status == SEC_E_OK) \
- { \
- SWIFT_LOG(debug) << "success" << std::endl; \
- } \
- else { \
- ASSIGN_ERROR(status, errorCode); \
- } \
+ if (status == SEC_E_OK) \
+ { \
+ SWIFT_LOG(debug) << "success" << std::endl; \
+ } \
+ else { \
+ ASSIGN_ERROR(status, errorCode); \
+ } \
}
namespace Swift {
boost::shared_ptr<boost::system::error_code> getUserNameEx(std::string& userName, std::string& clientName, std::string& serverName) {
- ULONG length = 512;
- DWORD status = ERROR_MORE_DATA;
- bool firstCall = true;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ ULONG length = 512;
+ DWORD status = ERROR_MORE_DATA;
+ bool firstCall = true;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- while (status == ERROR_MORE_DATA) {
- std::vector<wchar_t> value(length);
+ while (status == ERROR_MORE_DATA) {
+ std::vector<wchar_t> value(length);
- /* length after this call will contain the required length if current length is not enough - so the next call should succeed */
- if (GetUserNameExW(NameSamCompatible, vecptr(value), &length)) {
- std::size_t position;
+ /* length after this call will contain the required length if current length is not enough - so the next call should succeed */
+ if (GetUserNameExW(NameSamCompatible, vecptr(value), &length)) {
+ std::size_t position;
- userName = convertWStringToString(std::wstring(vecptr(value), length));
- SWIFT_LOG(debug) << "User Name: " << userName << std::endl;
+ userName = convertWStringToString(std::wstring(vecptr(value), length));
+ SWIFT_LOG(debug) << "User Name: " << userName << std::endl;
- position = userName.find("\\");
- clientName = userName.substr(position + 1);
- SWIFT_LOG(debug) << "Client name: " << clientName << std::endl;
+ position = userName.find("\\");
+ clientName = userName.substr(position + 1);
+ SWIFT_LOG(debug) << "Client name: " << clientName << std::endl;
- serverName = userName.substr(0, position);
- SWIFT_LOG(debug) << "Server name: " << serverName << std::endl;
+ serverName = userName.substr(0, position);
+ SWIFT_LOG(debug) << "Server name: " << serverName << std::endl;
- break;
- }
+ break;
+ }
- status = GetLastError();
- if ((firstCall == false) || (status != ERROR_MORE_DATA)) {
- ASSIGN_ERROR(status, errorCode);
- break;
- }
+ status = GetLastError();
+ if ((firstCall == false) || (status != ERROR_MORE_DATA)) {
+ ASSIGN_ERROR(status, errorCode);
+ break;
+ }
- firstCall = false;
- }
+ firstCall = false;
+ }
- return errorCode;
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> acquireCredentialsHandle(PCredHandle credentialsHandle) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
- TimeStamp validity;
-
- status = AcquireCredentialsHandle(
- NULL, /* NULL indicates credentials of the user under whose security context it is executing */
- "Kerberos",
- SECPKG_CRED_OUTBOUND, /* client credential */
- NULL,
- NULL, /* use default credentials */
- NULL, /* not used */
- NULL, /* not used */
- credentialsHandle,
- &validity);
- ASSIGN_SEC_ERROR(status, errorCode);
-
- return errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
+ TimeStamp validity;
+
+ status = AcquireCredentialsHandle(
+ NULL, /* NULL indicates credentials of the user under whose security context it is executing */
+ "Kerberos",
+ SECPKG_CRED_OUTBOUND, /* client credential */
+ NULL,
+ NULL, /* use default credentials */
+ NULL, /* not used */
+ NULL, /* not used */
+ credentialsHandle,
+ &validity);
+ ASSIGN_SEC_ERROR(status, errorCode);
+
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> freeCredentialsHandle(PCredHandle credentialsHandle) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- status = FreeCredentialsHandle(credentialsHandle);
- ASSIGN_SEC_ERROR(status, errorCode);
+ status = FreeCredentialsHandle(credentialsHandle);
+ ASSIGN_SEC_ERROR(status, errorCode);
- return errorCode;
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> initializeSecurityContext(const boost::optional<ByteArray>& inputToken, const std::string& servicePrincipalNameString, const PCredHandle credentialsHandle, bool haveContextHandle, PCtxtHandle contextHandle, ULONG contextRequested, ULONG* contextSupported, bool* haveCompleteContext, SafeByteArray& outputToken) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
- SecBufferDesc input;
- SecBufferDesc output;
- SecBuffer inputTokenBuffer;
- SecBuffer outputTokenBuffer;
- TimeStamp validity;
-
- *haveCompleteContext = false;
-
- input.ulVersion = 0;
- input.cBuffers = 1;
- input.pBuffers = &inputTokenBuffer;
-
- inputTokenBuffer.BufferType = SECBUFFER_TOKEN;
- inputTokenBuffer.cbBuffer = 0;
- inputTokenBuffer.pvBuffer = NULL;
- if (inputToken && inputToken->size()) {
- inputTokenBuffer.cbBuffer = inputToken->size();
- inputTokenBuffer.pvBuffer = (void *) vecptr(*inputToken);
- }
-
- output.ulVersion = 0;
- output.cBuffers = 1;
- output.pBuffers = &outputTokenBuffer;
-
- outputTokenBuffer.BufferType = SECBUFFER_TOKEN;
- outputTokenBuffer.cbBuffer = 0;
- outputTokenBuffer.pvBuffer = NULL;
-
- status = InitializeSecurityContext(
- credentialsHandle, /* previously acquired handle */
- haveContextHandle ? contextHandle : NULL, /* use partial context on subsequent calls */
- const_cast<char *>(servicePrincipalNameString.c_str()),
- contextRequested | ISC_REQ_ALLOCATE_MEMORY,
- 0, /* not used */
- SECURITY_NETWORK_DREP,
- haveContextHandle ? &input : NULL,
- 0, /* not used */
- contextHandle,
- &output,
- contextSupported,
- &validity);
- ASSIGN_SEC_ERROR(status, errorCode); /* errorCode set here will only be returned to caller if there was a non-success status */
- if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) {
- /* The Windows documentation suggests that this function is used only for Digest and only on the server side, but still asks to call this function for Kerberos clients. Most likely this function will never be called, but including it for compliance with documentation. */
- errorCode = completeAuthToken(contextHandle, &output);
- if (!errorCode) {
- /* success, move on */
- }
- else {
- freeContextBuffer(outputTokenBuffer.pvBuffer);
- return errorCode;
- }
- }
- if ((status == SEC_E_OK) || (status == SEC_I_COMPLETE_NEEDED)) {
- *haveCompleteContext = true;
- }
- if ((status == SEC_E_OK) || (status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED) || (status == SEC_I_CONTINUE_NEEDED)) {
- outputToken = createSafeByteArray (static_cast<unsigned char *>(outputTokenBuffer.pvBuffer), outputTokenBuffer.cbBuffer);
- SWIFT_LOG(debug) << "outputToken.size(): " << outputToken.size() << std::endl;
- freeContextBuffer(outputTokenBuffer.pvBuffer);
-
- return boost::shared_ptr<boost::system::error_code>(); /* success */
- }
-
- return errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
+ SecBufferDesc input;
+ SecBufferDesc output;
+ SecBuffer inputTokenBuffer;
+ SecBuffer outputTokenBuffer;
+ TimeStamp validity;
+
+ *haveCompleteContext = false;
+
+ input.ulVersion = 0;
+ input.cBuffers = 1;
+ input.pBuffers = &inputTokenBuffer;
+
+ inputTokenBuffer.BufferType = SECBUFFER_TOKEN;
+ inputTokenBuffer.cbBuffer = 0;
+ inputTokenBuffer.pvBuffer = NULL;
+ if (inputToken && inputToken->size()) {
+ inputTokenBuffer.cbBuffer = inputToken->size();
+ inputTokenBuffer.pvBuffer = (void *) vecptr(*inputToken);
+ }
+
+ output.ulVersion = 0;
+ output.cBuffers = 1;
+ output.pBuffers = &outputTokenBuffer;
+
+ outputTokenBuffer.BufferType = SECBUFFER_TOKEN;
+ outputTokenBuffer.cbBuffer = 0;
+ outputTokenBuffer.pvBuffer = NULL;
+
+ status = InitializeSecurityContext(
+ credentialsHandle, /* previously acquired handle */
+ haveContextHandle ? contextHandle : NULL, /* use partial context on subsequent calls */
+ const_cast<char *>(servicePrincipalNameString.c_str()),
+ contextRequested | ISC_REQ_ALLOCATE_MEMORY,
+ 0, /* not used */
+ SECURITY_NETWORK_DREP,
+ haveContextHandle ? &input : NULL,
+ 0, /* not used */
+ contextHandle,
+ &output,
+ contextSupported,
+ &validity);
+ ASSIGN_SEC_ERROR(status, errorCode); /* errorCode set here will only be returned to caller if there was a non-success status */
+ if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) {
+ /* The Windows documentation suggests that this function is used only for Digest and only on the server side, but still asks to call this function for Kerberos clients. Most likely this function will never be called, but including it for compliance with documentation. */
+ errorCode = completeAuthToken(contextHandle, &output);
+ if (!errorCode) {
+ /* success, move on */
+ }
+ else {
+ freeContextBuffer(outputTokenBuffer.pvBuffer);
+ return errorCode;
+ }
+ }
+ if ((status == SEC_E_OK) || (status == SEC_I_COMPLETE_NEEDED)) {
+ *haveCompleteContext = true;
+ }
+ if ((status == SEC_E_OK) || (status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED) || (status == SEC_I_CONTINUE_NEEDED)) {
+ outputToken = createSafeByteArray (static_cast<unsigned char *>(outputTokenBuffer.pvBuffer), outputTokenBuffer.cbBuffer);
+ SWIFT_LOG(debug) << "outputToken.size(): " << outputToken.size() << std::endl;
+ freeContextBuffer(outputTokenBuffer.pvBuffer);
+
+ return boost::shared_ptr<boost::system::error_code>(); /* success */
+ }
+
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> deleteSecurityContext(PCtxtHandle contextHandle) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- status = DeleteSecurityContext(contextHandle);
- ASSIGN_SEC_ERROR(status, errorCode);
+ status = DeleteSecurityContext(contextHandle);
+ ASSIGN_SEC_ERROR(status, errorCode);
- return errorCode;
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> completeAuthToken(const PCtxtHandle contextHandle, PSecBufferDesc token) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- status = CompleteAuthToken(
- contextHandle, /* partial context */
- token);
- ASSIGN_SEC_ERROR(status, errorCode);
+ status = CompleteAuthToken(
+ contextHandle, /* partial context */
+ token);
+ ASSIGN_SEC_ERROR(status, errorCode);
- return errorCode;
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> freeContextBuffer(PVOID contextBuffer) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- if (contextBuffer == NULL) {
- return errorCode;
- }
+ if (contextBuffer == NULL) {
+ return errorCode;
+ }
- status = FreeContextBuffer(contextBuffer);
- ASSIGN_SEC_ERROR(status, errorCode);
+ status = FreeContextBuffer(contextBuffer);
+ ASSIGN_SEC_ERROR(status, errorCode);
- return errorCode;
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> decryptMessage(const PCtxtHandle contextHandle, const ByteArray& message, SafeByteArray& decrypted) {
- /* Following https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
-
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
- SecBufferDesc inOut;
- SecBuffer messageBuffer[2];
- SafeByteArray inputMessage;
- ULONG qualityOfProtection;
-
- inOut.ulVersion = SECBUFFER_VERSION;
- inOut.cBuffers = 2;
- inOut.pBuffers = messageBuffer;
-
- inputMessage = createSafeByteArray (message); /* Make a copy as DecryptMessage decrypts the input in place, overwriting it */
- messageBuffer[0].BufferType = SECBUFFER_STREAM;
- messageBuffer[0].cbBuffer = inputMessage.size();
- messageBuffer[0].pvBuffer = static_cast<void *>(vecptr(inputMessage));
-
- messageBuffer[1].BufferType = SECBUFFER_DATA;
- messageBuffer[1].cbBuffer = 0;
- messageBuffer[1].pvBuffer = NULL;
-
- SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
-
- status = DecryptMessage(
- contextHandle,
- &inOut,
- 0, /* Don't maintain sequence numbers */
- &qualityOfProtection);
- ASSIGN_SEC_ERROR(status, errorCode);
- if (status == SEC_E_OK) {
- if (qualityOfProtection == SECQOP_WRAP_NO_ENCRYPT) {
- SWIFT_LOG(debug) << "Message was signed only" << std::endl;
- }
- else {
- SWIFT_LOG(debug) << "Message was encrypted" << std::endl;
- }
-
- SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
-
- decrypted = createSafeByteArray (static_cast<unsigned char *>(messageBuffer[1].pvBuffer), messageBuffer[1].cbBuffer);
- }
-
- return errorCode;
+ /* Following https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
+
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
+ SecBufferDesc inOut;
+ SecBuffer messageBuffer[2];
+ SafeByteArray inputMessage;
+ ULONG qualityOfProtection;
+
+ inOut.ulVersion = SECBUFFER_VERSION;
+ inOut.cBuffers = 2;
+ inOut.pBuffers = messageBuffer;
+
+ inputMessage = createSafeByteArray (message); /* Make a copy as DecryptMessage decrypts the input in place, overwriting it */
+ messageBuffer[0].BufferType = SECBUFFER_STREAM;
+ messageBuffer[0].cbBuffer = inputMessage.size();
+ messageBuffer[0].pvBuffer = static_cast<void *>(vecptr(inputMessage));
+
+ messageBuffer[1].BufferType = SECBUFFER_DATA;
+ messageBuffer[1].cbBuffer = 0;
+ messageBuffer[1].pvBuffer = NULL;
+
+ SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
+
+ status = DecryptMessage(
+ contextHandle,
+ &inOut,
+ 0, /* Don't maintain sequence numbers */
+ &qualityOfProtection);
+ ASSIGN_SEC_ERROR(status, errorCode);
+ if (status == SEC_E_OK) {
+ if (qualityOfProtection == SECQOP_WRAP_NO_ENCRYPT) {
+ SWIFT_LOG(debug) << "Message was signed only" << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "Message was encrypted" << std::endl;
+ }
+
+ SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
+
+ decrypted = createSafeByteArray (static_cast<unsigned char *>(messageBuffer[1].pvBuffer), messageBuffer[1].cbBuffer);
+ }
+
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> encryptMessage(const PCtxtHandle contextHandle, const SecPkgContext_Sizes& sizes, const SafeByteArray& message, SafeByteArray& output) {
- /* Following https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
-
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
- SecBufferDesc inOut;
- SecBuffer messageBuffer[3];
- SafeByteArray securityTrailer(sizes.cbSecurityTrailer);
- SafeByteArray blockSize(sizes.cbBlockSize);
- SafeByteArray inputMessage;
-
- inOut.ulVersion = SECBUFFER_VERSION;
- inOut.cBuffers = 3;
- inOut.pBuffers = messageBuffer;
-
- messageBuffer[0].BufferType = SECBUFFER_TOKEN;
- messageBuffer[0].cbBuffer = sizes.cbSecurityTrailer;
- messageBuffer[0].pvBuffer = vecptr(securityTrailer);
-
- inputMessage = createSafeByteArray (vecptr(message), message.size()); /* Make a copy as EncryptMessage encrypts the input in place, overwriting it */
- messageBuffer[1].BufferType = SECBUFFER_DATA;
- messageBuffer[1].cbBuffer = inputMessage.size();
- messageBuffer[1].pvBuffer = (void *) vecptr(inputMessage);
-
- messageBuffer[2].BufferType = SECBUFFER_PADDING;
- messageBuffer[2].cbBuffer = sizes.cbBlockSize;
- messageBuffer[2].pvBuffer = vecptr(blockSize);
-
- SWIFT_LOG(debug) << "sizes.cbSecurityTrailer: " << sizes.cbSecurityTrailer << std::endl;
- SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
- SWIFT_LOG(debug) << "sizes.cbBlockSize: " << sizes.cbBlockSize << std::endl;
-
- status = EncryptMessage(
- contextHandle,
- SECQOP_WRAP_NO_ENCRYPT,
- &inOut,
- 0); /* Don't maintain sequence numbers */
- ASSIGN_SEC_ERROR(status, errorCode);
- if (status == SEC_E_OK) {
- unsigned char* pointer;
-
- SWIFT_LOG(debug) << "messageBuffer[0].cbBuffer: " << messageBuffer[0].cbBuffer << std::endl;
- SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
- SWIFT_LOG(debug) << "messageBuffer[2].cbBuffer: " << messageBuffer[2].cbBuffer << std::endl;
-
- output.resize(messageBuffer[0].cbBuffer + messageBuffer[1].cbBuffer + messageBuffer[2].cbBuffer);
- pointer = vecptr(output);
- for (size_t i = 0; i < inOut.cBuffers; i++) {
- if (messageBuffer[i].cbBuffer) {
- memcpy(pointer, messageBuffer[i].pvBuffer, messageBuffer[i].cbBuffer);
- pointer += messageBuffer[i].cbBuffer;
- }
- }
- }
-
- return errorCode;
+ /* Following https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
+
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
+ SecBufferDesc inOut;
+ SecBuffer messageBuffer[3];
+ SafeByteArray securityTrailer(sizes.cbSecurityTrailer);
+ SafeByteArray blockSize(sizes.cbBlockSize);
+ SafeByteArray inputMessage;
+
+ inOut.ulVersion = SECBUFFER_VERSION;
+ inOut.cBuffers = 3;
+ inOut.pBuffers = messageBuffer;
+
+ messageBuffer[0].BufferType = SECBUFFER_TOKEN;
+ messageBuffer[0].cbBuffer = sizes.cbSecurityTrailer;
+ messageBuffer[0].pvBuffer = vecptr(securityTrailer);
+
+ inputMessage = createSafeByteArray (vecptr(message), message.size()); /* Make a copy as EncryptMessage encrypts the input in place, overwriting it */
+ messageBuffer[1].BufferType = SECBUFFER_DATA;
+ messageBuffer[1].cbBuffer = inputMessage.size();
+ messageBuffer[1].pvBuffer = (void *) vecptr(inputMessage);
+
+ messageBuffer[2].BufferType = SECBUFFER_PADDING;
+ messageBuffer[2].cbBuffer = sizes.cbBlockSize;
+ messageBuffer[2].pvBuffer = vecptr(blockSize);
+
+ SWIFT_LOG(debug) << "sizes.cbSecurityTrailer: " << sizes.cbSecurityTrailer << std::endl;
+ SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
+ SWIFT_LOG(debug) << "sizes.cbBlockSize: " << sizes.cbBlockSize << std::endl;
+
+ status = EncryptMessage(
+ contextHandle,
+ SECQOP_WRAP_NO_ENCRYPT,
+ &inOut,
+ 0); /* Don't maintain sequence numbers */
+ ASSIGN_SEC_ERROR(status, errorCode);
+ if (status == SEC_E_OK) {
+ unsigned char* pointer;
+
+ SWIFT_LOG(debug) << "messageBuffer[0].cbBuffer: " << messageBuffer[0].cbBuffer << std::endl;
+ SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
+ SWIFT_LOG(debug) << "messageBuffer[2].cbBuffer: " << messageBuffer[2].cbBuffer << std::endl;
+
+ output.resize(messageBuffer[0].cbBuffer + messageBuffer[1].cbBuffer + messageBuffer[2].cbBuffer);
+ pointer = vecptr(output);
+ for (size_t i = 0; i < inOut.cBuffers; i++) {
+ if (messageBuffer[i].cbBuffer) {
+ memcpy(pointer, messageBuffer[i].pvBuffer, messageBuffer[i].cbBuffer);
+ pointer += messageBuffer[i].cbBuffer;
+ }
+ }
+ }
+
+ return errorCode;
}
boost::shared_ptr<boost::system::error_code> queryContextAttributes(const PCtxtHandle contextHandle, ULONG attribute, PVOID buffer) {
- SECURITY_STATUS status;
- boost::shared_ptr<boost::system::error_code> errorCode;
+ SECURITY_STATUS status;
+ boost::shared_ptr<boost::system::error_code> errorCode;
- status = QueryContextAttributes(
- contextHandle,
- attribute,
- buffer);
- ASSIGN_SEC_ERROR(status, errorCode);
+ status = QueryContextAttributes(
+ contextHandle,
+ attribute,
+ buffer);
+ ASSIGN_SEC_ERROR(status, errorCode);
- return errorCode;
+ return errorCode;
}
}
diff --git a/Swiften/SASL/WindowsAuthentication.h b/Swiften/SASL/WindowsAuthentication.h
index 82e428c..e0cf4bc 100644
--- a/Swiften/SASL/WindowsAuthentication.h
+++ b/Swiften/SASL/WindowsAuthentication.h
@@ -17,154 +17,154 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- /**
- * Retrieves the names & Windows server domain of the user associated
- * with the calling thread.
- *
- * @param userName Will return the user name in the form "DOMAIN\user"
- * @param clientName Will return the client name in the form "user"
- * @param serverName Will return the server name in the form "DOMAIN"
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> getUserNameEx(std::string& userName, std::string& clientName, std::string& serverName);
+ /**
+ * Retrieves the names & Windows server domain of the user associated
+ * with the calling thread.
+ *
+ * @param userName Will return the user name in the form "DOMAIN\user"
+ * @param clientName Will return the client name in the form "user"
+ * @param serverName Will return the server name in the form "DOMAIN"
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> getUserNameEx(std::string& userName, std::string& clientName, std::string& serverName);
- /**
- * Retrieves the handle to preexisting client credentials for the
- * Kerberos security package that were established through a system
- * logon.
- * freeCredentialsHandle() should be called if this function is
- * successful and when credentials are no longer needed.
- *
- * @param credentialsHandle Pointer to the returned credentials handle.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> acquireCredentialsHandle(PCredHandle credentialsHandle);
+ /**
+ * Retrieves the handle to preexisting client credentials for the
+ * Kerberos security package that were established through a system
+ * logon.
+ * freeCredentialsHandle() should be called if this function is
+ * successful and when credentials are no longer needed.
+ *
+ * @param credentialsHandle Pointer to the returned credentials handle.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> acquireCredentialsHandle(PCredHandle credentialsHandle);
- /**
- * Releases the credentials handle obtained by the
- * acquireCredentialsHandle() function.
- * freeCredentialsHandle() should be called when credentials are no
- * longer needed.
- *
- * @param credentialsHandle Pointer to the credentials handle.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> freeCredentialsHandle(PCredHandle credentialsHandle);
+ /**
+ * Releases the credentials handle obtained by the
+ * acquireCredentialsHandle() function.
+ * freeCredentialsHandle() should be called when credentials are no
+ * longer needed.
+ *
+ * @param credentialsHandle Pointer to the credentials handle.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> freeCredentialsHandle(PCredHandle credentialsHandle);
- /**
- * Builds the security context between the client and remote peer.
- * Kerberos security package that were established through a system
- * logon.
- *
- * @param inputToken NULL or empty on the first call, otherwise the
- * token returned by the server.
- * @param servicePrincipalNameString Service principal name of the
- * server.
- * @param credentialsHandle Pointer to the credentials handle acquired
- * before.
- * @param haveContextHandle False on the first call to this function,
- * true otherwise.
- * @param contextHandle Pointer to the context handle returned on the
- * first call and passed on subsequent calls.
- * @param contextRequested Context related requests by the caller. See
- * the Windows API InitializeSecurityContext for allowed values.
- * @param contextSupported Pointer to context related attributes
- * returned when context is completely established (when
- * haveCompleteContext contains true). See the Windows API
- * InitializeSecurityContext for allowed values.
- * @param haveCompleteContext Pointer to boolean - this will only be
- * true on return when the context is completely established and
- * there is no need to call this function again.
- * @param outputToken Returned security token to be sent to the server,
- * may be empty.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> initializeSecurityContext(const boost::optional<ByteArray>& inputToken, const std::string& servicePrincipalNameString, const PCredHandle credentialsHandle, bool haveContextHandle, PCtxtHandle contextHandle, ULONG contextRequested, ULONG* contextSupported, bool* haveCompleteContext, SafeByteArray& outputToken);
+ /**
+ * Builds the security context between the client and remote peer.
+ * Kerberos security package that were established through a system
+ * logon.
+ *
+ * @param inputToken NULL or empty on the first call, otherwise the
+ * token returned by the server.
+ * @param servicePrincipalNameString Service principal name of the
+ * server.
+ * @param credentialsHandle Pointer to the credentials handle acquired
+ * before.
+ * @param haveContextHandle False on the first call to this function,
+ * true otherwise.
+ * @param contextHandle Pointer to the context handle returned on the
+ * first call and passed on subsequent calls.
+ * @param contextRequested Context related requests by the caller. See
+ * the Windows API InitializeSecurityContext for allowed values.
+ * @param contextSupported Pointer to context related attributes
+ * returned when context is completely established (when
+ * haveCompleteContext contains true). See the Windows API
+ * InitializeSecurityContext for allowed values.
+ * @param haveCompleteContext Pointer to boolean - this will only be
+ * true on return when the context is completely established and
+ * there is no need to call this function again.
+ * @param outputToken Returned security token to be sent to the server,
+ * may be empty.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> initializeSecurityContext(const boost::optional<ByteArray>& inputToken, const std::string& servicePrincipalNameString, const PCredHandle credentialsHandle, bool haveContextHandle, PCtxtHandle contextHandle, ULONG contextRequested, ULONG* contextSupported, bool* haveCompleteContext, SafeByteArray& outputToken);
- /**
- * Releases the context handle obtained by the
- * initializeSecurityContext() function.
- * deleteSecurityContext() should be called when the context is no
- * longer needed.
- *
- * @param contextHandle Pointer to the context handle.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> deleteSecurityContext(PCtxtHandle contextHandle);
+ /**
+ * Releases the context handle obtained by the
+ * initializeSecurityContext() function.
+ * deleteSecurityContext() should be called when the context is no
+ * longer needed.
+ *
+ * @param contextHandle Pointer to the context handle.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> deleteSecurityContext(PCtxtHandle contextHandle);
- /**
- * Completes an authentication token for a partial security context.
- *
- * @param contextHandle Pointer to the context handle.
- * @param token authentication token.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> completeAuthToken(const PCtxtHandle contextHandle, PSecBufferDesc token);
+ /**
+ * Completes an authentication token for a partial security context.
+ *
+ * @param contextHandle Pointer to the context handle.
+ * @param token authentication token.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> completeAuthToken(const PCtxtHandle contextHandle, PSecBufferDesc token);
- /**
- * Frees a memory buffer allocated by the security package.
- *
- * @param contextBuffer Pointer to buffer to be freed.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> freeContextBuffer(PVOID contextBuffer);
+ /**
+ * Frees a memory buffer allocated by the security package.
+ *
+ * @param contextBuffer Pointer to buffer to be freed.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> freeContextBuffer(PVOID contextBuffer);
- /**
- * Decrypt message (assumes that sequence numbers are not maintained).
- *
- * @param contextHandle Pointer to the context handle.
- * @param message Message to decrypt.
- * @param decrypted Returned decrypted message.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> decryptMessage(const PCtxtHandle contextHandle, const ByteArray& message, SafeByteArray& decrypted);
+ /**
+ * Decrypt message (assumes that sequence numbers are not maintained).
+ *
+ * @param contextHandle Pointer to the context handle.
+ * @param message Message to decrypt.
+ * @param decrypted Returned decrypted message.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> decryptMessage(const PCtxtHandle contextHandle, const ByteArray& message, SafeByteArray& decrypted);
- /**
- * Produces a header or trailer for the message but does not encrypt it
- * (also assumes that sequence numbers are not maintained).
- *
- * @param contextHandle Pointer to the context handle.
- * @param sizes SecPkgContext_Sizes obtained for the context.
- * @param message Input message.
- * @param output Returned output message.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> encryptMessage(const PCtxtHandle contextHandle, const SecPkgContext_Sizes& sizes, const SafeByteArray& message, SafeByteArray& output);
+ /**
+ * Produces a header or trailer for the message but does not encrypt it
+ * (also assumes that sequence numbers are not maintained).
+ *
+ * @param contextHandle Pointer to the context handle.
+ * @param sizes SecPkgContext_Sizes obtained for the context.
+ * @param message Input message.
+ * @param output Returned output message.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> encryptMessage(const PCtxtHandle contextHandle, const SecPkgContext_Sizes& sizes, const SafeByteArray& message, SafeByteArray& output);
- /**
- * Queries the security package for attributes of the security context.
- *
- * @param contextHandle Pointer to the context handle.
- * @param attribute Attribute to query. See the Windows API
- * QueryContextAttributes for allowed values.
- * @param buffer Pointer to a structure that receives the output.
- * The type of structure depends on the queried attribute and
- * memory for it must be allocated by caller. If the SSP allocates
- * any memory required to hold some members, that memory should be
- * freed using the function freeContextBuffer(). See the Windows
- * API QueryContextAttributes for details.
- *
- * @return NULL for success, otherwise the error code returned by
- * Windows.
- */
- SWIFTEN_API boost::shared_ptr<boost::system::error_code> queryContextAttributes(const PCtxtHandle contextHandle, ULONG attribute, PVOID buffer);
+ /**
+ * Queries the security package for attributes of the security context.
+ *
+ * @param contextHandle Pointer to the context handle.
+ * @param attribute Attribute to query. See the Windows API
+ * QueryContextAttributes for allowed values.
+ * @param buffer Pointer to a structure that receives the output.
+ * The type of structure depends on the queried attribute and
+ * memory for it must be allocated by caller. If the SSP allocates
+ * any memory required to hold some members, that memory should be
+ * freed using the function freeContextBuffer(). See the Windows
+ * API QueryContextAttributes for details.
+ *
+ * @return NULL for success, otherwise the error code returned by
+ * Windows.
+ */
+ SWIFTEN_API boost::shared_ptr<boost::system::error_code> queryContextAttributes(const PCtxtHandle contextHandle, ULONG attribute, PVOID buffer);
}
diff --git a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
index 12b0dc4..aae437f 100644
--- a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
+++ b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
@@ -15,183 +15,183 @@
namespace Swift {
WindowsGSSAPIClientAuthenticator::WindowsGSSAPIClientAuthenticator(const std::string& hostname, const std::string& domainname, int port) : ClientAuthenticator("GSSAPI"), step_(BuildingSecurityContext), error_(false), haveCredentialsHandle_(false), haveContextHandle_(false), haveCompleteContext_(false) {
- WindowsServicePrincipalName servicePrincipalName(domainname);
- servicePrincipalName.setInstanceName(hostname);
- if ((port != -1) && (port != 5222)) {
- servicePrincipalName.setInstancePort(port);
- }
- servicePrincipalNameString_ = servicePrincipalName.toString();
-
- errorCode_ = acquireCredentialsHandle(&credentialsHandle_);
- if (isError()) {
- return;
- }
- else {
- haveCredentialsHandle_ = true;
- }
-
- buildSecurityContext(boost::optional<ByteArray>());
+ WindowsServicePrincipalName servicePrincipalName(domainname);
+ servicePrincipalName.setInstanceName(hostname);
+ if ((port != -1) && (port != 5222)) {
+ servicePrincipalName.setInstancePort(port);
+ }
+ servicePrincipalNameString_ = servicePrincipalName.toString();
+
+ errorCode_ = acquireCredentialsHandle(&credentialsHandle_);
+ if (isError()) {
+ return;
+ }
+ else {
+ haveCredentialsHandle_ = true;
+ }
+
+ buildSecurityContext(boost::optional<ByteArray>());
}
WindowsGSSAPIClientAuthenticator::~WindowsGSSAPIClientAuthenticator() {
- if (haveContextHandle_) {
- deleteSecurityContext(&contextHandle_);
- }
+ if (haveContextHandle_) {
+ deleteSecurityContext(&contextHandle_);
+ }
- if (haveCredentialsHandle_) {
- freeCredentialsHandle(&credentialsHandle_);
- }
+ if (haveCredentialsHandle_) {
+ freeCredentialsHandle(&credentialsHandle_);
+ }
}
boost::optional<SafeByteArray> WindowsGSSAPIClientAuthenticator::getResponse() const {
- SWIFT_LOG(debug) << "response_.size(): " << response_.size() << std::endl;
- return response_;
+ SWIFT_LOG(debug) << "response_.size(): " << response_.size() << std::endl;
+ return response_;
}
bool WindowsGSSAPIClientAuthenticator::setChallenge(const boost::optional<ByteArray>& challengeData) {
- /* Following http://tools.ietf.org/html/rfc4752, https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
-
- if (step_ == BuildingSecurityContext) {
- buildSecurityContext(challengeData);
- }
- else if (step_ == SecurityLayerNegotiation) {
- if (!challengeData) {
- SWIFT_LOG(debug) << "Empty message received from the server" << std::endl;
- error_ = true;
- return false;
- }
-
- SafeByteArray challenge;
- errorCode_ = decryptMessage(&contextHandle_, challengeData.get(), challenge);
- if (isError()) {
- return false;
- }
-
- if (challenge.size() != 4) {
- SWIFT_LOG(debug) << "Token received from the server of incorrect length: " << challenge.size() << std::endl;
- error_ = true;
- return false;
- }
-
- unsigned char* challengePointer = vecptr(challenge);
-
- unsigned char serverSecurityLayer = challengePointer[0];
- if (serverSecurityLayer == 0) {
- SWIFT_LOG(debug) << "Server supports unknown security layer, assuming no security layer" << std::endl;
- serverSecurityLayer = SECURITY_LAYER_NONE;
- }
- else if (serverSecurityLayer == SECURITY_LAYER_NONE) {
- SWIFT_LOG(debug) << "Server supports no security layer" << std::endl;
- }
- else {
- SWIFT_LOG(debug) << "Server supports security layer" << std::endl;
- }
-
- unsigned int serverMaximumBuffer = (challengePointer[1] << 16) |
- (challengePointer[2] << 8) |
- (challengePointer[3] << 0);
-
- if ((serverSecurityLayer == SECURITY_LAYER_NONE) && (serverMaximumBuffer != 0)) {
- SWIFT_LOG(debug) << "Server supports no security layer but has maximum buffer size" << serverMaximumBuffer << std::endl;
- error_ = true;
- return false;
- }
-
- SafeByteArray message(4);
-
- /* Commenting this out as streamSizes was not obtained before
- if (message.size() > streamSizes_.cbMaximumMessage) {
- error_ = true;
- return false;
- } */
-
- unsigned char* messagePointer = vecptr(message);
- messagePointer[0] = SECURITY_LAYER_NONE;
-
- /* The next 3 bytes indicate the client's maximum size buffer which is set to 0 as we do not support a security layer */
- messagePointer[1] = 0;
- messagePointer[2] = 0;
- messagePointer[3] = 0;
-
- /* The authorization identity is omitted as it is the same as the authentication identity */
-
- errorCode_ = encryptMessage(&contextHandle_, sizes_, message, response_);
- if (isError()) {
- return false;
- }
-
- step_ = ServerAuthenticated;
- }
-
- if (isError()) {
- return false;
- }
-
- return true;
+ /* Following http://tools.ietf.org/html/rfc4752, https://msdn.microsoft.com/en-us/library/windows/desktop/aa380496%28v=vs.85%29.aspx */
+
+ if (step_ == BuildingSecurityContext) {
+ buildSecurityContext(challengeData);
+ }
+ else if (step_ == SecurityLayerNegotiation) {
+ if (!challengeData) {
+ SWIFT_LOG(debug) << "Empty message received from the server" << std::endl;
+ error_ = true;
+ return false;
+ }
+
+ SafeByteArray challenge;
+ errorCode_ = decryptMessage(&contextHandle_, challengeData.get(), challenge);
+ if (isError()) {
+ return false;
+ }
+
+ if (challenge.size() != 4) {
+ SWIFT_LOG(debug) << "Token received from the server of incorrect length: " << challenge.size() << std::endl;
+ error_ = true;
+ return false;
+ }
+
+ unsigned char* challengePointer = vecptr(challenge);
+
+ unsigned char serverSecurityLayer = challengePointer[0];
+ if (serverSecurityLayer == 0) {
+ SWIFT_LOG(debug) << "Server supports unknown security layer, assuming no security layer" << std::endl;
+ serverSecurityLayer = SECURITY_LAYER_NONE;
+ }
+ else if (serverSecurityLayer == SECURITY_LAYER_NONE) {
+ SWIFT_LOG(debug) << "Server supports no security layer" << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "Server supports security layer" << std::endl;
+ }
+
+ unsigned int serverMaximumBuffer = (challengePointer[1] << 16) |
+ (challengePointer[2] << 8) |
+ (challengePointer[3] << 0);
+
+ if ((serverSecurityLayer == SECURITY_LAYER_NONE) && (serverMaximumBuffer != 0)) {
+ SWIFT_LOG(debug) << "Server supports no security layer but has maximum buffer size" << serverMaximumBuffer << std::endl;
+ error_ = true;
+ return false;
+ }
+
+ SafeByteArray message(4);
+
+ /* Commenting this out as streamSizes was not obtained before
+ if (message.size() > streamSizes_.cbMaximumMessage) {
+ error_ = true;
+ return false;
+ } */
+
+ unsigned char* messagePointer = vecptr(message);
+ messagePointer[0] = SECURITY_LAYER_NONE;
+
+ /* The next 3 bytes indicate the client's maximum size buffer which is set to 0 as we do not support a security layer */
+ messagePointer[1] = 0;
+ messagePointer[2] = 0;
+ messagePointer[3] = 0;
+
+ /* The authorization identity is omitted as it is the same as the authentication identity */
+
+ errorCode_ = encryptMessage(&contextHandle_, sizes_, message, response_);
+ if (isError()) {
+ return false;
+ }
+
+ step_ = ServerAuthenticated;
+ }
+
+ if (isError()) {
+ return false;
+ }
+
+ return true;
}
bool WindowsGSSAPIClientAuthenticator::isError() {
- if (error_) {
- return true;
- }
+ if (error_) {
+ return true;
+ }
- if (!errorCode_) {
- return false;
- }
+ if (!errorCode_) {
+ return false;
+ }
- return true;
+ return true;
}
void WindowsGSSAPIClientAuthenticator::buildSecurityContext(const boost::optional<ByteArray>& inputToken) {
- ULONG contextSupported;
-
- /* An XMPP server may not support Kerberos encryption or SASL security layer so not requesting integrity or confidentiality */
- errorCode_ = initializeSecurityContext(inputToken, servicePrincipalNameString_, &credentialsHandle_, haveContextHandle_, &contextHandle_, ISC_REQ_MUTUAL_AUTH, &contextSupported, &haveCompleteContext_, response_);
- if (isError()) {
- return;
- }
-
- haveContextHandle_ = true;
-
- if (!haveCompleteContext_) {
- return;
- }
-
- if (contextSupported & ISC_REQ_MUTUAL_AUTH == 0) {
- SWIFT_LOG(debug) << "Mutual authentication not supported" << std::endl;
- error_ = true;
- return;
- }
-
- errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_SIZES, &sizes_);
- if (isError()) {
- return;
- }
-
- /* Commenting this out as it gives the error code 0x80090302: The function requested is not supported
- errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_STREAM_SIZES, &streamSizes_);
- if (isError()) {
- return;
- }*/
-
- SecPkgContext_Names names;
- errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_NAMES, &names);
- if (isError()) {
- return;
- }
-
- userName_ = names.sUserName;
- SWIFT_LOG(debug) << "User name: " << userName_ << std::endl;
-
- std::size_t position = userName_.find("\\");
- clientName_ = userName_.substr(position + 1);
- SWIFT_LOG(debug) << "Client name: " << clientName_ << std::endl;
-
- serverName_ = userName_.substr(0, position);
- SWIFT_LOG(debug) << "Server name: " << serverName_ << std::endl;
-
- freeContextBuffer(names.sUserName);
- step_ = SecurityLayerNegotiation;
+ ULONG contextSupported;
+
+ /* An XMPP server may not support Kerberos encryption or SASL security layer so not requesting integrity or confidentiality */
+ errorCode_ = initializeSecurityContext(inputToken, servicePrincipalNameString_, &credentialsHandle_, haveContextHandle_, &contextHandle_, ISC_REQ_MUTUAL_AUTH, &contextSupported, &haveCompleteContext_, response_);
+ if (isError()) {
+ return;
+ }
+
+ haveContextHandle_ = true;
+
+ if (!haveCompleteContext_) {
+ return;
+ }
+
+ if (contextSupported & ISC_REQ_MUTUAL_AUTH == 0) {
+ SWIFT_LOG(debug) << "Mutual authentication not supported" << std::endl;
+ error_ = true;
+ return;
+ }
+
+ errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_SIZES, &sizes_);
+ if (isError()) {
+ return;
+ }
+
+ /* Commenting this out as it gives the error code 0x80090302: The function requested is not supported
+ errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_STREAM_SIZES, &streamSizes_);
+ if (isError()) {
+ return;
+ }*/
+
+ SecPkgContext_Names names;
+ errorCode_ = queryContextAttributes(&contextHandle_, SECPKG_ATTR_NAMES, &names);
+ if (isError()) {
+ return;
+ }
+
+ userName_ = names.sUserName;
+ SWIFT_LOG(debug) << "User name: " << userName_ << std::endl;
+
+ std::size_t position = userName_.find("\\");
+ clientName_ = userName_.substr(position + 1);
+ SWIFT_LOG(debug) << "Client name: " << clientName_ << std::endl;
+
+ serverName_ = userName_.substr(0, position);
+ SWIFT_LOG(debug) << "Server name: " << serverName_ << std::endl;
+
+ freeContextBuffer(names.sUserName);
+ step_ = SecurityLayerNegotiation;
}
}
diff --git a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.h b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.h
index a249ba4..c48d4dc 100644
--- a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.h
+++ b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.h
@@ -18,102 +18,102 @@
#include <Swiften/SASL/ClientAuthenticator.h>
namespace Swift {
- class SWIFTEN_API WindowsGSSAPIClientAuthenticator : public ClientAuthenticator {
- public:
- WindowsGSSAPIClientAuthenticator(const std::string& hostname, const std::string& domainname, int port);
+ class SWIFTEN_API WindowsGSSAPIClientAuthenticator : public ClientAuthenticator {
+ public:
+ WindowsGSSAPIClientAuthenticator(const std::string& hostname, const std::string& domainname, int port);
- virtual ~WindowsGSSAPIClientAuthenticator();
+ virtual ~WindowsGSSAPIClientAuthenticator();
- virtual boost::optional<SafeByteArray> getResponse() const;
- virtual bool setChallenge(const boost::optional<std::vector<unsigned char> >&);
+ virtual boost::optional<SafeByteArray> getResponse() const;
+ virtual bool setChallenge(const boost::optional<std::vector<unsigned char> >&);
- /**
- * Returns whether the authenticator has the complete
- * security context. It could be true before any
- * message exchanges with the server or after some
- * messages have been exchanged.
- *
- * @return True if security context is complete.
- */
- bool isCompleteContext() {
- return haveCompleteContext_;
- }
+ /**
+ * Returns whether the authenticator has the complete
+ * security context. It could be true before any
+ * message exchanges with the server or after some
+ * messages have been exchanged.
+ *
+ * @return True if security context is complete.
+ */
+ bool isCompleteContext() {
+ return haveCompleteContext_;
+ }
- /**
- * Retrieves the user name associated with the
- * security context. It will only be set when
- * isCompleteContext() returns true.
- *
- * @return User name in the form "EXAMPLE.COM\user".
- */
- const std::string& getUserName() {
- return userName_;
- }
+ /**
+ * Retrieves the user name associated with the
+ * security context. It will only be set when
+ * isCompleteContext() returns true.
+ *
+ * @return User name in the form "EXAMPLE.COM\user".
+ */
+ const std::string& getUserName() {
+ return userName_;
+ }
- /**
- * Retrieves the client part of the user name
- * associated with the security context. It will only
- * be set when isCompleteContext() returns true.
- *
- * @return Client name in the form "user" when the user
- * name is "EXAMPLE.COM\user".
- */
- const std::string& getClientName() {
- return clientName_;
- }
+ /**
+ * Retrieves the client part of the user name
+ * associated with the security context. It will only
+ * be set when isCompleteContext() returns true.
+ *
+ * @return Client name in the form "user" when the user
+ * name is "EXAMPLE.COM\user".
+ */
+ const std::string& getClientName() {
+ return clientName_;
+ }
- /**
- * Retrieves the server name associated with the
- * security context. It will only be set when
- * isCompleteContext() returns true.
- *
- * @return Server name in the form "EXAMPLE.COM".
- */
- const std::string& getServerName() {
- return serverName_;
- }
+ /**
+ * Retrieves the server name associated with the
+ * security context. It will only be set when
+ * isCompleteContext() returns true.
+ *
+ * @return Server name in the form "EXAMPLE.COM".
+ */
+ const std::string& getServerName() {
+ return serverName_;
+ }
- /**
- * Returns whether an error has occurred at any point,
- * including in the constructor.
- *
- * @return True if an error has occured.
- */
- bool isError();
+ /**
+ * Returns whether an error has occurred at any point,
+ * including in the constructor.
+ *
+ * @return True if an error has occured.
+ */
+ bool isError();
- /**
- * Returns error details if isError() returns true.
- * May be empty if there are no details to be provided
- * for the error.
- *
- * @return Error details.
- */
- boost::shared_ptr<boost::system::error_code> getErrorCode() {
- return errorCode_;
- }
+ /**
+ * Returns error details if isError() returns true.
+ * May be empty if there are no details to be provided
+ * for the error.
+ *
+ * @return Error details.
+ */
+ boost::shared_ptr<boost::system::error_code> getErrorCode() {
+ return errorCode_;
+ }
- private:
- void buildSecurityContext(const boost::optional<ByteArray>& inputToken);
+ private:
+ void buildSecurityContext(const boost::optional<ByteArray>& inputToken);
- private:
- enum Step {
- BuildingSecurityContext,
- SecurityLayerNegotiation,
- ServerAuthenticated
- } step_;
- bool error_;
- boost::shared_ptr<boost::system::error_code> errorCode_;
- std::string servicePrincipalNameString_;
- bool haveCredentialsHandle_;
- bool haveContextHandle_;
- bool haveCompleteContext_;
- CredHandle credentialsHandle_;
- CtxtHandle contextHandle_;
- SecPkgContext_Sizes sizes_;
- SecPkgContext_StreamSizes streamSizes_;
- std::string userName_;
- std::string clientName_;
- std::string serverName_;
- SafeByteArray response_;
- };
+ private:
+ enum Step {
+ BuildingSecurityContext,
+ SecurityLayerNegotiation,
+ ServerAuthenticated
+ } step_;
+ bool error_;
+ boost::shared_ptr<boost::system::error_code> errorCode_;
+ std::string servicePrincipalNameString_;
+ bool haveCredentialsHandle_;
+ bool haveContextHandle_;
+ bool haveCompleteContext_;
+ CredHandle credentialsHandle_;
+ CtxtHandle contextHandle_;
+ SecPkgContext_Sizes sizes_;
+ SecPkgContext_StreamSizes streamSizes_;
+ std::string userName_;
+ std::string clientName_;
+ std::string serverName_;
+ SafeByteArray response_;
+ };
}
diff --git a/Swiften/SASL/WindowsServicePrincipalName.cpp b/Swiften/SASL/WindowsServicePrincipalName.cpp
index 187e9ac..419395c 100644
--- a/Swiften/SASL/WindowsServicePrincipalName.cpp
+++ b/Swiften/SASL/WindowsServicePrincipalName.cpp
@@ -17,90 +17,90 @@
namespace Swift {
WindowsServicePrincipalName::WindowsServicePrincipalName(const std::string& serviceName) : serviceClass_(L"xmpp"), instancePort_(0) {
- serviceName_ = convertStringToWString(serviceName);
+ serviceName_ = convertStringToWString(serviceName);
}
WindowsServicePrincipalName::~WindowsServicePrincipalName() {
}
void WindowsServicePrincipalName::setServiceClass(const std::string& serviceClass) {
- serviceClass_ = convertStringToWString(serviceClass);
+ serviceClass_ = convertStringToWString(serviceClass);
}
void WindowsServicePrincipalName::setInstanceName(const std::string& instanceName) {
- instanceName_ = convertStringToWString(instanceName);
+ instanceName_ = convertStringToWString(instanceName);
}
void WindowsServicePrincipalName::setReferrer(const std::string& referrer) {
- referrer_ = convertStringToWString(referrer);
+ referrer_ = convertStringToWString(referrer);
}
std::string WindowsServicePrincipalName::toString() {
- DWORD length = 512;
- DWORD status = ERROR_BUFFER_OVERFLOW;
- bool firstCall = true;
- std::string str;
+ DWORD length = 512;
+ DWORD status = ERROR_BUFFER_OVERFLOW;
+ bool firstCall = true;
+ std::string str;
- while (status == ERROR_BUFFER_OVERFLOW) {
- std::vector<wchar_t> value(length);
+ while (status == ERROR_BUFFER_OVERFLOW) {
+ std::vector<wchar_t> value(length);
- /* length after this call will contain the required length if current length is not enough - so the next call should succeed */
- status = dsMakeSpn(&length, vecptr(value));
- if (status == ERROR_SUCCESS) {
- str = convertWStringToString(std::wstring(vecptr(value), length-1 /* trailing 0 character */));
- break;
- }
+ /* length after this call will contain the required length if current length is not enough - so the next call should succeed */
+ status = dsMakeSpn(&length, vecptr(value));
+ if (status == ERROR_SUCCESS) {
+ str = convertWStringToString(std::wstring(vecptr(value), length-1 /* trailing 0 character */));
+ break;
+ }
- if ((firstCall == false) || (status != ERROR_BUFFER_OVERFLOW)) {
- std::stringstream errorString;
- boost::system::error_code errorCode(status, boost::system::system_category());
+ if ((firstCall == false) || (status != ERROR_BUFFER_OVERFLOW)) {
+ std::stringstream errorString;
+ boost::system::error_code errorCode(status, boost::system::system_category());
- errorString << "Error creating Service Principal Name: status: 0x" << std::hex << status << ": " << errorCode.message();
+ errorString << "Error creating Service Principal Name: status: 0x" << std::hex << status << ": " << errorCode.message();
- /* Any other error will be a programming error */
- throw std::runtime_error(errorString.str());
- }
+ /* Any other error will be a programming error */
+ throw std::runtime_error(errorString.str());
+ }
- firstCall = false;
- }
+ firstCall = false;
+ }
- SWIFT_LOG(debug) << "SPN: " << str << std::endl;
- return str;
+ SWIFT_LOG(debug) << "SPN: " << str << std::endl;
+ return str;
}
DWORD WindowsServicePrincipalName::dsMakeSpn(DWORD* length, wchar_t* value) {
- DWORD status;
+ DWORD status;
#ifdef UNICODE
- SWIFT_LOG(debug) << "UNICODE is defined" << std::endl;
+ SWIFT_LOG(debug) << "UNICODE is defined" << std::endl;
#else
- SWIFT_LOG(debug) << "UNICODE is not defined" << std::endl;
+ SWIFT_LOG(debug) << "UNICODE is not defined" << std::endl;
#endif
- SWIFT_LOG(debug) << "serviceClass_: " << convertWStringToString(serviceClass_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "serviceName_: " << convertWStringToString(serviceName_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "instanceName_: " << convertWStringToString(instanceName_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "referrer_: " << convertWStringToString(referrer_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "instancePort_: " << instancePort_ << std::endl;
- SWIFT_LOG(debug) << "length: " << *length << std::endl;
+ SWIFT_LOG(debug) << "serviceClass_: " << convertWStringToString(serviceClass_.c_str()) << std::endl;
+ SWIFT_LOG(debug) << "serviceName_: " << convertWStringToString(serviceName_.c_str()) << std::endl;
+ SWIFT_LOG(debug) << "instanceName_: " << convertWStringToString(instanceName_.c_str()) << std::endl;
+ SWIFT_LOG(debug) << "referrer_: " << convertWStringToString(referrer_.c_str()) << std::endl;
+ SWIFT_LOG(debug) << "instancePort_: " << instancePort_ << std::endl;
+ SWIFT_LOG(debug) << "length: " << *length << std::endl;
- /* Call the Unicode function because that is recommended:
+ /* Call the Unicode function because that is recommended:
https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.aspx */
- status = DsMakeSpnW(
- serviceClass_.c_str(),
- serviceName_.c_str(),
- instanceName_.empty() ? NULL : instanceName_.c_str(),
- instancePort_,
- referrer_.empty() ? NULL : referrer_.c_str(),
- length,
- value);
- if (status != ERROR_SUCCESS) {
- boost::system::error_code errorCode(status, boost::system::system_category());
-
- SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode.message() << std::endl;
- }
-
- return status;
+ status = DsMakeSpnW(
+ serviceClass_.c_str(),
+ serviceName_.c_str(),
+ instanceName_.empty() ? NULL : instanceName_.c_str(),
+ instancePort_,
+ referrer_.empty() ? NULL : referrer_.c_str(),
+ length,
+ value);
+ if (status != ERROR_SUCCESS) {
+ boost::system::error_code errorCode(status, boost::system::system_category());
+
+ SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode.message() << std::endl;
+ }
+
+ return status;
}
}
diff --git a/Swiften/SASL/WindowsServicePrincipalName.h b/Swiften/SASL/WindowsServicePrincipalName.h
index dc97c93..4c9f557 100644
--- a/Swiften/SASL/WindowsServicePrincipalName.h
+++ b/Swiften/SASL/WindowsServicePrincipalName.h
@@ -13,59 +13,59 @@
#include <Swiften/Base/API.h>
namespace Swift {
- /*
- * This represents the SPN used on Windows to identify a service
- * instance.
- */
- class SWIFTEN_API WindowsServicePrincipalName {
- public:
- /*
- * This assigns the provided service name,
- * "xmpp" service class, no instance name or referrer,
- * and default port. All of these (except the service
- * name) can be set to other values using the provided
- * methods.
- * If the constructor is called with the service name
- * "hostname.example.com" and the provided methods are
- * not used to change the defaults, then toString()
- * will return the SPN "xmpp/hostname.example.com".
- */
- WindowsServicePrincipalName(const std::string& serviceName);
+ /*
+ * This represents the SPN used on Windows to identify a service
+ * instance.
+ */
+ class SWIFTEN_API WindowsServicePrincipalName {
+ public:
+ /*
+ * This assigns the provided service name,
+ * "xmpp" service class, no instance name or referrer,
+ * and default port. All of these (except the service
+ * name) can be set to other values using the provided
+ * methods.
+ * If the constructor is called with the service name
+ * "hostname.example.com" and the provided methods are
+ * not used to change the defaults, then toString()
+ * will return the SPN "xmpp/hostname.example.com".
+ */
+ WindowsServicePrincipalName(const std::string& serviceName);
- ~WindowsServicePrincipalName();
+ ~WindowsServicePrincipalName();
- void setServiceClass(const std::string& serviceClass);
+ void setServiceClass(const std::string& serviceClass);
- void setInstanceName(const std::string& instanceName);
+ void setInstanceName(const std::string& instanceName);
- void setReferrer(const std::string& referrer);
+ void setReferrer(const std::string& referrer);
- /*
- * This sets a non-default port for the service. Note
- * that the default value is 0 which indicates the
- * default port for the service. So if the XMPP service
- * is using the default port of 5222 for client
- * connections, then do not set the port to 5222 but let
- * it remain 0 to indicate that the default port is
- * used.
- */
- void setInstancePort(short int instancePort) { instancePort_ = instancePort; }
+ /*
+ * This sets a non-default port for the service. Note
+ * that the default value is 0 which indicates the
+ * default port for the service. So if the XMPP service
+ * is using the default port of 5222 for client
+ * connections, then do not set the port to 5222 but let
+ * it remain 0 to indicate that the default port is
+ * used.
+ */
+ void setInstancePort(short int instancePort) { instancePort_ = instancePort; }
- /*
- * This follows the rules of SPN creation on Windows and
- * returns the SPN string constructed from the set
- * values.
- */
- std::string toString();
+ /*
+ * This follows the rules of SPN creation on Windows and
+ * returns the SPN string constructed from the set
+ * values.
+ */
+ std::string toString();
- private:
- DWORD dsMakeSpn(DWORD* length, wchar_t* value);
+ private:
+ DWORD dsMakeSpn(DWORD* length, wchar_t* value);
- private:
- std::wstring serviceClass_;
- std::wstring serviceName_;
- std::wstring instanceName_;
- USHORT instancePort_;
- std::wstring referrer_;
- };
+ private:
+ std::wstring serviceClass_;
+ std::wstring serviceName_;
+ std::wstring instanceName_;
+ USHORT instancePort_;
+ std::wstring referrer_;
+ };
}
diff --git a/Swiften/Serializer/AuthChallengeSerializer.cpp b/Swiften/Serializer/AuthChallengeSerializer.cpp
index a9f573f..2796a2d 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.cpp
+++ b/Swiften/Serializer/AuthChallengeSerializer.cpp
@@ -16,18 +16,18 @@ AuthChallengeSerializer::AuthChallengeSerializer() {
}
SafeByteArray AuthChallengeSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<AuthChallenge> authChallenge(boost::dynamic_pointer_cast<AuthChallenge>(element));
- std::string value;
- boost::optional<std::vector<unsigned char> > message = authChallenge->getValue();
- if (message) {
- if ((*message).empty()) {
- value = "=";
- }
- else {
- value = Base64::encode(ByteArray(*message));
- }
- }
- return createSafeByteArray("<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + value + "</challenge>");
+ boost::shared_ptr<AuthChallenge> authChallenge(boost::dynamic_pointer_cast<AuthChallenge>(element));
+ std::string value;
+ boost::optional<std::vector<unsigned char> > message = authChallenge->getValue();
+ if (message) {
+ if ((*message).empty()) {
+ value = "=";
+ }
+ else {
+ value = Base64::encode(ByteArray(*message));
+ }
+ }
+ return createSafeByteArray("<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + value + "</challenge>");
}
}
diff --git a/Swiften/Serializer/AuthChallengeSerializer.h b/Swiften/Serializer/AuthChallengeSerializer.h
index 4d6915a..6c88d0a 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.h
+++ b/Swiften/Serializer/AuthChallengeSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API AuthChallengeSerializer : public GenericElementSerializer<AuthChallenge> {
- public:
- AuthChallengeSerializer();
+ class SWIFTEN_API AuthChallengeSerializer : public GenericElementSerializer<AuthChallenge> {
+ public:
+ AuthChallengeSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthFailureSerializer.h b/Swiften/Serializer/AuthFailureSerializer.h
index 9c1d66e..fe85d2c 100644
--- a/Swiften/Serializer/AuthFailureSerializer.h
+++ b/Swiften/Serializer/AuthFailureSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API AuthFailureSerializer : public GenericElementSerializer<AuthFailure> {
- public:
- AuthFailureSerializer() : GenericElementSerializer<AuthFailure>() {
- }
+ class SWIFTEN_API AuthFailureSerializer : public GenericElementSerializer<AuthFailure> {
+ public:
+ AuthFailureSerializer() : GenericElementSerializer<AuthFailure>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-sasl").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-sasl").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/AuthRequestSerializer.cpp b/Swiften/Serializer/AuthRequestSerializer.cpp
index bde0d2d..f479eac 100644
--- a/Swiften/Serializer/AuthRequestSerializer.cpp
+++ b/Swiften/Serializer/AuthRequestSerializer.cpp
@@ -17,18 +17,18 @@ AuthRequestSerializer::AuthRequestSerializer() {
}
SafeByteArray AuthRequestSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<AuthRequest> authRequest(boost::dynamic_pointer_cast<AuthRequest>(element));
- SafeByteArray value;
- boost::optional<SafeByteArray> message = authRequest->getMessage();
- if (message) {
- if ((*message).empty()) {
- value = createSafeByteArray("=");
- }
- else {
- value = Base64::encode(*message);
- }
- }
- return concat(createSafeByteArray("<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"" + authRequest->getMechanism() + "\">"), value, createSafeByteArray("</auth>"));
+ boost::shared_ptr<AuthRequest> authRequest(boost::dynamic_pointer_cast<AuthRequest>(element));
+ SafeByteArray value;
+ boost::optional<SafeByteArray> message = authRequest->getMessage();
+ if (message) {
+ if ((*message).empty()) {
+ value = createSafeByteArray("=");
+ }
+ else {
+ value = Base64::encode(*message);
+ }
+ }
+ return concat(createSafeByteArray("<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"" + authRequest->getMechanism() + "\">"), value, createSafeByteArray("</auth>"));
}
}
diff --git a/Swiften/Serializer/AuthRequestSerializer.h b/Swiften/Serializer/AuthRequestSerializer.h
index c4c59ff..8522c35 100644
--- a/Swiften/Serializer/AuthRequestSerializer.h
+++ b/Swiften/Serializer/AuthRequestSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API AuthRequestSerializer : public GenericElementSerializer<AuthRequest> {
- public:
- AuthRequestSerializer();
+ class SWIFTEN_API AuthRequestSerializer : public GenericElementSerializer<AuthRequest> {
+ public:
+ AuthRequestSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthResponseSerializer.cpp b/Swiften/Serializer/AuthResponseSerializer.cpp
index 0f3128b..b4be521 100644
--- a/Swiften/Serializer/AuthResponseSerializer.cpp
+++ b/Swiften/Serializer/AuthResponseSerializer.cpp
@@ -16,19 +16,19 @@ namespace Swift {
AuthResponseSerializer::AuthResponseSerializer() {
}
-SafeByteArray AuthResponseSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<AuthResponse> authResponse(boost::dynamic_pointer_cast<AuthResponse>(element));
- SafeByteArray value;
- boost::optional<SafeByteArray> message = authResponse->getValue();
- if (message) {
- if ((*message).empty()) {
- value = createSafeByteArray("");
- }
- else {
- value = Base64::encode(*message);
- }
- }
- return concat(createSafeByteArray("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"), value, createSafeByteArray("</response>"));
+SafeByteArray AuthResponseSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
+ boost::shared_ptr<AuthResponse> authResponse(boost::dynamic_pointer_cast<AuthResponse>(element));
+ SafeByteArray value;
+ boost::optional<SafeByteArray> message = authResponse->getValue();
+ if (message) {
+ if ((*message).empty()) {
+ value = createSafeByteArray("");
+ }
+ else {
+ value = Base64::encode(*message);
+ }
+ }
+ return concat(createSafeByteArray("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"), value, createSafeByteArray("</response>"));
}
}
diff --git a/Swiften/Serializer/AuthResponseSerializer.h b/Swiften/Serializer/AuthResponseSerializer.h
index 52b1d07..2017f75 100644
--- a/Swiften/Serializer/AuthResponseSerializer.h
+++ b/Swiften/Serializer/AuthResponseSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API AuthResponseSerializer : public GenericElementSerializer<AuthResponse> {
- public:
- AuthResponseSerializer();
+ class SWIFTEN_API AuthResponseSerializer : public GenericElementSerializer<AuthResponse> {
+ public:
+ AuthResponseSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthSuccessSerializer.cpp b/Swiften/Serializer/AuthSuccessSerializer.cpp
index d506fb9..78fe6a1 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.cpp
+++ b/Swiften/Serializer/AuthSuccessSerializer.cpp
@@ -16,18 +16,18 @@ AuthSuccessSerializer::AuthSuccessSerializer() {
}
SafeByteArray AuthSuccessSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<AuthSuccess> authSuccess(boost::dynamic_pointer_cast<AuthSuccess>(element));
- std::string value;
- boost::optional<std::vector<unsigned char> > message = authSuccess->getValue();
- if (message) {
- if ((*message).empty()) {
- value = "=";
- }
- else {
- value = Base64::encode(ByteArray(*message));
- }
- }
- return createSafeByteArray("<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + value + "</success>");
+ boost::shared_ptr<AuthSuccess> authSuccess(boost::dynamic_pointer_cast<AuthSuccess>(element));
+ std::string value;
+ boost::optional<std::vector<unsigned char> > message = authSuccess->getValue();
+ if (message) {
+ if ((*message).empty()) {
+ value = "=";
+ }
+ else {
+ value = Base64::encode(ByteArray(*message));
+ }
+ }
+ return createSafeByteArray("<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + value + "</success>");
}
}
diff --git a/Swiften/Serializer/AuthSuccessSerializer.h b/Swiften/Serializer/AuthSuccessSerializer.h
index 87fa846..99133fa 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.h
+++ b/Swiften/Serializer/AuthSuccessSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API AuthSuccessSerializer : public GenericElementSerializer<AuthSuccess> {
- public:
- AuthSuccessSerializer();
+ class SWIFTEN_API AuthSuccessSerializer : public GenericElementSerializer<AuthSuccess> {
+ public:
+ AuthSuccessSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/ComponentHandshakeSerializer.cpp b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
index 0611b17..1ac1ce7 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.cpp
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
@@ -14,8 +14,8 @@ ComponentHandshakeSerializer::ComponentHandshakeSerializer() {
}
SafeByteArray ComponentHandshakeSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<ComponentHandshake> handshake(boost::dynamic_pointer_cast<ComponentHandshake>(element));
- return createSafeByteArray("<handshake>" + handshake->getData() + "</handshake>");
+ boost::shared_ptr<ComponentHandshake> handshake(boost::dynamic_pointer_cast<ComponentHandshake>(element));
+ return createSafeByteArray("<handshake>" + handshake->getData() + "</handshake>");
}
}
diff --git a/Swiften/Serializer/ComponentHandshakeSerializer.h b/Swiften/Serializer/ComponentHandshakeSerializer.h
index 0d102e2..651903f 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.h
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API ComponentHandshakeSerializer : public GenericElementSerializer<ComponentHandshake> {
- public:
- ComponentHandshakeSerializer();
+ class SWIFTEN_API ComponentHandshakeSerializer : public GenericElementSerializer<ComponentHandshake> {
+ public:
+ ComponentHandshakeSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/CompressFailureSerializer.h b/Swiften/Serializer/CompressFailureSerializer.h
index e20d458..154f167 100644
--- a/Swiften/Serializer/CompressFailureSerializer.h
+++ b/Swiften/Serializer/CompressFailureSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API CompressFailureSerializer : public GenericElementSerializer<CompressFailure> {
- public:
- CompressFailureSerializer() : GenericElementSerializer<CompressFailure>() {
- }
+ class SWIFTEN_API CompressFailureSerializer : public GenericElementSerializer<CompressFailure> {
+ public:
+ CompressFailureSerializer() : GenericElementSerializer<CompressFailure>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("failure", "http://jabber.org/protocol/compress").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("failure", "http://jabber.org/protocol/compress").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/CompressRequestSerializer.cpp b/Swiften/Serializer/CompressRequestSerializer.cpp
index aecf9f4..c053cca 100644
--- a/Swiften/Serializer/CompressRequestSerializer.cpp
+++ b/Swiften/Serializer/CompressRequestSerializer.cpp
@@ -14,12 +14,12 @@ CompressRequestSerializer::CompressRequestSerializer() {
}
SafeByteArray CompressRequestSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<CompressRequest> compressRequest(boost::dynamic_pointer_cast<CompressRequest>(element));
- return createSafeByteArray("<compress xmlns='http://jabber.org/protocol/compress'><method>" + compressRequest->getMethod() + "</method></compress>");
+ boost::shared_ptr<CompressRequest> compressRequest(boost::dynamic_pointer_cast<CompressRequest>(element));
+ return createSafeByteArray("<compress xmlns='http://jabber.org/protocol/compress'><method>" + compressRequest->getMethod() + "</method></compress>");
}
bool CompressRequestSerializer::canSerialize(boost::shared_ptr<ToplevelElement> element) const {
- return boost::dynamic_pointer_cast<CompressRequest>(element) != 0;
+ return boost::dynamic_pointer_cast<CompressRequest>(element) != 0;
}
}
diff --git a/Swiften/Serializer/CompressRequestSerializer.h b/Swiften/Serializer/CompressRequestSerializer.h
index 2ff349d..1472a81 100644
--- a/Swiften/Serializer/CompressRequestSerializer.h
+++ b/Swiften/Serializer/CompressRequestSerializer.h
@@ -12,11 +12,11 @@
#include <Swiften/Serializer/ElementSerializer.h>
namespace Swift {
- class SWIFTEN_API CompressRequestSerializer : public ElementSerializer {
- public:
- CompressRequestSerializer();
+ class SWIFTEN_API CompressRequestSerializer : public ElementSerializer {
+ public:
+ CompressRequestSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/ElementSerializer.h b/Swiften/Serializer/ElementSerializer.h
index 3f4f5c1..15f69da 100644
--- a/Swiften/Serializer/ElementSerializer.h
+++ b/Swiften/Serializer/ElementSerializer.h
@@ -12,11 +12,11 @@
#include <Swiften/Elements/ToplevelElement.h>
namespace Swift {
- class ElementSerializer {
- public:
- virtual ~ElementSerializer();
+ class ElementSerializer {
+ public:
+ virtual ~ElementSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const = 0;
- virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const = 0;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const = 0;
+ virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const = 0;
+ };
}
diff --git a/Swiften/Serializer/EnableStreamManagementSerializer.h b/Swiften/Serializer/EnableStreamManagementSerializer.h
index f837e9f..ffbcf8b 100644
--- a/Swiften/Serializer/EnableStreamManagementSerializer.h
+++ b/Swiften/Serializer/EnableStreamManagementSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API EnableStreamManagementSerializer : public GenericElementSerializer<EnableStreamManagement> {
- public:
- EnableStreamManagementSerializer() : GenericElementSerializer<EnableStreamManagement>() {
- }
+ class SWIFTEN_API EnableStreamManagementSerializer : public GenericElementSerializer<EnableStreamManagement> {
+ public:
+ EnableStreamManagementSerializer() : GenericElementSerializer<EnableStreamManagement>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("enable", "urn:xmpp:sm:2").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("enable", "urn:xmpp:sm:2").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/GenericElementSerializer.h b/Swiften/Serializer/GenericElementSerializer.h
index 40ecb0f..053a163 100644
--- a/Swiften/Serializer/GenericElementSerializer.h
+++ b/Swiften/Serializer/GenericElementSerializer.h
@@ -12,13 +12,13 @@
#include <Swiften/Serializer/ElementSerializer.h>
namespace Swift {
- template<typename T>
- class SWIFTEN_API GenericElementSerializer : public ElementSerializer {
- public:
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const = 0;
+ template<typename T>
+ class SWIFTEN_API GenericElementSerializer : public ElementSerializer {
+ public:
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const = 0;
- virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const {
- return !!boost::dynamic_pointer_cast<T>(element);
- }
- };
+ virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const {
+ return !!boost::dynamic_pointer_cast<T>(element);
+ }
+ };
}
diff --git a/Swiften/Serializer/GenericPayloadSerializer.h b/Swiften/Serializer/GenericPayloadSerializer.h
index f02ccda..080d04b 100644
--- a/Swiften/Serializer/GenericPayloadSerializer.h
+++ b/Swiften/Serializer/GenericPayloadSerializer.h
@@ -12,17 +12,17 @@
#include <Swiften/Serializer/PayloadSerializer.h>
namespace Swift {
- template<typename PAYLOAD_TYPE>
- class GenericPayloadSerializer : public PayloadSerializer {
- public:
- virtual std::string serialize(boost::shared_ptr<Payload> element) const {
- return serializePayload(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(element));
- }
+ template<typename PAYLOAD_TYPE>
+ class GenericPayloadSerializer : public PayloadSerializer {
+ public:
+ virtual std::string serialize(boost::shared_ptr<Payload> element) const {
+ return serializePayload(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(element));
+ }
- virtual bool canSerialize(boost::shared_ptr<Payload> element) const {
- return !!boost::dynamic_pointer_cast<PAYLOAD_TYPE>(element);
- }
+ virtual bool canSerialize(boost::shared_ptr<Payload> element) const {
+ return !!boost::dynamic_pointer_cast<PAYLOAD_TYPE>(element);
+ }
- virtual std::string serializePayload(boost::shared_ptr<PAYLOAD_TYPE>) const = 0;
- };
+ virtual std::string serializePayload(boost::shared_ptr<PAYLOAD_TYPE>) const = 0;
+ };
}
diff --git a/Swiften/Serializer/GenericStanzaSerializer.h b/Swiften/Serializer/GenericStanzaSerializer.h
index 319ea67..e3eaae6 100644
--- a/Swiften/Serializer/GenericStanzaSerializer.h
+++ b/Swiften/Serializer/GenericStanzaSerializer.h
@@ -10,24 +10,24 @@
#include <Swiften/Serializer/StanzaSerializer.h>
namespace Swift {
- template<typename STANZA_TYPE>
- class SWIFTEN_API GenericStanzaSerializer : public StanzaSerializer {
- public:
- GenericStanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>()) : StanzaSerializer(tag, payloadSerializers, explicitNS) {}
+ template<typename STANZA_TYPE>
+ class SWIFTEN_API GenericStanzaSerializer : public StanzaSerializer {
+ public:
+ GenericStanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>()) : StanzaSerializer(tag, payloadSerializers, explicitNS) {}
- virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const {
- return dynamic_cast<STANZA_TYPE*>(element.get()) != 0;
- }
+ virtual bool canSerialize(boost::shared_ptr<ToplevelElement> element) const {
+ return dynamic_cast<STANZA_TYPE*>(element.get()) != 0;
+ }
- virtual void setStanzaSpecificAttributes(
- boost::shared_ptr<ToplevelElement> stanza,
- XMLElement& element) const {
- setStanzaSpecificAttributesGeneric(
- boost::dynamic_pointer_cast<STANZA_TYPE>(stanza), element);
- }
+ virtual void setStanzaSpecificAttributes(
+ boost::shared_ptr<ToplevelElement> stanza,
+ XMLElement& element) const {
+ setStanzaSpecificAttributesGeneric(
+ boost::dynamic_pointer_cast<STANZA_TYPE>(stanza), element);
+ }
- virtual void setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<STANZA_TYPE>,
- XMLElement&) const = 0;
- };
+ virtual void setStanzaSpecificAttributesGeneric(
+ boost::shared_ptr<STANZA_TYPE>,
+ XMLElement&) const = 0;
+ };
}
diff --git a/Swiften/Serializer/IQSerializer.h b/Swiften/Serializer/IQSerializer.h
index f870ca1..db052fb 100644
--- a/Swiften/Serializer/IQSerializer.h
+++ b/Swiften/Serializer/IQSerializer.h
@@ -14,22 +14,22 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API IQSerializer : public GenericStanzaSerializer<IQ> {
- public:
- IQSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>()) :
- GenericStanzaSerializer<IQ>("iq", payloadSerializers, explicitNS) {
- }
+ class SWIFTEN_API IQSerializer : public GenericStanzaSerializer<IQ> {
+ public:
+ IQSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>()) :
+ GenericStanzaSerializer<IQ>("iq", payloadSerializers, explicitNS) {
+ }
- private:
- virtual void setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<IQ> iq,
- XMLElement& element) const {
- switch (iq->getType()) {
- case IQ::Get: element.setAttribute("type","get"); break;
- case IQ::Set: element.setAttribute("type","set"); break;
- case IQ::Result: element.setAttribute("type","result"); break;
- case IQ::Error: element.setAttribute("type","error"); break;
- }
- }
- };
+ private:
+ virtual void setStanzaSpecificAttributesGeneric(
+ boost::shared_ptr<IQ> iq,
+ XMLElement& element) const {
+ switch (iq->getType()) {
+ case IQ::Get: element.setAttribute("type","get"); break;
+ case IQ::Set: element.setAttribute("type","set"); break;
+ case IQ::Result: element.setAttribute("type","result"); break;
+ case IQ::Error: element.setAttribute("type","error"); break;
+ }
+ }
+ };
}
diff --git a/Swiften/Serializer/MessageSerializer.cpp b/Swiften/Serializer/MessageSerializer.cpp
index 63a399a..fb16393 100644
--- a/Swiften/Serializer/MessageSerializer.cpp
+++ b/Swiften/Serializer/MessageSerializer.cpp
@@ -11,24 +11,24 @@
namespace Swift {
MessageSerializer::MessageSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS) :
- GenericStanzaSerializer<Message>("message", payloadSerializers, explicitNS) {
+ GenericStanzaSerializer<Message>("message", payloadSerializers, explicitNS) {
}
void MessageSerializer::setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<Message> message,
- XMLElement& element) const {
- if (message->getType() == Message::Chat) {
- element.setAttribute("type", "chat");
- }
- else if (message->getType() == Message::Groupchat) {
- element.setAttribute("type", "groupchat");
- }
- else if (message->getType() == Message::Headline) {
- element.setAttribute("type", "headline");
- }
- else if (message->getType() == Message::Error) {
- element.setAttribute("type", "error");
- }
+ boost::shared_ptr<Message> message,
+ XMLElement& element) const {
+ if (message->getType() == Message::Chat) {
+ element.setAttribute("type", "chat");
+ }
+ else if (message->getType() == Message::Groupchat) {
+ element.setAttribute("type", "groupchat");
+ }
+ else if (message->getType() == Message::Headline) {
+ element.setAttribute("type", "headline");
+ }
+ else if (message->getType() == Message::Error) {
+ element.setAttribute("type", "error");
+ }
}
}
diff --git a/Swiften/Serializer/MessageSerializer.h b/Swiften/Serializer/MessageSerializer.h
index 91eee31..50df353 100644
--- a/Swiften/Serializer/MessageSerializer.h
+++ b/Swiften/Serializer/MessageSerializer.h
@@ -13,15 +13,15 @@
#include <Swiften/Serializer/GenericStanzaSerializer.h>
namespace Swift {
- class XMLElement;
+ class XMLElement;
- class SWIFTEN_API MessageSerializer : public GenericStanzaSerializer<Message> {
- public:
- MessageSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explitNS = boost::optional<std::string>());
+ class SWIFTEN_API MessageSerializer : public GenericStanzaSerializer<Message> {
+ public:
+ MessageSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explitNS = boost::optional<std::string>());
- private:
- void setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<Message> message,
- XMLElement& element) const;
- };
+ private:
+ void setStanzaSpecificAttributesGeneric(
+ boost::shared_ptr<Message> message,
+ XMLElement& element) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializer.h b/Swiften/Serializer/PayloadSerializer.h
index fd97b74..642247d 100644
--- a/Swiften/Serializer/PayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializer.h
@@ -13,13 +13,13 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class Payload;
+ class Payload;
- class SWIFTEN_API PayloadSerializer {
- public:
- virtual ~PayloadSerializer();
+ class SWIFTEN_API PayloadSerializer {
+ public:
+ virtual ~PayloadSerializer();
- virtual bool canSerialize(boost::shared_ptr<Payload>) const = 0;
- virtual std::string serialize(boost::shared_ptr<Payload>) const = 0;
- };
+ virtual bool canSerialize(boost::shared_ptr<Payload>) const = 0;
+ virtual std::string serialize(boost::shared_ptr<Payload>) const = 0;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializerCollection.cpp
index 080fc7c..ba8b191 100644
--- a/Swiften/Serializer/PayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializerCollection.cpp
@@ -18,18 +18,18 @@ PayloadSerializerCollection::PayloadSerializerCollection() {
}
void PayloadSerializerCollection::addSerializer(PayloadSerializer* serializer) {
- serializers_.push_back(serializer);
+ serializers_.push_back(serializer);
}
void PayloadSerializerCollection::removeSerializer(PayloadSerializer* serializer) {
- serializers_.erase(std::remove(serializers_.begin(), serializers_.end(), serializer), serializers_.end());
+ serializers_.erase(std::remove(serializers_.begin(), serializers_.end(), serializer), serializers_.end());
}
PayloadSerializer* PayloadSerializerCollection::getPayloadSerializer(boost::shared_ptr<Payload> payload) const {
- std::vector<PayloadSerializer*>::const_iterator i = std::find_if(
- serializers_.begin(), serializers_.end(),
- boost::bind(&PayloadSerializer::canSerialize, _1, payload));
- return (i != serializers_.end() ? *i : NULL);
+ std::vector<PayloadSerializer*>::const_iterator i = std::find_if(
+ serializers_.begin(), serializers_.end(),
+ boost::bind(&PayloadSerializer::canSerialize, _1, payload));
+ return (i != serializers_.end() ? *i : NULL);
}
}
diff --git a/Swiften/Serializer/PayloadSerializerCollection.h b/Swiften/Serializer/PayloadSerializerCollection.h
index abda457..47ba6a1 100644
--- a/Swiften/Serializer/PayloadSerializerCollection.h
+++ b/Swiften/Serializer/PayloadSerializerCollection.h
@@ -14,18 +14,18 @@
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class PayloadSerializer;
-
+ class PayloadSerializer;
- class SWIFTEN_API PayloadSerializerCollection {
- public:
- PayloadSerializerCollection();
- void addSerializer(PayloadSerializer* factory);
- void removeSerializer(PayloadSerializer* factory);
- PayloadSerializer* getPayloadSerializer(boost::shared_ptr<Payload>) const;
+ class SWIFTEN_API PayloadSerializerCollection {
+ public:
+ PayloadSerializerCollection();
- private:
- std::vector<PayloadSerializer*> serializers_;
- };
+ void addSerializer(PayloadSerializer* factory);
+ void removeSerializer(PayloadSerializer* factory);
+ PayloadSerializer* getPayloadSerializer(boost::shared_ptr<Payload>) const;
+
+ private:
+ std::vector<PayloadSerializer*> serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
index 48c8004..7490e4f 100644
--- a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
@@ -14,24 +14,24 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- template<typename BLOCK_ELEMENT>
- class SWIFTEN_API BlockSerializer : public GenericPayloadSerializer<BLOCK_ELEMENT> {
- public:
- BlockSerializer(std::string tag) : GenericPayloadSerializer<BLOCK_ELEMENT>(), tag(tag) {
- }
+ template<typename BLOCK_ELEMENT>
+ class SWIFTEN_API BlockSerializer : public GenericPayloadSerializer<BLOCK_ELEMENT> {
+ public:
+ BlockSerializer(std::string tag) : GenericPayloadSerializer<BLOCK_ELEMENT>(), tag(tag) {
+ }
- virtual std::string serializePayload(boost::shared_ptr<BLOCK_ELEMENT> payload) const {
- XMLElement element(tag, "urn:xmpp:blocking");
- const std::vector<JID>& items = payload->getItems();
- for (std::vector<JID>::const_iterator i = items.begin(); i != items.end(); ++i) {
- boost::shared_ptr<XMLElement> item = boost::make_shared<XMLElement>("item");
- item->setAttribute("jid", *i);
- element.addNode(item);
- }
- return element.serialize();
- }
+ virtual std::string serializePayload(boost::shared_ptr<BLOCK_ELEMENT> payload) const {
+ XMLElement element(tag, "urn:xmpp:blocking");
+ const std::vector<JID>& items = payload->getItems();
+ for (std::vector<JID>::const_iterator i = items.begin(); i != items.end(); ++i) {
+ boost::shared_ptr<XMLElement> item = boost::make_shared<XMLElement>("item");
+ item->setAttribute("jid", *i);
+ element.addNode(item);
+ }
+ return element.serialize();
+ }
- private:
- std::string tag;
- };
+ private:
+ std::string tag;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/BodySerializer.h b/Swiften/Serializer/PayloadSerializers/BodySerializer.h
index 4f4b5b3..f2d7a8d 100644
--- a/Swiften/Serializer/PayloadSerializers/BodySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BodySerializer.h
@@ -12,13 +12,13 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class SWIFTEN_API BodySerializer : public GenericPayloadSerializer<Body> {
- public:
- BodySerializer() : GenericPayloadSerializer<Body>() {}
+ class SWIFTEN_API BodySerializer : public GenericPayloadSerializer<Body> {
+ public:
+ BodySerializer() : GenericPayloadSerializer<Body>() {}
- virtual std::string serializePayload(boost::shared_ptr<Body> body) const {
- XMLTextNode textNode(body->getText());
- return "<body>" + textNode.serialize() + "</body>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Body> body) const {
+ XMLTextNode textNode(body->getText());
+ return "<body>" + textNode.serialize() + "</body>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
index bf1b8cb..b5218ee 100644
--- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
@@ -18,23 +18,23 @@ namespace Swift {
BytestreamsSerializer::BytestreamsSerializer() {
}
-std::string BytestreamsSerializer::serializePayload(boost::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()) {
- boost::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()) {
- boost::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost-used"));
- streamHostElement->setAttribute("jid", *bytestreams->getUsedStreamHost());
- queryElement.addNode(streamHostElement);
- }
- return queryElement.serialize();
+std::string BytestreamsSerializer::serializePayload(boost::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()) {
+ boost::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()) {
+ boost::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/BytestreamsSerializer.h b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
index 5cf4dee..6056cad 100644
--- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
@@ -11,12 +11,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API BytestreamsSerializer : public GenericPayloadSerializer<Bytestreams> {
- public:
- BytestreamsSerializer();
+ class SWIFTEN_API BytestreamsSerializer : public GenericPayloadSerializer<Bytestreams> {
+ public:
+ BytestreamsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Bytestreams>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<Bytestreams>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
index 87c45f6..799e662 100644
--- a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
@@ -16,11 +16,11 @@ CapsInfoSerializer::CapsInfoSerializer() : GenericPayloadSerializer<CapsInfo>()
}
std::string CapsInfoSerializer::serializePayload(boost::shared_ptr<CapsInfo> capsInfo) const {
- XMLElement capsElement("c", "http://jabber.org/protocol/caps");
- capsElement.setAttribute("node", capsInfo->getNode());
- capsElement.setAttribute("hash", capsInfo->getHash());
- capsElement.setAttribute("ver", capsInfo->getVersion());
- return capsElement.serialize();
+ XMLElement capsElement("c", "http://jabber.org/protocol/caps");
+ capsElement.setAttribute("node", capsInfo->getNode());
+ capsElement.setAttribute("hash", capsInfo->getHash());
+ capsElement.setAttribute("ver", capsInfo->getVersion());
+ return capsElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
index 9f20d06..bbf4c09 100644
--- a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API CapsInfoSerializer : public GenericPayloadSerializer<CapsInfo> {
- public:
- CapsInfoSerializer();
+ class SWIFTEN_API CapsInfoSerializer : public GenericPayloadSerializer<CapsInfo> {
+ public:
+ CapsInfoSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CapsInfo>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<CapsInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
index e39d005..406fdbc 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
@@ -9,16 +9,16 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- CarbonsDisableSerializer::CarbonsDisableSerializer() : GenericPayloadSerializer<CarbonsDisable>() {
+ CarbonsDisableSerializer::CarbonsDisableSerializer() : GenericPayloadSerializer<CarbonsDisable>() {
- }
+ }
- CarbonsDisableSerializer::~CarbonsDisableSerializer() {
+ CarbonsDisableSerializer::~CarbonsDisableSerializer() {
- }
+ }
- std::string CarbonsDisableSerializer::serializePayload(boost::shared_ptr<CarbonsDisable>) const {
- XMLElement element("disable", "urn:xmpp:carbons:2");
- return element.serialize();
- }
+ std::string CarbonsDisableSerializer::serializePayload(boost::shared_ptr<CarbonsDisable>) const {
+ XMLElement element("disable", "urn:xmpp:carbons:2");
+ return element.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h
index 6eeb5d5..da01ead 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h
@@ -11,11 +11,11 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API CarbonsDisableSerializer : public GenericPayloadSerializer<CarbonsDisable> {
- public:
- CarbonsDisableSerializer();
- virtual ~CarbonsDisableSerializer();
+ class SWIFTEN_API CarbonsDisableSerializer : public GenericPayloadSerializer<CarbonsDisable> {
+ public:
+ CarbonsDisableSerializer();
+ virtual ~CarbonsDisableSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CarbonsDisable>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<CarbonsDisable>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
index 0bc3822..a2520f9 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
@@ -9,15 +9,15 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- CarbonsEnableSerializer::CarbonsEnableSerializer() : GenericPayloadSerializer<CarbonsEnable>() {
- }
+ CarbonsEnableSerializer::CarbonsEnableSerializer() : GenericPayloadSerializer<CarbonsEnable>() {
+ }
- CarbonsEnableSerializer::~CarbonsEnableSerializer() {
+ CarbonsEnableSerializer::~CarbonsEnableSerializer() {
- }
+ }
- std::string CarbonsEnableSerializer::serializePayload(boost::shared_ptr<CarbonsEnable>) const {
- XMLElement element("enable", "urn:xmpp:carbons:2");
- return element.serialize();
- }
+ std::string CarbonsEnableSerializer::serializePayload(boost::shared_ptr<CarbonsEnable>) const {
+ XMLElement element("enable", "urn:xmpp:carbons:2");
+ return element.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h
index aa76d5f..8b26901 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h
@@ -12,11 +12,11 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API CarbonsEnableSerializer : public GenericPayloadSerializer<CarbonsEnable> {
- public:
- CarbonsEnableSerializer();
- virtual ~CarbonsEnableSerializer();
+ class SWIFTEN_API CarbonsEnableSerializer : public GenericPayloadSerializer<CarbonsEnable> {
+ public:
+ CarbonsEnableSerializer();
+ virtual ~CarbonsEnableSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CarbonsEnable>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<CarbonsEnable>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
index 1e77470..6fbfc26 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
@@ -9,15 +9,15 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- CarbonsPrivateSerializer::CarbonsPrivateSerializer() : GenericPayloadSerializer<CarbonsPrivate>() {
- }
+ CarbonsPrivateSerializer::CarbonsPrivateSerializer() : GenericPayloadSerializer<CarbonsPrivate>() {
+ }
- CarbonsPrivateSerializer::~CarbonsPrivateSerializer() {
+ CarbonsPrivateSerializer::~CarbonsPrivateSerializer() {
- }
+ }
- std::string CarbonsPrivateSerializer::serializePayload(boost::shared_ptr<CarbonsPrivate>) const {
- XMLElement element("private", "urn:xmpp:carbons:2");
- return element.serialize();
- }
+ std::string CarbonsPrivateSerializer::serializePayload(boost::shared_ptr<CarbonsPrivate>) const {
+ XMLElement element("private", "urn:xmpp:carbons:2");
+ return element.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h
index 37a6dd1..a93d87f 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h
@@ -12,11 +12,11 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API CarbonsPrivateSerializer : public GenericPayloadSerializer<CarbonsPrivate> {
- public:
- CarbonsPrivateSerializer();
- virtual ~CarbonsPrivateSerializer();
+ class SWIFTEN_API CarbonsPrivateSerializer : public GenericPayloadSerializer<CarbonsPrivate> {
+ public:
+ CarbonsPrivateSerializer();
+ virtual ~CarbonsPrivateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CarbonsPrivate>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<CarbonsPrivate>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
index bf63a69..981421b 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
@@ -9,18 +9,18 @@
#include <boost/make_shared.hpp>
namespace Swift {
- CarbonsReceivedSerializer::CarbonsReceivedSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<CarbonsReceived>(), serializers_(serializers) {
- }
+ CarbonsReceivedSerializer::CarbonsReceivedSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<CarbonsReceived>(), serializers_(serializers) {
+ }
- CarbonsReceivedSerializer::~CarbonsReceivedSerializer() {
- }
-
- std::string CarbonsReceivedSerializer::serializePayload(boost::shared_ptr<CarbonsReceived> received) const {
- XMLElement element("received", "urn:xmpp:carbons:2");
- if (received->getForwarded()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(received->getForwarded())));
- }
- return element.serialize();
- }
+ CarbonsReceivedSerializer::~CarbonsReceivedSerializer() {
+ }
+
+ std::string CarbonsReceivedSerializer::serializePayload(boost::shared_ptr<CarbonsReceived> received) const {
+ XMLElement element("received", "urn:xmpp:carbons:2");
+ if (received->getForwarded()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(received->getForwarded())));
+ }
+ return element.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h
index 072b98f..719e84a 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h
@@ -15,15 +15,15 @@
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
- class SWIFTEN_API CarbonsReceivedSerializer : public GenericPayloadSerializer<CarbonsReceived> {
- public:
- CarbonsReceivedSerializer(PayloadSerializerCollection* serializers);
- virtual ~CarbonsReceivedSerializer();
+ class SWIFTEN_API CarbonsReceivedSerializer : public GenericPayloadSerializer<CarbonsReceived> {
+ public:
+ CarbonsReceivedSerializer(PayloadSerializerCollection* serializers);
+ virtual ~CarbonsReceivedSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CarbonsReceived> received) const;
+ virtual std::string serializePayload(boost::shared_ptr<CarbonsReceived> received) const;
- private:
- PayloadSerializerCollection* serializers_;
- };
+ private:
+ PayloadSerializerCollection* serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp
index 30a283e..f71208f 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp
@@ -7,18 +7,18 @@
#include <Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h>
namespace Swift {
- CarbonsSentSerializer::CarbonsSentSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<CarbonsSent>(), serializers_(serializers) {
- }
+ CarbonsSentSerializer::CarbonsSentSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<CarbonsSent>(), serializers_(serializers) {
+ }
- CarbonsSentSerializer::~CarbonsSentSerializer() {
- }
-
- std::string CarbonsSentSerializer::serializePayload(boost::shared_ptr<CarbonsSent> sent) const {
- XMLElement element("sent", "urn:xmpp:carbons:2");
- if (sent->getForwarded()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(sent->getForwarded())));
- }
- return element.serialize();
- }
+ CarbonsSentSerializer::~CarbonsSentSerializer() {
+ }
+
+ std::string CarbonsSentSerializer::serializePayload(boost::shared_ptr<CarbonsSent> sent) const {
+ XMLElement element("sent", "urn:xmpp:carbons:2");
+ if (sent->getForwarded()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(sent->getForwarded())));
+ }
+ return element.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h
index f79def4..cecb3b8 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h
@@ -17,15 +17,15 @@
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
- class SWIFTEN_API CarbonsSentSerializer : public GenericPayloadSerializer<CarbonsSent> {
- public:
- CarbonsSentSerializer(PayloadSerializerCollection* serializers);
- virtual ~CarbonsSentSerializer();
+ class SWIFTEN_API CarbonsSentSerializer : public GenericPayloadSerializer<CarbonsSent> {
+ public:
+ CarbonsSentSerializer(PayloadSerializerCollection* serializers);
+ virtual ~CarbonsSentSerializer();
- virtual std::string serializePayload(boost::shared_ptr<CarbonsSent> sent) const;
+ virtual std::string serializePayload(boost::shared_ptr<CarbonsSent> sent) const;
- private:
- PayloadSerializerCollection* serializers_;
- };
+ private:
+ PayloadSerializerCollection* serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp
index 767d9ce..325215a 100644
--- a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp
@@ -12,16 +12,16 @@ ChatStateSerializer::ChatStateSerializer() : GenericPayloadSerializer<ChatState>
}
std::string ChatStateSerializer::serializePayload(boost::shared_ptr<ChatState> chatState) const {
- std::string result("<");
- switch (chatState->getChatState()) {
- case ChatState::Active: result += "active"; break;
- case ChatState::Composing: result += "composing"; break;
- case ChatState::Paused: result += "paused"; break;
- case ChatState::Inactive: result += "inactive"; break;
- case ChatState::Gone: result += "gone"; break;
- }
- result += " xmlns=\"http://jabber.org/protocol/chatstates\"/>";
- return result;
+ std::string result("<");
+ switch (chatState->getChatState()) {
+ case ChatState::Active: result += "active"; break;
+ case ChatState::Composing: result += "composing"; break;
+ case ChatState::Paused: result += "paused"; break;
+ case ChatState::Inactive: result += "inactive"; break;
+ case ChatState::Gone: result += "gone"; break;
+ }
+ result += " xmlns=\"http://jabber.org/protocol/chatstates\"/>";
+ return result;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
index 2b279f1..cfdaf83 100644
--- a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API ChatStateSerializer : public GenericPayloadSerializer<ChatState> {
- public:
- ChatStateSerializer();
+ class SWIFTEN_API ChatStateSerializer : public GenericPayloadSerializer<ChatState> {
+ public:
+ ChatStateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<ChatState> error) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<ChatState> error) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
index 6b6a542..9ed17dc 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
@@ -20,77 +20,77 @@ namespace Swift {
CommandSerializer::CommandSerializer() {
}
-std::string CommandSerializer::serializePayload(boost::shared_ptr<Command> command) const {
- XMLElement commandElement("command", "http://jabber.org/protocol/commands");
- commandElement.setAttribute("node", command->getNode());
+std::string CommandSerializer::serializePayload(boost::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());
- }
+ if (!command->getSessionID().empty()) {
+ commandElement.setAttribute("sessionid", command->getSessionID());
+ }
- std::string action = actionToString(command->getAction());
- if (!action.empty()) {
- commandElement.setAttribute("action", action);
- }
+ 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);
- }
+ 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()) {
- actions += "<" + actionToString(action) + "/>";
- }
- actions += "</actions>";
- commandElement.addNode(boost::make_shared<XMLRawTextNode>(actions));
- }
+ 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()) {
+ actions += "<" + actionToString(action) + "/>";
+ }
+ actions += "</actions>";
+ commandElement.addNode(boost::make_shared<XMLRawTextNode>(actions));
+ }
- foreach (Command::Note note, command->getNotes()) {
- boost::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(boost::make_shared<XMLTextNode>(note.note));
- commandElement.addNode(noteElement);
- }
+ foreach (Command::Note note, command->getNotes()) {
+ boost::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(boost::make_shared<XMLTextNode>(note.note));
+ commandElement.addNode(noteElement);
+ }
- Form::ref form = command->getForm();
- if (form) {
- commandElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
- return commandElement.serialize();
+ Form::ref form = command->getForm();
+ if (form) {
+ commandElement.addNode(boost::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;
- }
- return string;
+ 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;
+ }
+ return string;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/CommandSerializer.h b/Swiften/Serializer/PayloadSerializers/CommandSerializer.h
index 6fea85e..bc3642d 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.h
@@ -11,13 +11,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API CommandSerializer : public GenericPayloadSerializer<Command> {
- public:
- CommandSerializer();
+ class SWIFTEN_API CommandSerializer : public GenericPayloadSerializer<Command> {
+ public:
+ CommandSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Command>) const;
+ virtual std::string serializePayload(boost::shared_ptr<Command>) const;
- private:
- std::string actionToString(Command::Action action) const;
- };
+ private:
+ std::string actionToString(Command::Action action) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp b/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp
index ad16c21..428b565 100644
--- a/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp
@@ -19,12 +19,12 @@ DelaySerializer::DelaySerializer() : GenericPayloadSerializer<Delay>() {
}
std::string DelaySerializer::serializePayload(boost::shared_ptr<Delay> delay) const {
- XMLElement delayElement("delay", "urn:xmpp:delay");
- if (delay->getFrom() && delay->getFrom()->isValid()) {
- delayElement.setAttribute("from", delay->getFrom()->toString());
- }
- delayElement.setAttribute("stamp", dateTimeToString(delay->getStamp()));
- return delayElement.serialize();
+ XMLElement delayElement("delay", "urn:xmpp:delay");
+ if (delay->getFrom() && delay->getFrom()->isValid()) {
+ delayElement.setAttribute("from", delay->getFrom()->toString());
+ }
+ delayElement.setAttribute("stamp", dateTimeToString(delay->getStamp()));
+ return delayElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DelaySerializer.h b/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
index 493fe4c..71039f2 100644
--- a/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
@@ -11,12 +11,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API DelaySerializer : public GenericPayloadSerializer<Delay> {
- public:
- DelaySerializer();
+ class SWIFTEN_API DelaySerializer : public GenericPayloadSerializer<Delay> {
+ public:
+ DelaySerializer();
- virtual std::string serializePayload(boost::shared_ptr<Delay>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<Delay>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
index f4e5c60..887502a 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
@@ -21,8 +21,8 @@ DeliveryReceiptRequestSerializer::DeliveryReceiptRequestSerializer() : GenericPa
}
std::string DeliveryReceiptRequestSerializer::serializePayload(boost::shared_ptr<DeliveryReceiptRequest> /* request*/) const {
- XMLElement requestXML("request", "urn:xmpp:receipts");
- return requestXML.serialize();
+ XMLElement requestXML("request", "urn:xmpp:receipts");
+ return requestXML.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
index def5a38..97377d6 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
@@ -17,10 +17,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API DeliveryReceiptRequestSerializer : public GenericPayloadSerializer<DeliveryReceiptRequest> {
- public:
- DeliveryReceiptRequestSerializer();
+ class SWIFTEN_API DeliveryReceiptRequestSerializer : public GenericPayloadSerializer<DeliveryReceiptRequest> {
+ public:
+ DeliveryReceiptRequestSerializer();
- virtual std::string serializePayload(boost::shared_ptr<DeliveryReceiptRequest> request) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<DeliveryReceiptRequest> request) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
index 30fcb33..d3e1480 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
@@ -20,9 +20,9 @@ DeliveryReceiptSerializer::DeliveryReceiptSerializer() : GenericPayloadSerialize
}
std::string DeliveryReceiptSerializer::serializePayload(boost::shared_ptr<DeliveryReceipt> receipt) const {
- XMLElement received("received", "urn:xmpp:receipts");
- received.setAttribute("id", receipt->getReceivedID());
- return received.serialize();
+ XMLElement received("received", "urn:xmpp:receipts");
+ received.setAttribute("id", receipt->getReceivedID());
+ return received.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h
index 16c8258..943f4b9 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h
@@ -17,10 +17,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API DeliveryReceiptSerializer : public GenericPayloadSerializer<DeliveryReceipt> {
- public:
- DeliveryReceiptSerializer();
+ class SWIFTEN_API DeliveryReceiptSerializer : public GenericPayloadSerializer<DeliveryReceipt> {
+ public:
+ DeliveryReceiptSerializer();
- virtual std::string serializePayload(boost::shared_ptr<DeliveryReceipt> receipt) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<DeliveryReceipt> receipt) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
index 76909c7..e57fd12 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
@@ -20,29 +20,29 @@ DiscoInfoSerializer::DiscoInfoSerializer() : GenericPayloadSerializer<DiscoInfo>
}
std::string DiscoInfoSerializer::serializePayload(boost::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()) {
- boost::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()) {
- boost::shared_ptr<XMLElement> featureElement(new XMLElement("feature"));
- featureElement->setAttribute("var", feature);
- queryElement.addNode(featureElement);
- }
- foreach(const Form::ref extension, discoInfo->getExtensions()) {
- queryElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(extension)));
- }
- return queryElement.serialize();
+ 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()) {
+ boost::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()) {
+ boost::shared_ptr<XMLElement> featureElement(new XMLElement("feature"));
+ featureElement->setAttribute("var", feature);
+ queryElement.addNode(featureElement);
+ }
+ foreach(const Form::ref extension, discoInfo->getExtensions()) {
+ queryElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(extension)));
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
index 9eb627c..9850714 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API DiscoInfoSerializer : public GenericPayloadSerializer<DiscoInfo> {
- public:
- DiscoInfoSerializer();
+ class SWIFTEN_API DiscoInfoSerializer : public GenericPayloadSerializer<DiscoInfo> {
+ public:
+ DiscoInfoSerializer();
- virtual std::string serializePayload(boost::shared_ptr<DiscoInfo>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<DiscoInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
index 91a467c..f537f40 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
@@ -17,20 +17,20 @@ DiscoItemsSerializer::DiscoItemsSerializer() : GenericPayloadSerializer<DiscoIte
}
std::string DiscoItemsSerializer::serializePayload(boost::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()) {
- boost::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();
+ 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()) {
+ boost::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/DiscoItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
index 4be08e6..acc5a7b 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
@@ -11,11 +11,11 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API DiscoItemsSerializer : public GenericPayloadSerializer<DiscoItems> {
- public:
- DiscoItemsSerializer();
+ class SWIFTEN_API DiscoItemsSerializer : public GenericPayloadSerializer<DiscoItems> {
+ public:
+ DiscoItemsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<DiscoItems>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<DiscoItems>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
index 14329b9..1ed60d1 100644
--- a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
@@ -15,57 +15,57 @@ ErrorSerializer::ErrorSerializer(PayloadSerializerCollection* serializers) : Gen
}
std::string ErrorSerializer::serializePayload(boost::shared_ptr<ErrorPayload> error) const {
- std::string result("<error type=\"");
- switch (error->getType()) {
- case ErrorPayload::Continue: result += "continue"; break;
- case ErrorPayload::Modify: result += "modify"; break;
- case ErrorPayload::Auth: result += "auth"; break;
- case ErrorPayload::Wait: result += "wait"; break;
- case ErrorPayload::Cancel: result += "cancel"; break;
- }
- result += "\">";
+ std::string result("<error type=\"");
+ switch (error->getType()) {
+ case ErrorPayload::Continue: result += "continue"; break;
+ case ErrorPayload::Modify: result += "modify"; break;
+ case ErrorPayload::Auth: result += "auth"; break;
+ case ErrorPayload::Wait: result += "wait"; break;
+ case ErrorPayload::Cancel: result += "cancel"; break;
+ }
+ result += "\">";
- std::string conditionElement;
- switch (error->getCondition()) {
- case ErrorPayload::BadRequest: conditionElement = "bad-request"; break;
- case ErrorPayload::Conflict: conditionElement = "conflict"; break;
- case ErrorPayload::FeatureNotImplemented: conditionElement = "feature-not-implemented"; break;
- case ErrorPayload::Forbidden: conditionElement = "forbidden"; break;
- case ErrorPayload::Gone: conditionElement = "gone"; break;
- case ErrorPayload::InternalServerError: conditionElement = "internal-server-error"; break;
- case ErrorPayload::ItemNotFound: conditionElement = "item-not-found"; break;
- case ErrorPayload::JIDMalformed: conditionElement = "jid-malformed"; break;
- case ErrorPayload::NotAcceptable: conditionElement = "not-acceptable"; break;
- case ErrorPayload::NotAllowed: conditionElement = "not-allowed"; break;
- case ErrorPayload::NotAuthorized: conditionElement = "not-authorized"; break;
- case ErrorPayload::PaymentRequired: conditionElement = "payment-required"; break;
- case ErrorPayload::RecipientUnavailable: conditionElement = "recipient-unavailable"; break;
- case ErrorPayload::Redirect: conditionElement = "redirect"; break;
- case ErrorPayload::RegistrationRequired: conditionElement = "registration-required"; break;
- case ErrorPayload::RemoteServerNotFound: conditionElement = "remote-server-not-found"; break;
- case ErrorPayload::RemoteServerTimeout: conditionElement = "remote-server-timeout"; break;
- case ErrorPayload::ResourceConstraint: conditionElement = "resource-constraint"; break;
- case ErrorPayload::ServiceUnavailable: conditionElement = "service-unavailable"; break;
- case ErrorPayload::SubscriptionRequired: conditionElement = "subscription-required"; break;
- case ErrorPayload::UnexpectedRequest: conditionElement = "unexpected-request"; break;
- case ErrorPayload::UndefinedCondition: conditionElement = "undefined-condition"; break;
- }
- result += "<" + conditionElement + " xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>";
+ std::string conditionElement;
+ switch (error->getCondition()) {
+ case ErrorPayload::BadRequest: conditionElement = "bad-request"; break;
+ case ErrorPayload::Conflict: conditionElement = "conflict"; break;
+ case ErrorPayload::FeatureNotImplemented: conditionElement = "feature-not-implemented"; break;
+ case ErrorPayload::Forbidden: conditionElement = "forbidden"; break;
+ case ErrorPayload::Gone: conditionElement = "gone"; break;
+ case ErrorPayload::InternalServerError: conditionElement = "internal-server-error"; break;
+ case ErrorPayload::ItemNotFound: conditionElement = "item-not-found"; break;
+ case ErrorPayload::JIDMalformed: conditionElement = "jid-malformed"; break;
+ case ErrorPayload::NotAcceptable: conditionElement = "not-acceptable"; break;
+ case ErrorPayload::NotAllowed: conditionElement = "not-allowed"; break;
+ case ErrorPayload::NotAuthorized: conditionElement = "not-authorized"; break;
+ case ErrorPayload::PaymentRequired: conditionElement = "payment-required"; break;
+ case ErrorPayload::RecipientUnavailable: conditionElement = "recipient-unavailable"; break;
+ case ErrorPayload::Redirect: conditionElement = "redirect"; break;
+ case ErrorPayload::RegistrationRequired: conditionElement = "registration-required"; break;
+ case ErrorPayload::RemoteServerNotFound: conditionElement = "remote-server-not-found"; break;
+ case ErrorPayload::RemoteServerTimeout: conditionElement = "remote-server-timeout"; break;
+ case ErrorPayload::ResourceConstraint: conditionElement = "resource-constraint"; break;
+ case ErrorPayload::ServiceUnavailable: conditionElement = "service-unavailable"; break;
+ case ErrorPayload::SubscriptionRequired: conditionElement = "subscription-required"; break;
+ case ErrorPayload::UnexpectedRequest: conditionElement = "unexpected-request"; break;
+ case ErrorPayload::UndefinedCondition: conditionElement = "undefined-condition"; break;
+ }
+ result += "<" + conditionElement + " xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>";
- if (!error->getText().empty()) {
- XMLTextNode textNode(error->getText());
- result += "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">" + textNode.serialize() + "</text>";
- }
+ if (!error->getText().empty()) {
+ XMLTextNode textNode(error->getText());
+ result += "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">" + textNode.serialize() + "</text>";
+ }
- if (error->getPayload()) {
- PayloadSerializer* serializer = serializers->getPayloadSerializer(error->getPayload());
- if (serializer) {
- result += serializer->serialize(error->getPayload());
- }
- }
+ if (error->getPayload()) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(error->getPayload());
+ if (serializer) {
+ result += serializer->serialize(error->getPayload());
+ }
+ }
- result += "</error>";
- return result;
+ result += "</error>";
+ return result;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h
index 14666f4..2ccd5df 100644
--- a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h
@@ -11,15 +11,15 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API ErrorSerializer : public GenericPayloadSerializer<ErrorPayload> {
- public:
- ErrorSerializer(PayloadSerializerCollection* serializers);
+ class SWIFTEN_API ErrorSerializer : public GenericPayloadSerializer<ErrorPayload> {
+ public:
+ ErrorSerializer(PayloadSerializerCollection* serializers);
- virtual std::string serializePayload(boost::shared_ptr<ErrorPayload> error) const;
+ virtual std::string serializePayload(boost::shared_ptr<ErrorPayload> error) const;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
index f05c9cb..cc6339c 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
@@ -21,14 +21,14 @@
using namespace Swift;
namespace {
- template<typename T> void serializeValueAsString(boost::shared_ptr<FormField> field, boost::shared_ptr<XMLElement> parent) {
- std::string value = boost::dynamic_pointer_cast<T>(field)->getValue();
- if (!value.empty()) {
- boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
- valueElement->addNode(XMLTextNode::create(value));
- parent->addNode(valueElement);
- }
- }
+ template<typename T> void serializeValueAsString(boost::shared_ptr<FormField> field, boost::shared_ptr<XMLElement> parent) {
+ std::string value = boost::dynamic_pointer_cast<T>(field)->getValue();
+ if (!value.empty()) {
+ boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
+ valueElement->addNode(XMLTextNode::create(value));
+ parent->addNode(valueElement);
+ }
+ }
}
namespace Swift {
@@ -36,176 +36,176 @@ namespace Swift {
FormSerializer::FormSerializer() : GenericPayloadSerializer<Form>() {}
std::string FormSerializer::serializePayload(boost::shared_ptr<Form> form) const {
- if (!form) {
- return "";
- }
-
- boost::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(boost::shared_ptr<FormPage> page, form->getPages()) {
- formElement->addNode(pageToXML(page));
- }
- foreach(boost::shared_ptr<FormField> field, form->getFields()) {
- formElement->addNode(fieldToXML(field, true));
- }
- if (!form->getReportedFields().empty()) {
- boost::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
- foreach(FormField::ref field, form->getReportedFields()) {
- reportedElement->addNode(fieldToXML(field, true));
- }
- formElement->addNode(reportedElement);
- }
-
- foreach(Form::FormItem item, form->getItems()) {
- boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
- foreach(FormField::ref field, item) {
- itemElement->addNode(fieldToXML(field, false));
- }
- formElement->addNode(itemElement);
- }
-
- foreach(const FormText::text text, form->getTextElements()) {
- formElement->addNode(textToXML(text));
- }
-
- foreach (boost::shared_ptr<FormField> field, fields_) {
- formElement->addNode(fieldToXML(field,true));
- }
-
- return formElement->serialize();
+ if (!form) {
+ return "";
+ }
+
+ boost::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(boost::shared_ptr<FormPage> page, form->getPages()) {
+ formElement->addNode(pageToXML(page));
+ }
+ foreach(boost::shared_ptr<FormField> field, form->getFields()) {
+ formElement->addNode(fieldToXML(field, true));
+ }
+ if (!form->getReportedFields().empty()) {
+ boost::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
+ foreach(FormField::ref field, form->getReportedFields()) {
+ reportedElement->addNode(fieldToXML(field, true));
+ }
+ formElement->addNode(reportedElement);
+ }
+
+ foreach(Form::FormItem item, form->getItems()) {
+ boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ foreach(FormField::ref field, item) {
+ itemElement->addNode(fieldToXML(field, false));
+ }
+ formElement->addNode(itemElement);
+ }
+
+ foreach(const FormText::text text, form->getTextElements()) {
+ formElement->addNode(textToXML(text));
+ }
+
+ foreach (boost::shared_ptr<FormField> field, fields_) {
+ formElement->addNode(fieldToXML(field,true));
+ }
+
+ return formElement->serialize();
}
boost::shared_ptr<XMLElement> FormSerializer::textToXML(boost::shared_ptr<FormText> text) const {
- boost::shared_ptr<XMLElement> textElement (new XMLElement("text"));
- textElement->addNode(boost::make_shared<XMLTextNode>(text->getTextString()));
- return textElement;
+ boost::shared_ptr<XMLElement> textElement (new XMLElement("text"));
+ textElement->addNode(boost::make_shared<XMLTextNode>(text->getTextString()));
+ return textElement;
}
boost::shared_ptr<XMLElement> FormSerializer::fieldRefToXML(const std::string& ref) const {
- boost::shared_ptr<XMLElement> fieldRefElement(new XMLElement("fieldref"));
- fieldRefElement->setAttribute("var", ref);
- return fieldRefElement;
+ boost::shared_ptr<XMLElement> fieldRefElement(new XMLElement("fieldref"));
+ fieldRefElement->setAttribute("var", ref);
+ return fieldRefElement;
}
boost::shared_ptr<XMLElement> FormSerializer::pageToXML(boost::shared_ptr<FormPage> page) const {
- boost::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()) {
- pageElement->addNode(textToXML(text));
- }
- foreach (const boost::shared_ptr<FormField> field, page->getFields()) {
- pageElement->addNode(fieldRefToXML(field->getName()));
- fields_.push_back(field);
- }
- foreach(const FormReportedRef::ref reportedRef, page->getReportedRefs()) {
- pageElement->addNode(boost::make_shared<XMLElement>("reportedref"));
- }
- foreach(const FormSection::section section, page->getChildSections()) {
- pageElement->addNode(sectionToXML(section));
- }
- return pageElement;
+ boost::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()) {
+ pageElement->addNode(textToXML(text));
+ }
+ foreach (const boost::shared_ptr<FormField> field, page->getFields()) {
+ pageElement->addNode(fieldRefToXML(field->getName()));
+ fields_.push_back(field);
+ }
+ foreach(const FormReportedRef::ref reportedRef, page->getReportedRefs()) {
+ pageElement->addNode(boost::make_shared<XMLElement>("reportedref"));
+ }
+ foreach(const FormSection::section section, page->getChildSections()) {
+ pageElement->addNode(sectionToXML(section));
+ }
+ return pageElement;
}
boost::shared_ptr<XMLElement> FormSerializer::sectionToXML(boost::shared_ptr<FormSection> section) const {
- boost::shared_ptr<XMLElement> sectionElement(new XMLElement("section"));
- if (!section->getLabel().empty()) {
- sectionElement->setAttribute("label", section->getLabel());
- }
- foreach(const FormText::text text, section->getTextElements()) {
- sectionElement->addNode(textToXML(text));
- }
- foreach(const boost::shared_ptr<FormField> field, section->getFields()) {
- sectionElement->addNode(fieldRefToXML(field->getName()));
- fields_.push_back(field);
- }
- foreach(const FormReportedRef::ref reportedRef, section->getReportedRefs()) {
- sectionElement->addNode(boost::make_shared<XMLElement>("reportedref"));
- }
- foreach(const FormSection::section childSection, section->getChildSections()) {
- sectionElement->addNode(sectionToXML(childSection));
- }
- return sectionElement;
+ boost::shared_ptr<XMLElement> sectionElement(new XMLElement("section"));
+ if (!section->getLabel().empty()) {
+ sectionElement->setAttribute("label", section->getLabel());
+ }
+ foreach(const FormText::text text, section->getTextElements()) {
+ sectionElement->addNode(textToXML(text));
+ }
+ foreach(const boost::shared_ptr<FormField> field, section->getFields()) {
+ sectionElement->addNode(fieldRefToXML(field->getName()));
+ fields_.push_back(field);
+ }
+ foreach(const FormReportedRef::ref reportedRef, section->getReportedRefs()) {
+ sectionElement->addNode(boost::make_shared<XMLElement>("reportedref"));
+ }
+ foreach(const FormSection::section childSection, section->getChildSections()) {
+ sectionElement->addNode(sectionToXML(childSection));
+ }
+ return sectionElement;
}
boost::shared_ptr<XMLElement> FormSerializer::fieldToXML(boost::shared_ptr<FormField> field, bool withTypeAttribute) const {
- boost::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(boost::make_shared<XMLElement>("required"));
- }
- if (!field->getDescription().empty()) {
- boost::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
- descriptionElement->addNode(boost::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()) {
- boost::shared_ptr<XMLElement> valueElement = boost::make_shared<XMLElement>("value");
- valueElement->addNode(boost::make_shared<XMLTextNode>(value));
- fieldElement->addNode(valueElement);
- }
-
- foreach (const FormField::Option& option, field->getOptions()) {
- boost::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
- if (!option.label.empty()) {
- optionElement->setAttribute("label", option.label);
- }
-
- boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
- valueElement->addNode(XMLTextNode::create(option.value));
- optionElement->addNode(valueElement);
- fieldElement->addNode(optionElement);
- }
- return fieldElement;
+ boost::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(boost::make_shared<XMLElement>("required"));
+ }
+ if (!field->getDescription().empty()) {
+ boost::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
+ descriptionElement->addNode(boost::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()) {
+ boost::shared_ptr<XMLElement> valueElement = boost::make_shared<XMLElement>("value");
+ valueElement->addNode(boost::make_shared<XMLTextNode>(value));
+ fieldElement->addNode(valueElement);
+ }
+
+ foreach (const FormField::Option& option, field->getOptions()) {
+ boost::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
+ if (!option.label.empty()) {
+ optionElement->setAttribute("label", option.label);
+ }
+
+ boost::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, boost::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) {
- boost::shared_ptr<XMLElement> lineElement(new XMLElement(elementName));
- lineElement->addNode(boost::make_shared<XMLTextNode>(line));
- element->addNode(lineElement);
- }
+ std::string unRdText(text);
+ erase(unRdText, '\r');
+ std::vector<std::string> lines = String::split(unRdText, '\n');
+ foreach (std::string line, lines) {
+ boost::shared_ptr<XMLElement> lineElement(new XMLElement(elementName));
+ lineElement->addNode(boost::make_shared<XMLTextNode>(line));
+ element->addNode(lineElement);
+ }
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FormSerializer.h b/Swiften/Serializer/PayloadSerializers/FormSerializer.h
index a01ecdb..62f6484 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.h
@@ -15,19 +15,19 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API FormSerializer : public GenericPayloadSerializer<Form> {
- public:
- FormSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Form>) const;
+ class SWIFTEN_API FormSerializer : public GenericPayloadSerializer<Form> {
+ public:
+ FormSerializer();
+ virtual std::string serializePayload(boost::shared_ptr<Form>) const;
- private:
- boost::shared_ptr<XMLElement> textToXML(boost::shared_ptr<FormText> textElement) const;
- boost::shared_ptr<XMLElement> fieldRefToXML(const std::string& ref) const;
- boost::shared_ptr<XMLElement> reportedRefToXML(boost::shared_ptr<FormReportedRef> reportedRef) const;
- boost::shared_ptr<XMLElement> pageToXML(boost::shared_ptr<FormPage> page) const;
- boost::shared_ptr<XMLElement> sectionToXML(boost::shared_ptr<FormSection> section) const;
- boost::shared_ptr<XMLElement> fieldToXML(boost::shared_ptr<FormField> field, bool withTypeAttribute) const;
- void multiLineify(const std::string& text, const std::string& elementName, boost::shared_ptr<XMLElement> parent) const;
- mutable std::vector<boost::shared_ptr<FormField> > fields_;
- };
+ private:
+ boost::shared_ptr<XMLElement> textToXML(boost::shared_ptr<FormText> textElement) const;
+ boost::shared_ptr<XMLElement> fieldRefToXML(const std::string& ref) const;
+ boost::shared_ptr<XMLElement> reportedRefToXML(boost::shared_ptr<FormReportedRef> reportedRef) const;
+ boost::shared_ptr<XMLElement> pageToXML(boost::shared_ptr<FormPage> page) const;
+ boost::shared_ptr<XMLElement> sectionToXML(boost::shared_ptr<FormSection> section) const;
+ boost::shared_ptr<XMLElement> fieldToXML(boost::shared_ptr<FormField> field, bool withTypeAttribute) const;
+ void multiLineify(const std::string& text, const std::string& elementName, boost::shared_ptr<XMLElement> parent) const;
+ mutable std::vector<boost::shared_ptr<FormField> > fields_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
index 61fe698..8df5793 100644
--- a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
@@ -31,29 +31,29 @@ ForwardedSerializer::~ForwardedSerializer() {
}
std::string ForwardedSerializer::serializePayload(boost::shared_ptr<Forwarded> payload) const {
- if (!payload) {
- return "";
- }
-
- XMLElement element("forwarded", "urn:xmpp:forward:0");
-
- if (payload->getDelay()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(DelaySerializer().serialize(payload->getDelay())));
- }
-
- if (payload->getStanza()) { /* find out what type of stanza we are dealing with and branch into the correct serializer*/
- boost::shared_ptr<IQ> iq;
- boost::shared_ptr<Message> message;
- boost::shared_ptr<Presence> presence;
- const std::string ns = "jabber:client";
- if ((iq = boost::dynamic_pointer_cast<IQ>(payload->getStanza()))) {
- element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(IQSerializer(serializers_).serialize(iq, ns))));
- } else if ((message = boost::dynamic_pointer_cast<Message>(payload->getStanza()))) {
- element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(MessageSerializer(serializers_).serialize(message, ns))));
- } else if ((presence = boost::dynamic_pointer_cast<Presence>(payload->getStanza()))) {
- element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(PresenceSerializer(serializers_).serialize(presence, ns))));
- }
- }
-
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+
+ XMLElement element("forwarded", "urn:xmpp:forward:0");
+
+ if (payload->getDelay()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(DelaySerializer().serialize(payload->getDelay())));
+ }
+
+ if (payload->getStanza()) { /* find out what type of stanza we are dealing with and branch into the correct serializer*/
+ boost::shared_ptr<IQ> iq;
+ boost::shared_ptr<Message> message;
+ boost::shared_ptr<Presence> presence;
+ const std::string ns = "jabber:client";
+ if ((iq = boost::dynamic_pointer_cast<IQ>(payload->getStanza()))) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(IQSerializer(serializers_).serialize(iq, ns))));
+ } else if ((message = boost::dynamic_pointer_cast<Message>(payload->getStanza()))) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(MessageSerializer(serializers_).serialize(message, ns))));
+ } else if ((presence = boost::dynamic_pointer_cast<Presence>(payload->getStanza()))) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(safeByteArrayToString(PresenceSerializer(serializers_).serialize(presence, ns))));
+ }
+ }
+
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h
index c325233..08b82b9 100644
--- a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h
@@ -14,16 +14,16 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API ForwardedSerializer : public GenericPayloadSerializer<Forwarded> {
- public:
- ForwardedSerializer(PayloadSerializerCollection* serializers);
- virtual ~ForwardedSerializer();
+ class SWIFTEN_API ForwardedSerializer : public GenericPayloadSerializer<Forwarded> {
+ public:
+ ForwardedSerializer(PayloadSerializerCollection* serializers);
+ virtual ~ForwardedSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Forwarded>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<Forwarded>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers_;
- };
+ private:
+ PayloadSerializerCollection* serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
index 589eeef..175de1e 100644
--- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
@@ -86,96 +86,96 @@
namespace Swift {
FullPayloadSerializerCollection::FullPayloadSerializerCollection() {
- serializers_.push_back(new IBBSerializer());
- serializers_.push_back(new BodySerializer());
- serializers_.push_back(new SubjectSerializer());
- serializers_.push_back(new ThreadSerializer());
- serializers_.push_back(new ChatStateSerializer());
- serializers_.push_back(new PrioritySerializer());
- serializers_.push_back(new ErrorSerializer(this));
- serializers_.push_back(new RosterSerializer());
- serializers_.push_back(new RosterItemExchangeSerializer());
- serializers_.push_back(new MUCPayloadSerializer());
- serializers_.push_back(new MUCDestroyPayloadSerializer());
- serializers_.push_back(new MUCAdminPayloadSerializer());
- serializers_.push_back(new MUCInvitationPayloadSerializer());
- serializers_.push_back(new MUCOwnerPayloadSerializer(this));
- serializers_.push_back(new MUCUserPayloadSerializer(this));
- serializers_.push_back(new SoftwareVersionSerializer());
- serializers_.push_back(new StatusSerializer());
- serializers_.push_back(new StatusShowSerializer());
- serializers_.push_back(new DiscoInfoSerializer());
- serializers_.push_back(new DiscoItemsSerializer());
- serializers_.push_back(new CapsInfoSerializer());
- serializers_.push_back(new BlockSerializer<BlockPayload>("block"));
- serializers_.push_back(new BlockSerializer<UnblockPayload>("unblock"));
- serializers_.push_back(new BlockSerializer<BlockListPayload>("blocklist"));
- serializers_.push_back(new ResourceBindSerializer());
- serializers_.push_back(new StartSessionSerializer());
- serializers_.push_back(new SecurityLabelSerializer());
- serializers_.push_back(new SecurityLabelsCatalogSerializer());
- serializers_.push_back(new StreamInitiationSerializer());
- serializers_.push_back(new BytestreamsSerializer());
- serializers_.push_back(new VCardSerializer());
- serializers_.push_back(new VCardUpdateSerializer());
- serializers_.push_back(new RawXMLPayloadSerializer());
- serializers_.push_back(new StorageSerializer());
- serializers_.push_back(new DelaySerializer());
- serializers_.push_back(new FormSerializer());
- serializers_.push_back(new PrivateStorageSerializer(this));
- serializers_.push_back(new CommandSerializer());
- serializers_.push_back(new InBandRegistrationPayloadSerializer());
- serializers_.push_back(new NicknameSerializer());
- serializers_.push_back(new SearchPayloadSerializer());
- serializers_.push_back(new ReplaceSerializer());
- serializers_.push_back(new LastSerializer());
- serializers_.push_back(new WhiteboardSerializer());
- serializers_.push_back(new UserLocationSerializer(this));
- serializers_.push_back(new UserTuneSerializer(this));
- serializers_.push_back(new IdleSerializer());
-
- serializers_.push_back(new StreamInitiationFileInfoSerializer());
- 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 IBBSerializer());
+ serializers_.push_back(new BodySerializer());
+ serializers_.push_back(new SubjectSerializer());
+ serializers_.push_back(new ThreadSerializer());
+ serializers_.push_back(new ChatStateSerializer());
+ serializers_.push_back(new PrioritySerializer());
+ serializers_.push_back(new ErrorSerializer(this));
+ serializers_.push_back(new RosterSerializer());
+ serializers_.push_back(new RosterItemExchangeSerializer());
+ serializers_.push_back(new MUCPayloadSerializer());
+ serializers_.push_back(new MUCDestroyPayloadSerializer());
+ serializers_.push_back(new MUCAdminPayloadSerializer());
+ serializers_.push_back(new MUCInvitationPayloadSerializer());
+ serializers_.push_back(new MUCOwnerPayloadSerializer(this));
+ serializers_.push_back(new MUCUserPayloadSerializer(this));
+ serializers_.push_back(new SoftwareVersionSerializer());
+ serializers_.push_back(new StatusSerializer());
+ serializers_.push_back(new StatusShowSerializer());
+ serializers_.push_back(new DiscoInfoSerializer());
+ serializers_.push_back(new DiscoItemsSerializer());
+ serializers_.push_back(new CapsInfoSerializer());
+ serializers_.push_back(new BlockSerializer<BlockPayload>("block"));
+ serializers_.push_back(new BlockSerializer<UnblockPayload>("unblock"));
+ serializers_.push_back(new BlockSerializer<BlockListPayload>("blocklist"));
+ serializers_.push_back(new ResourceBindSerializer());
+ serializers_.push_back(new StartSessionSerializer());
+ serializers_.push_back(new SecurityLabelSerializer());
+ serializers_.push_back(new SecurityLabelsCatalogSerializer());
+ serializers_.push_back(new StreamInitiationSerializer());
+ serializers_.push_back(new BytestreamsSerializer());
+ serializers_.push_back(new VCardSerializer());
+ serializers_.push_back(new VCardUpdateSerializer());
+ serializers_.push_back(new RawXMLPayloadSerializer());
+ serializers_.push_back(new StorageSerializer());
+ serializers_.push_back(new DelaySerializer());
+ serializers_.push_back(new FormSerializer());
+ serializers_.push_back(new PrivateStorageSerializer(this));
+ serializers_.push_back(new CommandSerializer());
+ serializers_.push_back(new InBandRegistrationPayloadSerializer());
+ serializers_.push_back(new NicknameSerializer());
+ serializers_.push_back(new SearchPayloadSerializer());
+ serializers_.push_back(new ReplaceSerializer());
+ serializers_.push_back(new LastSerializer());
+ serializers_.push_back(new WhiteboardSerializer());
+ serializers_.push_back(new UserLocationSerializer(this));
+ serializers_.push_back(new UserTuneSerializer(this));
+ serializers_.push_back(new IdleSerializer());
- 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 StreamInitiationFileInfoSerializer());
+ 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 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 PubSubSerializer(this));
+ serializers_.push_back(new PubSubEventSerializer(this));
+ serializers_.push_back(new PubSubOwnerPubSubSerializer(this));
+ serializers_.push_back(new PubSubErrorSerializer());
- 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 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 IsodeIQDelegationSerializer(this));
-
- foreach(PayloadSerializer* serializer, serializers_) {
- addSerializer(serializer);
- }
+ 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_) {
+ addSerializer(serializer);
+ }
}
FullPayloadSerializerCollection::~FullPayloadSerializerCollection() {
- foreach(PayloadSerializer* serializer, serializers_) {
- removeSerializer(serializer);
- delete serializer;
- }
- serializers_.clear();
+ foreach(PayloadSerializer* serializer, serializers_) {
+ removeSerializer(serializer);
+ delete serializer;
+ }
+ serializers_.clear();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h
index 35f5713..59354ea 100644
--- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h
+++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h
@@ -12,12 +12,12 @@
#include <Swiften/Serializer/PayloadSerializerCollection.h>
namespace Swift {
- class SWIFTEN_API FullPayloadSerializerCollection : public PayloadSerializerCollection {
- public:
- FullPayloadSerializerCollection();
- virtual ~FullPayloadSerializerCollection();
+ class SWIFTEN_API FullPayloadSerializerCollection : public PayloadSerializerCollection {
+ public:
+ FullPayloadSerializerCollection();
+ virtual ~FullPayloadSerializerCollection();
- private:
- std::vector<PayloadSerializer*> serializers_;
- };
+ private:
+ std::vector<PayloadSerializer*> serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
index de8958a..53ae0d2 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
@@ -23,35 +23,35 @@ IBBSerializer::IBBSerializer() {
}
std::string IBBSerializer::serializePayload(boost::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(boost::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();
- }
- case IBB::Close: {
- XMLElement ibbElement("close", "http://jabber.org/protocol/ibb");
- ibbElement.setAttribute("sid", ibb->getStreamID());
- return ibbElement.serialize();
- }
- }
- assert(false);
- return "";
+ 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(boost::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();
+ }
+ case IBB::Close: {
+ XMLElement ibbElement("close", "http://jabber.org/protocol/ibb");
+ ibbElement.setAttribute("sid", ibb->getStreamID());
+ return ibbElement.serialize();
+ }
+ }
+ assert(false);
+ return "";
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.h b/Swiften/Serializer/PayloadSerializers/IBBSerializer.h
index d8914c1..fe45eac 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API IBBSerializer : public GenericPayloadSerializer<IBB> {
- public:
- IBBSerializer();
+ class SWIFTEN_API IBBSerializer : public GenericPayloadSerializer<IBB> {
+ public:
+ IBBSerializer();
- virtual std::string serializePayload(boost::shared_ptr<IBB>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<IBB>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/IdleSerializer.h b/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
index b86ebd2..1a832a1 100644
--- a/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
@@ -18,12 +18,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API IdleSerializer : public GenericPayloadSerializer<Idle> {
- public:
- IdleSerializer() : GenericPayloadSerializer<Idle>() {}
+ class SWIFTEN_API IdleSerializer : public GenericPayloadSerializer<Idle> {
+ public:
+ IdleSerializer() : GenericPayloadSerializer<Idle>() {}
- virtual std::string serializePayload(boost::shared_ptr<Idle> idle) const {
- return "<idle xmlns='urn:xmpp:idle:1' since='" + dateTimeToString(idle->getSince()) + "'/>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Idle> idle) const {
+ return "<idle xmlns='urn:xmpp:idle:1' since='" + dateTimeToString(idle->getSince()) + "'/>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
index 45b8122..5f275f1 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
@@ -19,95 +19,95 @@ namespace Swift {
InBandRegistrationPayloadSerializer::InBandRegistrationPayloadSerializer() {
}
-std::string InBandRegistrationPayloadSerializer::serializePayload(boost::shared_ptr<InBandRegistrationPayload> registration) const {
- XMLElement registerElement("query", "jabber:iq:register");
+std::string InBandRegistrationPayloadSerializer::serializePayload(boost::shared_ptr<InBandRegistrationPayload> registration) const {
+ XMLElement registerElement("query", "jabber:iq:register");
- if (registration->isRegistered()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("registered")));
- }
+ if (registration->isRegistered()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("registered")));
+ }
- if (registration->isRemove()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("remove")));
- }
+ if (registration->isRemove()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("remove")));
+ }
- if (registration->getInstructions()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *registration->getInstructions())));
- }
+ 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->getUsername()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("username", "", *registration->getUsername())));
+ }
- if (registration->getNick()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("nick", "", *registration->getNick())));
- }
+ if (registration->getNick()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("nick", "", *registration->getNick())));
+ }
- if (registration->getPassword()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("password", "", *registration->getPassword())));
- }
+ if (registration->getPassword()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("password", "", *registration->getPassword())));
+ }
- if (registration->getName()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("name", "", *registration->getName())));
- }
+ if (registration->getName()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("name", "", *registration->getName())));
+ }
- if (registration->getFirst()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("first", "", *registration->getFirst())));
- }
+ if (registration->getFirst()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("first", "", *registration->getFirst())));
+ }
- if (registration->getLast()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("last", "", *registration->getLast())));
- }
+ if (registration->getLast()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("last", "", *registration->getLast())));
+ }
- if (registration->getEMail()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("email", "", *registration->getEMail())));
- }
+ if (registration->getEMail()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("email", "", *registration->getEMail())));
+ }
- if (registration->getAddress()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("address", "", *registration->getAddress())));
- }
+ if (registration->getAddress()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("address", "", *registration->getAddress())));
+ }
- if (registration->getCity()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("city", "", *registration->getCity())));
- }
+ if (registration->getCity()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("city", "", *registration->getCity())));
+ }
- if (registration->getState()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("state", "", *registration->getState())));
- }
+ if (registration->getState()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("state", "", *registration->getState())));
+ }
- if (registration->getZip()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("zip", "", *registration->getZip())));
- }
+ if (registration->getZip()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("zip", "", *registration->getZip())));
+ }
- if (registration->getPhone()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("phone", "", *registration->getPhone())));
- }
+ if (registration->getPhone()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("phone", "", *registration->getPhone())));
+ }
- if (registration->getURL()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("url", "", *registration->getURL())));
- }
+ if (registration->getURL()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("url", "", *registration->getURL())));
+ }
- if (registration->getDate()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("date", "", *registration->getDate())));
- }
+ if (registration->getDate()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("date", "", *registration->getDate())));
+ }
- if (registration->getMisc()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("misc", "", *registration->getMisc())));
- }
+ if (registration->getMisc()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("misc", "", *registration->getMisc())));
+ }
- if (registration->getText()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("text", "", *registration->getText())));
- }
+ if (registration->getText()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("text", "", *registration->getText())));
+ }
- if (registration->getKey()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("key", "", *registration->getKey())));
- }
+ if (registration->getKey()) {
+ registerElement.addNode(XMLElement::ref(new XMLElement("key", "", *registration->getKey())));
+ }
- if (Form::ref form = registration->getForm()) {
- registerElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
+ if (Form::ref form = registration->getForm()) {
+ registerElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
- return registerElement.serialize();
+ return registerElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h
index 6480749..45eb2f5 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h
@@ -12,10 +12,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API InBandRegistrationPayloadSerializer : public GenericPayloadSerializer<InBandRegistrationPayload> {
- public:
- InBandRegistrationPayloadSerializer();
+ class SWIFTEN_API InBandRegistrationPayloadSerializer : public GenericPayloadSerializer<InBandRegistrationPayload> {
+ public:
+ InBandRegistrationPayloadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<InBandRegistrationPayload>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<InBandRegistrationPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
index 7d6c64e..243ebc0 100644
--- a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
@@ -22,12 +22,12 @@ IsodeIQDelegationSerializer::~IsodeIQDelegationSerializer() {
}
std::string IsodeIQDelegationSerializer::serializePayload(boost::shared_ptr<IsodeIQDelegation> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("delegate", "http://isode.com/iq_delegation");
- element.addNode(boost::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(payload->getForward())->serialize(payload->getForward())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delegate", "http://isode.com/iq_delegation");
+ element.addNode(boost::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(payload->getForward())->serialize(payload->getForward())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h
index c505510..47a9ddc 100644
--- a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API IsodeIQDelegationSerializer : public GenericPayloadSerializer<IsodeIQDelegation> {
- public:
- IsodeIQDelegationSerializer(PayloadSerializerCollection* serializers);
- virtual ~IsodeIQDelegationSerializer();
+ class SWIFTEN_API IsodeIQDelegationSerializer : public GenericPayloadSerializer<IsodeIQDelegation> {
+ public:
+ IsodeIQDelegationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~IsodeIQDelegationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<IsodeIQDelegation>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<IsodeIQDelegation>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
index 6e04db4..c006a93 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
@@ -31,53 +31,53 @@ JingleContentPayloadSerializer::JingleContentPayloadSerializer() {
}
std::string JingleContentPayloadSerializer::serializePayload(boost::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()) {
- if ((filetransfer = boost::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) {
- payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ftSerializer.serializePayload(filetransfer)));
- }
- }
- }
-
- if (!payload->getTransports().empty()) {
- // JingleIBBTransportPayload
- JingleIBBTransportPayloadSerializer ibbSerializer;
- JingleIBBTransportPayload::ref ibb;
-
- // JingleS5BTransportPayload
- JingleS5BTransportPayloadSerializer s5bSerializer;
- JingleS5BTransportPayload::ref s5b;
+ XMLElement payloadXML("content");
+ payloadXML.setAttribute("creator", creatorToString(payload->getCreator()));
+ payloadXML.setAttribute("name", payload->getName());
- foreach(JingleTransportPayload::ref transport, payload->getTransports()) {
- if ((ibb = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
- payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb)));
- } else if ((s5b = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) {
- payloadXML.addNode(boost::make_shared<XMLRawTextNode>(s5bSerializer.serializePayload(s5b)));
- }
- }
- }
- return payloadXML.serialize();
+ if (!payload->getDescriptions().empty()) {
+ // JingleFileTransferDescription
+ JingleFileTransferDescriptionSerializer ftSerializer;
+ JingleFileTransferDescription::ref filetransfer;
+
+ foreach(JingleDescription::ref desc, payload->getDescriptions()) {
+ if ((filetransfer = boost::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) {
+ payloadXML.addNode(boost::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()) {
+ if ((ibb = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
+ payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb)));
+ } else if ((s5b = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) {
+ payloadXML.addNode(boost::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 "";
+ 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/JingleContentPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
index 87a4162..ff0185e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
@@ -18,15 +18,15 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API JingleContentPayloadSerializer : public GenericPayloadSerializer<JingleContentPayload> {
- public:
- JingleContentPayloadSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<JingleContentPayload>) const;
-
- private:
- std::string creatorToString(JingleContentPayload::Creator creator) const;
- };
+ class PayloadSerializerCollection;
+
+ class SWIFTEN_API JingleContentPayloadSerializer : public GenericPayloadSerializer<JingleContentPayload> {
+ public:
+ JingleContentPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleContentPayload>) const;
+
+ private:
+ std::string creatorToString(JingleContentPayload::Creator creator) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
index 28431ce..b0bb78d 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
@@ -30,12 +30,12 @@ JingleFileTransferDescriptionSerializer::JingleFileTransferDescriptionSerializer
}
std::string JingleFileTransferDescriptionSerializer::serializePayload(boost::shared_ptr<JingleFileTransferDescription> payload) const {
- XMLElement description("description", "urn:xmpp:jingle:apps:file-transfer:4");
+ XMLElement description("description", "urn:xmpp:jingle:apps:file-transfer:4");
- JingleFileTransferFileInfoSerializer fileInfoSerializer;
- boost::shared_ptr<XMLRawTextNode> fileInfoXML = boost::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(boost::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
- description.addNode(fileInfoXML);
- return description.serialize();
+ JingleFileTransferFileInfoSerializer fileInfoSerializer;
+ boost::shared_ptr<XMLRawTextNode> fileInfoXML = boost::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(boost::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
+ description.addNode(fileInfoXML);
+ return description.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
index e731612..53199f6 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
@@ -18,13 +18,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API JingleFileTransferDescriptionSerializer : public GenericPayloadSerializer<JingleFileTransferDescription> {
- public:
- JingleFileTransferDescriptionSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferDescription>) const;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API JingleFileTransferDescriptionSerializer : public GenericPayloadSerializer<JingleFileTransferDescription> {
+ public:
+ JingleFileTransferDescriptionSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferDescription>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
index 0c30b9d..7fcf452 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
@@ -24,43 +24,43 @@ JingleFileTransferFileInfoSerializer::JingleFileTransferFileInfoSerializer() {
std::string JingleFileTransferFileInfoSerializer::serializePayload(boost::shared_ptr<JingleFileTransferFileInfo> fileInfo) const {
- XMLElement fileElement("file", "");
-
- if (fileInfo->getDate() != stringToDateTime("")) {
- fileElement.addNode(boost::make_shared<XMLElement>("date", "", dateTimeToString(fileInfo->getDate())));
- }
-
- if (!fileInfo->getDescription().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription()));
- }
-
- if (!fileInfo->getMediaType().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("media-type", "", fileInfo->getMediaType()));
- }
-
- if (!fileInfo->getName().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("name", "", fileInfo->getName()));
- }
-
- if (fileInfo->getSupportsRangeRequests()) {
- boost::shared_ptr<XMLElement> range = boost::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(boost::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize())));
- }
-
- foreach (JingleFileTransferFileInfo::HashElementMap::value_type hashElement, fileInfo->getHashes()) {
- boost::shared_ptr<XMLElement> hash = boost::make_shared<XMLElement>("hash", "urn:xmpp:hashes:1", Base64::encode(hashElement.second));
- hash->setAttribute("algo", hashElement.first);
- fileElement.addNode(hash);
- }
-
- return fileElement.serialize();
+ XMLElement fileElement("file", "");
+
+ if (fileInfo->getDate() != stringToDateTime("")) {
+ fileElement.addNode(boost::make_shared<XMLElement>("date", "", dateTimeToString(fileInfo->getDate())));
+ }
+
+ if (!fileInfo->getDescription().empty()) {
+ fileElement.addNode(boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription()));
+ }
+
+ if (!fileInfo->getMediaType().empty()) {
+ fileElement.addNode(boost::make_shared<XMLElement>("media-type", "", fileInfo->getMediaType()));
+ }
+
+ if (!fileInfo->getName().empty()) {
+ fileElement.addNode(boost::make_shared<XMLElement>("name", "", fileInfo->getName()));
+ }
+
+ if (fileInfo->getSupportsRangeRequests()) {
+ boost::shared_ptr<XMLElement> range = boost::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(boost::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize())));
+ }
+
+ foreach (JingleFileTransferFileInfo::HashElementMap::value_type hashElement, fileInfo->getHashes()) {
+ boost::shared_ptr<XMLElement> hash = boost::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/JingleFileTransferFileInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
index c7b5233..bd4d8cd 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
@@ -12,12 +12,12 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API JingleFileTransferFileInfoSerializer : public GenericPayloadSerializer<JingleFileTransferFileInfo> {
- public:
- JingleFileTransferFileInfoSerializer();
+ class SWIFTEN_API JingleFileTransferFileInfoSerializer : public GenericPayloadSerializer<JingleFileTransferFileInfo> {
+ public:
+ JingleFileTransferFileInfoSerializer();
- virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferFileInfo>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferFileInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
index 137e0c0..4db5f0c 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
@@ -30,19 +30,19 @@ JingleFileTransferHashSerializer::JingleFileTransferHashSerializer() {
}
std::string JingleFileTransferHashSerializer::serializePayload(boost::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: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");
+ // code for version urn:xmpp:jingle:apps:file-transfer:4
+ XMLElement checksum("checksum", "urn:xmpp:jingle:apps:file-transfer:4");
- JingleFileTransferFileInfoSerializer fileSerializer;
+ JingleFileTransferFileInfoSerializer fileSerializer;
- boost::shared_ptr<XMLRawTextNode> file = boost::make_shared<XMLRawTextNode>(fileSerializer.serialize(boost::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
+ boost::shared_ptr<XMLRawTextNode> file = boost::make_shared<XMLRawTextNode>(fileSerializer.serialize(boost::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
- checksum.addNode(file);
+ checksum.addNode(file);
- return checksum.serialize();
+ return checksum.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
index f63db33..5434c17 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
@@ -18,13 +18,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API JingleFileTransferHashSerializer : public GenericPayloadSerializer<JingleFileTransferHash> {
- public:
- JingleFileTransferHashSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferHash>) const;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API JingleFileTransferHashSerializer : public GenericPayloadSerializer<JingleFileTransferHash> {
+ public:
+ JingleFileTransferHashSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferHash>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
index c165740..0574ea7 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
@@ -27,13 +27,13 @@ JingleIBBTransportPayloadSerializer::JingleIBBTransportPayloadSerializer() {
}
std::string JingleIBBTransportPayloadSerializer::serializePayload(boost::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());
+ 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();
+ return payloadXML.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
index 333c369..1b77666 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
@@ -18,13 +18,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API JingleIBBTransportPayloadSerializer : public GenericPayloadSerializer<JingleIBBTransportPayload> {
- public:
- JingleIBBTransportPayloadSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<JingleIBBTransportPayload>) const;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API JingleIBBTransportPayloadSerializer : public GenericPayloadSerializer<JingleIBBTransportPayload> {
+ public:
+ JingleIBBTransportPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleIBBTransportPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
index cebf936..a5bd60a 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -36,115 +36,115 @@ JinglePayloadSerializer::JinglePayloadSerializer(PayloadSerializerCollection* se
}
std::string JinglePayloadSerializer::serializePayload(boost::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());
+ 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<boost::shared_ptr<Payload> > payloads = payload->getPayloads();
- if (!payloads.empty()) {
- foreach(boost::shared_ptr<Payload> subPayload, payloads) {
- PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
- if (serializer) {
- jinglePayload.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(subPayload)));
- }
- }
- }
-
- if (payload->getReason().is_initialized()) {
- boost::shared_ptr<XMLElement> reason = boost::make_shared<XMLElement>("reason");
- reason->addNode(boost::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
- if (!payload->getReason()->text.empty()) {
- reason->addNode(boost::make_shared<XMLElement>("desc", "", payload->getReason()->text));
- }
- jinglePayload.addNode(reason);
- }
-
- return jinglePayload.serialize();
+ std::vector<boost::shared_ptr<Payload> > payloads = payload->getPayloads();
+ if (!payloads.empty()) {
+ foreach(boost::shared_ptr<Payload> subPayload, payloads) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
+ if (serializer) {
+ jinglePayload.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(subPayload)));
+ }
+ }
+ }
+
+ if (payload->getReason().is_initialized()) {
+ boost::shared_ptr<XMLElement> reason = boost::make_shared<XMLElement>("reason");
+ reason->addNode(boost::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
+ if (!payload->getReason()->text.empty()) {
+ reason->addNode(boost::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:
- return "content-remove";
- case JinglePayload::DescriptionInfo:
- return "description-info";
- case JinglePayload::SecurityInfo:
- return "security-info";
- case JinglePayload::SessionAccept:
- return "session-accept";
- case JinglePayload::SessionInfo:
- return "session-info";
- case JinglePayload::SessionInitiate:
- return "session-initiate";
- case JinglePayload::SessionTerminate:
- return "session-terminate";
- case JinglePayload::TransportAccept:
- return "transport-accept";
- case JinglePayload::TransportInfo:
- return "transport-info";
- case JinglePayload::TransportReject:
- return "transport-reject";
- case JinglePayload::TransportReplace:
- return "transport-replace";
- case JinglePayload::UnknownAction:
- SWIFT_LOG(warning) << "Serializing unknown action value." << std::endl;
- return "";
- }
- assert(false);
- return "";
+ 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:
+ return "content-remove";
+ case JinglePayload::DescriptionInfo:
+ return "description-info";
+ case JinglePayload::SecurityInfo:
+ return "security-info";
+ case JinglePayload::SessionAccept:
+ return "session-accept";
+ case JinglePayload::SessionInfo:
+ return "session-info";
+ case JinglePayload::SessionInitiate:
+ return "session-initiate";
+ case JinglePayload::SessionTerminate:
+ return "session-terminate";
+ case JinglePayload::TransportAccept:
+ return "transport-accept";
+ case JinglePayload::TransportInfo:
+ return "transport-info";
+ case JinglePayload::TransportReject:
+ return "transport-reject";
+ case JinglePayload::TransportReplace:
+ return "transport-replace";
+ case JinglePayload::UnknownAction:
+ SWIFT_LOG(warning) << "Serializing unknown action value." << std::endl;
+ return "";
+ }
+ assert(false);
+ return "";
}
std::string JinglePayloadSerializer::reasonTypeToString(JinglePayload::Reason::Type type) const {
- switch(type) {
- case JinglePayload::Reason::UnknownType:
- SWIFT_LOG(warning) << "Unknown jingle reason type!" << std::endl;
- return "";
- case JinglePayload::Reason::AlternativeSession:
- return "alternative-session";
- case JinglePayload::Reason::Busy:
- return "busy";
- case JinglePayload::Reason::Cancel:
- return "cancel";
- case JinglePayload::Reason::ConnectivityError:
- return "connectivity-error";
- case JinglePayload::Reason::Decline:
- return "decline";
- case JinglePayload::Reason::Expired:
- return "expired";
- case JinglePayload::Reason::FailedApplication:
- return "failed-application";
- case JinglePayload::Reason::FailedTransport:
- return "failed-transport";
- case JinglePayload::Reason::GeneralError:
- return "general-error";
- case JinglePayload::Reason::Gone:
- return "gone";
- case JinglePayload::Reason::IncompatibleParameters:
- return "incompatible-parameters";
- case JinglePayload::Reason::MediaError:
- return "media-error";
- case JinglePayload::Reason::SecurityError:
- return "security-error";
- case JinglePayload::Reason::Success:
- return "success";
- case JinglePayload::Reason::Timeout:
- return "timeout";
- case JinglePayload::Reason::UnsupportedApplications:
- return "unsupported-applications";
- case JinglePayload::Reason::UnsupportedTransports:
- return "unsupported-transports";
- }
- assert(false);
- return "";
+ switch(type) {
+ case JinglePayload::Reason::UnknownType:
+ SWIFT_LOG(warning) << "Unknown jingle reason type!" << std::endl;
+ return "";
+ case JinglePayload::Reason::AlternativeSession:
+ return "alternative-session";
+ case JinglePayload::Reason::Busy:
+ return "busy";
+ case JinglePayload::Reason::Cancel:
+ return "cancel";
+ case JinglePayload::Reason::ConnectivityError:
+ return "connectivity-error";
+ case JinglePayload::Reason::Decline:
+ return "decline";
+ case JinglePayload::Reason::Expired:
+ return "expired";
+ case JinglePayload::Reason::FailedApplication:
+ return "failed-application";
+ case JinglePayload::Reason::FailedTransport:
+ return "failed-transport";
+ case JinglePayload::Reason::GeneralError:
+ return "general-error";
+ case JinglePayload::Reason::Gone:
+ return "gone";
+ case JinglePayload::Reason::IncompatibleParameters:
+ return "incompatible-parameters";
+ case JinglePayload::Reason::MediaError:
+ return "media-error";
+ case JinglePayload::Reason::SecurityError:
+ return "security-error";
+ case JinglePayload::Reason::Success:
+ return "success";
+ case JinglePayload::Reason::Timeout:
+ return "timeout";
+ case JinglePayload::Reason::UnsupportedApplications:
+ return "unsupported-applications";
+ case JinglePayload::Reason::UnsupportedTransports:
+ return "unsupported-transports";
+ }
+ assert(false);
+ return "";
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
index 97215ab..9b36626 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
@@ -18,20 +18,20 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API JinglePayloadSerializer : public GenericPayloadSerializer<JinglePayload> {
- public:
- JinglePayloadSerializer(PayloadSerializerCollection*);
-
- virtual std::string serializePayload(boost::shared_ptr<JinglePayload>) const;
-
- private:
- std::string actionToString(JinglePayload::Action action) const;
- std::string reasonTypeToString(JinglePayload::Reason::Type type) const;
-
- private:
- PayloadSerializerCollection* serializers;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API JinglePayloadSerializer : public GenericPayloadSerializer<JinglePayload> {
+ public:
+ JinglePayloadSerializer(PayloadSerializerCollection*);
+
+ virtual std::string serializePayload(boost::shared_ptr<JinglePayload>) const;
+
+ private:
+ std::string actionToString(JinglePayload::Action action) const;
+ std::string reasonTypeToString(JinglePayload::Reason::Type type) const;
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
index 69e2488..66e6515 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
@@ -28,69 +28,69 @@ JingleS5BTransportPayloadSerializer::JingleS5BTransportPayloadSerializer() {
}
std::string JingleS5BTransportPayloadSerializer::serializePayload(boost::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()) {
- boost::shared_ptr<XMLElement> candidateXML = boost::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(boost::make_shared<XMLElement>("candidate-error"));
- }
- if (payload->hasProxyError()) {
- payloadXML.addNode(boost::make_shared<XMLElement>("proxy-error"));
- }
-
- if (!payload->getActivated().empty()) {
- boost::shared_ptr<XMLElement> activatedXML = boost::make_shared<XMLElement>("activated");
- activatedXML->setAttribute("cid", payload->getActivated());
- payloadXML.addNode(activatedXML);
- }
- if (!payload->getCandidateUsed().empty()) {
- boost::shared_ptr<XMLElement> candusedXML = boost::make_shared<XMLElement>("candidate-used");
- candusedXML->setAttribute("cid", payload->getCandidateUsed());
- payloadXML.addNode(candusedXML);
- }
-
- return payloadXML.serialize();
+ 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()) {
+ boost::shared_ptr<XMLElement> candidateXML = boost::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(boost::make_shared<XMLElement>("candidate-error"));
+ }
+ if (payload->hasProxyError()) {
+ payloadXML.addNode(boost::make_shared<XMLElement>("proxy-error"));
+ }
+
+ if (!payload->getActivated().empty()) {
+ boost::shared_ptr<XMLElement> activatedXML = boost::make_shared<XMLElement>("activated");
+ activatedXML->setAttribute("cid", payload->getActivated());
+ payloadXML.addNode(activatedXML);
+ }
+ if (!payload->getCandidateUsed().empty()) {
+ boost::shared_ptr<XMLElement> candusedXML = boost::make_shared<XMLElement>("candidate-used");
+ candusedXML->setAttribute("cid", payload->getCandidateUsed());
+ payloadXML.addNode(candusedXML);
+ }
+
+ return payloadXML.serialize();
}
std::string JingleS5BTransportPayloadSerializer::modeToString(JingleS5BTransportPayload::Mode mode) const {
- switch(mode) {
- case JingleS5BTransportPayload::TCPMode:
- return "tcp";
- case JingleS5BTransportPayload::UDPMode:
- return "udp";
- }
- assert(false);
- return "";
+ switch(mode) {
+ case JingleS5BTransportPayload::TCPMode:
+ return "tcp";
+ case JingleS5BTransportPayload::UDPMode:
+ return "udp";
+ }
+ assert(false);
+ return "";
}
std::string JingleS5BTransportPayloadSerializer::typeToString(JingleS5BTransportPayload::Candidate::Type type) const {
- switch(type) {
- case JingleS5BTransportPayload::Candidate::AssistedType:
- return "assisted";
- case JingleS5BTransportPayload::Candidate::DirectType:
- return "direct";
- case JingleS5BTransportPayload::Candidate::ProxyType:
- return "proxy";
- case JingleS5BTransportPayload::Candidate::TunnelType:
- return "tunnel";
- }
- assert(false);
- return "";
+ switch(type) {
+ case JingleS5BTransportPayload::Candidate::AssistedType:
+ return "assisted";
+ case JingleS5BTransportPayload::Candidate::DirectType:
+ return "direct";
+ case JingleS5BTransportPayload::Candidate::ProxyType:
+ return "proxy";
+ case JingleS5BTransportPayload::Candidate::TunnelType:
+ return "tunnel";
+ }
+ assert(false);
+ return "";
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
index 1d05969..684423e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
@@ -18,17 +18,17 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API JingleS5BTransportPayloadSerializer : public GenericPayloadSerializer<JingleS5BTransportPayload> {
- public:
- JingleS5BTransportPayloadSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<JingleS5BTransportPayload>) const;
-
- private:
- std::string modeToString(JingleS5BTransportPayload::Mode) const;
- std::string typeToString(JingleS5BTransportPayload::Candidate::Type) const;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API JingleS5BTransportPayloadSerializer : public GenericPayloadSerializer<JingleS5BTransportPayload> {
+ public:
+ JingleS5BTransportPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleS5BTransportPayload>) const;
+
+ private:
+ std::string modeToString(JingleS5BTransportPayload::Mode) const;
+ std::string typeToString(JingleS5BTransportPayload::Candidate::Type) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/LastSerializer.h b/Swiften/Serializer/PayloadSerializers/LastSerializer.h
index 18c5578..6c831eb 100644
--- a/Swiften/Serializer/PayloadSerializers/LastSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/LastSerializer.h
@@ -13,12 +13,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API LastSerializer : public GenericPayloadSerializer<Last> {
- public:
- LastSerializer() : GenericPayloadSerializer<Last>() {}
+ class SWIFTEN_API LastSerializer : public GenericPayloadSerializer<Last> {
+ public:
+ LastSerializer() : GenericPayloadSerializer<Last>() {}
- virtual std::string serializePayload(boost::shared_ptr<Last> last) const {
- return "<query xmlns='jabber:iq:last' seconds='" + boost::lexical_cast<std::string>(last->getSeconds()) + "'/>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Last> last) const {
+ return "<query xmlns='jabber:iq:last' seconds='" + boost::lexical_cast<std::string>(last->getSeconds()) + "'/>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp
index e17408f..d15038c 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp
@@ -23,27 +23,27 @@ MAMFinSerializer::~MAMFinSerializer() {
}
std::string MAMFinSerializer::serializePayload(boost::shared_ptr<MAMFin> payload) const {
- if (!payload) {
- return "";
- }
+ if (!payload) {
+ return "";
+ }
- XMLElement element("fin", "urn:xmpp:mam:0");
+ XMLElement element("fin", "urn:xmpp:mam:0");
- if (payload->isComplete()) {
- element.setAttribute("complete", "true");
- }
+ if (payload->isComplete()) {
+ element.setAttribute("complete", "true");
+ }
- if (!payload->isStable()) {
- element.setAttribute("stable", "false");
- }
+ if (!payload->isStable()) {
+ element.setAttribute("stable", "false");
+ }
- if (payload->getQueryID()) {
- element.setAttribute("queryid", *payload->getQueryID());
- }
+ if (payload->getQueryID()) {
+ element.setAttribute("queryid", *payload->getQueryID());
+ }
- if (payload->getResultSet()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(ResultSetSerializer().serialize(payload->getResultSet())));
- }
+ if (payload->getResultSet()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(ResultSetSerializer().serialize(payload->getResultSet())));
+ }
- return element.serialize();
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h
index b8ee1b1..2be6981 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API MAMFinSerializer : public GenericPayloadSerializer<MAMFin> {
- public:
- MAMFinSerializer();
- virtual ~MAMFinSerializer();
+ class SWIFTEN_API MAMFinSerializer : public GenericPayloadSerializer<MAMFin> {
+ public:
+ MAMFinSerializer();
+ virtual ~MAMFinSerializer();
- virtual std::string serializePayload(boost::shared_ptr<MAMFin>) const SWIFTEN_OVERRIDE;
- };
+ virtual std::string serializePayload(boost::shared_ptr<MAMFin>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
index 853bbf1..d503d0b 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
@@ -25,27 +25,27 @@ MAMQuerySerializer::~MAMQuerySerializer() {
}
std::string MAMQuerySerializer::serializePayload(boost::shared_ptr<MAMQuery> payload) const {
- if (!payload) {
- return "";
- }
+ if (!payload) {
+ return "";
+ }
- XMLElement element("query", "urn:xmpp:mam:0");
+ XMLElement element("query", "urn:xmpp:mam:0");
- if (payload->getQueryID()) {
- element.setAttribute("queryid", *payload->getQueryID());
- }
+ if (payload->getQueryID()) {
+ element.setAttribute("queryid", *payload->getQueryID());
+ }
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
- if (payload->getForm()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getForm())));
- }
+ if (payload->getForm()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getForm())));
+ }
- if (payload->getResultSet()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(ResultSetSerializer().serialize(payload->getResultSet())));
- }
+ if (payload->getResultSet()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(ResultSetSerializer().serialize(payload->getResultSet())));
+ }
- return element.serialize();
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h
index e86663e..8b5e270 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API MAMQuerySerializer : public GenericPayloadSerializer<MAMQuery> {
- public:
- MAMQuerySerializer();
- virtual ~MAMQuerySerializer();
+ class SWIFTEN_API MAMQuerySerializer : public GenericPayloadSerializer<MAMQuery> {
+ public:
+ MAMQuerySerializer();
+ virtual ~MAMQuerySerializer();
- virtual std::string serializePayload(boost::shared_ptr<MAMQuery>) const SWIFTEN_OVERRIDE;
- };
+ virtual std::string serializePayload(boost::shared_ptr<MAMQuery>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
index 4406e71..4bf25c6 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
@@ -23,19 +23,19 @@ MAMResultSerializer::~MAMResultSerializer() {
}
std::string MAMResultSerializer::serializePayload(boost::shared_ptr<MAMResult> payload) const {
- if (!payload) {
- return "";
- }
+ if (!payload) {
+ return "";
+ }
- XMLElement element("result", "urn:xmpp:mam:0");
+ XMLElement element("result", "urn:xmpp:mam:0");
- element.setAttribute("id", payload->getID());
+ element.setAttribute("id", payload->getID());
- if (payload->getQueryID()) {
- element.setAttribute("queryid", *payload->getQueryID());
- }
+ if (payload->getQueryID()) {
+ element.setAttribute("queryid", *payload->getQueryID());
+ }
- element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(payload->getPayload())));
+ element.addNode(boost::make_shared<XMLRawTextNode>(ForwardedSerializer(serializers_).serialize(payload->getPayload())));
- return element.serialize();
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h
index 3338080..4d8168c 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h
@@ -14,16 +14,16 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API MAMResultSerializer : public GenericPayloadSerializer<MAMResult> {
- public:
- MAMResultSerializer(PayloadSerializerCollection* serializers);
- virtual ~MAMResultSerializer();
+ class SWIFTEN_API MAMResultSerializer : public GenericPayloadSerializer<MAMResult> {
+ public:
+ MAMResultSerializer(PayloadSerializerCollection* serializers);
+ virtual ~MAMResultSerializer();
- virtual std::string serializePayload(boost::shared_ptr<MAMResult>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<MAMResult>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers_;
- };
+ private:
+ PayloadSerializerCollection* serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
index 9f79c3e..5bd4b01 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
@@ -22,11 +22,11 @@ MUCAdminPayloadSerializer::MUCAdminPayloadSerializer() : GenericPayloadSerialize
}
std::string MUCAdminPayloadSerializer::serializePayload(boost::shared_ptr<MUCAdminPayload> payload) const {
- XMLElement mucElement("query", "http://jabber.org/protocol/muc#admin");
- foreach (const MUCItem& item, payload->getItems()) {
- mucElement.addNode(MUCItemSerializer::itemToElement(item));
- }
- return mucElement.serialize();
+ XMLElement mucElement("query", "http://jabber.org/protocol/muc#admin");
+ foreach (const MUCItem& item, payload->getItems()) {
+ mucElement.addNode(MUCItemSerializer::itemToElement(item));
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h
index 3f763ae..b1e1ed1 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h
@@ -11,13 +11,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API MUCAdminPayloadSerializer : public GenericPayloadSerializer<MUCAdminPayload> {
- public:
- MUCAdminPayloadSerializer();
- std::string affiliationToString(MUCOccupant::Affiliation affiliation) const;
- std::string roleToString(MUCOccupant::Role role) const;
+ class SWIFTEN_API MUCAdminPayloadSerializer : public GenericPayloadSerializer<MUCAdminPayload> {
+ public:
+ MUCAdminPayloadSerializer();
+ std::string affiliationToString(MUCOccupant::Affiliation affiliation) const;
+ std::string roleToString(MUCOccupant::Role role) const;
- virtual std::string serializePayload(boost::shared_ptr<MUCAdminPayload> version) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<MUCAdminPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
index f6d8c8f..86d684e 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
@@ -19,16 +19,16 @@ MUCDestroyPayloadSerializer::MUCDestroyPayloadSerializer() : GenericPayloadSeria
}
std::string MUCDestroyPayloadSerializer::serializePayload(boost::shared_ptr<MUCDestroyPayload> payload) const {
- XMLElement mucElement("destroy", "");
- if (!payload->getReason().empty()) {
- XMLElement::ref reason = boost::make_shared<XMLElement>("reason", "");
- reason->addNode(boost::make_shared<XMLTextNode>(payload->getReason()));
- mucElement.addNode(reason);
- }
- if (payload->getNewVenue().isValid()) {
- mucElement.setAttribute("jid", payload->getNewVenue().toString());
- }
- return mucElement.serialize();
+ XMLElement mucElement("destroy", "");
+ if (!payload->getReason().empty()) {
+ XMLElement::ref reason = boost::make_shared<XMLElement>("reason", "");
+ reason->addNode(boost::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/MUCDestroyPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
index 75804ce..c6175fb 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
@@ -11,11 +11,11 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class SWIFTEN_API MUCDestroyPayloadSerializer : public GenericPayloadSerializer<MUCDestroyPayload> {
- public:
- MUCDestroyPayloadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<MUCDestroyPayload> version) const;
- };
+ class PayloadSerializerCollection;
+ class SWIFTEN_API MUCDestroyPayloadSerializer : public GenericPayloadSerializer<MUCDestroyPayload> {
+ public:
+ MUCDestroyPayloadSerializer();
+ virtual std::string serializePayload(boost::shared_ptr<MUCDestroyPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
index ace52d5..4695f63 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
@@ -20,26 +20,26 @@ MUCInvitationPayloadSerializer::MUCInvitationPayloadSerializer() : GenericPayloa
}
std::string MUCInvitationPayloadSerializer::serializePayload(boost::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(boost::make_shared<XMLElement>("impromptu", "http://swift.im/impromptu"));
- }
- return mucElement.serialize();
+ 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(boost::make_shared<XMLElement>("impromptu", "http://swift.im/impromptu"));
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
index 6872520..a2d27b0 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
@@ -11,11 +11,11 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API MUCInvitationPayloadSerializer : public GenericPayloadSerializer<MUCInvitationPayload> {
- public:
- MUCInvitationPayloadSerializer();
+ class SWIFTEN_API MUCInvitationPayloadSerializer : public GenericPayloadSerializer<MUCInvitationPayload> {
+ public:
+ MUCInvitationPayloadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<MUCInvitationPayload> version) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<MUCInvitationPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
index 7906888..016caf4 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
@@ -14,57 +14,57 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class MUCItemSerializer {
- public:
- static std::string affiliationToString(MUCOccupant::Affiliation affiliation) {
- std::string result;
- switch (affiliation) {
- case MUCOccupant::Owner: result = "owner"; break;
- case MUCOccupant::Admin: result = "admin"; break;
- case MUCOccupant::Member: result = "member"; break;
- case MUCOccupant::Outcast: result = "outcast"; break;
- case MUCOccupant::NoAffiliation: result = "none"; break;
- }
- return result;
- }
+ class MUCItemSerializer {
+ public:
+ static std::string affiliationToString(MUCOccupant::Affiliation affiliation) {
+ std::string result;
+ switch (affiliation) {
+ case MUCOccupant::Owner: result = "owner"; break;
+ case MUCOccupant::Admin: result = "admin"; break;
+ case MUCOccupant::Member: result = "member"; break;
+ case MUCOccupant::Outcast: result = "outcast"; break;
+ case MUCOccupant::NoAffiliation: result = "none"; break;
+ }
+ return result;
+ }
- static std::string roleToString(MUCOccupant::Role role) {
- std::string result;
- switch (role) {
- case MUCOccupant::Moderator: result = "moderator"; break;
- case MUCOccupant::NoRole: result = "none"; break;
- case MUCOccupant::Participant: result = "participant"; break;
- case MUCOccupant::Visitor: result = "visitor"; break;
- }
- return result;
+ static std::string roleToString(MUCOccupant::Role role) {
+ std::string result;
+ switch (role) {
+ case MUCOccupant::Moderator: result = "moderator"; break;
+ case MUCOccupant::NoRole: result = "none"; break;
+ case MUCOccupant::Participant: result = "participant"; break;
+ case MUCOccupant::Visitor: result = "visitor"; break;
+ }
+ return result;
- }
+ }
- static boost::shared_ptr<XMLElement> itemToElement(const MUCItem& item) {
- boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
- if (item.affiliation) {
- itemElement->setAttribute("affiliation", affiliationToString(item.affiliation.get()));
- }
- if (item.role) {
- itemElement->setAttribute("role", roleToString(item.role.get()));
- }
- if (item.realJID) {
- itemElement->setAttribute("jid", item.realJID.get());
- }
- if (item.nick) {
- itemElement->setAttribute("nick", item.nick.get());
- }
- if (item.actor) {
- boost::shared_ptr<XMLElement> actorElement(new XMLElement("actor"));
- actorElement->setAttribute("jid", item.actor->toString());
- itemElement->addNode(actorElement);
- }
- if (item.reason) {
- boost::shared_ptr<XMLElement> reasonElement(new XMLElement("reason"));
- reasonElement->addNode(boost::make_shared<XMLTextNode>(*item.reason));
- itemElement->addNode(reasonElement);
- }
- return itemElement;
- }
- };
+ static boost::shared_ptr<XMLElement> itemToElement(const MUCItem& item) {
+ boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ if (item.affiliation) {
+ itemElement->setAttribute("affiliation", affiliationToString(item.affiliation.get()));
+ }
+ if (item.role) {
+ itemElement->setAttribute("role", roleToString(item.role.get()));
+ }
+ if (item.realJID) {
+ itemElement->setAttribute("jid", item.realJID.get());
+ }
+ if (item.nick) {
+ itemElement->setAttribute("nick", item.nick.get());
+ }
+ if (item.actor) {
+ boost::shared_ptr<XMLElement> actorElement(new XMLElement("actor"));
+ actorElement->setAttribute("jid", item.actor->toString());
+ itemElement->addNode(actorElement);
+ }
+ if (item.reason) {
+ boost::shared_ptr<XMLElement> reasonElement(new XMLElement("reason"));
+ reasonElement->addNode(boost::make_shared<XMLTextNode>(*item.reason));
+ itemElement->addNode(reasonElement);
+ }
+ return itemElement;
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
index 7597d8f..348f9f5 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
@@ -18,15 +18,15 @@ MUCOwnerPayloadSerializer::MUCOwnerPayloadSerializer(PayloadSerializerCollection
}
std::string MUCOwnerPayloadSerializer::serializePayload(boost::shared_ptr<MUCOwnerPayload> mucOwner) const {
- XMLElement mucElement("query", "http://jabber.org/protocol/muc#owner");
- boost::shared_ptr<Payload> payload = mucOwner->getPayload();
- if (payload) {
- PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
- if (serializer) {
- mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
- }
- }
- return mucElement.serialize();
+ XMLElement mucElement("query", "http://jabber.org/protocol/muc#owner");
+ boost::shared_ptr<Payload> payload = mucOwner->getPayload();
+ if (payload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
+ if (serializer) {
+ mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
+ }
+ }
+ return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
index ffce898..bbe919a 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
@@ -11,13 +11,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class SWIFTEN_API MUCOwnerPayloadSerializer : public GenericPayloadSerializer<MUCOwnerPayload> {
- public:
- MUCOwnerPayloadSerializer(PayloadSerializerCollection* serializers);
- virtual std::string serializePayload(boost::shared_ptr<MUCOwnerPayload> version) const;
- private:
- PayloadSerializerCollection* serializers;
- };
+ class PayloadSerializerCollection;
+ class SWIFTEN_API MUCOwnerPayloadSerializer : public GenericPayloadSerializer<MUCOwnerPayload> {
+ public:
+ MUCOwnerPayloadSerializer(PayloadSerializerCollection* serializers);
+ virtual std::string serializePayload(boost::shared_ptr<MUCOwnerPayload> version) const;
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
index 30421dd..9af2f15 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
@@ -20,38 +20,38 @@ MUCPayloadSerializer::MUCPayloadSerializer() : GenericPayloadSerializer<MUCPaylo
}
std::string MUCPayloadSerializer::serializePayload(boost::shared_ptr<MUCPayload> muc) const {
- XMLElement mucElement("x", "http://jabber.org/protocol/muc");
- boost::shared_ptr<XMLElement> historyElement(new XMLElement("history"));
- bool history = false;
- if (muc->getMaxChars() >= 0) {
- historyElement->setAttribute("maxchars", boost::lexical_cast<std::string>(muc->getMaxChars()));
- history = true;
- }
- if (muc->getMaxStanzas() >= 0) {
- historyElement->setAttribute("maxstanzas", boost::lexical_cast<std::string>(muc->getMaxStanzas()));
- history = true;
- }
- if (muc->getSeconds() >= 0) {
- historyElement->setAttribute("seconds", boost::lexical_cast<std::string>(muc->getSeconds()));
- history = true;
- }
- if (muc->getSince() != boost::posix_time::not_a_date_time) {
- std::string sinceString = std::string(boost::posix_time::to_iso_extended_string(muc->getSince()));
- String::replaceAll(sinceString, ',', ".");
- sinceString += "Z";
- historyElement->setAttribute("since", sinceString);
- history = true;
- }
- if (muc->getPassword()) {
- std::string password = *muc->getPassword();
- boost::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
- passwordElement->addNode(boost::make_shared<XMLTextNode>(password));
- mucElement.addNode(passwordElement);
- }
- if (history) {
- mucElement.addNode(historyElement);
- }
- return mucElement.serialize();
+ XMLElement mucElement("x", "http://jabber.org/protocol/muc");
+ boost::shared_ptr<XMLElement> historyElement(new XMLElement("history"));
+ bool history = false;
+ if (muc->getMaxChars() >= 0) {
+ historyElement->setAttribute("maxchars", boost::lexical_cast<std::string>(muc->getMaxChars()));
+ history = true;
+ }
+ if (muc->getMaxStanzas() >= 0) {
+ historyElement->setAttribute("maxstanzas", boost::lexical_cast<std::string>(muc->getMaxStanzas()));
+ history = true;
+ }
+ if (muc->getSeconds() >= 0) {
+ historyElement->setAttribute("seconds", boost::lexical_cast<std::string>(muc->getSeconds()));
+ history = true;
+ }
+ if (muc->getSince() != boost::posix_time::not_a_date_time) {
+ std::string sinceString = std::string(boost::posix_time::to_iso_extended_string(muc->getSince()));
+ String::replaceAll(sinceString, ',', ".");
+ sinceString += "Z";
+ historyElement->setAttribute("since", sinceString);
+ history = true;
+ }
+ if (muc->getPassword()) {
+ std::string password = *muc->getPassword();
+ boost::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
+ passwordElement->addNode(boost::make_shared<XMLTextNode>(password));
+ mucElement.addNode(passwordElement);
+ }
+ if (history) {
+ mucElement.addNode(historyElement);
+ }
+ return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h
index 84f38d2..fa3a11c 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API MUCPayloadSerializer : public GenericPayloadSerializer<MUCPayload> {
- public:
- MUCPayloadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<MUCPayload> version) const;
- };
+ class SWIFTEN_API MUCPayloadSerializer : public GenericPayloadSerializer<MUCPayload> {
+ public:
+ MUCPayloadSerializer();
+ virtual std::string serializePayload(boost::shared_ptr<MUCPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
index 0e560a2..d0c3b2b 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
@@ -24,47 +24,47 @@ MUCUserPayloadSerializer::MUCUserPayloadSerializer(PayloadSerializerCollection*
}
std::string MUCUserPayloadSerializer::serializePayload(boost::shared_ptr<MUCUserPayload> payload) const {
- XMLElement mucElement("x", "http://jabber.org/protocol/muc#user");
- foreach (const MUCUserPayload::StatusCode statusCode, payload->getStatusCodes()) {
- boost::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()) {
- mucElement.addNode(MUCItemSerializer::itemToElement(item));
- }
+ XMLElement mucElement("x", "http://jabber.org/protocol/muc#user");
+ foreach (const MUCUserPayload::StatusCode statusCode, payload->getStatusCodes()) {
+ boost::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()) {
+ mucElement.addNode(MUCItemSerializer::itemToElement(item));
+ }
- if (payload->getPassword()) {
- boost::shared_ptr<XMLElement> passwordElement = boost::make_shared<XMLElement>("password");
- passwordElement->addNode(boost::make_shared<XMLTextNode>(*payload->getPassword()));
- }
+ if (payload->getPassword()) {
+ boost::shared_ptr<XMLElement> passwordElement = boost::make_shared<XMLElement>("password");
+ passwordElement->addNode(boost::make_shared<XMLTextNode>(*payload->getPassword()));
+ }
- if (payload->getInvite()) {
- MUCUserPayload::Invite invite = *payload->getInvite();
- boost::shared_ptr<XMLElement> inviteElement = boost::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()) {
- boost::shared_ptr<XMLElement> reasonElement = boost::make_shared<XMLElement>("reason");
- reasonElement->addNode(boost::make_shared<XMLTextNode>(invite.reason));
- }
- mucElement.addNode(inviteElement);
- }
+ if (payload->getInvite()) {
+ MUCUserPayload::Invite invite = *payload->getInvite();
+ boost::shared_ptr<XMLElement> inviteElement = boost::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()) {
+ boost::shared_ptr<XMLElement> reasonElement = boost::make_shared<XMLElement>("reason");
+ reasonElement->addNode(boost::make_shared<XMLTextNode>(invite.reason));
+ }
+ mucElement.addNode(inviteElement);
+ }
- boost::shared_ptr<Payload> childPayload = payload->getPayload();
- if (childPayload) {
- PayloadSerializer* serializer = serializers->getPayloadSerializer(childPayload);
- if (serializer) {
- mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(childPayload)));
- }
- }
- return mucElement.serialize();
+ boost::shared_ptr<Payload> childPayload = payload->getPayload();
+ if (childPayload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(childPayload);
+ if (serializer) {
+ mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(childPayload)));
+ }
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
index b1ace20..91b2ae6 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
@@ -11,14 +11,14 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class SWIFTEN_API MUCUserPayloadSerializer : public GenericPayloadSerializer<MUCUserPayload> {
- public:
- MUCUserPayloadSerializer(PayloadSerializerCollection* serializers);
+ class PayloadSerializerCollection;
+ class SWIFTEN_API MUCUserPayloadSerializer : public GenericPayloadSerializer<MUCUserPayload> {
+ public:
+ MUCUserPayloadSerializer(PayloadSerializerCollection* serializers);
- virtual std::string serializePayload(boost::shared_ptr<MUCUserPayload> version) const;
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(boost::shared_ptr<MUCUserPayload> version) const;
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
index 303ef9a..3b927f4 100644
--- a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
@@ -18,9 +18,9 @@ NicknameSerializer::NicknameSerializer() : GenericPayloadSerializer<Nickname>()
}
std::string NicknameSerializer::serializePayload(boost::shared_ptr<Nickname> nick) const {
- XMLElement nickElement("nick", "http://jabber.org/protocol/nick");
- nickElement.addNode(boost::make_shared<XMLTextNode>(nick->getNickname()));
- return nickElement.serialize();
+ XMLElement nickElement("nick", "http://jabber.org/protocol/nick");
+ nickElement.addNode(boost::make_shared<XMLTextNode>(nick->getNickname()));
+ return nickElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
index e694624..d1b6e81 100644
--- a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
@@ -11,12 +11,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API NicknameSerializer : public GenericPayloadSerializer<Nickname> {
- public:
- NicknameSerializer();
+ class SWIFTEN_API NicknameSerializer : public GenericPayloadSerializer<Nickname> {
+ public:
+ NicknameSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Nickname>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<Nickname>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
index 406f527..d7f0957 100644
--- a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
@@ -13,12 +13,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API PrioritySerializer : public GenericPayloadSerializer<Priority> {
- public:
- PrioritySerializer() : GenericPayloadSerializer<Priority>() {}
+ class SWIFTEN_API PrioritySerializer : public GenericPayloadSerializer<Priority> {
+ public:
+ PrioritySerializer() : GenericPayloadSerializer<Priority>() {}
- virtual std::string serializePayload(boost::shared_ptr<Priority> priority) const {
- return "<priority>" + boost::lexical_cast<std::string>(priority->getPriority()) + "</priority>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Priority> priority) const {
+ return "<priority>" + boost::lexical_cast<std::string>(priority->getPriority()) + "</priority>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
index bc916aa..2d03e1b 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
@@ -20,16 +20,16 @@ namespace Swift {
PrivateStorageSerializer::PrivateStorageSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
-std::string PrivateStorageSerializer::serializePayload(boost::shared_ptr<PrivateStorage> storage) const {
- XMLElement storageElement("query", "jabber:iq:private");
- boost::shared_ptr<Payload> payload = storage->getPayload();
- if (payload) {
- PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
- if (serializer) {
- storageElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
- }
- }
- return storageElement.serialize();
+std::string PrivateStorageSerializer::serializePayload(boost::shared_ptr<PrivateStorage> storage) const {
+ XMLElement storageElement("query", "jabber:iq:private");
+ boost::shared_ptr<Payload> payload = storage->getPayload();
+ if (payload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
+ if (serializer) {
+ storageElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
+ }
+ }
+ return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
index 0a88193..a014e52 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
@@ -11,15 +11,15 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PrivateStorageSerializer : public GenericPayloadSerializer<PrivateStorage> {
- public:
- PrivateStorageSerializer(PayloadSerializerCollection* serializers);
+ class SWIFTEN_API PrivateStorageSerializer : public GenericPayloadSerializer<PrivateStorage> {
+ public:
+ PrivateStorageSerializer(PayloadSerializerCollection* serializers);
- virtual std::string serializePayload(boost::shared_ptr<PrivateStorage>) const;
+ virtual std::string serializePayload(boost::shared_ptr<PrivateStorage>) const;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp
index 0e02e2b..8e58ff5 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp
@@ -22,24 +22,24 @@ PubSubAffiliationSerializer::~PubSubAffiliationSerializer() {
}
std::string PubSubAffiliationSerializer::serializePayload(boost::shared_ptr<PubSubAffiliation> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("affiliation", "http://jabber.org/protocol/pubsub");
- element.setAttribute("node", payload->getNode());
- element.setAttribute("affiliation", serializeType(payload->getType()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliation", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ element.setAttribute("affiliation", serializeType(payload->getType()));
+ return element.serialize();
}
std::string PubSubAffiliationSerializer::serializeType(PubSubAffiliation::Type value) {
- switch (value) {
- case PubSubAffiliation::None: return "none";
- case PubSubAffiliation::Member: return "member";
- case PubSubAffiliation::Outcast: return "outcast";
- case PubSubAffiliation::Owner: return "owner";
- case PubSubAffiliation::Publisher: return "publisher";
- case PubSubAffiliation::PublishOnly: return "publish-only";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubAffiliation::None: return "none";
+ case PubSubAffiliation::Member: return "member";
+ case PubSubAffiliation::Outcast: return "outcast";
+ case PubSubAffiliation::Owner: return "owner";
+ case PubSubAffiliation::Publisher: return "publisher";
+ case PubSubAffiliation::PublishOnly: return "publish-only";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h
index dfa235f..d451745 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubAffiliationSerializer : public GenericPayloadSerializer<PubSubAffiliation> {
- public:
- PubSubAffiliationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubAffiliationSerializer();
+ class SWIFTEN_API PubSubAffiliationSerializer : public GenericPayloadSerializer<PubSubAffiliation> {
+ public:
+ PubSubAffiliationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubAffiliationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubAffiliation>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubAffiliation>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeType(PubSubAffiliation::Type);
+ private:
+ static std::string serializeType(PubSubAffiliation::Type);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
index 4003b6c..eba96aa 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
@@ -24,17 +24,17 @@ PubSubAffiliationsSerializer::~PubSubAffiliationsSerializer() {
}
std::string PubSubAffiliationsSerializer::serializePayload(boost::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(boost::shared_ptr<PubSubAffiliation> item, payload->getAffiliations()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubAffiliationSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliations", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ foreach(boost::shared_ptr<PubSubAffiliation> item, payload->getAffiliations()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubAffiliationSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
index 25e12b8..211d957 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubAffiliationsSerializer : public GenericPayloadSerializer<PubSubAffiliations> {
- public:
- PubSubAffiliationsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubAffiliationsSerializer();
+ class SWIFTEN_API PubSubAffiliationsSerializer : public GenericPayloadSerializer<PubSubAffiliations> {
+ public:
+ PubSubAffiliationsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubAffiliationsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubAffiliations>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubAffiliations>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp
index 887e6e9..1853c1c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp
@@ -23,12 +23,12 @@ PubSubConfigureSerializer::~PubSubConfigureSerializer() {
}
std::string PubSubConfigureSerializer::serializePayload(boost::shared_ptr<PubSubConfigure> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("configure", "http://jabber.org/protocol/pubsub");
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("configure", "http://jabber.org/protocol/pubsub");
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h
index 9fe3680..3d800d8 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubConfigureSerializer : public GenericPayloadSerializer<PubSubConfigure> {
- public:
- PubSubConfigureSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubConfigureSerializer();
+ class SWIFTEN_API PubSubConfigureSerializer : public GenericPayloadSerializer<PubSubConfigure> {
+ public:
+ PubSubConfigureSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubConfigureSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubConfigure>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubConfigure>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
index 0f9094d..8b38fc1 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
@@ -22,12 +22,12 @@ PubSubCreateSerializer::~PubSubCreateSerializer() {
}
std::string PubSubCreateSerializer::serializePayload(boost::shared_ptr<PubSubCreate> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("create", "http://jabber.org/protocol/pubsub");
- element.setAttribute("node", payload->getNode());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("create", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h
index c9bb95a..67b19bf 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubCreateSerializer : public GenericPayloadSerializer<PubSubCreate> {
- public:
- PubSubCreateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubCreateSerializer();
+ class SWIFTEN_API PubSubCreateSerializer : public GenericPayloadSerializer<PubSubCreate> {
+ public:
+ PubSubCreateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubCreateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubCreate>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubCreate>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
index c101623..aba1cae 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
@@ -22,23 +22,23 @@ PubSubDefaultSerializer::~PubSubDefaultSerializer() {
}
std::string PubSubDefaultSerializer::serializePayload(boost::shared_ptr<PubSubDefault> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("default", "http://jabber.org/protocol/pubsub");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- element.setAttribute("type", serializeType(payload->getType()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("default", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ element.setAttribute("type", serializeType(payload->getType()));
+ return element.serialize();
}
std::string PubSubDefaultSerializer::serializeType(PubSubDefault::Type value) {
- switch (value) {
- case PubSubDefault::None: return "none";
- case PubSubDefault::Collection: return "collection";
- case PubSubDefault::Leaf: return "leaf";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubDefault::None: return "none";
+ case PubSubDefault::Collection: return "collection";
+ case PubSubDefault::Leaf: return "leaf";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h
index 344a8c7..5dc774f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubDefaultSerializer : public GenericPayloadSerializer<PubSubDefault> {
- public:
- PubSubDefaultSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubDefaultSerializer();
+ class SWIFTEN_API PubSubDefaultSerializer : public GenericPayloadSerializer<PubSubDefault> {
+ public:
+ PubSubDefaultSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubDefaultSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubDefault>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubDefault>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeType(PubSubDefault::Type);
+ private:
+ static std::string serializeType(PubSubDefault::Type);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
index 8235746..d14db49 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
@@ -18,94 +18,94 @@ PubSubErrorSerializer::~PubSubErrorSerializer() {
}
std::string PubSubErrorSerializer::serializePayload(boost::shared_ptr<PubSubError> payload) const {
- if (payload->getType() == PubSubError::UnknownType) {
- return "";
- }
- XMLElement element(serializeType(payload->getType()), "http://jabber.org/protocol/pubsub#errors");
- if (payload->getType() == PubSubError::Unsupported) {
- if (payload->getUnsupportedFeatureType() != PubSubError::UnknownUnsupportedFeatureType) {
- element.setAttribute("feature", serializeUnsupportedFeatureType(payload->getUnsupportedFeatureType()));
- }
- }
- return element.serialize();
+ if (payload->getType() == PubSubError::UnknownType) {
+ return "";
+ }
+ XMLElement element(serializeType(payload->getType()), "http://jabber.org/protocol/pubsub#errors");
+ if (payload->getType() == PubSubError::Unsupported) {
+ if (payload->getUnsupportedFeatureType() != PubSubError::UnknownUnsupportedFeatureType) {
+ element.setAttribute("feature", serializeUnsupportedFeatureType(payload->getUnsupportedFeatureType()));
+ }
+ }
+ return element.serialize();
}
std::string PubSubErrorSerializer::serializeType(PubSubError::Type value) {
- switch (value) {
- case PubSubError::UnknownType: assert(false); return "";
- case PubSubError::ClosedNode: return "closed-node";
- case PubSubError::ConfigurationRequired: return "configuration-required";
- case PubSubError::InvalidJID: return "invalid-jid";
- case PubSubError::InvalidOptions: return "invalid-options";
- case PubSubError::InvalidPayload: return "invalid-payload";
- case PubSubError::InvalidSubscriptionID: return "invalid-subid";
- case PubSubError::ItemForbidden: return "item-forbidden";
- case PubSubError::ItemRequired: return "item-required";
- case PubSubError::JIDRequired: return "jid-required";
- case PubSubError::MaximumItemsExceeded: return "max-items-exceeded";
- case PubSubError::MaximumNodesExceeded: return "max-nodes-exceeded";
- case PubSubError::NodeIDRequired: return "nodeid-required";
- case PubSubError::NotInRosterGroup: return "not-in-roster-group";
- case PubSubError::NotSubscribed: return "not-subscribed";
- case PubSubError::PayloadTooBig: return "payload-too-big";
- case PubSubError::PayloadRequired: return "payload-required";
- case PubSubError::PendingSubscription: return "pending-subscription";
- case PubSubError::PresenceSubscriptionRequired: return "presence-subscription-required";
- case PubSubError::SubscriptionIDRequired: return "subid-required";
- case PubSubError::TooManySubscriptions: return "too-many-subscriptions";
- case PubSubError::Unsupported: return "unsupported";
- case PubSubError::UnsupportedAccessModel: return "unsupported-access-model";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubError::UnknownType: assert(false); return "";
+ case PubSubError::ClosedNode: return "closed-node";
+ case PubSubError::ConfigurationRequired: return "configuration-required";
+ case PubSubError::InvalidJID: return "invalid-jid";
+ case PubSubError::InvalidOptions: return "invalid-options";
+ case PubSubError::InvalidPayload: return "invalid-payload";
+ case PubSubError::InvalidSubscriptionID: return "invalid-subid";
+ case PubSubError::ItemForbidden: return "item-forbidden";
+ case PubSubError::ItemRequired: return "item-required";
+ case PubSubError::JIDRequired: return "jid-required";
+ case PubSubError::MaximumItemsExceeded: return "max-items-exceeded";
+ case PubSubError::MaximumNodesExceeded: return "max-nodes-exceeded";
+ case PubSubError::NodeIDRequired: return "nodeid-required";
+ case PubSubError::NotInRosterGroup: return "not-in-roster-group";
+ case PubSubError::NotSubscribed: return "not-subscribed";
+ case PubSubError::PayloadTooBig: return "payload-too-big";
+ case PubSubError::PayloadRequired: return "payload-required";
+ case PubSubError::PendingSubscription: return "pending-subscription";
+ case PubSubError::PresenceSubscriptionRequired: return "presence-subscription-required";
+ case PubSubError::SubscriptionIDRequired: return "subid-required";
+ case PubSubError::TooManySubscriptions: return "too-many-subscriptions";
+ case PubSubError::Unsupported: return "unsupported";
+ case PubSubError::UnsupportedAccessModel: return "unsupported-access-model";
+ }
+ assert(false);
+ return "";
}
std::string PubSubErrorSerializer::serializeUnsupportedFeatureType(PubSubError::UnsupportedFeatureType value) {
- switch (value) {
- case PubSubError::UnknownUnsupportedFeatureType: assert(false); return "";
- case PubSubError::AccessAuthorize: return "access-authorize";
- case PubSubError::AccessOpen: return "access-open";
- case PubSubError::AccessPresence: return "access-presence";
- case PubSubError::AccessRoster: return "access-roster";
- case PubSubError::AccessWhitelist: return "access-whitelist";
- case PubSubError::AutoCreate: return "auto-create";
- case PubSubError::AutoSubscribe: return "auto-subscribe";
- case PubSubError::Collections: return "collections";
- case PubSubError::ConfigNode: return "config-node";
- case PubSubError::CreateAndConfigure: return "create-and-configure";
- case PubSubError::CreateNodes: return "create-nodes";
- case PubSubError::DeleteItems: return "delete-items";
- case PubSubError::DeleteNodes: return "delete-nodes";
- case PubSubError::FilteredNotifications: return "filtered-notifications";
- case PubSubError::GetPending: return "get-pending";
- case PubSubError::InstantNodes: return "instant-nodes";
- case PubSubError::ItemIDs: return "item-ids";
- case PubSubError::LastPublished: return "last-published";
- case PubSubError::LeasedSubscription: return "leased-subscription";
- case PubSubError::ManageSubscriptions: return "manage-subscriptions";
- case PubSubError::MemberAffiliation: return "member-affiliation";
- case PubSubError::MetaData: return "meta-data";
- case PubSubError::ModifyAffiliations: return "modify-affiliations";
- case PubSubError::MultiCollection: return "multi-collection";
- case PubSubError::MultiSubscribe: return "multi-subscribe";
- case PubSubError::OutcastAffiliation: return "outcast-affiliation";
- case PubSubError::PersistentItems: return "persistent-items";
- case PubSubError::PresenceNotifications: return "presence-notifications";
- case PubSubError::PresenceSubscribe: return "presence-subscribe";
- case PubSubError::Publish: return "publish";
- case PubSubError::PublishOptions: return "publish-options";
- case PubSubError::PublishOnlyAffiliation: return "publish-only-affiliation";
- case PubSubError::PublisherAffiliation: return "publisher-affiliation";
- case PubSubError::PurgeNodes: return "purge-nodes";
- case PubSubError::RetractItems: return "retract-items";
- case PubSubError::RetrieveAffiliations: return "retrieve-affiliations";
- case PubSubError::RetrieveDefault: return "retrieve-default";
- case PubSubError::RetrieveItems: return "retrieve-items";
- case PubSubError::RetrieveSubscriptions: return "retrieve-subscriptions";
- case PubSubError::Subscribe: return "subscribe";
- case PubSubError::SubscriptionOptions: return "subscription-options";
- case PubSubError::SubscriptionNotifications: return "subscription-notifications";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubError::UnknownUnsupportedFeatureType: assert(false); return "";
+ case PubSubError::AccessAuthorize: return "access-authorize";
+ case PubSubError::AccessOpen: return "access-open";
+ case PubSubError::AccessPresence: return "access-presence";
+ case PubSubError::AccessRoster: return "access-roster";
+ case PubSubError::AccessWhitelist: return "access-whitelist";
+ case PubSubError::AutoCreate: return "auto-create";
+ case PubSubError::AutoSubscribe: return "auto-subscribe";
+ case PubSubError::Collections: return "collections";
+ case PubSubError::ConfigNode: return "config-node";
+ case PubSubError::CreateAndConfigure: return "create-and-configure";
+ case PubSubError::CreateNodes: return "create-nodes";
+ case PubSubError::DeleteItems: return "delete-items";
+ case PubSubError::DeleteNodes: return "delete-nodes";
+ case PubSubError::FilteredNotifications: return "filtered-notifications";
+ case PubSubError::GetPending: return "get-pending";
+ case PubSubError::InstantNodes: return "instant-nodes";
+ case PubSubError::ItemIDs: return "item-ids";
+ case PubSubError::LastPublished: return "last-published";
+ case PubSubError::LeasedSubscription: return "leased-subscription";
+ case PubSubError::ManageSubscriptions: return "manage-subscriptions";
+ case PubSubError::MemberAffiliation: return "member-affiliation";
+ case PubSubError::MetaData: return "meta-data";
+ case PubSubError::ModifyAffiliations: return "modify-affiliations";
+ case PubSubError::MultiCollection: return "multi-collection";
+ case PubSubError::MultiSubscribe: return "multi-subscribe";
+ case PubSubError::OutcastAffiliation: return "outcast-affiliation";
+ case PubSubError::PersistentItems: return "persistent-items";
+ case PubSubError::PresenceNotifications: return "presence-notifications";
+ case PubSubError::PresenceSubscribe: return "presence-subscribe";
+ case PubSubError::Publish: return "publish";
+ case PubSubError::PublishOptions: return "publish-options";
+ case PubSubError::PublishOnlyAffiliation: return "publish-only-affiliation";
+ case PubSubError::PublisherAffiliation: return "publisher-affiliation";
+ case PubSubError::PurgeNodes: return "purge-nodes";
+ case PubSubError::RetractItems: return "retract-items";
+ case PubSubError::RetrieveAffiliations: return "retrieve-affiliations";
+ case PubSubError::RetrieveDefault: return "retrieve-default";
+ case PubSubError::RetrieveItems: return "retrieve-items";
+ case PubSubError::RetrieveSubscriptions: return "retrieve-subscriptions";
+ case PubSubError::Subscribe: return "subscribe";
+ case PubSubError::SubscriptionOptions: return "subscription-options";
+ case PubSubError::SubscriptionNotifications: return "subscription-notifications";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h
index 068c89e..b6750e9 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h
@@ -12,17 +12,17 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubErrorSerializer : public GenericPayloadSerializer<PubSubError> {
- public:
- PubSubErrorSerializer();
- virtual ~PubSubErrorSerializer();
+ class SWIFTEN_API PubSubErrorSerializer : public GenericPayloadSerializer<PubSubError> {
+ public:
+ PubSubErrorSerializer();
+ virtual ~PubSubErrorSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubError>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubError>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeType(PubSubError::Type);
- static std::string serializeUnsupportedFeatureType(PubSubError::UnsupportedFeatureType);
- };
+ private:
+ static std::string serializeType(PubSubError::Type);
+ static std::string serializeUnsupportedFeatureType(PubSubError::UnsupportedFeatureType);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp
index 4537d8c..c855977 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp
@@ -22,12 +22,12 @@ PubSubEventAssociateSerializer::~PubSubEventAssociateSerializer() {
}
std::string PubSubEventAssociateSerializer::serializePayload(boost::shared_ptr<PubSubEventAssociate> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("associate", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("associate", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
index 4ca1b06..03025fb 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventAssociateSerializer : public GenericPayloadSerializer<PubSubEventAssociate> {
- public:
- PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventAssociateSerializer();
+ class SWIFTEN_API PubSubEventAssociateSerializer : public GenericPayloadSerializer<PubSubEventAssociate> {
+ public:
+ PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventAssociateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventAssociate>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventAssociate>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
index 96462d3..df255d2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
@@ -24,16 +24,16 @@ PubSubEventCollectionSerializer::~PubSubEventCollectionSerializer() {
}
std::string PubSubEventCollectionSerializer::serializePayload(boost::shared_ptr<PubSubEventCollection> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("collection", "http://jabber.org/protocol/pubsub#event");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventDisassociateSerializer(serializers).serialize(payload->getDisassociate())));
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventAssociateSerializer(serializers).serialize(payload->getAssociate())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("collection", "http://jabber.org/protocol/pubsub#event");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventDisassociateSerializer(serializers).serialize(payload->getDisassociate())));
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventAssociateSerializer(serializers).serialize(payload->getAssociate())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h
index 8e515a6..6e6817d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventCollectionSerializer : public GenericPayloadSerializer<PubSubEventCollection> {
- public:
- PubSubEventCollectionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventCollectionSerializer();
+ class SWIFTEN_API PubSubEventCollectionSerializer : public GenericPayloadSerializer<PubSubEventCollection> {
+ public:
+ PubSubEventCollectionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventCollectionSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventCollection>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventCollection>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp
index 68b498f..3e2d18b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp
@@ -23,13 +23,13 @@ PubSubEventConfigurationSerializer::~PubSubEventConfigurationSerializer() {
}
std::string PubSubEventConfigurationSerializer::serializePayload(boost::shared_ptr<PubSubEventConfiguration> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("configuration", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("configuration", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h
index 872fbab..6309e04 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventConfigurationSerializer : public GenericPayloadSerializer<PubSubEventConfiguration> {
- public:
- PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventConfigurationSerializer();
+ class SWIFTEN_API PubSubEventConfigurationSerializer : public GenericPayloadSerializer<PubSubEventConfiguration> {
+ public:
+ PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventConfigurationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventConfiguration>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventConfiguration>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
index 5d9a6b4..4dcd734 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
@@ -23,13 +23,13 @@ PubSubEventDeleteSerializer::~PubSubEventDeleteSerializer() {
}
std::string PubSubEventDeleteSerializer::serializePayload(boost::shared_ptr<PubSubEventDelete> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("delete", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventRedirectSerializer(serializers).serialize(payload->getRedirects())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delete", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventRedirectSerializer(serializers).serialize(payload->getRedirects())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h
index a4746fc..6d937aa 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventDeleteSerializer : public GenericPayloadSerializer<PubSubEventDelete> {
- public:
- PubSubEventDeleteSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventDeleteSerializer();
+ class SWIFTEN_API PubSubEventDeleteSerializer : public GenericPayloadSerializer<PubSubEventDelete> {
+ public:
+ PubSubEventDeleteSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventDeleteSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventDelete>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventDelete>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp
index b3dc1da..0818dee 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp
@@ -22,12 +22,12 @@ PubSubEventDisassociateSerializer::~PubSubEventDisassociateSerializer() {
}
std::string PubSubEventDisassociateSerializer::serializePayload(boost::shared_ptr<PubSubEventDisassociate> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("disassociate", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("disassociate", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
index ddebdd2..9313ab2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventDisassociateSerializer : public GenericPayloadSerializer<PubSubEventDisassociate> {
- public:
- PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventDisassociateSerializer();
+ class SWIFTEN_API PubSubEventDisassociateSerializer : public GenericPayloadSerializer<PubSubEventDisassociate> {
+ public:
+ PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventDisassociateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventDisassociate>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventDisassociate>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
index 01a58e3..4bc8815 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
@@ -23,23 +23,23 @@ PubSubEventItemSerializer::~PubSubEventItemSerializer() {
}
std::string PubSubEventItemSerializer::serializePayload(boost::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(boost::shared_ptr<Payload> item, payload->getData()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
- }
- if (payload->getID()) {
- element.setAttribute("id", *payload->getID());
- }
- return element.serialize();
+ 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(boost::shared_ptr<Payload> item, payload->getData()) {
+ element.addNode(boost::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/PubSubEventItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
index bd164fe..6666c6b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventItemSerializer : public GenericPayloadSerializer<PubSubEventItem> {
- public:
- PubSubEventItemSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventItemSerializer();
+ class SWIFTEN_API PubSubEventItemSerializer : public GenericPayloadSerializer<PubSubEventItem> {
+ public:
+ PubSubEventItemSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventItemSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventItem>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventItem>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
index 7faac5f..7128314 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
@@ -25,18 +25,18 @@ PubSubEventItemsSerializer::~PubSubEventItemsSerializer() {
}
std::string PubSubEventItemsSerializer::serializePayload(boost::shared_ptr<PubSubEventItems> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("items", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- foreach(boost::shared_ptr<PubSubEventItem> item, payload->getItems()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventItemSerializer(serializers).serialize(item)));
- }
- foreach(boost::shared_ptr<PubSubEventRetract> item, payload->getRetracts()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventRetractSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("items", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ foreach(boost::shared_ptr<PubSubEventItem> item, payload->getItems()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventItemSerializer(serializers).serialize(item)));
+ }
+ foreach(boost::shared_ptr<PubSubEventRetract> item, payload->getRetracts()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubEventRetractSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
index a1f4633..d174f30 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventItemsSerializer : public GenericPayloadSerializer<PubSubEventItems> {
- public:
- PubSubEventItemsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventItemsSerializer();
+ class SWIFTEN_API PubSubEventItemsSerializer : public GenericPayloadSerializer<PubSubEventItems> {
+ public:
+ PubSubEventItemsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventItemsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventItems>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventItems>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp
index 9541ece..86c7635 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp
@@ -22,12 +22,12 @@ PubSubEventPurgeSerializer::~PubSubEventPurgeSerializer() {
}
std::string PubSubEventPurgeSerializer::serializePayload(boost::shared_ptr<PubSubEventPurge> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("purge", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("purge", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
index 47648d4..c80c703 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventPurgeSerializer : public GenericPayloadSerializer<PubSubEventPurge> {
- public:
- PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventPurgeSerializer();
+ class SWIFTEN_API PubSubEventPurgeSerializer : public GenericPayloadSerializer<PubSubEventPurge> {
+ public:
+ PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventPurgeSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventPurge>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventPurge>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
index 80b4d94..a7fcd20 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
@@ -22,12 +22,12 @@ PubSubEventRedirectSerializer::~PubSubEventRedirectSerializer() {
}
std::string PubSubEventRedirectSerializer::serializePayload(boost::shared_ptr<PubSubEventRedirect> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("redirect", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("uri", payload->getURI());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("redirect", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("uri", payload->getURI());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
index 79d4f56..fe0f16e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventRedirectSerializer : public GenericPayloadSerializer<PubSubEventRedirect> {
- public:
- PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventRedirectSerializer();
+ class SWIFTEN_API PubSubEventRedirectSerializer : public GenericPayloadSerializer<PubSubEventRedirect> {
+ public:
+ PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventRedirectSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventRedirect>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventRedirect>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
index 197c087..6a132cc 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
@@ -22,12 +22,12 @@ PubSubEventRetractSerializer::~PubSubEventRetractSerializer() {
}
std::string PubSubEventRetractSerializer::serializePayload(boost::shared_ptr<PubSubEventRetract> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("retract", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("id", payload->getID());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("retract", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("id", payload->getID());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
index a7fd987..2c393c2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventRetractSerializer : public GenericPayloadSerializer<PubSubEventRetract> {
- public:
- PubSubEventRetractSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventRetractSerializer();
+ class SWIFTEN_API PubSubEventRetractSerializer : public GenericPayloadSerializer<PubSubEventRetract> {
+ public:
+ PubSubEventRetractSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventRetractSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventRetract>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventRetract>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
index 8a7b881..7305d29 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
@@ -23,29 +23,29 @@
using namespace Swift;
PubSubEventSerializer::PubSubEventSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
- pubsubSerializers.push_back(boost::make_shared<PubSubEventSubscriptionSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubEventPurgeSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubEventCollectionSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubEventDeleteSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubEventItemsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubEventConfigurationSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventSubscriptionSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventPurgeSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventCollectionSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventDeleteSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventItemsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubEventConfigurationSerializer>(serializers));
}
PubSubEventSerializer::~PubSubEventSerializer() {
}
std::string PubSubEventSerializer::serializePayload(boost::shared_ptr<PubSubEvent> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("event", "http://jabber.org/protocol/pubsub#event");
- boost::shared_ptr<PubSubEventPayload> p = payload->getPayload();
- foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
- if (serializer->canSerialize(p)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
- }
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("event", "http://jabber.org/protocol/pubsub#event");
+ boost::shared_ptr<PubSubEventPayload> p = payload->getPayload();
+ foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
index 9dae673..2b50e95 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
@@ -16,20 +16,20 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventSerializer : public GenericPayloadSerializer<PubSubEvent> {
- public:
- PubSubEventSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventSerializer();
+ class SWIFTEN_API PubSubEventSerializer : public GenericPayloadSerializer<PubSubEvent> {
+ public:
+ PubSubEventSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEvent>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEvent>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
index a7240c8..322b482 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
@@ -22,27 +22,27 @@ PubSubEventSubscriptionSerializer::~PubSubEventSubscriptionSerializer() {
}
std::string PubSubEventSubscriptionSerializer::serializePayload(boost::shared_ptr<PubSubEventSubscription> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscription", "http://jabber.org/protocol/pubsub#event");
- element.setAttribute("node", payload->getNode());
- element.setAttribute("jid", payload->getJID());
- element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
- if (payload->getSubscriptionID()) {
- element.setAttribute("subid", *payload->getSubscriptionID());
- }
- element.setAttribute("expiry", dateTimeToString(payload->getExpiry()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscription", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ element.setAttribute("jid", payload->getJID());
+ element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
+ if (payload->getSubscriptionID()) {
+ element.setAttribute("subid", *payload->getSubscriptionID());
+ }
+ element.setAttribute("expiry", dateTimeToString(payload->getExpiry()));
+ return element.serialize();
}
std::string PubSubEventSubscriptionSerializer::serializeSubscriptionType(PubSubEventSubscription::SubscriptionType value) {
- switch (value) {
- case PubSubEventSubscription::None: return "none";
- case PubSubEventSubscription::Pending: return "pending";
- case PubSubEventSubscription::Subscribed: return "subscribed";
- case PubSubEventSubscription::Unconfigured: return "unconfigured";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubEventSubscription::None: return "none";
+ case PubSubEventSubscription::Pending: return "pending";
+ case PubSubEventSubscription::Subscribed: return "subscribed";
+ case PubSubEventSubscription::Unconfigured: return "unconfigured";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h
index 1329ca6..74e3062 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubEventSubscriptionSerializer : public GenericPayloadSerializer<PubSubEventSubscription> {
- public:
- PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventSubscriptionSerializer();
+ class SWIFTEN_API PubSubEventSubscriptionSerializer : public GenericPayloadSerializer<PubSubEventSubscription> {
+ public:
+ PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventSubscriptionSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventSubscription>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubEventSubscription>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeSubscriptionType(PubSubEventSubscription::SubscriptionType);
+ private:
+ static std::string serializeSubscriptionType(PubSubEventSubscription::SubscriptionType);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
index 93fa8e2..e32f17a 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
@@ -23,17 +23,17 @@ PubSubItemSerializer::~PubSubItemSerializer() {
}
std::string PubSubItemSerializer::serializePayload(boost::shared_ptr<PubSubItem> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("item", "http://jabber.org/protocol/pubsub");
- foreach(boost::shared_ptr<Payload> item, payload->getData()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
- }
- if (!payload->getID().empty()) {
- element.setAttribute("id", payload->getID());
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("item", "http://jabber.org/protocol/pubsub");
+ foreach(boost::shared_ptr<Payload> item, payload->getData()) {
+ element.addNode(boost::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/PubSubItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
index 4f9a97e..e6dbb83 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubItemSerializer : public GenericPayloadSerializer<PubSubItem> {
- public:
- PubSubItemSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubItemSerializer();
+ class SWIFTEN_API PubSubItemSerializer : public GenericPayloadSerializer<PubSubItem> {
+ public:
+ PubSubItemSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubItemSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubItem>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubItem>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
index f09fba1..75d32f5 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
@@ -26,24 +26,24 @@ PubSubItemsSerializer::~PubSubItemsSerializer() {
}
std::string PubSubItemsSerializer::serializePayload(boost::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(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
- element.addNode(boost::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();
+ 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(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
+ element.addNode(boost::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/PubSubItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
index bd608d7..28b923f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubItemsSerializer : public GenericPayloadSerializer<PubSubItems> {
- public:
- PubSubItemsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubItemsSerializer();
+ class SWIFTEN_API PubSubItemsSerializer : public GenericPayloadSerializer<PubSubItems> {
+ public:
+ PubSubItemsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubItemsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubItems>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubItems>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp
index 4117041..09f72ef 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp
@@ -23,17 +23,17 @@ PubSubOptionsSerializer::~PubSubOptionsSerializer() {
}
std::string PubSubOptionsSerializer::serializePayload(boost::shared_ptr<PubSubOptions> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("options", "http://jabber.org/protocol/pubsub");
- element.setAttribute("node", payload->getNode());
- element.setAttribute("jid", payload->getJID());
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
- if (payload->getSubscriptionID()) {
- element.setAttribute("subid", *payload->getSubscriptionID());
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("options", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ element.setAttribute("jid", payload->getJID());
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
+ if (payload->getSubscriptionID()) {
+ element.setAttribute("subid", *payload->getSubscriptionID());
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h
index 44a0f17..91dabab 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOptionsSerializer : public GenericPayloadSerializer<PubSubOptions> {
- public:
- PubSubOptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOptionsSerializer();
+ class SWIFTEN_API PubSubOptionsSerializer : public GenericPayloadSerializer<PubSubOptions> {
+ public:
+ PubSubOptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOptionsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOptions>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOptions>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
index efc9eef..82980ff 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
@@ -22,24 +22,24 @@ PubSubOwnerAffiliationSerializer::~PubSubOwnerAffiliationSerializer() {
}
std::string PubSubOwnerAffiliationSerializer::serializePayload(boost::shared_ptr<PubSubOwnerAffiliation> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("affiliation", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("jid", payload->getJID());
- element.setAttribute("affiliation", serializeType(payload->getType()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliation", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("jid", payload->getJID());
+ element.setAttribute("affiliation", serializeType(payload->getType()));
+ return element.serialize();
}
std::string PubSubOwnerAffiliationSerializer::serializeType(PubSubOwnerAffiliation::Type value) {
- switch (value) {
- case PubSubOwnerAffiliation::None: return "none";
- case PubSubOwnerAffiliation::Member: return "member";
- case PubSubOwnerAffiliation::Outcast: return "outcast";
- case PubSubOwnerAffiliation::Owner: return "owner";
- case PubSubOwnerAffiliation::Publisher: return "publisher";
- case PubSubOwnerAffiliation::PublishOnly: return "publish-only";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubOwnerAffiliation::None: return "none";
+ case PubSubOwnerAffiliation::Member: return "member";
+ case PubSubOwnerAffiliation::Outcast: return "outcast";
+ case PubSubOwnerAffiliation::Owner: return "owner";
+ case PubSubOwnerAffiliation::Publisher: return "publisher";
+ case PubSubOwnerAffiliation::PublishOnly: return "publish-only";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h
index 9883ab9..ef0decf 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerAffiliationSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliation> {
- public:
- PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerAffiliationSerializer();
+ class SWIFTEN_API PubSubOwnerAffiliationSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliation> {
+ public:
+ PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerAffiliationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerAffiliation>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerAffiliation>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeType(PubSubOwnerAffiliation::Type);
+ private:
+ static std::string serializeType(PubSubOwnerAffiliation::Type);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
index 5e80747..12873e5 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
@@ -24,15 +24,15 @@ PubSubOwnerAffiliationsSerializer::~PubSubOwnerAffiliationsSerializer() {
}
std::string PubSubOwnerAffiliationsSerializer::serializePayload(boost::shared_ptr<PubSubOwnerAffiliations> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("affiliations", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("node", payload->getNode());
- foreach(boost::shared_ptr<PubSubOwnerAffiliation> item, payload->getAffiliations()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerAffiliationSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliations", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ foreach(boost::shared_ptr<PubSubOwnerAffiliation> item, payload->getAffiliations()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerAffiliationSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
index a2ee181..70ba66f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerAffiliationsSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliations> {
- public:
- PubSubOwnerAffiliationsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerAffiliationsSerializer();
+ class SWIFTEN_API PubSubOwnerAffiliationsSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliations> {
+ public:
+ PubSubOwnerAffiliationsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerAffiliationsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerAffiliations>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerAffiliations>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp
index d493e63..94e6860 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp
@@ -23,15 +23,15 @@ PubSubOwnerConfigureSerializer::~PubSubOwnerConfigureSerializer() {
}
std::string PubSubOwnerConfigureSerializer::serializePayload(boost::shared_ptr<PubSubOwnerConfigure> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("configure", "http://jabber.org/protocol/pubsub#owner");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("configure", "http://jabber.org/protocol/pubsub#owner");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h
index 8881ea5..be75a00 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerConfigureSerializer : public GenericPayloadSerializer<PubSubOwnerConfigure> {
- public:
- PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerConfigureSerializer();
+ class SWIFTEN_API PubSubOwnerConfigureSerializer : public GenericPayloadSerializer<PubSubOwnerConfigure> {
+ public:
+ PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerConfigureSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerConfigure>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerConfigure>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
index 934f877..4b91a81 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
@@ -23,12 +23,12 @@ PubSubOwnerDefaultSerializer::~PubSubOwnerDefaultSerializer() {
}
std::string PubSubOwnerDefaultSerializer::serializePayload(boost::shared_ptr<PubSubOwnerDefault> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("default", "http://jabber.org/protocol/pubsub#owner");
- element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("default", "http://jabber.org/protocol/pubsub#owner");
+ element.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h
index ab8487a..9d2916f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerDefaultSerializer : public GenericPayloadSerializer<PubSubOwnerDefault> {
- public:
- PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerDefaultSerializer();
+ class SWIFTEN_API PubSubOwnerDefaultSerializer : public GenericPayloadSerializer<PubSubOwnerDefault> {
+ public:
+ PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerDefaultSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerDefault>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerDefault>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
index 1594643..fbf9a24 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
@@ -23,13 +23,13 @@ PubSubOwnerDeleteSerializer::~PubSubOwnerDeleteSerializer() {
}
std::string PubSubOwnerDeleteSerializer::serializePayload(boost::shared_ptr<PubSubOwnerDelete> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("delete", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("node", payload->getNode());
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerRedirectSerializer(serializers).serialize(payload->getRedirect())));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delete", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerRedirectSerializer(serializers).serialize(payload->getRedirect())));
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h
index 28bb090..3a96e80 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerDeleteSerializer : public GenericPayloadSerializer<PubSubOwnerDelete> {
- public:
- PubSubOwnerDeleteSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerDeleteSerializer();
+ class SWIFTEN_API PubSubOwnerDeleteSerializer : public GenericPayloadSerializer<PubSubOwnerDelete> {
+ public:
+ PubSubOwnerDeleteSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerDeleteSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerDelete>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerDelete>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
index 39161f0..25b38d0 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
@@ -23,29 +23,29 @@
using namespace Swift;
PubSubOwnerPubSubSerializer::PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerConfigureSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerSubscriptionsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerDefaultSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerPurgeSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerAffiliationsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOwnerDeleteSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerConfigureSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerSubscriptionsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerDefaultSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerPurgeSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerAffiliationsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOwnerDeleteSerializer>(serializers));
}
PubSubOwnerPubSubSerializer::~PubSubOwnerPubSubSerializer() {
}
std::string PubSubOwnerPubSubSerializer::serializePayload(boost::shared_ptr<PubSubOwnerPubSub> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("pubsub", "http://jabber.org/protocol/pubsub#owner");
- boost::shared_ptr<PubSubOwnerPayload> p = payload->getPayload();
- foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
- if (serializer->canSerialize(p)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
- }
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("pubsub", "http://jabber.org/protocol/pubsub#owner");
+ boost::shared_ptr<PubSubOwnerPayload> p = payload->getPayload();
+ foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
index 398c084..2dd8400 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
@@ -16,20 +16,20 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerPubSubSerializer : public GenericPayloadSerializer<PubSubOwnerPubSub> {
- public:
- PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerPubSubSerializer();
+ class SWIFTEN_API PubSubOwnerPubSubSerializer : public GenericPayloadSerializer<PubSubOwnerPubSub> {
+ public:
+ PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerPubSubSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPubSub>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPubSub>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
index 9d2f0c1..f934c4e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
@@ -22,12 +22,12 @@ PubSubOwnerPurgeSerializer::~PubSubOwnerPurgeSerializer() {
}
std::string PubSubOwnerPurgeSerializer::serializePayload(boost::shared_ptr<PubSubOwnerPurge> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("purge", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("node", payload->getNode());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("purge", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
index 3ee1460..64be235 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerPurgeSerializer : public GenericPayloadSerializer<PubSubOwnerPurge> {
- public:
- PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerPurgeSerializer();
+ class SWIFTEN_API PubSubOwnerPurgeSerializer : public GenericPayloadSerializer<PubSubOwnerPurge> {
+ public:
+ PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerPurgeSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPurge>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPurge>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
index 7628379..f933a06 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
@@ -22,12 +22,12 @@ PubSubOwnerRedirectSerializer::~PubSubOwnerRedirectSerializer() {
}
std::string PubSubOwnerRedirectSerializer::serializePayload(boost::shared_ptr<PubSubOwnerRedirect> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("redirect", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("uri", payload->getURI());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("redirect", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("uri", payload->getURI());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
index 71d6f48..b183f46 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerRedirectSerializer : public GenericPayloadSerializer<PubSubOwnerRedirect> {
- public:
- PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerRedirectSerializer();
+ class SWIFTEN_API PubSubOwnerRedirectSerializer : public GenericPayloadSerializer<PubSubOwnerRedirect> {
+ public:
+ PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerRedirectSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerRedirect>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerRedirect>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
index a639716..923c160 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
@@ -22,22 +22,22 @@ PubSubOwnerSubscriptionSerializer::~PubSubOwnerSubscriptionSerializer() {
}
std::string PubSubOwnerSubscriptionSerializer::serializePayload(boost::shared_ptr<PubSubOwnerSubscription> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscription", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("jid", payload->getJID());
- element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscription", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("jid", payload->getJID());
+ element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
+ return element.serialize();
}
std::string PubSubOwnerSubscriptionSerializer::serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType value) {
- switch (value) {
- case PubSubOwnerSubscription::None: return "none";
- case PubSubOwnerSubscription::Pending: return "pending";
- case PubSubOwnerSubscription::Subscribed: return "subscribed";
- case PubSubOwnerSubscription::Unconfigured: return "unconfigured";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubOwnerSubscription::None: return "none";
+ case PubSubOwnerSubscription::Pending: return "pending";
+ case PubSubOwnerSubscription::Subscribed: return "subscribed";
+ case PubSubOwnerSubscription::Unconfigured: return "unconfigured";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h
index 2f02be4..1bba67f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerSubscriptionSerializer : public GenericPayloadSerializer<PubSubOwnerSubscription> {
- public:
- PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerSubscriptionSerializer();
+ class SWIFTEN_API PubSubOwnerSubscriptionSerializer : public GenericPayloadSerializer<PubSubOwnerSubscription> {
+ public:
+ PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerSubscriptionSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerSubscription>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerSubscription>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType);
+ private:
+ static std::string serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
index 3b49329..088f6c2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
@@ -24,15 +24,15 @@ PubSubOwnerSubscriptionsSerializer::~PubSubOwnerSubscriptionsSerializer() {
}
std::string PubSubOwnerSubscriptionsSerializer::serializePayload(boost::shared_ptr<PubSubOwnerSubscriptions> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub#owner");
- element.setAttribute("node", payload->getNode());
- foreach(boost::shared_ptr<PubSubOwnerSubscription> item, payload->getSubscriptions()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerSubscriptionSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ foreach(boost::shared_ptr<PubSubOwnerSubscription> item, payload->getSubscriptions()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubOwnerSubscriptionSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
index ec011f8..70ea7b2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubOwnerSubscriptionsSerializer : public GenericPayloadSerializer<PubSubOwnerSubscriptions> {
- public:
- PubSubOwnerSubscriptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerSubscriptionsSerializer();
+ class SWIFTEN_API PubSubOwnerSubscriptionsSerializer : public GenericPayloadSerializer<PubSubOwnerSubscriptions> {
+ public:
+ PubSubOwnerSubscriptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerSubscriptionsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerSubscriptions>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerSubscriptions>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
index f9044fd..efae018 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
@@ -24,15 +24,15 @@ PubSubPublishSerializer::~PubSubPublishSerializer() {
}
std::string PubSubPublishSerializer::serializePayload(boost::shared_ptr<PubSubPublish> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("publish", "http://jabber.org/protocol/pubsub");
- element.setAttribute("node", payload->getNode());
- foreach(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("publish", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ foreach(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
index f834484..c576225 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubPublishSerializer : public GenericPayloadSerializer<PubSubPublish> {
- public:
- PubSubPublishSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubPublishSerializer();
+ class SWIFTEN_API PubSubPublishSerializer : public GenericPayloadSerializer<PubSubPublish> {
+ public:
+ PubSubPublishSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubPublishSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubPublish>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubPublish>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
index 2d5af7a..9a84959 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
@@ -24,16 +24,16 @@ PubSubRetractSerializer::~PubSubRetractSerializer() {
}
std::string PubSubRetractSerializer::serializePayload(boost::shared_ptr<PubSubRetract> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("retract", "http://jabber.org/protocol/pubsub");
- element.setAttribute("node", payload->getNode());
- foreach(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
- }
- element.setAttribute("notify", payload->isNotify() ? "true" : "false");
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("retract", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ foreach(boost::shared_ptr<PubSubItem> item, payload->getItems()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
+ }
+ element.setAttribute("notify", payload->isNotify() ? "true" : "false");
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
index 6f0d041..60acb6e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubRetractSerializer : public GenericPayloadSerializer<PubSubRetract> {
- public:
- PubSubRetractSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubRetractSerializer();
+ class SWIFTEN_API PubSubRetractSerializer : public GenericPayloadSerializer<PubSubRetract> {
+ public:
+ PubSubRetractSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubRetractSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubRetract>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubRetract>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
index 2e75ecb..9562edb 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
@@ -30,40 +30,40 @@
using namespace Swift;
PubSubSerializer::PubSubSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
- pubsubSerializers.push_back(boost::make_shared<PubSubItemsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubCreateSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubPublishSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubOptionsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubAffiliationsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubRetractSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubDefaultSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubSubscriptionsSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubSubscribeSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubUnsubscribeSerializer>(serializers));
- pubsubSerializers.push_back(boost::make_shared<PubSubSubscriptionSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubItemsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubCreateSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubPublishSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubOptionsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubAffiliationsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubRetractSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubDefaultSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubSubscriptionsSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubSubscribeSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubUnsubscribeSerializer>(serializers));
+ pubsubSerializers.push_back(boost::make_shared<PubSubSubscriptionSerializer>(serializers));
}
PubSubSerializer::~PubSubSerializer() {
}
std::string PubSubSerializer::serializePayload(boost::shared_ptr<PubSub> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("pubsub", "http://jabber.org/protocol/pubsub");
- boost::shared_ptr<PubSubPayload> p = payload->getPayload();
- foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
- if (serializer->canSerialize(p)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
- if (boost::shared_ptr<PubSubCreate> create = boost::dynamic_pointer_cast<PubSubCreate>(p)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(boost::make_shared<PubSubConfigureSerializer>(serializers)->serialize(create->getConfigure())));
- }
- if (boost::shared_ptr<PubSubSubscribe> subscribe = boost::dynamic_pointer_cast<PubSubSubscribe>(p)) {
- element.addNode(boost::make_shared<XMLRawTextNode>(boost::make_shared<PubSubConfigureSerializer>(serializers)->serialize(subscribe->getOptions())));
- }
- }
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("pubsub", "http://jabber.org/protocol/pubsub");
+ boost::shared_ptr<PubSubPayload> p = payload->getPayload();
+ foreach(boost::shared_ptr<PayloadSerializer> serializer, pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ if (boost::shared_ptr<PubSubCreate> create = boost::dynamic_pointer_cast<PubSubCreate>(p)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(boost::make_shared<PubSubConfigureSerializer>(serializers)->serialize(create->getConfigure())));
+ }
+ if (boost::shared_ptr<PubSubSubscribe> subscribe = boost::dynamic_pointer_cast<PubSubSubscribe>(p)) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(boost::make_shared<PubSubConfigureSerializer>(serializers)->serialize(subscribe->getOptions())));
+ }
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
index e257e26..0721d13 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
@@ -14,17 +14,17 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubSerializer : public GenericPayloadSerializer<PubSub> {
- public:
- PubSubSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSerializer();
+ class SWIFTEN_API PubSubSerializer : public GenericPayloadSerializer<PubSub> {
+ public:
+ PubSubSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSub>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSub>) const SWIFTEN_OVERRIDE;
- private:
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- PayloadSerializerCollection* serializers;
- };
+ private:
+ std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
index 692158f..2e3987e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
@@ -22,12 +22,12 @@ PubSubSubscribeOptionsSerializer::~PubSubSubscribeOptionsSerializer() {
}
std::string PubSubSubscribeOptionsSerializer::serializePayload(boost::shared_ptr<PubSubSubscribeOptions> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscribe-options", "http://jabber.org/protocol/pubsub");
- element.addNode(payload->isRequired() ? boost::make_shared<XMLElement>("required", "") : boost::shared_ptr<XMLElement>());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscribe-options", "http://jabber.org/protocol/pubsub");
+ element.addNode(payload->isRequired() ? boost::make_shared<XMLElement>("required", "") : boost::shared_ptr<XMLElement>());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
index 399047d..663d91b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubSubscribeOptionsSerializer : public GenericPayloadSerializer<PubSubSubscribeOptions> {
- public:
- PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscribeOptionsSerializer();
+ class SWIFTEN_API PubSubSubscribeOptionsSerializer : public GenericPayloadSerializer<PubSubSubscribeOptions> {
+ public:
+ PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscribeOptionsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribeOptions>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribeOptions>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
index f761531..dcc7ab1 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
@@ -22,15 +22,15 @@ PubSubSubscribeSerializer::~PubSubSubscribeSerializer() {
}
std::string PubSubSubscribeSerializer::serializePayload(boost::shared_ptr<PubSubSubscribe> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscribe", "http://jabber.org/protocol/pubsub");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- element.setAttribute("jid", payload->getJID());
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscribe", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ element.setAttribute("jid", payload->getJID());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
index 8618e27..c655464 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubSubscribeSerializer : public GenericPayloadSerializer<PubSubSubscribe> {
- public:
- PubSubSubscribeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscribeSerializer();
+ class SWIFTEN_API PubSubSubscribeSerializer : public GenericPayloadSerializer<PubSubSubscribe> {
+ public:
+ PubSubSubscribeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscribeSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribe>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribe>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
index a856f75..cadfce9 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
@@ -23,29 +23,29 @@ PubSubSubscriptionSerializer::~PubSubSubscriptionSerializer() {
}
std::string PubSubSubscriptionSerializer::serializePayload(boost::shared_ptr<PubSubSubscription> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("subscription", "http://jabber.org/protocol/pubsub");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- if (payload->getSubscriptionID()) {
- element.setAttribute("subid", *payload->getSubscriptionID());
- }
- element.setAttribute("jid", payload->getJID());
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubSubscribeOptionsSerializer(serializers).serialize(payload->getOptions())));
- element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscription", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ if (payload->getSubscriptionID()) {
+ element.setAttribute("subid", *payload->getSubscriptionID());
+ }
+ element.setAttribute("jid", payload->getJID());
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubSubscribeOptionsSerializer(serializers).serialize(payload->getOptions())));
+ element.setAttribute("subscription", serializeSubscriptionType(payload->getSubscription()));
+ return element.serialize();
}
std::string PubSubSubscriptionSerializer::serializeSubscriptionType(PubSubSubscription::SubscriptionType value) {
- switch (value) {
- case PubSubSubscription::None: return "none";
- case PubSubSubscription::Pending: return "pending";
- case PubSubSubscription::Subscribed: return "subscribed";
- case PubSubSubscription::Unconfigured: return "unconfigured";
- }
- assert(false);
- return "";
+ switch (value) {
+ case PubSubSubscription::None: return "none";
+ case PubSubSubscription::Pending: return "pending";
+ case PubSubSubscription::Subscribed: return "subscribed";
+ case PubSubSubscription::Unconfigured: return "unconfigured";
+ }
+ assert(false);
+ return "";
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h
index 1b061ee..7d96a06 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubSubscriptionSerializer : public GenericPayloadSerializer<PubSubSubscription> {
- public:
- PubSubSubscriptionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscriptionSerializer();
+ class SWIFTEN_API PubSubSubscriptionSerializer : public GenericPayloadSerializer<PubSubSubscription> {
+ public:
+ PubSubSubscriptionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscriptionSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscription>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubSubscription>) const SWIFTEN_OVERRIDE;
- private:
- static std::string serializeSubscriptionType(PubSubSubscription::SubscriptionType);
+ private:
+ static std::string serializeSubscriptionType(PubSubSubscription::SubscriptionType);
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
index 5e8c337..3347187 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
@@ -24,17 +24,17 @@ PubSubSubscriptionsSerializer::~PubSubSubscriptionsSerializer() {
}
std::string PubSubSubscriptionsSerializer::serializePayload(boost::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(boost::shared_ptr<PubSubSubscription> item, payload->getSubscriptions()) {
- element.addNode(boost::make_shared<XMLRawTextNode>(PubSubSubscriptionSerializer(serializers).serialize(item)));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ foreach(boost::shared_ptr<PubSubSubscription> item, payload->getSubscriptions()) {
+ element.addNode(boost::make_shared<XMLRawTextNode>(PubSubSubscriptionSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
index 82245fb..cc64483 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubSubscriptionsSerializer : public GenericPayloadSerializer<PubSubSubscriptions> {
- public:
- PubSubSubscriptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscriptionsSerializer();
+ class SWIFTEN_API PubSubSubscriptionsSerializer : public GenericPayloadSerializer<PubSubSubscriptions> {
+ public:
+ PubSubSubscriptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscriptionsSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscriptions>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubSubscriptions>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp
index 8a71583..e9a16d6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp
@@ -22,18 +22,18 @@ PubSubUnsubscribeSerializer::~PubSubUnsubscribeSerializer() {
}
std::string PubSubUnsubscribeSerializer::serializePayload(boost::shared_ptr<PubSubUnsubscribe> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("unsubscribe", "http://jabber.org/protocol/pubsub");
- if (payload->getNode()) {
- element.setAttribute("node", *payload->getNode());
- }
- element.setAttribute("jid", payload->getJID());
- if (payload->getSubscriptionID()) {
- element.setAttribute("subid", *payload->getSubscriptionID());
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("unsubscribe", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ element.setAttribute("jid", payload->getJID());
+ if (payload->getSubscriptionID()) {
+ element.setAttribute("subid", *payload->getSubscriptionID());
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
index 3341422..ab9a053 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API PubSubUnsubscribeSerializer : public GenericPayloadSerializer<PubSubUnsubscribe> {
- public:
- PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubUnsubscribeSerializer();
+ class SWIFTEN_API PubSubUnsubscribeSerializer : public GenericPayloadSerializer<PubSubUnsubscribe> {
+ public:
+ PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubUnsubscribeSerializer();
- virtual std::string serializePayload(boost::shared_ptr<PubSubUnsubscribe>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<PubSubUnsubscribe>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
index f6aaec9..21ca59f 100644
--- a/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
@@ -11,12 +11,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API RawXMLPayloadSerializer : public GenericPayloadSerializer<RawXMLPayload> {
- public:
- RawXMLPayloadSerializer() : GenericPayloadSerializer<RawXMLPayload>() {}
+ class SWIFTEN_API RawXMLPayloadSerializer : public GenericPayloadSerializer<RawXMLPayload> {
+ public:
+ RawXMLPayloadSerializer() : GenericPayloadSerializer<RawXMLPayload>() {}
- virtual std::string serializePayload(boost::shared_ptr<RawXMLPayload> p) const {
- return p->getRawXML();
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<RawXMLPayload> p) const {
+ return p->getRawXML();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h b/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
index b61547e..a16f52b 100644
--- a/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
@@ -18,12 +18,12 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class SWIFTEN_API ReplaceSerializer : public GenericPayloadSerializer<Replace> {
- public:
- ReplaceSerializer() : GenericPayloadSerializer<Replace>() {}
+ class SWIFTEN_API ReplaceSerializer : public GenericPayloadSerializer<Replace> {
+ public:
+ ReplaceSerializer() : GenericPayloadSerializer<Replace>() {}
- virtual std::string serializePayload(boost::shared_ptr<Replace> replace) const {
- return "<replace id = '" + replace->getID() + "' xmlns='urn:xmpp:message-correct:0'/>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Replace> replace) const {
+ return "<replace id = '" + replace->getID() + "' xmlns='urn:xmpp:message-correct:0'/>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
index 87614cd..c737102 100644
--- a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
@@ -18,18 +18,18 @@ ResourceBindSerializer::ResourceBindSerializer() : GenericPayloadSerializer<Reso
}
std::string ResourceBindSerializer::serializePayload(boost::shared_ptr<ResourceBind> resourceBind) const {
- XMLElement bindElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
- if (resourceBind->getJID().isValid()) {
- boost::shared_ptr<XMLElement> jidNode(new XMLElement("jid"));
- jidNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getJID().toString()));
- bindElement.addNode(jidNode);
- }
- else if (!resourceBind->getResource().empty()) {
- boost::shared_ptr<XMLElement> resourceNode(new XMLElement("resource"));
- resourceNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getResource()));
- bindElement.addNode(resourceNode);
- }
- return bindElement.serialize();
+ XMLElement bindElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
+ if (resourceBind->getJID().isValid()) {
+ boost::shared_ptr<XMLElement> jidNode(new XMLElement("jid"));
+ jidNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getJID().toString()));
+ bindElement.addNode(jidNode);
+ }
+ else if (!resourceBind->getResource().empty()) {
+ boost::shared_ptr<XMLElement> resourceNode(new XMLElement("resource"));
+ resourceNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getResource()));
+ bindElement.addNode(resourceNode);
+ }
+ return bindElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h
index 4f60b71..2878c34 100644
--- a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API ResourceBindSerializer : public GenericPayloadSerializer<ResourceBind> {
- public:
- ResourceBindSerializer();
+ class SWIFTEN_API ResourceBindSerializer : public GenericPayloadSerializer<ResourceBind> {
+ public:
+ ResourceBindSerializer();
- virtual std::string serializePayload(boost::shared_ptr<ResourceBind>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<ResourceBind>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
index 479d6be..205d9e0 100644
--- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
@@ -21,43 +21,43 @@ ResultSetSerializer::~ResultSetSerializer() {
}
std::string ResultSetSerializer::serializePayload(boost::shared_ptr<ResultSet> payload) const {
- if (!payload) {
- return "";
- }
+ if (!payload) {
+ return "";
+ }
- XMLElement element("set", "http://jabber.org/protocol/rsm");
+ XMLElement element("set", "http://jabber.org/protocol/rsm");
- if (payload->getMaxItems()) {
- element.addNode(boost::make_shared<XMLElement>("max", "", boost::lexical_cast<std::string>(*payload->getMaxItems())));
- }
+ if (payload->getMaxItems()) {
+ element.addNode(boost::make_shared<XMLElement>("max", "", boost::lexical_cast<std::string>(*payload->getMaxItems())));
+ }
- if (payload->getCount()) {
- element.addNode(boost::make_shared<XMLElement>("count", "", boost::lexical_cast<std::string>(*payload->getCount())));
- }
+ if (payload->getCount()) {
+ element.addNode(boost::make_shared<XMLElement>("count", "", boost::lexical_cast<std::string>(*payload->getCount())));
+ }
- if (payload->getIndex()) {
- element.addNode(boost::make_shared<XMLElement>("index", "", boost::lexical_cast<std::string>(*payload->getIndex())));
- }
+ if (payload->getIndex()) {
+ element.addNode(boost::make_shared<XMLElement>("index", "", boost::lexical_cast<std::string>(*payload->getIndex())));
+ }
- if (payload->getFirstID()) {
- boost::shared_ptr<XMLElement> firstElement = boost::make_shared<XMLElement>("first", "", *payload->getFirstID());
- if (payload->getFirstIDIndex()) {
- firstElement->setAttribute("index", boost::lexical_cast<std::string>(*payload->getFirstIDIndex()));
- }
- element.addNode(firstElement);
- }
+ if (payload->getFirstID()) {
+ boost::shared_ptr<XMLElement> firstElement = boost::make_shared<XMLElement>("first", "", *payload->getFirstID());
+ if (payload->getFirstIDIndex()) {
+ firstElement->setAttribute("index", boost::lexical_cast<std::string>(*payload->getFirstIDIndex()));
+ }
+ element.addNode(firstElement);
+ }
- if (payload->getLastID()) {
- element.addNode(boost::make_shared<XMLElement>("last", "", *payload->getLastID()));
- }
+ if (payload->getLastID()) {
+ element.addNode(boost::make_shared<XMLElement>("last", "", *payload->getLastID()));
+ }
- if (payload->getBefore()) {
- element.addNode(boost::make_shared<XMLElement>("before", "", *payload->getBefore()));
- }
+ if (payload->getBefore()) {
+ element.addNode(boost::make_shared<XMLElement>("before", "", *payload->getBefore()));
+ }
- if (payload->getAfter()) {
- element.addNode(boost::make_shared<XMLElement>("after", "", *payload->getAfter()));
- }
+ if (payload->getAfter()) {
+ element.addNode(boost::make_shared<XMLElement>("after", "", *payload->getAfter()));
+ }
- return element.serialize();
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h
index 7c4a0c9..9d8e24d 100644
--- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API ResultSetSerializer : public GenericPayloadSerializer<ResultSet> {
- public:
- ResultSetSerializer();
- virtual ~ResultSetSerializer();
+ class SWIFTEN_API ResultSetSerializer : public GenericPayloadSerializer<ResultSet> {
+ public:
+ ResultSetSerializer();
+ virtual ~ResultSetSerializer();
- virtual std::string serializePayload(boost::shared_ptr<ResultSet>) const SWIFTEN_OVERRIDE;
- };
+ virtual std::string serializePayload(boost::shared_ptr<ResultSet>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
index 54c31bd..f0b19e1 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
@@ -26,28 +26,28 @@ RosterItemExchangeSerializer::RosterItemExchangeSerializer() : GenericPayloadSer
}
std::string RosterItemExchangeSerializer::serializePayload(boost::shared_ptr<RosterItemExchangePayload> roster) const {
- XMLElement queryElement("x", "http://jabber.org/protocol/rosterx");
- foreach(const RosterItemExchangePayload::Item& item, roster->getItems()) {
- boost::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()) {
- boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
- groupElement->addNode(boost::make_shared<XMLTextNode>(group));
- itemElement->addNode(groupElement);
- }
-
- queryElement.addNode(itemElement);
- }
-
- return queryElement.serialize();
+ XMLElement queryElement("x", "http://jabber.org/protocol/rosterx");
+ foreach(const RosterItemExchangePayload::Item& item, roster->getItems()) {
+ boost::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()) {
+ boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
+ groupElement->addNode(boost::make_shared<XMLTextNode>(group));
+ itemElement->addNode(groupElement);
+ }
+
+ queryElement.addNode(itemElement);
+ }
+
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
index 8fbc202..ec4e81e 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
@@ -17,10 +17,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API RosterItemExchangeSerializer : public GenericPayloadSerializer<RosterItemExchangePayload> {
- public:
- RosterItemExchangeSerializer();
+ class SWIFTEN_API RosterItemExchangeSerializer : public GenericPayloadSerializer<RosterItemExchangePayload> {
+ public:
+ RosterItemExchangeSerializer();
- virtual std::string serializePayload(boost::shared_ptr<RosterItemExchangePayload>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<RosterItemExchangePayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
index b90e859..1094f2d 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
@@ -20,42 +20,42 @@ RosterSerializer::RosterSerializer() : GenericPayloadSerializer<RosterPayload>()
}
std::string RosterSerializer::serializePayload(boost::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()) {
- boost::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()) {
- boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
- groupElement->addNode(boost::make_shared<XMLTextNode>(group));
- itemElement->addNode(groupElement);
- }
-
- if (!item.getUnknownContent().empty()) {
- itemElement->addNode(boost::make_shared<XMLRawTextNode>(item.getUnknownContent()));
- }
-
-
- queryElement.addNode(itemElement);
- }
-
- return queryElement.serialize();
+ XMLElement queryElement("query", "jabber:iq:roster");
+ if (roster->getVersion()) {
+ queryElement.setAttribute("ver", *roster->getVersion());
+ }
+ foreach(const RosterItemPayload& item, roster->getItems()) {
+ boost::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()) {
+ boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
+ groupElement->addNode(boost::make_shared<XMLTextNode>(group));
+ itemElement->addNode(groupElement);
+ }
+
+ if (!item.getUnknownContent().empty()) {
+ itemElement->addNode(boost::make_shared<XMLRawTextNode>(item.getUnknownContent()));
+ }
+
+
+ queryElement.addNode(itemElement);
+ }
+
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.h b/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
index 1788d7b..799d88f 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API RosterSerializer : public GenericPayloadSerializer<RosterPayload> {
- public:
- RosterSerializer();
+ class SWIFTEN_API RosterSerializer : public GenericPayloadSerializer<RosterPayload> {
+ public:
+ RosterSerializer();
- virtual std::string serializePayload(boost::shared_ptr<RosterPayload>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<RosterPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
index 062e7c6..f10bcfc 100644
--- a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
@@ -21,24 +21,24 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API S5BProxyRequestSerializer : public GenericPayloadSerializer<S5BProxyRequest> {
- public:
- virtual std::string serializePayload(boost::shared_ptr<S5BProxyRequest> s5bProxyRequest) const {
- XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
- if (s5bProxyRequest && s5bProxyRequest->getStreamHost()) {
- boost::shared_ptr<XMLElement> streamHost = boost::make_shared<XMLElement>("streamhost");
- streamHost->setAttribute("host", s5bProxyRequest->getStreamHost().get().host);
- streamHost->setAttribute("port", boost::lexical_cast<std::string>(s5bProxyRequest->getStreamHost().get().port));
- streamHost->setAttribute("jid", s5bProxyRequest->getStreamHost().get().jid.toString());
- queryElement.addNode(streamHost);
- } else if (s5bProxyRequest && s5bProxyRequest->getActivate()) {
- queryElement.setAttribute("sid", s5bProxyRequest->getSID());
- boost::shared_ptr<XMLElement> activate = boost::make_shared<XMLElement>("activate", "", s5bProxyRequest->getActivate().get().toString());
- queryElement.addNode(activate);
- }
- return queryElement.serialize();
- }
- };
+ class SWIFTEN_API S5BProxyRequestSerializer : public GenericPayloadSerializer<S5BProxyRequest> {
+ public:
+ virtual std::string serializePayload(boost::shared_ptr<S5BProxyRequest> s5bProxyRequest) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
+ if (s5bProxyRequest && s5bProxyRequest->getStreamHost()) {
+ boost::shared_ptr<XMLElement> streamHost = boost::make_shared<XMLElement>("streamhost");
+ streamHost->setAttribute("host", s5bProxyRequest->getStreamHost().get().host);
+ streamHost->setAttribute("port", boost::lexical_cast<std::string>(s5bProxyRequest->getStreamHost().get().port));
+ streamHost->setAttribute("jid", s5bProxyRequest->getStreamHost().get().jid.toString());
+ queryElement.addNode(streamHost);
+ } else if (s5bProxyRequest && s5bProxyRequest->getActivate()) {
+ queryElement.setAttribute("sid", s5bProxyRequest->getSID());
+ boost::shared_ptr<XMLElement> activate = boost::make_shared<XMLElement>("activate", "", s5bProxyRequest->getActivate().get().toString());
+ queryElement.addNode(activate);
+ }
+ return queryElement.serialize();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
index e2cb766..de036df 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
@@ -19,45 +19,45 @@ namespace Swift {
SearchPayloadSerializer::SearchPayloadSerializer() {
}
-std::string SearchPayloadSerializer::serializePayload(boost::shared_ptr<SearchPayload> searchPayload) const {
- XMLElement searchElement("query", "jabber:iq:search");
+std::string SearchPayloadSerializer::serializePayload(boost::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->getInstructions()) {
+ searchElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *searchPayload->getInstructions())));
+ }
- if (searchPayload->getNick()) {
- searchElement.addNode(XMLElement::ref(new XMLElement("nick", "", *searchPayload->getNick())));
- }
+ 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->getFirst()) {
+ searchElement.addNode(XMLElement::ref(new XMLElement("first", "", *searchPayload->getFirst())));
+ }
- if (searchPayload->getLast()) {
- searchElement.addNode(XMLElement::ref(new XMLElement("last", "", *searchPayload->getLast())));
- }
+ if (searchPayload->getLast()) {
+ searchElement.addNode(XMLElement::ref(new XMLElement("last", "", *searchPayload->getLast())));
+ }
- if (searchPayload->getEMail()) {
- searchElement.addNode(XMLElement::ref(new XMLElement("email", "", *searchPayload->getEMail())));
- }
+ if (searchPayload->getEMail()) {
+ searchElement.addNode(XMLElement::ref(new XMLElement("email", "", *searchPayload->getEMail())));
+ }
- foreach(const SearchPayload::Item& 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)));
+ foreach(const SearchPayload::Item& 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);
- }
+ searchElement.addNode(itemElement);
+ }
- if (Form::ref form = searchPayload->getForm()) {
- searchElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
+ if (Form::ref form = searchPayload->getForm()) {
+ searchElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
- return searchElement.serialize();
+ return searchElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h
index ff5e2cc..594e5d7 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h
@@ -12,12 +12,12 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API SearchPayloadSerializer : public GenericPayloadSerializer<SearchPayload> {
- public:
- SearchPayloadSerializer();
+ class SWIFTEN_API SearchPayloadSerializer : public GenericPayloadSerializer<SearchPayload> {
+ public:
+ SearchPayloadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<SearchPayload>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<SearchPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
index fb7092c..9b35952 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
@@ -19,29 +19,29 @@ SecurityLabelSerializer::SecurityLabelSerializer() : GenericPayloadSerializer<Se
}
std::string SecurityLabelSerializer::serializePayload(boost::shared_ptr<SecurityLabel> label) const {
- XMLElement element("securitylabel", "urn:xmpp:sec-label:0");
- if (!label->getDisplayMarking().empty()) {
- boost::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(boost::make_shared<XMLTextNode>(label->getDisplayMarking()));
- element.addNode(displayMarking);
- }
-
- boost::shared_ptr<XMLElement> labelElement(new XMLElement("label"));
- labelElement->addNode(boost::make_shared<XMLRawTextNode>(label->getLabel()));
- element.addNode(labelElement);
-
- foreach(const std::string& equivalentLabel, label->getEquivalentLabels()) {
- boost::shared_ptr<XMLElement> equivalentLabelElement(new XMLElement("equivalentlabel"));
- equivalentLabelElement->addNode(boost::make_shared<XMLRawTextNode>(equivalentLabel));
- element.addNode(equivalentLabelElement);
- }
- return element.serialize();
+ XMLElement element("securitylabel", "urn:xmpp:sec-label:0");
+ if (!label->getDisplayMarking().empty()) {
+ boost::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(boost::make_shared<XMLTextNode>(label->getDisplayMarking()));
+ element.addNode(displayMarking);
+ }
+
+ boost::shared_ptr<XMLElement> labelElement(new XMLElement("label"));
+ labelElement->addNode(boost::make_shared<XMLRawTextNode>(label->getLabel()));
+ element.addNode(labelElement);
+
+ foreach(const std::string& equivalentLabel, label->getEquivalentLabels()) {
+ boost::shared_ptr<XMLElement> equivalentLabelElement(new XMLElement("equivalentlabel"));
+ equivalentLabelElement->addNode(boost::make_shared<XMLRawTextNode>(equivalentLabel));
+ element.addNode(equivalentLabelElement);
+ }
+ return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
index cf95243..23f50f4 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API SecurityLabelSerializer : public GenericPayloadSerializer<SecurityLabel> {
- public:
- SecurityLabelSerializer();
+ class SWIFTEN_API SecurityLabelSerializer : public GenericPayloadSerializer<SecurityLabel> {
+ public:
+ SecurityLabelSerializer();
- virtual std::string serializePayload(boost::shared_ptr<SecurityLabel> version) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<SecurityLabel> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
index 1aeae06..2bf6bbb 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
@@ -19,29 +19,29 @@ SecurityLabelsCatalogSerializer::SecurityLabelsCatalogSerializer() : GenericPayl
}
std::string SecurityLabelsCatalogSerializer::serializePayload(boost::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()) {
- boost::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(boost::make_shared<XMLRawTextNode>(serializedLabel));
- }
- element.addNode(itemElement);
- }
- return element.serialize();
+ 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()) {
+ boost::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(boost::make_shared<XMLRawTextNode>(serializedLabel));
+ }
+ element.addNode(itemElement);
+ }
+ return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
index 3829995..da3b7f3 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API SecurityLabelsCatalogSerializer : public GenericPayloadSerializer<SecurityLabelsCatalog> {
- public:
- SecurityLabelsCatalogSerializer();
+ class SWIFTEN_API SecurityLabelsCatalogSerializer : public GenericPayloadSerializer<SecurityLabelsCatalog> {
+ public:
+ SecurityLabelsCatalogSerializer();
- virtual std::string serializePayload(boost::shared_ptr<SecurityLabelsCatalog> version) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<SecurityLabelsCatalog> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
index 8c0c605..05beaae 100644
--- a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
@@ -12,18 +12,18 @@ SoftwareVersionSerializer::SoftwareVersionSerializer() : GenericPayloadSerialize
}
std::string SoftwareVersionSerializer::serializePayload(boost::shared_ptr<SoftwareVersion> version) const {
- std::string result("<query xmlns=\"jabber:iq:version\">");
- if (!version->getName().empty()) {
- result += "<name>" + version->getName() + "</name>";
- }
- if (!version->getVersion().empty()) {
- result += "<version>" + version->getVersion() + "</version>";
- }
- if (!version->getOS().empty()) {
- result += "<os>" + version->getOS() + "</os>";
- }
- result += "</query>";
- return result;
+ std::string result("<query xmlns=\"jabber:iq:version\">");
+ if (!version->getName().empty()) {
+ result += "<name>" + version->getName() + "</name>";
+ }
+ if (!version->getVersion().empty()) {
+ result += "<version>" + version->getVersion() + "</version>";
+ }
+ if (!version->getOS().empty()) {
+ result += "<os>" + version->getOS() + "</os>";
+ }
+ result += "</query>";
+ return result;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
index d514df0..6c03c84 100644
--- a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API SoftwareVersionSerializer : public GenericPayloadSerializer<SoftwareVersion> {
- public:
- SoftwareVersionSerializer();
+ class SWIFTEN_API SoftwareVersionSerializer : public GenericPayloadSerializer<SoftwareVersion> {
+ public:
+ SoftwareVersionSerializer();
- virtual std::string serializePayload(boost::shared_ptr<SoftwareVersion> version) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<SoftwareVersion> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h b/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
index 1815955..086652f 100644
--- a/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
@@ -14,12 +14,12 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StartSessionSerializer : public GenericPayloadSerializer<StartSession> {
- public:
- StartSessionSerializer() : GenericPayloadSerializer<StartSession>() {}
+ class SWIFTEN_API StartSessionSerializer : public GenericPayloadSerializer<StartSession> {
+ public:
+ StartSessionSerializer() : GenericPayloadSerializer<StartSession>() {}
- virtual std::string serializePayload(boost::shared_ptr<StartSession>) const {
- return XMLElement("session", "urn:ietf:params:xml:ns:xmpp-session").serialize();
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<StartSession>) const {
+ return XMLElement("session", "urn:ietf:params:xml:ns:xmpp-session").serialize();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StatusSerializer.h b/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
index fb30744..8247e28 100644
--- a/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
@@ -15,14 +15,14 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class SWIFTEN_API StatusSerializer : public GenericPayloadSerializer<Status> {
- public:
- StatusSerializer() : GenericPayloadSerializer<Status>() {}
+ class SWIFTEN_API StatusSerializer : public GenericPayloadSerializer<Status> {
+ public:
+ StatusSerializer() : GenericPayloadSerializer<Status>() {}
- virtual std::string serializePayload(boost::shared_ptr<Status> status) const {
- XMLElement element("status");
- element.addNode(boost::make_shared<XMLTextNode>(status->getText()));
- return element.serialize();
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Status> status) const {
+ XMLElement element("status");
+ element.addNode(boost::make_shared<XMLTextNode>(status->getText()));
+ return element.serialize();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h b/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
index 13462f3..24fbe1b 100644
--- a/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
@@ -11,27 +11,27 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API StatusShowSerializer : public GenericPayloadSerializer<StatusShow> {
- public:
- StatusShowSerializer() : GenericPayloadSerializer<StatusShow>() {}
+ class SWIFTEN_API StatusShowSerializer : public GenericPayloadSerializer<StatusShow> {
+ public:
+ StatusShowSerializer() : GenericPayloadSerializer<StatusShow>() {}
- virtual std::string serializePayload(boost::shared_ptr<StatusShow> statusShow) const {
- if (statusShow->getType () == StatusShow::Online || statusShow->getType() == StatusShow::None) {
- return "";
- }
- else {
- std::string result("<show>");
- switch (statusShow->getType()) {
- case StatusShow::Away: result += "away"; break;
- case StatusShow::XA: result += "xa"; break;
- case StatusShow::FFC: result += "chat"; break;
- case StatusShow::DND: result += "dnd"; break;
- case StatusShow::Online: assert(false); break;
- case StatusShow::None: assert(false); break;
- }
- result += "</show>";
- return result;
- }
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<StatusShow> statusShow) const {
+ if (statusShow->getType () == StatusShow::Online || statusShow->getType() == StatusShow::None) {
+ return "";
+ }
+ else {
+ std::string result("<show>");
+ switch (statusShow->getType()) {
+ case StatusShow::Away: result += "away"; break;
+ case StatusShow::XA: result += "xa"; break;
+ case StatusShow::FFC: result += "chat"; break;
+ case StatusShow::DND: result += "dnd"; break;
+ case StatusShow::Online: assert(false); break;
+ case StatusShow::None: assert(false); break;
+ }
+ result += "</show>";
+ return result;
+ }
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
index 45d8f8e..64ea62c 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
@@ -18,35 +18,35 @@ namespace Swift {
StorageSerializer::StorageSerializer() : GenericPayloadSerializer<Storage>() {
}
-std::string StorageSerializer::serializePayload(boost::shared_ptr<Storage> storage) const {
- XMLElement storageElement("storage", "storage:bookmarks");
-
- foreach(const Storage::Room& room, storage->getRooms()) {
- boost::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()) {
- boost::shared_ptr<XMLElement> nickElement(new XMLElement("nick"));
- nickElement->addNode(boost::make_shared<XMLTextNode>(room.nick));
- conferenceElement->addNode(nickElement);
- }
- if (room.password) {
- boost::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
- passwordElement->addNode(boost::make_shared<XMLTextNode>(*room.password));
- conferenceElement->addNode(passwordElement);
- }
- storageElement.addNode(conferenceElement);
- }
-
- foreach(const Storage::URL& url, storage->getURLs()) {
- boost::shared_ptr<XMLElement> urlElement(new XMLElement("url"));
- urlElement->setAttribute("name", url.name);
- urlElement->setAttribute("url", url.url);
- storageElement.addNode(urlElement);
- }
-
- return storageElement.serialize();
+std::string StorageSerializer::serializePayload(boost::shared_ptr<Storage> storage) const {
+ XMLElement storageElement("storage", "storage:bookmarks");
+
+ foreach(const Storage::Room& room, storage->getRooms()) {
+ boost::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()) {
+ boost::shared_ptr<XMLElement> nickElement(new XMLElement("nick"));
+ nickElement->addNode(boost::make_shared<XMLTextNode>(room.nick));
+ conferenceElement->addNode(nickElement);
+ }
+ if (room.password) {
+ boost::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
+ passwordElement->addNode(boost::make_shared<XMLTextNode>(*room.password));
+ conferenceElement->addNode(passwordElement);
+ }
+ storageElement.addNode(conferenceElement);
+ }
+
+ foreach(const Storage::URL& url, storage->getURLs()) {
+ boost::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/StorageSerializer.h b/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
index 6d62f35..a3a55f4 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API StorageSerializer : public GenericPayloadSerializer<Storage> {
- public:
- StorageSerializer();
+ class SWIFTEN_API StorageSerializer : public GenericPayloadSerializer<Storage> {
+ public:
+ StorageSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Storage>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<Storage>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
index 06e28d8..a64d7ae 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
@@ -26,35 +26,35 @@ namespace Swift {
StreamInitiationFileInfoSerializer::StreamInitiationFileInfoSerializer() {
}
-
+
std::string StreamInitiationFileInfoSerializer::serializePayload(boost::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()) {
- boost::shared_ptr<XMLElement> desc = boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription());
- fileElement.addNode(desc);
- }
- if (fileInfo->getSupportsRangeRequests()) {
- boost::shared_ptr<XMLElement> range = boost::make_shared<XMLElement>("range");
- if (fileInfo->getRangeOffset() != 0) {
- range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
- }
- fileElement.addNode(range);
- }
- return fileElement.serialize();
+ 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()) {
+ boost::shared_ptr<XMLElement> desc = boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription());
+ fileElement.addNode(desc);
+ }
+ if (fileInfo->getSupportsRangeRequests()) {
+ boost::shared_ptr<XMLElement> range = boost::make_shared<XMLElement>("range");
+ if (fileInfo->getRangeOffset() != 0) {
+ range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
+ }
+ fileElement.addNode(range);
+ }
+ return fileElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
index 50268c5..e7714f0 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
@@ -19,12 +19,12 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API StreamInitiationFileInfoSerializer : public GenericPayloadSerializer<StreamInitiationFileInfo> {
- public:
- StreamInitiationFileInfoSerializer();
+ class SWIFTEN_API StreamInitiationFileInfoSerializer : public GenericPayloadSerializer<StreamInitiationFileInfo> {
+ public:
+ StreamInitiationFileInfoSerializer();
- virtual std::string serializePayload(boost::shared_ptr<StreamInitiationFileInfo>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<StreamInitiationFileInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
index bd44040..824569a 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
@@ -25,51 +25,51 @@ namespace Swift {
StreamInitiationSerializer::StreamInitiationSerializer() {
}
-std::string StreamInitiationSerializer::serializePayload(boost::shared_ptr<StreamInitiation> streamInitiation) const {
- assert(streamInitiation->getIsFileTransfer());
+std::string StreamInitiationSerializer::serializePayload(boost::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);
+ 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();
- boost::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()) {
- boost::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
- descElement->addNode(boost::make_shared<XMLTextNode>(file.getDescription()));
- fileElement->addNode(descElement);
- }
- siElement.addNode(fileElement);
- }
+ if (streamInitiation->getFileInfo()) {
+ StreamInitiationFileInfo file = *streamInitiation->getFileInfo();
+ boost::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()) {
+ boost::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
+ descElement->addNode(boost::make_shared<XMLTextNode>(file.getDescription()));
+ fileElement->addNode(descElement);
+ }
+ siElement.addNode(fileElement);
+ }
- boost::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 = boost::make_shared<FormField>(FormField::ListSingleType);
- field->setName("stream-method");
- foreach(const std::string& method, streamInitiation->getProvidedMethods()) {
- field->addOption(FormField::Option("", method));
- }
- form->addField(field);
- featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
- else if (!streamInitiation->getRequestedMethod().empty()) {
- Form::ref form(new Form(Form::SubmitType));
- FormField::ref field = boost::make_shared<FormField>(FormField::ListSingleType);
- field->addValue(streamInitiation->getRequestedMethod());
- field->setName("stream-method");
- form->addField(field);
- featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
- siElement.addNode(featureElement);
- return siElement.serialize();
+ boost::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 = boost::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("stream-method");
+ foreach(const std::string& method, streamInitiation->getProvidedMethods()) {
+ field->addOption(FormField::Option("", method));
+ }
+ form->addField(field);
+ featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
+ else if (!streamInitiation->getRequestedMethod().empty()) {
+ Form::ref form(new Form(Form::SubmitType));
+ FormField::ref field = boost::make_shared<FormField>(FormField::ListSingleType);
+ field->addValue(streamInitiation->getRequestedMethod());
+ field->setName("stream-method");
+ form->addField(field);
+ featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
+ siElement.addNode(featureElement);
+ return siElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
index f83b2b8..056806e 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamInitiationSerializer : public GenericPayloadSerializer<StreamInitiation> {
- public:
- StreamInitiationSerializer();
+ class SWIFTEN_API StreamInitiationSerializer : public GenericPayloadSerializer<StreamInitiation> {
+ public:
+ StreamInitiationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<StreamInitiation>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<StreamInitiation>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h b/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
index 7e113c5..9f90ce0 100644
--- a/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
@@ -12,13 +12,13 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class SWIFTEN_API SubjectSerializer : public GenericPayloadSerializer<Subject> {
- public:
- SubjectSerializer() : GenericPayloadSerializer<Subject>() {}
+ class SWIFTEN_API SubjectSerializer : public GenericPayloadSerializer<Subject> {
+ public:
+ SubjectSerializer() : GenericPayloadSerializer<Subject>() {}
- virtual std::string serializePayload(boost::shared_ptr<Subject> subject) const {
- XMLTextNode textNode(subject->getText());
- return "<subject>" + textNode.serialize() + "</subject>";
- }
- };
+ virtual std::string serializePayload(boost::shared_ptr<Subject> subject) const {
+ XMLTextNode textNode(subject->getText());
+ return "<subject>" + textNode.serialize() + "</subject>";
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp
index cc4d573..61b91ae 100644
--- a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp
@@ -9,17 +9,17 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- ThreadSerializer::ThreadSerializer() : GenericPayloadSerializer<Thread>() {
- }
+ ThreadSerializer::ThreadSerializer() : GenericPayloadSerializer<Thread>() {
+ }
- ThreadSerializer::~ThreadSerializer() {
- }
+ ThreadSerializer::~ThreadSerializer() {
+ }
- std::string ThreadSerializer::serializePayload(boost::shared_ptr<Thread> thread) const {
- XMLElement threadNode("thread", "", thread->getText());
- if (!thread->getParent().empty()) {
- threadNode.setAttribute("parent", thread->getParent());
- }
- return threadNode.serialize();
- }
+ std::string ThreadSerializer::serializePayload(boost::shared_ptr<Thread> thread) const {
+ XMLElement threadNode("thread", "", thread->getText());
+ if (!thread->getParent().empty()) {
+ threadNode.setAttribute("parent", thread->getParent());
+ }
+ return threadNode.serialize();
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h
index e54c39a..264faba 100644
--- a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h
@@ -12,11 +12,11 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- class SWIFTEN_API ThreadSerializer : public GenericPayloadSerializer<Thread> {
- public:
- ThreadSerializer();
- virtual ~ThreadSerializer();
+ class SWIFTEN_API ThreadSerializer : public GenericPayloadSerializer<Thread> {
+ public:
+ ThreadSerializer();
+ virtual ~ThreadSerializer();
- virtual std::string serializePayload(boost::shared_ptr<Thread> thread) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<Thread> thread) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
index d130577..1dc97f8 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
@@ -23,39 +23,39 @@ using namespace Swift;
class BlockSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(BlockSerializerTest);
- CPPUNIT_TEST(testExample4);
- CPPUNIT_TEST(testExample6);
- CPPUNIT_TEST(testExample10);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- BlockSerializerTest() {}
-
- void testExample4() {
- BlockSerializer<BlockListPayload> testling("blocklist");
- boost::shared_ptr<BlockListPayload> blocklist = boost::make_shared<BlockListPayload>();
- blocklist->addItem(JID("romeo@montague.net"));
- blocklist->addItem(JID("iago@shakespeare.lit"));
-
- CPPUNIT_ASSERT_EQUAL(std::string("<blocklist xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/><item jid=\"iago@shakespeare.lit\"/></blocklist>"), testling.serialize(blocklist));
- }
-
- void testExample6() {
- BlockSerializer<BlockPayload> testling("block");
- boost::shared_ptr<BlockPayload> block = boost::make_shared<BlockPayload>();
- block->addItem(JID("romeo@montague.net"));
-
- CPPUNIT_ASSERT_EQUAL(std::string("<block xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/></block>"), testling.serialize(block));
- }
-
- void testExample10() {
- BlockSerializer<UnblockPayload> testling("unblock");
- boost::shared_ptr<UnblockPayload> unblock = boost::make_shared<UnblockPayload>();
- unblock->addItem(JID("romeo@montague.net"));
-
- CPPUNIT_ASSERT_EQUAL(std::string("<unblock xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/></unblock>"), testling.serialize(unblock));
- }
+ CPPUNIT_TEST_SUITE(BlockSerializerTest);
+ CPPUNIT_TEST(testExample4);
+ CPPUNIT_TEST(testExample6);
+ CPPUNIT_TEST(testExample10);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ BlockSerializerTest() {}
+
+ void testExample4() {
+ BlockSerializer<BlockListPayload> testling("blocklist");
+ boost::shared_ptr<BlockListPayload> blocklist = boost::make_shared<BlockListPayload>();
+ blocklist->addItem(JID("romeo@montague.net"));
+ blocklist->addItem(JID("iago@shakespeare.lit"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<blocklist xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/><item jid=\"iago@shakespeare.lit\"/></blocklist>"), testling.serialize(blocklist));
+ }
+
+ void testExample6() {
+ BlockSerializer<BlockPayload> testling("block");
+ boost::shared_ptr<BlockPayload> block = boost::make_shared<BlockPayload>();
+ block->addItem(JID("romeo@montague.net"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<block xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/></block>"), testling.serialize(block));
+ }
+
+ void testExample10() {
+ BlockSerializer<UnblockPayload> testling("unblock");
+ boost::shared_ptr<UnblockPayload> unblock = boost::make_shared<UnblockPayload>();
+ unblock->addItem(JID("romeo@montague.net"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<unblock xmlns=\"urn:xmpp:blocking\"><item jid=\"romeo@montague.net\"/></unblock>"), testling.serialize(unblock));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(BlockSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp
index bdf5cbc..517e98b 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp
@@ -13,19 +13,19 @@ using namespace Swift;
class CapsInfoSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(CapsInfoSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(CapsInfoSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- CapsInfoSerializerTest() {}
+ public:
+ CapsInfoSerializerTest() {}
- void testSerialize() {
- CapsInfoSerializer testling;
- boost::shared_ptr<CapsInfo> priority(new CapsInfo("http://swift.im", "myversion", "sha-1"));
+ void testSerialize() {
+ CapsInfoSerializer testling;
+ boost::shared_ptr<CapsInfo> priority(new CapsInfo("http://swift.im", "myversion", "sha-1"));
- CPPUNIT_ASSERT_EQUAL(std::string("<c hash=\"sha-1\" node=\"http://swift.im\" ver=\"myversion\" xmlns=\"http://jabber.org/protocol/caps\"/>"), testling.serialize(priority));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<c hash=\"sha-1\" node=\"http://swift.im\" ver=\"myversion\" xmlns=\"http://jabber.org/protocol/caps\"/>"), testling.serialize(priority));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(CapsInfoSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp
index b4dadf8..a0c49a6 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp
@@ -20,117 +20,117 @@
#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/CarbonsSentSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
using namespace Swift;
class CarbonsSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CarbonsSerializerTest);
- CPPUNIT_TEST(testSerializeExample3);
- CPPUNIT_TEST(testSerializeExample6);
- CPPUNIT_TEST(testSerializeExample12);
- CPPUNIT_TEST(testSerializeExample14);
- CPPUNIT_TEST(testSerializeExample15);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- CarbonsSerializerTest() {}
-
- /*
- * Test serializing of example 3 in XEP-0280.
- */
- void testSerializeExample3() {
- CarbonsEnableSerializer testling;
-
- CPPUNIT_ASSERT_EQUAL(std::string("<enable xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsEnable>()));
- }
-
- /*
- * Test serializing of example 6 in XEP-0280.
- */
- void testSerializeExample6() {
- CarbonsDisableSerializer testling;
-
- CPPUNIT_ASSERT_EQUAL(std::string("<disable xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsDisable>()));
- }
-
- /*
- * Test serializing of example 12 in XEP-0280.
- */
- void testSerializeExample12() {
- CarbonsReceivedSerializer testling(&serializers);
-
- CarbonsReceived::ref received = boost::make_shared<CarbonsReceived>();
-
- boost::shared_ptr<Forwarded> forwarded = boost::make_shared<Forwarded>();
-
- Message::ref message = boost::make_shared<Message>();
- message->setFrom(JID("juliet@capulet.example/balcony"));
- message->setTo(JID("romeo@montague.example/garden"));
- message->setBody("What man art thou that, thus bescreen'd in night, so stumblest on my counsel?");
- message->addPayload(boost::make_shared<Thread>("0e3141cd80894871a68e6fe6b1ec56fa"));
-
- forwarded->setStanza(message);
- received->setForwarded(forwarded);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<received xmlns=\"urn:xmpp:carbons:2\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<message from=\"juliet@capulet.example/balcony\""
- " to=\"romeo@montague.example/garden\""
- " type=\"chat\""
- " xmlns=\"jabber:client\">"
- "<body>What man art thou that, thus bescreen'd in night, so stumblest on my counsel?</body>"
- "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
- "</message>"
- "</forwarded>"
- "</received>"), testling.serialize(received));
- }
-
- /*
- * Test serializing of example 14 in XEP-0280.
- */
- void testSerializeExample14() {
- CarbonsSentSerializer testling(&serializers);
-
- CarbonsSent::ref sent = boost::make_shared<CarbonsSent>();
-
- boost::shared_ptr<Forwarded> forwarded = boost::make_shared<Forwarded>();
-
- Message::ref message = boost::make_shared<Message>();
- message->setTo(JID("juliet@capulet.example/balcony"));
- message->setFrom(JID("romeo@montague.example/home"));
- message->setBody("Neither, fair saint, if either thee dislike.");
- message->addPayload(boost::make_shared<Thread>("0e3141cd80894871a68e6fe6b1ec56fa"));
-
- forwarded->setStanza(message);
- sent->setForwarded(forwarded);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<sent xmlns=\"urn:xmpp:carbons:2\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<message from=\"romeo@montague.example/home\""
- " to=\"juliet@capulet.example/balcony\""
- " type=\"chat\""
- " xmlns=\"jabber:client\">"
- "<body>Neither, fair saint, if either thee dislike.</body>"
- "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
- "</message>"
- "</forwarded>"
- "</sent>"), testling.serialize(sent));
- }
-
- /*
- * Test serializing of example 15 in XEP-0280.
- */
- void testSerializeExample15() {
- CarbonsPrivateSerializer testling;
-
- CPPUNIT_ASSERT_EQUAL(std::string("<private xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsPrivate>()));
- }
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_TEST_SUITE(CarbonsSerializerTest);
+ CPPUNIT_TEST(testSerializeExample3);
+ CPPUNIT_TEST(testSerializeExample6);
+ CPPUNIT_TEST(testSerializeExample12);
+ CPPUNIT_TEST(testSerializeExample14);
+ CPPUNIT_TEST(testSerializeExample15);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ CarbonsSerializerTest() {}
+
+ /*
+ * Test serializing of example 3 in XEP-0280.
+ */
+ void testSerializeExample3() {
+ CarbonsEnableSerializer testling;
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<enable xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsEnable>()));
+ }
+
+ /*
+ * Test serializing of example 6 in XEP-0280.
+ */
+ void testSerializeExample6() {
+ CarbonsDisableSerializer testling;
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<disable xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsDisable>()));
+ }
+
+ /*
+ * Test serializing of example 12 in XEP-0280.
+ */
+ void testSerializeExample12() {
+ CarbonsReceivedSerializer testling(&serializers);
+
+ CarbonsReceived::ref received = boost::make_shared<CarbonsReceived>();
+
+ boost::shared_ptr<Forwarded> forwarded = boost::make_shared<Forwarded>();
+
+ Message::ref message = boost::make_shared<Message>();
+ message->setFrom(JID("juliet@capulet.example/balcony"));
+ message->setTo(JID("romeo@montague.example/garden"));
+ message->setBody("What man art thou that, thus bescreen'd in night, so stumblest on my counsel?");
+ message->addPayload(boost::make_shared<Thread>("0e3141cd80894871a68e6fe6b1ec56fa"));
+
+ forwarded->setStanza(message);
+ received->setForwarded(forwarded);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<received xmlns=\"urn:xmpp:carbons:2\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<message from=\"juliet@capulet.example/balcony\""
+ " to=\"romeo@montague.example/garden\""
+ " type=\"chat\""
+ " xmlns=\"jabber:client\">"
+ "<body>What man art thou that, thus bescreen'd in night, so stumblest on my counsel?</body>"
+ "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
+ "</message>"
+ "</forwarded>"
+ "</received>"), testling.serialize(received));
+ }
+
+ /*
+ * Test serializing of example 14 in XEP-0280.
+ */
+ void testSerializeExample14() {
+ CarbonsSentSerializer testling(&serializers);
+
+ CarbonsSent::ref sent = boost::make_shared<CarbonsSent>();
+
+ boost::shared_ptr<Forwarded> forwarded = boost::make_shared<Forwarded>();
+
+ Message::ref message = boost::make_shared<Message>();
+ message->setTo(JID("juliet@capulet.example/balcony"));
+ message->setFrom(JID("romeo@montague.example/home"));
+ message->setBody("Neither, fair saint, if either thee dislike.");
+ message->addPayload(boost::make_shared<Thread>("0e3141cd80894871a68e6fe6b1ec56fa"));
+
+ forwarded->setStanza(message);
+ sent->setForwarded(forwarded);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<sent xmlns=\"urn:xmpp:carbons:2\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<message from=\"romeo@montague.example/home\""
+ " to=\"juliet@capulet.example/balcony\""
+ " type=\"chat\""
+ " xmlns=\"jabber:client\">"
+ "<body>Neither, fair saint, if either thee dislike.</body>"
+ "<thread>0e3141cd80894871a68e6fe6b1ec56fa</thread>"
+ "</message>"
+ "</forwarded>"
+ "</sent>"), testling.serialize(sent));
+ }
+
+ /*
+ * Test serializing of example 15 in XEP-0280.
+ */
+ void testSerializeExample15() {
+ CarbonsPrivateSerializer testling;
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<private xmlns=\"urn:xmpp:carbons:2\"/>"), testling.serialize(boost::make_shared<CarbonsPrivate>()));
+ }
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CarbonsSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp
index 36a01d3..85b067f 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp
@@ -13,42 +13,42 @@ using namespace Swift;
class ChatStateSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ChatStateSerializerTest);
- CPPUNIT_TEST(testSerialize_ActiveState);
- CPPUNIT_TEST(testSerialize_GoneState);
- CPPUNIT_TEST(testSerialize_ComposingState);
- CPPUNIT_TEST(testSerialize_PausedState);
- CPPUNIT_TEST(testSerialize_InacativeState);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- ChatStateSerializerTest() {}
- ChatStateSerializer testling;
-
- void testSerialize_ActiveState() {
- boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Active));
- CPPUNIT_ASSERT_EQUAL(std::string("<active xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
- }
-
- void testSerialize_GoneState() {
- boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Gone));
- CPPUNIT_ASSERT_EQUAL(std::string("<gone xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
- }
-
- void testSerialize_ComposingState() {
- boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Composing));
- CPPUNIT_ASSERT_EQUAL(std::string("<composing xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
- }
-
- void testSerialize_PausedState() {
- boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Paused));
- CPPUNIT_ASSERT_EQUAL(std::string("<paused xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
- }
-
- void testSerialize_InacativeState() {
- boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Inactive));
- CPPUNIT_ASSERT_EQUAL(std::string("<inactive xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
- }
+ CPPUNIT_TEST_SUITE(ChatStateSerializerTest);
+ CPPUNIT_TEST(testSerialize_ActiveState);
+ CPPUNIT_TEST(testSerialize_GoneState);
+ CPPUNIT_TEST(testSerialize_ComposingState);
+ CPPUNIT_TEST(testSerialize_PausedState);
+ CPPUNIT_TEST(testSerialize_InacativeState);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ ChatStateSerializerTest() {}
+ ChatStateSerializer testling;
+
+ void testSerialize_ActiveState() {
+ boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Active));
+ CPPUNIT_ASSERT_EQUAL(std::string("<active xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
+ }
+
+ void testSerialize_GoneState() {
+ boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Gone));
+ CPPUNIT_ASSERT_EQUAL(std::string("<gone xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
+ }
+
+ void testSerialize_ComposingState() {
+ boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Composing));
+ CPPUNIT_ASSERT_EQUAL(std::string("<composing xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
+ }
+
+ void testSerialize_PausedState() {
+ boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Paused));
+ CPPUNIT_ASSERT_EQUAL(std::string("<paused xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
+ }
+
+ void testSerialize_InacativeState() {
+ boost::shared_ptr<ChatState> priority(new ChatState(ChatState::Inactive));
+ CPPUNIT_ASSERT_EQUAL(std::string("<inactive xmlns=\"http://jabber.org/protocol/chatstates\"/>"), testling.serialize(priority));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChatStateSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp
index 0c39e14..bda9ab7 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp
@@ -22,29 +22,29 @@
using namespace Swift;
class DeliveryReceiptSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(DeliveryReceiptSerializerTest);
- CPPUNIT_TEST(testSerialize_XEP0184Example3);
- CPPUNIT_TEST(testSerialize_XEP0184Example4);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DeliveryReceiptSerializerTest);
+ CPPUNIT_TEST(testSerialize_XEP0184Example3);
+ CPPUNIT_TEST(testSerialize_XEP0184Example4);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize_XEP0184Example3() {
- std::string expected = "<request xmlns=\"urn:xmpp:receipts\"/>";
+ public:
+ void testSerialize_XEP0184Example3() {
+ std::string expected = "<request xmlns=\"urn:xmpp:receipts\"/>";
- DeliveryReceiptRequest::ref receipt = boost::make_shared<DeliveryReceiptRequest>();
+ DeliveryReceiptRequest::ref receipt = boost::make_shared<DeliveryReceiptRequest>();
- boost::shared_ptr<DeliveryReceiptRequestSerializer> serializer = boost::make_shared<DeliveryReceiptRequestSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
- }
+ boost::shared_ptr<DeliveryReceiptRequestSerializer> serializer = boost::make_shared<DeliveryReceiptRequestSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
+ }
- void testSerialize_XEP0184Example4() {
- std::string expected = "<received id=\"richard2-4.1.247\" xmlns=\"urn:xmpp:receipts\"/>";
+ void testSerialize_XEP0184Example4() {
+ std::string expected = "<received id=\"richard2-4.1.247\" xmlns=\"urn:xmpp:receipts\"/>";
- DeliveryReceipt::ref receipt = boost::make_shared<DeliveryReceipt>("richard2-4.1.247");
+ DeliveryReceipt::ref receipt = boost::make_shared<DeliveryReceipt>("richard2-4.1.247");
- boost::shared_ptr<DeliveryReceiptSerializer> serializer = boost::make_shared<DeliveryReceiptSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
- }
+ boost::shared_ptr<DeliveryReceiptSerializer> serializer = boost::make_shared<DeliveryReceiptSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DeliveryReceiptSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp
index 9aff6d2..14b1a34 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp
@@ -13,54 +13,54 @@ using namespace Swift;
class DiscoInfoSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(DiscoInfoSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_Form);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(DiscoInfoSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_Form);
+ CPPUNIT_TEST_SUITE_END();
- public:
- DiscoInfoSerializerTest() {}
+ public:
+ DiscoInfoSerializerTest() {}
- void testSerialize() {
- DiscoInfoSerializer testling;
- boost::shared_ptr<DiscoInfo> discoInfo(new DiscoInfo());
- discoInfo->addIdentity(DiscoInfo::Identity("Swift", "client", "pc"));
- discoInfo->addIdentity(DiscoInfo::Identity("Vlug", "client", "pc", "nl"));
- discoInfo->addFeature("http://jabber.org/protocol/caps");
- discoInfo->addFeature("http://jabber.org/protocol/disco#info");
- discoInfo->setNode("http://swift.im#bla");
+ void testSerialize() {
+ DiscoInfoSerializer testling;
+ boost::shared_ptr<DiscoInfo> discoInfo(new DiscoInfo());
+ discoInfo->addIdentity(DiscoInfo::Identity("Swift", "client", "pc"));
+ discoInfo->addIdentity(DiscoInfo::Identity("Vlug", "client", "pc", "nl"));
+ discoInfo->addFeature("http://jabber.org/protocol/caps");
+ discoInfo->addFeature("http://jabber.org/protocol/disco#info");
+ discoInfo->setNode("http://swift.im#bla");
- std::string expectedResult =
- "<query node=\"http://swift.im#bla\" xmlns=\"http://jabber.org/protocol/disco#info\">"
- "<identity category=\"client\" name=\"Swift\" type=\"pc\"/>"
- "<identity category=\"client\" name=\"Vlug\" type=\"pc\" xml:lang=\"nl\"/>"
- "<feature var=\"http://jabber.org/protocol/caps\"/>"
- "<feature var=\"http://jabber.org/protocol/disco#info\"/>"
- "</query>";
+ std::string expectedResult =
+ "<query node=\"http://swift.im#bla\" xmlns=\"http://jabber.org/protocol/disco#info\">"
+ "<identity category=\"client\" name=\"Swift\" type=\"pc\"/>"
+ "<identity category=\"client\" name=\"Vlug\" type=\"pc\" xml:lang=\"nl\"/>"
+ "<feature var=\"http://jabber.org/protocol/caps\"/>"
+ "<feature var=\"http://jabber.org/protocol/disco#info\"/>"
+ "</query>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(discoInfo));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(discoInfo));
+ }
- void testSerialize_Form() {
- DiscoInfoSerializer testling;
- boost::shared_ptr<DiscoInfo> discoInfo(new DiscoInfo());
- discoInfo->addFeature("http://jabber.org/protocol/caps");
- discoInfo->addFeature("http://jabber.org/protocol/disco#info");
- boost::shared_ptr<Form> form(new Form(Form::FormType));
- form->setTitle("Bot Configuration");
- discoInfo->addExtension(form);
+ void testSerialize_Form() {
+ DiscoInfoSerializer testling;
+ boost::shared_ptr<DiscoInfo> discoInfo(new DiscoInfo());
+ discoInfo->addFeature("http://jabber.org/protocol/caps");
+ discoInfo->addFeature("http://jabber.org/protocol/disco#info");
+ boost::shared_ptr<Form> form(new Form(Form::FormType));
+ form->setTitle("Bot Configuration");
+ discoInfo->addExtension(form);
- std::string expectedResult =
- "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
- "<feature var=\"http://jabber.org/protocol/caps\"/>"
- "<feature var=\"http://jabber.org/protocol/disco#info\"/>"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<title>Bot Configuration</title>"
- "</x>"
- "</query>";
+ std::string expectedResult =
+ "<query xmlns=\"http://jabber.org/protocol/disco#info\">"
+ "<feature var=\"http://jabber.org/protocol/caps\"/>"
+ "<feature var=\"http://jabber.org/protocol/disco#info\"/>"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<title>Bot Configuration</title>"
+ "</x>"
+ "</query>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(discoInfo));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(discoInfo));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(DiscoInfoSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp
index c4d3e29..13d9e3c 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp
@@ -16,31 +16,31 @@
using namespace Swift;
class ErrorSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ErrorSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_Payload);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- ErrorSerializer testling(&serializers);
- boost::shared_ptr<ErrorPayload> error(new ErrorPayload(ErrorPayload::BadRequest, ErrorPayload::Cancel, "My Error"));
-
- CPPUNIT_ASSERT_EQUAL(std::string("<error type=\"cancel\"><bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/><text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">My Error</text></error>"), testling.serialize(error));
- }
-
- void testSerialize_Payload() {
- ErrorSerializer testling(&serializers);
- boost::shared_ptr<ErrorPayload> error = boost::make_shared<ErrorPayload>();
- error->setPayload(boost::make_shared<Delay>());
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<error type=\"cancel\"><undefined-condition xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/><delay stamp=\"not-a-date-timeZ\" xmlns=\"urn:xmpp:delay\"/></error>"
- ), testling.serialize(error));
- }
-
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_TEST_SUITE(ErrorSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_Payload);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ ErrorSerializer testling(&serializers);
+ boost::shared_ptr<ErrorPayload> error(new ErrorPayload(ErrorPayload::BadRequest, ErrorPayload::Cancel, "My Error"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<error type=\"cancel\"><bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/><text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">My Error</text></error>"), testling.serialize(error));
+ }
+
+ void testSerialize_Payload() {
+ ErrorSerializer testling(&serializers);
+ boost::shared_ptr<ErrorPayload> error = boost::make_shared<ErrorPayload>();
+ error->setPayload(boost::make_shared<Delay>());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<error type=\"cancel\"><undefined-condition xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/><delay stamp=\"not-a-date-timeZ\" xmlns=\"urn:xmpp:delay\"/></error>"
+ ), testling.serialize(error));
+ }
+
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ErrorSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp
index 967bc0e..8bd16cd 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp
@@ -12,287 +12,287 @@
using namespace Swift;
class FormSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(FormSerializerTest);
- CPPUNIT_TEST(testSerializeFormInformation);
- CPPUNIT_TEST(testSerializeLayout);
- CPPUNIT_TEST(testSerializeFields);
- CPPUNIT_TEST(testSerializeFormItems);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerializeFormInformation() {
- FormSerializer testling;
- boost::shared_ptr<Form> form(new Form(Form::FormType));
- form->setTitle("Bot Configuration");
- form->setInstructions("Hello!\nFill out this form to configure your new bot!");
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<title>Bot Configuration</title>"
- "<instructions>Hello!</instructions>"
- "<instructions>Fill out this form to configure your new bot!</instructions>"
- "</x>"), testling.serialize(form));
- }
-
- void testSerializeLayout() {
- FormSerializer testling;
- boost::shared_ptr<Form> form(new Form(Form::FormType));
-
- FormPage::page page = boost::make_shared<FormPage>();
- page->setLabel("P1");
- FormReportedRef::ref reportedRef = boost::make_shared<FormReportedRef>();
- page->addReportedRef(reportedRef);
- FormText::text formText = boost::make_shared<FormText>();
- formText->setTextString("P1T1");
- page->addTextElement(formText);
- FormField::ref field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("P1F1");
- field->setLabel("field one");
- page->addField(field);
-
- FormSection::section section = boost::make_shared<FormSection>();
- section->setLabel("P1S1");
- formText = boost::make_shared<FormText>();
- formText->setTextString("P1S1T1");
- section->addTextElement(formText);
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("P1S1F1");
- field->setLabel("field two");
- section->addField(field);
- page->addChildSection(section);
- form->addPage(page);
-
- page = boost::make_shared<FormPage>();
- page->setLabel("P2");
- section = boost::make_shared<FormSection>();
- section->setLabel("P2S1");
- FormSection::section subSection = boost::make_shared<FormSection>();
- subSection->setLabel("P2S2");
- FormSection::section subSection2 = boost::make_shared<FormSection>();
- subSection2->setLabel("P2S3");
- subSection->addChildSection(subSection2);
- section->addChildSection(subSection);
- page->addChildSection(section);
- form->addPage(page);
-
- // P1 = page one, S1 = section one, F1 = field one, T1 = text one
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<page label=\"P1\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
- "<text>P1T1</text>"
- "<fieldref var=\"P1F1\"/>"
- "<reportedref/>"
- "<section label=\"P1S1\">"
- "<text>P1S1T1</text>"
- "<fieldref var=\"P1S1F1\"/>"
- "</section>"
- "</page>"
- "<page label=\"P2\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
- "<section label=\"P2S1\">"
- "<section label=\"P2S2\">"
- "<section label=\"P2S3\"/>"
- "</section>"
- "</section>"
- "</page>"
- "<field label=\"field one\" type=\"text-single\" var=\"P1F1\"/>"
- "<field label=\"field two\" type=\"text-single\" var=\"P1S1F1\"/>"
- "</x>"), testling.serialize(form));
- }
-
- void testSerializeFields() {
- FormSerializer testling;
- boost::shared_ptr<Form> form(new Form(Form::FormType));
-
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot");
- field->setName("FORM_TYPE");
- form->addField(field);
-
- form->addField(boost::make_shared<FormField>(FormField::FixedType, "Section 1: Bot Info"));
-
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("botname");
- field->setLabel("The name of your bot");
- form->addField(field);
-
- field = boost::make_shared<FormField>(FormField::TextMultiType);
- field->setTextMultiValue("This is a bot.\nA quite good one actually");
- field->setName("description");
- field->setLabel("Helpful description of your bot");
- form->addField(field);
-
- field = boost::make_shared<FormField>(FormField::BooleanType, "1");
- field->setName("public");
- field->setLabel("Public bot?");
- field->setRequired(true);
- form->addField(field);
-
- field = boost::make_shared<FormField>(FormField::TextPrivateType);
- field->setName("password");
- field->setLabel("Password for special access");
- form->addField(field);
-
- field = boost::make_shared<FormField>(FormField::ListMultiType);
- field->addValue("news");
- field->addValue("search");
- field->setName("features");
- field->setLabel("What features will the bot support?");
- field->addOption(FormField::Option("Contests", "contests"));
- field->addOption(FormField::Option("News", "news"));
- field->addOption(FormField::Option("Polls", "polls"));
- field->addOption(FormField::Option("Reminders", "reminders"));
- field->addOption(FormField::Option("Search", "search"));
- form->addField(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType, "20");
- field->setName("maxsubs");
- field->setLabel("Maximum number of subscribers");
- field->addOption(FormField::Option("10", "10"));
- field->addOption(FormField::Option("20", "20"));
- field->addOption(FormField::Option("30", "30"));
- field->addOption(FormField::Option("50", "50"));
- field->addOption(FormField::Option("100", "100"));
- field->addOption(FormField::Option("", "none"));
- form->addField(field);
-
- std::vector<JID> jids;
- field = boost::make_shared<FormField>(FormField::JIDMultiType);
- field->addValue("foo@bar.com");
- field->addValue("baz@fum.org");
- field->setName("invitelist");
- field->setLabel("People to invite");
- field->setDescription("Tell all your friends about your new bot!");
- form->addField(field);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:bot</value>"
- "</field>"
- "<field type=\"fixed\"><value>Section 1: Bot Info</value></field>"
- "<field label=\"The name of your bot\" type=\"text-single\" var=\"botname\"/>"
- "<field label=\"Helpful description of your bot\" type=\"text-multi\" var=\"description\"><value>This is a bot.</value><value>A quite good one actually</value></field>"
- "<field label=\"Public bot?\" type=\"boolean\" var=\"public\">"
- "<required/>"
- "<value>1</value>"
- "</field>"
- "<field label=\"Password for special access\" type=\"text-private\" var=\"password\"/>"
- "<field label=\"What features will the bot support?\" type=\"list-multi\" var=\"features\">"
- "<value>news</value>"
- "<value>search</value>"
- "<option label=\"Contests\"><value>contests</value></option>"
- "<option label=\"News\"><value>news</value></option>"
- "<option label=\"Polls\"><value>polls</value></option>"
- "<option label=\"Reminders\"><value>reminders</value></option>"
- "<option label=\"Search\"><value>search</value></option>"
- "</field>"
- "<field label=\"Maximum number of subscribers\" type=\"list-single\" var=\"maxsubs\">"
- "<value>20</value>"
- "<option label=\"10\"><value>10</value></option>"
- "<option label=\"20\"><value>20</value></option>"
- "<option label=\"30\"><value>30</value></option>"
- "<option label=\"50\"><value>50</value></option>"
- "<option label=\"100\"><value>100</value></option>"
- "<option><value>none</value></option>"
- "</field>"
- "<field label=\"People to invite\" type=\"jid-multi\" var=\"invitelist\">"
- "<desc>Tell all your friends about your new bot!</desc>"
- "<value>foo@bar.com</value>"
- "<value>baz@fum.org</value>"
- "</field>"
- "</x>"), testling.serialize(form));
- }
-
- void testSerializeFormItems() {
- FormSerializer testling;
- boost::shared_ptr<Form> form(new Form(Form::ResultType));
-
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
- field->setName("FORM_TYPE");
- form->addField(field);
-
- // reported fields
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("first");
- field->setLabel("Given Name");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("last");
- field->setLabel("Family Name");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::JIDSingleType);
- field->setName("jid");
- field->setLabel("Jabber ID");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType);
- field->setName("x-gender");
- field->setLabel("Gender");
- form->addReportedField(field);
-
- Form::FormItem firstItem;
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
- field->setName("first");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
- field->setName("last");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::JIDSingleType, JID("benvolio@montague.net"));
- field->setName("jid");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
- field->setName("x-gender");
- firstItem.push_back(field);
-
- Form::FormItem secondItem;
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Romeo");
- field->setName("first");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
- field->setName("last");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::JIDSingleType, JID("romeo@montague.net"));
- field->setName("jid");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
- field->setName("x-gender");
- secondItem.push_back(field);
-
- form->addItem(firstItem);
- form->addItem(secondItem);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<x type=\"result\" xmlns=\"jabber:x:data\">"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:iq:search</value>"
- "</field>"
- "<reported>"
- "<field label=\"Given Name\" type=\"text-single\" var=\"first\"/>"
- "<field label=\"Family Name\" type=\"text-single\" var=\"last\"/>"
- "<field label=\"Jabber ID\" type=\"jid-single\" var=\"jid\"/>"
- "<field label=\"Gender\" type=\"list-single\" var=\"x-gender\"/>"
- "</reported>"
- "<item>"
- "<field var=\"first\"><value>Benvolio</value></field>"
- "<field var=\"last\"><value>Montague</value></field>"
- "<field var=\"jid\"><value>benvolio@montague.net</value></field>"
- "<field var=\"x-gender\"><value>male</value></field>"
- "</item>"
- "<item>"
- "<field var=\"first\"><value>Romeo</value></field>"
- "<field var=\"last\"><value>Montague</value></field>"
- "<field var=\"jid\"><value>romeo@montague.net</value></field>"
- "<field var=\"x-gender\"><value>male</value></field>"
- "</item>"
- "</x>"), testling.serialize(form));
- }
+ CPPUNIT_TEST_SUITE(FormSerializerTest);
+ CPPUNIT_TEST(testSerializeFormInformation);
+ CPPUNIT_TEST(testSerializeLayout);
+ CPPUNIT_TEST(testSerializeFields);
+ CPPUNIT_TEST(testSerializeFormItems);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerializeFormInformation() {
+ FormSerializer testling;
+ boost::shared_ptr<Form> form(new Form(Form::FormType));
+ form->setTitle("Bot Configuration");
+ form->setInstructions("Hello!\nFill out this form to configure your new bot!");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<title>Bot Configuration</title>"
+ "<instructions>Hello!</instructions>"
+ "<instructions>Fill out this form to configure your new bot!</instructions>"
+ "</x>"), testling.serialize(form));
+ }
+
+ void testSerializeLayout() {
+ FormSerializer testling;
+ boost::shared_ptr<Form> form(new Form(Form::FormType));
+
+ FormPage::page page = boost::make_shared<FormPage>();
+ page->setLabel("P1");
+ FormReportedRef::ref reportedRef = boost::make_shared<FormReportedRef>();
+ page->addReportedRef(reportedRef);
+ FormText::text formText = boost::make_shared<FormText>();
+ formText->setTextString("P1T1");
+ page->addTextElement(formText);
+ FormField::ref field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("P1F1");
+ field->setLabel("field one");
+ page->addField(field);
+
+ FormSection::section section = boost::make_shared<FormSection>();
+ section->setLabel("P1S1");
+ formText = boost::make_shared<FormText>();
+ formText->setTextString("P1S1T1");
+ section->addTextElement(formText);
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("P1S1F1");
+ field->setLabel("field two");
+ section->addField(field);
+ page->addChildSection(section);
+ form->addPage(page);
+
+ page = boost::make_shared<FormPage>();
+ page->setLabel("P2");
+ section = boost::make_shared<FormSection>();
+ section->setLabel("P2S1");
+ FormSection::section subSection = boost::make_shared<FormSection>();
+ subSection->setLabel("P2S2");
+ FormSection::section subSection2 = boost::make_shared<FormSection>();
+ subSection2->setLabel("P2S3");
+ subSection->addChildSection(subSection2);
+ section->addChildSection(subSection);
+ page->addChildSection(section);
+ form->addPage(page);
+
+ // P1 = page one, S1 = section one, F1 = field one, T1 = text one
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<page label=\"P1\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
+ "<text>P1T1</text>"
+ "<fieldref var=\"P1F1\"/>"
+ "<reportedref/>"
+ "<section label=\"P1S1\">"
+ "<text>P1S1T1</text>"
+ "<fieldref var=\"P1S1F1\"/>"
+ "</section>"
+ "</page>"
+ "<page label=\"P2\" xmlns=\"http://jabber.org/protocol/xdata-layout\">"
+ "<section label=\"P2S1\">"
+ "<section label=\"P2S2\">"
+ "<section label=\"P2S3\"/>"
+ "</section>"
+ "</section>"
+ "</page>"
+ "<field label=\"field one\" type=\"text-single\" var=\"P1F1\"/>"
+ "<field label=\"field two\" type=\"text-single\" var=\"P1S1F1\"/>"
+ "</x>"), testling.serialize(form));
+ }
+
+ void testSerializeFields() {
+ FormSerializer testling;
+ boost::shared_ptr<Form> form(new Form(Form::FormType));
+
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:bot");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ form->addField(boost::make_shared<FormField>(FormField::FixedType, "Section 1: Bot Info"));
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("botname");
+ field->setLabel("The name of your bot");
+ form->addField(field);
+
+ field = boost::make_shared<FormField>(FormField::TextMultiType);
+ field->setTextMultiValue("This is a bot.\nA quite good one actually");
+ field->setName("description");
+ field->setLabel("Helpful description of your bot");
+ form->addField(field);
+
+ field = boost::make_shared<FormField>(FormField::BooleanType, "1");
+ field->setName("public");
+ field->setLabel("Public bot?");
+ field->setRequired(true);
+ form->addField(field);
+
+ field = boost::make_shared<FormField>(FormField::TextPrivateType);
+ field->setName("password");
+ field->setLabel("Password for special access");
+ form->addField(field);
+
+ field = boost::make_shared<FormField>(FormField::ListMultiType);
+ field->addValue("news");
+ field->addValue("search");
+ field->setName("features");
+ field->setLabel("What features will the bot support?");
+ field->addOption(FormField::Option("Contests", "contests"));
+ field->addOption(FormField::Option("News", "news"));
+ field->addOption(FormField::Option("Polls", "polls"));
+ field->addOption(FormField::Option("Reminders", "reminders"));
+ field->addOption(FormField::Option("Search", "search"));
+ form->addField(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType, "20");
+ field->setName("maxsubs");
+ field->setLabel("Maximum number of subscribers");
+ field->addOption(FormField::Option("10", "10"));
+ field->addOption(FormField::Option("20", "20"));
+ field->addOption(FormField::Option("30", "30"));
+ field->addOption(FormField::Option("50", "50"));
+ field->addOption(FormField::Option("100", "100"));
+ field->addOption(FormField::Option("", "none"));
+ form->addField(field);
+
+ std::vector<JID> jids;
+ field = boost::make_shared<FormField>(FormField::JIDMultiType);
+ field->addValue("foo@bar.com");
+ field->addValue("baz@fum.org");
+ field->setName("invitelist");
+ field->setLabel("People to invite");
+ field->setDescription("Tell all your friends about your new bot!");
+ form->addField(field);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:bot</value>"
+ "</field>"
+ "<field type=\"fixed\"><value>Section 1: Bot Info</value></field>"
+ "<field label=\"The name of your bot\" type=\"text-single\" var=\"botname\"/>"
+ "<field label=\"Helpful description of your bot\" type=\"text-multi\" var=\"description\"><value>This is a bot.</value><value>A quite good one actually</value></field>"
+ "<field label=\"Public bot?\" type=\"boolean\" var=\"public\">"
+ "<required/>"
+ "<value>1</value>"
+ "</field>"
+ "<field label=\"Password for special access\" type=\"text-private\" var=\"password\"/>"
+ "<field label=\"What features will the bot support?\" type=\"list-multi\" var=\"features\">"
+ "<value>news</value>"
+ "<value>search</value>"
+ "<option label=\"Contests\"><value>contests</value></option>"
+ "<option label=\"News\"><value>news</value></option>"
+ "<option label=\"Polls\"><value>polls</value></option>"
+ "<option label=\"Reminders\"><value>reminders</value></option>"
+ "<option label=\"Search\"><value>search</value></option>"
+ "</field>"
+ "<field label=\"Maximum number of subscribers\" type=\"list-single\" var=\"maxsubs\">"
+ "<value>20</value>"
+ "<option label=\"10\"><value>10</value></option>"
+ "<option label=\"20\"><value>20</value></option>"
+ "<option label=\"30\"><value>30</value></option>"
+ "<option label=\"50\"><value>50</value></option>"
+ "<option label=\"100\"><value>100</value></option>"
+ "<option><value>none</value></option>"
+ "</field>"
+ "<field label=\"People to invite\" type=\"jid-multi\" var=\"invitelist\">"
+ "<desc>Tell all your friends about your new bot!</desc>"
+ "<value>foo@bar.com</value>"
+ "<value>baz@fum.org</value>"
+ "</field>"
+ "</x>"), testling.serialize(form));
+ }
+
+ void testSerializeFormItems() {
+ FormSerializer testling;
+ boost::shared_ptr<Form> form(new Form(Form::ResultType));
+
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ // reported fields
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("first");
+ field->setLabel("Given Name");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("last");
+ field->setLabel("Family Name");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::JIDSingleType);
+ field->setName("jid");
+ field->setLabel("Jabber ID");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("x-gender");
+ field->setLabel("Gender");
+ form->addReportedField(field);
+
+ Form::FormItem firstItem;
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
+ field->setName("first");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::JIDSingleType, JID("benvolio@montague.net"));
+ field->setName("jid");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ firstItem.push_back(field);
+
+ Form::FormItem secondItem;
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Romeo");
+ field->setName("first");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::JIDSingleType, JID("romeo@montague.net"));
+ field->setName("jid");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ secondItem.push_back(field);
+
+ form->addItem(firstItem);
+ form->addItem(secondItem);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<x type=\"result\" xmlns=\"jabber:x:data\">"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:iq:search</value>"
+ "</field>"
+ "<reported>"
+ "<field label=\"Given Name\" type=\"text-single\" var=\"first\"/>"
+ "<field label=\"Family Name\" type=\"text-single\" var=\"last\"/>"
+ "<field label=\"Jabber ID\" type=\"jid-single\" var=\"jid\"/>"
+ "<field label=\"Gender\" type=\"list-single\" var=\"x-gender\"/>"
+ "</reported>"
+ "<item>"
+ "<field var=\"first\"><value>Benvolio</value></field>"
+ "<field var=\"last\"><value>Montague</value></field>"
+ "<field var=\"jid\"><value>benvolio@montague.net</value></field>"
+ "<field var=\"x-gender\"><value>male</value></field>"
+ "</item>"
+ "<item>"
+ "<field var=\"first\"><value>Romeo</value></field>"
+ "<field var=\"last\"><value>Montague</value></field>"
+ "<field var=\"jid\"><value>romeo@montague.net</value></field>"
+ "<field var=\"x-gender\"><value>male</value></field>"
+ "</item>"
+ "</x>"), testling.serialize(form));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(FormSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp
index 9e986d3..d7aed26 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp
@@ -21,99 +21,99 @@
using namespace Swift;
class ForwardedSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ForwardedSerializerTest);
- CPPUNIT_TEST(testSerializeIQ);
- CPPUNIT_TEST(testSerializeMessage);
- CPPUNIT_TEST(testSerializeMessageNoDelay);
- CPPUNIT_TEST(testSerializePresence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerializeIQ() {
- ForwardedSerializer serializer(&serializers);
-
- boost::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(iq);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
-
- std::string expectedResult =
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<iq from=\"romeo@montague.lit/orchard\" id=\"id0\" to=\"juliet@capulet.lit/balcony\" type=\"result\" xmlns=\"jabber:client\"/>"
- "</forwarded>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
- }
-
- void testSerializeMessage() {
- ForwardedSerializer serializer(&serializers);
-
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setType(Message::Chat);
- message->setTo(JID("juliet@capulet.lit/balcony"));
- message->setFrom(JID("romeo@montague.lit/orchard"));
- message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(message);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
-
- std::string expectedResult =
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
- }
-
- void testSerializeMessageNoDelay() {
- ForwardedSerializer serializer(&serializers);
-
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setType(Message::Chat);
- message->setTo(JID("juliet@capulet.lit/balcony"));
- message->setFrom(JID("romeo@montague.lit/orchard"));
- message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(message);
-
- std::string expectedResult =
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
- }
-
- void testSerializePresence() {
- ForwardedSerializer serializer(&serializers);
-
- boost::shared_ptr<Presence> presence(boost::make_shared<Presence>());
- presence->setType(Presence::Subscribe);
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(presence);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
-
- std::string expectedResult =
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<presence type=\"subscribe\" xmlns=\"jabber:client\"/>"
- "</forwarded>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
- }
-
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_TEST_SUITE(ForwardedSerializerTest);
+ CPPUNIT_TEST(testSerializeIQ);
+ CPPUNIT_TEST(testSerializeMessage);
+ CPPUNIT_TEST(testSerializeMessageNoDelay);
+ CPPUNIT_TEST(testSerializePresence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerializeIQ() {
+ ForwardedSerializer serializer(&serializers);
+
+ boost::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(iq);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ std::string expectedResult =
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<iq from=\"romeo@montague.lit/orchard\" id=\"id0\" to=\"juliet@capulet.lit/balcony\" type=\"result\" xmlns=\"jabber:client\"/>"
+ "</forwarded>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
+ }
+
+ void testSerializeMessage() {
+ ForwardedSerializer serializer(&serializers);
+
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setType(Message::Chat);
+ message->setTo(JID("juliet@capulet.lit/balcony"));
+ message->setFrom(JID("romeo@montague.lit/orchard"));
+ message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ std::string expectedResult =
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
+ }
+
+ void testSerializeMessageNoDelay() {
+ ForwardedSerializer serializer(&serializers);
+
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setType(Message::Chat);
+ message->setTo(JID("juliet@capulet.lit/balcony"));
+ message->setFrom(JID("romeo@montague.lit/orchard"));
+ message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+
+ std::string expectedResult =
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
+ }
+
+ void testSerializePresence() {
+ ForwardedSerializer serializer(&serializers);
+
+ boost::shared_ptr<Presence> presence(boost::make_shared<Presence>());
+ presence->setType(Presence::Subscribe);
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(presence);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ std::string expectedResult =
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<presence type=\"subscribe\" xmlns=\"jabber:client\"/>"
+ "</forwarded>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(forwarded));
+ }
+
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ForwardedSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp
index 311ade3..45badea 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp
@@ -21,24 +21,24 @@ using namespace Swift;
class IBBSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(IBBSerializerTest);
- CPPUNIT_TEST(testSerialize_data);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- IBBSerializerTest() {}
-
- void testSerialize_data() {
- IBBSerializer testling;
- boost::shared_ptr<IBB> ibb = boost::make_shared<IBB>();
- ibb->setAction(IBB::Data);
- ibb->setData(createByteArray("abcdefgihjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\x0a"));
- ibb->setSequenceNumber(4);
- CPPUNIT_ASSERT_EQUAL(std::string("<data seq=\"4\" sid=\"\" xmlns=\"http://jabber.org/protocol/ibb\">"
- "YWJjZGVmZ2loamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjEyMzQ1"
- "Njc4OTAK"
- "</data>"), testling.serialize(ibb));
- }
+ CPPUNIT_TEST_SUITE(IBBSerializerTest);
+ CPPUNIT_TEST(testSerialize_data);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ IBBSerializerTest() {}
+
+ void testSerialize_data() {
+ IBBSerializer testling;
+ boost::shared_ptr<IBB> ibb = boost::make_shared<IBB>();
+ ibb->setAction(IBB::Data);
+ ibb->setData(createByteArray("abcdefgihjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\x0a"));
+ ibb->setSequenceNumber(4);
+ CPPUNIT_ASSERT_EQUAL(std::string("<data seq=\"4\" sid=\"\" xmlns=\"http://jabber.org/protocol/ibb\">"
+ "YWJjZGVmZ2loamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjEyMzQ1"
+ "Njc4OTAK"
+ "</data>"), testling.serialize(ibb));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(IBBSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp
index e00a929..147c7be 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp
@@ -20,19 +20,19 @@
using namespace Swift;
class IdleSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(IdleSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(IdleSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- IdleSerializerTest() {}
+ public:
+ IdleSerializerTest() {}
- void testSerialize() {
- IdleSerializer testling;
- Idle::ref idle = boost::make_shared<Idle>(stringToDateTime("1969-07-21T02:56:15Z"));
+ void testSerialize() {
+ IdleSerializer testling;
+ Idle::ref idle = boost::make_shared<Idle>(stringToDateTime("1969-07-21T02:56:15Z"));
- CPPUNIT_ASSERT_EQUAL(std::string("<idle xmlns='urn:xmpp:idle:1' since='1969-07-21T02:56:15Z'/>"), testling.serialize(idle));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<idle xmlns='urn:xmpp:idle:1' since='1969-07-21T02:56:15Z'/>"), testling.serialize(idle));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(IdleSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp
index 9320eff..b1b0c45 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp
@@ -14,50 +14,50 @@
using namespace Swift;
class InBandRegistrationPayloadSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(InBandRegistrationPayloadSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_Form);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- InBandRegistrationPayloadSerializer testling;
- boost::shared_ptr<InBandRegistrationPayload> registration(new InBandRegistrationPayload());
- registration->setRegistered(true);
-
- std::string expectedResult =
- "<query xmlns=\"jabber:iq:register\">"
- "<registered/>"
- "</query>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(registration));
- }
- void testSerialize_Form() {
- InBandRegistrationPayloadSerializer testling;
- boost::shared_ptr<InBandRegistrationPayload> registration(new InBandRegistrationPayload());
- registration->setInstructions("Use the enclosed form to register.");
-
- boost::shared_ptr<Form> form(new Form(Form::FormType));
- form->setTitle("Contest Registration");
-
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:register");
- field->setName("FORM_TYPE");
- form->addField(field);
- registration->setForm(form);
-
- std::string expectedResult =
- "<query xmlns=\"jabber:iq:register\">"
- "<instructions>Use the enclosed form to register.</instructions>"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<title>Contest Registration</title>"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:iq:register</value>"
- "</field>"
- "</x>"
- "</query>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(registration));
- }
+ CPPUNIT_TEST_SUITE(InBandRegistrationPayloadSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_Form);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ InBandRegistrationPayloadSerializer testling;
+ boost::shared_ptr<InBandRegistrationPayload> registration(new InBandRegistrationPayload());
+ registration->setRegistered(true);
+
+ std::string expectedResult =
+ "<query xmlns=\"jabber:iq:register\">"
+ "<registered/>"
+ "</query>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(registration));
+ }
+ void testSerialize_Form() {
+ InBandRegistrationPayloadSerializer testling;
+ boost::shared_ptr<InBandRegistrationPayload> registration(new InBandRegistrationPayload());
+ registration->setInstructions("Use the enclosed form to register.");
+
+ boost::shared_ptr<Form> form(new Form(Form::FormType));
+ form->setTitle("Contest Registration");
+
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:register");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+ registration->setForm(form);
+
+ std::string expectedResult =
+ "<query xmlns=\"jabber:iq:register\">"
+ "<instructions>Use the enclosed form to register.</instructions>"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<title>Contest Registration</title>"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:iq:register</value>"
+ "</field>"
+ "</x>"
+ "</query>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(registration));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(InBandRegistrationPayloadSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp
index 4e84648..8f46ca8 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp
@@ -29,104 +29,104 @@ using namespace Swift;
class IsodeIQDelegationSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(IsodeIQDelegationSerializerTest);
- CPPUNIT_TEST(testSerialize_Forwarded_IQ);
- CPPUNIT_TEST(testSerialize_Forwarded_Message);
- CPPUNIT_TEST(testSerialize_Forwarded_MessageNoDelay);
- CPPUNIT_TEST(testSerialize_Forwarded_Presence);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- IsodeIQDelegationSerializerTest() {}
-
- void testSerialize_Forwarded_IQ() {
- IsodeIQDelegationSerializer testling(&serializers);
- boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
-
- boost::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0", boost::make_shared<Subject>("text"));
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(iq);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
- isodeIQDelegation->setForward(forwarded);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<iq from=\"romeo@montague.lit/orchard\" id=\"id0\" to=\"juliet@capulet.lit/balcony\" type=\"result\" xmlns=\"jabber:client\"><subject>text</subject></iq>"
- "</forwarded>"
- "</delegate>"), testling.serialize(isodeIQDelegation));
- }
-
- void testSerialize_Forwarded_Message() {
- IsodeIQDelegationSerializer testling(&serializers);
- boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
-
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setType(Message::Chat);
- message->setTo(JID("juliet@capulet.lit/balcony"));
- message->setFrom(JID("romeo@montague.lit/orchard"));
- message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(message);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
-
- isodeIQDelegation->setForward(forwarded);
- CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"
- "</delegate>"), testling.serialize(isodeIQDelegation));
- }
-
- void testSerialize_Forwarded_MessageNoDelay() {
- IsodeIQDelegationSerializer testling(&serializers);
- boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
-
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setType(Message::Chat);
- message->setTo(JID("juliet@capulet.lit/balcony"));
- message->setFrom(JID("romeo@montague.lit/orchard"));
- message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(message);
- isodeIQDelegation->setForward(forwarded);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"
- "</delegate>"), testling.serialize(isodeIQDelegation));
- }
-
- void testSerialize_Forwarded_Presence() {
- IsodeIQDelegationSerializer testling(&serializers);
- boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
-
- boost::shared_ptr<Presence> presence(boost::make_shared<Presence>());
- presence->setType(Presence::Subscribe);
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(presence);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
- isodeIQDelegation->setForward(forwarded);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<presence type=\"subscribe\" xmlns=\"jabber:client\"/>"
- "</forwarded>"
- "</delegate>"), testling.serialize(isodeIQDelegation));
- }
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_TEST_SUITE(IsodeIQDelegationSerializerTest);
+ CPPUNIT_TEST(testSerialize_Forwarded_IQ);
+ CPPUNIT_TEST(testSerialize_Forwarded_Message);
+ CPPUNIT_TEST(testSerialize_Forwarded_MessageNoDelay);
+ CPPUNIT_TEST(testSerialize_Forwarded_Presence);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ IsodeIQDelegationSerializerTest() {}
+
+ void testSerialize_Forwarded_IQ() {
+ IsodeIQDelegationSerializer testling(&serializers);
+ boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
+
+ boost::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0", boost::make_shared<Subject>("text"));
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(iq);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+ isodeIQDelegation->setForward(forwarded);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<iq from=\"romeo@montague.lit/orchard\" id=\"id0\" to=\"juliet@capulet.lit/balcony\" type=\"result\" xmlns=\"jabber:client\"><subject>text</subject></iq>"
+ "</forwarded>"
+ "</delegate>"), testling.serialize(isodeIQDelegation));
+ }
+
+ void testSerialize_Forwarded_Message() {
+ IsodeIQDelegationSerializer testling(&serializers);
+ boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
+
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setType(Message::Chat);
+ message->setTo(JID("juliet@capulet.lit/balcony"));
+ message->setFrom(JID("romeo@montague.lit/orchard"));
+ message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ isodeIQDelegation->setForward(forwarded);
+ CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"
+ "</delegate>"), testling.serialize(isodeIQDelegation));
+ }
+
+ void testSerialize_Forwarded_MessageNoDelay() {
+ IsodeIQDelegationSerializer testling(&serializers);
+ boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
+
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setType(Message::Chat);
+ message->setTo(JID("juliet@capulet.lit/balcony"));
+ message->setFrom(JID("romeo@montague.lit/orchard"));
+ message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ isodeIQDelegation->setForward(forwarded);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"
+ "</delegate>"), testling.serialize(isodeIQDelegation));
+ }
+
+ void testSerialize_Forwarded_Presence() {
+ IsodeIQDelegationSerializer testling(&serializers);
+ boost::shared_ptr<IsodeIQDelegation> isodeIQDelegation = boost::make_shared<IsodeIQDelegation>();
+
+ boost::shared_ptr<Presence> presence(boost::make_shared<Presence>());
+ presence->setType(Presence::Subscribe);
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(presence);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+ isodeIQDelegation->setForward(forwarded);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<delegate xmlns=\"http://isode.com/iq_delegation\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<presence type=\"subscribe\" xmlns=\"jabber:client\"/>"
+ "</forwarded>"
+ "</delegate>"), testling.serialize(isodeIQDelegation));
+ }
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IsodeIQDelegationSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
index d0e469f..ecb68cd 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
@@ -32,377 +32,377 @@
using namespace Swift;
class JingleSerializersTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(JingleSerializersTest);
- CPPUNIT_TEST(testSerialize_StreamInitiationFileInfo);
- CPPUNIT_TEST(testSerialize_StreamInitiationFileInfoRange);
-
- CPPUNIT_TEST(testSerialize_Xep0261_Example1);
- CPPUNIT_TEST(testSerialize_Xep0261_Example9);
- CPPUNIT_TEST(testSerialize_Xep0261_Example13);
-
- CPPUNIT_TEST(testSerialize_Xep0234_Example1);
- CPPUNIT_TEST(testSerialize_Xep0234_Example3);
- CPPUNIT_TEST(testSerialize_Xep0234_Example5);
- CPPUNIT_TEST(testSerialize_Xep0234_Example8);
-
- CPPUNIT_TEST(testSerialize_Xep0260_Example1);
-
- CPPUNIT_TEST_SUITE_END();
-
- boost::shared_ptr<JinglePayloadSerializer> createTestling() {
- return boost::make_shared<JinglePayloadSerializer>(&collection);
- }
-
-
- public:
- void testSerialize_StreamInitiationFileInfo() {
- std::string expected = "<file"
- " date=\"1969-07-21T02:56:15Z\""
- " hash=\"552da749930852c69ae5d2141d3766b1\""
- " name=\"test.txt\""
- " size=\"1022\""
- " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
- "<desc>This is a test. If this were a real file...</desc>"
- "<range/>"
- "</file>";
-
- StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
- fileInfo->setDate(stringToDateTime("1969-07-21T02:56:15Z"));
- fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
- fileInfo->setSize(1022);
- fileInfo->setName("test.txt");
- fileInfo->setDescription("This is a test. If this were a real file...");
- fileInfo->setSupportsRangeRequests(true);
-
- boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
- }
-
- void testSerialize_StreamInitiationFileInfoRange() {
- std::string expected = "<file hash=\"552da749930852c69ae5d2141d3766b1\""
- " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
- "<range offset=\"270336\"/>"
- "</file>";
-
- StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
- fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
- fileInfo->setSupportsRangeRequests(true);
- fileInfo->setRangeOffset(270336);
-
- boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
- }
-
-
- // IBB Transport Method Examples
-
- // http://xmpp.org/extensions/xep-0261.html#example-1
- void testSerialize_Xep0261_Example1() {
- std::string expected =
- "<jingle action=\"session-initiate\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<content creator=\"initiator\" name=\"ex\">"
- "<transport block-size=\"4096\""
- " sid=\"ch3d9s71\""
- " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
- "</content>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::SessionInitiate);
- payload->setSessionID("a73sjjvkla37jfea");
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
-
- JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
- transport->setBlockSize(4096);
- transport->setSessionID("ch3d9s71");
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(JingleContentPayload::InitiatorCreator);
- content->setName("ex");
- content->addTransport(transport);
-
- payload->addPayload(content);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0261.html#example-9
- void testSerialize_Xep0261_Example9() {
- std::string expected =
- "<jingle action=\"transport-info\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<content creator=\"initiator\" name=\"ex\">"
- "<transport block-size=\"2048\""
- " sid=\"bt8a71h6\""
- " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
- "</content>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::TransportInfo);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("a73sjjvkla37jfea");
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(JingleContentPayload::InitiatorCreator);
- content->setName("ex");
-
- JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
- transport->setBlockSize(2048);
- transport->setSessionID("bt8a71h6");
-
- content->addTransport(transport);
- payload->addPayload(content);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0261.html#example-13
- void testSerialize_Xep0261_Example13() {
- std::string expected =
- "<jingle action=\"session-terminate\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<reason><success/></reason>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::SessionTerminate);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("a73sjjvkla37jfea");
- payload->setReason(JinglePayload::Reason(JinglePayload::Reason::Success));
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-1
- void testSerialize_Xep0234_Example1() {
- std::string expected = "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
- "<file>"
- "<date>1969-07-21T02:56:15Z</date>"
- "<desc>This is a test. If this were a real file...</desc>"
- "<name>test.txt</name>"
- "<range/>"
- "<size>1022</size>"
- "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
- "</file>"
- "</description>";
- JingleFileTransferDescription::ref desc = boost::make_shared<JingleFileTransferDescription>();
- JingleFileTransferFileInfo fileInfo;
-
- fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
- fileInfo.addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
- fileInfo.setSize(1022);
- fileInfo.setName("test.txt");
- fileInfo.setDescription("This is a test. If this were a real file...");
- fileInfo.setSupportsRangeRequests(true);
-
- desc->setFileInfo(fileInfo);
-
- CPPUNIT_ASSERT_EQUAL(expected, boost::make_shared<JingleFileTransferDescriptionSerializer>()->serialize(desc));
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-3
- void testSerialize_Xep0234_Example3() {
- std::string expected =
- "<jingle action=\"session-accept\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"851ba2\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<content creator=\"initiator\" name=\"a-file-offer\">"
- "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
- "<file>"
- "<date>1969-07-21T02:56:15Z</date>"
- "<desc>This is a test. If this were a real file...</desc>"
- "<name>test.txt</name>"
- "<range/>"
- "<size>1022</size>"
- "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
- "</file>"
- "</description>"
- /*"<transport xmlns=\"urn:xmpp:jingle:transports:s5b:1\""
- " mode=\"tcp\""
- " sid=\"vj3hs98y\">"
- "<candidate cid=\"ht567dq\""
- " host=\"192.169.1.10\""
- " jid=\"juliet@capulet.lit/balcony\""
- " port=\"6539\""
- " priority=\"8257636\""
- " type=\"direct\"/>"
- "<candidate cid=\"hr65dqyd\""
- " host=\"134.102.201.180\""
- " jid=\"juliet@capulet.lit/balcony\""
- " port=\"16453\""
- " priority=\"7929856\""
- " type=\"assisted\"/>"
- "<candidate cid=\"grt654q2\""
- " host=\"2001:638:708:30c9:219:d1ff:fea4:a17d\""
- " jid=\"juliet@capulet.lit/balcony\""
- " port=\"6539\""
- " priority=\"8257606\""
- " type=\"direct\"/>"
- "</transport>"*/
- "</content>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::SessionAccept);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("851ba2");
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(JingleContentPayload::InitiatorCreator);
- content->setName("a-file-offer");
-
- JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>();
- JingleFileTransferFileInfo fileInfo;
- fileInfo.setName("test.txt");
- fileInfo.setSize(1022);
- fileInfo.addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
- fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
- fileInfo.setDescription("This is a test. If this were a real file...");
- fileInfo.setSupportsRangeRequests(true);
-
- description->setFileInfo(fileInfo);
- content->addDescription(description);
- payload->addPayload(content);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-5
- void testSerialize_Xep0234_Example5() {
- std::string expected =
- "<jingle"
- " action=\"transport-info\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<content creator=\"initiator\" name=\"ex\"/>"
- /*"<transport"
- " sid=\"vj3hs98y\""
- " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
- "<candidate-used cid=\"hr65dqyd\"/>"
- "</transport>"*/
- //"</content>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::TransportInfo);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("a73sjjvkla37jfea");
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(JingleContentPayload::InitiatorCreator);
- content->setName("ex");
- payload->addPayload(content);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0234.html#example-8
- void testSerialize_Xep0234_Example8() {
- std::string expected =
- "<jingle"
- " action=\"session-info\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<checksum xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
- "<file>"
- "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
- "</file>"
- "</checksum>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::SessionInfo);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("a73sjjvkla37jfea");
-
- JingleFileTransferHash::ref hash = boost::make_shared<JingleFileTransferHash>();
- hash->getFileInfo().addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
-
- payload->addPayload(hash);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- // http://xmpp.org/extensions/xep-0260.html#example-1
- void testSerialize_Xep0260_Example1() {
- std::string expected =
- "<jingle"
- " action=\"session-initiate\""
- " initiator=\"romeo@montague.lit/orchard\""
- " sid=\"a73sjjvkla37jfea\""
- " xmlns=\"urn:xmpp:jingle:1\">"
- "<content creator=\"initiator\" name=\"ex\">"
- "<transport"
- " dstaddr=\"1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba\""
- " mode=\"tcp\""
- " sid=\"vj3hs98y\""
- " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
- "<candidate cid=\"hft54dqy\""
- " host=\"192.168.4.1\""
- " jid=\"romeo@montague.lit/orchard\""
- " port=\"5086\""
- " priority=\"8257636\""
- " type=\"direct\"/>"
- "<candidate cid=\"hutr46fe\""
- " host=\"24.24.24.1\""
- " jid=\"romeo@montague.lit/orchard\""
- " port=\"5087\""
- " priority=\"8258636\""
- " type=\"direct\"/>"
- "</transport>"
- "</content>"
- "</jingle>";
-
- JinglePayload::ref payload = boost::make_shared<JinglePayload>();
- payload->setAction(JinglePayload::SessionInitiate);
- payload->setInitiator(JID("romeo@montague.lit/orchard"));
- payload->setSessionID("a73sjjvkla37jfea");
-
- JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
- content->setCreator(JingleContentPayload::InitiatorCreator);
- content->setName("ex");
-
- JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
- transport->setMode(JingleS5BTransportPayload::TCPMode);
- transport->setDstAddr("1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba");
- transport->setSessionID("vj3hs98y");
-
- JingleS5BTransportPayload::Candidate candidate1;
- candidate1.cid = "hft54dqy";
- candidate1.hostPort = HostAddressPort(HostAddress("192.168.4.1"), 5086);
- candidate1.jid = JID("romeo@montague.lit/orchard");
- candidate1.priority = 8257636;
- candidate1.type = JingleS5BTransportPayload::Candidate::DirectType;
- transport->addCandidate(candidate1);
-
- JingleS5BTransportPayload::Candidate candidate2;
- candidate2.cid = "hutr46fe";
- candidate2.hostPort = HostAddressPort(HostAddress("24.24.24.1"), 5087);
- candidate2.jid = JID("romeo@montague.lit/orchard");
- candidate2.priority = 8258636;
- candidate2.type = JingleS5BTransportPayload::Candidate::DirectType;
- transport->addCandidate(candidate2);
-
- content->addTransport(transport);
-
- payload->addPayload(content);
-
- CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
- }
-
- private:
- FullPayloadSerializerCollection collection;
+ CPPUNIT_TEST_SUITE(JingleSerializersTest);
+ CPPUNIT_TEST(testSerialize_StreamInitiationFileInfo);
+ CPPUNIT_TEST(testSerialize_StreamInitiationFileInfoRange);
+
+ CPPUNIT_TEST(testSerialize_Xep0261_Example1);
+ CPPUNIT_TEST(testSerialize_Xep0261_Example9);
+ CPPUNIT_TEST(testSerialize_Xep0261_Example13);
+
+ CPPUNIT_TEST(testSerialize_Xep0234_Example1);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example3);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example5);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example8);
+
+ CPPUNIT_TEST(testSerialize_Xep0260_Example1);
+
+ CPPUNIT_TEST_SUITE_END();
+
+ boost::shared_ptr<JinglePayloadSerializer> createTestling() {
+ return boost::make_shared<JinglePayloadSerializer>(&collection);
+ }
+
+
+ public:
+ void testSerialize_StreamInitiationFileInfo() {
+ std::string expected = "<file"
+ " date=\"1969-07-21T02:56:15Z\""
+ " hash=\"552da749930852c69ae5d2141d3766b1\""
+ " name=\"test.txt\""
+ " size=\"1022\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<range/>"
+ "</file>";
+
+ StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
+ fileInfo->setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo->setSize(1022);
+ fileInfo->setName("test.txt");
+ fileInfo->setDescription("This is a test. If this were a real file...");
+ fileInfo->setSupportsRangeRequests(true);
+
+ boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
+ }
+
+ void testSerialize_StreamInitiationFileInfoRange() {
+ std::string expected = "<file hash=\"552da749930852c69ae5d2141d3766b1\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<range offset=\"270336\"/>"
+ "</file>";
+
+ StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
+ fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo->setSupportsRangeRequests(true);
+ fileInfo->setRangeOffset(270336);
+
+ boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
+ }
+
+
+ // IBB Transport Method Examples
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testSerialize_Xep0261_Example1() {
+ std::string expected =
+ "<jingle action=\"session-initiate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport block-size=\"4096\""
+ " sid=\"ch3d9s71\""
+ " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setSessionID("a73sjjvkla37jfea");
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+
+ JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
+ transport->setBlockSize(4096);
+ transport->setSessionID("ch3d9s71");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+ content->addTransport(transport);
+
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-9
+ void testSerialize_Xep0261_Example9() {
+ std::string expected =
+ "<jingle action=\"transport-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport block-size=\"2048\""
+ " sid=\"bt8a71h6\""
+ " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
+ transport->setBlockSize(2048);
+ transport->setSessionID("bt8a71h6");
+
+ content->addTransport(transport);
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-13
+ void testSerialize_Xep0261_Example13() {
+ std::string expected =
+ "<jingle action=\"session-terminate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<reason><success/></reason>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionTerminate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+ payload->setReason(JinglePayload::Reason(JinglePayload::Reason::Success));
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-1
+ void testSerialize_Xep0234_Example1() {
+ std::string expected = "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
+ "<file>"
+ "<date>1969-07-21T02:56:15Z</date>"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<name>test.txt</name>"
+ "<range/>"
+ "<size>1022</size>"
+ "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
+ "</file>"
+ "</description>";
+ JingleFileTransferDescription::ref desc = boost::make_shared<JingleFileTransferDescription>();
+ JingleFileTransferFileInfo fileInfo;
+
+ fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo.addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
+ fileInfo.setSize(1022);
+ fileInfo.setName("test.txt");
+ fileInfo.setDescription("This is a test. If this were a real file...");
+ fileInfo.setSupportsRangeRequests(true);
+
+ desc->setFileInfo(fileInfo);
+
+ CPPUNIT_ASSERT_EQUAL(expected, boost::make_shared<JingleFileTransferDescriptionSerializer>()->serialize(desc));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-3
+ void testSerialize_Xep0234_Example3() {
+ std::string expected =
+ "<jingle action=\"session-accept\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"851ba2\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"a-file-offer\">"
+ "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
+ "<file>"
+ "<date>1969-07-21T02:56:15Z</date>"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<name>test.txt</name>"
+ "<range/>"
+ "<size>1022</size>"
+ "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
+ "</file>"
+ "</description>"
+ /*"<transport xmlns=\"urn:xmpp:jingle:transports:s5b:1\""
+ " mode=\"tcp\""
+ " sid=\"vj3hs98y\">"
+ "<candidate cid=\"ht567dq\""
+ " host=\"192.169.1.10\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257636\""
+ " type=\"direct\"/>"
+ "<candidate cid=\"hr65dqyd\""
+ " host=\"134.102.201.180\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"16453\""
+ " priority=\"7929856\""
+ " type=\"assisted\"/>"
+ "<candidate cid=\"grt654q2\""
+ " host=\"2001:638:708:30c9:219:d1ff:fea4:a17d\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257606\""
+ " type=\"direct\"/>"
+ "</transport>"*/
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionAccept);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("851ba2");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("a-file-offer");
+
+ JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>();
+ JingleFileTransferFileInfo fileInfo;
+ fileInfo.setName("test.txt");
+ fileInfo.setSize(1022);
+ fileInfo.addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
+ fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo.setDescription("This is a test. If this were a real file...");
+ fileInfo.setSupportsRangeRequests(true);
+
+ description->setFileInfo(fileInfo);
+ content->addDescription(description);
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-5
+ void testSerialize_Xep0234_Example5() {
+ std::string expected =
+ "<jingle"
+ " action=\"transport-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\"/>"
+ /*"<transport"
+ " sid=\"vj3hs98y\""
+ " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
+ "<candidate-used cid=\"hr65dqyd\"/>"
+ "</transport>"*/
+ //"</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-8
+ void testSerialize_Xep0234_Example8() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<checksum xmlns=\"urn:xmpp:jingle:apps:file-transfer:4\">"
+ "<file>"
+ "<hash algo=\"sha-1\" xmlns=\"urn:xmpp:hashes:1\">VS2nSZMIUsaa5dIUHTdmsQ==</hash>"
+ "</file>"
+ "</checksum>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleFileTransferHash::ref hash = boost::make_shared<JingleFileTransferHash>();
+ hash->getFileInfo().addHash(HashElement("sha-1", Base64::decode("VS2nSZMIUsaa5dIUHTdmsQ==")));
+
+ payload->addPayload(hash);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-1
+ void testSerialize_Xep0260_Example1() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-initiate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport"
+ " dstaddr=\"1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba\""
+ " mode=\"tcp\""
+ " sid=\"vj3hs98y\""
+ " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
+ "<candidate cid=\"hft54dqy\""
+ " host=\"192.168.4.1\""
+ " jid=\"romeo@montague.lit/orchard\""
+ " port=\"5086\""
+ " priority=\"8257636\""
+ " type=\"direct\"/>"
+ "<candidate cid=\"hutr46fe\""
+ " host=\"24.24.24.1\""
+ " jid=\"romeo@montague.lit/orchard\""
+ " port=\"5087\""
+ " priority=\"8258636\""
+ " type=\"direct\"/>"
+ "</transport>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
+ transport->setMode(JingleS5BTransportPayload::TCPMode);
+ transport->setDstAddr("1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba");
+ transport->setSessionID("vj3hs98y");
+
+ JingleS5BTransportPayload::Candidate candidate1;
+ candidate1.cid = "hft54dqy";
+ candidate1.hostPort = HostAddressPort(HostAddress("192.168.4.1"), 5086);
+ candidate1.jid = JID("romeo@montague.lit/orchard");
+ candidate1.priority = 8257636;
+ candidate1.type = JingleS5BTransportPayload::Candidate::DirectType;
+ transport->addCandidate(candidate1);
+
+ JingleS5BTransportPayload::Candidate candidate2;
+ candidate2.cid = "hutr46fe";
+ candidate2.hostPort = HostAddressPort(HostAddress("24.24.24.1"), 5087);
+ candidate2.jid = JID("romeo@montague.lit/orchard");
+ candidate2.priority = 8258636;
+ candidate2.type = JingleS5BTransportPayload::Candidate::DirectType;
+ transport->addCandidate(candidate2);
+
+ content->addTransport(transport);
+
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ private:
+ FullPayloadSerializerCollection collection;
};
CPPUNIT_TEST_SUITE_REGISTRATION(JingleSerializersTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp
index caa904e..0eda01c 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp
@@ -15,50 +15,50 @@
using namespace Swift;
class MAMFinSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MAMFinSerializerTest);
- CPPUNIT_TEST(testSerialize_XEP0313_Exmaple1);
- CPPUNIT_TEST(testSerialize_XEP0313_Exmaple9);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(MAMFinSerializerTest);
+ CPPUNIT_TEST(testSerialize_XEP0313_Exmaple1);
+ CPPUNIT_TEST(testSerialize_XEP0313_Exmaple9);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize_XEP0313_Exmaple1() {
- MAMFinSerializer serializer;
+ public:
+ void testSerialize_XEP0313_Exmaple1() {
+ MAMFinSerializer serializer;
- boost::shared_ptr<MAMFin> fin = boost::make_shared<MAMFin>();
- fin->setQueryID("f27");
+ boost::shared_ptr<MAMFin> fin = boost::make_shared<MAMFin>();
+ fin->setQueryID("f27");
- std::string expectedResult =
- "<fin queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\"/>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(fin));
- }
+ std::string expectedResult =
+ "<fin queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\"/>";
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(fin));
+ }
- void testSerialize_XEP0313_Exmaple9() {
- MAMFinSerializer serializer;
+ void testSerialize_XEP0313_Exmaple9() {
+ MAMFinSerializer serializer;
- boost::shared_ptr<MAMFin> fin = boost::make_shared<MAMFin>();
- fin->setComplete(true);
+ boost::shared_ptr<MAMFin> fin = boost::make_shared<MAMFin>();
+ fin->setComplete(true);
- boost::shared_ptr<ResultSet> set = boost::make_shared<ResultSet>();
- set->setFirstID(std::string("23452-4534-1"));
- set->setFirstIDIndex(0);
- set->setLastID(std::string("390-2342-22"));
- set->setCount(16);
+ boost::shared_ptr<ResultSet> set = boost::make_shared<ResultSet>();
+ set->setFirstID(std::string("23452-4534-1"));
+ set->setFirstIDIndex(0);
+ set->setLastID(std::string("390-2342-22"));
+ set->setCount(16);
- fin->setResultSet(set);
+ fin->setResultSet(set);
- std::string expectedResult =
- "<fin complete=\"true\" xmlns=\"urn:xmpp:mam:0\">"
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<count>16</count>"
- "<first index=\"0\">23452-4534-1</first>"
- "<last>390-2342-22</last>"
- "</set>"
- "</fin>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(fin));
- }
+ std::string expectedResult =
+ "<fin complete=\"true\" xmlns=\"urn:xmpp:mam:0\">"
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<count>16</count>"
+ "<first index=\"0\">23452-4534-1</first>"
+ "<last>390-2342-22</last>"
+ "</set>"
+ "</fin>";
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(fin));
+ }
- private:
- FullPayloadSerializerCollection serializers;
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MAMFinSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp
index d9f7f12..faf788d 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp
@@ -19,55 +19,55 @@
using namespace Swift;
class MAMQuerySerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MAMQuerySerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(MAMQuerySerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize() {
- MAMQuerySerializer serializer;
+ public:
+ void testSerialize() {
+ MAMQuerySerializer serializer;
- boost::shared_ptr<Form> parameters(boost::make_shared<Form>());
+ boost::shared_ptr<Form> parameters(boost::make_shared<Form>());
- boost::shared_ptr<FormField> fieldType = boost::make_shared<FormField>(FormField::TextSingleType);
- fieldType->setName("FORM_TYPE");
- fieldType->addValue("urn:xmpp:mam:0");
- parameters->addField(fieldType);
+ boost::shared_ptr<FormField> fieldType = boost::make_shared<FormField>(FormField::TextSingleType);
+ fieldType->setName("FORM_TYPE");
+ fieldType->addValue("urn:xmpp:mam:0");
+ parameters->addField(fieldType);
- boost::shared_ptr<FormField> fieldStart = boost::make_shared<FormField>(FormField::TextSingleType);
- fieldStart->setName("start");
- fieldStart->addValue("2010-08-07T00:00:00Z");
- parameters->addField(fieldStart);
+ boost::shared_ptr<FormField> fieldStart = boost::make_shared<FormField>(FormField::TextSingleType);
+ fieldStart->setName("start");
+ fieldStart->addValue("2010-08-07T00:00:00Z");
+ parameters->addField(fieldStart);
- boost::shared_ptr<ResultSet> set = boost::make_shared<ResultSet>();
- set->setMaxItems(10);
+ boost::shared_ptr<ResultSet> set = boost::make_shared<ResultSet>();
+ set->setMaxItems(10);
- boost::shared_ptr<MAMQuery> query(boost::make_shared<MAMQuery>());
- query->setQueryID(std::string("id0"));
- query->setNode(std::string("node1"));
- query->setForm(parameters);
- query->setResultSet(set);
+ boost::shared_ptr<MAMQuery> query(boost::make_shared<MAMQuery>());
+ query->setQueryID(std::string("id0"));
+ query->setNode(std::string("node1"));
+ query->setForm(parameters);
+ query->setResultSet(set);
- std::string expectedResult =
- "<query node=\"node1\" queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\">"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<field type=\"text-single\" var=\"FORM_TYPE\">"
- "<value>urn:xmpp:mam:0</value>"
- "</field>"
- "<field type=\"text-single\" var=\"start\">"
- "<value>2010-08-07T00:00:00Z</value>"
- "</field>"
- "</x>"
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<max>10</max>"
- "</set>"
- "</query>";
+ std::string expectedResult =
+ "<query node=\"node1\" queryid=\"id0\" xmlns=\"urn:xmpp:mam:0\">"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<field type=\"text-single\" var=\"FORM_TYPE\">"
+ "<value>urn:xmpp:mam:0</value>"
+ "</field>"
+ "<field type=\"text-single\" var=\"start\">"
+ "<value>2010-08-07T00:00:00Z</value>"
+ "</field>"
+ "</x>"
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<max>10</max>"
+ "</set>"
+ "</query>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(query));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(query));
+ }
- private:
- FullPayloadSerializerCollection serializers;
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MAMQuerySerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp
index c829f3d..40ca27d 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp
@@ -19,44 +19,44 @@
using namespace Swift;
class MAMResultSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(MAMResultSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- MAMResultSerializer serializer(&serializers);
-
- boost::shared_ptr<Message> message(boost::make_shared<Message>());
- message->setType(Message::Chat);
- message->setTo(JID("juliet@capulet.lit/balcony"));
- message->setFrom(JID("romeo@montague.lit/orchard"));
- message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
-
- boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
- forwarded->setStanza(message);
- forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
-
- boost::shared_ptr<MAMResult> result(boost::make_shared<MAMResult>());
- result->setID("28482-98726-73623");
- result->setQueryID(std::string("f27"));
- result->setPayload(forwarded);
-
- std::string expectedResult =
- "<result id=\"28482-98726-73623\" queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\">"
- "<forwarded xmlns=\"urn:xmpp:forward:0\">"
- "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
- "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
- "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
- "</message>"
- "</forwarded>"
- "</result>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(result));
- }
-
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_TEST_SUITE(MAMResultSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ MAMResultSerializer serializer(&serializers);
+
+ boost::shared_ptr<Message> message(boost::make_shared<Message>());
+ message->setType(Message::Chat);
+ message->setTo(JID("juliet@capulet.lit/balcony"));
+ message->setFrom(JID("romeo@montague.lit/orchard"));
+ message->setBody("Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.");
+
+ boost::shared_ptr<Forwarded> forwarded(boost::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(boost::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ boost::shared_ptr<MAMResult> result(boost::make_shared<MAMResult>());
+ result->setID("28482-98726-73623");
+ result->setQueryID(std::string("f27"));
+ result->setPayload(forwarded);
+
+ std::string expectedResult =
+ "<result id=\"28482-98726-73623\" queryid=\"f27\" xmlns=\"urn:xmpp:mam:0\">"
+ "<forwarded xmlns=\"urn:xmpp:forward:0\">"
+ "<delay stamp=\"2010-07-10T23:08:25Z\" xmlns=\"urn:xmpp:delay\"/>"
+ "<message from=\"romeo@montague.lit/orchard\" to=\"juliet@capulet.lit/balcony\" type=\"chat\" xmlns=\"jabber:client\">"
+ "<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>"
+ "</message>"
+ "</forwarded>"
+ "</result>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(result));
+ }
+
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(MAMResultSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp
index 2c0baff..fc6b346 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp
@@ -15,25 +15,25 @@ using namespace Swift;
class MUCAdminPayloadSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MUCAdminPayloadSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- MUCAdminPayloadSerializerTest() {}
-
- void testSerialize() {
- MUCAdminPayloadSerializer testling;
- boost::shared_ptr<MUCAdminPayload> admin = boost::make_shared<MUCAdminPayload>();
- MUCItem item;
- item.affiliation = MUCOccupant::Owner;
- item.role = MUCOccupant::Visitor;
- item.reason = "malice";
- item.actor = JID("kev@tester.lit");
- admin->addItem(item);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<query xmlns=\"http://jabber.org/protocol/muc#admin\"><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item></query>"), testling.serialize(admin));
- }
+ CPPUNIT_TEST_SUITE(MUCAdminPayloadSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ MUCAdminPayloadSerializerTest() {}
+
+ void testSerialize() {
+ MUCAdminPayloadSerializer testling;
+ boost::shared_ptr<MUCAdminPayload> admin = boost::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.affiliation = MUCOccupant::Owner;
+ item.role = MUCOccupant::Visitor;
+ item.reason = "malice";
+ item.actor = JID("kev@tester.lit");
+ admin->addItem(item);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<query xmlns=\"http://jabber.org/protocol/muc#admin\"><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item></query>"), testling.serialize(admin));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(MUCAdminPayloadSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp
index 7bd729d..223e7d9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp
@@ -13,14 +13,14 @@
namespace Swift {
std::string PayloadsSerializer::serialize(boost::shared_ptr<Payload> payload) {
- PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
- if (serializer) {
- return serializer->serialize(payload);
- }
- else {
- CPPUNIT_ASSERT(false);
- return "";
- }
+ PayloadSerializer* serializer = serializers.getPayloadSerializer(payload);
+ if (serializer) {
+ return serializer->serialize(payload);
+ }
+ else {
+ CPPUNIT_ASSERT(false);
+ return "";
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h
index 6abe396..827e9da 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h
@@ -14,11 +14,11 @@
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
namespace Swift {
- class PayloadsSerializer {
- public:
- std::string serialize(boost::shared_ptr<Payload> payload);
+ class PayloadsSerializer {
+ public:
+ std::string serialize(boost::shared_ptr<Payload> payload);
- private:
- FullPayloadSerializerCollection serializers;
- };
+ private:
+ FullPayloadSerializerCollection serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp
index 272c25f..19971c2 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp
@@ -13,19 +13,19 @@ using namespace Swift;
class PrioritySerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(PrioritySerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PrioritySerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- PrioritySerializerTest() {}
+ public:
+ PrioritySerializerTest() {}
- void testSerialize() {
- PrioritySerializer testling;
- boost::shared_ptr<Priority> priority(new Priority(-113));
+ void testSerialize() {
+ PrioritySerializer testling;
+ boost::shared_ptr<Priority> priority(new Priority(-113));
- CPPUNIT_ASSERT_EQUAL(std::string("<priority>-113</priority>"), testling.serialize(priority));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<priority>-113</priority>"), testling.serialize(priority));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PrioritySerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp
index 5236821..3b115b3 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp
@@ -14,37 +14,37 @@
using namespace Swift;
class PrivateStorageSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PrivateStorageSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- PrivateStorageSerializerTest() {}
-
- void testSerialize() {
- PayloadsSerializer serializer;
-
- boost::shared_ptr<PrivateStorage> privateStorage(new PrivateStorage());
- boost::shared_ptr<Storage> storage(new Storage());
- Storage::Room room;
- room.name = "Swift";
- room.jid = JID("swift@rooms.swift.im");
- room.nick = "Alice";
- storage->addRoom(room);
- privateStorage->setPayload(storage);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<query xmlns=\"jabber:iq:private\">"
- "<storage xmlns=\"storage:bookmarks\">"
- "<conference "
- "autojoin=\"0\" "
- "jid=\"swift@rooms.swift.im\" "
- "name=\"Swift\">"
- "<nick>Alice</nick>"
- "</conference>"
- "</storage>"
- "</query>"), serializer.serialize(privateStorage));
- }
+ CPPUNIT_TEST_SUITE(PrivateStorageSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ PrivateStorageSerializerTest() {}
+
+ void testSerialize() {
+ PayloadsSerializer serializer;
+
+ boost::shared_ptr<PrivateStorage> privateStorage(new PrivateStorage());
+ boost::shared_ptr<Storage> storage(new Storage());
+ Storage::Room room;
+ room.name = "Swift";
+ room.jid = JID("swift@rooms.swift.im");
+ room.nick = "Alice";
+ storage->addRoom(room);
+ privateStorage->setPayload(storage);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<query xmlns=\"jabber:iq:private\">"
+ "<storage xmlns=\"storage:bookmarks\">"
+ "<conference "
+ "autojoin=\"0\" "
+ "jid=\"swift@rooms.swift.im\" "
+ "name=\"Swift\">"
+ "<nick>Alice</nick>"
+ "</conference>"
+ "</storage>"
+ "</query>"), serializer.serialize(privateStorage));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PrivateStorageSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp
index c871a4e..b835421 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp
@@ -17,43 +17,43 @@
using namespace Swift;
class PubSubItemSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PubSubItemSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerializeEmptyID);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PubSubItemSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerializeEmptyID);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize() {
- PubSubItemSerializer serializer(&serializers);
+ public:
+ void testSerialize() {
+ PubSubItemSerializer serializer(&serializers);
- boost::shared_ptr<RawXMLPayload> payload(boost::make_shared<RawXMLPayload>());
- payload->setRawXML("<payload xmlns=\"tmp\"/>");
+ boost::shared_ptr<RawXMLPayload> payload(boost::make_shared<RawXMLPayload>());
+ payload->setRawXML("<payload xmlns=\"tmp\"/>");
- boost::shared_ptr<PubSubItem> item(boost::make_shared<PubSubItem>());
- item->addData(payload);
- item->setID("pubsub-item-1");
+ boost::shared_ptr<PubSubItem> item(boost::make_shared<PubSubItem>());
+ item->addData(payload);
+ item->setID("pubsub-item-1");
- std::string expectedResult =
- "<item id=\"pubsub-item-1\" xmlns=\"http://jabber.org/protocol/pubsub\">"
- "<payload xmlns=\"tmp\"/>"
- "</item>";
+ std::string expectedResult =
+ "<item id=\"pubsub-item-1\" xmlns=\"http://jabber.org/protocol/pubsub\">"
+ "<payload xmlns=\"tmp\"/>"
+ "</item>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(item));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(item));
+ }
- void testSerializeEmptyID() {
- PubSubItemSerializer serializer(&serializers);
+ void testSerializeEmptyID() {
+ PubSubItemSerializer serializer(&serializers);
- boost::shared_ptr<PubSubItem> item(boost::make_shared<PubSubItem>());
+ boost::shared_ptr<PubSubItem> item(boost::make_shared<PubSubItem>());
- std::string expectedResult =
- "<item xmlns=\"http://jabber.org/protocol/pubsub\"/>";
+ std::string expectedResult =
+ "<item xmlns=\"http://jabber.org/protocol/pubsub\"/>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(item));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(item));
+ }
- private:
- FullPayloadSerializerCollection serializers;
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PubSubItemSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp
index d557a89..fa99202 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp
@@ -17,61 +17,61 @@
using namespace Swift;
class PubSubItemsSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PubSubItemsSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerializeEmptyItems);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PubSubItemsSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerializeEmptyItems);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize() {
- PubSubItemsSerializer serializer(&serializers);
+ public:
+ void testSerialize() {
+ PubSubItemsSerializer serializer(&serializers);
- boost::shared_ptr<RawXMLPayload> payload1(boost::make_shared<RawXMLPayload>());
- payload1->setRawXML("<payload xmlns=\"tmp\"/>");
+ boost::shared_ptr<RawXMLPayload> payload1(boost::make_shared<RawXMLPayload>());
+ payload1->setRawXML("<payload xmlns=\"tmp\"/>");
- boost::shared_ptr<PubSubItem> item1(boost::make_shared<PubSubItem>());
- item1->addData(payload1);
- item1->setID("pubsub-item-1");
+ boost::shared_ptr<PubSubItem> item1(boost::make_shared<PubSubItem>());
+ item1->addData(payload1);
+ item1->setID("pubsub-item-1");
- boost::shared_ptr<RawXMLPayload> payload2(boost::make_shared<RawXMLPayload>());
- payload2->setRawXML("<payload xmlns=\"other-tmp\"/>");
+ boost::shared_ptr<RawXMLPayload> payload2(boost::make_shared<RawXMLPayload>());
+ payload2->setRawXML("<payload xmlns=\"other-tmp\"/>");
- boost::shared_ptr<PubSubItem> item2(boost::make_shared<PubSubItem>());
- item2->addData(payload2);
- item2->setID("pubsub-item-2");
+ boost::shared_ptr<PubSubItem> item2(boost::make_shared<PubSubItem>());
+ item2->addData(payload2);
+ item2->setID("pubsub-item-2");
- boost::shared_ptr<PubSubItems> items(boost::make_shared<PubSubItems>());
- items->setNode("test-node");
- items->setSubscriptionID(std::string("sub-id"));
- items->addItem(item1);
- items->addItem(item2);
+ boost::shared_ptr<PubSubItems> items(boost::make_shared<PubSubItems>());
+ items->setNode("test-node");
+ items->setSubscriptionID(std::string("sub-id"));
+ items->addItem(item1);
+ items->addItem(item2);
- std::string expectedResult =
- "<items node=\"test-node\" subid=\"sub-id\" xmlns=\"http://jabber.org/protocol/pubsub\">"
- "<item id=\"pubsub-item-1\" xmlns=\"http://jabber.org/protocol/pubsub\">"
- "<payload xmlns=\"tmp\"/>"
- "</item>"
- "<item id=\"pubsub-item-2\" xmlns=\"http://jabber.org/protocol/pubsub\">"
- "<payload xmlns=\"other-tmp\"/>"
- "</item>"
- "</items>";
+ std::string expectedResult =
+ "<items node=\"test-node\" subid=\"sub-id\" xmlns=\"http://jabber.org/protocol/pubsub\">"
+ "<item id=\"pubsub-item-1\" xmlns=\"http://jabber.org/protocol/pubsub\">"
+ "<payload xmlns=\"tmp\"/>"
+ "</item>"
+ "<item id=\"pubsub-item-2\" xmlns=\"http://jabber.org/protocol/pubsub\">"
+ "<payload xmlns=\"other-tmp\"/>"
+ "</item>"
+ "</items>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(items));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(items));
+ }
- void testSerializeEmptyItems() {
- PubSubItemsSerializer serializer(&serializers);
+ void testSerializeEmptyItems() {
+ PubSubItemsSerializer serializer(&serializers);
- boost::shared_ptr<PubSubItems> items(boost::make_shared<PubSubItems>());
+ boost::shared_ptr<PubSubItems> items(boost::make_shared<PubSubItems>());
- std::string expectedResult =
- "<items node=\"\" xmlns=\"http://jabber.org/protocol/pubsub\"/>";
+ std::string expectedResult =
+ "<items node=\"\" xmlns=\"http://jabber.org/protocol/pubsub\"/>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(items));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(items));
+ }
- private:
- FullPayloadSerializerCollection serializers;
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PubSubItemsSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
index 6a51182..1f40b26 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
@@ -18,19 +18,19 @@
using namespace Swift;
class ReplaceSerializerTest: public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ReplaceSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- ReplaceSerializerTest() {}
-
- void testSerialize() {
- ReplaceSerializer testling;
- boost::shared_ptr<Replace> replace(new Replace());
- replace->setID("bad1");
- CPPUNIT_ASSERT_EQUAL(std::string("<replace id = 'bad1' xmlns='urn:xmpp:message-correct:0'/>"), testling.serialize(replace));
- }
+ CPPUNIT_TEST_SUITE(ReplaceSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ ReplaceSerializerTest() {}
+
+ void testSerialize() {
+ ReplaceSerializer testling;
+ boost::shared_ptr<Replace> replace(new Replace());
+ replace->setID("bad1");
+ CPPUNIT_ASSERT_EQUAL(std::string("<replace id = 'bad1' xmlns='urn:xmpp:message-correct:0'/>"), testling.serialize(replace));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ReplaceSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp
index 718370f..9bc637f 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp
@@ -13,43 +13,43 @@ using namespace Swift;
class ResourceBindSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(ResourceBindSerializerTest);
- CPPUNIT_TEST(testSerialize_JID);
- CPPUNIT_TEST(testSerialize_Resource);
- CPPUNIT_TEST(testSerialize_Empty);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- ResourceBindSerializerTest() {}
-
- void testSerialize_JID() {
- ResourceBindSerializer testling;
- boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
- resourceBind->setJID(JID("somenode@example.com/someresource"));
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"
- "<jid>somenode@example.com/someresource</jid>"
- "</bind>"), testling.serialize(resourceBind));
- }
-
- void testSerialize_Resource() {
- ResourceBindSerializer testling;
- boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
- resourceBind->setResource("someresource");
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"
- "<resource>someresource</resource>"
- "</bind>"), testling.serialize(resourceBind));
- }
-
- void testSerialize_Empty() {
- ResourceBindSerializer testling;
- boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
-
- CPPUNIT_ASSERT_EQUAL(std::string("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"), testling.serialize(resourceBind));
- }
+ CPPUNIT_TEST_SUITE(ResourceBindSerializerTest);
+ CPPUNIT_TEST(testSerialize_JID);
+ CPPUNIT_TEST(testSerialize_Resource);
+ CPPUNIT_TEST(testSerialize_Empty);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ ResourceBindSerializerTest() {}
+
+ void testSerialize_JID() {
+ ResourceBindSerializer testling;
+ boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
+ resourceBind->setJID(JID("somenode@example.com/someresource"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"
+ "<jid>somenode@example.com/someresource</jid>"
+ "</bind>"), testling.serialize(resourceBind));
+ }
+
+ void testSerialize_Resource() {
+ ResourceBindSerializer testling;
+ boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
+ resourceBind->setResource("someresource");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"
+ "<resource>someresource</resource>"
+ "</bind>"), testling.serialize(resourceBind));
+ }
+
+ void testSerialize_Empty() {
+ ResourceBindSerializer testling;
+ boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"), testling.serialize(resourceBind));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResourceBindSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp
index b44ac0b..0b0163e 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp
@@ -16,103 +16,103 @@
using namespace Swift;
class ResultSetSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ResultSetSerializerTest);
- CPPUNIT_TEST(testSerializeFull);
- CPPUNIT_TEST(testSerializeMaxItems);
- CPPUNIT_TEST(testSerializeEmptyBefore);
- CPPUNIT_TEST(testSerializeFirst);
- CPPUNIT_TEST(testSerializeFirstWithIndex);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(ResultSetSerializerTest);
+ CPPUNIT_TEST(testSerializeFull);
+ CPPUNIT_TEST(testSerializeMaxItems);
+ CPPUNIT_TEST(testSerializeEmptyBefore);
+ CPPUNIT_TEST(testSerializeFirst);
+ CPPUNIT_TEST(testSerializeFirstWithIndex);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerializeFull() {
- ResultSetSerializer serializer;
+ public:
+ void testSerializeFull() {
+ ResultSetSerializer serializer;
- boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
+ boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
- resultSet->setMaxItems(100);
- resultSet->setCount(800);
- resultSet->setIndex(0);
- resultSet->setFirstIDIndex(123);
- resultSet->setFirstID(std::string("stpeter@jabber.org"));
- resultSet->setLastID(std::string("peterpan@neverland.lit"));
- resultSet->setAfter(std::string("09af3-cc343-b409f"));
- resultSet->setBefore(std::string("decaf-badba-dbad1"));
+ resultSet->setMaxItems(100);
+ resultSet->setCount(800);
+ resultSet->setIndex(0);
+ resultSet->setFirstIDIndex(123);
+ resultSet->setFirstID(std::string("stpeter@jabber.org"));
+ resultSet->setLastID(std::string("peterpan@neverland.lit"));
+ resultSet->setAfter(std::string("09af3-cc343-b409f"));
+ resultSet->setBefore(std::string("decaf-badba-dbad1"));
- std::string expectedResult =
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<max>100</max>"
- "<count>800</count>"
- "<index>0</index>"
- "<first index=\"123\">stpeter@jabber.org</first>"
- "<last>peterpan@neverland.lit</last>"
- "<before>decaf-badba-dbad1</before>"
- "<after>09af3-cc343-b409f</after>"
- "</set>";
+ std::string expectedResult =
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<max>100</max>"
+ "<count>800</count>"
+ "<index>0</index>"
+ "<first index=\"123\">stpeter@jabber.org</first>"
+ "<last>peterpan@neverland.lit</last>"
+ "<before>decaf-badba-dbad1</before>"
+ "<after>09af3-cc343-b409f</after>"
+ "</set>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
+ }
- void testSerializeMaxItems() {
- ResultSetSerializer serializer;
+ void testSerializeMaxItems() {
+ ResultSetSerializer serializer;
- boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
+ boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
- resultSet->setMaxItems(100);
+ resultSet->setMaxItems(100);
- std::string expectedResult =
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<max>100</max>"
- "</set>";
+ std::string expectedResult =
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<max>100</max>"
+ "</set>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
+ }
- void testSerializeEmptyBefore() {
- ResultSetSerializer serializer;
+ void testSerializeEmptyBefore() {
+ ResultSetSerializer serializer;
- boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
+ boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
- resultSet->setBefore(std::string());
+ resultSet->setBefore(std::string());
- std::string expectedResult =
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<before/>"
- "</set>";
+ std::string expectedResult =
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<before/>"
+ "</set>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
+ }
- void testSerializeFirst() {
- ResultSetSerializer serializer;
+ void testSerializeFirst() {
+ ResultSetSerializer serializer;
- boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
+ boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
- resultSet->setFirstID(std::string("stpeter@jabber.org"));
+ resultSet->setFirstID(std::string("stpeter@jabber.org"));
- std::string expectedResult =
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<first>stpeter@jabber.org</first>"
- "</set>";
+ std::string expectedResult =
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<first>stpeter@jabber.org</first>"
+ "</set>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
+ }
- void testSerializeFirstWithIndex() {
- ResultSetSerializer serializer;
+ void testSerializeFirstWithIndex() {
+ ResultSetSerializer serializer;
- boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
+ boost::shared_ptr<ResultSet> resultSet(boost::make_shared<ResultSet>());
- resultSet->setFirstID(std::string("stpeter@jabber.org"));
- resultSet->setFirstIDIndex(123);
+ resultSet->setFirstID(std::string("stpeter@jabber.org"));
+ resultSet->setFirstIDIndex(123);
- std::string expectedResult =
- "<set xmlns=\"http://jabber.org/protocol/rsm\">"
- "<first index=\"123\">stpeter@jabber.org</first>"
- "</set>";
+ std::string expectedResult =
+ "<set xmlns=\"http://jabber.org/protocol/rsm\">"
+ "<first index=\"123\">stpeter@jabber.org</first>"
+ "</set>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, serializer.serialize(resultSet));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResultSetSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp
index b6a90d9..65922f7 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp
@@ -13,42 +13,42 @@ using namespace Swift;
class RosterItemExchangeSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(RosterItemExchangeSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- RosterItemExchangeSerializerTest() {}
-
- void testSerialize() {
- RosterItemExchangeSerializer testling;
- boost::shared_ptr<RosterItemExchangePayload> roster(new RosterItemExchangePayload());
-
- RosterItemExchangePayload::Item item1;
- item1.setJID("foo@bar.com");
- item1.setName("Foo @ Bar");
- item1.setAction(RosterItemExchangePayload::Item::Add);
- item1.addGroup("Group 1");
- item1.addGroup("Group 2");
- roster->addItem(item1);
-
- RosterItemExchangePayload::Item item2;
- item2.setJID("baz@blo.com");
- item2.setName("Baz");
- item2.setAction(RosterItemExchangePayload::Item::Modify);
- roster->addItem(item2);
-
- std::string expectedResult =
- "<x xmlns=\"http://jabber.org/protocol/rosterx\">"
- "<item action=\"add\" jid=\"foo@bar.com\" name=\"Foo @ Bar\">"
- "<group>Group 1</group>"
- "<group>Group 2</group>"
- "</item>"
- "<item action=\"modify\" jid=\"baz@blo.com\" name=\"Baz\"/>"
- "</x>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
- }
+ CPPUNIT_TEST_SUITE(RosterItemExchangeSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ RosterItemExchangeSerializerTest() {}
+
+ void testSerialize() {
+ RosterItemExchangeSerializer testling;
+ boost::shared_ptr<RosterItemExchangePayload> roster(new RosterItemExchangePayload());
+
+ RosterItemExchangePayload::Item item1;
+ item1.setJID("foo@bar.com");
+ item1.setName("Foo @ Bar");
+ item1.setAction(RosterItemExchangePayload::Item::Add);
+ item1.addGroup("Group 1");
+ item1.addGroup("Group 2");
+ roster->addItem(item1);
+
+ RosterItemExchangePayload::Item item2;
+ item2.setJID("baz@blo.com");
+ item2.setName("Baz");
+ item2.setAction(RosterItemExchangePayload::Item::Modify);
+ roster->addItem(item2);
+
+ std::string expectedResult =
+ "<x xmlns=\"http://jabber.org/protocol/rosterx\">"
+ "<item action=\"add\" jid=\"foo@bar.com\" name=\"Foo @ Bar\">"
+ "<group>Group 1</group>"
+ "<group>Group 2</group>"
+ "</item>"
+ "<item action=\"modify\" jid=\"baz@blo.com\" name=\"Baz\"/>"
+ "</x>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterItemExchangeSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp
index b75b0a0..6670bb8 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp
@@ -12,90 +12,90 @@
using namespace Swift;
class RosterSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(RosterSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_ItemWithUnknownContent);
- CPPUNIT_TEST(testSerialize_WithVersion);
- CPPUNIT_TEST(testSerialize_WithEmptyVersion);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- RosterSerializer testling;
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
-
- RosterItemPayload item1;
- item1.setJID(JID("foo@bar.com"));
- item1.setName("Foo @ Bar");
- item1.setSubscription(RosterItemPayload::From);
- item1.addGroup("Group 1");
- item1.addGroup("Group 2");
- item1.setSubscriptionRequested();
- roster->addItem(item1);
-
- RosterItemPayload item2;
- item2.setJID(JID("baz@blo.com"));
- item2.setName("Baz");
- roster->addItem(item2);
-
- std::string expectedResult =
- "<query xmlns=\"jabber:iq:roster\">"
- "<item ask=\"subscribe\" jid=\"foo@bar.com\" name=\"Foo @ Bar\" subscription=\"from\">"
- "<group>Group 1</group>"
- "<group>Group 2</group>"
- "</item>"
- "<item jid=\"baz@blo.com\" name=\"Baz\" subscription=\"none\"/>"
- "</query>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
- }
-
- void testSerialize_ItemWithUnknownContent() {
- RosterSerializer testling;
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
-
- RosterItemPayload item;
- item.setJID(JID("baz@blo.com"));
- item.setName("Baz");
- item.addGroup("Group 1");
- item.addGroup("Group 2");
- item.addUnknownContent(std::string(
- "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
- "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"));
- roster->addItem(item);
-
- std::string expectedResult =
- "<query xmlns=\"jabber:iq:roster\">"
- "<item jid=\"baz@blo.com\" name=\"Baz\" subscription=\"none\">"
- "<group>Group 1</group>"
- "<group>Group 2</group>"
- "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
- "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"
- "</item>"
- "</query>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
- }
-
- void testSerialize_WithVersion() {
- RosterSerializer testling;
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->setVersion("ver20");
-
- std::string expectedResult = "<query ver=\"ver20\" xmlns=\"jabber:iq:roster\"/>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
- }
-
- void testSerialize_WithEmptyVersion() {
- RosterSerializer testling;
- boost::shared_ptr<RosterPayload> roster(new RosterPayload());
- roster->setVersion("");
-
- std::string expectedResult = "<query ver=\"\" xmlns=\"jabber:iq:roster\"/>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
- }
+ CPPUNIT_TEST_SUITE(RosterSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_ItemWithUnknownContent);
+ CPPUNIT_TEST(testSerialize_WithVersion);
+ CPPUNIT_TEST(testSerialize_WithEmptyVersion);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ RosterSerializer testling;
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+
+ RosterItemPayload item1;
+ item1.setJID(JID("foo@bar.com"));
+ item1.setName("Foo @ Bar");
+ item1.setSubscription(RosterItemPayload::From);
+ item1.addGroup("Group 1");
+ item1.addGroup("Group 2");
+ item1.setSubscriptionRequested();
+ roster->addItem(item1);
+
+ RosterItemPayload item2;
+ item2.setJID(JID("baz@blo.com"));
+ item2.setName("Baz");
+ roster->addItem(item2);
+
+ std::string expectedResult =
+ "<query xmlns=\"jabber:iq:roster\">"
+ "<item ask=\"subscribe\" jid=\"foo@bar.com\" name=\"Foo @ Bar\" subscription=\"from\">"
+ "<group>Group 1</group>"
+ "<group>Group 2</group>"
+ "</item>"
+ "<item jid=\"baz@blo.com\" name=\"Baz\" subscription=\"none\"/>"
+ "</query>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
+ }
+
+ void testSerialize_ItemWithUnknownContent() {
+ RosterSerializer testling;
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+
+ RosterItemPayload item;
+ item.setJID(JID("baz@blo.com"));
+ item.setName("Baz");
+ item.addGroup("Group 1");
+ item.addGroup("Group 2");
+ item.addUnknownContent(std::string(
+ "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
+ "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"));
+ roster->addItem(item);
+
+ std::string expectedResult =
+ "<query xmlns=\"jabber:iq:roster\">"
+ "<item jid=\"baz@blo.com\" name=\"Baz\" subscription=\"none\">"
+ "<group>Group 1</group>"
+ "<group>Group 2</group>"
+ "<foo xmlns=\"http://example.com\"><bar xmlns=\"http://example.com\">Baz</bar></foo>"
+ "<baz xmlns=\"jabber:iq:roster\"><fum xmlns=\"jabber:iq:roster\">foo</fum></baz>"
+ "</item>"
+ "</query>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
+ }
+
+ void testSerialize_WithVersion() {
+ RosterSerializer testling;
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->setVersion("ver20");
+
+ std::string expectedResult = "<query ver=\"ver20\" xmlns=\"jabber:iq:roster\"/>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
+ }
+
+ void testSerialize_WithEmptyVersion() {
+ RosterSerializer testling;
+ boost::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->setVersion("");
+
+ std::string expectedResult = "<query ver=\"\" xmlns=\"jabber:iq:roster\"/>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(roster));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp
index 54da0bc..0dfe0b0 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp
@@ -14,164 +14,164 @@
using namespace Swift;
class SearchPayloadSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SearchPayloadSerializerTest);
- CPPUNIT_TEST(testSerialize_Request);
- CPPUNIT_TEST(testSerialize_Items);
- CPPUNIT_TEST(testSerialize_DataForm);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize_Request() {
- SearchPayloadSerializer testling;
-
- SearchPayload::ref payload(new SearchPayload());
- payload->setFirst("Juliet");
- payload->setLast("Capulet");
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<query xmlns=\"jabber:iq:search\">"
- "<first>Juliet</first>"
- "<last>Capulet</last>"
- "</query>"
- ), testling.serialize(payload));
- }
-
- void testSerialize_Items() {
- SearchPayloadSerializer testling;
-
- SearchPayload::ref payload(new SearchPayload());
- SearchPayload::Item item1;
- item1.jid = JID("juliet@capulet.com");
- item1.first = "Juliet";
- item1.last = "Capulet";
- item1.nick = "JuliC";
- item1.email = "juliet@shakespeare.lit";
- payload->addItem(item1);
-
- SearchPayload::Item item2;
- item2.jid = JID("tybalt@shakespeare.lit");
- item2.first = "Tybalt";
- item2.last = "Capulet";
- item2.nick = "ty";
- item2.email = "tybalt@shakespeare.lit";
- payload->addItem(item2);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<query xmlns=\"jabber:iq:search\">"
- "<item jid=\"juliet@capulet.com\">"
- "<first>Juliet</first>"
- "<last>Capulet</last>"
- "<nick>JuliC</nick>"
- "<email>juliet@shakespeare.lit</email>"
- "</item>"
- "<item jid=\"tybalt@shakespeare.lit\">"
- "<first>Tybalt</first>"
- "<last>Capulet</last>"
- "<nick>ty</nick>"
- "<email>tybalt@shakespeare.lit</email>"
- "</item>"
- "</query>"
- ), testling.serialize(payload));
- }
-
- void testSerialize_DataForm() {
- SearchPayloadSerializer testling;
-
- SearchPayload::ref payload(new SearchPayload());
- boost::shared_ptr<Form> form(new Form(Form::ResultType));
-
- FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
- field->setName("FORM_TYPE");
- form->addField(field);
-
- // reported fields
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("first");
- field->setLabel("Given Name");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType);
- field->setName("last");
- field->setLabel("Family Name");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::JIDSingleType);
- field->setName("jid");
- field->setLabel("Jabber ID");
- form->addReportedField(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType);
- field->setName("x-gender");
- field->setLabel("Gender");
- form->addReportedField(field);
-
- Form::FormItem firstItem;
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
- field->setName("first");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
- field->setName("last");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "benvolio@montague.net");
- field->setName("jid");
- firstItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
- field->setName("x-gender");
- firstItem.push_back(field);
-
- Form::FormItem secondItem;
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Romeo");
- field->setName("first");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
- field->setName("last");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::TextSingleType, "romeo@montague.net");
- field->setName("jid");
- secondItem.push_back(field);
-
- field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
- field->setName("x-gender");
- secondItem.push_back(field);
-
- form->addItem(firstItem);
- form->addItem(secondItem);
-
- payload->setForm(form);
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<query xmlns=\"jabber:iq:search\">"
- "<x type=\"result\" xmlns=\"jabber:x:data\">"
- "<field type=\"hidden\" var=\"FORM_TYPE\">"
- "<value>jabber:iq:search</value>"
- "</field>"
- "<reported>"
- "<field label=\"Given Name\" type=\"text-single\" var=\"first\"/>"
- "<field label=\"Family Name\" type=\"text-single\" var=\"last\"/>"
- "<field label=\"Jabber ID\" type=\"jid-single\" var=\"jid\"/>"
- "<field label=\"Gender\" type=\"list-single\" var=\"x-gender\"/>"
- "</reported>"
- "<item>"
- "<field var=\"first\"><value>Benvolio</value></field>"
- "<field var=\"last\"><value>Montague</value></field>"
- "<field var=\"jid\"><value>benvolio@montague.net</value></field>"
- "<field var=\"x-gender\"><value>male</value></field>"
- "</item>"
- "<item>"
- "<field var=\"first\"><value>Romeo</value></field>"
- "<field var=\"last\"><value>Montague</value></field>"
- "<field var=\"jid\"><value>romeo@montague.net</value></field>"
- "<field var=\"x-gender\"><value>male</value></field>"
- "</item>"
- "</x>"
- "</query>"), testling.serialize(payload));
-
- }
+ CPPUNIT_TEST_SUITE(SearchPayloadSerializerTest);
+ CPPUNIT_TEST(testSerialize_Request);
+ CPPUNIT_TEST(testSerialize_Items);
+ CPPUNIT_TEST(testSerialize_DataForm);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize_Request() {
+ SearchPayloadSerializer testling;
+
+ SearchPayload::ref payload(new SearchPayload());
+ payload->setFirst("Juliet");
+ payload->setLast("Capulet");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<query xmlns=\"jabber:iq:search\">"
+ "<first>Juliet</first>"
+ "<last>Capulet</last>"
+ "</query>"
+ ), testling.serialize(payload));
+ }
+
+ void testSerialize_Items() {
+ SearchPayloadSerializer testling;
+
+ SearchPayload::ref payload(new SearchPayload());
+ SearchPayload::Item item1;
+ item1.jid = JID("juliet@capulet.com");
+ item1.first = "Juliet";
+ item1.last = "Capulet";
+ item1.nick = "JuliC";
+ item1.email = "juliet@shakespeare.lit";
+ payload->addItem(item1);
+
+ SearchPayload::Item item2;
+ item2.jid = JID("tybalt@shakespeare.lit");
+ item2.first = "Tybalt";
+ item2.last = "Capulet";
+ item2.nick = "ty";
+ item2.email = "tybalt@shakespeare.lit";
+ payload->addItem(item2);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<query xmlns=\"jabber:iq:search\">"
+ "<item jid=\"juliet@capulet.com\">"
+ "<first>Juliet</first>"
+ "<last>Capulet</last>"
+ "<nick>JuliC</nick>"
+ "<email>juliet@shakespeare.lit</email>"
+ "</item>"
+ "<item jid=\"tybalt@shakespeare.lit\">"
+ "<first>Tybalt</first>"
+ "<last>Capulet</last>"
+ "<nick>ty</nick>"
+ "<email>tybalt@shakespeare.lit</email>"
+ "</item>"
+ "</query>"
+ ), testling.serialize(payload));
+ }
+
+ void testSerialize_DataForm() {
+ SearchPayloadSerializer testling;
+
+ SearchPayload::ref payload(new SearchPayload());
+ boost::shared_ptr<Form> form(new Form(Form::ResultType));
+
+ FormField::ref field = boost::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ // reported fields
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("first");
+ field->setLabel("Given Name");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("last");
+ field->setLabel("Family Name");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::JIDSingleType);
+ field->setName("jid");
+ field->setLabel("Jabber ID");
+ form->addReportedField(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("x-gender");
+ field->setLabel("Gender");
+ form->addReportedField(field);
+
+ Form::FormItem firstItem;
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
+ field->setName("first");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "benvolio@montague.net");
+ field->setName("jid");
+ firstItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ firstItem.push_back(field);
+
+ Form::FormItem secondItem;
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Romeo");
+ field->setName("first");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::TextSingleType, "romeo@montague.net");
+ field->setName("jid");
+ secondItem.push_back(field);
+
+ field = boost::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ secondItem.push_back(field);
+
+ form->addItem(firstItem);
+ form->addItem(secondItem);
+
+ payload->setForm(form);
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<query xmlns=\"jabber:iq:search\">"
+ "<x type=\"result\" xmlns=\"jabber:x:data\">"
+ "<field type=\"hidden\" var=\"FORM_TYPE\">"
+ "<value>jabber:iq:search</value>"
+ "</field>"
+ "<reported>"
+ "<field label=\"Given Name\" type=\"text-single\" var=\"first\"/>"
+ "<field label=\"Family Name\" type=\"text-single\" var=\"last\"/>"
+ "<field label=\"Jabber ID\" type=\"jid-single\" var=\"jid\"/>"
+ "<field label=\"Gender\" type=\"list-single\" var=\"x-gender\"/>"
+ "</reported>"
+ "<item>"
+ "<field var=\"first\"><value>Benvolio</value></field>"
+ "<field var=\"last\"><value>Montague</value></field>"
+ "<field var=\"jid\"><value>benvolio@montague.net</value></field>"
+ "<field var=\"x-gender\"><value>male</value></field>"
+ "</item>"
+ "<item>"
+ "<field var=\"first\"><value>Romeo</value></field>"
+ "<field var=\"last\"><value>Montague</value></field>"
+ "<field var=\"jid\"><value>romeo@montague.net</value></field>"
+ "<field var=\"x-gender\"><value>male</value></field>"
+ "</item>"
+ "</x>"
+ "</query>"), testling.serialize(payload));
+
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SearchPayloadSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp
index 9ad9ea6..db482ff 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp
@@ -12,49 +12,49 @@
using namespace Swift;
class SecurityLabelSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(SecurityLabelSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_EmptyLabel);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- SecurityLabelSerializer testling;
- boost::shared_ptr<SecurityLabel> securityLabel(new SecurityLabel());
- securityLabel->setDisplayMarking("SECRET");
- securityLabel->setForegroundColor("black");
- securityLabel->setBackgroundColor("red");
- securityLabel->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>");
- securityLabel->addEquivalentLabel("<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>");
- securityLabel->addEquivalentLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>");
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
- "<label>"
- "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"
- "</label>"
- "<equivalentlabel>"
- "<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>"
- "</equivalentlabel>"
- "<equivalentlabel>"
- "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"
- "</equivalentlabel>"
- "</securitylabel>"), testling.serialize(securityLabel));
- }
-
- void testSerialize_EmptyLabel() {
- SecurityLabelSerializer testling;
- boost::shared_ptr<SecurityLabel> securityLabel(new SecurityLabel());
- securityLabel->setDisplayMarking("SECRET");
- securityLabel->setLabel("");
-
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking>SECRET</displaymarking>"
- "<label></label>"
- "</securitylabel>"), testling.serialize(securityLabel));
- }
+ CPPUNIT_TEST_SUITE(SecurityLabelSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_EmptyLabel);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ SecurityLabelSerializer testling;
+ boost::shared_ptr<SecurityLabel> securityLabel(new SecurityLabel());
+ securityLabel->setDisplayMarking("SECRET");
+ securityLabel->setForegroundColor("black");
+ securityLabel->setBackgroundColor("red");
+ securityLabel->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>");
+ securityLabel->addEquivalentLabel("<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>");
+ securityLabel->addEquivalentLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
+ "<label>"
+ "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>"
+ "</label>"
+ "<equivalentlabel>"
+ "<icismlabel xmlns=\"http://example.gov/IC-ISM/0\" classification=\"S\" ownerProducer=\"USA\" disseminationControls=\"FOUO\"/>"
+ "</equivalentlabel>"
+ "<equivalentlabel>"
+ "<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MRUCAgD9DA9BcXVhIChvYnNvbGV0ZSk=</esssecuritylabel>"
+ "</equivalentlabel>"
+ "</securitylabel>"), testling.serialize(securityLabel));
+ }
+
+ void testSerialize_EmptyLabel() {
+ SecurityLabelSerializer testling;
+ boost::shared_ptr<SecurityLabel> securityLabel(new SecurityLabel());
+ securityLabel->setDisplayMarking("SECRET");
+ securityLabel->setLabel("");
+
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking>SECRET</displaymarking>"
+ "<label></label>"
+ "</securitylabel>"), testling.serialize(securityLabel));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SecurityLabelSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp
index e18b4d7..51c98c1 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp
@@ -13,63 +13,63 @@ using namespace Swift;
class SecurityLabelsCatalogSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SecurityLabelsCatalogSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SecurityLabelsCatalogSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- SecurityLabelsCatalogSerializerTest() {}
+ public:
+ SecurityLabelsCatalogSerializerTest() {}
- void testSerialize() {
- SecurityLabelsCatalogSerializer testling;
- boost::shared_ptr<SecurityLabelsCatalog> catalog(new SecurityLabelsCatalog());
- catalog->setTo(JID("example.com"));
- catalog->setName("Default");
- catalog->setDescription("an example set of labels");
+ void testSerialize() {
+ SecurityLabelsCatalogSerializer testling;
+ boost::shared_ptr<SecurityLabelsCatalog> catalog(new SecurityLabelsCatalog());
+ catalog->setTo(JID("example.com"));
+ catalog->setName("Default");
+ catalog->setDescription("an example set of labels");
- SecurityLabelsCatalog::Item item1;
- boost::shared_ptr<SecurityLabel> securityLabel1(new SecurityLabel());
- item1.setLabel(securityLabel1);
- securityLabel1->setDisplayMarking("SECRET");
- securityLabel1->setForegroundColor("black");
- securityLabel1->setBackgroundColor("red");
- item1.setIsDefault(false);
- item1.setSelector("Classified|SECRET");
- securityLabel1->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>");
- catalog->addItem(item1);
+ SecurityLabelsCatalog::Item item1;
+ boost::shared_ptr<SecurityLabel> securityLabel1(new SecurityLabel());
+ item1.setLabel(securityLabel1);
+ securityLabel1->setDisplayMarking("SECRET");
+ securityLabel1->setForegroundColor("black");
+ securityLabel1->setBackgroundColor("red");
+ item1.setIsDefault(false);
+ item1.setSelector("Classified|SECRET");
+ securityLabel1->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel>");
+ catalog->addItem(item1);
- SecurityLabelsCatalog::Item item2;
- boost::shared_ptr<SecurityLabel> securityLabel2(new SecurityLabel());
- item2.setLabel(securityLabel2);
- securityLabel2->setDisplayMarking("CONFIDENTIAL");
- securityLabel2->setForegroundColor("black");
- securityLabel2->setBackgroundColor("navy");
- item2.setIsDefault(true);
- item2.setSelector("Classified|CONFIDENTIAL");
- securityLabel2->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel>");
- catalog->addItem(item2);
+ SecurityLabelsCatalog::Item item2;
+ boost::shared_ptr<SecurityLabel> securityLabel2(new SecurityLabel());
+ item2.setLabel(securityLabel2);
+ securityLabel2->setDisplayMarking("CONFIDENTIAL");
+ securityLabel2->setForegroundColor("black");
+ securityLabel2->setBackgroundColor("navy");
+ item2.setIsDefault(true);
+ item2.setSelector("Classified|CONFIDENTIAL");
+ securityLabel2->setLabel("<esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel>");
+ catalog->addItem(item2);
- SecurityLabelsCatalog::Item item3;
- item3.setSelector("Unclassified|UNCLASSIFIED");
- catalog->addItem(item3);
+ SecurityLabelsCatalog::Item item3;
+ item3.setSelector("Unclassified|UNCLASSIFIED");
+ catalog->addItem(item3);
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<catalog desc=\"an example set of labels\" name=\"Default\" to=\"example.com\" xmlns=\"urn:xmpp:sec-label:catalog:2\">"
- "<item selector=\"Classified|SECRET\">"
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
- "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel></label>"
- "</securitylabel>"
- "</item>"
- "<item default=\"true\" selector=\"Classified|CONFIDENTIAL\">"
- "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
- "<displaymarking bgcolor=\"navy\" fgcolor=\"black\">CONFIDENTIAL</displaymarking>"
- "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel></label>"
- "</securitylabel>"
- "</item>"
- "<item selector=\"Unclassified|UNCLASSIFIED\"/>"
- "</catalog>"), testling.serialize(catalog));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<catalog desc=\"an example set of labels\" name=\"Default\" to=\"example.com\" xmlns=\"urn:xmpp:sec-label:catalog:2\">"
+ "<item selector=\"Classified|SECRET\">"
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking bgcolor=\"red\" fgcolor=\"black\">SECRET</displaymarking>"
+ "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQYCAQQGASk=</esssecuritylabel></label>"
+ "</securitylabel>"
+ "</item>"
+ "<item default=\"true\" selector=\"Classified|CONFIDENTIAL\">"
+ "<securitylabel xmlns=\"urn:xmpp:sec-label:0\">"
+ "<displaymarking bgcolor=\"navy\" fgcolor=\"black\">CONFIDENTIAL</displaymarking>"
+ "<label><esssecuritylabel xmlns=\"urn:xmpp:sec-label:ess:0\">MQMGASk=</esssecuritylabel></label>"
+ "</securitylabel>"
+ "</item>"
+ "<item selector=\"Unclassified|UNCLASSIFIED\"/>"
+ "</catalog>"), testling.serialize(catalog));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SecurityLabelsCatalogSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp
index 52e64b6..5643e1e 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp
@@ -13,19 +13,19 @@ using namespace Swift;
class SoftwareVersionSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(SoftwareVersionSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(SoftwareVersionSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- SoftwareVersionSerializerTest() {}
+ public:
+ SoftwareVersionSerializerTest() {}
- void testSerialize() {
- SoftwareVersionSerializer testling;
- boost::shared_ptr<SoftwareVersion> softwareVersion(new SoftwareVersion("Swift", "0.1", "Mac OS X"));
+ void testSerialize() {
+ SoftwareVersionSerializer testling;
+ boost::shared_ptr<SoftwareVersion> softwareVersion(new SoftwareVersion("Swift", "0.1", "Mac OS X"));
- CPPUNIT_ASSERT_EQUAL(std::string("<query xmlns=\"jabber:iq:version\"><name>Swift</name><version>0.1</version><os>Mac OS X</os></query>"), testling.serialize(softwareVersion));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<query xmlns=\"jabber:iq:version\"><name>Swift</name><version>0.1</version><os>Mac OS X</os></query>"), testling.serialize(softwareVersion));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(SoftwareVersionSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp
index cb3ab7e..c8c2156 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp
@@ -13,19 +13,19 @@ using namespace Swift;
class StatusSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StatusSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StatusSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- StatusSerializerTest() {}
+ public:
+ StatusSerializerTest() {}
- void testSerialize() {
- StatusSerializer testling;
- boost::shared_ptr<Status> status(new Status("I am away"));
+ void testSerialize() {
+ StatusSerializer testling;
+ boost::shared_ptr<Status> status(new Status("I am away"));
- CPPUNIT_ASSERT_EQUAL(std::string("<status>I am away</status>"), testling.serialize(status));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<status>I am away</status>"), testling.serialize(status));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StatusSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp
index 272e61a..9fda49e 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp
@@ -13,52 +13,52 @@ using namespace Swift;
class StatusShowSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StatusShowSerializerTest);
- CPPUNIT_TEST(testSerialize_Online);
- CPPUNIT_TEST(testSerialize_Away);
- CPPUNIT_TEST(testSerialize_FFC);
- CPPUNIT_TEST(testSerialize_XA);
- CPPUNIT_TEST(testSerialize_DND);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StatusShowSerializerTest);
+ CPPUNIT_TEST(testSerialize_Online);
+ CPPUNIT_TEST(testSerialize_Away);
+ CPPUNIT_TEST(testSerialize_FFC);
+ CPPUNIT_TEST(testSerialize_XA);
+ CPPUNIT_TEST(testSerialize_DND);
+ CPPUNIT_TEST_SUITE_END();
- public:
- StatusShowSerializerTest() {}
+ public:
+ StatusShowSerializerTest() {}
- void testSerialize_Online() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::Online));
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.serialize(statusShow));
- }
+ void testSerialize_Online() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::Online));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.serialize(statusShow));
+ }
- void testSerialize_Away() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::Away));
- CPPUNIT_ASSERT_EQUAL(std::string("<show>away</show>"), testling.serialize(statusShow));
- }
+ void testSerialize_Away() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::Away));
+ CPPUNIT_ASSERT_EQUAL(std::string("<show>away</show>"), testling.serialize(statusShow));
+ }
- void testSerialize_FFC() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::FFC));
- CPPUNIT_ASSERT_EQUAL(std::string("<show>chat</show>"), testling.serialize(statusShow));
- }
+ void testSerialize_FFC() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::FFC));
+ CPPUNIT_ASSERT_EQUAL(std::string("<show>chat</show>"), testling.serialize(statusShow));
+ }
- void testSerialize_XA() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::XA));
- CPPUNIT_ASSERT_EQUAL(std::string("<show>xa</show>"), testling.serialize(statusShow));
- }
+ void testSerialize_XA() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::XA));
+ CPPUNIT_ASSERT_EQUAL(std::string("<show>xa</show>"), testling.serialize(statusShow));
+ }
- void testSerialize_DND() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::DND));
- CPPUNIT_ASSERT_EQUAL(std::string("<show>dnd</show>"), testling.serialize(statusShow));
- }
+ void testSerialize_DND() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::DND));
+ CPPUNIT_ASSERT_EQUAL(std::string("<show>dnd</show>"), testling.serialize(statusShow));
+ }
- void testSerialize_None() {
- StatusShowSerializer testling;
- boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::None));
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.serialize(statusShow));
- }
+ void testSerialize_None() {
+ StatusShowSerializer testling;
+ boost::shared_ptr<StatusShow> statusShow(new StatusShow(StatusShow::None));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.serialize(statusShow));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StatusShowSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp
index 3273e4b..e98ee3a 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp
@@ -13,59 +13,59 @@
using namespace Swift;
class StorageSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StorageSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoNickOrPassword);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StorageSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoNickOrPassword);
+ CPPUNIT_TEST_SUITE_END();
- public:
- StorageSerializerTest() {}
+ public:
+ StorageSerializerTest() {}
- void testSerialize() {
- PayloadsSerializer serializer;
- boost::shared_ptr<Storage> storage(new Storage());
- Storage::Room room;
- room.name = "Council of Oberon";
- room.autoJoin = true;
- room.jid = JID("council@conference.underhill.org");
- room.nick = "Puck";
- room.password = "MyPass";
- storage->addRoom(room);
- Storage::URL url;
- url.name = "Complete Works of Shakespeare";
- url.url = "http://the-tech.mit.edu/Shakespeare/";
- storage->addURL(url);
+ void testSerialize() {
+ PayloadsSerializer serializer;
+ boost::shared_ptr<Storage> storage(new Storage());
+ Storage::Room room;
+ room.name = "Council of Oberon";
+ room.autoJoin = true;
+ room.jid = JID("council@conference.underhill.org");
+ room.nick = "Puck";
+ room.password = "MyPass";
+ storage->addRoom(room);
+ Storage::URL url;
+ url.name = "Complete Works of Shakespeare";
+ url.url = "http://the-tech.mit.edu/Shakespeare/";
+ storage->addURL(url);
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<storage xmlns=\"storage:bookmarks\">"
- "<conference "
- "autojoin=\"1\" "
- "jid=\"council@conference.underhill.org\" "
- "name=\"Council of Oberon\">"
- "<nick>Puck</nick>"
- "<password>MyPass</password>"
- "</conference>"
- "<url name=\"Complete Works of Shakespeare\" url=\"http://the-tech.mit.edu/Shakespeare/\"/>"
- "</storage>"), serializer.serialize(storage));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<storage xmlns=\"storage:bookmarks\">"
+ "<conference "
+ "autojoin=\"1\" "
+ "jid=\"council@conference.underhill.org\" "
+ "name=\"Council of Oberon\">"
+ "<nick>Puck</nick>"
+ "<password>MyPass</password>"
+ "</conference>"
+ "<url name=\"Complete Works of Shakespeare\" url=\"http://the-tech.mit.edu/Shakespeare/\"/>"
+ "</storage>"), serializer.serialize(storage));
+ }
- void testSerialize_NoNickOrPassword() {
- PayloadsSerializer serializer;
- boost::shared_ptr<Storage> storage(new Storage());
- Storage::Room room;
- room.name = "Council of Oberon";
- room.autoJoin = true;
- room.jid = JID("council@conference.underhill.org");
- storage->addRoom(room);
+ void testSerialize_NoNickOrPassword() {
+ PayloadsSerializer serializer;
+ boost::shared_ptr<Storage> storage(new Storage());
+ Storage::Room room;
+ room.name = "Council of Oberon";
+ room.autoJoin = true;
+ room.jid = JID("council@conference.underhill.org");
+ storage->addRoom(room);
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<storage xmlns=\"storage:bookmarks\">"
- "<conference "
- "autojoin=\"1\" "
- "jid=\"council@conference.underhill.org\" "
- "name=\"Council of Oberon\"/>"
- "</storage>"), serializer.serialize(storage));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<storage xmlns=\"storage:bookmarks\">"
+ "<conference "
+ "autojoin=\"1\" "
+ "jid=\"council@conference.underhill.org\" "
+ "name=\"Council of Oberon\"/>"
+ "</storage>"), serializer.serialize(storage));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StorageSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp
index 2d11dc4..ada65a9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp
@@ -12,57 +12,57 @@
using namespace Swift;
class StreamInitiationSerializerTest : public CppUnit::TestFixture{
- CPPUNIT_TEST_SUITE(StreamInitiationSerializerTest);
- CPPUNIT_TEST(testSerialize_Request);
- CPPUNIT_TEST(testSerialize_Response);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(StreamInitiationSerializerTest);
+ CPPUNIT_TEST(testSerialize_Request);
+ CPPUNIT_TEST(testSerialize_Response);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize_Request() {
- StreamInitiationSerializer testling;
- boost::shared_ptr<StreamInitiation> streamInitiation(new StreamInitiation());
- StreamInitiationFileInfo fileInfo("test.txt", "This is info about the file.", 1022);
- streamInitiation->setID("a0");
- streamInitiation->setFileInfo(fileInfo);
- streamInitiation->addProvidedMethod("http://jabber.org/protocol/bytestreams");
- streamInitiation->addProvidedMethod("jabber:iq:oob");
- streamInitiation->addProvidedMethod("http://jabber.org/protocol/ibb");
+ public:
+ void testSerialize_Request() {
+ StreamInitiationSerializer testling;
+ boost::shared_ptr<StreamInitiation> streamInitiation(new StreamInitiation());
+ StreamInitiationFileInfo fileInfo("test.txt", "This is info about the file.", 1022);
+ streamInitiation->setID("a0");
+ streamInitiation->setFileInfo(fileInfo);
+ streamInitiation->addProvidedMethod("http://jabber.org/protocol/bytestreams");
+ streamInitiation->addProvidedMethod("jabber:iq:oob");
+ streamInitiation->addProvidedMethod("http://jabber.org/protocol/ibb");
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<si id=\"a0\" profile=\"http://jabber.org/protocol/si/profile/file-transfer\" xmlns=\"http://jabber.org/protocol/si\">"
- "<file name=\"test.txt\" size=\"1022\" xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
- "<desc>This is info about the file.</desc>"
- "</file>"
- "<feature xmlns=\"http://jabber.org/protocol/feature-neg\">"
- "<x type=\"form\" xmlns=\"jabber:x:data\">"
- "<field type=\"list-single\" var=\"stream-method\">"
- "<option><value>http://jabber.org/protocol/bytestreams</value></option>"
- "<option><value>jabber:iq:oob</value></option>"
- "<option><value>http://jabber.org/protocol/ibb</value></option>"
- "</field>"
- "</x>"
- "</feature>"
- "</si>"
- ), testling.serialize(streamInitiation));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<si id=\"a0\" profile=\"http://jabber.org/protocol/si/profile/file-transfer\" xmlns=\"http://jabber.org/protocol/si\">"
+ "<file name=\"test.txt\" size=\"1022\" xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<desc>This is info about the file.</desc>"
+ "</file>"
+ "<feature xmlns=\"http://jabber.org/protocol/feature-neg\">"
+ "<x type=\"form\" xmlns=\"jabber:x:data\">"
+ "<field type=\"list-single\" var=\"stream-method\">"
+ "<option><value>http://jabber.org/protocol/bytestreams</value></option>"
+ "<option><value>jabber:iq:oob</value></option>"
+ "<option><value>http://jabber.org/protocol/ibb</value></option>"
+ "</field>"
+ "</x>"
+ "</feature>"
+ "</si>"
+ ), testling.serialize(streamInitiation));
+ }
- void testSerialize_Response() {
- StreamInitiationSerializer testling;
- boost::shared_ptr<StreamInitiation> streamInitiation(new StreamInitiation());
- streamInitiation->setRequestedMethod("http://jabber.org/protocol/bytestreams");
+ void testSerialize_Response() {
+ StreamInitiationSerializer testling;
+ boost::shared_ptr<StreamInitiation> streamInitiation(new StreamInitiation());
+ streamInitiation->setRequestedMethod("http://jabber.org/protocol/bytestreams");
- CPPUNIT_ASSERT_EQUAL(std::string(
- "<si profile=\"http://jabber.org/protocol/si/profile/file-transfer\" xmlns=\"http://jabber.org/protocol/si\">"
- "<feature xmlns=\"http://jabber.org/protocol/feature-neg\">"
- "<x type=\"submit\" xmlns=\"jabber:x:data\">"
- "<field type=\"list-single\" var=\"stream-method\">"
- "<value>http://jabber.org/protocol/bytestreams</value>"
- "</field>"
- "</x>"
- "</feature>"
- "</si>"
- ), testling.serialize(streamInitiation));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(
+ "<si profile=\"http://jabber.org/protocol/si/profile/file-transfer\" xmlns=\"http://jabber.org/protocol/si\">"
+ "<feature xmlns=\"http://jabber.org/protocol/feature-neg\">"
+ "<x type=\"submit\" xmlns=\"jabber:x:data\">"
+ "<field type=\"list-single\" var=\"stream-method\">"
+ "<value>http://jabber.org/protocol/bytestreams</value>"
+ "</field>"
+ "</x>"
+ "</feature>"
+ "</si>"
+ ), testling.serialize(streamInitiation));
+ }
};
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp
index 565f61d..3aed450 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp
@@ -17,88 +17,88 @@
#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserLocation.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h>
using namespace Swift;
class UserLocationSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(UserLocationSerializerTest);
- CPPUNIT_TEST(testSerialize_withAllVariablesSet);
- CPPUNIT_TEST(testSerialize_withSomeVariablesSet);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(UserLocationSerializerTest);
+ CPPUNIT_TEST(testSerialize_withAllVariablesSet);
+ CPPUNIT_TEST(testSerialize_withSomeVariablesSet);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize_withAllVariablesSet() {
- UserLocationSerializer testling(&serializers);
- boost::shared_ptr<UserLocation> userLocation(new UserLocation());
- userLocation->setArea(boost::optional<std::string>("Barbaric"));
- userLocation->setAltitude(5.75F);
- userLocation->setLocality(boost::optional<std::string>("Near"));
- userLocation->setLatitude(boost::optional<float>(5.75F));
- userLocation->setAccuracy(5.75F);
- userLocation->setDescription(boost::optional<std::string>("Nice"));
- userLocation->setCountryCode(boost::optional<std::string>("+91"));
- userLocation->setTimestamp(stringToDateTime("2015-06-11T20:55:50Z"));
- userLocation->setFloor(boost::optional<std::string>("3"));
- userLocation->setBuilding(boost::optional<std::string>("First"));
- userLocation->setRoom(boost::optional<std::string>("E315"));
- userLocation->setCountry(boost::optional<std::string>("USA"));
- userLocation->setRegion(boost::optional<std::string>("NewSode"));
- userLocation->setURI(boost::optional<std::string>("URIs"));
- userLocation->setLongitude(5.75F);
- userLocation->setError(5.75F);
- userLocation->setPostalCode(boost::optional<std::string>("67"));
- userLocation->setBearing(5.75F);
- userLocation->setText(boost::optional<std::string>("Hello"));
- userLocation->setDatum(boost::optional<std::string>("Datee"));
- userLocation->setStreet(boost::optional<std::string>("Highway"));
- userLocation->setSpeed(5.75F);
+ public:
+ void testSerialize_withAllVariablesSet() {
+ UserLocationSerializer testling(&serializers);
+ boost::shared_ptr<UserLocation> userLocation(new UserLocation());
+ userLocation->setArea(boost::optional<std::string>("Barbaric"));
+ userLocation->setAltitude(5.75F);
+ userLocation->setLocality(boost::optional<std::string>("Near"));
+ userLocation->setLatitude(boost::optional<float>(5.75F));
+ userLocation->setAccuracy(5.75F);
+ userLocation->setDescription(boost::optional<std::string>("Nice"));
+ userLocation->setCountryCode(boost::optional<std::string>("+91"));
+ userLocation->setTimestamp(stringToDateTime("2015-06-11T20:55:50Z"));
+ userLocation->setFloor(boost::optional<std::string>("3"));
+ userLocation->setBuilding(boost::optional<std::string>("First"));
+ userLocation->setRoom(boost::optional<std::string>("E315"));
+ userLocation->setCountry(boost::optional<std::string>("USA"));
+ userLocation->setRegion(boost::optional<std::string>("NewSode"));
+ userLocation->setURI(boost::optional<std::string>("URIs"));
+ userLocation->setLongitude(5.75F);
+ userLocation->setError(5.75F);
+ userLocation->setPostalCode(boost::optional<std::string>("67"));
+ userLocation->setBearing(5.75F);
+ userLocation->setText(boost::optional<std::string>("Hello"));
+ userLocation->setDatum(boost::optional<std::string>("Datee"));
+ userLocation->setStreet(boost::optional<std::string>("Highway"));
+ userLocation->setSpeed(5.75F);
- std::string expectedResult =
- "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
- "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
- "<lat>5.75</lat><accuracy>5.75</accuracy><description>Nice</description>"
- "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
- "<building>First</building><room>E315</room><country>USA</country>"
- "<region>NewSode</region><uri>URIs</uri><lon>5.75</lon><error>5.75</error>"
- "<postalcode>67</postalcode><bearing>5.75</bearing><text>Hello</text>"
- "<datum>Datee</datum><street>Highway</street><speed>5.75</speed></geoloc>";
+ std::string expectedResult =
+ "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
+ "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
+ "<lat>5.75</lat><accuracy>5.75</accuracy><description>Nice</description>"
+ "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
+ "<building>First</building><room>E315</room><country>USA</country>"
+ "<region>NewSode</region><uri>URIs</uri><lon>5.75</lon><error>5.75</error>"
+ "<postalcode>67</postalcode><bearing>5.75</bearing><text>Hello</text>"
+ "<datum>Datee</datum><street>Highway</street><speed>5.75</speed></geoloc>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userLocation));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userLocation));
+ }
- void testSerialize_withSomeVariablesSet() {
- UserLocationSerializer testling(&serializers);
- boost::shared_ptr<UserLocation> userLocation(new UserLocation());
- userLocation->setArea(boost::optional<std::string>("Barbaric"));
- userLocation->setAltitude(5.75F);
- userLocation->setLocality(boost::optional<std::string>("Near"));
- userLocation->setAccuracy(5.75F);
- userLocation->setDescription(boost::optional<std::string>("Nice"));
- userLocation->setCountryCode(boost::optional<std::string>("+91"));
- userLocation->setTimestamp(stringToDateTime("2015-06-11T20:55:50Z"));
- userLocation->setFloor(boost::optional<std::string>("3"));
- userLocation->setRegion(boost::optional<std::string>("NewSode"));
- userLocation->setURI(boost::optional<std::string>("URIs"));
- userLocation->setLongitude(5.75F);
- userLocation->setError(5.75F);
- userLocation->setPostalCode(boost::optional<std::string>("67"));
- userLocation->setBearing(5.75F);
- userLocation->setText(boost::optional<std::string>("Hello"));
+ void testSerialize_withSomeVariablesSet() {
+ UserLocationSerializer testling(&serializers);
+ boost::shared_ptr<UserLocation> userLocation(new UserLocation());
+ userLocation->setArea(boost::optional<std::string>("Barbaric"));
+ userLocation->setAltitude(5.75F);
+ userLocation->setLocality(boost::optional<std::string>("Near"));
+ userLocation->setAccuracy(5.75F);
+ userLocation->setDescription(boost::optional<std::string>("Nice"));
+ userLocation->setCountryCode(boost::optional<std::string>("+91"));
+ userLocation->setTimestamp(stringToDateTime("2015-06-11T20:55:50Z"));
+ userLocation->setFloor(boost::optional<std::string>("3"));
+ userLocation->setRegion(boost::optional<std::string>("NewSode"));
+ userLocation->setURI(boost::optional<std::string>("URIs"));
+ userLocation->setLongitude(5.75F);
+ userLocation->setError(5.75F);
+ userLocation->setPostalCode(boost::optional<std::string>("67"));
+ userLocation->setBearing(5.75F);
+ userLocation->setText(boost::optional<std::string>("Hello"));
- std::string expectedResult =
- "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
- "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
- "<accuracy>5.75</accuracy><description>Nice</description>"
- "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
- "<region>NewSode</region><uri>URIs</uri><lon>5.75</lon><error>5.75</error>"
- "<postalcode>67</postalcode><bearing>5.75</bearing><text>Hello</text></geoloc>";
+ std::string expectedResult =
+ "<geoloc xmlns=\"http://jabber.org/protocol/geoloc\">"
+ "<area>Barbaric</area><alt>5.75</alt><locality>Near</locality>"
+ "<accuracy>5.75</accuracy><description>Nice</description>"
+ "<countrycode>+91</countrycode><timestamp>2015-06-11T20:55:50Z</timestamp><floor>3</floor>"
+ "<region>NewSode</region><uri>URIs</uri><lon>5.75</lon><error>5.75</error>"
+ "<postalcode>67</postalcode><bearing>5.75</bearing><text>Hello</text></geoloc>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userLocation));
- }
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userLocation));
+ }
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(UserLocationSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp
index 6e2fc8b..50f2a54 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp
@@ -17,53 +17,53 @@
#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserTune.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h>
using namespace Swift;
class UserTuneSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(UserTuneSerializerTest);
- CPPUNIT_TEST(testSerialize_withAllVariablesSet);
- CPPUNIT_TEST(testSerialize_withSomeVariablesSet);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(UserTuneSerializerTest);
+ CPPUNIT_TEST(testSerialize_withAllVariablesSet);
+ CPPUNIT_TEST(testSerialize_withSomeVariablesSet);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testSerialize_withAllVariablesSet() {
- UserTuneSerializer testling(&serializers);
- boost::shared_ptr<UserTune> userTune(new UserTune());
- userTune->setRating(5);
- userTune->setTitle(boost::optional<std::string>("Minion"));
- userTune->setTrack(boost::optional<std::string>("Yellow"));
- userTune->setArtist(boost::optional<std::string>("Ice"));
- userTune->setURI(boost::optional<std::string>("Fire"));
- userTune->setSource(boost::optional<std::string>("Origin"));
- userTune->setLength(226);
+ public:
+ void testSerialize_withAllVariablesSet() {
+ UserTuneSerializer testling(&serializers);
+ boost::shared_ptr<UserTune> userTune(new UserTune());
+ userTune->setRating(5);
+ userTune->setTitle(boost::optional<std::string>("Minion"));
+ userTune->setTrack(boost::optional<std::string>("Yellow"));
+ userTune->setArtist(boost::optional<std::string>("Ice"));
+ userTune->setURI(boost::optional<std::string>("Fire"));
+ userTune->setSource(boost::optional<std::string>("Origin"));
+ userTune->setLength(226);
- std::string expectedResult =
- "<tune xmlns=\"http://jabber.org/protocol/tune\">"
- "<rating>5</rating><title>Minion</title><track>Yellow</track><artist>Ice</artist><uri>Fire</uri><source>Origin</source><length>226</length></tune>";
+ std::string expectedResult =
+ "<tune xmlns=\"http://jabber.org/protocol/tune\">"
+ "<rating>5</rating><title>Minion</title><track>Yellow</track><artist>Ice</artist><uri>Fire</uri><source>Origin</source><length>226</length></tune>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userTune));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userTune));
+ }
- void testSerialize_withSomeVariablesSet() {
- UserTuneSerializer testling(&serializers);
- boost::shared_ptr<UserTune> userTune(new UserTune());
- userTune->setTitle(boost::optional<std::string>("Minion"));
- userTune->setTrack(boost::optional<std::string>("Yellow"));
- userTune->setArtist(boost::optional<std::string>("Ice"));
- userTune->setSource(boost::optional<std::string>("Origin"));
- userTune->setLength(226);
+ void testSerialize_withSomeVariablesSet() {
+ UserTuneSerializer testling(&serializers);
+ boost::shared_ptr<UserTune> userTune(new UserTune());
+ userTune->setTitle(boost::optional<std::string>("Minion"));
+ userTune->setTrack(boost::optional<std::string>("Yellow"));
+ userTune->setArtist(boost::optional<std::string>("Ice"));
+ userTune->setSource(boost::optional<std::string>("Origin"));
+ userTune->setLength(226);
- std::string expectedResult =
- "<tune xmlns=\"http://jabber.org/protocol/tune\">"
- "<title>Minion</title><track>Yellow</track><artist>Ice</artist><source>Origin</source><length>226</length></tune>";
+ std::string expectedResult =
+ "<tune xmlns=\"http://jabber.org/protocol/tune\">"
+ "<title>Minion</title><track>Yellow</track><artist>Ice</artist><source>Origin</source><length>226</length></tune>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userTune));
- }
- private:
- FullPayloadSerializerCollection serializers;
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userTune));
+ }
+ private:
+ FullPayloadSerializerCollection serializers;
};
CPPUNIT_TEST_SUITE_REGISTRATION(UserTuneSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp
index d0385d3..c4a8156 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp
@@ -13,136 +13,136 @@ using namespace Swift;
class VCardSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(VCardSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- VCardSerializer testling;
- boost::shared_ptr<VCard> vcard(new VCard());
- vcard->setVersion("2.0");
- vcard->setFullName("Alice In Wonderland");
- vcard->setPrefix("Mrs");
- vcard->setGivenName("Alice");
- vcard->setMiddleName("In");
- vcard->setFamilyName("Wonderland");
- vcard->setSuffix("PhD");
- vcard->setNickname("DreamGirl");
- vcard->setPhoto(createByteArray("abcdef"));
- vcard->setPhotoType("image/png");
- vcard->setBirthday(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4)));
- vcard->addUnknownContent("<MAILER>mutt</MAILER>");
-
- VCard::EMailAddress emailAddress1;
- emailAddress1.address = "alice@wonderland.lit";
- emailAddress1.isHome = true;
- emailAddress1.isPreferred = true;
- emailAddress1.isInternet = true;
- vcard->addEMailAddress(emailAddress1);
-
- VCard::EMailAddress address2;
- address2.address = "alice@teaparty.lit";
- address2.isWork = true;
- address2.isX400 = true;
- vcard->addEMailAddress(address2);
-
- VCard::Telephone telephone1;
- telephone1.number = "555-6273";
- telephone1.isHome = true;
- telephone1.isVoice = true;
- vcard->addTelephone(telephone1);
-
- VCard::Address address1;
- address1.locality = "Any Town";
- address1.street = "Fake Street 123";
- address1.postalCode = "12345";
- address1.country = "USA";
- address1.isHome = true;
- vcard->addAddress(address1);
-
- VCard::AddressLabel label1;
- label1.lines.push_back("Fake Street 123");
- label1.lines.push_back("12345 Any Town");
- label1.lines.push_back("USA");
- label1.isHome = true;
- vcard->addAddressLabel(label1);
-
- vcard->addJID(JID("alice@teaparty.lit"));
- vcard->addJID(JID("alice@wonderland.lit"));
-
- vcard->setDescription("I once fell down a rabbit hole.");
-
- VCard::Organization org1;
- org1.name = "Alice In Wonderland Inc.";
- vcard->addOrganization(org1);
-
- vcard->addTitle("Some Title");
- vcard->addRole("Main Character");
- vcard->addURL("http://wonderland.lit/~alice");
- vcard->addURL("http://teaparty.lit/~alice2");
-
- std::string expectedResult =
- "<vCard xmlns=\"vcard-temp\">"
- "<VERSION>2.0</VERSION>"
- "<FN>Alice In Wonderland</FN>"
- "<N>"
- "<FAMILY>Wonderland</FAMILY>"
- "<GIVEN>Alice</GIVEN>"
- "<MIDDLE>In</MIDDLE>"
- "<PREFIX>Mrs</PREFIX>"
- "<SUFFIX>PhD</SUFFIX>"
- "</N>"
- "<EMAIL>"
- "<USERID>alice@wonderland.lit</USERID>"
- "<HOME/>"
- "<INTERNET/>"
- "<PREF/>"
- "</EMAIL>"
- "<EMAIL>"
- "<USERID>alice@teaparty.lit</USERID>"
- "<WORK/>"
- "<X400/>"
- "</EMAIL>"
- "<NICKNAME>DreamGirl</NICKNAME>"
- "<PHOTO>"
- "<TYPE>image/png</TYPE>"
- "<BINVAL>YWJjZGVm</BINVAL>"
- "</PHOTO>"
- "<BDAY>1865-05-04T00:00:00Z</BDAY>"
- "<TEL>"
- "<NUMBER>555-6273</NUMBER>"
- "<HOME/>"
- "<VOICE/>"
- "</TEL>"
- "<ADR>"
- "<STREET>Fake Street 123</STREET>"
- "<LOCALITY>Any Town</LOCALITY>"
- "<PCODE>12345</PCODE>"
- "<CTRY>USA</CTRY>"
- "<HOME/>"
- "</ADR>"
- "<LABEL>"
- "<LINE>Fake Street 123</LINE>"
- "<LINE>12345 Any Town</LINE>"
- "<LINE>USA</LINE>"
- "<HOME/>"
- "</LABEL>"
- "<JID>alice@teaparty.lit</JID>"
- "<JID>alice@wonderland.lit</JID>"
- "<DESC>I once fell down a rabbit hole.</DESC>"
- "<ORG>"
- "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>"
- "</ORG>"
- "<TITLE>Some Title</TITLE>"
- "<ROLE>Main Character</ROLE>"
- "<URL>http://wonderland.lit/~alice</URL>"
- "<URL>http://teaparty.lit/~alice2</URL>"
- "<MAILER>mutt</MAILER>"
- "</vCard>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(vcard));
- }
+ CPPUNIT_TEST_SUITE(VCardSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ VCardSerializer testling;
+ boost::shared_ptr<VCard> vcard(new VCard());
+ vcard->setVersion("2.0");
+ vcard->setFullName("Alice In Wonderland");
+ vcard->setPrefix("Mrs");
+ vcard->setGivenName("Alice");
+ vcard->setMiddleName("In");
+ vcard->setFamilyName("Wonderland");
+ vcard->setSuffix("PhD");
+ vcard->setNickname("DreamGirl");
+ vcard->setPhoto(createByteArray("abcdef"));
+ vcard->setPhotoType("image/png");
+ vcard->setBirthday(boost::posix_time::ptime(boost::gregorian::date(1865, 5, 4)));
+ vcard->addUnknownContent("<MAILER>mutt</MAILER>");
+
+ VCard::EMailAddress emailAddress1;
+ emailAddress1.address = "alice@wonderland.lit";
+ emailAddress1.isHome = true;
+ emailAddress1.isPreferred = true;
+ emailAddress1.isInternet = true;
+ vcard->addEMailAddress(emailAddress1);
+
+ VCard::EMailAddress address2;
+ address2.address = "alice@teaparty.lit";
+ address2.isWork = true;
+ address2.isX400 = true;
+ vcard->addEMailAddress(address2);
+
+ VCard::Telephone telephone1;
+ telephone1.number = "555-6273";
+ telephone1.isHome = true;
+ telephone1.isVoice = true;
+ vcard->addTelephone(telephone1);
+
+ VCard::Address address1;
+ address1.locality = "Any Town";
+ address1.street = "Fake Street 123";
+ address1.postalCode = "12345";
+ address1.country = "USA";
+ address1.isHome = true;
+ vcard->addAddress(address1);
+
+ VCard::AddressLabel label1;
+ label1.lines.push_back("Fake Street 123");
+ label1.lines.push_back("12345 Any Town");
+ label1.lines.push_back("USA");
+ label1.isHome = true;
+ vcard->addAddressLabel(label1);
+
+ vcard->addJID(JID("alice@teaparty.lit"));
+ vcard->addJID(JID("alice@wonderland.lit"));
+
+ vcard->setDescription("I once fell down a rabbit hole.");
+
+ VCard::Organization org1;
+ org1.name = "Alice In Wonderland Inc.";
+ vcard->addOrganization(org1);
+
+ vcard->addTitle("Some Title");
+ vcard->addRole("Main Character");
+ vcard->addURL("http://wonderland.lit/~alice");
+ vcard->addURL("http://teaparty.lit/~alice2");
+
+ std::string expectedResult =
+ "<vCard xmlns=\"vcard-temp\">"
+ "<VERSION>2.0</VERSION>"
+ "<FN>Alice In Wonderland</FN>"
+ "<N>"
+ "<FAMILY>Wonderland</FAMILY>"
+ "<GIVEN>Alice</GIVEN>"
+ "<MIDDLE>In</MIDDLE>"
+ "<PREFIX>Mrs</PREFIX>"
+ "<SUFFIX>PhD</SUFFIX>"
+ "</N>"
+ "<EMAIL>"
+ "<USERID>alice@wonderland.lit</USERID>"
+ "<HOME/>"
+ "<INTERNET/>"
+ "<PREF/>"
+ "</EMAIL>"
+ "<EMAIL>"
+ "<USERID>alice@teaparty.lit</USERID>"
+ "<WORK/>"
+ "<X400/>"
+ "</EMAIL>"
+ "<NICKNAME>DreamGirl</NICKNAME>"
+ "<PHOTO>"
+ "<TYPE>image/png</TYPE>"
+ "<BINVAL>YWJjZGVm</BINVAL>"
+ "</PHOTO>"
+ "<BDAY>1865-05-04T00:00:00Z</BDAY>"
+ "<TEL>"
+ "<NUMBER>555-6273</NUMBER>"
+ "<HOME/>"
+ "<VOICE/>"
+ "</TEL>"
+ "<ADR>"
+ "<STREET>Fake Street 123</STREET>"
+ "<LOCALITY>Any Town</LOCALITY>"
+ "<PCODE>12345</PCODE>"
+ "<CTRY>USA</CTRY>"
+ "<HOME/>"
+ "</ADR>"
+ "<LABEL>"
+ "<LINE>Fake Street 123</LINE>"
+ "<LINE>12345 Any Town</LINE>"
+ "<LINE>USA</LINE>"
+ "<HOME/>"
+ "</LABEL>"
+ "<JID>alice@teaparty.lit</JID>"
+ "<JID>alice@wonderland.lit</JID>"
+ "<DESC>I once fell down a rabbit hole.</DESC>"
+ "<ORG>"
+ "<ORGNAME>Alice In Wonderland Inc.</ORGNAME>"
+ "</ORG>"
+ "<TITLE>Some Title</TITLE>"
+ "<ROLE>Main Character</ROLE>"
+ "<URL>http://wonderland.lit/~alice</URL>"
+ "<URL>http://teaparty.lit/~alice2</URL>"
+ "<MAILER>mutt</MAILER>"
+ "</vCard>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(vcard));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp
index fd2bb42..ed0500a 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp
@@ -13,25 +13,25 @@ using namespace Swift;
class VCardUpdateSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(VCardUpdateSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(VCardUpdateSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
- public:
- VCardUpdateSerializerTest() {}
+ public:
+ VCardUpdateSerializerTest() {}
- void testSerialize() {
- VCardUpdateSerializer testling;
- boost::shared_ptr<VCardUpdate> update(new VCardUpdate());
- update->setPhotoHash("sha1-hash-of-image");
+ void testSerialize() {
+ VCardUpdateSerializer testling;
+ boost::shared_ptr<VCardUpdate> update(new VCardUpdate());
+ update->setPhotoHash("sha1-hash-of-image");
- std::string expectedResult =
- "<x xmlns=\"vcard-temp:x:update\">"
- "<photo>sha1-hash-of-image</photo>"
- "</x>";
+ std::string expectedResult =
+ "<x xmlns=\"vcard-temp:x:update\">"
+ "<photo>sha1-hash-of-image</photo>"
+ "</x>";
- CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(update));
- }
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(update));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardUpdateSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp
index 130e8a2..2383cc8 100644
--- a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp
@@ -24,77 +24,77 @@ UserLocationSerializer::~UserLocationSerializer() {
}
std::string UserLocationSerializer::serializePayload(boost::shared_ptr<UserLocation> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("geoloc", "http://jabber.org/protocol/geoloc");
- if (payload->getArea()) {
- element.addNode(boost::make_shared<XMLElement>("area", "", *payload->getArea()));
- }
- if (payload->getAltitude()) {
- element.addNode(boost::make_shared<XMLElement>("alt", "", boost::lexical_cast<std::string>(*payload->getAltitude())));
- }
- if (payload->getLocality()) {
- element.addNode(boost::make_shared<XMLElement>("locality", "", *payload->getLocality()));
- }
- if (payload->getLatitude()) {
- element.addNode(boost::make_shared<XMLElement>("lat", "", boost::lexical_cast<std::string>(*payload->getLatitude())));
- }
- if (payload->getAccuracy()) {
- element.addNode(boost::make_shared<XMLElement>("accuracy", "", boost::lexical_cast<std::string>(*payload->getAccuracy())));
- }
- if (payload->getDescription()) {
- element.addNode(boost::make_shared<XMLElement>("description", "", *payload->getDescription()));
- }
- if (payload->getCountryCode()) {
- element.addNode(boost::make_shared<XMLElement>("countrycode", "", *payload->getCountryCode()));
- }
- if (payload->getTimestamp()) {
- element.addNode(boost::make_shared<XMLElement>("timestamp", "", dateTimeToString(*payload->getTimestamp())));
- }
- if (payload->getFloor()) {
- element.addNode(boost::make_shared<XMLElement>("floor", "", *payload->getFloor()));
- }
- if (payload->getBuilding()) {
- element.addNode(boost::make_shared<XMLElement>("building", "", *payload->getBuilding()));
- }
- if (payload->getRoom()) {
- element.addNode(boost::make_shared<XMLElement>("room", "", *payload->getRoom()));
- }
- if (payload->getCountry()) {
- element.addNode(boost::make_shared<XMLElement>("country", "", *payload->getCountry()));
- }
- if (payload->getRegion()) {
- element.addNode(boost::make_shared<XMLElement>("region", "", *payload->getRegion()));
- }
- if (payload->getURI()) {
- element.addNode(boost::make_shared<XMLElement>("uri", "", *payload->getURI()));
- }
- if (payload->getLongitude()) {
- element.addNode(boost::make_shared<XMLElement>("lon", "", boost::lexical_cast<std::string>(*payload->getLongitude())));
- }
- if (payload->getError()) {
- element.addNode(boost::make_shared<XMLElement>("error", "", boost::lexical_cast<std::string>(*payload->getError())));
- }
- if (payload->getPostalCode()) {
- element.addNode(boost::make_shared<XMLElement>("postalcode", "", *payload->getPostalCode()));
- }
- if (payload->getBearing()) {
- element.addNode(boost::make_shared<XMLElement>("bearing", "", boost::lexical_cast<std::string>(*payload->getBearing())));
- }
- if (payload->getText()) {
- element.addNode(boost::make_shared<XMLElement>("text", "", *payload->getText()));
- }
- if (payload->getDatum()) {
- element.addNode(boost::make_shared<XMLElement>("datum", "", *payload->getDatum()));
- }
- if (payload->getStreet()) {
- element.addNode(boost::make_shared<XMLElement>("street", "", *payload->getStreet()));
- }
- if (payload->getSpeed()) {
- element.addNode(boost::make_shared<XMLElement>("speed", "", boost::lexical_cast<std::string>(*payload->getSpeed())));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("geoloc", "http://jabber.org/protocol/geoloc");
+ if (payload->getArea()) {
+ element.addNode(boost::make_shared<XMLElement>("area", "", *payload->getArea()));
+ }
+ if (payload->getAltitude()) {
+ element.addNode(boost::make_shared<XMLElement>("alt", "", boost::lexical_cast<std::string>(*payload->getAltitude())));
+ }
+ if (payload->getLocality()) {
+ element.addNode(boost::make_shared<XMLElement>("locality", "", *payload->getLocality()));
+ }
+ if (payload->getLatitude()) {
+ element.addNode(boost::make_shared<XMLElement>("lat", "", boost::lexical_cast<std::string>(*payload->getLatitude())));
+ }
+ if (payload->getAccuracy()) {
+ element.addNode(boost::make_shared<XMLElement>("accuracy", "", boost::lexical_cast<std::string>(*payload->getAccuracy())));
+ }
+ if (payload->getDescription()) {
+ element.addNode(boost::make_shared<XMLElement>("description", "", *payload->getDescription()));
+ }
+ if (payload->getCountryCode()) {
+ element.addNode(boost::make_shared<XMLElement>("countrycode", "", *payload->getCountryCode()));
+ }
+ if (payload->getTimestamp()) {
+ element.addNode(boost::make_shared<XMLElement>("timestamp", "", dateTimeToString(*payload->getTimestamp())));
+ }
+ if (payload->getFloor()) {
+ element.addNode(boost::make_shared<XMLElement>("floor", "", *payload->getFloor()));
+ }
+ if (payload->getBuilding()) {
+ element.addNode(boost::make_shared<XMLElement>("building", "", *payload->getBuilding()));
+ }
+ if (payload->getRoom()) {
+ element.addNode(boost::make_shared<XMLElement>("room", "", *payload->getRoom()));
+ }
+ if (payload->getCountry()) {
+ element.addNode(boost::make_shared<XMLElement>("country", "", *payload->getCountry()));
+ }
+ if (payload->getRegion()) {
+ element.addNode(boost::make_shared<XMLElement>("region", "", *payload->getRegion()));
+ }
+ if (payload->getURI()) {
+ element.addNode(boost::make_shared<XMLElement>("uri", "", *payload->getURI()));
+ }
+ if (payload->getLongitude()) {
+ element.addNode(boost::make_shared<XMLElement>("lon", "", boost::lexical_cast<std::string>(*payload->getLongitude())));
+ }
+ if (payload->getError()) {
+ element.addNode(boost::make_shared<XMLElement>("error", "", boost::lexical_cast<std::string>(*payload->getError())));
+ }
+ if (payload->getPostalCode()) {
+ element.addNode(boost::make_shared<XMLElement>("postalcode", "", *payload->getPostalCode()));
+ }
+ if (payload->getBearing()) {
+ element.addNode(boost::make_shared<XMLElement>("bearing", "", boost::lexical_cast<std::string>(*payload->getBearing())));
+ }
+ if (payload->getText()) {
+ element.addNode(boost::make_shared<XMLElement>("text", "", *payload->getText()));
+ }
+ if (payload->getDatum()) {
+ element.addNode(boost::make_shared<XMLElement>("datum", "", *payload->getDatum()));
+ }
+ if (payload->getStreet()) {
+ element.addNode(boost::make_shared<XMLElement>("street", "", *payload->getStreet()));
+ }
+ if (payload->getSpeed()) {
+ element.addNode(boost::make_shared<XMLElement>("speed", "", boost::lexical_cast<std::string>(*payload->getSpeed())));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h
index acfc16c..4b17628 100644
--- a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API UserLocationSerializer : public GenericPayloadSerializer<UserLocation> {
- public:
- UserLocationSerializer(PayloadSerializerCollection* serializers);
- virtual ~UserLocationSerializer();
+ class SWIFTEN_API UserLocationSerializer : public GenericPayloadSerializer<UserLocation> {
+ public:
+ UserLocationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~UserLocationSerializer();
- virtual std::string serializePayload(boost::shared_ptr<UserLocation>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<UserLocation>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
index fd6eebd..eeab2b7 100644
--- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
@@ -23,32 +23,32 @@ UserTuneSerializer::~UserTuneSerializer() {
}
std::string UserTuneSerializer::serializePayload(boost::shared_ptr<UserTune> payload) const {
- if (!payload) {
- return "";
- }
- XMLElement element("tune", "http://jabber.org/protocol/tune");
- if (payload->getRating()) {
- element.addNode(boost::make_shared<XMLElement>("rating", "", boost::lexical_cast<std::string>(*payload->getRating())));
- }
- if (payload->getTitle()) {
- element.addNode(boost::make_shared<XMLElement>("title", "", *payload->getTitle()));
- }
- if (payload->getTrack()) {
- element.addNode(boost::make_shared<XMLElement>("track", "", *payload->getTrack()));
- }
- if (payload->getArtist()) {
- element.addNode(boost::make_shared<XMLElement>("artist", "", *payload->getArtist()));
- }
- if (payload->getURI()) {
- element.addNode(boost::make_shared<XMLElement>("uri", "", *payload->getURI()));
- }
- if (payload->getSource()) {
- element.addNode(boost::make_shared<XMLElement>("source", "", *payload->getSource()));
- }
- if (payload->getLength()) {
- element.addNode(boost::make_shared<XMLElement>("length", "", boost::lexical_cast<std::string>(*payload->getLength())));
- }
- return element.serialize();
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("tune", "http://jabber.org/protocol/tune");
+ if (payload->getRating()) {
+ element.addNode(boost::make_shared<XMLElement>("rating", "", boost::lexical_cast<std::string>(*payload->getRating())));
+ }
+ if (payload->getTitle()) {
+ element.addNode(boost::make_shared<XMLElement>("title", "", *payload->getTitle()));
+ }
+ if (payload->getTrack()) {
+ element.addNode(boost::make_shared<XMLElement>("track", "", *payload->getTrack()));
+ }
+ if (payload->getArtist()) {
+ element.addNode(boost::make_shared<XMLElement>("artist", "", *payload->getArtist()));
+ }
+ if (payload->getURI()) {
+ element.addNode(boost::make_shared<XMLElement>("uri", "", *payload->getURI()));
+ }
+ if (payload->getSource()) {
+ element.addNode(boost::make_shared<XMLElement>("source", "", *payload->getSource()));
+ }
+ if (payload->getLength()) {
+ element.addNode(boost::make_shared<XMLElement>("length", "", boost::lexical_cast<std::string>(*payload->getLength())));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h
index 13f56ae..1d3c76b 100644
--- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h
@@ -14,19 +14,19 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
+ class PayloadSerializerCollection;
- class SWIFTEN_API UserTuneSerializer : public GenericPayloadSerializer<UserTune> {
- public:
- UserTuneSerializer(PayloadSerializerCollection* serializers);
- virtual ~UserTuneSerializer();
+ class SWIFTEN_API UserTuneSerializer : public GenericPayloadSerializer<UserTune> {
+ public:
+ UserTuneSerializer(PayloadSerializerCollection* serializers);
+ virtual ~UserTuneSerializer();
- virtual std::string serializePayload(boost::shared_ptr<UserTune>) const SWIFTEN_OVERRIDE;
+ virtual std::string serializePayload(boost::shared_ptr<UserTune>) const SWIFTEN_OVERRIDE;
- private:
-
+ private:
- private:
- PayloadSerializerCollection* serializers;
- };
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
index 2b1d179..98597e4 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
@@ -22,230 +22,230 @@ VCardSerializer::VCardSerializer() : GenericPayloadSerializer<VCard>() {
}
std::string VCardSerializer::serializePayload(boost::shared_ptr<VCard> vcard) const {
- XMLElement queryElement("vCard", "vcard-temp");
- if (!vcard->getVersion().empty()) {
- queryElement.addNode(boost::make_shared<XMLElement>("VERSION", "", vcard->getVersion()));
- }
- if (!vcard->getFullName().empty()) {
- queryElement.addNode(boost::make_shared<XMLElement>("FN", "", vcard->getFullName()));
- }
- if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) {
- boost::shared_ptr<XMLElement> nameElement(new XMLElement("N"));
- if (!vcard->getFamilyName().empty()) {
- nameElement->addNode(boost::make_shared<XMLElement>("FAMILY", "", vcard->getFamilyName()));
- }
- if (!vcard->getGivenName().empty()) {
- nameElement->addNode(boost::make_shared<XMLElement>("GIVEN", "", vcard->getGivenName()));
- }
- if (!vcard->getMiddleName().empty()) {
- nameElement->addNode(boost::make_shared<XMLElement>("MIDDLE", "", vcard->getMiddleName()));
- }
- if (!vcard->getPrefix().empty()) {
- nameElement->addNode(boost::make_shared<XMLElement>("PREFIX", "", vcard->getPrefix()));
- }
- if (!vcard->getSuffix().empty()) {
- nameElement->addNode(boost::make_shared<XMLElement>("SUFFIX", "", vcard->getSuffix()));
- }
- queryElement.addNode(nameElement);
- }
- foreach(const VCard::EMailAddress& emailAddress, vcard->getEMailAddresses()) {
- boost::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL"));
- emailElement->addNode(boost::make_shared<XMLElement>("USERID", "", emailAddress.address));
- if (emailAddress.isHome) {
- emailElement->addNode(boost::make_shared<XMLElement>("HOME"));
- }
- if (emailAddress.isWork) {
- emailElement->addNode(boost::make_shared<XMLElement>("WORK"));
- }
- if (emailAddress.isInternet) {
- emailElement->addNode(boost::make_shared<XMLElement>("INTERNET"));
- }
- if (emailAddress.isPreferred) {
- emailElement->addNode(boost::make_shared<XMLElement>("PREF"));
- }
- if (emailAddress.isX400) {
- emailElement->addNode(boost::make_shared<XMLElement>("X400"));
- }
- queryElement.addNode(emailElement);
- }
- if (!vcard->getNickname().empty()) {
- queryElement.addNode(boost::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(boost::make_shared<XMLElement>("TYPE", "", vcard->getPhotoType()));
- }
- if (!vcard->getPhoto().empty()) {
- photoElement->addNode(boost::make_shared<XMLElement>("BINVAL", "", Base64::encode(vcard->getPhoto())));
- }
- queryElement.addNode(photoElement);
- }
- if (!vcard->getBirthday().is_not_a_date_time()) {
- queryElement.addNode(boost::make_shared<XMLElement>("BDAY", "", dateTimeToString(vcard->getBirthday())));
- }
-
- foreach(const VCard::Telephone& telephone, vcard->getTelephones()) {
- boost::shared_ptr<XMLElement> telElement(new XMLElement("TEL"));
- telElement->addNode(boost::make_shared<XMLElement>("NUMBER", "", telephone.number));
- if (telephone.isHome) {
- telElement->addNode(boost::make_shared<XMLElement>("HOME"));
- }
- if (telephone.isWork) {
- telElement->addNode(boost::make_shared<XMLElement>("WORK"));
- }
- if (telephone.isVoice) {
- telElement->addNode(boost::make_shared<XMLElement>("VOICE"));
- }
- if (telephone.isFax) {
- telElement->addNode(boost::make_shared<XMLElement>("FAX"));
- }
- if (telephone.isPager) {
- telElement->addNode(boost::make_shared<XMLElement>("PAGER"));
- }
- if (telephone.isMSG) {
- telElement->addNode(boost::make_shared<XMLElement>("MSG"));
- }
- if (telephone.isCell) {
- telElement->addNode(boost::make_shared<XMLElement>("CELL"));
- }
- if (telephone.isVideo) {
- telElement->addNode(boost::make_shared<XMLElement>("VIDEO"));
- }
- if (telephone.isBBS) {
- telElement->addNode(boost::make_shared<XMLElement>("BBS"));
- }
- if (telephone.isModem) {
- telElement->addNode(boost::make_shared<XMLElement>("MODEM"));
- }
- if (telephone.isISDN) {
- telElement->addNode(boost::make_shared<XMLElement>("ISDN"));
- }
- if (telephone.isPCS) {
- telElement->addNode(boost::make_shared<XMLElement>("PCS"));
- }
- if (telephone.isPreferred) {
- telElement->addNode(boost::make_shared<XMLElement>("PREF"));
- }
- queryElement.addNode(telElement);
- }
-
- foreach(const VCard::Address& address, vcard->getAddresses()) {
- boost::shared_ptr<XMLElement> adrElement = boost::make_shared<XMLElement>("ADR");
- if (!address.poBox.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("POBOX", "", address.poBox));
- }
- if (!address.addressExtension.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("EXTADD", "", address.addressExtension));
- }
- if (!address.street.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("STREET", "", address.street));
- }
- if (!address.locality.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("LOCALITY", "", address.locality));
- }
- if (!address.region.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("REGION", "", address.region));
- }
- if (!address.postalCode.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("PCODE", "", address.postalCode));
- }
- if (!address.country.empty()) {
- adrElement->addNode(boost::make_shared<XMLElement>("CTRY", "", address.country));
- }
-
- if (address.isHome) {
- adrElement->addNode(boost::make_shared<XMLElement>("HOME"));
- }
- if (address.isWork) {
- adrElement->addNode(boost::make_shared<XMLElement>("WORK"));
- }
- if (address.isPostal) {
- adrElement->addNode(boost::make_shared<XMLElement>("POSTAL"));
- }
- if (address.isParcel) {
- adrElement->addNode(boost::make_shared<XMLElement>("PARCEL"));
- }
- if (address.deliveryType == VCard::DomesticDelivery) {
- adrElement->addNode(boost::make_shared<XMLElement>("DOM"));
- }
- if (address.deliveryType == VCard::InternationalDelivery) {
- adrElement->addNode(boost::make_shared<XMLElement>("INTL"));
- }
- if (address.isPreferred) {
- adrElement->addNode(boost::make_shared<XMLElement>("PREF"));
- }
- queryElement.addNode(adrElement);
- }
-
- foreach(const VCard::AddressLabel& addressLabel, vcard->getAddressLabels()) {
- boost::shared_ptr<XMLElement> labelElement = boost::make_shared<XMLElement>("LABEL");
-
- foreach(const std::string& line, addressLabel.lines) {
- labelElement->addNode(boost::make_shared<XMLElement>("LINE", "", line));
- }
-
- if (addressLabel.isHome) {
- labelElement->addNode(boost::make_shared<XMLElement>("HOME"));
- }
- if (addressLabel.isWork) {
- labelElement->addNode(boost::make_shared<XMLElement>("WORK"));
- }
- if (addressLabel.isPostal) {
- labelElement->addNode(boost::make_shared<XMLElement>("POSTAL"));
- }
- if (addressLabel.isParcel) {
- labelElement->addNode(boost::make_shared<XMLElement>("PARCEL"));
- }
- if (addressLabel.deliveryType == VCard::DomesticDelivery) {
- labelElement->addNode(boost::make_shared<XMLElement>("DOM"));
- }
- if (addressLabel.deliveryType == VCard::InternationalDelivery) {
- labelElement->addNode(boost::make_shared<XMLElement>("INTL"));
- }
- if (addressLabel.isPreferred) {
- labelElement->addNode(boost::make_shared<XMLElement>("PREF"));
- }
- queryElement.addNode(labelElement);
- }
-
- foreach(const JID& jid, vcard->getJIDs()) {
- queryElement.addNode(boost::make_shared<XMLElement>("JID", "", jid.toString()));
- }
-
- if (!vcard->getDescription().empty()) {
- queryElement.addNode(boost::make_shared<XMLElement>("DESC", "", vcard->getDescription()));
- }
-
- foreach(const VCard::Organization& org, vcard->getOrganizations()) {
- boost::shared_ptr<XMLElement> orgElement = boost::make_shared<XMLElement>("ORG");
- if (!org.name.empty()) {
- orgElement->addNode(boost::make_shared<XMLElement>("ORGNAME", "", org.name));
- }
- if (!org.units.empty()) {
- foreach(const std::string& unit, org.units) {
- orgElement->addNode(boost::make_shared<XMLElement>("ORGUNIT", "", unit));
- }
- }
- queryElement.addNode(orgElement);
- }
-
- foreach(const std::string& title, vcard->getTitles()) {
- queryElement.addNode(boost::make_shared<XMLElement>("TITLE", "", title));
- }
-
- foreach(const std::string& role, vcard->getRoles()) {
- queryElement.addNode(boost::make_shared<XMLElement>("ROLE", "", role));
- }
-
- foreach(const std::string& url, vcard->getURLs()) {
- queryElement.addNode(boost::make_shared<XMLElement>("URL", "", url));
- }
-
- if (!vcard->getUnknownContent().empty()) {
- queryElement.addNode(boost::make_shared<XMLRawTextNode>(vcard->getUnknownContent()));
- }
- return queryElement.serialize();
+ XMLElement queryElement("vCard", "vcard-temp");
+ if (!vcard->getVersion().empty()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("VERSION", "", vcard->getVersion()));
+ }
+ if (!vcard->getFullName().empty()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("FN", "", vcard->getFullName()));
+ }
+ if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) {
+ boost::shared_ptr<XMLElement> nameElement(new XMLElement("N"));
+ if (!vcard->getFamilyName().empty()) {
+ nameElement->addNode(boost::make_shared<XMLElement>("FAMILY", "", vcard->getFamilyName()));
+ }
+ if (!vcard->getGivenName().empty()) {
+ nameElement->addNode(boost::make_shared<XMLElement>("GIVEN", "", vcard->getGivenName()));
+ }
+ if (!vcard->getMiddleName().empty()) {
+ nameElement->addNode(boost::make_shared<XMLElement>("MIDDLE", "", vcard->getMiddleName()));
+ }
+ if (!vcard->getPrefix().empty()) {
+ nameElement->addNode(boost::make_shared<XMLElement>("PREFIX", "", vcard->getPrefix()));
+ }
+ if (!vcard->getSuffix().empty()) {
+ nameElement->addNode(boost::make_shared<XMLElement>("SUFFIX", "", vcard->getSuffix()));
+ }
+ queryElement.addNode(nameElement);
+ }
+ foreach(const VCard::EMailAddress& emailAddress, vcard->getEMailAddresses()) {
+ boost::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL"));
+ emailElement->addNode(boost::make_shared<XMLElement>("USERID", "", emailAddress.address));
+ if (emailAddress.isHome) {
+ emailElement->addNode(boost::make_shared<XMLElement>("HOME"));
+ }
+ if (emailAddress.isWork) {
+ emailElement->addNode(boost::make_shared<XMLElement>("WORK"));
+ }
+ if (emailAddress.isInternet) {
+ emailElement->addNode(boost::make_shared<XMLElement>("INTERNET"));
+ }
+ if (emailAddress.isPreferred) {
+ emailElement->addNode(boost::make_shared<XMLElement>("PREF"));
+ }
+ if (emailAddress.isX400) {
+ emailElement->addNode(boost::make_shared<XMLElement>("X400"));
+ }
+ queryElement.addNode(emailElement);
+ }
+ if (!vcard->getNickname().empty()) {
+ queryElement.addNode(boost::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(boost::make_shared<XMLElement>("TYPE", "", vcard->getPhotoType()));
+ }
+ if (!vcard->getPhoto().empty()) {
+ photoElement->addNode(boost::make_shared<XMLElement>("BINVAL", "", Base64::encode(vcard->getPhoto())));
+ }
+ queryElement.addNode(photoElement);
+ }
+ if (!vcard->getBirthday().is_not_a_date_time()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("BDAY", "", dateTimeToString(vcard->getBirthday())));
+ }
+
+ foreach(const VCard::Telephone& telephone, vcard->getTelephones()) {
+ boost::shared_ptr<XMLElement> telElement(new XMLElement("TEL"));
+ telElement->addNode(boost::make_shared<XMLElement>("NUMBER", "", telephone.number));
+ if (telephone.isHome) {
+ telElement->addNode(boost::make_shared<XMLElement>("HOME"));
+ }
+ if (telephone.isWork) {
+ telElement->addNode(boost::make_shared<XMLElement>("WORK"));
+ }
+ if (telephone.isVoice) {
+ telElement->addNode(boost::make_shared<XMLElement>("VOICE"));
+ }
+ if (telephone.isFax) {
+ telElement->addNode(boost::make_shared<XMLElement>("FAX"));
+ }
+ if (telephone.isPager) {
+ telElement->addNode(boost::make_shared<XMLElement>("PAGER"));
+ }
+ if (telephone.isMSG) {
+ telElement->addNode(boost::make_shared<XMLElement>("MSG"));
+ }
+ if (telephone.isCell) {
+ telElement->addNode(boost::make_shared<XMLElement>("CELL"));
+ }
+ if (telephone.isVideo) {
+ telElement->addNode(boost::make_shared<XMLElement>("VIDEO"));
+ }
+ if (telephone.isBBS) {
+ telElement->addNode(boost::make_shared<XMLElement>("BBS"));
+ }
+ if (telephone.isModem) {
+ telElement->addNode(boost::make_shared<XMLElement>("MODEM"));
+ }
+ if (telephone.isISDN) {
+ telElement->addNode(boost::make_shared<XMLElement>("ISDN"));
+ }
+ if (telephone.isPCS) {
+ telElement->addNode(boost::make_shared<XMLElement>("PCS"));
+ }
+ if (telephone.isPreferred) {
+ telElement->addNode(boost::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(telElement);
+ }
+
+ foreach(const VCard::Address& address, vcard->getAddresses()) {
+ boost::shared_ptr<XMLElement> adrElement = boost::make_shared<XMLElement>("ADR");
+ if (!address.poBox.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("POBOX", "", address.poBox));
+ }
+ if (!address.addressExtension.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("EXTADD", "", address.addressExtension));
+ }
+ if (!address.street.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("STREET", "", address.street));
+ }
+ if (!address.locality.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("LOCALITY", "", address.locality));
+ }
+ if (!address.region.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("REGION", "", address.region));
+ }
+ if (!address.postalCode.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("PCODE", "", address.postalCode));
+ }
+ if (!address.country.empty()) {
+ adrElement->addNode(boost::make_shared<XMLElement>("CTRY", "", address.country));
+ }
+
+ if (address.isHome) {
+ adrElement->addNode(boost::make_shared<XMLElement>("HOME"));
+ }
+ if (address.isWork) {
+ adrElement->addNode(boost::make_shared<XMLElement>("WORK"));
+ }
+ if (address.isPostal) {
+ adrElement->addNode(boost::make_shared<XMLElement>("POSTAL"));
+ }
+ if (address.isParcel) {
+ adrElement->addNode(boost::make_shared<XMLElement>("PARCEL"));
+ }
+ if (address.deliveryType == VCard::DomesticDelivery) {
+ adrElement->addNode(boost::make_shared<XMLElement>("DOM"));
+ }
+ if (address.deliveryType == VCard::InternationalDelivery) {
+ adrElement->addNode(boost::make_shared<XMLElement>("INTL"));
+ }
+ if (address.isPreferred) {
+ adrElement->addNode(boost::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(adrElement);
+ }
+
+ foreach(const VCard::AddressLabel& addressLabel, vcard->getAddressLabels()) {
+ boost::shared_ptr<XMLElement> labelElement = boost::make_shared<XMLElement>("LABEL");
+
+ foreach(const std::string& line, addressLabel.lines) {
+ labelElement->addNode(boost::make_shared<XMLElement>("LINE", "", line));
+ }
+
+ if (addressLabel.isHome) {
+ labelElement->addNode(boost::make_shared<XMLElement>("HOME"));
+ }
+ if (addressLabel.isWork) {
+ labelElement->addNode(boost::make_shared<XMLElement>("WORK"));
+ }
+ if (addressLabel.isPostal) {
+ labelElement->addNode(boost::make_shared<XMLElement>("POSTAL"));
+ }
+ if (addressLabel.isParcel) {
+ labelElement->addNode(boost::make_shared<XMLElement>("PARCEL"));
+ }
+ if (addressLabel.deliveryType == VCard::DomesticDelivery) {
+ labelElement->addNode(boost::make_shared<XMLElement>("DOM"));
+ }
+ if (addressLabel.deliveryType == VCard::InternationalDelivery) {
+ labelElement->addNode(boost::make_shared<XMLElement>("INTL"));
+ }
+ if (addressLabel.isPreferred) {
+ labelElement->addNode(boost::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(labelElement);
+ }
+
+ foreach(const JID& jid, vcard->getJIDs()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("JID", "", jid.toString()));
+ }
+
+ if (!vcard->getDescription().empty()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("DESC", "", vcard->getDescription()));
+ }
+
+ foreach(const VCard::Organization& org, vcard->getOrganizations()) {
+ boost::shared_ptr<XMLElement> orgElement = boost::make_shared<XMLElement>("ORG");
+ if (!org.name.empty()) {
+ orgElement->addNode(boost::make_shared<XMLElement>("ORGNAME", "", org.name));
+ }
+ if (!org.units.empty()) {
+ foreach(const std::string& unit, org.units) {
+ orgElement->addNode(boost::make_shared<XMLElement>("ORGUNIT", "", unit));
+ }
+ }
+ queryElement.addNode(orgElement);
+ }
+
+ foreach(const std::string& title, vcard->getTitles()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("TITLE", "", title));
+ }
+
+ foreach(const std::string& role, vcard->getRoles()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("ROLE", "", role));
+ }
+
+ foreach(const std::string& url, vcard->getURLs()) {
+ queryElement.addNode(boost::make_shared<XMLElement>("URL", "", url));
+ }
+
+ if (!vcard->getUnknownContent().empty()) {
+ queryElement.addNode(boost::make_shared<XMLRawTextNode>(vcard->getUnknownContent()));
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.h b/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
index b4502f5..e84252d 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API VCardSerializer : public GenericPayloadSerializer<VCard> {
- public:
- VCardSerializer();
+ class SWIFTEN_API VCardSerializer : public GenericPayloadSerializer<VCard> {
+ public:
+ VCardSerializer();
- virtual std::string serializePayload(boost::shared_ptr<VCard>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<VCard>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
index 0edca0a..8fb1e3f 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
@@ -17,12 +17,12 @@ namespace Swift {
VCardUpdateSerializer::VCardUpdateSerializer() : GenericPayloadSerializer<VCardUpdate>() {
}
-std::string VCardUpdateSerializer::serializePayload(boost::shared_ptr<VCardUpdate> vcardUpdate) const {
- XMLElement updateElement("x", "vcard-temp:x:update");
- boost::shared_ptr<XMLElement> photoElement(new XMLElement("photo"));
- photoElement->addNode(boost::make_shared<XMLTextNode>(vcardUpdate->getPhotoHash()));
- updateElement.addNode(photoElement);
- return updateElement.serialize();
+std::string VCardUpdateSerializer::serializePayload(boost::shared_ptr<VCardUpdate> vcardUpdate) const {
+ XMLElement updateElement("x", "vcard-temp:x:update");
+ boost::shared_ptr<XMLElement> photoElement(new XMLElement("photo"));
+ photoElement->addNode(boost::make_shared<XMLTextNode>(vcardUpdate->getPhotoHash()));
+ updateElement.addNode(photoElement);
+ return updateElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h
index 87fb235..777da3e 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class SWIFTEN_API VCardUpdateSerializer : public GenericPayloadSerializer<VCardUpdate> {
- public:
- VCardUpdateSerializer();
+ class SWIFTEN_API VCardUpdateSerializer : public GenericPayloadSerializer<VCardUpdate> {
+ public:
+ VCardUpdateSerializer();
- virtual std::string serializePayload(boost::shared_ptr<VCardUpdate>) const;
- };
+ virtual std::string serializePayload(boost::shared_ptr<VCardUpdate>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
index b037e5a..27d3f57 100644
--- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
@@ -23,186 +23,186 @@
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
- void WhiteboardElementSerializingVisitor::visit(WhiteboardLineElement& line) {
- element = boost::make_shared<XMLElement>("line");
- try {
- element->setAttribute("x1", boost::lexical_cast<std::string>(line.x1()));
- element->setAttribute("y1", boost::lexical_cast<std::string>(line.y1()));
- element->setAttribute("x2", boost::lexical_cast<std::string>(line.x2()));
- element->setAttribute("y2", boost::lexical_cast<std::string>(line.y2()));
- element->setAttribute("id", line.getID());
- element->setAttribute("stroke", line.getColor().toHex());
- element->setAttribute("stroke-width", boost::lexical_cast<std::string>(line.getPenWidth()));
- element->setAttribute("opacity", alphaToOpacity(line.getColor().getAlpha()));
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- void WhiteboardElementSerializingVisitor::visit(WhiteboardFreehandPathElement& path) {
- element = boost::make_shared<XMLElement>("path");
- element->setAttribute("id", path.getID());
- element->setAttribute("stroke", path.getColor().toHex());
- try {
- element->setAttribute("stroke-width", boost::lexical_cast<std::string>(path.getPenWidth()));
- element->setAttribute("opacity", alphaToOpacity(path.getColor().getAlpha()));
- std::string pathData;
- if (path.getPoints().size() != 0) {
- std::vector<std::pair<int, int> >::const_iterator it = path.getPoints().begin();
- pathData = "M"+boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+"L";
- for (; it != path.getPoints().end(); ++it) {
- pathData += boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+" ";
- }
- }
- element->setAttribute("d", pathData);
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- void WhiteboardElementSerializingVisitor::visit(WhiteboardRectElement& rect) {
- element = boost::make_shared<XMLElement>("rect");
- try {
- element->setAttribute("x", boost::lexical_cast<std::string>(rect.getX()));
- element->setAttribute("y", boost::lexical_cast<std::string>(rect.getY()));
- element->setAttribute("width", boost::lexical_cast<std::string>(rect.getWidth()));
- element->setAttribute("height", boost::lexical_cast<std::string>(rect.getHeight()));
- element->setAttribute("id", rect.getID());
- element->setAttribute("stroke", rect.getPenColor().toHex());
- element->setAttribute("fill", rect.getBrushColor().toHex());;
- element->setAttribute("stroke-width", boost::lexical_cast<std::string>(rect.getPenWidth()));
- element->setAttribute("opacity", alphaToOpacity(rect.getPenColor().getAlpha()));
- element->setAttribute("fill-opacity", alphaToOpacity(rect.getBrushColor().getAlpha()));
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- void WhiteboardElementSerializingVisitor::visit(WhiteboardPolygonElement& polygon) {
- element = boost::make_shared<XMLElement>("polygon");
- try {
- element->setAttribute("id", polygon.getID());
- element->setAttribute("stroke", polygon.getPenColor().toHex());
- element->setAttribute("fill", polygon.getBrushColor().toHex());;
- element->setAttribute("stroke-width", boost::lexical_cast<std::string>(polygon.getPenWidth()));
- element->setAttribute("opacity", alphaToOpacity(polygon.getPenColor().getAlpha()));
- element->setAttribute("fill-opacity", alphaToOpacity(polygon.getBrushColor().getAlpha()));
- std::string points;
- std::vector<std::pair<int, int> >::const_iterator it = polygon.getPoints().begin();
- for (; it != polygon.getPoints().end(); ++it) {
- points += boost::lexical_cast<std::string>(it->first)+","+boost::lexical_cast<std::string>(it->second)+" ";
- }
- element->setAttribute("points", points);
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- void WhiteboardElementSerializingVisitor::visit(WhiteboardTextElement& text) {
- element = boost::make_shared<XMLElement>("text");
- try {
- element->setAttribute("x", boost::lexical_cast<std::string>(text.getX()));
- element->setAttribute("y", boost::lexical_cast<std::string>(text.getY()));
- element->setAttribute("font-size", boost::lexical_cast<std::string>(text.getSize()));
- element->setAttribute("id", text.getID());
- element->setAttribute("fill", text.getColor().toHex());
- element->setAttribute("opacity", alphaToOpacity(text.getColor().getAlpha()));
- element->addNode(boost::make_shared<XMLTextNode>(text.getText()));
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- void WhiteboardElementSerializingVisitor::visit(WhiteboardEllipseElement& ellipse) {
- element = boost::make_shared<XMLElement>("ellipse");
- try {
- element->setAttribute("cx", boost::lexical_cast<std::string>(ellipse.getCX()));
- element->setAttribute("cy", boost::lexical_cast<std::string>(ellipse.getCY()));
- element->setAttribute("rx", boost::lexical_cast<std::string>(ellipse.getRX()));
- element->setAttribute("ry", boost::lexical_cast<std::string>(ellipse.getRY()));
- element->setAttribute("id", ellipse.getID());
- element->setAttribute("stroke", ellipse.getPenColor().toHex());
- element->setAttribute("fill", ellipse.getBrushColor().toHex());;
- element->setAttribute("stroke-width", boost::lexical_cast<std::string>(ellipse.getPenWidth()));
- element->setAttribute("opacity", alphaToOpacity(ellipse.getPenColor().getAlpha()));
- element->setAttribute("fill-opacity", alphaToOpacity(ellipse.getBrushColor().getAlpha()));
- } catch (boost::bad_lexical_cast&) {
- }
- }
-
- XMLElement::ref WhiteboardElementSerializingVisitor::getResult() const {
- return element;
- }
-
- std::string WhiteboardElementSerializingVisitor::alphaToOpacity(int alpha) const {
- int opacity = 100*alpha/254;
- if (opacity == 100) {
- return "1";
- } else {
- return "."+boost::lexical_cast<std::string>(opacity);
- }
- }
-
- std::string WhiteboardSerializer::serializePayload(boost::shared_ptr<WhiteboardPayload> payload) const {
- XMLElement element("wb", "http://swift.im/whiteboard");
- if (payload->getType() == WhiteboardPayload::Data) {
- XMLElement::ref operationNode = boost::make_shared<XMLElement>("operation");
- WhiteboardElementSerializingVisitor visitor;
-// payload->getElement()->accept(visitor);
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(payload->getOperation());
- if (insertOp) {
- try {
- operationNode->setAttribute("type", "insert");
- operationNode->setAttribute("pos", boost::lexical_cast<std::string>(insertOp->getPos()));
- operationNode->setAttribute("id", insertOp->getID());
- operationNode->setAttribute("parentid", insertOp->getParentID());
- } catch (boost::bad_lexical_cast&) {
- }
- insertOp->getElement()->accept(visitor);
- operationNode->addNode(visitor.getResult());
- }
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(payload->getOperation());
- if (updateOp) {
- try {
- operationNode->setAttribute("type", "update");
- operationNode->setAttribute("pos", boost::lexical_cast<std::string>(updateOp->getPos()));
- operationNode->setAttribute("id", updateOp->getID());
- operationNode->setAttribute("parentid", updateOp->getParentID());
- operationNode->setAttribute("newpos", boost::lexical_cast<std::string>(updateOp->getNewPos()));
- } catch (boost::bad_lexical_cast&) {
- }
- updateOp->getElement()->accept(visitor);
- operationNode->addNode(visitor.getResult());
-
- }
-
- WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(payload->getOperation());
- if (deleteOp) {
- try {
- operationNode->setAttribute("type", "delete");
- operationNode->setAttribute("pos", boost::lexical_cast<std::string>(deleteOp->getPos()));
- operationNode->setAttribute("id", deleteOp->getID());
- operationNode->setAttribute("parentid", deleteOp->getParentID());
- operationNode->setAttribute("elementid", deleteOp->getElementID());
- } catch (boost::bad_lexical_cast&) {
- }
- }
- element.addNode(operationNode);
- }
- element.setAttribute("type", typeToString(payload->getType()));
- return element.serialize();
- }
-
- std::string WhiteboardSerializer::typeToString(WhiteboardPayload::Type type) const {
- switch (type) {
- case WhiteboardPayload::Data:
- return "data";
- case WhiteboardPayload::SessionRequest:
- return "session-request";
- case WhiteboardPayload::SessionAccept:
- return "session-accept";
- case WhiteboardPayload::SessionTerminate:
- return "session-terminate";
- case WhiteboardPayload::UnknownType:
- std::cerr << "Warning: Serializing unknown action value." << std::endl;
- return "";
- }
- assert(false);
- return "";
- }
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardLineElement& line) {
+ element = boost::make_shared<XMLElement>("line");
+ try {
+ element->setAttribute("x1", boost::lexical_cast<std::string>(line.x1()));
+ element->setAttribute("y1", boost::lexical_cast<std::string>(line.y1()));
+ element->setAttribute("x2", boost::lexical_cast<std::string>(line.x2()));
+ element->setAttribute("y2", boost::lexical_cast<std::string>(line.y2()));
+ element->setAttribute("id", line.getID());
+ element->setAttribute("stroke", line.getColor().toHex());
+ element->setAttribute("stroke-width", boost::lexical_cast<std::string>(line.getPenWidth()));
+ element->setAttribute("opacity", alphaToOpacity(line.getColor().getAlpha()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardFreehandPathElement& path) {
+ element = boost::make_shared<XMLElement>("path");
+ element->setAttribute("id", path.getID());
+ element->setAttribute("stroke", path.getColor().toHex());
+ try {
+ element->setAttribute("stroke-width", boost::lexical_cast<std::string>(path.getPenWidth()));
+ element->setAttribute("opacity", alphaToOpacity(path.getColor().getAlpha()));
+ std::string pathData;
+ if (path.getPoints().size() != 0) {
+ std::vector<std::pair<int, int> >::const_iterator it = path.getPoints().begin();
+ pathData = "M"+boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+"L";
+ for (; it != path.getPoints().end(); ++it) {
+ pathData += boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+" ";
+ }
+ }
+ element->setAttribute("d", pathData);
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardRectElement& rect) {
+ element = boost::make_shared<XMLElement>("rect");
+ try {
+ element->setAttribute("x", boost::lexical_cast<std::string>(rect.getX()));
+ element->setAttribute("y", boost::lexical_cast<std::string>(rect.getY()));
+ element->setAttribute("width", boost::lexical_cast<std::string>(rect.getWidth()));
+ element->setAttribute("height", boost::lexical_cast<std::string>(rect.getHeight()));
+ element->setAttribute("id", rect.getID());
+ element->setAttribute("stroke", rect.getPenColor().toHex());
+ element->setAttribute("fill", rect.getBrushColor().toHex());;
+ element->setAttribute("stroke-width", boost::lexical_cast<std::string>(rect.getPenWidth()));
+ element->setAttribute("opacity", alphaToOpacity(rect.getPenColor().getAlpha()));
+ element->setAttribute("fill-opacity", alphaToOpacity(rect.getBrushColor().getAlpha()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardPolygonElement& polygon) {
+ element = boost::make_shared<XMLElement>("polygon");
+ try {
+ element->setAttribute("id", polygon.getID());
+ element->setAttribute("stroke", polygon.getPenColor().toHex());
+ element->setAttribute("fill", polygon.getBrushColor().toHex());;
+ element->setAttribute("stroke-width", boost::lexical_cast<std::string>(polygon.getPenWidth()));
+ element->setAttribute("opacity", alphaToOpacity(polygon.getPenColor().getAlpha()));
+ element->setAttribute("fill-opacity", alphaToOpacity(polygon.getBrushColor().getAlpha()));
+ std::string points;
+ std::vector<std::pair<int, int> >::const_iterator it = polygon.getPoints().begin();
+ for (; it != polygon.getPoints().end(); ++it) {
+ points += boost::lexical_cast<std::string>(it->first)+","+boost::lexical_cast<std::string>(it->second)+" ";
+ }
+ element->setAttribute("points", points);
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardTextElement& text) {
+ element = boost::make_shared<XMLElement>("text");
+ try {
+ element->setAttribute("x", boost::lexical_cast<std::string>(text.getX()));
+ element->setAttribute("y", boost::lexical_cast<std::string>(text.getY()));
+ element->setAttribute("font-size", boost::lexical_cast<std::string>(text.getSize()));
+ element->setAttribute("id", text.getID());
+ element->setAttribute("fill", text.getColor().toHex());
+ element->setAttribute("opacity", alphaToOpacity(text.getColor().getAlpha()));
+ element->addNode(boost::make_shared<XMLTextNode>(text.getText()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardEllipseElement& ellipse) {
+ element = boost::make_shared<XMLElement>("ellipse");
+ try {
+ element->setAttribute("cx", boost::lexical_cast<std::string>(ellipse.getCX()));
+ element->setAttribute("cy", boost::lexical_cast<std::string>(ellipse.getCY()));
+ element->setAttribute("rx", boost::lexical_cast<std::string>(ellipse.getRX()));
+ element->setAttribute("ry", boost::lexical_cast<std::string>(ellipse.getRY()));
+ element->setAttribute("id", ellipse.getID());
+ element->setAttribute("stroke", ellipse.getPenColor().toHex());
+ element->setAttribute("fill", ellipse.getBrushColor().toHex());;
+ element->setAttribute("stroke-width", boost::lexical_cast<std::string>(ellipse.getPenWidth()));
+ element->setAttribute("opacity", alphaToOpacity(ellipse.getPenColor().getAlpha()));
+ element->setAttribute("fill-opacity", alphaToOpacity(ellipse.getBrushColor().getAlpha()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ XMLElement::ref WhiteboardElementSerializingVisitor::getResult() const {
+ return element;
+ }
+
+ std::string WhiteboardElementSerializingVisitor::alphaToOpacity(int alpha) const {
+ int opacity = 100*alpha/254;
+ if (opacity == 100) {
+ return "1";
+ } else {
+ return "."+boost::lexical_cast<std::string>(opacity);
+ }
+ }
+
+ std::string WhiteboardSerializer::serializePayload(boost::shared_ptr<WhiteboardPayload> payload) const {
+ XMLElement element("wb", "http://swift.im/whiteboard");
+ if (payload->getType() == WhiteboardPayload::Data) {
+ XMLElement::ref operationNode = boost::make_shared<XMLElement>("operation");
+ WhiteboardElementSerializingVisitor visitor;
+// payload->getElement()->accept(visitor);
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(payload->getOperation());
+ if (insertOp) {
+ try {
+ operationNode->setAttribute("type", "insert");
+ operationNode->setAttribute("pos", boost::lexical_cast<std::string>(insertOp->getPos()));
+ operationNode->setAttribute("id", insertOp->getID());
+ operationNode->setAttribute("parentid", insertOp->getParentID());
+ } catch (boost::bad_lexical_cast&) {
+ }
+ insertOp->getElement()->accept(visitor);
+ operationNode->addNode(visitor.getResult());
+ }
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(payload->getOperation());
+ if (updateOp) {
+ try {
+ operationNode->setAttribute("type", "update");
+ operationNode->setAttribute("pos", boost::lexical_cast<std::string>(updateOp->getPos()));
+ operationNode->setAttribute("id", updateOp->getID());
+ operationNode->setAttribute("parentid", updateOp->getParentID());
+ operationNode->setAttribute("newpos", boost::lexical_cast<std::string>(updateOp->getNewPos()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ updateOp->getElement()->accept(visitor);
+ operationNode->addNode(visitor.getResult());
+
+ }
+
+ WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(payload->getOperation());
+ if (deleteOp) {
+ try {
+ operationNode->setAttribute("type", "delete");
+ operationNode->setAttribute("pos", boost::lexical_cast<std::string>(deleteOp->getPos()));
+ operationNode->setAttribute("id", deleteOp->getID());
+ operationNode->setAttribute("parentid", deleteOp->getParentID());
+ operationNode->setAttribute("elementid", deleteOp->getElementID());
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+ element.addNode(operationNode);
+ }
+ element.setAttribute("type", typeToString(payload->getType()));
+ return element.serialize();
+ }
+
+ std::string WhiteboardSerializer::typeToString(WhiteboardPayload::Type type) const {
+ switch (type) {
+ case WhiteboardPayload::Data:
+ return "data";
+ case WhiteboardPayload::SessionRequest:
+ return "session-request";
+ case WhiteboardPayload::SessionAccept:
+ return "session-accept";
+ case WhiteboardPayload::SessionTerminate:
+ return "session-terminate";
+ case WhiteboardPayload::UnknownType:
+ std::cerr << "Warning: Serializing unknown action value." << std::endl;
+ return "";
+ }
+ assert(false);
+ return "";
+ }
}
diff --git a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h
index cf93c8c..70aef1e 100644
--- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h
@@ -25,27 +25,27 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API WhiteboardElementSerializingVisitor : public WhiteboardElementVisitor {
- public:
- void visit(WhiteboardLineElement& line);
- void visit(WhiteboardFreehandPathElement& path);
- void visit(WhiteboardRectElement& rect);
- void visit(WhiteboardPolygonElement& polygon);
- void visit(WhiteboardTextElement& text);
- void visit(WhiteboardEllipseElement& ellipse);
- XMLElement::ref getResult() const;
-
- private:
- std::string alphaToOpacity(int alpha) const;
-
- XMLElement::ref element;
- };
-
- class SWIFTEN_API WhiteboardSerializer : public GenericPayloadSerializer<WhiteboardPayload> {
- public:
- std::string serializePayload(boost::shared_ptr<WhiteboardPayload> payload) const;
-
- private:
- std::string typeToString(WhiteboardPayload::Type type) const;
- };
+ class SWIFTEN_API WhiteboardElementSerializingVisitor : public WhiteboardElementVisitor {
+ public:
+ void visit(WhiteboardLineElement& line);
+ void visit(WhiteboardFreehandPathElement& path);
+ void visit(WhiteboardRectElement& rect);
+ void visit(WhiteboardPolygonElement& polygon);
+ void visit(WhiteboardTextElement& text);
+ void visit(WhiteboardEllipseElement& ellipse);
+ XMLElement::ref getResult() const;
+
+ private:
+ std::string alphaToOpacity(int alpha) const;
+
+ XMLElement::ref element;
+ };
+
+ class SWIFTEN_API WhiteboardSerializer : public GenericPayloadSerializer<WhiteboardPayload> {
+ public:
+ std::string serializePayload(boost::shared_ptr<WhiteboardPayload> payload) const;
+
+ private:
+ std::string typeToString(WhiteboardPayload::Type type) const;
+ };
}
diff --git a/Swiften/Serializer/PresenceSerializer.cpp b/Swiften/Serializer/PresenceSerializer.cpp
index 71cf8eb..24c4365 100644
--- a/Swiften/Serializer/PresenceSerializer.cpp
+++ b/Swiften/Serializer/PresenceSerializer.cpp
@@ -14,23 +14,23 @@
namespace Swift {
PresenceSerializer::PresenceSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS) :
- GenericStanzaSerializer<Presence>("presence", payloadSerializers, explicitNS) {
+ GenericStanzaSerializer<Presence>("presence", payloadSerializers, explicitNS) {
}
void PresenceSerializer::setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<Presence> presence,
- XMLElement& element) const {
- switch (presence->getType()) {
- case Presence::Unavailable: element.setAttribute("type","unavailable"); break;
- case Presence::Probe: element.setAttribute("type","probe"); break;
- case Presence::Subscribe: element.setAttribute("type","subscribe"); break;
- case Presence::Subscribed: element.setAttribute("type","subscribed"); break;
- case Presence::Unsubscribe: element.setAttribute("type","unsubscribe"); break;
- case Presence::Unsubscribed: element.setAttribute("type","unsubscribed"); break;
- case Presence::Error: element.setAttribute("type","error"); break;
- case Presence::Available: break;
- }
+ boost::shared_ptr<Presence> presence,
+ XMLElement& element) const {
+ switch (presence->getType()) {
+ case Presence::Unavailable: element.setAttribute("type","unavailable"); break;
+ case Presence::Probe: element.setAttribute("type","probe"); break;
+ case Presence::Subscribe: element.setAttribute("type","subscribe"); break;
+ case Presence::Subscribed: element.setAttribute("type","subscribed"); break;
+ case Presence::Unsubscribe: element.setAttribute("type","unsubscribe"); break;
+ case Presence::Unsubscribed: element.setAttribute("type","unsubscribed"); break;
+ case Presence::Error: element.setAttribute("type","error"); break;
+ case Presence::Available: break;
+ }
}
}
diff --git a/Swiften/Serializer/PresenceSerializer.h b/Swiften/Serializer/PresenceSerializer.h
index 1119f27..e40b9c2 100644
--- a/Swiften/Serializer/PresenceSerializer.h
+++ b/Swiften/Serializer/PresenceSerializer.h
@@ -13,14 +13,14 @@
#include <Swiften/Serializer/GenericStanzaSerializer.h>
namespace Swift {
- class SWIFTEN_API PresenceSerializer : public GenericStanzaSerializer<Presence> {
- public:
- PresenceSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>());
- ~PresenceSerializer() {}
+ class SWIFTEN_API PresenceSerializer : public GenericStanzaSerializer<Presence> {
+ public:
+ PresenceSerializer(PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>());
+ ~PresenceSerializer() {}
- private:
- virtual void setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<Presence> presence,
- XMLElement& element) const;
- };
+ private:
+ virtual void setStanzaSpecificAttributesGeneric(
+ boost::shared_ptr<Presence> presence,
+ XMLElement& element) const;
+ };
}
diff --git a/Swiften/Serializer/StanzaAckRequestSerializer.h b/Swiften/Serializer/StanzaAckRequestSerializer.h
index e8517b6..b178db1 100644
--- a/Swiften/Serializer/StanzaAckRequestSerializer.h
+++ b/Swiften/Serializer/StanzaAckRequestSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StanzaAckRequestSerializer : public GenericElementSerializer<StanzaAckRequest> {
- public:
- StanzaAckRequestSerializer() : GenericElementSerializer<StanzaAckRequest>() {
- }
+ class SWIFTEN_API StanzaAckRequestSerializer : public GenericElementSerializer<StanzaAckRequest> {
+ public:
+ StanzaAckRequestSerializer() : GenericElementSerializer<StanzaAckRequest>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("r", "urn:xmpp:sm:2").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("r", "urn:xmpp:sm:2").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/StanzaAckSerializer.h b/Swiften/Serializer/StanzaAckSerializer.h
index 80e086b..7ca6ab8 100644
--- a/Swiften/Serializer/StanzaAckSerializer.h
+++ b/Swiften/Serializer/StanzaAckSerializer.h
@@ -15,17 +15,17 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StanzaAckSerializer : public GenericElementSerializer<StanzaAck> {
- public:
- StanzaAckSerializer() : GenericElementSerializer<StanzaAck>() {
- }
+ class SWIFTEN_API StanzaAckSerializer : public GenericElementSerializer<StanzaAck> {
+ public:
+ StanzaAckSerializer() : GenericElementSerializer<StanzaAck>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const {
- StanzaAck::ref stanzaAck(boost::dynamic_pointer_cast<StanzaAck>(element));
- assert(stanzaAck->isValid());
- XMLElement result("a", "urn:xmpp:sm:2");
- result.setAttribute("h", std::string(boost::lexical_cast<std::string>(stanzaAck->getHandledStanzasCount())));
- return createSafeByteArray(result.serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const {
+ StanzaAck::ref stanzaAck(boost::dynamic_pointer_cast<StanzaAck>(element));
+ assert(stanzaAck->isValid());
+ XMLElement result("a", "urn:xmpp:sm:2");
+ result.setAttribute("h", std::string(boost::lexical_cast<std::string>(stanzaAck->getHandledStanzasCount())));
+ return createSafeByteArray(result.serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/StanzaSerializer.cpp b/Swiften/Serializer/StanzaSerializer.cpp
index d44dce4..002f2c3 100644
--- a/Swiften/Serializer/StanzaSerializer.cpp
+++ b/Swiften/Serializer/StanzaSerializer.cpp
@@ -23,44 +23,44 @@ StanzaSerializer::StanzaSerializer(const std::string& tag, PayloadSerializerColl
}
SafeByteArray StanzaSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- if (explicitDefaultNS_) {
- return serialize(element, explicitDefaultNS_.get());
- }
- else {
- return serialize(element, "");
- }
+ if (explicitDefaultNS_) {
+ return serialize(element, explicitDefaultNS_.get());
+ }
+ else {
+ return serialize(element, "");
+ }
}
SafeByteArray StanzaSerializer::serialize(boost::shared_ptr<ToplevelElement> element, const std::string& xmlns) const {
- boost::shared_ptr<Stanza> stanza(boost::dynamic_pointer_cast<Stanza>(element));
+ boost::shared_ptr<Stanza> stanza(boost::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);
+ 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 boost::shared_ptr<Payload>& payload, stanza->getPayloads()) {
- PayloadSerializer* serializer = payloadSerializers_->getPayloadSerializer(payload);
- if (serializer) {
- serializedPayloads += serializer->serialize(payload);
- }
- else {
- std::cerr << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
- }
- }
- if (!serializedPayloads.empty()) {
- stanzaElement.addNode(boost::shared_ptr<XMLNode>(new XMLRawTextNode(serializedPayloads)));
- }
+ std::string serializedPayloads;
+ foreach (const boost::shared_ptr<Payload>& payload, stanza->getPayloads()) {
+ PayloadSerializer* serializer = payloadSerializers_->getPayloadSerializer(payload);
+ if (serializer) {
+ serializedPayloads += serializer->serialize(payload);
+ }
+ else {
+ std::cerr << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
+ }
+ }
+ if (!serializedPayloads.empty()) {
+ stanzaElement.addNode(boost::shared_ptr<XMLNode>(new XMLRawTextNode(serializedPayloads)));
+ }
- return createSafeByteArray(stanzaElement.serialize());
+ return createSafeByteArray(stanzaElement.serialize());
}
}
diff --git a/Swiften/Serializer/StanzaSerializer.h b/Swiften/Serializer/StanzaSerializer.h
index b8de056..34aab9e 100644
--- a/Swiften/Serializer/StanzaSerializer.h
+++ b/Swiften/Serializer/StanzaSerializer.h
@@ -15,20 +15,20 @@
#include <Swiften/Serializer/ElementSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class XMLElement;
-
- class SWIFTEN_API StanzaSerializer : public ElementSerializer {
- public:
- StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>());
-
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element, const std::string& xmlns) const;
- virtual void setStanzaSpecificAttributes(boost::shared_ptr<ToplevelElement>, XMLElement&) const = 0;
-
- private:
- std::string tag_;
- PayloadSerializerCollection* payloadSerializers_;
- boost::optional<std::string> explicitDefaultNS_;
- };
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class SWIFTEN_API StanzaSerializer : public ElementSerializer {
+ public:
+ StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS = boost::optional<std::string>());
+
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element, const std::string& xmlns) const;
+ virtual void setStanzaSpecificAttributes(boost::shared_ptr<ToplevelElement>, XMLElement&) const = 0;
+
+ private:
+ std::string tag_;
+ PayloadSerializerCollection* payloadSerializers_;
+ boost::optional<std::string> explicitDefaultNS_;
+ };
}
diff --git a/Swiften/Serializer/StartTLSFailureSerializer.h b/Swiften/Serializer/StartTLSFailureSerializer.h
index b645953..f7f7296 100644
--- a/Swiften/Serializer/StartTLSFailureSerializer.h
+++ b/Swiften/Serializer/StartTLSFailureSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StartTLSFailureSerializer : public GenericElementSerializer<StartTLSFailure> {
- public:
- StartTLSFailureSerializer() : GenericElementSerializer<StartTLSFailure>() {
- }
+ class SWIFTEN_API StartTLSFailureSerializer : public GenericElementSerializer<StartTLSFailure> {
+ public:
+ StartTLSFailureSerializer() : GenericElementSerializer<StartTLSFailure>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("failure", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/StartTLSRequestSerializer.h b/Swiften/Serializer/StartTLSRequestSerializer.h
index 47dc1e7..cc8e3d5 100644
--- a/Swiften/Serializer/StartTLSRequestSerializer.h
+++ b/Swiften/Serializer/StartTLSRequestSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StartTLSRequestSerializer : public GenericElementSerializer<StartTLSRequest> {
- public:
- StartTLSRequestSerializer() : GenericElementSerializer<StartTLSRequest>() {
- }
+ class SWIFTEN_API StartTLSRequestSerializer : public GenericElementSerializer<StartTLSRequest> {
+ public:
+ StartTLSRequestSerializer() : GenericElementSerializer<StartTLSRequest>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("starttls", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("starttls", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/StreamErrorSerializer.cpp b/Swiften/Serializer/StreamErrorSerializer.cpp
index 6ddaf4c..3cad478 100644
--- a/Swiften/Serializer/StreamErrorSerializer.cpp
+++ b/Swiften/Serializer/StreamErrorSerializer.cpp
@@ -16,44 +16,44 @@ StreamErrorSerializer::StreamErrorSerializer() : GenericElementSerializer<Stream
}
SafeByteArray StreamErrorSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- StreamError::ref error = boost::dynamic_pointer_cast<StreamError>(element);
- XMLElement errorElement("error", "http://etherx.jabber.org/streams");
-
- std::string typeTag;
- switch (error->getType()) {
- case StreamError::BadFormat: typeTag = "bad-format"; break;
- case StreamError::BadNamespacePrefix: typeTag = "bad-namespace-prefix"; break;
- case StreamError::Conflict: typeTag = "conflict"; break;
- case StreamError::ConnectionTimeout: typeTag = "connection-timeout"; break;
- case StreamError::HostGone: typeTag = "host-gone"; break;
- case StreamError::HostUnknown: typeTag = "host-unknown"; break;
- case StreamError::ImproperAddressing: typeTag = "improper-addressing"; break;
- case StreamError::InternalServerError: typeTag = "internal-server-error"; break;
- case StreamError::InvalidFrom: typeTag = "invalid-from"; break;
- case StreamError::InvalidID: typeTag = "invalid-id"; break;
- case StreamError::InvalidNamespace: typeTag = "invalid-namespace"; break;
- case StreamError::InvalidXML: typeTag = "invalid-xml"; break;
- case StreamError::NotAuthorized: typeTag = "not-authorized"; break;
- case StreamError::NotWellFormed: typeTag = "not-well-formed"; break;
- case StreamError::PolicyViolation: typeTag = "policy-violation"; break;
- case StreamError::RemoteConnectionFailed: typeTag = "remote-connection-failed"; break;
- case StreamError::Reset: typeTag = "reset"; break;
- case StreamError::ResourceConstraint: typeTag = "resource-constraint"; break;
- case StreamError::RestrictedXML: typeTag = "restricted-xml"; break;
- case StreamError::SeeOtherHost: typeTag = "see-other-host"; break;
- case StreamError::SystemShutdown: typeTag = "system-shutdown"; break;
- case StreamError::UndefinedCondition: typeTag = "undefined-condition"; break;
- case StreamError::UnsupportedEncoding: typeTag = "unsupported-encoding"; break;
- case StreamError::UnsupportedStanzaType: typeTag = "unsupported-stanza-type"; break;
- case StreamError::UnsupportedVersion: typeTag = "unsupported-version"; break;
- }
- errorElement.addNode(boost::make_shared<XMLElement>(typeTag, "urn:ietf:params:xml:ns:xmpp-streams"));
-
- if (!error->getText().empty()) {
- errorElement.addNode(boost::make_shared<XMLElement>("text", "urn:ietf:params:xml:ns:xmpp-streams", error->getText()));
- }
-
- return createSafeByteArray(errorElement.serialize());
+ StreamError::ref error = boost::dynamic_pointer_cast<StreamError>(element);
+ XMLElement errorElement("error", "http://etherx.jabber.org/streams");
+
+ std::string typeTag;
+ switch (error->getType()) {
+ case StreamError::BadFormat: typeTag = "bad-format"; break;
+ case StreamError::BadNamespacePrefix: typeTag = "bad-namespace-prefix"; break;
+ case StreamError::Conflict: typeTag = "conflict"; break;
+ case StreamError::ConnectionTimeout: typeTag = "connection-timeout"; break;
+ case StreamError::HostGone: typeTag = "host-gone"; break;
+ case StreamError::HostUnknown: typeTag = "host-unknown"; break;
+ case StreamError::ImproperAddressing: typeTag = "improper-addressing"; break;
+ case StreamError::InternalServerError: typeTag = "internal-server-error"; break;
+ case StreamError::InvalidFrom: typeTag = "invalid-from"; break;
+ case StreamError::InvalidID: typeTag = "invalid-id"; break;
+ case StreamError::InvalidNamespace: typeTag = "invalid-namespace"; break;
+ case StreamError::InvalidXML: typeTag = "invalid-xml"; break;
+ case StreamError::NotAuthorized: typeTag = "not-authorized"; break;
+ case StreamError::NotWellFormed: typeTag = "not-well-formed"; break;
+ case StreamError::PolicyViolation: typeTag = "policy-violation"; break;
+ case StreamError::RemoteConnectionFailed: typeTag = "remote-connection-failed"; break;
+ case StreamError::Reset: typeTag = "reset"; break;
+ case StreamError::ResourceConstraint: typeTag = "resource-constraint"; break;
+ case StreamError::RestrictedXML: typeTag = "restricted-xml"; break;
+ case StreamError::SeeOtherHost: typeTag = "see-other-host"; break;
+ case StreamError::SystemShutdown: typeTag = "system-shutdown"; break;
+ case StreamError::UndefinedCondition: typeTag = "undefined-condition"; break;
+ case StreamError::UnsupportedEncoding: typeTag = "unsupported-encoding"; break;
+ case StreamError::UnsupportedStanzaType: typeTag = "unsupported-stanza-type"; break;
+ case StreamError::UnsupportedVersion: typeTag = "unsupported-version"; break;
+ }
+ errorElement.addNode(boost::make_shared<XMLElement>(typeTag, "urn:ietf:params:xml:ns:xmpp-streams"));
+
+ if (!error->getText().empty()) {
+ errorElement.addNode(boost::make_shared<XMLElement>("text", "urn:ietf:params:xml:ns:xmpp-streams", error->getText()));
+ }
+
+ return createSafeByteArray(errorElement.serialize());
}
}
diff --git a/Swiften/Serializer/StreamErrorSerializer.h b/Swiften/Serializer/StreamErrorSerializer.h
index 35af764..f578005 100644
--- a/Swiften/Serializer/StreamErrorSerializer.h
+++ b/Swiften/Serializer/StreamErrorSerializer.h
@@ -11,10 +11,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamErrorSerializer : public GenericElementSerializer<StreamError> {
- public:
- StreamErrorSerializer();
+ class SWIFTEN_API StreamErrorSerializer : public GenericElementSerializer<StreamError> {
+ public:
+ StreamErrorSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> error) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> error) const;
+ };
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.cpp b/Swiften/Serializer/StreamFeaturesSerializer.cpp
index 5908ec8..ed042ec 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.cpp
+++ b/Swiften/Serializer/StreamFeaturesSerializer.cpp
@@ -18,43 +18,43 @@ StreamFeaturesSerializer::StreamFeaturesSerializer() {
}
SafeByteArray StreamFeaturesSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- boost::shared_ptr<StreamFeatures> streamFeatures(boost::dynamic_pointer_cast<StreamFeatures>(element));
-
- XMLElement streamFeaturesElement("stream:features");
- if (streamFeatures->hasStartTLS()) {
- streamFeaturesElement.addNode(boost::make_shared<XMLElement>("starttls", "urn:ietf:params:xml:ns:xmpp-tls"));
- }
- if (!streamFeatures->getCompressionMethods().empty()) {
- boost::shared_ptr<XMLElement> compressionElement(new XMLElement("compression", "http://jabber.org/features/compress"));
- foreach(const std::string& method, streamFeatures->getCompressionMethods()) {
- boost::shared_ptr<XMLElement> methodElement(new XMLElement("method"));
- methodElement->addNode(boost::make_shared<XMLTextNode>(method));
- compressionElement->addNode(methodElement);
- }
- streamFeaturesElement.addNode(compressionElement);
- }
- if (!streamFeatures->getAuthenticationMechanisms().empty()) {
- boost::shared_ptr<XMLElement> mechanismsElement(new XMLElement("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"));
- foreach(const std::string& mechanism, streamFeatures->getAuthenticationMechanisms()) {
- boost::shared_ptr<XMLElement> mechanismElement(new XMLElement("mechanism"));
- mechanismElement->addNode(boost::make_shared<XMLTextNode>(mechanism));
- mechanismsElement->addNode(mechanismElement);
- }
- streamFeaturesElement.addNode(mechanismsElement);
- }
- if (streamFeatures->hasResourceBind()) {
- streamFeaturesElement.addNode(boost::make_shared<XMLElement>("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
- }
- if (streamFeatures->hasSession()) {
- streamFeaturesElement.addNode(boost::make_shared<XMLElement>("session", "urn:ietf:params:xml:ns:xmpp-session"));
- }
- if (streamFeatures->hasStreamManagement()) {
- streamFeaturesElement.addNode(boost::make_shared<XMLElement>("sm", "urn:xmpp:sm:2"));
- }
- if (streamFeatures->hasRosterVersioning()) {
- streamFeaturesElement.addNode(boost::make_shared<XMLElement>("ver", "urn:xmpp:features:rosterver"));
- }
- return createSafeByteArray(streamFeaturesElement.serialize());
+ boost::shared_ptr<StreamFeatures> streamFeatures(boost::dynamic_pointer_cast<StreamFeatures>(element));
+
+ XMLElement streamFeaturesElement("stream:features");
+ if (streamFeatures->hasStartTLS()) {
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("starttls", "urn:ietf:params:xml:ns:xmpp-tls"));
+ }
+ if (!streamFeatures->getCompressionMethods().empty()) {
+ boost::shared_ptr<XMLElement> compressionElement(new XMLElement("compression", "http://jabber.org/features/compress"));
+ foreach(const std::string& method, streamFeatures->getCompressionMethods()) {
+ boost::shared_ptr<XMLElement> methodElement(new XMLElement("method"));
+ methodElement->addNode(boost::make_shared<XMLTextNode>(method));
+ compressionElement->addNode(methodElement);
+ }
+ streamFeaturesElement.addNode(compressionElement);
+ }
+ if (!streamFeatures->getAuthenticationMechanisms().empty()) {
+ boost::shared_ptr<XMLElement> mechanismsElement(new XMLElement("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"));
+ foreach(const std::string& mechanism, streamFeatures->getAuthenticationMechanisms()) {
+ boost::shared_ptr<XMLElement> mechanismElement(new XMLElement("mechanism"));
+ mechanismElement->addNode(boost::make_shared<XMLTextNode>(mechanism));
+ mechanismsElement->addNode(mechanismElement);
+ }
+ streamFeaturesElement.addNode(mechanismsElement);
+ }
+ if (streamFeatures->hasResourceBind()) {
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
+ }
+ if (streamFeatures->hasSession()) {
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("session", "urn:ietf:params:xml:ns:xmpp-session"));
+ }
+ if (streamFeatures->hasStreamManagement()) {
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("sm", "urn:xmpp:sm:2"));
+ }
+ if (streamFeatures->hasRosterVersioning()) {
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("ver", "urn:xmpp:features:rosterver"));
+ }
+ return createSafeByteArray(streamFeaturesElement.serialize());
}
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.h b/Swiften/Serializer/StreamFeaturesSerializer.h
index f98a86f..f2328a5 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.h
+++ b/Swiften/Serializer/StreamFeaturesSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamFeaturesSerializer : public GenericElementSerializer<StreamFeatures> {
- public:
- StreamFeaturesSerializer();
+ class SWIFTEN_API StreamFeaturesSerializer : public GenericElementSerializer<StreamFeatures> {
+ public:
+ StreamFeaturesSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
index 3ee0772..b03196c 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
@@ -17,13 +17,13 @@ StreamManagementEnabledSerializer::StreamManagementEnabledSerializer() : Generic
}
SafeByteArray StreamManagementEnabledSerializer::serialize(boost::shared_ptr<ToplevelElement> el) const {
- boost::shared_ptr<StreamManagementEnabled> e(boost::dynamic_pointer_cast<StreamManagementEnabled>(el));
- XMLElement element("enabled", "urn:xmpp:sm:2");
- if (!e->getResumeID().empty()) {
- element.setAttribute("id", e->getResumeID());
- }
- if (e->getResumeSupported()) {
- element.setAttribute("resume", "true");
- }
- return createSafeByteArray(element.serialize());
+ boost::shared_ptr<StreamManagementEnabled> e(boost::dynamic_pointer_cast<StreamManagementEnabled>(el));
+ XMLElement element("enabled", "urn:xmpp:sm:2");
+ if (!e->getResumeID().empty()) {
+ element.setAttribute("id", e->getResumeID());
+ }
+ if (e->getResumeSupported()) {
+ element.setAttribute("resume", "true");
+ }
+ return createSafeByteArray(element.serialize());
}
diff --git a/Swiften/Serializer/StreamManagementEnabledSerializer.h b/Swiften/Serializer/StreamManagementEnabledSerializer.h
index fc44739..9ffe233 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.h
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamManagementEnabledSerializer : public GenericElementSerializer<StreamManagementEnabled> {
- public:
- StreamManagementEnabledSerializer();
+ class SWIFTEN_API StreamManagementEnabledSerializer : public GenericElementSerializer<StreamManagementEnabled> {
+ public:
+ StreamManagementEnabledSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/StreamManagementFailedSerializer.h b/Swiften/Serializer/StreamManagementFailedSerializer.h
index 4489f97..b189bd8 100644
--- a/Swiften/Serializer/StreamManagementFailedSerializer.h
+++ b/Swiften/Serializer/StreamManagementFailedSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API StreamManagementFailedSerializer : public GenericElementSerializer<StreamManagementFailed> {
- public:
- StreamManagementFailedSerializer() : GenericElementSerializer<StreamManagementFailed>() {
- }
+ class SWIFTEN_API StreamManagementFailedSerializer : public GenericElementSerializer<StreamManagementFailed> {
+ public:
+ StreamManagementFailedSerializer() : GenericElementSerializer<StreamManagementFailed>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("failed", "urn:xmpp:sm:2").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("failed", "urn:xmpp:sm:2").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/StreamResumeSerializer.cpp b/Swiften/Serializer/StreamResumeSerializer.cpp
index 261956d..c660083 100644
--- a/Swiften/Serializer/StreamResumeSerializer.cpp
+++ b/Swiften/Serializer/StreamResumeSerializer.cpp
@@ -18,11 +18,11 @@ StreamResumeSerializer::StreamResumeSerializer() : GenericElementSerializer<Stre
}
SafeByteArray StreamResumeSerializer::serialize(boost::shared_ptr<ToplevelElement> el) const {
- boost::shared_ptr<StreamResume> e(boost::dynamic_pointer_cast<StreamResume>(el));
- XMLElement element("resume", "urn:xmpp:sm:2");
- element.setAttribute("previd", e->getResumeID());
- if (e->getHandledStanzasCount()) {
- element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get()));
- }
- return createSafeByteArray(element.serialize());
+ boost::shared_ptr<StreamResume> e(boost::dynamic_pointer_cast<StreamResume>(el));
+ XMLElement element("resume", "urn:xmpp:sm:2");
+ element.setAttribute("previd", e->getResumeID());
+ if (e->getHandledStanzasCount()) {
+ element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get()));
+ }
+ return createSafeByteArray(element.serialize());
}
diff --git a/Swiften/Serializer/StreamResumeSerializer.h b/Swiften/Serializer/StreamResumeSerializer.h
index f166ac3..5e7c58d 100644
--- a/Swiften/Serializer/StreamResumeSerializer.h
+++ b/Swiften/Serializer/StreamResumeSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamResumeSerializer : public GenericElementSerializer<StreamResume> {
- public:
- StreamResumeSerializer();
+ class SWIFTEN_API StreamResumeSerializer : public GenericElementSerializer<StreamResume> {
+ public:
+ StreamResumeSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/StreamResumedSerializer.cpp b/Swiften/Serializer/StreamResumedSerializer.cpp
index 295096a..9778338 100644
--- a/Swiften/Serializer/StreamResumedSerializer.cpp
+++ b/Swiften/Serializer/StreamResumedSerializer.cpp
@@ -18,11 +18,11 @@ StreamResumedSerializer::StreamResumedSerializer() : GenericElementSerializer<St
}
SafeByteArray StreamResumedSerializer::serialize(boost::shared_ptr<ToplevelElement> el) const {
- boost::shared_ptr<StreamResumed> e(boost::dynamic_pointer_cast<StreamResumed>(el));
- XMLElement element("resumed", "urn:xmpp:sm:2");
- element.setAttribute("previd", e->getResumeID());
- if (e->getHandledStanzasCount()) {
- element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get()));
- }
- return createSafeByteArray(element.serialize());
+ boost::shared_ptr<StreamResumed> e(boost::dynamic_pointer_cast<StreamResumed>(el));
+ XMLElement element("resumed", "urn:xmpp:sm:2");
+ element.setAttribute("previd", e->getResumeID());
+ if (e->getHandledStanzasCount()) {
+ element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get()));
+ }
+ return createSafeByteArray(element.serialize());
}
diff --git a/Swiften/Serializer/StreamResumedSerializer.h b/Swiften/Serializer/StreamResumedSerializer.h
index a0c316e..82a66d7 100644
--- a/Swiften/Serializer/StreamResumedSerializer.h
+++ b/Swiften/Serializer/StreamResumedSerializer.h
@@ -13,10 +13,10 @@
#include <Swiften/Serializer/GenericElementSerializer.h>
namespace Swift {
- class SWIFTEN_API StreamResumedSerializer : public GenericElementSerializer<StreamResumed> {
- public:
- StreamResumedSerializer();
+ class SWIFTEN_API StreamResumedSerializer : public GenericElementSerializer<StreamResumed> {
+ public:
+ StreamResumedSerializer();
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/TLSProceedSerializer.h b/Swiften/Serializer/TLSProceedSerializer.h
index 7203042..e9af0a2 100644
--- a/Swiften/Serializer/TLSProceedSerializer.h
+++ b/Swiften/Serializer/TLSProceedSerializer.h
@@ -14,13 +14,13 @@
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
- class SWIFTEN_API TLSProceedSerializer : public GenericElementSerializer<TLSProceed> {
- public:
- TLSProceedSerializer() : GenericElementSerializer<TLSProceed>() {
- }
+ class SWIFTEN_API TLSProceedSerializer : public GenericElementSerializer<TLSProceed> {
+ public:
+ TLSProceedSerializer() : GenericElementSerializer<TLSProceed>() {
+ }
- virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
- return createSafeByteArray(XMLElement("proceed", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
- }
- };
+ virtual SafeByteArray serialize(boost::shared_ptr<ToplevelElement>) const {
+ return createSafeByteArray(XMLElement("proceed", "urn:ietf:params:xml:ns:xmpp-tls").serialize());
+ }
+ };
}
diff --git a/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
index 71da7e8..1d41e81 100644
--- a/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
@@ -15,43 +15,43 @@
using namespace Swift;
class AuthChallengeSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(AuthChallengeSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoMessage);
- CPPUNIT_TEST(testSerialize_EmptyMessage);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- AuthChallengeSerializer testling;
- boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
- authChallenge->setValue(createByteArray("foo"));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "Zm9v"
- "</challenge>"), testling.serialize(authChallenge));
- }
-
- void testSerialize_NoMessage() {
- AuthChallengeSerializer testling;
- boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "</challenge>"), testling.serialize(authChallenge));
- }
-
- void testSerialize_EmptyMessage() {
- AuthChallengeSerializer testling;
- boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
- authChallenge->setValue(std::vector<unsigned char>());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "="
- "</challenge>"), testling.serialize(authChallenge));
- }
+ CPPUNIT_TEST_SUITE(AuthChallengeSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoMessage);
+ CPPUNIT_TEST(testSerialize_EmptyMessage);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ AuthChallengeSerializer testling;
+ boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
+ authChallenge->setValue(createByteArray("foo"));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "Zm9v"
+ "</challenge>"), testling.serialize(authChallenge));
+ }
+
+ void testSerialize_NoMessage() {
+ AuthChallengeSerializer testling;
+ boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "</challenge>"), testling.serialize(authChallenge));
+ }
+
+ void testSerialize_EmptyMessage() {
+ AuthChallengeSerializer testling;
+ boost::shared_ptr<AuthChallenge> authChallenge(new AuthChallenge());
+ authChallenge->setValue(std::vector<unsigned char>());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<challenge xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "="
+ "</challenge>"), testling.serialize(authChallenge));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(AuthChallengeSerializerTest);
diff --git a/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
index b27b736..95460b2 100644
--- a/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
@@ -15,43 +15,43 @@
using namespace Swift;
class AuthRequestSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(AuthRequestSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoMessage);
- CPPUNIT_TEST(testSerialize_EmptyMessage);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- AuthRequestSerializer testling;
- boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
- authRequest->setMessage(createSafeByteArray("foo"));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
- "Zm9v"
- "</auth>"), testling.serialize(authRequest));
- }
-
- void testSerialize_NoMessage() {
- AuthRequestSerializer testling;
- boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
- "</auth>"), testling.serialize(authRequest));
- }
-
- void testSerialize_EmptyMessage() {
- AuthRequestSerializer testling;
- boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
- authRequest->setMessage(SafeByteArray());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
- "="
- "</auth>"), testling.serialize(authRequest));
- }
+ CPPUNIT_TEST_SUITE(AuthRequestSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoMessage);
+ CPPUNIT_TEST(testSerialize_EmptyMessage);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ AuthRequestSerializer testling;
+ boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
+ authRequest->setMessage(createSafeByteArray("foo"));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
+ "Zm9v"
+ "</auth>"), testling.serialize(authRequest));
+ }
+
+ void testSerialize_NoMessage() {
+ AuthRequestSerializer testling;
+ boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
+ "</auth>"), testling.serialize(authRequest));
+ }
+
+ void testSerialize_EmptyMessage() {
+ AuthRequestSerializer testling;
+ boost::shared_ptr<AuthRequest> authRequest(new AuthRequest("PLAIN"));
+ authRequest->setMessage(SafeByteArray());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"PLAIN\">"
+ "="
+ "</auth>"), testling.serialize(authRequest));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(AuthRequestSerializerTest);
diff --git a/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
index fdff30b..67c6f16 100644
--- a/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
@@ -15,43 +15,43 @@
using namespace Swift;
class AuthResponseSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(AuthResponseSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoMessage);
- CPPUNIT_TEST(testSerialize_EmptyMessage);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- AuthResponseSerializer testling;
- boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
- authResponse->setValue(createSafeByteArray("foo"));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "Zm9v"
- "</response>"), testling.serialize(authResponse));
- }
-
- void testSerialize_NoMessage() {
- AuthResponseSerializer testling;
- boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "</response>"), testling.serialize(authResponse));
- }
-
- void testSerialize_EmptyMessage() {
- AuthResponseSerializer testling;
- boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
- authResponse->setValue(SafeByteArray());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- ""
- "</response>"), testling.serialize(authResponse));
- }
+ CPPUNIT_TEST_SUITE(AuthResponseSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoMessage);
+ CPPUNIT_TEST(testSerialize_EmptyMessage);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ AuthResponseSerializer testling;
+ boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
+ authResponse->setValue(createSafeByteArray("foo"));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "Zm9v"
+ "</response>"), testling.serialize(authResponse));
+ }
+
+ void testSerialize_NoMessage() {
+ AuthResponseSerializer testling;
+ boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "</response>"), testling.serialize(authResponse));
+ }
+
+ void testSerialize_EmptyMessage() {
+ AuthResponseSerializer testling;
+ boost::shared_ptr<AuthResponse> authResponse(new AuthResponse());
+ authResponse->setValue(SafeByteArray());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ ""
+ "</response>"), testling.serialize(authResponse));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(AuthResponseSerializerTest);
diff --git a/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp b/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
index 2d9b610..228bd9b 100644
--- a/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
@@ -15,43 +15,43 @@
using namespace Swift;
class AuthSuccessSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(AuthSuccessSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoMessage);
- CPPUNIT_TEST(testSerialize_EmptyMessage);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testSerialize() {
- AuthSuccessSerializer testling;
- boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
- authSuccess->setValue(createByteArray("foo"));
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "Zm9v"
- "</success>"), testling.serialize(authSuccess));
- }
-
- void testSerialize_NoMessage() {
- AuthSuccessSerializer testling;
- boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "</success>"), testling.serialize(authSuccess));
- }
-
- void testSerialize_EmptyMessage() {
- AuthSuccessSerializer testling;
- boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
- authSuccess->setValue(std::vector<unsigned char>());
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "="
- "</success>"), testling.serialize(authSuccess));
- }
+ CPPUNIT_TEST_SUITE(AuthSuccessSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoMessage);
+ CPPUNIT_TEST(testSerialize_EmptyMessage);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize() {
+ AuthSuccessSerializer testling;
+ boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
+ authSuccess->setValue(createByteArray("foo"));
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "Zm9v"
+ "</success>"), testling.serialize(authSuccess));
+ }
+
+ void testSerialize_NoMessage() {
+ AuthSuccessSerializer testling;
+ boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "</success>"), testling.serialize(authSuccess));
+ }
+
+ void testSerialize_EmptyMessage() {
+ AuthSuccessSerializer testling;
+ boost::shared_ptr<AuthSuccess> authSuccess(new AuthSuccess());
+ authSuccess->setValue(std::vector<unsigned char>());
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "="
+ "</success>"), testling.serialize(authSuccess));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(AuthSuccessSerializerTest);
diff --git a/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp b/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
index adfadbc..5f4f821 100644
--- a/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
@@ -15,43 +15,43 @@ using namespace Swift;
class StreamFeaturesSerializerTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(StreamFeaturesSerializerTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- StreamFeaturesSerializerTest() {}
-
- void testSerialize() {
- StreamFeaturesSerializer testling;
- boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
- streamFeatures->setHasStartTLS();
- streamFeatures->addCompressionMethod("zlib");
- streamFeatures->addCompressionMethod("lzw");
- streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
- streamFeatures->addAuthenticationMechanism("PLAIN");
- streamFeatures->setHasResourceBind();
- streamFeatures->setHasSession();
- streamFeatures->setHasStreamManagement();
- streamFeatures->setHasRosterVersioning();
-
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
- "<stream:features>"
- "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
- "<compression xmlns=\"http://jabber.org/features/compress\">"
- "<method>zlib</method>"
- "<method>lzw</method>"
- "</compression>"
- "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
- "<mechanism>DIGEST-MD5</mechanism>"
- "<mechanism>PLAIN</mechanism>"
- "</mechanisms>"
- "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
- "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
- "<sm xmlns=\"urn:xmpp:sm:2\"/>"
- "<ver xmlns=\"urn:xmpp:features:rosterver\"/>"
- "</stream:features>"), testling.serialize(streamFeatures));
- }
+ CPPUNIT_TEST_SUITE(StreamFeaturesSerializerTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ StreamFeaturesSerializerTest() {}
+
+ void testSerialize() {
+ StreamFeaturesSerializer testling;
+ boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->setHasStartTLS();
+ streamFeatures->addCompressionMethod("zlib");
+ streamFeatures->addCompressionMethod("lzw");
+ streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
+ streamFeatures->addAuthenticationMechanism("PLAIN");
+ streamFeatures->setHasResourceBind();
+ streamFeatures->setHasSession();
+ streamFeatures->setHasStreamManagement();
+ streamFeatures->setHasRosterVersioning();
+
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray(
+ "<stream:features>"
+ "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
+ "<compression xmlns=\"http://jabber.org/features/compress\">"
+ "<method>zlib</method>"
+ "<method>lzw</method>"
+ "</compression>"
+ "<mechanisms xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">"
+ "<mechanism>DIGEST-MD5</mechanism>"
+ "<mechanism>PLAIN</mechanism>"
+ "</mechanisms>"
+ "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
+ "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
+ "<sm xmlns=\"urn:xmpp:sm:2\"/>"
+ "<ver xmlns=\"urn:xmpp:features:rosterver\"/>"
+ "</stream:features>"), testling.serialize(streamFeatures));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(StreamFeaturesSerializerTest);
diff --git a/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp b/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp
index 83bb737..3eaeef0 100644
--- a/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp
@@ -15,61 +15,61 @@
using namespace Swift;
class XMPPSerializerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPSerializerTest);
- CPPUNIT_TEST(testSerializeHeader_Client);
- CPPUNIT_TEST(testSerializeHeader_Component);
- CPPUNIT_TEST(testSerializeHeader_Server);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(XMPPSerializerTest);
+ CPPUNIT_TEST(testSerializeHeader_Client);
+ CPPUNIT_TEST(testSerializeHeader_Component);
+ CPPUNIT_TEST(testSerializeHeader_Server);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- payloadSerializerCollection = new PayloadSerializerCollection();
- }
+ public:
+ void setUp() {
+ payloadSerializerCollection = new PayloadSerializerCollection();
+ }
- void tearDown() {
- delete payloadSerializerCollection;
- }
+ void tearDown() {
+ delete payloadSerializerCollection;
+ }
- void testSerializeHeader_Client() {
- boost::shared_ptr<XMPPSerializer> testling(createSerializer(ClientStreamType));
- ProtocolHeader protocolHeader;
- protocolHeader.setFrom("bla@foo.com");
- protocolHeader.setTo("foo.com");
- protocolHeader.setID("myid");
- protocolHeader.setVersion("0.99");
+ void testSerializeHeader_Client() {
+ boost::shared_ptr<XMPPSerializer> testling(createSerializer(ClientStreamType));
+ ProtocolHeader protocolHeader;
+ protocolHeader.setFrom("bla@foo.com");
+ protocolHeader.setTo("foo.com");
+ protocolHeader.setID("myid");
+ protocolHeader.setVersion("0.99");
- CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
+ }
- void testSerializeHeader_Component() {
- boost::shared_ptr<XMPPSerializer> testling(createSerializer(ComponentStreamType));
- ProtocolHeader protocolHeader;
- protocolHeader.setFrom("bla@foo.com");
- protocolHeader.setTo("foo.com");
- protocolHeader.setID("myid");
- protocolHeader.setVersion("0.99");
+ void testSerializeHeader_Component() {
+ boost::shared_ptr<XMPPSerializer> testling(createSerializer(ComponentStreamType));
+ ProtocolHeader protocolHeader;
+ protocolHeader.setFrom("bla@foo.com");
+ protocolHeader.setTo("foo.com");
+ protocolHeader.setID("myid");
+ protocolHeader.setVersion("0.99");
- CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:component:accept\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:component:accept\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
+ }
- void testSerializeHeader_Server() {
- boost::shared_ptr<XMPPSerializer> testling(createSerializer(ServerStreamType));
- ProtocolHeader protocolHeader;
- protocolHeader.setFrom("bla@foo.com");
- protocolHeader.setTo("foo.com");
- protocolHeader.setID("myid");
- protocolHeader.setVersion("0.99");
+ void testSerializeHeader_Server() {
+ boost::shared_ptr<XMPPSerializer> testling(createSerializer(ServerStreamType));
+ ProtocolHeader protocolHeader;
+ protocolHeader.setFrom("bla@foo.com");
+ protocolHeader.setTo("foo.com");
+ protocolHeader.setID("myid");
+ protocolHeader.setVersion("0.99");
- CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:server\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:server\" xmlns:stream=\"http://etherx.jabber.org/streams\" from=\"bla@foo.com\" to=\"foo.com\" id=\"myid\" version=\"0.99\">"), testling->serializeHeader(protocolHeader));
+ }
- private:
- XMPPSerializer* createSerializer(StreamType type) {
- return new XMPPSerializer(payloadSerializerCollection, type, false);
- }
+ private:
+ XMPPSerializer* createSerializer(StreamType type) {
+ return new XMPPSerializer(payloadSerializerCollection, type, false);
+ }
- private:
- PayloadSerializerCollection* payloadSerializerCollection;
+ private:
+ PayloadSerializerCollection* payloadSerializerCollection;
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPSerializerTest);
diff --git a/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp b/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
index f9a5e2a..edd1b0e 100644
--- a/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
+++ b/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
@@ -16,55 +16,55 @@ using namespace Swift;
class XMLElementTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(XMLElementTest);
- CPPUNIT_TEST(testSerialize);
- CPPUNIT_TEST(testSerialize_NoChildren);
- CPPUNIT_TEST(testSerialize_SpecialAttributeCharacters);
- CPPUNIT_TEST(testSerialize_EmptyAttributeValue);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- XMLElementTest() {}
-
- void testSerialize() {
- XMLElement testling("foo", "http://example.com");
- testling.setAttribute("myatt", "myval");
- boost::shared_ptr<XMLElement> barElement(new XMLElement("bar"));
- barElement->addNode(boost::make_shared<XMLTextNode>("Blo"));
- testling.addNode(barElement);
- boost::shared_ptr<XMLElement> bazElement(new XMLElement("baz"));
- bazElement->addNode(boost::make_shared<XMLTextNode>("Bli&</stream>"));
- testling.addNode(bazElement);
-
- std::string result = testling.serialize();
- std::string expectedResult =
- "<foo myatt=\"myval\" xmlns=\"http://example.com\">"
- "<bar>Blo</bar>"
- "<baz>Bli&amp;&lt;/stream&gt;</baz>"
- "</foo>";
-
- CPPUNIT_ASSERT_EQUAL(expectedResult, result);
- }
-
- void testSerialize_NoChildren() {
- XMLElement testling("foo", "http://example.com");
-
- CPPUNIT_ASSERT_EQUAL(std::string("<foo xmlns=\"http://example.com\"/>"), testling.serialize());
- }
-
- void testSerialize_SpecialAttributeCharacters() {
- XMLElement testling("foo");
- testling.setAttribute("myatt", "<\"'&>");
-
- CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"&lt;&quot;&apos;&amp;&gt;\"/>"), testling.serialize());
- }
-
- void testSerialize_EmptyAttributeValue() {
- XMLElement testling("foo");
- testling.setAttribute("myatt", "");
-
- CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"\"/>"), testling.serialize());
- }
+ CPPUNIT_TEST_SUITE(XMLElementTest);
+ CPPUNIT_TEST(testSerialize);
+ CPPUNIT_TEST(testSerialize_NoChildren);
+ CPPUNIT_TEST(testSerialize_SpecialAttributeCharacters);
+ CPPUNIT_TEST(testSerialize_EmptyAttributeValue);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ XMLElementTest() {}
+
+ void testSerialize() {
+ XMLElement testling("foo", "http://example.com");
+ testling.setAttribute("myatt", "myval");
+ boost::shared_ptr<XMLElement> barElement(new XMLElement("bar"));
+ barElement->addNode(boost::make_shared<XMLTextNode>("Blo"));
+ testling.addNode(barElement);
+ boost::shared_ptr<XMLElement> bazElement(new XMLElement("baz"));
+ bazElement->addNode(boost::make_shared<XMLTextNode>("Bli&</stream>"));
+ testling.addNode(bazElement);
+
+ std::string result = testling.serialize();
+ std::string expectedResult =
+ "<foo myatt=\"myval\" xmlns=\"http://example.com\">"
+ "<bar>Blo</bar>"
+ "<baz>Bli&amp;&lt;/stream&gt;</baz>"
+ "</foo>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, result);
+ }
+
+ void testSerialize_NoChildren() {
+ XMLElement testling("foo", "http://example.com");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<foo xmlns=\"http://example.com\"/>"), testling.serialize());
+ }
+
+ void testSerialize_SpecialAttributeCharacters() {
+ XMLElement testling("foo");
+ testling.setAttribute("myatt", "<\"'&>");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"&lt;&quot;&apos;&amp;&gt;\"/>"), testling.serialize());
+ }
+
+ void testSerialize_EmptyAttributeValue() {
+ XMLElement testling("foo");
+ testling.setAttribute("myatt", "");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"\"/>"), testling.serialize());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMLElementTest);
diff --git a/Swiften/Serializer/XML/XMLElement.cpp b/Swiften/Serializer/XML/XMLElement.cpp
index 01e89bc..fc5e470 100644
--- a/Swiften/Serializer/XML/XMLElement.cpp
+++ b/Swiften/Serializer/XML/XMLElement.cpp
@@ -12,49 +12,49 @@
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)));
- }
+ 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_) {
- result += " " + p.first + "=\"" + p.second + "\"";
- }
-
- if (!childNodes_.empty()) {
- result += ">";
- foreach (boost::shared_ptr<XMLNode> node, childNodes_) {
- result += node->serialize();
- }
- result += "</" + tag_ + ">";
- }
- else {
- result += "/>";
- }
- return result;
+ std::string result;
+ result += "<" + tag_;
+ typedef std::pair<std::string,std::string> Pair;
+ foreach(const Pair& p, attributes_) {
+ result += " " + p.first + "=\"" + p.second + "\"";
+ }
+
+ if (!childNodes_.empty()) {
+ result += ">";
+ foreach (boost::shared_ptr<XMLNode> 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;
+ 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(boost::shared_ptr<XMLNode> node) {
- if (node) {
- childNodes_.push_back(node);
- }
+ if (node) {
+ childNodes_.push_back(node);
+ }
}
}
diff --git a/Swiften/Serializer/XML/XMLElement.h b/Swiften/Serializer/XML/XMLElement.h
index 66e0a77..e7507f2 100644
--- a/Swiften/Serializer/XML/XMLElement.h
+++ b/Swiften/Serializer/XML/XMLElement.h
@@ -16,20 +16,20 @@
#include <Swiften/Serializer/XML/XMLNode.h>
namespace Swift {
- class SWIFTEN_API XMLElement : public XMLNode {
- public:
- typedef boost::shared_ptr<XMLElement> ref;
+ class SWIFTEN_API XMLElement : public XMLNode {
+ public:
+ typedef boost::shared_ptr<XMLElement> ref;
- XMLElement(const std::string& tag, const std::string& xmlns = "", const std::string& text = "");
+ XMLElement(const std::string& tag, const std::string& xmlns = "", const std::string& text = "");
- void setAttribute(const std::string& attribute, const std::string& value);
- void addNode(boost::shared_ptr<XMLNode> node);
+ void setAttribute(const std::string& attribute, const std::string& value);
+ void addNode(boost::shared_ptr<XMLNode> node);
- virtual std::string serialize();
+ virtual std::string serialize();
- private:
- std::string tag_;
- std::map<std::string, std::string> attributes_;
- std::vector< boost::shared_ptr<XMLNode> > childNodes_;
- };
+ private:
+ std::string tag_;
+ std::map<std::string, std::string> attributes_;
+ std::vector< boost::shared_ptr<XMLNode> > childNodes_;
+ };
}
diff --git a/Swiften/Serializer/XML/XMLNode.h b/Swiften/Serializer/XML/XMLNode.h
index e3ac925..8417b5c 100644
--- a/Swiften/Serializer/XML/XMLNode.h
+++ b/Swiften/Serializer/XML/XMLNode.h
@@ -11,10 +11,10 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API XMLNode {
- public:
- virtual ~XMLNode();
+ class SWIFTEN_API XMLNode {
+ public:
+ virtual ~XMLNode();
- virtual std::string serialize() = 0;
- };
+ virtual std::string serialize() = 0;
+ };
}
diff --git a/Swiften/Serializer/XML/XMLRawTextNode.h b/Swiften/Serializer/XML/XMLRawTextNode.h
index f1e75e6..fbd7754 100644
--- a/Swiften/Serializer/XML/XMLRawTextNode.h
+++ b/Swiften/Serializer/XML/XMLRawTextNode.h
@@ -10,16 +10,16 @@
#include <Swiften/Serializer/XML/XMLNode.h>
namespace Swift {
- class SWIFTEN_API XMLRawTextNode : public XMLNode {
- public:
- XMLRawTextNode(const std::string& text) : text_(text) {
- }
+ class SWIFTEN_API XMLRawTextNode : public XMLNode {
+ public:
+ XMLRawTextNode(const std::string& text) : text_(text) {
+ }
- std::string serialize() {
- return text_;
- }
+ std::string serialize() {
+ return text_;
+ }
- private:
- std::string text_;
- };
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Serializer/XML/XMLTextNode.h b/Swiften/Serializer/XML/XMLTextNode.h
index 86efdf1..b0f8d01 100644
--- a/Swiften/Serializer/XML/XMLTextNode.h
+++ b/Swiften/Serializer/XML/XMLTextNode.h
@@ -13,25 +13,25 @@
#include <Swiften/Serializer/XML/XMLNode.h>
namespace Swift {
- class SWIFTEN_API XMLTextNode : public XMLNode {
- public:
- typedef boost::shared_ptr<XMLTextNode> ref;
-
- XMLTextNode(const std::string& text) : text_(text) {
- String::replaceAll(text_, '&', "&amp;"); // Should come first
- String::replaceAll(text_, '<', "&lt;");
- String::replaceAll(text_, '>', "&gt;");
- }
-
- std::string serialize() {
- return text_;
- }
-
- static ref create(const std::string& text) {
- return ref(new XMLTextNode(text));
- }
-
- private:
- std::string text_;
- };
+ class SWIFTEN_API XMLTextNode : public XMLNode {
+ public:
+ typedef boost::shared_ptr<XMLTextNode> ref;
+
+ XMLTextNode(const std::string& text) : text_(text) {
+ String::replaceAll(text_, '&', "&amp;"); // Should come first
+ String::replaceAll(text_, '<', "&lt;");
+ String::replaceAll(text_, '>', "&gt;");
+ }
+
+ std::string serialize() {
+ return text_;
+ }
+
+ static ref create(const std::string& text) {
+ return ref(new XMLTextNode(text));
+ }
+
+ private:
+ std::string text_;
+ };
}
diff --git a/Swiften/Serializer/XMPPSerializer.cpp b/Swiften/Serializer/XMPPSerializer.cpp
index 7130e51..b17e31b 100644
--- a/Swiften/Serializer/XMPPSerializer.cpp
+++ b/Swiften/Serializer/XMPPSerializer.cpp
@@ -41,72 +41,72 @@
namespace Swift {
XMPPSerializer::XMPPSerializer(PayloadSerializerCollection* payloadSerializers, StreamType type, bool setExplictNSonTopLevelElements) : type_(type) {
- serializers_.push_back(boost::make_shared<PresenceSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
- serializers_.push_back(boost::make_shared<IQSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
- serializers_.push_back(boost::make_shared<MessageSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
- serializers_.push_back(boost::make_shared<CompressRequestSerializer>());
- serializers_.push_back(boost::make_shared<CompressFailureSerializer>());
- serializers_.push_back(boost::make_shared<AuthRequestSerializer>());
- serializers_.push_back(boost::make_shared<AuthFailureSerializer>());
- serializers_.push_back(boost::make_shared<AuthSuccessSerializer>());
- serializers_.push_back(boost::make_shared<AuthChallengeSerializer>());
- serializers_.push_back(boost::make_shared<AuthResponseSerializer>());
- serializers_.push_back(boost::make_shared<StartTLSRequestSerializer>());
- serializers_.push_back(boost::make_shared<StartTLSFailureSerializer>());
- serializers_.push_back(boost::make_shared<TLSProceedSerializer>());
- serializers_.push_back(boost::make_shared<StreamFeaturesSerializer>());
- serializers_.push_back(boost::make_shared<StreamErrorSerializer>());
- serializers_.push_back(boost::make_shared<EnableStreamManagementSerializer>());
- serializers_.push_back(boost::make_shared<StreamManagementEnabledSerializer>());
- serializers_.push_back(boost::make_shared<StreamManagementFailedSerializer>());
- serializers_.push_back(boost::make_shared<StreamResumeSerializer>());
- serializers_.push_back(boost::make_shared<StreamResumedSerializer>());
- serializers_.push_back(boost::make_shared<StanzaAckSerializer>());
- serializers_.push_back(boost::make_shared<StanzaAckRequestSerializer>());
- serializers_.push_back(boost::make_shared<ComponentHandshakeSerializer>());
+ serializers_.push_back(boost::make_shared<PresenceSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(boost::make_shared<IQSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(boost::make_shared<MessageSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(boost::make_shared<CompressRequestSerializer>());
+ serializers_.push_back(boost::make_shared<CompressFailureSerializer>());
+ serializers_.push_back(boost::make_shared<AuthRequestSerializer>());
+ serializers_.push_back(boost::make_shared<AuthFailureSerializer>());
+ serializers_.push_back(boost::make_shared<AuthSuccessSerializer>());
+ serializers_.push_back(boost::make_shared<AuthChallengeSerializer>());
+ serializers_.push_back(boost::make_shared<AuthResponseSerializer>());
+ serializers_.push_back(boost::make_shared<StartTLSRequestSerializer>());
+ serializers_.push_back(boost::make_shared<StartTLSFailureSerializer>());
+ serializers_.push_back(boost::make_shared<TLSProceedSerializer>());
+ serializers_.push_back(boost::make_shared<StreamFeaturesSerializer>());
+ serializers_.push_back(boost::make_shared<StreamErrorSerializer>());
+ serializers_.push_back(boost::make_shared<EnableStreamManagementSerializer>());
+ serializers_.push_back(boost::make_shared<StreamManagementEnabledSerializer>());
+ serializers_.push_back(boost::make_shared<StreamManagementFailedSerializer>());
+ serializers_.push_back(boost::make_shared<StreamResumeSerializer>());
+ serializers_.push_back(boost::make_shared<StreamResumedSerializer>());
+ serializers_.push_back(boost::make_shared<StanzaAckSerializer>());
+ serializers_.push_back(boost::make_shared<StanzaAckRequestSerializer>());
+ serializers_.push_back(boost::make_shared<ComponentHandshakeSerializer>());
}
std::string XMPPSerializer::serializeHeader(const ProtocolHeader& header) const {
- std::string result = "<?xml version=\"1.0\"?><stream:stream xmlns=\"" + getDefaultNamespace() + "\" xmlns:stream=\"http://etherx.jabber.org/streams\"";
- if (!header.getFrom().empty()) {
- result += " from=\"" + header.getFrom() + "\"";
- }
- if (!header.getTo().empty()) {
- result += " to=\"" + header.getTo() + "\"";
- }
- if (!header.getID().empty()) {
- result += " id=\"" + header.getID() + "\"";
- }
- if (!header.getVersion().empty()) {
- result += " version=\"" + header.getVersion() + "\"";
- }
- result += ">";
- return result;
+ std::string result = "<?xml version=\"1.0\"?><stream:stream xmlns=\"" + getDefaultNamespace() + "\" xmlns:stream=\"http://etherx.jabber.org/streams\"";
+ if (!header.getFrom().empty()) {
+ result += " from=\"" + header.getFrom() + "\"";
+ }
+ if (!header.getTo().empty()) {
+ result += " to=\"" + header.getTo() + "\"";
+ }
+ if (!header.getID().empty()) {
+ result += " id=\"" + header.getID() + "\"";
+ }
+ if (!header.getVersion().empty()) {
+ result += " version=\"" + header.getVersion() + "\"";
+ }
+ result += ">";
+ return result;
}
SafeByteArray XMPPSerializer::serializeElement(boost::shared_ptr<ToplevelElement> element) const {
- std::vector< boost::shared_ptr<ElementSerializer> >::const_iterator i = std::find_if(serializers_.begin(), serializers_.end(), boost::bind(&ElementSerializer::canSerialize, _1, element));
- if (i != serializers_.end()) {
- return (*i)->serialize(element);
- }
- else {
- std::cerr << "Could not find serializer for " << typeid(*(element.get())).name() << std::endl;
- return createSafeByteArray("");
- }
+ std::vector< boost::shared_ptr<ElementSerializer> >::const_iterator i = std::find_if(serializers_.begin(), serializers_.end(), boost::bind(&ElementSerializer::canSerialize, _1, element));
+ if (i != serializers_.end()) {
+ return (*i)->serialize(element);
+ }
+ else {
+ std::cerr << "Could not find serializer for " << typeid(*(element.get())).name() << std::endl;
+ return createSafeByteArray("");
+ }
}
std::string XMPPSerializer::serializeFooter() const {
- return "</stream:stream>";
+ return "</stream:stream>";
}
std::string XMPPSerializer::getDefaultNamespace() const {
- switch (type_) {
- case ClientStreamType: return "jabber:client";
- case ServerStreamType: return "jabber:server";
- case ComponentStreamType: return "jabber:component:accept";
- }
- assert(false);
- return "";
+ switch (type_) {
+ case ClientStreamType: return "jabber:client";
+ case ServerStreamType: return "jabber:server";
+ case ComponentStreamType: return "jabber:component:accept";
+ }
+ assert(false);
+ return "";
}
}
diff --git a/Swiften/Serializer/XMPPSerializer.h b/Swiften/Serializer/XMPPSerializer.h
index 493a88d..a771fdd 100644
--- a/Swiften/Serializer/XMPPSerializer.h
+++ b/Swiften/Serializer/XMPPSerializer.h
@@ -17,23 +17,23 @@
#include <Swiften/Serializer/ElementSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
- class CompressRequestSerializer;
- class ProtocolHeader;
-
- class SWIFTEN_API XMPPSerializer {
- public:
- XMPPSerializer(PayloadSerializerCollection*, StreamType type, bool setExplictNSonTopLevelElements);
-
- std::string serializeHeader(const ProtocolHeader&) const;
- SafeByteArray serializeElement(boost::shared_ptr<ToplevelElement> stanza) const;
- std::string serializeFooter() const;
-
- private:
- std::string getDefaultNamespace() const;
-
- private:
- StreamType type_;
- std::vector< boost::shared_ptr<ElementSerializer> > serializers_;
- };
+ class PayloadSerializerCollection;
+ class CompressRequestSerializer;
+ class ProtocolHeader;
+
+ class SWIFTEN_API XMPPSerializer {
+ public:
+ XMPPSerializer(PayloadSerializerCollection*, StreamType type, bool setExplictNSonTopLevelElements);
+
+ std::string serializeHeader(const ProtocolHeader&) const;
+ SafeByteArray serializeElement(boost::shared_ptr<ToplevelElement> stanza) const;
+ std::string serializeFooter() const;
+
+ private:
+ std::string getDefaultNamespace() const;
+
+ private:
+ StreamType type_;
+ std::vector< boost::shared_ptr<ElementSerializer> > serializers_;
+ };
}
diff --git a/Swiften/Session/BOSHSessionStream.cpp b/Swiften/Session/BOSHSessionStream.cpp
index 7fb8b31..3794ae3 100644
--- a/Swiften/Session/BOSHSessionStream.cpp
+++ b/Swiften/Session/BOSHSessionStream.cpp
@@ -27,123 +27,123 @@
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,
- boost::shared_ptr<HTTPTrafficFilter> trafficFilter) :
- available(false),
- eventLoop(eventLoop),
- firstHeader(true) {
-
- boost::mt19937 random;
- boost::uniform_int<unsigned long long> dist(0, (1LL<<53) - 1);
- random.seed(static_cast<unsigned int>(time(NULL)));
- unsigned long long initialRID = boost::variate_generator<boost::mt19937&, boost::uniform_int<unsigned long long> >(random, dist)();
-
- connectionPool = new BOSHConnectionPool(boshURL, resolver, connectionFactory, xmlParserFactory, tlsContextFactory, timerFactory, eventLoop, to, initialRID, boshHTTPConnectProxyURL, boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, tlsOptions, trafficFilter);
- connectionPool->onSessionTerminated.connect(boost::bind(&BOSHSessionStream::handlePoolSessionTerminated, this, _1));
- connectionPool->onSessionStarted.connect(boost::bind(&BOSHSessionStream::handlePoolSessionStarted, this));
- connectionPool->onXMPPDataRead.connect(boost::bind(&BOSHSessionStream::handlePoolXMPPDataRead, this, _1));
- connectionPool->onBOSHDataRead.connect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataRead, this, _1));
- connectionPool->onBOSHDataWritten.connect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataWritten, this, _1));
-
- xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType, true);
- xmppLayer->onStreamStart.connect(boost::bind(&BOSHSessionStream::handleStreamStartReceived, this, _1));
- xmppLayer->onElement.connect(boost::bind(&BOSHSessionStream::handleElementReceived, this, _1));
- xmppLayer->onError.connect(boost::bind(&BOSHSessionStream::handleXMPPError, this));
- xmppLayer->onWriteData.connect(boost::bind(&BOSHSessionStream::handleXMPPLayerDataWritten, this, _1));
-
- available = true;
+ 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,
+ boost::shared_ptr<HTTPTrafficFilter> trafficFilter) :
+ available(false),
+ eventLoop(eventLoop),
+ firstHeader(true) {
+
+ boost::mt19937 random;
+ boost::uniform_int<unsigned long long> dist(0, (1LL<<53) - 1);
+ random.seed(static_cast<unsigned int>(time(NULL)));
+ unsigned long long initialRID = boost::variate_generator<boost::mt19937&, boost::uniform_int<unsigned long long> >(random, dist)();
+
+ connectionPool = new BOSHConnectionPool(boshURL, resolver, connectionFactory, xmlParserFactory, tlsContextFactory, timerFactory, eventLoop, to, initialRID, boshHTTPConnectProxyURL, boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, tlsOptions, trafficFilter);
+ connectionPool->onSessionTerminated.connect(boost::bind(&BOSHSessionStream::handlePoolSessionTerminated, this, _1));
+ connectionPool->onSessionStarted.connect(boost::bind(&BOSHSessionStream::handlePoolSessionStarted, this));
+ connectionPool->onXMPPDataRead.connect(boost::bind(&BOSHSessionStream::handlePoolXMPPDataRead, this, _1));
+ connectionPool->onBOSHDataRead.connect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataRead, this, _1));
+ connectionPool->onBOSHDataWritten.connect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataWritten, this, _1));
+
+ xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType, true);
+ xmppLayer->onStreamStart.connect(boost::bind(&BOSHSessionStream::handleStreamStartReceived, this, _1));
+ xmppLayer->onElement.connect(boost::bind(&BOSHSessionStream::handleElementReceived, this, _1));
+ xmppLayer->onError.connect(boost::bind(&BOSHSessionStream::handleXMPPError, this));
+ xmppLayer->onWriteData.connect(boost::bind(&BOSHSessionStream::handleXMPPLayerDataWritten, this, _1));
+
+ available = true;
}
BOSHSessionStream::~BOSHSessionStream() {
- BOSHSessionStream::close();
- connectionPool->onSessionTerminated.disconnect(boost::bind(&BOSHSessionStream::handlePoolSessionTerminated, this, _1));
- connectionPool->onSessionStarted.disconnect(boost::bind(&BOSHSessionStream::handlePoolSessionStarted, this));
- connectionPool->onXMPPDataRead.disconnect(boost::bind(&BOSHSessionStream::handlePoolXMPPDataRead, this, _1));
- connectionPool->onBOSHDataRead.disconnect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataRead, this, _1));
- connectionPool->onBOSHDataWritten.disconnect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataWritten, this, _1));
- delete connectionPool;
- connectionPool = NULL;
- xmppLayer->onStreamStart.disconnect(boost::bind(&BOSHSessionStream::handleStreamStartReceived, this, _1));
- xmppLayer->onElement.disconnect(boost::bind(&BOSHSessionStream::handleElementReceived, this, _1));
- xmppLayer->onError.disconnect(boost::bind(&BOSHSessionStream::handleXMPPError, this));
- xmppLayer->onWriteData.disconnect(boost::bind(&BOSHSessionStream::handleXMPPLayerDataWritten, this, _1));
- delete xmppLayer;
- xmppLayer = NULL;
+ BOSHSessionStream::close();
+ connectionPool->onSessionTerminated.disconnect(boost::bind(&BOSHSessionStream::handlePoolSessionTerminated, this, _1));
+ connectionPool->onSessionStarted.disconnect(boost::bind(&BOSHSessionStream::handlePoolSessionStarted, this));
+ connectionPool->onXMPPDataRead.disconnect(boost::bind(&BOSHSessionStream::handlePoolXMPPDataRead, this, _1));
+ connectionPool->onBOSHDataRead.disconnect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataRead, this, _1));
+ connectionPool->onBOSHDataWritten.disconnect(boost::bind(&BOSHSessionStream::handlePoolBOSHDataWritten, this, _1));
+ delete connectionPool;
+ connectionPool = NULL;
+ xmppLayer->onStreamStart.disconnect(boost::bind(&BOSHSessionStream::handleStreamStartReceived, this, _1));
+ xmppLayer->onElement.disconnect(boost::bind(&BOSHSessionStream::handleElementReceived, this, _1));
+ xmppLayer->onError.disconnect(boost::bind(&BOSHSessionStream::handleXMPPError, this));
+ xmppLayer->onWriteData.disconnect(boost::bind(&BOSHSessionStream::handleXMPPLayerDataWritten, this, _1));
+ delete xmppLayer;
+ xmppLayer = NULL;
}
void BOSHSessionStream::open() {
- connectionPool->setTLSCertificate(getTLSCertificate());
- connectionPool->open();
+ connectionPool->setTLSCertificate(getTLSCertificate());
+ connectionPool->open();
}
void BOSHSessionStream::handlePoolXMPPDataRead(const SafeByteArray& data) {
- xmppLayer->handleDataRead(data);
+ xmppLayer->handleDataRead(data);
}
void BOSHSessionStream::writeElement(boost::shared_ptr<ToplevelElement> element) {
- assert(available);
- xmppLayer->writeElement(element);
+ assert(available);
+ xmppLayer->writeElement(element);
}
void BOSHSessionStream::writeFooter() {
- connectionPool->writeFooter();
+ connectionPool->writeFooter();
}
void BOSHSessionStream::writeData(const std::string& data) {
- assert(available);
- xmppLayer->writeData(data);
+ assert(available);
+ xmppLayer->writeData(data);
}
void BOSHSessionStream::close() {
- connectionPool->close();
+ connectionPool->close();
}
bool BOSHSessionStream::isOpen() {
- return available;
+ return available;
}
bool BOSHSessionStream::supportsTLSEncryption() {
- return false;
+ return false;
}
void BOSHSessionStream::addTLSEncryption() {
- assert(available);
+ assert(available);
}
bool BOSHSessionStream::isTLSEncrypted() {
- return connectionPool->isTLSEncrypted();
+ return connectionPool->isTLSEncrypted();
}
Certificate::ref BOSHSessionStream::getPeerCertificate() const {
- return connectionPool->getPeerCertificate();
+ return connectionPool->getPeerCertificate();
}
std::vector<Certificate::ref> BOSHSessionStream::getPeerCertificateChain() const {
- return connectionPool->getPeerCertificateChain();
+ return connectionPool->getPeerCertificateChain();
}
boost::shared_ptr<CertificateVerificationError> BOSHSessionStream::getPeerCertificateVerificationError() const {
- return connectionPool->getPeerCertificateVerificationError();
+ return connectionPool->getPeerCertificateVerificationError();
}
ByteArray BOSHSessionStream::getTLSFinishMessage() const {
- return ByteArray();
+ return ByteArray();
}
bool BOSHSessionStream::supportsZLibCompression() {
- return false;
+ return false;
}
void BOSHSessionStream::addZLibCompression() {
@@ -151,71 +151,71 @@ void BOSHSessionStream::addZLibCompression() {
}
void BOSHSessionStream::setWhitespacePingEnabled(bool /*enabled*/) {
- return;
+ return;
}
void BOSHSessionStream::resetXMPPParser() {
- xmppLayer->resetParser();
+ xmppLayer->resetParser();
}
void BOSHSessionStream::handleStreamStartReceived(const ProtocolHeader& header) {
- onStreamStartReceived(header);
+ onStreamStartReceived(header);
}
void BOSHSessionStream::handleElementReceived(boost::shared_ptr<ToplevelElement> element) {
- onElementReceived(element);
+ onElementReceived(element);
}
void BOSHSessionStream::handleXMPPError() {
- available = false;
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
+ available = false;
+ onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
}
void BOSHSessionStream::handlePoolSessionStarted() {
- fakeStreamHeaderReceipt();
+ fakeStreamHeaderReceipt();
}
void BOSHSessionStream::handlePoolSessionTerminated(BOSHError::ref error) {
- eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamFooterReceipt, this, error), shared_from_this());
+ eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamFooterReceipt, this, error), shared_from_this());
}
void BOSHSessionStream::writeHeader(const ProtocolHeader& header) {
- streamHeader = header;
- /*First time we're told to do this, don't (the sending of the initial header is handled on connect)
- On subsequent requests we should restart the stream the BOSH way.
- */
- if (!firstHeader) {
- eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamHeaderReceipt, this), shared_from_this());
- eventLoop->postEvent(boost::bind(&BOSHConnectionPool::restartStream, connectionPool), shared_from_this());
- }
- firstHeader = false;
+ streamHeader = header;
+ /*First time we're told to do this, don't (the sending of the initial header is handled on connect)
+ On subsequent requests we should restart the stream the BOSH way.
+ */
+ if (!firstHeader) {
+ eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamHeaderReceipt, this), shared_from_this());
+ eventLoop->postEvent(boost::bind(&BOSHConnectionPool::restartStream, connectionPool), shared_from_this());
+ }
+ firstHeader = false;
}
void BOSHSessionStream::fakeStreamHeaderReceipt() {
- std::stringstream header;
- header << "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' from='";
- header << streamHeader.getTo() << "' id='dummy' version='1.0'>";
+ std::stringstream header;
+ header << "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' from='";
+ header << streamHeader.getTo() << "' id='dummy' version='1.0'>";
- xmppLayer->handleDataRead(createSafeByteArray(header.str()));
+ xmppLayer->handleDataRead(createSafeByteArray(header.str()));
}
void BOSHSessionStream::fakeStreamFooterReceipt(BOSHError::ref error) {
- std::string footer("</stream:stream>");
- xmppLayer->handleDataRead(createSafeByteArray(footer));
- onClosed(error);
+ std::string footer("</stream:stream>");
+ xmppLayer->handleDataRead(createSafeByteArray(footer));
+ onClosed(error);
}
void BOSHSessionStream::handleXMPPLayerDataWritten(const SafeByteArray& data) {
- eventLoop->postEvent(boost::bind(&BOSHConnectionPool::write, connectionPool, data), shared_from_this());
+ eventLoop->postEvent(boost::bind(&BOSHConnectionPool::write, connectionPool, data), shared_from_this());
}
void BOSHSessionStream::handlePoolBOSHDataRead(const SafeByteArray& data) {
- onDataRead(data);
+ onDataRead(data);
}
void BOSHSessionStream::handlePoolBOSHDataWritten(const SafeByteArray& data) {
- onDataWritten(data);
+ onDataWritten(data);
}
}
diff --git a/Swiften/Session/BOSHSessionStream.h b/Swiften/Session/BOSHSessionStream.h
index 66e41ea..17292f4 100644
--- a/Swiften/Session/BOSHSessionStream.h
+++ b/Swiften/Session/BOSHSessionStream.h
@@ -18,85 +18,85 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class CompressionLayer;
- class ConnectionLayer;
- class EventLoop;
- class HTTPTrafficFilter;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
- class StreamStack;
- class TLSContextFactory;
- class TimerFactory;
- class XMLParserFactory;
- class XMPPLayer;
+ class CompressionLayer;
+ class ConnectionLayer;
+ class EventLoop;
+ class HTTPTrafficFilter;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+ class StreamStack;
+ class TLSContextFactory;
+ class TimerFactory;
+ class XMLParserFactory;
+ class XMPPLayer;
- class SWIFTEN_API BOSHSessionStream : public SessionStream, public EventOwner, public boost::enable_shared_from_this<BOSHSessionStream> {
- public:
- BOSHSessionStream(
- const URL& boshURL,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- ConnectionFactory* connectionFactory,
- TLSContextFactory* tlsContextFactory,
- TimerFactory* whitespacePingLayerFactory,
- XMLParserFactory* xmlParserFactory,
- EventLoop* eventLoop,
- DomainNameResolver* resolver,
- const std::string& to,
- const URL& boshHTTPConnectProxyURL,
- const SafeString& boshHTTPConnectProxyAuthID,
- const SafeString& boshHTTPConnectProxyAuthPassword,
- const TLSOptions& tlsOptions,
- boost::shared_ptr<HTTPTrafficFilter> trafficFilter
- );
- virtual ~BOSHSessionStream();
+ class SWIFTEN_API BOSHSessionStream : public SessionStream, public EventOwner, public boost::enable_shared_from_this<BOSHSessionStream> {
+ public:
+ BOSHSessionStream(
+ const URL& boshURL,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ ConnectionFactory* connectionFactory,
+ TLSContextFactory* tlsContextFactory,
+ TimerFactory* whitespacePingLayerFactory,
+ XMLParserFactory* xmlParserFactory,
+ EventLoop* eventLoop,
+ DomainNameResolver* resolver,
+ const std::string& to,
+ const URL& boshHTTPConnectProxyURL,
+ const SafeString& boshHTTPConnectProxyAuthID,
+ const SafeString& boshHTTPConnectProxyAuthPassword,
+ const TLSOptions& tlsOptions,
+ boost::shared_ptr<HTTPTrafficFilter> trafficFilter
+ );
+ virtual ~BOSHSessionStream();
- void open();
- virtual void close();
- virtual bool isOpen();
+ void open();
+ virtual void close();
+ virtual bool isOpen();
- virtual void writeHeader(const ProtocolHeader& header);
- virtual void writeElement(boost::shared_ptr<ToplevelElement>);
- virtual void writeFooter();
- virtual void writeData(const std::string& data);
+ virtual void writeHeader(const ProtocolHeader& header);
+ virtual void writeElement(boost::shared_ptr<ToplevelElement>);
+ virtual void writeFooter();
+ virtual void writeData(const std::string& data);
- virtual bool supportsZLibCompression();
- virtual void addZLibCompression();
+ virtual bool supportsZLibCompression();
+ virtual void addZLibCompression();
- virtual bool supportsTLSEncryption();
- virtual void addTLSEncryption();
- virtual bool isTLSEncrypted();
- virtual Certificate::ref getPeerCertificate() const;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
- virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
- virtual ByteArray getTLSFinishMessage() const;
+ virtual bool supportsTLSEncryption();
+ virtual void addTLSEncryption();
+ virtual bool isTLSEncrypted();
+ virtual Certificate::ref getPeerCertificate() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+ virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ virtual ByteArray getTLSFinishMessage() const;
- virtual void setWhitespacePingEnabled(bool);
+ virtual void setWhitespacePingEnabled(bool);
- virtual void resetXMPPParser();
+ virtual void resetXMPPParser();
- private:
- void handleXMPPError();
- void handleStreamStartReceived(const ProtocolHeader&);
- void handleElementReceived(boost::shared_ptr<ToplevelElement>);
- void handlePoolXMPPDataRead(const SafeByteArray& data);
- void handleXMPPLayerDataWritten(const SafeByteArray& data);
- void handlePoolSessionStarted();
- void handlePoolBOSHDataRead(const SafeByteArray& data);
- void handlePoolBOSHDataWritten(const SafeByteArray& data);
- void handlePoolSessionTerminated(BOSHError::ref condition);
+ private:
+ void handleXMPPError();
+ void handleStreamStartReceived(const ProtocolHeader&);
+ void handleElementReceived(boost::shared_ptr<ToplevelElement>);
+ void handlePoolXMPPDataRead(const SafeByteArray& data);
+ void handleXMPPLayerDataWritten(const SafeByteArray& data);
+ void handlePoolSessionStarted();
+ void handlePoolBOSHDataRead(const SafeByteArray& data);
+ void handlePoolBOSHDataWritten(const SafeByteArray& data);
+ void handlePoolSessionTerminated(BOSHError::ref condition);
- private:
- void fakeStreamHeaderReceipt();
- void fakeStreamFooterReceipt(BOSHError::ref error);
+ private:
+ void fakeStreamHeaderReceipt();
+ void fakeStreamFooterReceipt(BOSHError::ref error);
- private:
- BOSHConnectionPool* connectionPool;
- bool available;
- XMPPLayer* xmppLayer;
- ProtocolHeader streamHeader;
- EventLoop* eventLoop;
- bool firstHeader;
- };
+ private:
+ BOSHConnectionPool* connectionPool;
+ bool available;
+ XMPPLayer* xmppLayer;
+ ProtocolHeader streamHeader;
+ EventLoop* eventLoop;
+ bool firstHeader;
+ };
}
diff --git a/Swiften/Session/BasicSessionStream.cpp b/Swiften/Session/BasicSessionStream.cpp
index c2d8515..697115a 100644
--- a/Swiften/Session/BasicSessionStream.cpp
+++ b/Swiften/Session/BasicSessionStream.cpp
@@ -21,192 +21,192 @@
namespace Swift {
BasicSessionStream::BasicSessionStream(
- StreamType streamType,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- TLSContextFactory* tlsContextFactory,
- TimerFactory* timerFactory,
- XMLParserFactory* xmlParserFactory,
- const TLSOptions& tlsOptions) :
- available(false),
- connection(connection),
- tlsContextFactory(tlsContextFactory),
- timerFactory(timerFactory),
- compressionLayer(NULL),
- tlsLayer(NULL),
- whitespacePingLayer(NULL),
- tlsOptions_(tlsOptions) {
- xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType);
- xmppLayer->onStreamStart.connect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
- xmppLayer->onElement.connect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1));
- xmppLayer->onError.connect(boost::bind(&BasicSessionStream::handleXMPPError, this));
- xmppLayer->onDataRead.connect(boost::bind(&BasicSessionStream::handleDataRead, this, _1));
- xmppLayer->onWriteData.connect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1));
-
- connection->onDisconnected.connect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1));
- connectionLayer = new ConnectionLayer(connection);
-
- streamStack = new StreamStack(xmppLayer, connectionLayer);
-
- available = true;
+ StreamType streamType,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ TLSContextFactory* tlsContextFactory,
+ TimerFactory* timerFactory,
+ XMLParserFactory* xmlParserFactory,
+ const TLSOptions& tlsOptions) :
+ available(false),
+ connection(connection),
+ tlsContextFactory(tlsContextFactory),
+ timerFactory(timerFactory),
+ compressionLayer(NULL),
+ tlsLayer(NULL),
+ whitespacePingLayer(NULL),
+ tlsOptions_(tlsOptions) {
+ xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType);
+ xmppLayer->onStreamStart.connect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
+ xmppLayer->onElement.connect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1));
+ xmppLayer->onError.connect(boost::bind(&BasicSessionStream::handleXMPPError, this));
+ xmppLayer->onDataRead.connect(boost::bind(&BasicSessionStream::handleDataRead, this, _1));
+ xmppLayer->onWriteData.connect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1));
+
+ connection->onDisconnected.connect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1));
+ connectionLayer = new ConnectionLayer(connection);
+
+ streamStack = new StreamStack(xmppLayer, connectionLayer);
+
+ available = true;
}
BasicSessionStream::~BasicSessionStream() {
- delete compressionLayer;
+ delete compressionLayer;
- if (tlsLayer) {
- tlsLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleTLSError, this, _1));
- tlsLayer->onConnected.disconnect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
- delete tlsLayer;
- }
- delete whitespacePingLayer;
- delete streamStack;
+ if (tlsLayer) {
+ tlsLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleTLSError, this, _1));
+ tlsLayer->onConnected.disconnect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
+ delete tlsLayer;
+ }
+ delete whitespacePingLayer;
+ delete streamStack;
- connection->onDisconnected.disconnect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1));
- delete connectionLayer;
+ connection->onDisconnected.disconnect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1));
+ delete connectionLayer;
- xmppLayer->onStreamStart.disconnect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
- xmppLayer->onElement.disconnect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1));
- xmppLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleXMPPError, this));
- xmppLayer->onDataRead.disconnect(boost::bind(&BasicSessionStream::handleDataRead, this, _1));
- xmppLayer->onWriteData.disconnect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1));
- delete xmppLayer;
+ xmppLayer->onStreamStart.disconnect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
+ xmppLayer->onElement.disconnect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1));
+ xmppLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleXMPPError, this));
+ xmppLayer->onDataRead.disconnect(boost::bind(&BasicSessionStream::handleDataRead, this, _1));
+ xmppLayer->onWriteData.disconnect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1));
+ delete xmppLayer;
}
void BasicSessionStream::writeHeader(const ProtocolHeader& header) {
- assert(available);
- xmppLayer->writeHeader(header);
+ assert(available);
+ xmppLayer->writeHeader(header);
}
void BasicSessionStream::writeElement(boost::shared_ptr<ToplevelElement> element) {
- assert(available);
- xmppLayer->writeElement(element);
+ assert(available);
+ xmppLayer->writeElement(element);
}
void BasicSessionStream::writeFooter() {
- assert(available);
- xmppLayer->writeFooter();
+ assert(available);
+ xmppLayer->writeFooter();
}
void BasicSessionStream::writeData(const std::string& data) {
- assert(available);
- xmppLayer->writeData(data);
+ assert(available);
+ xmppLayer->writeData(data);
}
void BasicSessionStream::close() {
- connection->disconnect();
+ connection->disconnect();
}
bool BasicSessionStream::isOpen() {
- return available;
+ return available;
}
bool BasicSessionStream::supportsTLSEncryption() {
- return tlsContextFactory && tlsContextFactory->canCreate();
+ return tlsContextFactory && tlsContextFactory->canCreate();
}
void BasicSessionStream::addTLSEncryption() {
- assert(available);
- tlsLayer = new TLSLayer(tlsContextFactory, tlsOptions_);
- if (hasTLSCertificate() && !tlsLayer->setClientCertificate(getTLSCertificate())) {
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::InvalidTLSCertificateError));
- }
- else {
- streamStack->addLayer(tlsLayer);
- tlsLayer->onError.connect(boost::bind(&BasicSessionStream::handleTLSError, this, _1));
- tlsLayer->onConnected.connect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
- tlsLayer->connect();
- }
+ assert(available);
+ tlsLayer = new TLSLayer(tlsContextFactory, tlsOptions_);
+ if (hasTLSCertificate() && !tlsLayer->setClientCertificate(getTLSCertificate())) {
+ onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::InvalidTLSCertificateError));
+ }
+ else {
+ streamStack->addLayer(tlsLayer);
+ tlsLayer->onError.connect(boost::bind(&BasicSessionStream::handleTLSError, this, _1));
+ tlsLayer->onConnected.connect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
+ tlsLayer->connect();
+ }
}
bool BasicSessionStream::isTLSEncrypted() {
- return tlsLayer;
+ return tlsLayer;
}
Certificate::ref BasicSessionStream::getPeerCertificate() const {
- return tlsLayer->getPeerCertificate();
+ return tlsLayer->getPeerCertificate();
}
std::vector<Certificate::ref> BasicSessionStream::getPeerCertificateChain() const {
- return tlsLayer->getPeerCertificateChain();
+ return tlsLayer->getPeerCertificateChain();
}
boost::shared_ptr<CertificateVerificationError> BasicSessionStream::getPeerCertificateVerificationError() const {
- return tlsLayer->getPeerCertificateVerificationError();
+ return tlsLayer->getPeerCertificateVerificationError();
}
ByteArray BasicSessionStream::getTLSFinishMessage() const {
- return tlsLayer->getContext()->getFinishMessage();
+ return tlsLayer->getContext()->getFinishMessage();
}
bool BasicSessionStream::supportsZLibCompression() {
- return true;
+ return true;
}
void BasicSessionStream::addZLibCompression() {
- compressionLayer = new CompressionLayer();
- streamStack->addLayer(compressionLayer);
+ compressionLayer = new CompressionLayer();
+ streamStack->addLayer(compressionLayer);
}
void BasicSessionStream::setWhitespacePingEnabled(bool enabled) {
- if (enabled) {
- if (!whitespacePingLayer) {
- whitespacePingLayer = new WhitespacePingLayer(timerFactory);
- streamStack->addLayer(whitespacePingLayer);
- }
- whitespacePingLayer->setActive();
- }
- else if (whitespacePingLayer) {
- whitespacePingLayer->setInactive();
- }
+ if (enabled) {
+ if (!whitespacePingLayer) {
+ whitespacePingLayer = new WhitespacePingLayer(timerFactory);
+ streamStack->addLayer(whitespacePingLayer);
+ }
+ whitespacePingLayer->setActive();
+ }
+ else if (whitespacePingLayer) {
+ whitespacePingLayer->setInactive();
+ }
}
void BasicSessionStream::resetXMPPParser() {
- xmppLayer->resetParser();
+ xmppLayer->resetParser();
}
void BasicSessionStream::handleStreamStartReceived(const ProtocolHeader& header) {
- onStreamStartReceived(header);
+ onStreamStartReceived(header);
}
void BasicSessionStream::handleElementReceived(boost::shared_ptr<ToplevelElement> element) {
- onElementReceived(element);
+ onElementReceived(element);
}
void BasicSessionStream::handleXMPPError() {
- available = false;
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
+ available = false;
+ onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
}
void BasicSessionStream::handleTLSConnected() {
- onTLSEncrypted();
+ onTLSEncrypted();
}
void BasicSessionStream::handleTLSError(boost::shared_ptr<TLSError> error) {
- available = false;
- onClosed(error);
+ available = false;
+ onClosed(error);
}
void BasicSessionStream::handleConnectionFinished(const boost::optional<Connection::Error>& error) {
- available = false;
- if (error == Connection::ReadError) {
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ConnectionReadError));
- }
- else if (error) {
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ConnectionWriteError));
- }
- else {
- onClosed(boost::shared_ptr<SessionStreamError>());
- }
+ available = false;
+ if (error == Connection::ReadError) {
+ onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ConnectionReadError));
+ }
+ else if (error) {
+ onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ConnectionWriteError));
+ }
+ else {
+ onClosed(boost::shared_ptr<SessionStreamError>());
+ }
}
void BasicSessionStream::handleDataRead(const SafeByteArray& data) {
- onDataRead(data);
+ onDataRead(data);
}
void BasicSessionStream::handleDataWritten(const SafeByteArray& data) {
- onDataWritten(data);
+ onDataWritten(data);
}
}
diff --git a/Swiften/Session/BasicSessionStream.h b/Swiften/Session/BasicSessionStream.h
index 2298351..db4a7e0 100644
--- a/Swiften/Session/BasicSessionStream.h
+++ b/Swiften/Session/BasicSessionStream.h
@@ -17,78 +17,78 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class TLSContextFactory;
- class TLSLayer;
- class TimerFactory;
- class WhitespacePingLayer;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
- class StreamStack;
- class XMPPLayer;
- class ConnectionLayer;
- class CompressionLayer;
- class XMLParserFactory;
+ class TLSContextFactory;
+ class TLSLayer;
+ class TimerFactory;
+ class WhitespacePingLayer;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+ class StreamStack;
+ class XMPPLayer;
+ class ConnectionLayer;
+ class CompressionLayer;
+ class XMLParserFactory;
- class SWIFTEN_API BasicSessionStream : public SessionStream {
- public:
- BasicSessionStream(
- StreamType streamType,
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- TLSContextFactory* tlsContextFactory,
- TimerFactory* whitespacePingLayerFactory,
- XMLParserFactory* xmlParserFactory,
- const TLSOptions& tlsOptions
- );
- virtual ~BasicSessionStream();
+ class SWIFTEN_API BasicSessionStream : public SessionStream {
+ public:
+ BasicSessionStream(
+ StreamType streamType,
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ TLSContextFactory* tlsContextFactory,
+ TimerFactory* whitespacePingLayerFactory,
+ XMLParserFactory* xmlParserFactory,
+ const TLSOptions& tlsOptions
+ );
+ virtual ~BasicSessionStream();
- virtual void close();
- virtual bool isOpen();
+ virtual void close();
+ virtual bool isOpen();
- virtual void writeHeader(const ProtocolHeader& header);
- virtual void writeElement(boost::shared_ptr<ToplevelElement>);
- virtual void writeFooter();
- virtual void writeData(const std::string& data);
+ virtual void writeHeader(const ProtocolHeader& header);
+ virtual void writeElement(boost::shared_ptr<ToplevelElement>);
+ virtual void writeFooter();
+ virtual void writeData(const std::string& data);
- virtual bool supportsZLibCompression();
- virtual void addZLibCompression();
+ virtual bool supportsZLibCompression();
+ virtual void addZLibCompression();
- virtual bool supportsTLSEncryption();
- virtual void addTLSEncryption();
- virtual bool isTLSEncrypted();
- virtual Certificate::ref getPeerCertificate() const;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+ virtual bool supportsTLSEncryption();
+ virtual void addTLSEncryption();
+ virtual bool isTLSEncrypted();
+ virtual Certificate::ref getPeerCertificate() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
- virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
- virtual ByteArray getTLSFinishMessage() const;
+ virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ virtual ByteArray getTLSFinishMessage() const;
- virtual void setWhitespacePingEnabled(bool);
+ virtual void setWhitespacePingEnabled(bool);
- virtual void resetXMPPParser();
+ virtual void resetXMPPParser();
- private:
- void handleConnectionFinished(const boost::optional<Connection::Error>& error);
- void handleXMPPError();
- void handleTLSConnected();
- void handleTLSError(boost::shared_ptr<TLSError>);
- void handleStreamStartReceived(const ProtocolHeader&);
- void handleElementReceived(boost::shared_ptr<ToplevelElement>);
- void handleDataRead(const SafeByteArray& data);
- void handleDataWritten(const SafeByteArray& data);
+ private:
+ void handleConnectionFinished(const boost::optional<Connection::Error>& error);
+ void handleXMPPError();
+ void handleTLSConnected();
+ void handleTLSError(boost::shared_ptr<TLSError>);
+ void handleStreamStartReceived(const ProtocolHeader&);
+ void handleElementReceived(boost::shared_ptr<ToplevelElement>);
+ void handleDataRead(const SafeByteArray& data);
+ void handleDataWritten(const SafeByteArray& data);
- private:
- bool available;
- boost::shared_ptr<Connection> connection;
- TLSContextFactory* tlsContextFactory;
- TimerFactory* timerFactory;
- XMPPLayer* xmppLayer;
- ConnectionLayer* connectionLayer;
- CompressionLayer* compressionLayer;
- TLSLayer* tlsLayer;
- WhitespacePingLayer* whitespacePingLayer;
- StreamStack* streamStack;
- TLSOptions tlsOptions_;
- };
+ private:
+ bool available;
+ boost::shared_ptr<Connection> connection;
+ TLSContextFactory* tlsContextFactory;
+ TimerFactory* timerFactory;
+ XMPPLayer* xmppLayer;
+ ConnectionLayer* connectionLayer;
+ CompressionLayer* compressionLayer;
+ TLSLayer* tlsLayer;
+ WhitespacePingLayer* whitespacePingLayer;
+ StreamStack* streamStack;
+ TLSOptions tlsOptions_;
+ };
}
diff --git a/Swiften/Session/Session.cpp b/Swiften/Session/Session.cpp
index 95d7227..7f13cd7 100644
--- a/Swiften/Session/Session.cpp
+++ b/Swiften/Session/Session.cpp
@@ -14,92 +14,92 @@
namespace Swift {
Session::Session(
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory) :
- connection(connection),
- payloadParserFactories(payloadParserFactories),
- payloadSerializers(payloadSerializers),
- xmlParserFactory(xmlParserFactory),
- xmppLayer(NULL),
- connectionLayer(NULL),
- streamStack(0),
- finishing(false) {
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory) :
+ connection(connection),
+ payloadParserFactories(payloadParserFactories),
+ payloadSerializers(payloadSerializers),
+ xmlParserFactory(xmlParserFactory),
+ xmppLayer(NULL),
+ connectionLayer(NULL),
+ streamStack(0),
+ finishing(false) {
}
Session::~Session() {
- delete streamStack;
- delete connectionLayer;
- delete xmppLayer;
+ delete streamStack;
+ delete connectionLayer;
+ delete xmppLayer;
}
void Session::startSession() {
- initializeStreamStack();
- handleSessionStarted();
+ initializeStreamStack();
+ handleSessionStarted();
}
void Session::finishSession() {
- if (finishing) {
- return;
- }
- finishing = true;
- if (xmppLayer) {
- xmppLayer->writeFooter();
- }
- connection->disconnect();
+ if (finishing) {
+ return;
+ }
+ finishing = true;
+ if (xmppLayer) {
+ xmppLayer->writeFooter();
+ }
+ connection->disconnect();
}
void Session::finishSession(const SessionError& /*error*/) {
- if (finishing) {
- return;
- }
- finishing = true;
- if (xmppLayer) {
- xmppLayer->writeFooter();
- }
- connection->disconnect();
+ if (finishing) {
+ return;
+ }
+ finishing = true;
+ if (xmppLayer) {
+ xmppLayer->writeFooter();
+ }
+ connection->disconnect();
}
void Session::initializeStreamStack() {
- xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType);
- xmppLayer->onStreamStart.connect(
- boost::bind(&Session::handleStreamStart, this, _1));
- xmppLayer->onElement.connect(boost::bind(&Session::handleElement, this, _1));
- xmppLayer->onError.connect(
- boost::bind(&Session::finishSession, this, XMLError));
- xmppLayer->onDataRead.connect(boost::bind(boost::ref(onDataRead), _1));
- xmppLayer->onWriteData.connect(boost::bind(boost::ref(onDataWritten), _1));
- connection->onDisconnected.connect(
- boost::bind(&Session::handleDisconnected, this, _1));
- connectionLayer = new ConnectionLayer(connection);
- streamStack = new StreamStack(xmppLayer, connectionLayer);
+ xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType);
+ xmppLayer->onStreamStart.connect(
+ boost::bind(&Session::handleStreamStart, this, _1));
+ xmppLayer->onElement.connect(boost::bind(&Session::handleElement, this, _1));
+ xmppLayer->onError.connect(
+ boost::bind(&Session::finishSession, this, XMLError));
+ xmppLayer->onDataRead.connect(boost::bind(boost::ref(onDataRead), _1));
+ xmppLayer->onWriteData.connect(boost::bind(boost::ref(onDataWritten), _1));
+ connection->onDisconnected.connect(
+ boost::bind(&Session::handleDisconnected, this, _1));
+ connectionLayer = new ConnectionLayer(connection);
+ streamStack = new StreamStack(xmppLayer, connectionLayer);
}
void Session::sendElement(boost::shared_ptr<ToplevelElement> stanza) {
- xmppLayer->writeElement(stanza);
+ xmppLayer->writeElement(stanza);
}
void Session::handleDisconnected(const boost::optional<Connection::Error>& connectionError) {
- connection->onDisconnected.disconnect(
- boost::bind(&Session::handleDisconnected, this, _1));
- if (connectionError) {
- switch (*connectionError) {
- case Connection::ReadError:
- handleSessionFinished(ConnectionReadError);
- onSessionFinished(ConnectionReadError);
- break;
- case Connection::WriteError:
- handleSessionFinished(ConnectionWriteError);
- onSessionFinished(ConnectionWriteError);
- break;
- }
- }
- else {
- boost::optional<SessionError> error;
- handleSessionFinished(error);
- onSessionFinished(error);
- }
+ connection->onDisconnected.disconnect(
+ boost::bind(&Session::handleDisconnected, this, _1));
+ if (connectionError) {
+ switch (*connectionError) {
+ case Connection::ReadError:
+ handleSessionFinished(ConnectionReadError);
+ onSessionFinished(ConnectionReadError);
+ break;
+ case Connection::WriteError:
+ handleSessionFinished(ConnectionWriteError);
+ onSessionFinished(ConnectionWriteError);
+ break;
+ }
+ }
+ else {
+ boost::optional<SessionError> error;
+ handleSessionFinished(error);
+ onSessionFinished(error);
+ }
}
}
diff --git a/Swiften/Session/Session.h b/Swiften/Session/Session.h
index a6dae80..d01833d 100644
--- a/Swiften/Session/Session.h
+++ b/Swiften/Session/Session.h
@@ -19,97 +19,97 @@
#include <Swiften/StreamStack/ConnectionLayer.h>
namespace Swift {
- class ProtocolHeader;
- class StreamStack;
- class JID;
- class Element;
- class PayloadParserFactoryCollection;
- class PayloadSerializerCollection;
- class XMPPLayer;
- class XMLParserFactory;
-
- class SWIFTEN_API Session : public boost::enable_shared_from_this<Session> {
- public:
- enum SessionError {
- ConnectionReadError,
- ConnectionWriteError,
- XMLError,
- AuthenticationFailedError,
- NoSupportedAuthMechanismsError,
- UnexpectedElementError,
- ResourceBindError,
- SessionStartError,
- TLSError,
- ClientCertificateLoadError,
- ClientCertificateError
- };
-
- Session(
- boost::shared_ptr<Connection> connection,
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory);
- virtual ~Session();
-
- void startSession();
- void finishSession();
-
- void sendElement(boost::shared_ptr<ToplevelElement>);
-
- const JID& getLocalJID() const {
- return localJID;
- }
-
- const JID& getRemoteJID() const {
- return remoteJID;
- }
-
- boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElementReceived;
- boost::signal<void (const boost::optional<SessionError>&)> onSessionFinished;
- boost::signal<void (const SafeByteArray&)> onDataWritten;
- boost::signal<void (const SafeByteArray&)> onDataRead;
-
- protected:
- void setRemoteJID(const JID& j) {
- remoteJID = j;
- }
-
- void setLocalJID(const JID& j) {
- localJID = j;
- }
-
- void finishSession(const SessionError&);
-
- virtual void handleSessionStarted() {}
- virtual void handleSessionFinished(const boost::optional<SessionError>&) {}
- virtual void handleElement(boost::shared_ptr<ToplevelElement>) = 0;
- virtual void handleStreamStart(const ProtocolHeader&) = 0;
-
- void initializeStreamStack();
-
- XMPPLayer* getXMPPLayer() const {
- return xmppLayer;
- }
-
- StreamStack* getStreamStack() const {
- return streamStack;
- }
-
- void setFinished();
-
- private:
- void handleDisconnected(const boost::optional<Connection::Error>& error);
-
- private:
- JID localJID;
- JID remoteJID;
- boost::shared_ptr<Connection> connection;
- PayloadParserFactoryCollection* payloadParserFactories;
- PayloadSerializerCollection* payloadSerializers;
- XMLParserFactory* xmlParserFactory;
- XMPPLayer* xmppLayer;
- ConnectionLayer* connectionLayer;
- StreamStack* streamStack;
- bool finishing;
- };
+ class ProtocolHeader;
+ class StreamStack;
+ class JID;
+ class Element;
+ class PayloadParserFactoryCollection;
+ class PayloadSerializerCollection;
+ class XMPPLayer;
+ class XMLParserFactory;
+
+ class SWIFTEN_API Session : public boost::enable_shared_from_this<Session> {
+ public:
+ enum SessionError {
+ ConnectionReadError,
+ ConnectionWriteError,
+ XMLError,
+ AuthenticationFailedError,
+ NoSupportedAuthMechanismsError,
+ UnexpectedElementError,
+ ResourceBindError,
+ SessionStartError,
+ TLSError,
+ ClientCertificateLoadError,
+ ClientCertificateError
+ };
+
+ Session(
+ boost::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+ virtual ~Session();
+
+ void startSession();
+ void finishSession();
+
+ void sendElement(boost::shared_ptr<ToplevelElement>);
+
+ const JID& getLocalJID() const {
+ return localJID;
+ }
+
+ const JID& getRemoteJID() const {
+ return remoteJID;
+ }
+
+ boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElementReceived;
+ boost::signal<void (const boost::optional<SessionError>&)> onSessionFinished;
+ boost::signal<void (const SafeByteArray&)> onDataWritten;
+ boost::signal<void (const SafeByteArray&)> onDataRead;
+
+ protected:
+ void setRemoteJID(const JID& j) {
+ remoteJID = j;
+ }
+
+ void setLocalJID(const JID& j) {
+ localJID = j;
+ }
+
+ void finishSession(const SessionError&);
+
+ virtual void handleSessionStarted() {}
+ virtual void handleSessionFinished(const boost::optional<SessionError>&) {}
+ virtual void handleElement(boost::shared_ptr<ToplevelElement>) = 0;
+ virtual void handleStreamStart(const ProtocolHeader&) = 0;
+
+ void initializeStreamStack();
+
+ XMPPLayer* getXMPPLayer() const {
+ return xmppLayer;
+ }
+
+ StreamStack* getStreamStack() const {
+ return streamStack;
+ }
+
+ void setFinished();
+
+ private:
+ void handleDisconnected(const boost::optional<Connection::Error>& error);
+
+ private:
+ JID localJID;
+ JID remoteJID;
+ boost::shared_ptr<Connection> connection;
+ PayloadParserFactoryCollection* payloadParserFactories;
+ PayloadSerializerCollection* payloadSerializers;
+ XMLParserFactory* xmlParserFactory;
+ XMPPLayer* xmppLayer;
+ ConnectionLayer* connectionLayer;
+ StreamStack* streamStack;
+ bool finishing;
+ };
}
diff --git a/Swiften/Session/SessionStream.h b/Swiften/Session/SessionStream.h
index 9dcec71..18404c6 100644
--- a/Swiften/Session/SessionStream.h
+++ b/Swiften/Session/SessionStream.h
@@ -20,72 +20,72 @@
#include <Swiften/TLS/CertificateWithKey.h>
namespace Swift {
- class SWIFTEN_API SessionStream {
- public:
- class SWIFTEN_API SessionStreamError : public Swift::Error {
- public:
- enum Type {
- ParseError,
- TLSError,
- InvalidTLSCertificateError,
- ConnectionReadError,
- ConnectionWriteError
- };
-
- SessionStreamError(Type type) : type(type) {}
-
- Type type;
- };
-
- SessionStream(): certificate() {}
-
- virtual ~SessionStream();
-
- virtual void close() = 0;
- virtual bool isOpen() = 0;
-
- virtual void writeHeader(const ProtocolHeader& header) = 0;
- virtual void writeFooter() = 0;
- virtual void writeElement(boost::shared_ptr<ToplevelElement>) = 0;
- virtual void writeData(const std::string& data) = 0;
-
- virtual bool supportsZLibCompression() = 0;
- virtual void addZLibCompression() = 0;
-
- virtual bool supportsTLSEncryption() = 0;
- virtual void addTLSEncryption() = 0;
- virtual bool isTLSEncrypted() = 0;
- virtual void setWhitespacePingEnabled(bool enabled) = 0;
-
- virtual void resetXMPPParser() = 0;
-
- void setTLSCertificate(CertificateWithKey::ref cert) {
- certificate = cert;
- }
-
- virtual bool hasTLSCertificate() {
- return certificate && !certificate->isNull();
- }
-
- virtual Certificate::ref getPeerCertificate() const = 0;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
- virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const = 0;
-
- virtual ByteArray getTLSFinishMessage() const = 0;
-
- boost::signal<void (const ProtocolHeader&)> onStreamStartReceived;
- boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElementReceived;
- boost::signal<void (boost::shared_ptr<Error>)> onClosed;
- boost::signal<void ()> onTLSEncrypted;
- boost::signal<void (const SafeByteArray&)> onDataRead;
- boost::signal<void (const SafeByteArray&)> onDataWritten;
-
- protected:
- CertificateWithKey::ref getTLSCertificate() const {
- return certificate;
- }
-
- private:
- CertificateWithKey::ref certificate;
- };
+ class SWIFTEN_API SessionStream {
+ public:
+ class SWIFTEN_API SessionStreamError : public Swift::Error {
+ public:
+ enum Type {
+ ParseError,
+ TLSError,
+ InvalidTLSCertificateError,
+ ConnectionReadError,
+ ConnectionWriteError
+ };
+
+ SessionStreamError(Type type) : type(type) {}
+
+ Type type;
+ };
+
+ SessionStream(): certificate() {}
+
+ virtual ~SessionStream();
+
+ virtual void close() = 0;
+ virtual bool isOpen() = 0;
+
+ virtual void writeHeader(const ProtocolHeader& header) = 0;
+ virtual void writeFooter() = 0;
+ virtual void writeElement(boost::shared_ptr<ToplevelElement>) = 0;
+ virtual void writeData(const std::string& data) = 0;
+
+ virtual bool supportsZLibCompression() = 0;
+ virtual void addZLibCompression() = 0;
+
+ virtual bool supportsTLSEncryption() = 0;
+ virtual void addTLSEncryption() = 0;
+ virtual bool isTLSEncrypted() = 0;
+ virtual void setWhitespacePingEnabled(bool enabled) = 0;
+
+ virtual void resetXMPPParser() = 0;
+
+ void setTLSCertificate(CertificateWithKey::ref cert) {
+ certificate = cert;
+ }
+
+ virtual bool hasTLSCertificate() {
+ return certificate && !certificate->isNull();
+ }
+
+ virtual Certificate::ref getPeerCertificate() const = 0;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
+ virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const = 0;
+
+ virtual ByteArray getTLSFinishMessage() const = 0;
+
+ boost::signal<void (const ProtocolHeader&)> onStreamStartReceived;
+ boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElementReceived;
+ boost::signal<void (boost::shared_ptr<Error>)> onClosed;
+ boost::signal<void ()> onTLSEncrypted;
+ boost::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signal<void (const SafeByteArray&)> onDataWritten;
+
+ protected:
+ CertificateWithKey::ref getTLSCertificate() const {
+ return certificate;
+ }
+
+ private:
+ CertificateWithKey::ref certificate;
+ };
}
diff --git a/Swiften/Session/SessionTracer.cpp b/Swiften/Session/SessionTracer.cpp
index 61e8cc7..aa44b9c 100644
--- a/Swiften/Session/SessionTracer.cpp
+++ b/Swiften/Session/SessionTracer.cpp
@@ -13,17 +13,17 @@
namespace Swift {
SessionTracer::SessionTracer(boost::shared_ptr<Session> session) : session(session) {
- session->onDataRead.connect(boost::bind(&SessionTracer::printData, this, '<', _1));
- session->onDataWritten.connect(boost::bind(&SessionTracer::printData, this, '>', _1));
+ session->onDataRead.connect(boost::bind(&SessionTracer::printData, this, '<', _1));
+ session->onDataWritten.connect(boost::bind(&SessionTracer::printData, this, '>', _1));
}
void SessionTracer::printData(char direction, const SafeByteArray& data) {
- std::cerr << direction << direction << " " << session->getLocalJID() << " ";
- for (unsigned int i = 0; i < 72 - session->getLocalJID().toString().size() - session->getRemoteJID().toString().size(); ++i) {
- std::cerr << direction;
- }
- std::cerr << " " << session->getRemoteJID()<< " " << direction << direction << std::endl;
- std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
+ std::cerr << direction << direction << " " << session->getLocalJID() << " ";
+ for (unsigned int i = 0; i < 72 - session->getLocalJID().toString().size() - session->getRemoteJID().toString().size(); ++i) {
+ std::cerr << direction;
+ }
+ std::cerr << " " << session->getRemoteJID()<< " " << direction << direction << std::endl;
+ std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
}
}
diff --git a/Swiften/Session/SessionTracer.h b/Swiften/Session/SessionTracer.h
index adc72b0..3993a87 100644
--- a/Swiften/Session/SessionTracer.h
+++ b/Swiften/Session/SessionTracer.h
@@ -13,13 +13,13 @@
#include <Swiften/Session/Session.h>
namespace Swift {
- class SWIFTEN_API SessionTracer {
- public:
- SessionTracer(boost::shared_ptr<Session> session);
+ class SWIFTEN_API SessionTracer {
+ public:
+ SessionTracer(boost::shared_ptr<Session> session);
- private:
- void printData(char direction, const SafeByteArray& data);
+ private:
+ void printData(char direction, const SafeByteArray& data);
- boost::shared_ptr<Session> session;
- };
+ boost::shared_ptr<Session> session;
+ };
}
diff --git a/Swiften/StreamManagement/StanzaAckRequester.cpp b/Swiften/StreamManagement/StanzaAckRequester.cpp
index 07927ac..ceafe28 100644
--- a/Swiften/StreamManagement/StanzaAckRequester.cpp
+++ b/Swiften/StreamManagement/StanzaAckRequester.cpp
@@ -21,25 +21,25 @@ StanzaAckRequester::StanzaAckRequester() : lastHandledStanzasCount(0) {
}
void StanzaAckRequester::handleStanzaSent(boost::shared_ptr<Stanza> stanza) {
- unackedStanzas.push_back(stanza);
- if (boost::dynamic_pointer_cast<Message>(stanza)) {
- onRequestAck();
- }
+ unackedStanzas.push_back(stanza);
+ if (boost::dynamic_pointer_cast<Message>(stanza)) {
+ onRequestAck();
+ }
}
void StanzaAckRequester::handleAckReceived(unsigned int handledStanzasCount) {
- unsigned int i = lastHandledStanzasCount;
- while (i != handledStanzasCount) {
- if (unackedStanzas.empty()) {
- std::cerr << "Warning: Server acked more stanzas than we sent" << std::endl;
- break;
- }
- boost::shared_ptr<Stanza> ackedStanza = unackedStanzas.front();
- unackedStanzas.pop_front();
- onStanzaAcked(ackedStanza);
- i = (i == MAX_HANDLED_STANZA_COUNT ? 0 : i + 1);
- }
- lastHandledStanzasCount = handledStanzasCount;
+ unsigned int i = lastHandledStanzasCount;
+ while (i != handledStanzasCount) {
+ if (unackedStanzas.empty()) {
+ std::cerr << "Warning: Server acked more stanzas than we sent" << std::endl;
+ break;
+ }
+ boost::shared_ptr<Stanza> ackedStanza = unackedStanzas.front();
+ unackedStanzas.pop_front();
+ onStanzaAcked(ackedStanza);
+ i = (i == MAX_HANDLED_STANZA_COUNT ? 0 : i + 1);
+ }
+ lastHandledStanzasCount = handledStanzasCount;
}
}
diff --git a/Swiften/StreamManagement/StanzaAckRequester.h b/Swiften/StreamManagement/StanzaAckRequester.h
index 6b04238..4d913bb 100644
--- a/Swiften/StreamManagement/StanzaAckRequester.h
+++ b/Swiften/StreamManagement/StanzaAckRequester.h
@@ -15,21 +15,21 @@
#include <Swiften/Elements/Stanza.h>
namespace Swift {
- class SWIFTEN_API StanzaAckRequester {
- public:
- StanzaAckRequester();
-
- void handleStanzaSent(boost::shared_ptr<Stanza> stanza);
- void handleAckReceived(unsigned int handledStanzasCount);
-
- public:
- boost::signal<void ()> onRequestAck;
- boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
-
- private:
- friend class StanzaAckRequesterTest;
- unsigned int lastHandledStanzasCount;
- std::deque<boost::shared_ptr<Stanza> > unackedStanzas;
- };
+ class SWIFTEN_API StanzaAckRequester {
+ public:
+ StanzaAckRequester();
+
+ void handleStanzaSent(boost::shared_ptr<Stanza> stanza);
+ void handleAckReceived(unsigned int handledStanzasCount);
+
+ public:
+ boost::signal<void ()> onRequestAck;
+ boost::signal<void (boost::shared_ptr<Stanza>)> onStanzaAcked;
+
+ private:
+ friend class StanzaAckRequesterTest;
+ unsigned int lastHandledStanzasCount;
+ std::deque<boost::shared_ptr<Stanza> > unackedStanzas;
+ };
}
diff --git a/Swiften/StreamManagement/StanzaAckResponder.cpp b/Swiften/StreamManagement/StanzaAckResponder.cpp
index ee6f077..b6171d0 100644
--- a/Swiften/StreamManagement/StanzaAckResponder.cpp
+++ b/Swiften/StreamManagement/StanzaAckResponder.cpp
@@ -16,11 +16,11 @@ StanzaAckResponder::StanzaAckResponder() : handledStanzasCount(0) {
}
void StanzaAckResponder::handleStanzaReceived() {
- handledStanzasCount = (handledStanzasCount == MAX_HANDLED_STANZA_COUNT ? 0 : handledStanzasCount + 1);
+ handledStanzasCount = (handledStanzasCount == MAX_HANDLED_STANZA_COUNT ? 0 : handledStanzasCount + 1);
}
void StanzaAckResponder::handleAckRequestReceived() {
- onAck(handledStanzasCount);
+ onAck(handledStanzasCount);
}
}
diff --git a/Swiften/StreamManagement/StanzaAckResponder.h b/Swiften/StreamManagement/StanzaAckResponder.h
index a2e1f42..16c8825 100644
--- a/Swiften/StreamManagement/StanzaAckResponder.h
+++ b/Swiften/StreamManagement/StanzaAckResponder.h
@@ -13,19 +13,19 @@
#include <Swiften/Elements/Stanza.h>
namespace Swift {
- class SWIFTEN_API StanzaAckResponder {
- public:
- StanzaAckResponder();
+ class SWIFTEN_API StanzaAckResponder {
+ public:
+ StanzaAckResponder();
- void handleStanzaReceived();
- void handleAckRequestReceived();
+ void handleStanzaReceived();
+ void handleAckRequestReceived();
- public:
- boost::signal<void (unsigned int /* handledStanzaCount */)> onAck;
+ public:
+ boost::signal<void (unsigned int /* handledStanzaCount */)> onAck;
- private:
- friend class StanzaAckResponderTest;
- unsigned int handledStanzasCount;
- };
+ private:
+ friend class StanzaAckResponderTest;
+ unsigned int handledStanzasCount;
+ };
}
diff --git a/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp b/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp
index 99713a9..55e6012 100644
--- a/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp
+++ b/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp
@@ -20,145 +20,145 @@ using namespace Swift;
namespace Swift {
class StanzaAckRequesterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StanzaAckRequesterTest);
- CPPUNIT_TEST(testHandleStanzaSent_MessageRequestsAck);
- CPPUNIT_TEST(testHandleStanzaSent_IQDoesNotRequestAck);
- CPPUNIT_TEST(testHandleStanzaSent_PresenceDoesNotRequestAck);
- CPPUNIT_TEST(testHandleAckReceived_AcksStanza);
- CPPUNIT_TEST(testHandleAckReceived_AcksMultipleMessages);
- CPPUNIT_TEST(testHandleAckReceived_AcksMultipleStanzas);
- CPPUNIT_TEST(testHandleAckReceived_MultipleAcks);
- CPPUNIT_TEST(testHandleAckReceived_WrapAround);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- acksRequested = 0;
- }
-
- void testHandleStanzaSent_MessageRequestsAck() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createMessage("m1"));
-
- CPPUNIT_ASSERT_EQUAL(1, acksRequested);
- }
-
- void testHandleStanzaSent_IQDoesNotRequestAck() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createIQ("iq1"));
-
- CPPUNIT_ASSERT_EQUAL(0, acksRequested);
- }
-
- void testHandleStanzaSent_PresenceDoesNotRequestAck() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createPresence("p1"));
-
- CPPUNIT_ASSERT_EQUAL(0, acksRequested);
- }
-
- void testHandleAckReceived_AcksStanza() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createMessage("m1"));
-
- testling->handleAckReceived(1);
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(ackedStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
- }
-
- void testHandleAckReceived_AcksMultipleMessages() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createMessage("m1"));
- testling->handleStanzaSent(createMessage("m2"));
-
- testling->handleAckReceived(2);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(ackedStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
- }
-
- void testHandleAckReceived_AcksMultipleStanzas() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createIQ("iq1"));
- testling->handleStanzaSent(createPresence("p1"));
- testling->handleStanzaSent(createMessage("m1"));
-
- testling->handleAckReceived(3);
-
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(ackedStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("iq1"), ackedStanzas[0]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("p1"), ackedStanzas[1]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[2]->getID());
- }
-
- void testHandleAckReceived_MultipleAcks() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->handleStanzaSent(createMessage("m1"));
- testling->handleAckReceived(1);
-
- testling->handleStanzaSent(createMessage("m2"));
- testling->handleStanzaSent(createMessage("m3"));
- testling->handleAckReceived(3);
-
- CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(ackedStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("m3"), ackedStanzas[2]->getID());
- }
-
- // Handle stanza ack count wrapping, as per the XEP
- void testHandleAckReceived_WrapAround() {
- boost::shared_ptr<StanzaAckRequester> testling(createRequester());
- testling->lastHandledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1);
- testling->handleStanzaSent(createMessage("m1"));
- testling->handleStanzaSent(createMessage("m2"));
-
- testling->handleAckReceived(1);
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(ackedStanzas.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
- CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
- }
-
- private:
- Message::ref createMessage(const std::string& id) {
- Message::ref result(new Message());
- result->setID(id);
- return result;
- }
-
- IQ::ref createIQ(const std::string& id) {
- IQ::ref result(new IQ());
- result->setID(id);
- return result;
- }
-
- Presence::ref createPresence(const std::string& id) {
- Presence::ref result(new Presence());
- result->setID(id);
- return result;
- }
-
- StanzaAckRequester* createRequester() {
- StanzaAckRequester* requester = new StanzaAckRequester();
- requester->onRequestAck.connect(boost::bind(&StanzaAckRequesterTest::handleRequestAck, this));
- requester->onStanzaAcked.connect(boost::bind(&StanzaAckRequesterTest::handleStanzaAcked, this, _1));
- return requester;
- }
-
- void handleRequestAck() {
- acksRequested++;
- }
-
- void handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
- ackedStanzas.push_back(stanza);
- }
-
- private:
- int acksRequested;
- std::vector< boost::shared_ptr<Stanza> > ackedStanzas;
+ CPPUNIT_TEST_SUITE(StanzaAckRequesterTest);
+ CPPUNIT_TEST(testHandleStanzaSent_MessageRequestsAck);
+ CPPUNIT_TEST(testHandleStanzaSent_IQDoesNotRequestAck);
+ CPPUNIT_TEST(testHandleStanzaSent_PresenceDoesNotRequestAck);
+ CPPUNIT_TEST(testHandleAckReceived_AcksStanza);
+ CPPUNIT_TEST(testHandleAckReceived_AcksMultipleMessages);
+ CPPUNIT_TEST(testHandleAckReceived_AcksMultipleStanzas);
+ CPPUNIT_TEST(testHandleAckReceived_MultipleAcks);
+ CPPUNIT_TEST(testHandleAckReceived_WrapAround);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ acksRequested = 0;
+ }
+
+ void testHandleStanzaSent_MessageRequestsAck() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createMessage("m1"));
+
+ CPPUNIT_ASSERT_EQUAL(1, acksRequested);
+ }
+
+ void testHandleStanzaSent_IQDoesNotRequestAck() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createIQ("iq1"));
+
+ CPPUNIT_ASSERT_EQUAL(0, acksRequested);
+ }
+
+ void testHandleStanzaSent_PresenceDoesNotRequestAck() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createPresence("p1"));
+
+ CPPUNIT_ASSERT_EQUAL(0, acksRequested);
+ }
+
+ void testHandleAckReceived_AcksStanza() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createMessage("m1"));
+
+ testling->handleAckReceived(1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(ackedStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
+ }
+
+ void testHandleAckReceived_AcksMultipleMessages() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createMessage("m1"));
+ testling->handleStanzaSent(createMessage("m2"));
+
+ testling->handleAckReceived(2);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(ackedStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
+ }
+
+ void testHandleAckReceived_AcksMultipleStanzas() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createIQ("iq1"));
+ testling->handleStanzaSent(createPresence("p1"));
+ testling->handleStanzaSent(createMessage("m1"));
+
+ testling->handleAckReceived(3);
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(ackedStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("iq1"), ackedStanzas[0]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("p1"), ackedStanzas[1]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[2]->getID());
+ }
+
+ void testHandleAckReceived_MultipleAcks() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createMessage("m1"));
+ testling->handleAckReceived(1);
+
+ testling->handleStanzaSent(createMessage("m2"));
+ testling->handleStanzaSent(createMessage("m3"));
+ testling->handleAckReceived(3);
+
+ CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(ackedStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("m3"), ackedStanzas[2]->getID());
+ }
+
+ // Handle stanza ack count wrapping, as per the XEP
+ void testHandleAckReceived_WrapAround() {
+ boost::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->lastHandledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1);
+ testling->handleStanzaSent(createMessage("m1"));
+ testling->handleStanzaSent(createMessage("m2"));
+
+ testling->handleAckReceived(1);
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(ackedStanzas.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID());
+ CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID());
+ }
+
+ private:
+ Message::ref createMessage(const std::string& id) {
+ Message::ref result(new Message());
+ result->setID(id);
+ return result;
+ }
+
+ IQ::ref createIQ(const std::string& id) {
+ IQ::ref result(new IQ());
+ result->setID(id);
+ return result;
+ }
+
+ Presence::ref createPresence(const std::string& id) {
+ Presence::ref result(new Presence());
+ result->setID(id);
+ return result;
+ }
+
+ StanzaAckRequester* createRequester() {
+ StanzaAckRequester* requester = new StanzaAckRequester();
+ requester->onRequestAck.connect(boost::bind(&StanzaAckRequesterTest::handleRequestAck, this));
+ requester->onStanzaAcked.connect(boost::bind(&StanzaAckRequesterTest::handleStanzaAcked, this, _1));
+ return requester;
+ }
+
+ void handleRequestAck() {
+ acksRequested++;
+ }
+
+ void handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
+ ackedStanzas.push_back(stanza);
+ }
+
+ private:
+ int acksRequested;
+ std::vector< boost::shared_ptr<Stanza> > ackedStanzas;
};
}
diff --git a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
index 11d1c57..70cd8fc 100644
--- a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
+++ b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
@@ -18,80 +18,80 @@ using namespace Swift;
namespace Swift {
class StanzaAckResponderTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StanzaAckResponderTest);
- CPPUNIT_TEST(testHandleAckRequestReceived_AcksStanza);
- CPPUNIT_TEST(testHandleAckRequestReceived_AcksMultipleStanzas);
- CPPUNIT_TEST(testHandleAckRequestReceived_MultipleAcks);
- CPPUNIT_TEST(testHandleAckRequestReceived_WrapAround);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testHandleAckRequestReceived_AcksStanza() {
- boost::shared_ptr<StanzaAckResponder> testling(createResponder());
- testling->handleStanzaReceived();
-
- testling->handleAckRequestReceived();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
- CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
- }
-
- void testHandleAckRequestReceived_AcksMultipleStanzas() {
- boost::shared_ptr<StanzaAckResponder> testling(createResponder());
- testling->handleStanzaReceived();
- testling->handleStanzaReceived();
-
- testling->handleAckRequestReceived();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
- CPPUNIT_ASSERT_EQUAL(2U, acks[0]);
- }
-
- void testHandleAckRequestReceived_MultipleAcks() {
- boost::shared_ptr<StanzaAckResponder> testling(createResponder());
- testling->handleStanzaReceived();
- testling->handleAckRequestReceived();
-
- testling->handleStanzaReceived();
- testling->handleAckRequestReceived();
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(acks.size()));
- CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
- CPPUNIT_ASSERT_EQUAL(2U, acks[1]);
- }
-
- // Handle stanza ack count wrapping, as per the XEP
- void testHandleAckRequestReceived_WrapAround() {
- boost::shared_ptr<StanzaAckResponder> testling(createResponder());
- testling->handledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1);
- testling->handleStanzaReceived();
- testling->handleStanzaReceived();
-
- testling->handleAckRequestReceived();
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
- CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
- }
-
- private:
- Message::ref createMessage(const std::string& id) {
- Message::ref result(new Message());
- result->setID(id);
- return result;
- }
-
- StanzaAckResponder* createResponder() {
- StanzaAckResponder* responder = new StanzaAckResponder();
- responder->onAck.connect(boost::bind(&StanzaAckResponderTest::handleAck, this, _1));
- return responder;
- }
-
- void handleAck(unsigned int h) {
- acks.push_back(h);
- }
-
- private:
- std::vector<unsigned int> acks;
+ CPPUNIT_TEST_SUITE(StanzaAckResponderTest);
+ CPPUNIT_TEST(testHandleAckRequestReceived_AcksStanza);
+ CPPUNIT_TEST(testHandleAckRequestReceived_AcksMultipleStanzas);
+ CPPUNIT_TEST(testHandleAckRequestReceived_MultipleAcks);
+ CPPUNIT_TEST(testHandleAckRequestReceived_WrapAround);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testHandleAckRequestReceived_AcksStanza() {
+ boost::shared_ptr<StanzaAckResponder> testling(createResponder());
+ testling->handleStanzaReceived();
+
+ testling->handleAckRequestReceived();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
+ CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
+ }
+
+ void testHandleAckRequestReceived_AcksMultipleStanzas() {
+ boost::shared_ptr<StanzaAckResponder> testling(createResponder());
+ testling->handleStanzaReceived();
+ testling->handleStanzaReceived();
+
+ testling->handleAckRequestReceived();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
+ CPPUNIT_ASSERT_EQUAL(2U, acks[0]);
+ }
+
+ void testHandleAckRequestReceived_MultipleAcks() {
+ boost::shared_ptr<StanzaAckResponder> testling(createResponder());
+ testling->handleStanzaReceived();
+ testling->handleAckRequestReceived();
+
+ testling->handleStanzaReceived();
+ testling->handleAckRequestReceived();
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(acks.size()));
+ CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
+ CPPUNIT_ASSERT_EQUAL(2U, acks[1]);
+ }
+
+ // Handle stanza ack count wrapping, as per the XEP
+ void testHandleAckRequestReceived_WrapAround() {
+ boost::shared_ptr<StanzaAckResponder> testling(createResponder());
+ testling->handledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1);
+ testling->handleStanzaReceived();
+ testling->handleStanzaReceived();
+
+ testling->handleAckRequestReceived();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size()));
+ CPPUNIT_ASSERT_EQUAL(1U, acks[0]);
+ }
+
+ private:
+ Message::ref createMessage(const std::string& id) {
+ Message::ref result(new Message());
+ result->setID(id);
+ return result;
+ }
+
+ StanzaAckResponder* createResponder() {
+ StanzaAckResponder* responder = new StanzaAckResponder();
+ responder->onAck.connect(boost::bind(&StanzaAckResponderTest::handleAck, this, _1));
+ return responder;
+ }
+
+ void handleAck(unsigned int h) {
+ acks.push_back(h);
+ }
+
+ private:
+ std::vector<unsigned int> acks;
};
}
diff --git a/Swiften/StreamStack/CompressionLayer.h b/Swiften/StreamStack/CompressionLayer.h
index 1e694c9..32fad37 100644
--- a/Swiften/StreamStack/CompressionLayer.h
+++ b/Swiften/StreamStack/CompressionLayer.h
@@ -17,36 +17,36 @@
#include <Swiften/StreamStack/StreamLayer.h>
namespace Swift {
- class ZLibCompressor;
- class ZLibDecompressor;
-
- class SWIFTEN_API CompressionLayer : public StreamLayer, boost::noncopyable {
- public:
- CompressionLayer() {}
-
- virtual void writeData(const SafeByteArray& data) {
- try {
- writeDataToChildLayer(compressor_.process(data));
- }
- catch (const ZLibException&) {
- onError();
- }
- }
-
- virtual void handleDataRead(const SafeByteArray& data) {
- try {
- writeDataToParentLayer(decompressor_.process(data));
- }
- catch (const ZLibException&) {
- onError();
- }
- }
-
- public:
- boost::signal<void ()> onError;
-
- private:
- ZLibCompressor compressor_;
- ZLibDecompressor decompressor_;
- };
+ class ZLibCompressor;
+ class ZLibDecompressor;
+
+ class SWIFTEN_API CompressionLayer : public StreamLayer, boost::noncopyable {
+ public:
+ CompressionLayer() {}
+
+ virtual void writeData(const SafeByteArray& data) {
+ try {
+ writeDataToChildLayer(compressor_.process(data));
+ }
+ catch (const ZLibException&) {
+ onError();
+ }
+ }
+
+ virtual void handleDataRead(const SafeByteArray& data) {
+ try {
+ writeDataToParentLayer(decompressor_.process(data));
+ }
+ catch (const ZLibException&) {
+ onError();
+ }
+ }
+
+ public:
+ boost::signal<void ()> onError;
+
+ private:
+ ZLibCompressor compressor_;
+ ZLibDecompressor decompressor_;
+ };
}
diff --git a/Swiften/StreamStack/ConnectionLayer.cpp b/Swiften/StreamStack/ConnectionLayer.cpp
index 5bf07d0..09b6f87 100644
--- a/Swiften/StreamStack/ConnectionLayer.cpp
+++ b/Swiften/StreamStack/ConnectionLayer.cpp
@@ -11,15 +11,15 @@
namespace Swift {
ConnectionLayer::ConnectionLayer(boost::shared_ptr<Connection> connection) : connection(connection) {
- connection->onDataRead.connect(boost::bind(&ConnectionLayer::handleDataRead, this, _1));
+ connection->onDataRead.connect(boost::bind(&ConnectionLayer::handleDataRead, this, _1));
}
ConnectionLayer::~ConnectionLayer() {
- connection->onDataRead.disconnect(boost::bind(&ConnectionLayer::handleDataRead, this, _1));
+ connection->onDataRead.disconnect(boost::bind(&ConnectionLayer::handleDataRead, this, _1));
}
void ConnectionLayer::handleDataRead(boost::shared_ptr<SafeByteArray> data) {
- writeDataToParentLayer(*data);
+ writeDataToParentLayer(*data);
}
diff --git a/Swiften/StreamStack/ConnectionLayer.h b/Swiften/StreamStack/ConnectionLayer.h
index e89e24c..c2d0fde 100644
--- a/Swiften/StreamStack/ConnectionLayer.h
+++ b/Swiften/StreamStack/ConnectionLayer.h
@@ -13,19 +13,19 @@
#include <Swiften/StreamStack/LowLayer.h>
namespace Swift {
- class SWIFTEN_API ConnectionLayer : public LowLayer {
- public:
- ConnectionLayer(boost::shared_ptr<Connection> connection);
- virtual ~ConnectionLayer();
+ class SWIFTEN_API ConnectionLayer : public LowLayer {
+ public:
+ ConnectionLayer(boost::shared_ptr<Connection> connection);
+ virtual ~ConnectionLayer();
- void writeData(const SafeByteArray& data) {
- connection->write(data);
- }
+ void writeData(const SafeByteArray& data) {
+ connection->write(data);
+ }
- private:
- void handleDataRead(boost::shared_ptr<SafeByteArray>);
+ private:
+ void handleDataRead(boost::shared_ptr<SafeByteArray>);
- private:
- boost::shared_ptr<Connection> connection;
- };
+ private:
+ boost::shared_ptr<Connection> connection;
+ };
}
diff --git a/Swiften/StreamStack/DummyStreamLayer.h b/Swiften/StreamStack/DummyStreamLayer.h
index b06c8aa..5a93b7f 100644
--- a/Swiften/StreamStack/DummyStreamLayer.h
+++ b/Swiften/StreamStack/DummyStreamLayer.h
@@ -11,20 +11,20 @@
#include <Swiften/StreamStack/LowLayer.h>
namespace Swift {
- /**
- * The \ref DummyStreamLayer can be used to use a \ref LowLayer on its own, without a functioning parent layer.
- * The \ref DummyStreamLayer will serve as the parent layer to the \ref LowLayer and is called when the \ref LowLayer
- * wants to write data to its parent layer.
- */
- class SWIFTEN_API DummyStreamLayer : public HighLayer {
- public:
- DummyStreamLayer(LowLayer* lowLayer) {
- setChildLayer(lowLayer);
- lowLayer->setParentLayer(this);
- }
+ /**
+ * The \ref DummyStreamLayer can be used to use a \ref LowLayer on its own, without a functioning parent layer.
+ * The \ref DummyStreamLayer will serve as the parent layer to the \ref LowLayer and is called when the \ref LowLayer
+ * wants to write data to its parent layer.
+ */
+ class SWIFTEN_API DummyStreamLayer : public HighLayer {
+ public:
+ DummyStreamLayer(LowLayer* lowLayer) {
+ setChildLayer(lowLayer);
+ lowLayer->setParentLayer(this);
+ }
- virtual void handleDataRead(const SafeByteArray& /* data */) {
+ virtual void handleDataRead(const SafeByteArray& /* data */) {
- }
- };
+ }
+ };
}
diff --git a/Swiften/StreamStack/HighLayer.cpp b/Swiften/StreamStack/HighLayer.cpp
index b3e8ae8..fcfdacf 100644
--- a/Swiften/StreamStack/HighLayer.cpp
+++ b/Swiften/StreamStack/HighLayer.cpp
@@ -19,10 +19,10 @@ HighLayer::~HighLayer() {
}
void HighLayer::writeDataToChildLayer(const SafeByteArray& data) {
- //assert(childLayer);
- if (childLayer) {
- childLayer->writeData(data);
- }
+ //assert(childLayer);
+ if (childLayer) {
+ childLayer->writeData(data);
+ }
}
}
diff --git a/Swiften/StreamStack/HighLayer.h b/Swiften/StreamStack/HighLayer.h
index 178de70..a877d8d 100644
--- a/Swiften/StreamStack/HighLayer.h
+++ b/Swiften/StreamStack/HighLayer.h
@@ -10,29 +10,29 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class LowLayer;
+ class LowLayer;
- class SWIFTEN_API HighLayer {
- friend class StreamStack;
+ class SWIFTEN_API HighLayer {
+ friend class StreamStack;
- public:
- HighLayer();
- virtual ~HighLayer();
+ public:
+ HighLayer();
+ virtual ~HighLayer();
- virtual void handleDataRead(const SafeByteArray& data) = 0;
-
- protected:
- LowLayer* getChildLayer() {
- return childLayer;
- }
+ virtual void handleDataRead(const SafeByteArray& data) = 0;
- void setChildLayer(LowLayer* childLayer) {
- this->childLayer = childLayer;
- }
+ protected:
+ LowLayer* getChildLayer() {
+ return childLayer;
+ }
- void writeDataToChildLayer(const SafeByteArray& data);
+ void setChildLayer(LowLayer* childLayer) {
+ this->childLayer = childLayer;
+ }
- private:
- LowLayer* childLayer;
- };
+ void writeDataToChildLayer(const SafeByteArray& data);
+
+ private:
+ LowLayer* childLayer;
+ };
}
diff --git a/Swiften/StreamStack/LowLayer.cpp b/Swiften/StreamStack/LowLayer.cpp
index 4829bd1..07b0f43 100644
--- a/Swiften/StreamStack/LowLayer.cpp
+++ b/Swiften/StreamStack/LowLayer.cpp
@@ -19,8 +19,8 @@ LowLayer::~LowLayer() {
}
void LowLayer::writeDataToParentLayer(const SafeByteArray& data) {
- assert(parentLayer);
- parentLayer->handleDataRead(data);
+ assert(parentLayer);
+ parentLayer->handleDataRead(data);
}
}
diff --git a/Swiften/StreamStack/LowLayer.h b/Swiften/StreamStack/LowLayer.h
index b1bddec..83cc190 100644
--- a/Swiften/StreamStack/LowLayer.h
+++ b/Swiften/StreamStack/LowLayer.h
@@ -10,30 +10,30 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class HighLayer;
+ class HighLayer;
- class SWIFTEN_API LowLayer {
- friend class StreamStack;
- friend class DummyStreamLayer;
+ class SWIFTEN_API LowLayer {
+ friend class StreamStack;
+ friend class DummyStreamLayer;
- public:
- LowLayer();
- virtual ~LowLayer();
+ public:
+ LowLayer();
+ virtual ~LowLayer();
- virtual void writeData(const SafeByteArray& data) = 0;
-
- protected:
- HighLayer* getParentLayer() {
- return parentLayer;
- }
+ virtual void writeData(const SafeByteArray& data) = 0;
- void setParentLayer(HighLayer* parentLayer) {
- this->parentLayer = parentLayer;
- }
+ protected:
+ HighLayer* getParentLayer() {
+ return parentLayer;
+ }
- void writeDataToParentLayer(const SafeByteArray& data);
+ void setParentLayer(HighLayer* parentLayer) {
+ this->parentLayer = parentLayer;
+ }
- private:
- HighLayer* parentLayer;
- };
+ void writeDataToParentLayer(const SafeByteArray& data);
+
+ private:
+ HighLayer* parentLayer;
+ };
}
diff --git a/Swiften/StreamStack/StreamLayer.h b/Swiften/StreamStack/StreamLayer.h
index 2d3ea50..14a1ea6 100644
--- a/Swiften/StreamStack/StreamLayer.h
+++ b/Swiften/StreamStack/StreamLayer.h
@@ -11,8 +11,8 @@
#include <Swiften/StreamStack/LowLayer.h>
namespace Swift {
- class SWIFTEN_API StreamLayer : public LowLayer, public HighLayer {
- public:
- StreamLayer() {}
- };
+ class SWIFTEN_API StreamLayer : public LowLayer, public HighLayer {
+ public:
+ StreamLayer() {}
+ };
}
diff --git a/Swiften/StreamStack/StreamStack.cpp b/Swiften/StreamStack/StreamStack.cpp
index 99e2bcd..0bcd1b3 100644
--- a/Swiften/StreamStack/StreamStack.cpp
+++ b/Swiften/StreamStack/StreamStack.cpp
@@ -16,23 +16,23 @@
namespace Swift {
StreamStack::StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer) : xmppLayer_(xmppLayer), physicalLayer_(physicalLayer) {
- physicalLayer_->setParentLayer(xmppLayer_);
- xmppLayer_->setChildLayer(physicalLayer_);
+ physicalLayer_->setParentLayer(xmppLayer_);
+ xmppLayer_->setChildLayer(physicalLayer_);
}
StreamStack::~StreamStack() {
}
void StreamStack::addLayer(StreamLayer* newLayer) {
- LowLayer* lowLayer = layers_.empty() ? physicalLayer_ : *layers_.rbegin();
+ LowLayer* lowLayer = layers_.empty() ? physicalLayer_ : *layers_.rbegin();
- xmppLayer_->setChildLayer(newLayer);
- newLayer->setParentLayer(xmppLayer_);
-
- lowLayer->setParentLayer(newLayer);
- newLayer->setChildLayer(lowLayer);
+ xmppLayer_->setChildLayer(newLayer);
+ newLayer->setParentLayer(xmppLayer_);
- layers_.push_back(newLayer);
+ lowLayer->setParentLayer(newLayer);
+ newLayer->setChildLayer(lowLayer);
+
+ layers_.push_back(newLayer);
}
}
diff --git a/Swiften/StreamStack/StreamStack.h b/Swiften/StreamStack/StreamStack.h
index 8bf91b0..2a0b1f1 100644
--- a/Swiften/StreamStack/StreamStack.h
+++ b/Swiften/StreamStack/StreamStack.h
@@ -15,34 +15,34 @@
#include <Swiften/Elements/Stanza.h>
namespace Swift {
- class XMPPLayer;
- class LowLayer;
- class StreamLayer;
-
- class SWIFTEN_API StreamStack {
- public:
- StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer);
- ~StreamStack();
-
- void addLayer(StreamLayer*);
-
- XMPPLayer* getXMPPLayer() const {
- return xmppLayer_;
- }
-
- template<typename T> T* getLayer() {
- for (size_t i = 0; i < layers_.size(); ++i) {
- T* layer = dynamic_cast<T*>(layers_[i]);
- if (layer) {
- return layer;
- }
- }
- return NULL;
- }
-
- private:
- XMPPLayer* xmppLayer_;
- LowLayer* physicalLayer_;
- std::vector<StreamLayer*> layers_;
- };
+ class XMPPLayer;
+ class LowLayer;
+ class StreamLayer;
+
+ class SWIFTEN_API StreamStack {
+ public:
+ StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer);
+ ~StreamStack();
+
+ void addLayer(StreamLayer*);
+
+ XMPPLayer* getXMPPLayer() const {
+ return xmppLayer_;
+ }
+
+ template<typename T> T* getLayer() {
+ for (size_t i = 0; i < layers_.size(); ++i) {
+ T* layer = dynamic_cast<T*>(layers_[i]);
+ if (layer) {
+ return layer;
+ }
+ }
+ return NULL;
+ }
+
+ private:
+ XMPPLayer* xmppLayer_;
+ LowLayer* physicalLayer_;
+ std::vector<StreamLayer*> layers_;
+ };
}
diff --git a/Swiften/StreamStack/TLSLayer.cpp b/Swiften/StreamStack/TLSLayer.cpp
index bb0fe0f..3ab885a 100644
--- a/Swiften/StreamStack/TLSLayer.cpp
+++ b/Swiften/StreamStack/TLSLayer.cpp
@@ -14,43 +14,43 @@
namespace Swift {
TLSLayer::TLSLayer(TLSContextFactory* factory, const TLSOptions& tlsOptions) {
- context = factory->createTLSContext(tlsOptions);
- context->onDataForNetwork.connect(boost::bind(&TLSLayer::writeDataToChildLayer, this, _1));
- context->onDataForApplication.connect(boost::bind(&TLSLayer::writeDataToParentLayer, this, _1));
- context->onConnected.connect(onConnected);
- context->onError.connect(onError);
+ context = factory->createTLSContext(tlsOptions);
+ context->onDataForNetwork.connect(boost::bind(&TLSLayer::writeDataToChildLayer, this, _1));
+ context->onDataForApplication.connect(boost::bind(&TLSLayer::writeDataToParentLayer, this, _1));
+ context->onConnected.connect(onConnected);
+ context->onError.connect(onError);
}
TLSLayer::~TLSLayer() {
- delete context;
+ delete context;
}
void TLSLayer::connect() {
- context->connect();
+ context->connect();
}
void TLSLayer::writeData(const SafeByteArray& data) {
- context->handleDataFromApplication(data);
+ context->handleDataFromApplication(data);
}
void TLSLayer::handleDataRead(const SafeByteArray& data) {
- context->handleDataFromNetwork(data);
+ context->handleDataFromNetwork(data);
}
bool TLSLayer::setClientCertificate(CertificateWithKey::ref certificate) {
- return context->setClientCertificate(certificate);
+ return context->setClientCertificate(certificate);
}
Certificate::ref TLSLayer::getPeerCertificate() const {
- return context->getPeerCertificate();
+ return context->getPeerCertificate();
}
std::vector<Certificate::ref> TLSLayer::getPeerCertificateChain() const {
- return context->getPeerCertificateChain();
+ return context->getPeerCertificateChain();
}
boost::shared_ptr<CertificateVerificationError> TLSLayer::getPeerCertificateVerificationError() const {
- return context->getPeerCertificateVerificationError();
+ return context->getPeerCertificateVerificationError();
}
}
diff --git a/Swiften/StreamStack/TLSLayer.h b/Swiften/StreamStack/TLSLayer.h
index 0ab35d5..b9072f3 100644
--- a/Swiften/StreamStack/TLSLayer.h
+++ b/Swiften/StreamStack/TLSLayer.h
@@ -17,33 +17,33 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class TLSContext;
- class TLSContextFactory;
+ class TLSContext;
+ class TLSContextFactory;
- class SWIFTEN_API TLSLayer : public StreamLayer {
- public:
- TLSLayer(TLSContextFactory*, const TLSOptions&);
- virtual ~TLSLayer();
+ class SWIFTEN_API TLSLayer : public StreamLayer {
+ public:
+ TLSLayer(TLSContextFactory*, const TLSOptions&);
+ virtual ~TLSLayer();
- void connect();
- bool setClientCertificate(CertificateWithKey::ref cert);
+ void connect();
+ bool setClientCertificate(CertificateWithKey::ref cert);
- Certificate::ref getPeerCertificate() const;
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ Certificate::ref getPeerCertificate() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const;
+ boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
- void writeData(const SafeByteArray& data);
- void handleDataRead(const SafeByteArray& data);
+ void writeData(const SafeByteArray& data);
+ void handleDataRead(const SafeByteArray& data);
- TLSContext* getContext() const {
- return context;
- }
+ TLSContext* getContext() const {
+ return context;
+ }
- public:
- boost::signal<void (boost::shared_ptr<TLSError>)> onError;
- boost::signal<void ()> onConnected;
+ public:
+ boost::signal<void (boost::shared_ptr<TLSError>)> onError;
+ boost::signal<void ()> onConnected;
- private:
- TLSContext* context;
- };
+ private:
+ TLSContext* context;
+ };
}
diff --git a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
index 84a78fa..7044ad9 100644
--- a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
+++ b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
@@ -27,157 +27,157 @@
using namespace Swift;
class StreamStackTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(StreamStackTest);
- CPPUNIT_TEST(testWriteData_NoIntermediateStreamStack);
- CPPUNIT_TEST(testWriteData_OneIntermediateStream);
- CPPUNIT_TEST(testWriteData_TwoIntermediateStreamStack);
- CPPUNIT_TEST(testReadData_NoIntermediateStreamStack);
- CPPUNIT_TEST(testReadData_OneIntermediateStream);
- CPPUNIT_TEST(testReadData_TwoIntermediateStreamStack);
- CPPUNIT_TEST(testAddLayer_ExistingOnWriteDataSlot);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- physicalStream_ = new TestLowLayer();
- xmppStream_ = new XMPPLayer(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType);
- elementsReceived_ = 0;
- dataWriteReceived_ = 0;
- }
-
- void tearDown() {
- delete physicalStream_;
- delete xmppStream_;
- }
-
- void testWriteData_NoIntermediateStreamStack() {
- StreamStack testling(xmppStream_, physicalStream_);
-
- xmppStream_->writeData("foo");
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), physicalStream_->data_[0]);
- }
-
- void testWriteData_OneIntermediateStream() {
- StreamStack testling(xmppStream_, physicalStream_);
- boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
- testling.addLayer(xStream.get());
-
- xmppStream_->writeData("foo");
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("Xfoo"), physicalStream_->data_[0]);
- }
-
- void testWriteData_TwoIntermediateStreamStack() {
- StreamStack testling(xmppStream_, physicalStream_);
- boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
- boost::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("Y"));
- testling.addLayer(xStream.get());
- testling.addLayer(yStream.get());
-
- xmppStream_->writeData("foo");
-
- CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
- CPPUNIT_ASSERT_EQUAL(createSafeByteArray("XYfoo"), physicalStream_->data_[0]);
- }
-
- void testReadData_NoIntermediateStreamStack() {
- StreamStack testling(xmppStream_, physicalStream_);
- xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
-
- physicalStream_->onDataRead(createSafeByteArray("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
- }
-
- void testReadData_OneIntermediateStream() {
- StreamStack testling(xmppStream_, physicalStream_);
- xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
- boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("<"));
- testling.addLayer(xStream.get());
-
- physicalStream_->onDataRead(createSafeByteArray("stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
- }
-
- void testReadData_TwoIntermediateStreamStack() {
- StreamStack testling(xmppStream_, physicalStream_);
- xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
- boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("s"));
- boost::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("<"));
- testling.addLayer(xStream.get());
- testling.addLayer(yStream.get());
-
- physicalStream_->onDataRead(createSafeByteArray("tream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
- }
-
- void testAddLayer_ExistingOnWriteDataSlot() {
- StreamStack testling(xmppStream_, physicalStream_);
- xmppStream_->onWriteData.connect(boost::bind(&StreamStackTest::handleWriteData, this, _1));
- boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
- testling.addLayer(xStream.get());
-
- xmppStream_->writeData("foo");
-
- CPPUNIT_ASSERT_EQUAL(1, dataWriteReceived_);
- }
-
- void handleElement(boost::shared_ptr<ToplevelElement>) {
- ++elementsReceived_;
- }
-
- void handleWriteData(const SafeByteArray&) {
- ++dataWriteReceived_;
- }
-
- private:
- class MyStreamLayer : public StreamLayer {
- public:
- MyStreamLayer(const std::string& prepend) : prepend_(prepend) {
- }
-
- virtual void writeData(const SafeByteArray& data) {
- writeDataToChildLayer(concat(createSafeByteArray(prepend_), data));
- }
-
- virtual void handleDataRead(const SafeByteArray& data) {
- writeDataToParentLayer(concat(createSafeByteArray(prepend_), data));
- }
-
- private:
- std::string prepend_;
- };
-
- class TestLowLayer : public LowLayer {
- public:
- TestLowLayer() {
- }
-
- virtual void writeData(const SafeByteArray& data) {
- data_.push_back(data);
- }
-
- void onDataRead(const SafeByteArray& data) {
- writeDataToParentLayer(data);
- }
-
- std::vector<SafeByteArray> data_;
- };
-
-
- private:
- FullPayloadParserFactoryCollection parserFactories_;
- FullPayloadSerializerCollection serializers_;
- TestLowLayer* physicalStream_;
- PlatformXMLParserFactory xmlParserFactory_;
- XMPPLayer* xmppStream_;
- int elementsReceived_;
- int dataWriteReceived_;
+ CPPUNIT_TEST_SUITE(StreamStackTest);
+ CPPUNIT_TEST(testWriteData_NoIntermediateStreamStack);
+ CPPUNIT_TEST(testWriteData_OneIntermediateStream);
+ CPPUNIT_TEST(testWriteData_TwoIntermediateStreamStack);
+ CPPUNIT_TEST(testReadData_NoIntermediateStreamStack);
+ CPPUNIT_TEST(testReadData_OneIntermediateStream);
+ CPPUNIT_TEST(testReadData_TwoIntermediateStreamStack);
+ CPPUNIT_TEST(testAddLayer_ExistingOnWriteDataSlot);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ physicalStream_ = new TestLowLayer();
+ xmppStream_ = new XMPPLayer(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType);
+ elementsReceived_ = 0;
+ dataWriteReceived_ = 0;
+ }
+
+ void tearDown() {
+ delete physicalStream_;
+ delete xmppStream_;
+ }
+
+ void testWriteData_NoIntermediateStreamStack() {
+ StreamStack testling(xmppStream_, physicalStream_);
+
+ xmppStream_->writeData("foo");
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), physicalStream_->data_[0]);
+ }
+
+ void testWriteData_OneIntermediateStream() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
+ testling.addLayer(xStream.get());
+
+ xmppStream_->writeData("foo");
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("Xfoo"), physicalStream_->data_[0]);
+ }
+
+ void testWriteData_TwoIntermediateStreamStack() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
+ boost::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("Y"));
+ testling.addLayer(xStream.get());
+ testling.addLayer(yStream.get());
+
+ xmppStream_->writeData("foo");
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size());
+ CPPUNIT_ASSERT_EQUAL(createSafeByteArray("XYfoo"), physicalStream_->data_[0]);
+ }
+
+ void testReadData_NoIntermediateStreamStack() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
+
+ physicalStream_->onDataRead(createSafeByteArray("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
+ }
+
+ void testReadData_OneIntermediateStream() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
+ boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("<"));
+ testling.addLayer(xStream.get());
+
+ physicalStream_->onDataRead(createSafeByteArray("stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
+ }
+
+ void testReadData_TwoIntermediateStreamStack() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1));
+ boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("s"));
+ boost::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("<"));
+ testling.addLayer(xStream.get());
+ testling.addLayer(yStream.get());
+
+ physicalStream_->onDataRead(createSafeByteArray("tream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
+ }
+
+ void testAddLayer_ExistingOnWriteDataSlot() {
+ StreamStack testling(xmppStream_, physicalStream_);
+ xmppStream_->onWriteData.connect(boost::bind(&StreamStackTest::handleWriteData, this, _1));
+ boost::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
+ testling.addLayer(xStream.get());
+
+ xmppStream_->writeData("foo");
+
+ CPPUNIT_ASSERT_EQUAL(1, dataWriteReceived_);
+ }
+
+ void handleElement(boost::shared_ptr<ToplevelElement>) {
+ ++elementsReceived_;
+ }
+
+ void handleWriteData(const SafeByteArray&) {
+ ++dataWriteReceived_;
+ }
+
+ private:
+ class MyStreamLayer : public StreamLayer {
+ public:
+ MyStreamLayer(const std::string& prepend) : prepend_(prepend) {
+ }
+
+ virtual void writeData(const SafeByteArray& data) {
+ writeDataToChildLayer(concat(createSafeByteArray(prepend_), data));
+ }
+
+ virtual void handleDataRead(const SafeByteArray& data) {
+ writeDataToParentLayer(concat(createSafeByteArray(prepend_), data));
+ }
+
+ private:
+ std::string prepend_;
+ };
+
+ class TestLowLayer : public LowLayer {
+ public:
+ TestLowLayer() {
+ }
+
+ virtual void writeData(const SafeByteArray& data) {
+ data_.push_back(data);
+ }
+
+ void onDataRead(const SafeByteArray& data) {
+ writeDataToParentLayer(data);
+ }
+
+ std::vector<SafeByteArray> data_;
+ };
+
+
+ private:
+ FullPayloadParserFactoryCollection parserFactories_;
+ FullPayloadSerializerCollection serializers_;
+ TestLowLayer* physicalStream_;
+ PlatformXMLParserFactory xmlParserFactory_;
+ XMPPLayer* xmppStream_;
+ int elementsReceived_;
+ int dataWriteReceived_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(StreamStackTest);
diff --git a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
index 0250666..86e02ba 100644
--- a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
+++ b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
@@ -23,121 +23,121 @@
using namespace Swift;
class XMPPLayerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(XMPPLayerTest);
- CPPUNIT_TEST(testParseData_Error);
- CPPUNIT_TEST(testResetParser);
- CPPUNIT_TEST(testResetParser_FromSlot);
- CPPUNIT_TEST(testWriteHeader);
- CPPUNIT_TEST(testWriteElement);
- CPPUNIT_TEST(testWriteFooter);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- lowLayer_ = new DummyLowLayer();
- testling_ = new XMPPLayerExposed(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType);
- testling_->setChildLayer(lowLayer_);
- elementsReceived_ = 0;
- errorReceived_ = 0;
- }
-
- void tearDown() {
- delete testling_;
- delete lowLayer_;
- }
-
- void testParseData_Error() {
- testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
-
- testling_->handleDataRead(createSafeByteArray("<iq>"));
-
- CPPUNIT_ASSERT_EQUAL(1, errorReceived_);
- }
-
- void testResetParser() {
- testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElement, this, _1));
- testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
-
- testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
- testling_->resetParser();
- testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
- testling_->handleDataRead(createSafeByteArray("<presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
- CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
- }
-
- void testResetParser_FromSlot() {
- testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElementAndReset, this, _1));
- testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
- testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
-
- CPPUNIT_ASSERT_EQUAL(2, elementsReceived_);
- CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
- }
-
- void testWriteHeader() {
- ProtocolHeader header;
- header.setTo("example.com");
- testling_->writeHeader(header);
-
- CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" to=\"example.com\" version=\"1.0\">"), lowLayer_->writtenData);
- }
-
- void testWriteElement() {
- testling_->writeElement(boost::make_shared<Presence>());
-
- CPPUNIT_ASSERT_EQUAL(std::string("<presence/>"), lowLayer_->writtenData);
- }
-
- void testWriteFooter() {
- testling_->writeFooter();
-
- CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), lowLayer_->writtenData);
- }
-
- void handleElement(boost::shared_ptr<ToplevelElement>) {
- ++elementsReceived_;
- }
-
- void handleElementAndReset(boost::shared_ptr<ToplevelElement>) {
- ++elementsReceived_;
- testling_->resetParser();
- }
-
- void handleError() {
- ++errorReceived_;
- }
-
- private:
- class XMPPLayerExposed : public XMPPLayer {
- public:
- XMPPLayerExposed(
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory,
- StreamType streamType) : XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType) {}
-
- using XMPPLayer::handleDataRead;
- using HighLayer::setChildLayer;
- };
-
- class DummyLowLayer : public LowLayer {
- public:
- virtual void writeData(const SafeByteArray& data) {
- writtenData += byteArrayToString(ByteArray(data.begin(), data.end()));
- }
-
- std::string writtenData;
- };
-
- FullPayloadParserFactoryCollection parserFactories_;
- FullPayloadSerializerCollection serializers_;
- DummyLowLayer* lowLayer_;
- XMPPLayerExposed* testling_;
- PlatformXMLParserFactory xmlParserFactory_;
- int elementsReceived_;
- int errorReceived_;
+ CPPUNIT_TEST_SUITE(XMPPLayerTest);
+ CPPUNIT_TEST(testParseData_Error);
+ CPPUNIT_TEST(testResetParser);
+ CPPUNIT_TEST(testResetParser_FromSlot);
+ CPPUNIT_TEST(testWriteHeader);
+ CPPUNIT_TEST(testWriteElement);
+ CPPUNIT_TEST(testWriteFooter);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ lowLayer_ = new DummyLowLayer();
+ testling_ = new XMPPLayerExposed(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType);
+ testling_->setChildLayer(lowLayer_);
+ elementsReceived_ = 0;
+ errorReceived_ = 0;
+ }
+
+ void tearDown() {
+ delete testling_;
+ delete lowLayer_;
+ }
+
+ void testParseData_Error() {
+ testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
+
+ testling_->handleDataRead(createSafeByteArray("<iq>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, errorReceived_);
+ }
+
+ void testResetParser() {
+ testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElement, this, _1));
+ testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
+
+ testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
+ testling_->resetParser();
+ testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
+ testling_->handleDataRead(createSafeByteArray("<presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
+ }
+
+ void testResetParser_FromSlot() {
+ testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElementAndReset, this, _1));
+ testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
+ testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
+
+ CPPUNIT_ASSERT_EQUAL(2, elementsReceived_);
+ CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
+ }
+
+ void testWriteHeader() {
+ ProtocolHeader header;
+ header.setTo("example.com");
+ testling_->writeHeader(header);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" to=\"example.com\" version=\"1.0\">"), lowLayer_->writtenData);
+ }
+
+ void testWriteElement() {
+ testling_->writeElement(boost::make_shared<Presence>());
+
+ CPPUNIT_ASSERT_EQUAL(std::string("<presence/>"), lowLayer_->writtenData);
+ }
+
+ void testWriteFooter() {
+ testling_->writeFooter();
+
+ CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), lowLayer_->writtenData);
+ }
+
+ void handleElement(boost::shared_ptr<ToplevelElement>) {
+ ++elementsReceived_;
+ }
+
+ void handleElementAndReset(boost::shared_ptr<ToplevelElement>) {
+ ++elementsReceived_;
+ testling_->resetParser();
+ }
+
+ void handleError() {
+ ++errorReceived_;
+ }
+
+ private:
+ class XMPPLayerExposed : public XMPPLayer {
+ public:
+ XMPPLayerExposed(
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ StreamType streamType) : XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType) {}
+
+ using XMPPLayer::handleDataRead;
+ using HighLayer::setChildLayer;
+ };
+
+ class DummyLowLayer : public LowLayer {
+ public:
+ virtual void writeData(const SafeByteArray& data) {
+ writtenData += byteArrayToString(ByteArray(data.begin(), data.end()));
+ }
+
+ std::string writtenData;
+ };
+
+ FullPayloadParserFactoryCollection parserFactories_;
+ FullPayloadSerializerCollection serializers_;
+ DummyLowLayer* lowLayer_;
+ XMPPLayerExposed* testling_;
+ PlatformXMLParserFactory xmlParserFactory_;
+ int elementsReceived_;
+ int errorReceived_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMPPLayerTest);
diff --git a/Swiften/StreamStack/WhitespacePingLayer.cpp b/Swiften/StreamStack/WhitespacePingLayer.cpp
index 5ea5423..9a473f3 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.cpp
+++ b/Swiften/StreamStack/WhitespacePingLayer.cpp
@@ -17,40 +17,40 @@ namespace Swift {
static const int TIMEOUT_MILLISECONDS = 60000;
WhitespacePingLayer::WhitespacePingLayer(TimerFactory* timerFactory) : isActive(false) {
- timer = timerFactory->createTimer(TIMEOUT_MILLISECONDS);
- timer->onTick.connect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
+ timer = timerFactory->createTimer(TIMEOUT_MILLISECONDS);
+ timer->onTick.connect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
}
WhitespacePingLayer::~WhitespacePingLayer() {
- SWIFT_LOG_ASSERT(!isActive, debug) << "WhitespacePingLayer still active at destruction." << std::endl;
- if (isActive) {
- timer->stop();
- }
- timer->onTick.disconnect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
+ SWIFT_LOG_ASSERT(!isActive, debug) << "WhitespacePingLayer still active at destruction." << std::endl;
+ if (isActive) {
+ timer->stop();
+ }
+ timer->onTick.disconnect(boost::bind(&WhitespacePingLayer::handleTimerTick, this));
}
void WhitespacePingLayer::writeData(const SafeByteArray& data) {
- writeDataToChildLayer(data);
+ writeDataToChildLayer(data);
}
void WhitespacePingLayer::handleDataRead(const SafeByteArray& data) {
- writeDataToParentLayer(data);
+ writeDataToParentLayer(data);
}
void WhitespacePingLayer::handleTimerTick() {
- timer->stop();
- writeDataToChildLayer(createSafeByteArray(" "));
- timer->start();
+ timer->stop();
+ writeDataToChildLayer(createSafeByteArray(" "));
+ timer->start();
}
void WhitespacePingLayer::setActive() {
- isActive = true;
- timer->start();
+ isActive = true;
+ timer->start();
}
void WhitespacePingLayer::setInactive() {
- timer->stop();
- isActive = false;
+ timer->stop();
+ isActive = false;
}
}
diff --git a/Swiften/StreamStack/WhitespacePingLayer.h b/Swiften/StreamStack/WhitespacePingLayer.h
index 7ed56ca..41189ba 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.h
+++ b/Swiften/StreamStack/WhitespacePingLayer.h
@@ -13,28 +13,28 @@
#include <Swiften/StreamStack/StreamLayer.h>
namespace Swift {
- class Timer;
- class TimerFactory;
-
- class SWIFTEN_API WhitespacePingLayer : public StreamLayer, boost::noncopyable {
- public:
- WhitespacePingLayer(TimerFactory* timerFactory);
- virtual ~WhitespacePingLayer();
-
- void setActive();
- void setInactive();
- void writeData(const SafeByteArray& data);
- void handleDataRead(const SafeByteArray& data);
-
- bool getIsActive() const {
- return isActive;
- }
-
- private:
- void handleTimerTick();
-
- private:
- bool isActive;
- boost::shared_ptr<Timer> timer;
- };
+ class Timer;
+ class TimerFactory;
+
+ class SWIFTEN_API WhitespacePingLayer : public StreamLayer, boost::noncopyable {
+ public:
+ WhitespacePingLayer(TimerFactory* timerFactory);
+ virtual ~WhitespacePingLayer();
+
+ void setActive();
+ void setInactive();
+ void writeData(const SafeByteArray& data);
+ void handleDataRead(const SafeByteArray& data);
+
+ bool getIsActive() const {
+ return isActive;
+ }
+
+ private:
+ void handleTimerTick();
+
+ private:
+ bool isActive;
+ boost::shared_ptr<Timer> timer;
+ };
}
diff --git a/Swiften/StreamStack/XMPPLayer.cpp b/Swiften/StreamStack/XMPPLayer.cpp
index 2f7e578..e0d683c 100644
--- a/Swiften/StreamStack/XMPPLayer.cpp
+++ b/Swiften/StreamStack/XMPPLayer.cpp
@@ -13,88 +13,88 @@
namespace Swift {
XMPPLayer::XMPPLayer(
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory,
- StreamType streamType,
- bool setExplictNSonTopLevelElements) :
- payloadParserFactories_(payloadParserFactories),
- payloadSerializers_(payloadSerializers),
- xmlParserFactory_(xmlParserFactory),
- setExplictNSonTopLevelElements_(setExplictNSonTopLevelElements),
- resetParserAfterParse_(false),
- inParser_(false) {
- xmppParser_ = new XMPPParser(this, payloadParserFactories_, xmlParserFactory);
- xmppSerializer_ = new XMPPSerializer(payloadSerializers_, streamType, setExplictNSonTopLevelElements);
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ StreamType streamType,
+ bool setExplictNSonTopLevelElements) :
+ payloadParserFactories_(payloadParserFactories),
+ payloadSerializers_(payloadSerializers),
+ xmlParserFactory_(xmlParserFactory),
+ setExplictNSonTopLevelElements_(setExplictNSonTopLevelElements),
+ resetParserAfterParse_(false),
+ inParser_(false) {
+ xmppParser_ = new XMPPParser(this, payloadParserFactories_, xmlParserFactory);
+ xmppSerializer_ = new XMPPSerializer(payloadSerializers_, streamType, setExplictNSonTopLevelElements);
}
XMPPLayer::~XMPPLayer() {
- delete xmppSerializer_;
- delete xmppParser_;
+ delete xmppSerializer_;
+ delete xmppParser_;
}
void XMPPLayer::writeHeader(const ProtocolHeader& header) {
- writeDataInternal(createSafeByteArray(xmppSerializer_->serializeHeader(header)));
+ writeDataInternal(createSafeByteArray(xmppSerializer_->serializeHeader(header)));
}
void XMPPLayer::writeFooter() {
- writeDataInternal(createSafeByteArray(xmppSerializer_->serializeFooter()));
+ writeDataInternal(createSafeByteArray(xmppSerializer_->serializeFooter()));
}
void XMPPLayer::writeElement(boost::shared_ptr<ToplevelElement> element) {
- writeDataInternal(xmppSerializer_->serializeElement(element));
+ writeDataInternal(xmppSerializer_->serializeElement(element));
}
void XMPPLayer::writeData(const std::string& data) {
- writeDataInternal(createSafeByteArray(data));
+ writeDataInternal(createSafeByteArray(data));
}
void XMPPLayer::writeDataInternal(const SafeByteArray& data) {
- onWriteData(data);
- writeDataToChildLayer(data);
+ onWriteData(data);
+ writeDataToChildLayer(data);
}
void XMPPLayer::handleDataRead(const SafeByteArray& data) {
- onDataRead(data);
- inParser_ = true;
- // FIXME: Converting to unsafe string. Should be ok, since we don't take passwords
- // from the stream in clients. If servers start using this, and require safe storage,
- // we need to fix this.
- if (!xmppParser_->parse(byteArrayToString(ByteArray(data.begin(), data.end())))) {
- inParser_ = false;
- onError();
- return;
- }
- inParser_ = false;
- if (resetParserAfterParse_) {
- doResetParser();
- }
+ onDataRead(data);
+ inParser_ = true;
+ // FIXME: Converting to unsafe string. Should be ok, since we don't take passwords
+ // from the stream in clients. If servers start using this, and require safe storage,
+ // we need to fix this.
+ if (!xmppParser_->parse(byteArrayToString(ByteArray(data.begin(), data.end())))) {
+ inParser_ = false;
+ onError();
+ return;
+ }
+ inParser_ = false;
+ if (resetParserAfterParse_) {
+ doResetParser();
+ }
}
void XMPPLayer::doResetParser() {
- delete xmppParser_;
- xmppParser_ = new XMPPParser(this, payloadParserFactories_, xmlParserFactory_);
- resetParserAfterParse_ = false;
+ delete xmppParser_;
+ xmppParser_ = new XMPPParser(this, payloadParserFactories_, xmlParserFactory_);
+ resetParserAfterParse_ = false;
}
void XMPPLayer::handleStreamStart(const ProtocolHeader& header) {
- onStreamStart(header);
+ onStreamStart(header);
}
void XMPPLayer::handleElement(boost::shared_ptr<ToplevelElement> stanza) {
- onElement(stanza);
+ onElement(stanza);
}
void XMPPLayer::handleStreamEnd() {
}
void XMPPLayer::resetParser() {
- if (inParser_) {
- resetParserAfterParse_ = true;
- }
- else {
- doResetParser();
- }
+ if (inParser_) {
+ resetParserAfterParse_ = true;
+ }
+ else {
+ doResetParser();
+ }
}
}
diff --git a/Swiften/StreamStack/XMPPLayer.h b/Swiften/StreamStack/XMPPLayer.h
index 1bf145d..25d48bf 100644
--- a/Swiften/StreamStack/XMPPLayer.h
+++ b/Swiften/StreamStack/XMPPLayer.h
@@ -18,58 +18,58 @@
#include <Swiften/StreamStack/HighLayer.h>
namespace Swift {
- class ProtocolHeader;
- class XMPPParser;
- class PayloadParserFactoryCollection;
- class XMPPSerializer;
- class PayloadSerializerCollection;
- class XMLParserFactory;
- class BOSHSessionStream;
+ class ProtocolHeader;
+ class XMPPParser;
+ class PayloadParserFactoryCollection;
+ class XMPPSerializer;
+ class PayloadSerializerCollection;
+ class XMLParserFactory;
+ class BOSHSessionStream;
- class SWIFTEN_API XMPPLayer : public XMPPParserClient, public HighLayer, boost::noncopyable {
- friend class BOSHSessionStream;
- public:
- XMPPLayer(
- PayloadParserFactoryCollection* payloadParserFactories,
- PayloadSerializerCollection* payloadSerializers,
- XMLParserFactory* xmlParserFactory,
- StreamType streamType,
- bool setExplictNSonTopLevelElements = false);
- virtual ~XMPPLayer();
+ class SWIFTEN_API XMPPLayer : public XMPPParserClient, public HighLayer, boost::noncopyable {
+ friend class BOSHSessionStream;
+ public:
+ XMPPLayer(
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ StreamType streamType,
+ bool setExplictNSonTopLevelElements = false);
+ virtual ~XMPPLayer();
- void writeHeader(const ProtocolHeader& header);
- void writeFooter();
- void writeElement(boost::shared_ptr<ToplevelElement>);
- void writeData(const std::string& data);
+ void writeHeader(const ProtocolHeader& header);
+ void writeFooter();
+ void writeElement(boost::shared_ptr<ToplevelElement>);
+ void writeData(const std::string& data);
- void resetParser();
+ void resetParser();
- protected:
- void handleDataRead(const SafeByteArray& data);
- void writeDataInternal(const SafeByteArray& data);
+ protected:
+ void handleDataRead(const SafeByteArray& data);
+ void writeDataInternal(const SafeByteArray& data);
- public:
- boost::signal<void (const ProtocolHeader&)> onStreamStart;
- boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElement;
- boost::signal<void (const SafeByteArray&)> onWriteData;
- boost::signal<void (const SafeByteArray&)> onDataRead;
- boost::signal<void ()> onError;
+ public:
+ boost::signal<void (const ProtocolHeader&)> onStreamStart;
+ boost::signal<void (boost::shared_ptr<ToplevelElement>)> onElement;
+ boost::signal<void (const SafeByteArray&)> onWriteData;
+ boost::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signal<void ()> onError;
- private:
- void handleStreamStart(const ProtocolHeader&);
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamEnd();
+ private:
+ void handleStreamStart(const ProtocolHeader&);
+ void handleElement(boost::shared_ptr<ToplevelElement>);
+ void handleStreamEnd();
- void doResetParser();
+ void doResetParser();
- private:
- PayloadParserFactoryCollection* payloadParserFactories_;
- XMPPParser* xmppParser_;
- PayloadSerializerCollection* payloadSerializers_;
- XMLParserFactory* xmlParserFactory_;
- XMPPSerializer* xmppSerializer_;
- bool setExplictNSonTopLevelElements_;
- bool resetParserAfterParse_;
- bool inParser_;
- };
+ private:
+ PayloadParserFactoryCollection* payloadParserFactories_;
+ XMPPParser* xmppParser_;
+ PayloadSerializerCollection* payloadSerializers_;
+ XMLParserFactory* xmlParserFactory_;
+ XMPPSerializer* xmppSerializer_;
+ bool setExplictNSonTopLevelElements_;
+ bool resetParserAfterParse_;
+ bool inParser_;
+ };
}
diff --git a/Swiften/StringCodecs/Base64.cpp b/Swiften/StringCodecs/Base64.cpp
index 4e6ac8c..6eeaca9 100644
--- a/Swiften/StringCodecs/Base64.cpp
+++ b/Swiften/StringCodecs/Base64.cpp
@@ -11,91 +11,91 @@
using namespace Swift;
namespace {
- const char* encodeMap =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- const unsigned char decodeMap[255] = {
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 62, 255, 255, 255, 63,
- 52, 53, 54, 55, 56, 57, 58, 59,
- 60, 61, 255, 255, 255, 255, 255, 255,
- 255, 0, 1, 2, 3, 4, 5, 6,
- 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22,
- 23, 24, 25, 255, 255, 255, 255, 255,
- 255, 26, 27, 28, 29, 30, 31, 32,
- 33, 34, 35, 36, 37, 38, 39, 40,
- 41, 42, 43, 44, 45, 46, 47, 48,
- 49, 50, 51, 255, 255, 255, 255, 255
- };
+ const char* encodeMap =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ const unsigned char decodeMap[255] = {
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 62, 255, 255, 255, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59,
+ 60, 61, 255, 255, 255, 255, 255, 255,
+ 255, 0, 1, 2, 3, 4, 5, 6,
+ 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22,
+ 23, 24, 25, 255, 255, 255, 255, 255,
+ 255, 26, 27, 28, 29, 30, 31, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40,
+ 41, 42, 43, 44, 45, 46, 47, 48,
+ 49, 50, 51, 255, 255, 255, 255, 255
+ };
- template<typename ResultType, typename InputType>
- ResultType encodeDetail(const InputType& input) {
- ResultType result;
- size_t i = 0;
- for (; i < (input.size()/3)*3; i += 3) {
- unsigned int c = input[i+2] | (input[i+1]<<8) | (input[i]<<16);
- result.push_back(encodeMap[(c&0xFC0000)>>18]);
- result.push_back(encodeMap[(c&0x3F000)>>12]);
- result.push_back(encodeMap[(c&0xFC0)>>6]);
- result.push_back(encodeMap[c&0x3F]);
- }
- if (input.size() % 3 == 2) {
- unsigned int c = (input[i+1]<<8) | (input[i]<<16);
- result.push_back(encodeMap[(c&0xFC0000)>>18]);
- result.push_back(encodeMap[(c&0x3F000)>>12]);
- result.push_back(encodeMap[(c&0xFC0)>>6]);
- result.push_back('=');
- }
- else if (input.size() % 3 == 1) {
- unsigned int c = input[i]<<16;
- result.push_back(encodeMap[(c&0xFC0000)>>18]);
- result.push_back(encodeMap[(c&0x3F000)>>12]);
- result.push_back('=');
- result.push_back('=');
- }
- return result;
- }
+ template<typename ResultType, typename InputType>
+ ResultType encodeDetail(const InputType& input) {
+ ResultType result;
+ size_t i = 0;
+ for (; i < (input.size()/3)*3; i += 3) {
+ unsigned int c = input[i+2] | (input[i+1]<<8) | (input[i]<<16);
+ result.push_back(encodeMap[(c&0xFC0000)>>18]);
+ result.push_back(encodeMap[(c&0x3F000)>>12]);
+ result.push_back(encodeMap[(c&0xFC0)>>6]);
+ result.push_back(encodeMap[c&0x3F]);
+ }
+ if (input.size() % 3 == 2) {
+ unsigned int c = (input[i+1]<<8) | (input[i]<<16);
+ result.push_back(encodeMap[(c&0xFC0000)>>18]);
+ result.push_back(encodeMap[(c&0x3F000)>>12]);
+ result.push_back(encodeMap[(c&0xFC0)>>6]);
+ result.push_back('=');
+ }
+ else if (input.size() % 3 == 1) {
+ unsigned int c = input[i]<<16;
+ result.push_back(encodeMap[(c&0xFC0000)>>18]);
+ result.push_back(encodeMap[(c&0x3F000)>>12]);
+ result.push_back('=');
+ result.push_back('=');
+ }
+ return result;
+ }
}
std::string Base64::encode(const ByteArray& s) {
- return encodeDetail<std::string>(s);
+ return encodeDetail<std::string>(s);
}
SafeByteArray Base64::encode(const SafeByteArray& s) {
- return encodeDetail<SafeByteArray>(s);
+ return encodeDetail<SafeByteArray>(s);
}
ByteArray Base64::decode(const std::string& input) {
- ByteArray result;
+ ByteArray result;
- if (input.size() % 4) {
- return ByteArray();
- }
- for (size_t i = 0; i < input.size(); i += 4) {
- unsigned char c1 = input[i+0];
- unsigned char c2 = input[i+1];
- unsigned char c3 = input[i+2];
- unsigned char c4 = input[i+3];
- if (c3 == '=') {
- unsigned int c = (((decodeMap[c1]<<6)|decodeMap[c2])&0xFF0)>>4;
- result.push_back(c);
- }
- else if (c4 == '=') {
- unsigned int c = (((decodeMap[c1]<<12)|(decodeMap[c2]<<6)|decodeMap[c3])&0x3FFFC)>>2;
- result.push_back((c&0xFF00) >> 8);
- result.push_back(c&0xFF);
- }
- else {
- unsigned int c = (decodeMap[c1]<<18) | (decodeMap[c2]<<12) | (decodeMap[c3]<<6) | decodeMap[c4];
- result.push_back((c&0xFF0000) >> 16);
- result.push_back((c&0xFF00) >> 8);
- result.push_back(c&0xFF);
- }
- }
- return result;
+ if (input.size() % 4) {
+ return ByteArray();
+ }
+ for (size_t i = 0; i < input.size(); i += 4) {
+ unsigned char c1 = input[i+0];
+ unsigned char c2 = input[i+1];
+ unsigned char c3 = input[i+2];
+ unsigned char c4 = input[i+3];
+ if (c3 == '=') {
+ unsigned int c = (((decodeMap[c1]<<6)|decodeMap[c2])&0xFF0)>>4;
+ result.push_back(c);
+ }
+ else if (c4 == '=') {
+ unsigned int c = (((decodeMap[c1]<<12)|(decodeMap[c2]<<6)|decodeMap[c3])&0x3FFFC)>>2;
+ result.push_back((c&0xFF00) >> 8);
+ result.push_back(c&0xFF);
+ }
+ else {
+ unsigned int c = (decodeMap[c1]<<18) | (decodeMap[c2]<<12) | (decodeMap[c3]<<6) | decodeMap[c4];
+ result.push_back((c&0xFF0000) >> 16);
+ result.push_back((c&0xFF00) >> 8);
+ result.push_back(c&0xFF);
+ }
+ }
+ return result;
}
diff --git a/Swiften/StringCodecs/Base64.h b/Swiften/StringCodecs/Base64.h
index 416f48c..e1be4bc 100644
--- a/Swiften/StringCodecs/Base64.h
+++ b/Swiften/StringCodecs/Base64.h
@@ -14,11 +14,11 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API Base64 {
- public:
- static std::string encode(const ByteArray& s);
- static SafeByteArray encode(const SafeByteArray& s);
+ class SWIFTEN_API Base64 {
+ public:
+ static std::string encode(const ByteArray& s);
+ static SafeByteArray encode(const SafeByteArray& s);
- static ByteArray decode(const std::string &s);
- };
+ static ByteArray decode(const std::string &s);
+ };
}
diff --git a/Swiften/StringCodecs/Hexify.cpp b/Swiften/StringCodecs/Hexify.cpp
index 832d5b7..f4e4ecc 100644
--- a/Swiften/StringCodecs/Hexify.cpp
+++ b/Swiften/StringCodecs/Hexify.cpp
@@ -18,56 +18,56 @@
namespace Swift {
std::string Hexify::hexify(unsigned char byte) {
- std::ostringstream result;
- result << std::hex << std::setw(2) << std::setfill('0') << boost::numeric_cast<unsigned int>(byte);
- return std::string(result.str());
+ std::ostringstream result;
+ result << std::hex << std::setw(2) << std::setfill('0') << boost::numeric_cast<unsigned int>(byte);
+ return std::string(result.str());
}
std::string Hexify::hexify(const ByteArray& data) {
- std::ostringstream result;
- result << std::hex;
+ std::ostringstream result;
+ result << std::hex;
- for (unsigned int i = 0; i < data.size(); ++i) {
- result << std::setw(2) << std::setfill('0') << boost::numeric_cast<unsigned int>(static_cast<unsigned char>(data[i]));
- }
- return std::string(result.str());
+ for (unsigned int i = 0; i < data.size(); ++i) {
+ result << std::setw(2) << std::setfill('0') << boost::numeric_cast<unsigned int>(static_cast<unsigned char>(data[i]));
+ }
+ return std::string(result.str());
}
static const unsigned char map[256] = {
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 0, 1, 2, 3, 4, 5, 6, 7,
- 8, 9, 255, 255, 255, 255, 255, 255,
- 255, 10, 11, 12, 13, 14, 15, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 10, 11, 12, 13, 14, 15, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255
};
ByteArray Hexify::unhexify(const std::string& in) {
- if (in.size() % 2) {
- return ByteArray();
- }
+ if (in.size() % 2) {
+ return ByteArray();
+ }
- ByteArray result(in.size() / 2);
- for (size_t pos = 0; pos < in.size() - 1; pos += 2) {
- unsigned char a = map[static_cast<size_t>(in[pos])];
- unsigned char b = map[static_cast<size_t>(in[pos+1])];
- if (a == 255 || b == 255) {
- return ByteArray();
- }
- result[pos/2] = (a<<4) | b;
- }
- return result;
+ ByteArray result(in.size() / 2);
+ for (size_t pos = 0; pos < in.size() - 1; pos += 2) {
+ unsigned char a = map[static_cast<size_t>(in[pos])];
+ unsigned char b = map[static_cast<size_t>(in[pos+1])];
+ if (a == 255 || b == 255) {
+ return ByteArray();
+ }
+ result[pos/2] = (a<<4) | b;
+ }
+ return result;
}
}
diff --git a/Swiften/StringCodecs/Hexify.h b/Swiften/StringCodecs/Hexify.h
index b29864c..20027d3 100644
--- a/Swiften/StringCodecs/Hexify.h
+++ b/Swiften/StringCodecs/Hexify.h
@@ -10,10 +10,10 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- class SWIFTEN_API Hexify {
- public:
- static std::string hexify(unsigned char byte);
- static std::string hexify(const ByteArray& data);
- static ByteArray unhexify(const std::string& hexstring);
- };
+ class SWIFTEN_API Hexify {
+ public:
+ static std::string hexify(unsigned char byte);
+ static std::string hexify(const ByteArray& data);
+ static ByteArray unhexify(const std::string& hexstring);
+ };
}
diff --git a/Swiften/StringCodecs/PBKDF2.h b/Swiften/StringCodecs/PBKDF2.h
index 76a9656..2177b5f 100644
--- a/Swiften/StringCodecs/PBKDF2.h
+++ b/Swiften/StringCodecs/PBKDF2.h
@@ -12,20 +12,20 @@
#include <Swiften/Crypto/CryptoProvider.h>
namespace Swift {
- class SWIFTEN_API PBKDF2 {
- public:
- static ByteArray encode(const SafeByteArray& password, const ByteArray& salt, int iterations, CryptoProvider* crypto) {
- ByteArray u = crypto->getHMACSHA1(password, concat(salt, createByteArray("\0\0\0\1", 4)));
- ByteArray result(u);
- int i = 1;
- while (i < iterations) {
- u = crypto->getHMACSHA1(password, u);
- for (unsigned int j = 0; j < u.size(); ++j) {
- result[j] ^= u[j];
- }
- ++i;
- }
- return result;
- }
- };
+ class SWIFTEN_API PBKDF2 {
+ public:
+ static ByteArray encode(const SafeByteArray& password, const ByteArray& salt, int iterations, CryptoProvider* crypto) {
+ ByteArray u = crypto->getHMACSHA1(password, concat(salt, createByteArray("\0\0\0\1", 4)));
+ ByteArray result(u);
+ int i = 1;
+ while (i < iterations) {
+ u = crypto->getHMACSHA1(password, u);
+ for (unsigned int j = 0; j < u.size(); ++j) {
+ result[j] ^= u[j];
+ }
+ ++i;
+ }
+ return result;
+ }
+ };
}
diff --git a/Swiften/StringCodecs/SHA1_Windows.cpp b/Swiften/StringCodecs/SHA1_Windows.cpp
index f883d13..ff02012 100644
--- a/Swiften/StringCodecs/SHA1_Windows.cpp
+++ b/Swiften/StringCodecs/SHA1_Windows.cpp
@@ -10,95 +10,95 @@
#include <Swiften/StringCodecs/SHA1_Windows.h>
namespace {
- HCRYPTPROV context = 0;
-
- struct ContextDeleter {
- ~ContextDeleter() {
- if (context) {
- CryptReleaseContext(context, 0);
- context = 0;
- }
- }
- } contextDeleter;
+ HCRYPTPROV context = 0;
+
+ struct ContextDeleter {
+ ~ContextDeleter() {
+ if (context) {
+ CryptReleaseContext(context, 0);
+ context = 0;
+ }
+ }
+ } contextDeleter;
}
namespace Swift {
SHA1::SHA1() : hash(NULL) {
- if (!context) {
- if (!CryptAcquireContext(&context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
-// DWORD error = GetLastError();
-// switch (error) {
-// std::cerr << (long)error << std::endl;
-// }
-// assert(false);
- context = 0;
- }
- }
-
- if (!CryptCreateHash(context, CALG_SHA1, 0, 0, &hash)) {
- hash = NULL;
- }
+ if (!context) {
+ if (!CryptAcquireContext(&context, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
+// DWORD error = GetLastError();
+// switch (error) {
+// std::cerr << (long)error << std::endl;
+// }
+// assert(false);
+ context = 0;
+ }
+ }
+
+ if (!CryptCreateHash(context, CALG_SHA1, 0, 0, &hash)) {
+ hash = NULL;
+ }
}
SHA1::~SHA1() {
- if (hash) {
- CryptDestroyHash(hash);
- }
+ if (hash) {
+ CryptDestroyHash(hash);
+ }
}
SHA1& SHA1::update(const std::vector<unsigned char>& data) {
- return update(vecptr(data), data.size());
+ return update(vecptr(data), data.size());
}
SHA1& SHA1::update(const unsigned char* data, size_t dataSize) {
- if (!hash || !context) {
- return *this;
- }
- if (!CryptHashData(hash, const_cast<BYTE*>(data), dataSize, 0)) {
-// DWORD error = GetLastError();
-// switch (error) {
-// std::cerr << (long)error << std::endl;
-// }
-// assert(false);
-// }
- }
- return *this;
+ if (!hash || !context) {
+ return *this;
+ }
+ if (!CryptHashData(hash, const_cast<BYTE*>(data), dataSize, 0)) {
+// DWORD error = GetLastError();
+// switch (error) {
+// std::cerr << (long)error << std::endl;
+// }
+// assert(false);
+// }
+ }
+ return *this;
}
std::vector<unsigned char> SHA1::getHash() const {
- if (!hash || !context) {
- return std::vector<unsigned char>();
- }
- std::vector<unsigned char> result;
- DWORD hashLength = sizeof(DWORD);
- DWORD hashSize;
- CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
- result.resize(static_cast<size_t>(hashSize));
- if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
-// DWORD error = GetLastError();
-// switch (error) {
-// std::cerr << (long)error << std::endl;
-// }
-// assert(false);
- return std::vector<unsigned char>();
- }
- result.resize(static_cast<size_t>(hashSize));
- return result;
+ if (!hash || !context) {
+ return std::vector<unsigned char>();
+ }
+ std::vector<unsigned char> result;
+ DWORD hashLength = sizeof(DWORD);
+ DWORD hashSize;
+ CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0);
+ result.resize(static_cast<size_t>(hashSize));
+ if (!CryptGetHashParam(hash, HP_HASHVAL, vecptr(result), &hashSize, 0)) {
+// DWORD error = GetLastError();
+// switch (error) {
+// std::cerr << (long)error << std::endl;
+// }
+// assert(false);
+ return std::vector<unsigned char>();
+ }
+ result.resize(static_cast<size_t>(hashSize));
+ return result;
}
ByteArray SHA1::getHash(const ByteArray& data) {
- SHA1 hash;
- hash.update(vecptr(data), data.size());
- return hash.getHash();
+ SHA1 hash;
+ hash.update(vecptr(data), data.size());
+ return hash.getHash();
}
ByteArray SHA1::getHash(const SafeByteArray& data) {
- SHA1 hash;
- hash.update(vecptr(data), data.size());
- return hash.getHash();
+ SHA1 hash;
+ hash.update(vecptr(data), data.size());
+ return hash.getHash();
}
}
diff --git a/Swiften/StringCodecs/SHA1_Windows.h b/Swiften/StringCodecs/SHA1_Windows.h
index 29ec78b..b94de21 100644
--- a/Swiften/StringCodecs/SHA1_Windows.h
+++ b/Swiften/StringCodecs/SHA1_Windows.h
@@ -16,29 +16,29 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API SHA1 {
- public:
- SHA1();
- ~SHA1();
+ class SWIFTEN_API SHA1 {
+ public:
+ SHA1();
+ ~SHA1();
- SHA1& update(const std::vector<unsigned char>& data);
- std::vector<unsigned char> getHash() const;
+ SHA1& update(const std::vector<unsigned char>& data);
+ std::vector<unsigned char> getHash() const;
- static ByteArray getHash(const ByteArray& data);
- static ByteArray getHash(const SafeByteArray& data);
+ static ByteArray getHash(const ByteArray& data);
+ static ByteArray getHash(const SafeByteArray& data);
- ByteArray operator()(const SafeByteArray& data) {
- return getHash(data);
- }
+ ByteArray operator()(const SafeByteArray& data) {
+ return getHash(data);
+ }
- ByteArray operator()(const ByteArray& data) {
- return getHash(data);
- }
+ ByteArray operator()(const ByteArray& data) {
+ return getHash(data);
+ }
- private:
- SHA1& update(const unsigned char* data, size_t dataSize);
+ private:
+ SHA1& update(const unsigned char* data, size_t dataSize);
- private:
- HCRYPTHASH hash;
- };
+ private:
+ HCRYPTHASH hash;
+ };
}
diff --git a/Swiften/StringCodecs/UnitTest/Base64Test.cpp b/Swiften/StringCodecs/UnitTest/Base64Test.cpp
index d626090..272514f 100644
--- a/Swiften/StringCodecs/UnitTest/Base64Test.cpp
+++ b/Swiften/StringCodecs/UnitTest/Base64Test.cpp
@@ -15,53 +15,53 @@
using namespace Swift;
class Base64Test : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(Base64Test);
- CPPUNIT_TEST(testEncodeDecodeAllChars);
- CPPUNIT_TEST(testEncodeDecodeOneBytePadding);
- CPPUNIT_TEST(testEncodeDecodeTwoBytesPadding);
- CPPUNIT_TEST(testEncode_NoData);
- CPPUNIT_TEST(testDecode_NoData);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testEncodeDecodeAllChars() {
- ByteArray input;
- for (unsigned char i = 0; i < 255; ++i) {
- input.push_back(i);
- }
- std::string result(Base64::encode(input));
-
- CPPUNIT_ASSERT_EQUAL(std::string("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+"), result);
- CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
- }
-
- void testEncodeDecodeOneBytePadding() {
- ByteArray input = createByteArray("ABCDE", 5);
-
- std::string result = Base64::encode(input);
-
- CPPUNIT_ASSERT_EQUAL(std::string("QUJDREU="), result);
- CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
- }
-
- void testEncodeDecodeTwoBytesPadding() {
- ByteArray input = createByteArray("ABCD", 4);
-
- std::string result = Base64::encode(input);
-
- CPPUNIT_ASSERT_EQUAL(std::string("QUJDRA=="), result);
- CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
- }
-
- void testEncode_NoData() {
- std::string result(Base64::encode(ByteArray()));
- CPPUNIT_ASSERT_EQUAL(std::string(""), result);
- }
-
- void testDecode_NoData() {
- ByteArray result(Base64::decode(""));
- CPPUNIT_ASSERT_EQUAL(ByteArray(), result);
- }
+ CPPUNIT_TEST_SUITE(Base64Test);
+ CPPUNIT_TEST(testEncodeDecodeAllChars);
+ CPPUNIT_TEST(testEncodeDecodeOneBytePadding);
+ CPPUNIT_TEST(testEncodeDecodeTwoBytesPadding);
+ CPPUNIT_TEST(testEncode_NoData);
+ CPPUNIT_TEST(testDecode_NoData);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testEncodeDecodeAllChars() {
+ ByteArray input;
+ for (unsigned char i = 0; i < 255; ++i) {
+ input.push_back(i);
+ }
+ std::string result(Base64::encode(input));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+"), result);
+ CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
+ }
+
+ void testEncodeDecodeOneBytePadding() {
+ ByteArray input = createByteArray("ABCDE", 5);
+
+ std::string result = Base64::encode(input);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("QUJDREU="), result);
+ CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
+ }
+
+ void testEncodeDecodeTwoBytesPadding() {
+ ByteArray input = createByteArray("ABCD", 4);
+
+ std::string result = Base64::encode(input);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("QUJDRA=="), result);
+ CPPUNIT_ASSERT_EQUAL(input, Base64::decode(result));
+ }
+
+ void testEncode_NoData() {
+ std::string result(Base64::encode(ByteArray()));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), result);
+ }
+
+ void testDecode_NoData() {
+ ByteArray result(Base64::decode(""));
+ CPPUNIT_ASSERT_EQUAL(ByteArray(), result);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(Base64Test);
diff --git a/Swiften/StringCodecs/UnitTest/HexifyTest.cpp b/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
index 57f4fe8..7d349fa 100644
--- a/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
+++ b/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
@@ -15,25 +15,25 @@
using namespace Swift;
class HexifyTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(HexifyTest);
- CPPUNIT_TEST(testHexify);
- CPPUNIT_TEST(testHexify_Byte);
- CPPUNIT_TEST(testUnhexify);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void testHexify() {
- CPPUNIT_ASSERT_EQUAL(std::string("4206b23ca6b0a643d20d89b04ff58cf78b8096ed"), Hexify::hexify(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed")));
- }
-
- void testHexify_Byte() {
- CPPUNIT_ASSERT_EQUAL(std::string("b2"), Hexify::hexify(0xb2));
- }
-
- void testUnhexify() {
- CPPUNIT_ASSERT_EQUAL(std::string("ffaf02"), Hexify::hexify(Hexify::unhexify("ffaf02")));
- CPPUNIT_ASSERT(createByteArray("\x01\x23\xf2", 3) == Hexify::unhexify("0123f2"));
- }
+ CPPUNIT_TEST_SUITE(HexifyTest);
+ CPPUNIT_TEST(testHexify);
+ CPPUNIT_TEST(testHexify_Byte);
+ CPPUNIT_TEST(testUnhexify);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testHexify() {
+ CPPUNIT_ASSERT_EQUAL(std::string("4206b23ca6b0a643d20d89b04ff58cf78b8096ed"), Hexify::hexify(createByteArray("\x42\x06\xb2\x3c\xa6\xb0\xa6\x43\xd2\x0d\x89\xb0\x4f\xf5\x8c\xf7\x8b\x80\x96\xed")));
+ }
+
+ void testHexify_Byte() {
+ CPPUNIT_ASSERT_EQUAL(std::string("b2"), Hexify::hexify(0xb2));
+ }
+
+ void testUnhexify() {
+ CPPUNIT_ASSERT_EQUAL(std::string("ffaf02"), Hexify::hexify(Hexify::unhexify("ffaf02")));
+ CPPUNIT_ASSERT(createByteArray("\x01\x23\xf2", 3) == Hexify::unhexify("0123f2"));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(HexifyTest);
diff --git a/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp b/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp
index b75f6fb..343c170 100644
--- a/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp
+++ b/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp
@@ -17,37 +17,37 @@
using namespace Swift;
class PBKDF2Test : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(PBKDF2Test);
- CPPUNIT_TEST(testGetResult_I1);
- CPPUNIT_TEST(testGetResult_I2);
- CPPUNIT_TEST(testGetResult_I4096);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(PBKDF2Test);
+ CPPUNIT_TEST(testGetResult_I1);
+ CPPUNIT_TEST(testGetResult_I2);
+ CPPUNIT_TEST(testGetResult_I4096);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void setUp() {
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- }
+ public:
+ void setUp() {
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
- void testGetResult_I1() {
- ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 1, crypto.get()));
+ void testGetResult_I1() {
+ ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 1, crypto.get()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24\xaf\x60\x12\x06\x2f\xe0\x37\xa6"), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24\xaf\x60\x12\x06\x2f\xe0\x37\xa6"), result);
+ }
- void testGetResult_I2() {
- ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 2, crypto.get()));
+ void testGetResult_I2() {
+ ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 2, crypto.get()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\xea\x6c\x1\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a\xce\x1d\x41\xf0\xd8\xde\x89\x57"), result);
- }
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xea\x6c\x1\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a\xce\x1d\x41\xf0\xd8\xde\x89\x57"), result);
+ }
- void testGetResult_I4096() {
- ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 4096, crypto.get()));
+ void testGetResult_I4096() {
+ ByteArray result(PBKDF2::encode(createSafeByteArray("password"), createByteArray("salt"), 4096, crypto.get()));
- CPPUNIT_ASSERT_EQUAL(createByteArray("\x4b\x00\x79\x1\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26\xf7\x21\xd0\x65\xa4\x29\xc1", 20), result);
- }
-
- private:
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x4b\x00\x79\x1\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26\xf7\x21\xd0\x65\xa4\x29\xc1", 20), result);
+ }
+
+ private:
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(PBKDF2Test);
diff --git a/Swiften/TLS/BlindCertificateTrustChecker.h b/Swiften/TLS/BlindCertificateTrustChecker.h
index b21f7a6..76a7a02 100644
--- a/Swiften/TLS/BlindCertificateTrustChecker.h
+++ b/Swiften/TLS/BlindCertificateTrustChecker.h
@@ -10,18 +10,18 @@
#include <Swiften/TLS/CertificateTrustChecker.h>
namespace Swift {
- /**
- * A certificate trust checker that trusts any ceritficate.
- *
- * This can be used to ignore any TLS certificate errors occurring
- * during connection.
- *
- * \see Client::setAlwaysTrustCertificates()
- */
- class SWIFTEN_API BlindCertificateTrustChecker : public CertificateTrustChecker {
- public:
- virtual bool isCertificateTrusted(const std::vector<Certificate::ref>&) {
- return true;
- }
- };
+ /**
+ * A certificate trust checker that trusts any ceritficate.
+ *
+ * This can be used to ignore any TLS certificate errors occurring
+ * during connection.
+ *
+ * \see Client::setAlwaysTrustCertificates()
+ */
+ class SWIFTEN_API BlindCertificateTrustChecker : public CertificateTrustChecker {
+ public:
+ virtual bool isCertificateTrusted(const std::vector<Certificate::ref>&) {
+ return true;
+ }
+ };
}
diff --git a/Swiften/TLS/CAPICertificate.cpp b/Swiften/TLS/CAPICertificate.cpp
index 90398e9..29bb338 100644
--- a/Swiften/TLS/CAPICertificate.cpp
+++ b/Swiften/TLS/CAPICertificate.cpp
@@ -20,332 +20,332 @@
#define DEBUG_SCARD_STATUS(function, status) \
{ \
- boost::shared_ptr<boost::system::error_code> errorCode = boost::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
- SWIFT_LOG(debug) << std::hex << function << ": status: 0x" << status << ": " << errorCode->message() << std::endl; \
+ boost::shared_ptr<boost::system::error_code> errorCode = boost::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
+ SWIFT_LOG(debug) << std::hex << function << ": status: 0x" << status << ": " << errorCode->message() << std::endl; \
}
namespace Swift {
-CAPICertificate::CAPICertificate(const std::string& capiUri, TimerFactory* timerFactory) :
- valid_(false),
- uri_(capiUri),
- certStoreHandle_(0),
- scardContext_(0),
- cardHandle_(0),
- certStore_(),
- certName_(),
- smartCardReaderName_(),
- timerFactory_(timerFactory),
- lastPollingResult_(true) {
- assert(timerFactory_);
-
- setUri(capiUri);
+CAPICertificate::CAPICertificate(const std::string& capiUri, TimerFactory* timerFactory) :
+ valid_(false),
+ uri_(capiUri),
+ certStoreHandle_(0),
+ scardContext_(0),
+ cardHandle_(0),
+ certStore_(),
+ certName_(),
+ smartCardReaderName_(),
+ timerFactory_(timerFactory),
+ lastPollingResult_(true) {
+ assert(timerFactory_);
+
+ setUri(capiUri);
}
CAPICertificate::~CAPICertificate() {
- if (smartCardTimer_) {
- smartCardTimer_->stop();
- smartCardTimer_->onTick.disconnect(boost::bind(&CAPICertificate::handleSmartCardTimerTick, this));
- smartCardTimer_.reset();
- }
-
- if (certStoreHandle_) {
- CertCloseStore(certStoreHandle_, 0);
- }
-
- if (cardHandle_) {
- LONG result = SCardDisconnect(cardHandle_, SCARD_LEAVE_CARD);
- DEBUG_SCARD_STATUS("SCardDisconnect", result);
- }
-
- if (scardContext_) {
- LONG result = SCardReleaseContext(scardContext_);
- DEBUG_SCARD_STATUS("SCardReleaseContext", result);
- }
+ if (smartCardTimer_) {
+ smartCardTimer_->stop();
+ smartCardTimer_->onTick.disconnect(boost::bind(&CAPICertificate::handleSmartCardTimerTick, this));
+ smartCardTimer_.reset();
+ }
+
+ if (certStoreHandle_) {
+ CertCloseStore(certStoreHandle_, 0);
+ }
+
+ if (cardHandle_) {
+ LONG result = SCardDisconnect(cardHandle_, SCARD_LEAVE_CARD);
+ DEBUG_SCARD_STATUS("SCardDisconnect", result);
+ }
+
+ if (scardContext_) {
+ LONG result = SCardReleaseContext(scardContext_);
+ DEBUG_SCARD_STATUS("SCardReleaseContext", result);
+ }
}
bool CAPICertificate::isNull() const {
- return uri_.empty() || !valid_;
+ return uri_.empty() || !valid_;
}
const std::string& CAPICertificate::getCertStoreName() const {
- return certStore_;
+ return certStore_;
}
const std::string& CAPICertificate::getCertName() const {
- return certName_;
+ return certName_;
}
const std::string& CAPICertificate::getSmartCardReaderName() const {
- return smartCardReaderName_;
+ return smartCardReaderName_;
}
PCCERT_CONTEXT findCertificateInStore (HCERTSTORE certStoreHandle, const std::string &certName) {
- if (!boost::iequals(certName.substr(0, 5), "sha1:")) {
+ if (!boost::iequals(certName.substr(0, 5), "sha1:")) {
- // Find client certificate. Note that this sample just searches for a
- // certificate that contains the user name somewhere in the subject name.
- return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /*dwFindFlags*/ 0, CERT_FIND_SUBJECT_STR_A, /* *pvFindPara*/certName.c_str(), /*pPrevCertContext*/ NULL);
- }
+ // Find client certificate. Note that this sample just searches for a
+ // certificate that contains the user name somewhere in the subject name.
+ return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /*dwFindFlags*/ 0, CERT_FIND_SUBJECT_STR_A, /* *pvFindPara*/certName.c_str(), /*pPrevCertContext*/ NULL);
+ }
- std::string hexstring = certName.substr(5);
- ByteArray byteArray = Hexify::unhexify(hexstring);
- CRYPT_HASH_BLOB HashBlob;
+ std::string hexstring = certName.substr(5);
+ ByteArray byteArray = Hexify::unhexify(hexstring);
+ CRYPT_HASH_BLOB HashBlob;
- if (byteArray.size() != SHA1_HASH_LEN) {
- return NULL;
- }
- HashBlob.cbData = SHA1_HASH_LEN;
- HashBlob.pbData = static_cast<BYTE *>(vecptr(byteArray));
+ if (byteArray.size() != SHA1_HASH_LEN) {
+ return NULL;
+ }
+ HashBlob.cbData = SHA1_HASH_LEN;
+ HashBlob.pbData = static_cast<BYTE *>(vecptr(byteArray));
- // Find client certificate. Note that this sample just searches for a
- // certificate that contains the user name somewhere in the subject name.
- return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /* dwFindFlags */ 0, CERT_FIND_HASH, &HashBlob, /* pPrevCertContext */ NULL);
+ // Find client certificate. Note that this sample just searches for a
+ // certificate that contains the user name somewhere in the subject name.
+ return CertFindCertificateInStore(certStoreHandle, X509_ASN_ENCODING, /* dwFindFlags */ 0, CERT_FIND_HASH, &HashBlob, /* pPrevCertContext */ NULL);
}
void CAPICertificate::setUri (const std::string& capiUri) {
- valid_ = false;
-
- /* Syntax: "certstore:" <cert_store> ":" <hash> ":" <hash_of_cert> */
-
- if (!boost::iequals(capiUri.substr(0, 10), "certstore:")) {
- return;
- }
-
- /* Substring of subject: uses "storename" */
- std::string capiIdentity = capiUri.substr(10);
- std::string newCertStoreName;
- size_t pos = capiIdentity.find_first_of (':');
-
- if (pos == std::string::npos) {
- /* Using the default certificate store */
- newCertStoreName = "MY";
- certName_ = capiIdentity;
- }
- else {
- newCertStoreName = capiIdentity.substr(0, pos);
- certName_ = capiIdentity.substr(pos + 1);
- }
-
- if (certStoreHandle_ != NULL) {
- if (newCertStoreName != certStore_) {
- CertCloseStore(certStoreHandle_, 0);
- certStoreHandle_ = NULL;
- }
- }
-
- if (certStoreHandle_ == NULL) {
- certStoreHandle_ = CertOpenSystemStore(0, newCertStoreName.c_str());
- if (!certStoreHandle_) {
- return;
- }
- }
-
- certStore_ = newCertStoreName;
-
- PCCERT_CONTEXT certContext = findCertificateInStore (certStoreHandle_, certName_);
-
- if (!certContext) {
- return;
- }
-
-
- /* Now verify that we can have access to the corresponding private key */
-
- DWORD len;
- CRYPT_KEY_PROV_INFO *pinfo;
- HCRYPTPROV hprov;
- HCRYPTKEY key;
-
- if (!CertGetCertificateContextProperty(certContext,
- CERT_KEY_PROV_INFO_PROP_ID,
- NULL,
- &len)) {
- CertFreeCertificateContext(certContext);
- return;
- }
-
- pinfo = static_cast<CRYPT_KEY_PROV_INFO *>(malloc(len));
- if (!pinfo) {
- CertFreeCertificateContext(certContext);
- return;
- }
-
- if (!CertGetCertificateContextProperty(certContext, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
- CertFreeCertificateContext(certContext);
- free(pinfo);
- return;
- }
-
- CertFreeCertificateContext(certContext);
-
- // Now verify if we have access to the private key
- if (!CryptAcquireContextW(&hprov, pinfo->pwszContainerName, pinfo->pwszProvName, pinfo->dwProvType, 0)) {
- free(pinfo);
- return;
- }
-
-
- char smartCardReader[1024];
- DWORD bufferLength = sizeof(smartCardReader);
- if (!CryptGetProvParam(hprov, PP_SMARTCARD_READER, (BYTE *)&smartCardReader, &bufferLength, 0)) {
- DWORD error = GetLastError();
- smartCardReaderName_ = "";
- }
- else {
- smartCardReaderName_ = smartCardReader;
-
- LONG result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &scardContext_);
- DEBUG_SCARD_STATUS("SCardEstablishContext", result);
- if (SCARD_S_SUCCESS == result) {
- // Initiate monitoring for smartcard ejection
- smartCardTimer_ = timerFactory_->createTimer(SMARTCARD_EJECTION_CHECK_FREQUENCY_MILLISECONDS);
- }
- else {
- ///Need to handle an error here
- }
- }
-
- if (!CryptGetUserKey(hprov, pinfo->dwKeySpec, &key)) {
- CryptReleaseContext(hprov, 0);
- free(pinfo);
- return;
- }
-
- CryptDestroyKey(key);
- CryptReleaseContext(hprov, 0);
- free(pinfo);
-
- if (smartCardTimer_) {
- smartCardTimer_->onTick.connect(boost::bind(&CAPICertificate::handleSmartCardTimerTick, this));
- smartCardTimer_->start();
- }
-
- valid_ = true;
+ valid_ = false;
+
+ /* Syntax: "certstore:" <cert_store> ":" <hash> ":" <hash_of_cert> */
+
+ if (!boost::iequals(capiUri.substr(0, 10), "certstore:")) {
+ return;
+ }
+
+ /* Substring of subject: uses "storename" */
+ std::string capiIdentity = capiUri.substr(10);
+ std::string newCertStoreName;
+ size_t pos = capiIdentity.find_first_of (':');
+
+ if (pos == std::string::npos) {
+ /* Using the default certificate store */
+ newCertStoreName = "MY";
+ certName_ = capiIdentity;
+ }
+ else {
+ newCertStoreName = capiIdentity.substr(0, pos);
+ certName_ = capiIdentity.substr(pos + 1);
+ }
+
+ if (certStoreHandle_ != NULL) {
+ if (newCertStoreName != certStore_) {
+ CertCloseStore(certStoreHandle_, 0);
+ certStoreHandle_ = NULL;
+ }
+ }
+
+ if (certStoreHandle_ == NULL) {
+ certStoreHandle_ = CertOpenSystemStore(0, newCertStoreName.c_str());
+ if (!certStoreHandle_) {
+ return;
+ }
+ }
+
+ certStore_ = newCertStoreName;
+
+ PCCERT_CONTEXT certContext = findCertificateInStore (certStoreHandle_, certName_);
+
+ if (!certContext) {
+ return;
+ }
+
+
+ /* Now verify that we can have access to the corresponding private key */
+
+ DWORD len;
+ CRYPT_KEY_PROV_INFO *pinfo;
+ HCRYPTPROV hprov;
+ HCRYPTKEY key;
+
+ if (!CertGetCertificateContextProperty(certContext,
+ CERT_KEY_PROV_INFO_PROP_ID,
+ NULL,
+ &len)) {
+ CertFreeCertificateContext(certContext);
+ return;
+ }
+
+ pinfo = static_cast<CRYPT_KEY_PROV_INFO *>(malloc(len));
+ if (!pinfo) {
+ CertFreeCertificateContext(certContext);
+ return;
+ }
+
+ if (!CertGetCertificateContextProperty(certContext, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
+ CertFreeCertificateContext(certContext);
+ free(pinfo);
+ return;
+ }
+
+ CertFreeCertificateContext(certContext);
+
+ // Now verify if we have access to the private key
+ if (!CryptAcquireContextW(&hprov, pinfo->pwszContainerName, pinfo->pwszProvName, pinfo->dwProvType, 0)) {
+ free(pinfo);
+ return;
+ }
+
+
+ char smartCardReader[1024];
+ DWORD bufferLength = sizeof(smartCardReader);
+ if (!CryptGetProvParam(hprov, PP_SMARTCARD_READER, (BYTE *)&smartCardReader, &bufferLength, 0)) {
+ DWORD error = GetLastError();
+ smartCardReaderName_ = "";
+ }
+ else {
+ smartCardReaderName_ = smartCardReader;
+
+ LONG result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &scardContext_);
+ DEBUG_SCARD_STATUS("SCardEstablishContext", result);
+ if (SCARD_S_SUCCESS == result) {
+ // Initiate monitoring for smartcard ejection
+ smartCardTimer_ = timerFactory_->createTimer(SMARTCARD_EJECTION_CHECK_FREQUENCY_MILLISECONDS);
+ }
+ else {
+ ///Need to handle an error here
+ }
+ }
+
+ if (!CryptGetUserKey(hprov, pinfo->dwKeySpec, &key)) {
+ CryptReleaseContext(hprov, 0);
+ free(pinfo);
+ return;
+ }
+
+ CryptDestroyKey(key);
+ CryptReleaseContext(hprov, 0);
+ free(pinfo);
+
+ if (smartCardTimer_) {
+ smartCardTimer_->onTick.connect(boost::bind(&CAPICertificate::handleSmartCardTimerTick, this));
+ smartCardTimer_->start();
+ }
+
+ valid_ = true;
}
static void smartcard_check_status (SCARDCONTEXT hContext,
- const char* pReader,
- SCARDHANDLE hCardHandle, /* Can be 0 on the first call */
- SCARDHANDLE* newCardHandle, /* The handle returned */
- DWORD* pdwState) {
- DWORD shareMode = SCARD_SHARE_SHARED;
- DWORD preferredProtocols = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1;
- DWORD dwAP;
- LONG result;
-
- if (hCardHandle == 0) {
- result = SCardConnect(hContext, pReader, shareMode, preferredProtocols, &hCardHandle, &dwAP);
- DEBUG_SCARD_STATUS("SCardConnect", result);
- if (SCARD_S_SUCCESS != result) {
- hCardHandle = 0;
- }
- }
-
- char szReader[200];
- DWORD cch = sizeof(szReader);
- BYTE bAttr[32];
- DWORD cByte = 32;
- size_t countStatusAttempts = 0;
-
- while (hCardHandle && (countStatusAttempts < 2)) {
- *pdwState = SCARD_UNKNOWN;
-
- result = SCardStatus(hCardHandle, /* Unfortunately we can't use NULL here */ szReader, &cch, pdwState, NULL, (LPBYTE)&bAttr, &cByte);
- DEBUG_SCARD_STATUS("SCardStatus", result);
- countStatusAttempts++;
-
- if ((SCARD_W_RESET_CARD == result) && (countStatusAttempts < 2)) {
- result = SCardReconnect(hCardHandle, shareMode, preferredProtocols, SCARD_RESET_CARD, &dwAP);
- DEBUG_SCARD_STATUS("SCardReconnect", result);
- if (SCARD_S_SUCCESS != result) {
- break;
- }
- }
- else {
- break;
- }
- }
-
- if (SCARD_S_SUCCESS != result) {
- if (SCARD_E_NO_SMARTCARD == result || SCARD_W_REMOVED_CARD == result) {
- *pdwState = SCARD_ABSENT;
- }
- else {
- *pdwState = SCARD_UNKNOWN;
- }
- }
-
- if (newCardHandle == NULL) {
- result = SCardDisconnect(hCardHandle, SCARD_LEAVE_CARD);
- DEBUG_SCARD_STATUS("SCardDisconnect", result);
- }
- else {
- *newCardHandle = hCardHandle;
- }
+ const char* pReader,
+ SCARDHANDLE hCardHandle, /* Can be 0 on the first call */
+ SCARDHANDLE* newCardHandle, /* The handle returned */
+ DWORD* pdwState) {
+ DWORD shareMode = SCARD_SHARE_SHARED;
+ DWORD preferredProtocols = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1;
+ DWORD dwAP;
+ LONG result;
+
+ if (hCardHandle == 0) {
+ result = SCardConnect(hContext, pReader, shareMode, preferredProtocols, &hCardHandle, &dwAP);
+ DEBUG_SCARD_STATUS("SCardConnect", result);
+ if (SCARD_S_SUCCESS != result) {
+ hCardHandle = 0;
+ }
+ }
+
+ char szReader[200];
+ DWORD cch = sizeof(szReader);
+ BYTE bAttr[32];
+ DWORD cByte = 32;
+ size_t countStatusAttempts = 0;
+
+ while (hCardHandle && (countStatusAttempts < 2)) {
+ *pdwState = SCARD_UNKNOWN;
+
+ result = SCardStatus(hCardHandle, /* Unfortunately we can't use NULL here */ szReader, &cch, pdwState, NULL, (LPBYTE)&bAttr, &cByte);
+ DEBUG_SCARD_STATUS("SCardStatus", result);
+ countStatusAttempts++;
+
+ if ((SCARD_W_RESET_CARD == result) && (countStatusAttempts < 2)) {
+ result = SCardReconnect(hCardHandle, shareMode, preferredProtocols, SCARD_RESET_CARD, &dwAP);
+ DEBUG_SCARD_STATUS("SCardReconnect", result);
+ if (SCARD_S_SUCCESS != result) {
+ break;
+ }
+ }
+ else {
+ break;
+ }
+ }
+
+ if (SCARD_S_SUCCESS != result) {
+ if (SCARD_E_NO_SMARTCARD == result || SCARD_W_REMOVED_CARD == result) {
+ *pdwState = SCARD_ABSENT;
+ }
+ else {
+ *pdwState = SCARD_UNKNOWN;
+ }
+ }
+
+ if (newCardHandle == NULL) {
+ result = SCardDisconnect(hCardHandle, SCARD_LEAVE_CARD);
+ DEBUG_SCARD_STATUS("SCardDisconnect", result);
+ }
+ else {
+ *newCardHandle = hCardHandle;
+ }
}
bool CAPICertificate::checkIfSmartCardPresent () {
- if (!smartCardReaderName_.empty()) {
- DWORD dwState;
- smartcard_check_status(scardContext_, smartCardReaderName_.c_str(), cardHandle_, &cardHandle_, &dwState);
-
- switch (dwState) {
- case SCARD_ABSENT:
- SWIFT_LOG(debug) << "Card absent." << std::endl;
- break;
- case SCARD_PRESENT:
- SWIFT_LOG(debug) << "Card present." << std::endl;
- break;
- case SCARD_SWALLOWED:
- SWIFT_LOG(debug) << "Card swallowed." << std::endl;
- break;
- case SCARD_POWERED:
- SWIFT_LOG(debug) << "Card has power." << std::endl;
- break;
- case SCARD_NEGOTIABLE:
- SWIFT_LOG(debug) << "Card reset and waiting PTS negotiation." << std::endl;
- break;
- case SCARD_SPECIFIC:
- SWIFT_LOG(debug) << "Card has specific communication protocols set." << std::endl;
- break;
- default:
- SWIFT_LOG(debug) << "Unknown or unexpected card state." << std::endl;
- break;
- }
-
-
-
- switch (dwState) {
- case SCARD_ABSENT:
- return false;
-
- case SCARD_PRESENT:
- case SCARD_SWALLOWED:
- case SCARD_POWERED:
- case SCARD_NEGOTIABLE:
- case SCARD_SPECIFIC:
- return true;
-
- default:
- return false;
- }
- }
- else {
- return false;
- }
+ if (!smartCardReaderName_.empty()) {
+ DWORD dwState;
+ smartcard_check_status(scardContext_, smartCardReaderName_.c_str(), cardHandle_, &cardHandle_, &dwState);
+
+ switch (dwState) {
+ case SCARD_ABSENT:
+ SWIFT_LOG(debug) << "Card absent." << std::endl;
+ break;
+ case SCARD_PRESENT:
+ SWIFT_LOG(debug) << "Card present." << std::endl;
+ break;
+ case SCARD_SWALLOWED:
+ SWIFT_LOG(debug) << "Card swallowed." << std::endl;
+ break;
+ case SCARD_POWERED:
+ SWIFT_LOG(debug) << "Card has power." << std::endl;
+ break;
+ case SCARD_NEGOTIABLE:
+ SWIFT_LOG(debug) << "Card reset and waiting PTS negotiation." << std::endl;
+ break;
+ case SCARD_SPECIFIC:
+ SWIFT_LOG(debug) << "Card has specific communication protocols set." << std::endl;
+ break;
+ default:
+ SWIFT_LOG(debug) << "Unknown or unexpected card state." << std::endl;
+ break;
+ }
+
+
+
+ switch (dwState) {
+ case SCARD_ABSENT:
+ return false;
+
+ case SCARD_PRESENT:
+ case SCARD_SWALLOWED:
+ case SCARD_POWERED:
+ case SCARD_NEGOTIABLE:
+ case SCARD_SPECIFIC:
+ return true;
+
+ default:
+ return false;
+ }
+ }
+ else {
+ return false;
+ }
}
void CAPICertificate::handleSmartCardTimerTick() {
- bool poll = checkIfSmartCardPresent();
- if (lastPollingResult_ && !poll) {
- onCertificateCardRemoved();
- }
- lastPollingResult_ = poll;
- smartCardTimer_->start();
+ bool poll = checkIfSmartCardPresent();
+ if (lastPollingResult_ && !poll) {
+ onCertificateCardRemoved();
+ }
+ lastPollingResult_ = poll;
+ smartCardTimer_->start();
}
}
diff --git a/Swiften/TLS/CAPICertificate.h b/Swiften/TLS/CAPICertificate.h
index aebfb41..e0b5488 100644
--- a/Swiften/TLS/CAPICertificate.h
+++ b/Swiften/TLS/CAPICertificate.h
@@ -17,52 +17,52 @@
#include <WinCrypt.h>
#include <Winscard.h>
-#define SMARTCARD_EJECTION_CHECK_FREQUENCY_MILLISECONDS 1000
+#define SMARTCARD_EJECTION_CHECK_FREQUENCY_MILLISECONDS 1000
namespace Swift {
- class TimerFactory;
+ class TimerFactory;
- class SWIFTEN_API CAPICertificate : public Swift::CertificateWithKey {
- public:
- CAPICertificate(const std::string& capiUri, TimerFactory* timerFactory);
+ class SWIFTEN_API CAPICertificate : public Swift::CertificateWithKey {
+ public:
+ CAPICertificate(const std::string& capiUri, TimerFactory* timerFactory);
- virtual ~CAPICertificate();
+ virtual ~CAPICertificate();
- virtual bool isNull() const;
+ virtual bool isNull() const;
- const std::string& getCertStoreName() const;
+ const std::string& getCertStoreName() const;
- const std::string& getCertName() const;
+ const std::string& getCertName() const;
- const std::string& getSmartCardReaderName() const;
+ const std::string& getSmartCardReaderName() const;
- public:
- boost::signal<void ()> onCertificateCardRemoved;
+ public:
+ boost::signal<void ()> onCertificateCardRemoved;
- private:
- void setUri (const std::string& capiUri);
+ private:
+ void setUri (const std::string& capiUri);
- void handleSmartCardTimerTick();
+ void handleSmartCardTimerTick();
- bool checkIfSmartCardPresent();
+ bool checkIfSmartCardPresent();
- private:
- bool valid_;
- std::string uri_;
+ private:
+ bool valid_;
+ std::string uri_;
- HCERTSTORE certStoreHandle_;
- SCARDCONTEXT scardContext_;
- SCARDHANDLE cardHandle_;
+ HCERTSTORE certStoreHandle_;
+ SCARDCONTEXT scardContext_;
+ SCARDHANDLE cardHandle_;
- /* Parsed components of the uri_ */
- std::string certStore_;
- std::string certName_;
- std::string smartCardReaderName_;
- boost::shared_ptr<Timer> smartCardTimer_;
- TimerFactory* timerFactory_;
+ /* Parsed components of the uri_ */
+ std::string certStore_;
+ std::string certName_;
+ std::string smartCardReaderName_;
+ boost::shared_ptr<Timer> smartCardTimer_;
+ TimerFactory* timerFactory_;
- bool lastPollingResult_;
- };
+ bool lastPollingResult_;
+ };
PCCERT_CONTEXT findCertificateInStore (HCERTSTORE certStoreHandle, const std::string &certName);
diff --git a/Swiften/TLS/Certificate.cpp b/Swiften/TLS/Certificate.cpp
index fe84a74..c7d48b2 100644
--- a/Swiften/TLS/Certificate.cpp
+++ b/Swiften/TLS/Certificate.cpp
@@ -20,15 +20,15 @@ Certificate::~Certificate() {
}
std::string Certificate::getSHA1Fingerprint(Certificate::ref certificate, CryptoProvider* crypto) {
- ByteArray hash = crypto->getSHA1Hash(certificate->toDER());
- std::ostringstream s;
- for (size_t i = 0; i < hash.size(); ++i) {
- if (i > 0) {
- s << ":";
- }
- s << Hexify::hexify(hash[i]);
- }
- return std::string(s.str());
+ ByteArray hash = crypto->getSHA1Hash(certificate->toDER());
+ std::ostringstream s;
+ for (size_t i = 0; i < hash.size(); ++i) {
+ if (i > 0) {
+ s << ":";
+ }
+ s << Hexify::hexify(hash[i]);
+ }
+ return std::string(s.str());
}
}
diff --git a/Swiften/TLS/Certificate.h b/Swiften/TLS/Certificate.h
index 00d618e..0b45479 100644
--- a/Swiften/TLS/Certificate.h
+++ b/Swiften/TLS/Certificate.h
@@ -15,32 +15,32 @@
#include <Swiften/Base/ByteArray.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
- class SWIFTEN_API Certificate {
- public:
- typedef boost::shared_ptr<Certificate> ref;
+ class SWIFTEN_API Certificate {
+ public:
+ typedef boost::shared_ptr<Certificate> ref;
- virtual ~Certificate();
+ virtual ~Certificate();
- /**
- * Returns the textual representation of the full Subject
- * name.
- */
- virtual std::string getSubjectName() const = 0;
+ /**
+ * Returns the textual representation of the full Subject
+ * name.
+ */
+ virtual std::string getSubjectName() const = 0;
- virtual std::vector<std::string> getCommonNames() const = 0;
- virtual std::vector<std::string> getSRVNames() const = 0;
- virtual std::vector<std::string> getDNSNames() const = 0;
- virtual std::vector<std::string> getXMPPAddresses() const = 0;
+ virtual std::vector<std::string> getCommonNames() const = 0;
+ virtual std::vector<std::string> getSRVNames() const = 0;
+ virtual std::vector<std::string> getDNSNames() const = 0;
+ virtual std::vector<std::string> getXMPPAddresses() const = 0;
- virtual ByteArray toDER() const = 0;
+ virtual ByteArray toDER() const = 0;
- static std::string getSHA1Fingerprint(Certificate::ref, CryptoProvider* crypto);
+ static std::string getSHA1Fingerprint(Certificate::ref, CryptoProvider* crypto);
- protected:
- static const char* ID_ON_XMPPADDR_OID;
- static const char* ID_ON_DNSSRV_OID;
+ protected:
+ static const char* ID_ON_XMPPADDR_OID;
+ static const char* ID_ON_DNSSRV_OID;
- };
+ };
}
diff --git a/Swiften/TLS/CertificateFactory.h b/Swiften/TLS/CertificateFactory.h
index 28d39bb..522a6e6 100644
--- a/Swiften/TLS/CertificateFactory.h
+++ b/Swiften/TLS/CertificateFactory.h
@@ -10,10 +10,10 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class SWIFTEN_API CertificateFactory {
- public:
- virtual ~CertificateFactory();
+ class SWIFTEN_API CertificateFactory {
+ public:
+ virtual ~CertificateFactory();
- virtual Certificate* createCertificateFromDER(const ByteArray& der) = 0;
- };
+ virtual Certificate* createCertificateFromDER(const ByteArray& der) = 0;
+ };
}
diff --git a/Swiften/TLS/CertificateTrustChecker.h b/Swiften/TLS/CertificateTrustChecker.h
index 77a56f4..bf2b891 100644
--- a/Swiften/TLS/CertificateTrustChecker.h
+++ b/Swiften/TLS/CertificateTrustChecker.h
@@ -15,21 +15,21 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- /**
- * A class to implement a check for certificate trust.
- */
- class SWIFTEN_API CertificateTrustChecker {
- public:
- virtual ~CertificateTrustChecker();
+ /**
+ * A class to implement a check for certificate trust.
+ */
+ class SWIFTEN_API CertificateTrustChecker {
+ public:
+ virtual ~CertificateTrustChecker();
- /**
- * This method is called to find out whether a certificate (chain) is
- * trusted. This usually happens when a certificate's validation
- * fails, to check whether to proceed with the connection or not.
- *
- * certificateChain contains the chain of certificates. The first certificate
- * is the subject certificate.
- */
- virtual bool isCertificateTrusted(const std::vector<Certificate::ref>& certificateChain) = 0;
- };
+ /**
+ * This method is called to find out whether a certificate (chain) is
+ * trusted. This usually happens when a certificate's validation
+ * fails, to check whether to proceed with the connection or not.
+ *
+ * certificateChain contains the chain of certificates. The first certificate
+ * is the subject certificate.
+ */
+ virtual bool isCertificateTrusted(const std::vector<Certificate::ref>& certificateChain) = 0;
+ };
}
diff --git a/Swiften/TLS/CertificateVerificationError.h b/Swiften/TLS/CertificateVerificationError.h
index 9861382..0079e4f 100644
--- a/Swiften/TLS/CertificateVerificationError.h
+++ b/Swiften/TLS/CertificateVerificationError.h
@@ -12,33 +12,33 @@
#include <Swiften/Base/Error.h>
namespace Swift {
- class SWIFTEN_API CertificateVerificationError : public Error {
- public:
- typedef boost::shared_ptr<CertificateVerificationError> ref;
-
- enum Type {
- UnknownError,
- Expired,
- NotYetValid,
- SelfSigned,
- Rejected,
- Untrusted,
- InvalidPurpose,
- PathLengthExceeded,
- InvalidSignature,
- InvalidCA,
- InvalidServerIdentity,
- Revoked,
- RevocationCheckFailed
- };
-
- CertificateVerificationError(Type type = UnknownError) : type(type) {}
-
- Type getType() const {
- return type;
- }
-
- private:
- Type type;
- };
+ class SWIFTEN_API CertificateVerificationError : public Error {
+ public:
+ typedef boost::shared_ptr<CertificateVerificationError> ref;
+
+ enum Type {
+ UnknownError,
+ Expired,
+ NotYetValid,
+ SelfSigned,
+ Rejected,
+ Untrusted,
+ InvalidPurpose,
+ PathLengthExceeded,
+ InvalidSignature,
+ InvalidCA,
+ InvalidServerIdentity,
+ Revoked,
+ RevocationCheckFailed
+ };
+
+ CertificateVerificationError(Type type = UnknownError) : type(type) {}
+
+ Type getType() const {
+ return type;
+ }
+
+ private:
+ Type type;
+ };
}
diff --git a/Swiften/TLS/CertificateWithKey.h b/Swiften/TLS/CertificateWithKey.h
index 687118a..3d95e5b 100644
--- a/Swiften/TLS/CertificateWithKey.h
+++ b/Swiften/TLS/CertificateWithKey.h
@@ -10,14 +10,14 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class SWIFTEN_API CertificateWithKey {
- public:
- typedef boost::shared_ptr<CertificateWithKey> ref;
- CertificateWithKey() {}
+ class SWIFTEN_API CertificateWithKey {
+ public:
+ typedef boost::shared_ptr<CertificateWithKey> ref;
+ CertificateWithKey() {}
- virtual ~CertificateWithKey() {}
+ virtual ~CertificateWithKey() {}
- virtual bool isNull() const = 0;
+ virtual bool isNull() const = 0;
- };
+ };
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
index fc8dce5..3110813 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
@@ -20,91 +20,91 @@
namespace Swift {
OpenSSLCertificate::OpenSSLCertificate(boost::shared_ptr<X509> cert) : cert(cert) {
- parse();
+ parse();
}
OpenSSLCertificate::OpenSSLCertificate(const ByteArray& der) {
#if OPENSSL_VERSION_NUMBER <= 0x009070cfL
- unsigned char* p = const_cast<unsigned char*>(vecptr(der));
+ unsigned char* p = const_cast<unsigned char*>(vecptr(der));
#else
- const unsigned char* p = vecptr(der);
+ const unsigned char* p = vecptr(der);
#endif
- cert = boost::shared_ptr<X509>(d2i_X509(NULL, &p, der.size()), X509_free);
- if (!cert) {
- SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl;
- }
- parse();
+ cert = boost::shared_ptr<X509>(d2i_X509(NULL, &p, der.size()), X509_free);
+ if (!cert) {
+ SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl;
+ }
+ parse();
}
ByteArray OpenSSLCertificate::toDER() const {
- ByteArray result;
- if (!cert) {
- return result;
- }
- result.resize(i2d_X509(cert.get(), NULL));
- unsigned char* p = vecptr(result);
- i2d_X509(cert.get(), &p);
- return result;
+ ByteArray result;
+ if (!cert) {
+ return result;
+ }
+ result.resize(i2d_X509(cert.get(), NULL));
+ unsigned char* p = vecptr(result);
+ i2d_X509(cert.get(), &p);
+ return result;
}
void OpenSSLCertificate::parse() {
- if (!cert) {
- return;
- }
- // Subject name
- X509_NAME* subjectName = X509_get_subject_name(cert.get());
- if (subjectName) {
- // Subject name
- ByteArray subjectNameData;
- subjectNameData.resize(256);
- X509_NAME_oneline(X509_get_subject_name(cert.get()), reinterpret_cast<char*>(vecptr(subjectNameData)), static_cast<unsigned int>(subjectNameData.size()));
- this->subjectName = byteArrayToString(subjectNameData);
+ if (!cert) {
+ return;
+ }
+ // Subject name
+ X509_NAME* subjectName = X509_get_subject_name(cert.get());
+ if (subjectName) {
+ // Subject name
+ ByteArray subjectNameData;
+ subjectNameData.resize(256);
+ X509_NAME_oneline(X509_get_subject_name(cert.get()), reinterpret_cast<char*>(vecptr(subjectNameData)), static_cast<unsigned int>(subjectNameData.size()));
+ this->subjectName = byteArrayToString(subjectNameData);
- // Common name
- int cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, -1);
- while (cnLoc != -1) {
- X509_NAME_ENTRY* cnEntry = X509_NAME_get_entry(subjectName, cnLoc);
- ASN1_STRING* cnData = X509_NAME_ENTRY_get_data(cnEntry);
- commonNames.push_back(byteArrayToString(createByteArray(reinterpret_cast<const char*>(cnData->data), cnData->length)));
- cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, cnLoc);
- }
- }
+ // Common name
+ int cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, -1);
+ while (cnLoc != -1) {
+ X509_NAME_ENTRY* cnEntry = X509_NAME_get_entry(subjectName, cnLoc);
+ ASN1_STRING* cnData = X509_NAME_ENTRY_get_data(cnEntry);
+ commonNames.push_back(byteArrayToString(createByteArray(reinterpret_cast<const char*>(cnData->data), cnData->length)));
+ cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, cnLoc);
+ }
+ }
- // subjectAltNames
- int subjectAltNameLoc = X509_get_ext_by_NID(cert.get(), NID_subject_alt_name, -1);
- if(subjectAltNameLoc != -1) {
- X509_EXTENSION* extension = X509_get_ext(cert.get(), subjectAltNameLoc);
- boost::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
- boost::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
- boost::shared_ptr<ASN1_OBJECT> dnsSRVObject(OBJ_txt2obj(ID_ON_DNSSRV_OID, 1), ASN1_OBJECT_free);
- for (int i = 0; i < sk_GENERAL_NAME_num(generalNames.get()); ++i) {
- GENERAL_NAME* generalName = sk_GENERAL_NAME_value(generalNames.get(), i);
- if (generalName->type == GEN_OTHERNAME) {
- OTHERNAME* otherName = generalName->d.otherName;
- if (OBJ_cmp(otherName->type_id, xmppAddrObject.get()) == 0) {
- // XmppAddr
- if (otherName->value->type != V_ASN1_UTF8STRING) {
- continue;
- }
- ASN1_UTF8STRING* xmppAddrValue = otherName->value->value.utf8string;
- addXMPPAddress(byteArrayToString(createByteArray(reinterpret_cast<const char*>(ASN1_STRING_data(xmppAddrValue)), ASN1_STRING_length(xmppAddrValue))));
- }
- else if (OBJ_cmp(otherName->type_id, dnsSRVObject.get()) == 0) {
- // SRVName
- if (otherName->value->type != V_ASN1_IA5STRING) {
- continue;
- }
- ASN1_IA5STRING* srvNameValue = otherName->value->value.ia5string;
- addSRVName(byteArrayToString(createByteArray(reinterpret_cast<const char*>(ASN1_STRING_data(srvNameValue)), ASN1_STRING_length(srvNameValue))));
- }
- }
- else if (generalName->type == GEN_DNS) {
- // DNSName
- addDNSName(byteArrayToString(createByteArray(ASN1_STRING_data(generalName->d.dNSName), ASN1_STRING_length(generalName->d.dNSName))));
- }
- }
- }
+ // subjectAltNames
+ int subjectAltNameLoc = X509_get_ext_by_NID(cert.get(), NID_subject_alt_name, -1);
+ if(subjectAltNameLoc != -1) {
+ X509_EXTENSION* extension = X509_get_ext(cert.get(), subjectAltNameLoc);
+ boost::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
+ boost::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
+ boost::shared_ptr<ASN1_OBJECT> dnsSRVObject(OBJ_txt2obj(ID_ON_DNSSRV_OID, 1), ASN1_OBJECT_free);
+ for (int i = 0; i < sk_GENERAL_NAME_num(generalNames.get()); ++i) {
+ GENERAL_NAME* generalName = sk_GENERAL_NAME_value(generalNames.get(), i);
+ if (generalName->type == GEN_OTHERNAME) {
+ OTHERNAME* otherName = generalName->d.otherName;
+ if (OBJ_cmp(otherName->type_id, xmppAddrObject.get()) == 0) {
+ // XmppAddr
+ if (otherName->value->type != V_ASN1_UTF8STRING) {
+ continue;
+ }
+ ASN1_UTF8STRING* xmppAddrValue = otherName->value->value.utf8string;
+ addXMPPAddress(byteArrayToString(createByteArray(reinterpret_cast<const char*>(ASN1_STRING_data(xmppAddrValue)), ASN1_STRING_length(xmppAddrValue))));
+ }
+ else if (OBJ_cmp(otherName->type_id, dnsSRVObject.get()) == 0) {
+ // SRVName
+ if (otherName->value->type != V_ASN1_IA5STRING) {
+ continue;
+ }
+ ASN1_IA5STRING* srvNameValue = otherName->value->value.ia5string;
+ addSRVName(byteArrayToString(createByteArray(reinterpret_cast<const char*>(ASN1_STRING_data(srvNameValue)), ASN1_STRING_length(srvNameValue))));
+ }
+ }
+ else if (generalName->type == GEN_DNS) {
+ // DNSName
+ addDNSName(byteArrayToString(createByteArray(ASN1_STRING_data(generalName->d.dNSName), ASN1_STRING_length(generalName->d.dNSName))));
+ }
+ }
+ }
}
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.h b/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
index 7419849..4b8b32c 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
@@ -15,58 +15,58 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class OpenSSLCertificate : public Certificate {
- public:
- OpenSSLCertificate(boost::shared_ptr<X509>);
- OpenSSLCertificate(const ByteArray& der);
-
- std::string getSubjectName() const {
- return subjectName;
- }
-
- std::vector<std::string> getCommonNames() const {
- return commonNames;
- }
-
- std::vector<std::string> getSRVNames() const {
- return srvNames;
- }
-
- std::vector<std::string> getDNSNames() const {
- return dnsNames;
- }
-
- std::vector<std::string> getXMPPAddresses() const {
- return xmppAddresses;
- }
-
- ByteArray toDER() const;
-
- boost::shared_ptr<X509> getInternalX509() const {
- return cert;
- }
-
- private:
- void parse();
-
- void addSRVName(const std::string& name) {
- srvNames.push_back(name);
- }
-
- void addDNSName(const std::string& name) {
- dnsNames.push_back(name);
- }
-
- void addXMPPAddress(const std::string& addr) {
- xmppAddresses.push_back(addr);
- }
-
- private:
- boost::shared_ptr<X509> cert;
- std::string subjectName;
- std::vector<std::string> commonNames;
- std::vector<std::string> dnsNames;
- std::vector<std::string> xmppAddresses;
- std::vector<std::string> srvNames;
- };
+ class OpenSSLCertificate : public Certificate {
+ public:
+ OpenSSLCertificate(boost::shared_ptr<X509>);
+ OpenSSLCertificate(const ByteArray& der);
+
+ std::string getSubjectName() const {
+ return subjectName;
+ }
+
+ std::vector<std::string> getCommonNames() const {
+ return commonNames;
+ }
+
+ std::vector<std::string> getSRVNames() const {
+ return srvNames;
+ }
+
+ std::vector<std::string> getDNSNames() const {
+ return dnsNames;
+ }
+
+ std::vector<std::string> getXMPPAddresses() const {
+ return xmppAddresses;
+ }
+
+ ByteArray toDER() const;
+
+ boost::shared_ptr<X509> getInternalX509() const {
+ return cert;
+ }
+
+ private:
+ void parse();
+
+ void addSRVName(const std::string& name) {
+ srvNames.push_back(name);
+ }
+
+ void addDNSName(const std::string& name) {
+ dnsNames.push_back(name);
+ }
+
+ void addXMPPAddress(const std::string& addr) {
+ xmppAddresses.push_back(addr);
+ }
+
+ private:
+ boost::shared_ptr<X509> cert;
+ std::string subjectName;
+ std::vector<std::string> commonNames;
+ std::vector<std::string> dnsNames;
+ std::vector<std::string> xmppAddresses;
+ std::vector<std::string> srvNames;
+ };
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
index bb8780e..c996cd5 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
@@ -10,10 +10,10 @@
#include <Swiften/TLS/OpenSSL/OpenSSLCertificate.h>
namespace Swift {
- class OpenSSLCertificateFactory : public CertificateFactory {
- public:
- virtual Certificate* createCertificateFromDER(const ByteArray& der) {
- return new OpenSSLCertificate(der);
- }
- };
+ class OpenSSLCertificateFactory : public CertificateFactory {
+ public:
+ virtual Certificate* createCertificateFromDER(const ByteArray& der) {
+ return new OpenSSLCertificate(der);
+ }
+ };
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
index a3e0e1d..cc420e6 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
@@ -36,302 +36,302 @@ static const int MAX_FINISHED_SIZE = 4096;
static const int SSL_READ_BUFFERSIZE = 8192;
static void freeX509Stack(STACK_OF(X509)* stack) {
- sk_X509_free(stack);
+ sk_X509_free(stack);
}
OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readBIO_(0), writeBIO_(0) {
- ensureLibraryInitialized();
- context_ = SSL_CTX_new(SSLv23_client_method());
- SSL_CTX_set_options(context_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
+ ensureLibraryInitialized();
+ context_ = SSL_CTX_new(SSLv23_client_method());
+ SSL_CTX_set_options(context_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
- // TODO: implement CRL checking
- // TODO: download CRL (HTTP transport)
- // TODO: cache CRL downloads for configurable time period
+ // TODO: implement CRL checking
+ // TODO: download CRL (HTTP transport)
+ // TODO: cache CRL downloads for configurable time period
- // TODO: implement OCSP support
- // TODO: handle OCSP stapling see https://www.rfc-editor.org/rfc/rfc4366.txt
- // Load system certs
+ // TODO: implement OCSP support
+ // TODO: handle OCSP stapling see https://www.rfc-editor.org/rfc/rfc4366.txt
+ // Load system certs
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- X509_STORE* store = SSL_CTX_get_cert_store(context_);
- HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
- if (systemStore) {
- PCCERT_CONTEXT certContext = NULL;
- while (true) {
- certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext);
- if (!certContext) {
- break;
- }
- OpenSSLCertificate cert(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded));
- if (store && cert.getInternalX509()) {
- X509_STORE_add_cert(store, cert.getInternalX509().get());
- }
- }
- }
+ X509_STORE* store = SSL_CTX_get_cert_store(context_);
+ HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
+ if (systemStore) {
+ PCCERT_CONTEXT certContext = NULL;
+ while (true) {
+ certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext);
+ if (!certContext) {
+ break;
+ }
+ OpenSSLCertificate cert(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded));
+ if (store && cert.getInternalX509()) {
+ X509_STORE_add_cert(store, cert.getInternalX509().get());
+ }
+ }
+ }
#elif !defined(SWIFTEN_PLATFORM_MACOSX)
- SSL_CTX_load_verify_locations(context_, NULL, "/etc/ssl/certs");
+ SSL_CTX_load_verify_locations(context_, NULL, "/etc/ssl/certs");
#elif defined(SWIFTEN_PLATFORM_MACOSX) && !defined(SWIFTEN_PLATFORM_IPHONE)
- // On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store.
- // On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust.
- // However, if there is a certificate error, it will always emit the "Invalid CA" error if we didn't add
- // the certificates first. See
- // http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c
- // to understand why. We therefore add all certs from the system store ourselves.
- X509_STORE* store = SSL_CTX_get_cert_store(context_);
- CFArrayRef anchorCertificates;
- if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) {
- for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) {
- SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(anchorCertificates, i)));
- CSSM_DATA certCSSMData;
- if (SecCertificateGetData(cert, &certCSSMData) != 0 || certCSSMData.Length == 0) {
- continue;
- }
- std::vector<unsigned char> certData;
- certData.resize(certCSSMData.Length);
- memcpy(&certData[0], certCSSMData.Data, certCSSMData.Length);
- OpenSSLCertificate certificate(certData);
- if (store && certificate.getInternalX509()) {
- X509_STORE_add_cert(store, certificate.getInternalX509().get());
- }
- }
- CFRelease(anchorCertificates);
- }
+ // On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store.
+ // On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust.
+ // However, if there is a certificate error, it will always emit the "Invalid CA" error if we didn't add
+ // the certificates first. See
+ // http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c
+ // to understand why. We therefore add all certs from the system store ourselves.
+ X509_STORE* store = SSL_CTX_get_cert_store(context_);
+ CFArrayRef anchorCertificates;
+ if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) {
+ for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) {
+ SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(anchorCertificates, i)));
+ CSSM_DATA certCSSMData;
+ if (SecCertificateGetData(cert, &certCSSMData) != 0 || certCSSMData.Length == 0) {
+ continue;
+ }
+ std::vector<unsigned char> certData;
+ certData.resize(certCSSMData.Length);
+ memcpy(&certData[0], certCSSMData.Data, certCSSMData.Length);
+ OpenSSLCertificate certificate(certData);
+ if (store && certificate.getInternalX509()) {
+ X509_STORE_add_cert(store, certificate.getInternalX509().get());
+ }
+ }
+ CFRelease(anchorCertificates);
+ }
#endif
}
OpenSSLContext::~OpenSSLContext() {
- SSL_free(handle_);
- SSL_CTX_free(context_);
+ SSL_free(handle_);
+ SSL_CTX_free(context_);
}
void OpenSSLContext::ensureLibraryInitialized() {
- static bool isLibraryInitialized = false;
- if (!isLibraryInitialized) {
- SSL_load_error_strings();
- SSL_library_init();
- OpenSSL_add_all_algorithms();
-
- // Disable compression
- /*
- STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods();
- sk_SSL_COMP_zero(compressionMethods);*/
-
- isLibraryInitialized = true;
- }
+ static bool isLibraryInitialized = false;
+ if (!isLibraryInitialized) {
+ SSL_load_error_strings();
+ SSL_library_init();
+ OpenSSL_add_all_algorithms();
+
+ // Disable compression
+ /*
+ STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods();
+ sk_SSL_COMP_zero(compressionMethods);*/
+
+ isLibraryInitialized = true;
+ }
}
void OpenSSLContext::connect() {
- handle_ = SSL_new(context_);
- // Ownership of BIOs is ransferred
- readBIO_ = BIO_new(BIO_s_mem());
- writeBIO_ = BIO_new(BIO_s_mem());
- SSL_set_bio(handle_, readBIO_, writeBIO_);
-
- state_ = Connecting;
- doConnect();
+ handle_ = SSL_new(context_);
+ // Ownership of BIOs is ransferred
+ readBIO_ = BIO_new(BIO_s_mem());
+ writeBIO_ = BIO_new(BIO_s_mem());
+ SSL_set_bio(handle_, readBIO_, writeBIO_);
+
+ state_ = Connecting;
+ doConnect();
}
void OpenSSLContext::doConnect() {
- int connectResult = SSL_connect(handle_);
- int error = SSL_get_error(handle_, connectResult);
- switch (error) {
- case SSL_ERROR_NONE: {
- state_ = Connected;
- //std::cout << x->name << std::endl;
- //const char* comp = SSL_get_current_compression(handle_);
- //std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl;
- onConnected();
- break;
- }
- case SSL_ERROR_WANT_READ:
- sendPendingDataToNetwork();
- break;
- default:
- state_ = Error;
- onError(boost::make_shared<TLSError>());
- }
+ int connectResult = SSL_connect(handle_);
+ int error = SSL_get_error(handle_, connectResult);
+ switch (error) {
+ case SSL_ERROR_NONE: {
+ state_ = Connected;
+ //std::cout << x->name << std::endl;
+ //const char* comp = SSL_get_current_compression(handle_);
+ //std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl;
+ onConnected();
+ break;
+ }
+ case SSL_ERROR_WANT_READ:
+ sendPendingDataToNetwork();
+ break;
+ default:
+ state_ = Error;
+ onError(boost::make_shared<TLSError>());
+ }
}
void OpenSSLContext::sendPendingDataToNetwork() {
- int size = BIO_pending(writeBIO_);
- if (size > 0) {
- SafeByteArray data;
- data.resize(size);
- BIO_read(writeBIO_, vecptr(data), size);
- onDataForNetwork(data);
- }
+ int size = BIO_pending(writeBIO_);
+ if (size > 0) {
+ SafeByteArray data;
+ data.resize(size);
+ BIO_read(writeBIO_, vecptr(data), size);
+ onDataForNetwork(data);
+ }
}
void OpenSSLContext::handleDataFromNetwork(const SafeByteArray& data) {
- BIO_write(readBIO_, vecptr(data), data.size());
- switch (state_) {
- case Connecting:
- doConnect();
- break;
- case Connected:
- sendPendingDataToApplication();
- break;
- case Start: assert(false); break;
- case Error: /*assert(false);*/ break;
- }
+ BIO_write(readBIO_, vecptr(data), data.size());
+ switch (state_) {
+ case Connecting:
+ doConnect();
+ break;
+ case Connected:
+ sendPendingDataToApplication();
+ break;
+ case Start: assert(false); break;
+ case Error: /*assert(false);*/ break;
+ }
}
void OpenSSLContext::handleDataFromApplication(const SafeByteArray& data) {
- if (SSL_write(handle_, vecptr(data), data.size()) >= 0) {
- sendPendingDataToNetwork();
- }
- else {
- state_ = Error;
- onError(boost::make_shared<TLSError>());
- }
+ if (SSL_write(handle_, vecptr(data), data.size()) >= 0) {
+ sendPendingDataToNetwork();
+ }
+ else {
+ state_ = Error;
+ onError(boost::make_shared<TLSError>());
+ }
}
void OpenSSLContext::sendPendingDataToApplication() {
- SafeByteArray data;
- data.resize(SSL_READ_BUFFERSIZE);
- int ret = SSL_read(handle_, vecptr(data), data.size());
- while (ret > 0) {
- data.resize(ret);
- onDataForApplication(data);
- data.resize(SSL_READ_BUFFERSIZE);
- ret = SSL_read(handle_, vecptr(data), data.size());
- }
- if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
- state_ = Error;
- onError(boost::make_shared<TLSError>());
- }
+ SafeByteArray data;
+ data.resize(SSL_READ_BUFFERSIZE);
+ int ret = SSL_read(handle_, vecptr(data), data.size());
+ while (ret > 0) {
+ data.resize(ret);
+ onDataForApplication(data);
+ data.resize(SSL_READ_BUFFERSIZE);
+ ret = SSL_read(handle_, vecptr(data), data.size());
+ }
+ if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
+ state_ = Error;
+ onError(boost::make_shared<TLSError>());
+ }
}
bool OpenSSLContext::setClientCertificate(CertificateWithKey::ref certificate) {
- boost::shared_ptr<PKCS12Certificate> pkcs12Certificate = boost::dynamic_pointer_cast<PKCS12Certificate>(certificate);
- if (!pkcs12Certificate || pkcs12Certificate->isNull()) {
- return false;
- }
-
- // Create a PKCS12 structure
- BIO* bio = BIO_new(BIO_s_mem());
- BIO_write(bio, vecptr(pkcs12Certificate->getData()), pkcs12Certificate->getData().size());
- boost::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free);
- BIO_free(bio);
- if (!pkcs12) {
- return false;
- }
-
- // Parse PKCS12
- X509 *certPtr = 0;
- EVP_PKEY* privateKeyPtr = 0;
- STACK_OF(X509)* caCertsPtr = 0;
- SafeByteArray password(pkcs12Certificate->getPassword());
- password.push_back(0);
- int result = PKCS12_parse(pkcs12.get(), reinterpret_cast<const char*>(vecptr(password)), &privateKeyPtr, &certPtr, &caCertsPtr);
- if (result != 1) {
- return false;
- }
- boost::shared_ptr<X509> cert(certPtr, X509_free);
- boost::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free);
- boost::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack);
-
- // Use the key & certificates
- if (SSL_CTX_use_certificate(context_, cert.get()) != 1) {
- return false;
- }
- if (SSL_CTX_use_PrivateKey(context_, privateKey.get()) != 1) {
- return false;
- }
- for (int i = 0; i < sk_X509_num(caCerts.get()); ++i) {
- SSL_CTX_add_extra_chain_cert(context_, sk_X509_value(caCerts.get(), i));
- }
- return true;
+ boost::shared_ptr<PKCS12Certificate> pkcs12Certificate = boost::dynamic_pointer_cast<PKCS12Certificate>(certificate);
+ if (!pkcs12Certificate || pkcs12Certificate->isNull()) {
+ return false;
+ }
+
+ // Create a PKCS12 structure
+ BIO* bio = BIO_new(BIO_s_mem());
+ BIO_write(bio, vecptr(pkcs12Certificate->getData()), pkcs12Certificate->getData().size());
+ boost::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free);
+ BIO_free(bio);
+ if (!pkcs12) {
+ return false;
+ }
+
+ // Parse PKCS12
+ X509 *certPtr = 0;
+ EVP_PKEY* privateKeyPtr = 0;
+ STACK_OF(X509)* caCertsPtr = 0;
+ SafeByteArray password(pkcs12Certificate->getPassword());
+ password.push_back(0);
+ int result = PKCS12_parse(pkcs12.get(), reinterpret_cast<const char*>(vecptr(password)), &privateKeyPtr, &certPtr, &caCertsPtr);
+ if (result != 1) {
+ return false;
+ }
+ boost::shared_ptr<X509> cert(certPtr, X509_free);
+ boost::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free);
+ boost::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack);
+
+ // Use the key & certificates
+ if (SSL_CTX_use_certificate(context_, cert.get()) != 1) {
+ return false;
+ }
+ if (SSL_CTX_use_PrivateKey(context_, privateKey.get()) != 1) {
+ return false;
+ }
+ for (int i = 0; i < sk_X509_num(caCerts.get()); ++i) {
+ SSL_CTX_add_extra_chain_cert(context_, sk_X509_value(caCerts.get(), i));
+ }
+ return true;
}
std::vector<Certificate::ref> OpenSSLContext::getPeerCertificateChain() const {
- std::vector<Certificate::ref> result;
- STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_);
- for (int i = 0; i < sk_X509_num(chain); ++i) {
- boost::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free);
-
- Certificate::ref cert = boost::make_shared<OpenSSLCertificate>(x509Cert);
- result.push_back(cert);
- }
- return result;
+ std::vector<Certificate::ref> result;
+ STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_);
+ for (int i = 0; i < sk_X509_num(chain); ++i) {
+ boost::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free);
+
+ Certificate::ref cert = boost::make_shared<OpenSSLCertificate>(x509Cert);
+ result.push_back(cert);
+ }
+ return result;
}
boost::shared_ptr<CertificateVerificationError> OpenSSLContext::getPeerCertificateVerificationError() const {
- int verifyResult = SSL_get_verify_result(handle_);
- if (verifyResult != X509_V_OK) {
- return boost::make_shared<CertificateVerificationError>(getVerificationErrorTypeForResult(verifyResult));
- }
- else {
- return boost::shared_ptr<CertificateVerificationError>();
- }
+ int verifyResult = SSL_get_verify_result(handle_);
+ if (verifyResult != X509_V_OK) {
+ return boost::make_shared<CertificateVerificationError>(getVerificationErrorTypeForResult(verifyResult));
+ }
+ else {
+ return boost::shared_ptr<CertificateVerificationError>();
+ }
}
ByteArray OpenSSLContext::getFinishMessage() const {
- ByteArray data;
- data.resize(MAX_FINISHED_SIZE);
- size_t size = SSL_get_finished(handle_, vecptr(data), data.size());
- data.resize(size);
- return data;
+ ByteArray data;
+ data.resize(MAX_FINISHED_SIZE);
+ size_t size = SSL_get_finished(handle_, vecptr(data), data.size());
+ data.resize(size);
+ return data;
}
CertificateVerificationError::Type OpenSSLContext::getVerificationErrorTypeForResult(int result) {
- assert(result != 0);
- switch (result) {
- case X509_V_ERR_CERT_NOT_YET_VALID:
- case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
- return CertificateVerificationError::NotYetValid;
-
- case X509_V_ERR_CERT_HAS_EXPIRED:
- case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
- return CertificateVerificationError::Expired;
-
- case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
- case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
- return CertificateVerificationError::SelfSigned;
-
- case X509_V_ERR_CERT_UNTRUSTED:
- return CertificateVerificationError::Untrusted;
-
- case X509_V_ERR_CERT_REJECTED:
- return CertificateVerificationError::Rejected;
-
- case X509_V_ERR_INVALID_PURPOSE:
- return CertificateVerificationError::InvalidPurpose;
-
- case X509_V_ERR_PATH_LENGTH_EXCEEDED:
- return CertificateVerificationError::PathLengthExceeded;
-
- case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
- case X509_V_ERR_CERT_SIGNATURE_FAILURE:
- case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
- return CertificateVerificationError::InvalidSignature;
-
- case X509_V_ERR_INVALID_CA:
- case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
- case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
- case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
- return CertificateVerificationError::InvalidCA;
-
- case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
- case X509_V_ERR_AKID_SKID_MISMATCH:
- case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
- case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
- return CertificateVerificationError::UnknownError;
-
- // Unused / should not happen
- case X509_V_ERR_CERT_REVOKED:
- case X509_V_ERR_OUT_OF_MEM:
- case X509_V_ERR_UNABLE_TO_GET_CRL:
- case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
- case X509_V_ERR_CRL_SIGNATURE_FAILURE:
- case X509_V_ERR_CRL_NOT_YET_VALID:
- case X509_V_ERR_CRL_HAS_EXPIRED:
- case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
- case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
- case X509_V_ERR_CERT_CHAIN_TOO_LONG:
- case X509_V_ERR_APPLICATION_VERIFICATION:
- default:
- return CertificateVerificationError::UnknownError;
- }
+ assert(result != 0);
+ switch (result) {
+ case X509_V_ERR_CERT_NOT_YET_VALID:
+ case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
+ return CertificateVerificationError::NotYetValid;
+
+ case X509_V_ERR_CERT_HAS_EXPIRED:
+ case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
+ return CertificateVerificationError::Expired;
+
+ case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
+ case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
+ return CertificateVerificationError::SelfSigned;
+
+ case X509_V_ERR_CERT_UNTRUSTED:
+ return CertificateVerificationError::Untrusted;
+
+ case X509_V_ERR_CERT_REJECTED:
+ return CertificateVerificationError::Rejected;
+
+ case X509_V_ERR_INVALID_PURPOSE:
+ return CertificateVerificationError::InvalidPurpose;
+
+ case X509_V_ERR_PATH_LENGTH_EXCEEDED:
+ return CertificateVerificationError::PathLengthExceeded;
+
+ case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
+ case X509_V_ERR_CERT_SIGNATURE_FAILURE:
+ case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
+ return CertificateVerificationError::InvalidSignature;
+
+ case X509_V_ERR_INVALID_CA:
+ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+ case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
+ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
+ return CertificateVerificationError::InvalidCA;
+
+ case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
+ case X509_V_ERR_AKID_SKID_MISMATCH:
+ case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
+ case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
+ return CertificateVerificationError::UnknownError;
+
+ // Unused / should not happen
+ case X509_V_ERR_CERT_REVOKED:
+ case X509_V_ERR_OUT_OF_MEM:
+ case X509_V_ERR_UNABLE_TO_GET_CRL:
+ case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
+ case X509_V_ERR_CRL_SIGNATURE_FAILURE:
+ case X509_V_ERR_CRL_NOT_YET_VALID:
+ case X509_V_ERR_CRL_HAS_EXPIRED:
+ case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
+ case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
+ case X509_V_ERR_CERT_CHAIN_TOO_LONG:
+ case X509_V_ERR_APPLICATION_VERIFICATION:
+ default:
+ return CertificateVerificationError::UnknownError;
+ }
}
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.h b/Swiften/TLS/OpenSSL/OpenSSLContext.h
index 73fe75c..7fd5af7 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h
@@ -17,38 +17,38 @@
namespace Swift {
- class OpenSSLContext : public TLSContext, boost::noncopyable {
- public:
- OpenSSLContext();
- virtual ~OpenSSLContext();
+ class OpenSSLContext : public TLSContext, boost::noncopyable {
+ public:
+ OpenSSLContext();
+ virtual ~OpenSSLContext();
- void connect();
- bool setClientCertificate(CertificateWithKey::ref cert);
+ void connect();
+ bool setClientCertificate(CertificateWithKey::ref cert);
- void handleDataFromNetwork(const SafeByteArray&);
- void handleDataFromApplication(const SafeByteArray&);
+ void handleDataFromNetwork(const SafeByteArray&);
+ void handleDataFromApplication(const SafeByteArray&);
- std::vector<Certificate::ref> getPeerCertificateChain() const;
- boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+ std::vector<Certificate::ref> getPeerCertificateChain() const;
+ boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
- virtual ByteArray getFinishMessage() const;
+ virtual ByteArray getFinishMessage() const;
- private:
- static void ensureLibraryInitialized();
+ private:
+ static void ensureLibraryInitialized();
- static CertificateVerificationError::Type getVerificationErrorTypeForResult(int);
+ static CertificateVerificationError::Type getVerificationErrorTypeForResult(int);
- void doConnect();
- void sendPendingDataToNetwork();
- void sendPendingDataToApplication();
+ void doConnect();
+ void sendPendingDataToNetwork();
+ void sendPendingDataToApplication();
- private:
- enum State { Start, Connecting, Connected, Error };
+ private:
+ enum State { Start, Connecting, Connected, Error };
- State state_;
- SSL_CTX* context_;
- SSL* handle_;
- BIO* readBIO_;
- BIO* writeBIO_;
- };
+ State state_;
+ SSL_CTX* context_;
+ SSL* handle_;
+ BIO* readBIO_;
+ BIO* writeBIO_;
+ };
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
index ff27b49..9f7b2aa 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
@@ -12,24 +12,24 @@
namespace Swift {
bool OpenSSLContextFactory::canCreate() const {
- return true;
+ return true;
}
TLSContext* OpenSSLContextFactory::createTLSContext(const TLSOptions&) {
- return new OpenSSLContext();
+ return new OpenSSLContext();
}
void OpenSSLContextFactory::setCheckCertificateRevocation(bool check) {
- if (check) {
- SWIFT_LOG(warning) << "CRL Checking not supported for OpenSSL" << std::endl;
- assert(false);
- }
+ if (check) {
+ SWIFT_LOG(warning) << "CRL Checking not supported for OpenSSL" << std::endl;
+ assert(false);
+ }
}
void OpenSSLContextFactory::setDisconnectOnCardRemoval(bool check) {
- if (check) {
- SWIFT_LOG(warning) << "Smart cards not supported for OpenSSL" << std::endl;
- }
+ if (check) {
+ SWIFT_LOG(warning) << "Smart cards not supported for OpenSSL" << std::endl;
+ }
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
index 21f05a4..e121a1a 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
@@ -11,13 +11,13 @@
#include <Swiften/TLS/TLSContextFactory.h>
namespace Swift {
- class OpenSSLContextFactory : public TLSContextFactory {
- public:
- bool canCreate() const;
- virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
+ class OpenSSLContextFactory : public TLSContextFactory {
+ public:
+ bool canCreate() const;
+ virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
- // Not supported
- virtual void setCheckCertificateRevocation(bool b);
- virtual void setDisconnectOnCardRemoval(bool b);
- };
+ // Not supported
+ virtual void setCheckCertificateRevocation(bool b);
+ virtual void setDisconnectOnCardRemoval(bool b);
+ };
}
diff --git a/Swiften/TLS/PKCS12Certificate.h b/Swiften/TLS/PKCS12Certificate.h
index cd2f5cb..4ed5040 100644
--- a/Swiften/TLS/PKCS12Certificate.h
+++ b/Swiften/TLS/PKCS12Certificate.h
@@ -13,50 +13,50 @@
#include <Swiften/TLS/CertificateWithKey.h>
namespace Swift {
- class SWIFTEN_API PKCS12Certificate : public Swift::CertificateWithKey {
- public:
- PKCS12Certificate() {}
+ class SWIFTEN_API PKCS12Certificate : public Swift::CertificateWithKey {
+ public:
+ PKCS12Certificate() {}
- PKCS12Certificate(const boost::filesystem::path& filename, const SafeByteArray& password) : password_(password) {
- readByteArrayFromFile(data_, filename);
- }
+ PKCS12Certificate(const boost::filesystem::path& filename, const SafeByteArray& password) : password_(password) {
+ readByteArrayFromFile(data_, filename);
+ }
- virtual ~PKCS12Certificate() {}
+ virtual ~PKCS12Certificate() {}
- virtual bool isNull() const {
- return data_.empty();
- }
+ virtual bool isNull() const {
+ return data_.empty();
+ }
- virtual bool isPrivateKeyExportable() const {
+ virtual bool isPrivateKeyExportable() const {
/////Hopefully a PKCS12 is never missing a private key
- return true;
- }
-
- virtual const std::string& getCertStoreName() const {
-///// assert(0);
- throw std::exception();
- }
-
- virtual const std::string& getCertName() const {
- /* We can return the original filename instead, if we care */
-///// assert(0);
- throw std::exception();
- }
-
- virtual const ByteArray& getData() const {
- return data_;
- }
-
- void setData(const ByteArray& data) {
- data_ = data;
- }
-
- virtual const SafeByteArray& getPassword() const {
- return password_;
- }
-
- private:
- ByteArray data_;
- SafeByteArray password_;
- };
+ return true;
+ }
+
+ virtual const std::string& getCertStoreName() const {
+///// assert(0);
+ throw std::exception();
+ }
+
+ virtual const std::string& getCertName() const {
+ /* We can return the original filename instead, if we care */
+///// assert(0);
+ throw std::exception();
+ }
+
+ virtual const ByteArray& getData() const {
+ return data_;
+ }
+
+ void setData(const ByteArray& data) {
+ data_ = data;
+ }
+
+ virtual const SafeByteArray& getPassword() const {
+ return password_;
+ }
+
+ private:
+ ByteArray data_;
+ SafeByteArray password_;
+ };
}
diff --git a/Swiften/TLS/PlatformTLSFactories.cpp b/Swiften/TLS/PlatformTLSFactories.cpp
index d776508..c1c0868 100644
--- a/Swiften/TLS/PlatformTLSFactories.cpp
+++ b/Swiften/TLS/PlatformTLSFactories.cpp
@@ -10,46 +10,46 @@
#include <Swiften/TLS/CertificateFactory.h>
#include <Swiften/TLS/TLSContextFactory.h>
#ifdef HAVE_OPENSSL
- #include <Swiften/TLS/OpenSSL/OpenSSLContextFactory.h>
- #include <Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h>
+ #include <Swiften/TLS/OpenSSL/OpenSSLContextFactory.h>
+ #include <Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h>
#endif
#ifdef HAVE_SCHANNEL
- #include <Swiften/TLS/Schannel/SchannelContextFactory.h>
- #include <Swiften/TLS/Schannel/SchannelCertificateFactory.h>
+ #include <Swiften/TLS/Schannel/SchannelContextFactory.h>
+ #include <Swiften/TLS/Schannel/SchannelCertificateFactory.h>
#endif
#ifdef HAVE_SECURETRANSPORT
- #include <Swiften/TLS/SecureTransport/SecureTransportContextFactory.h>
- #include <Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h>
+ #include <Swiften/TLS/SecureTransport/SecureTransportContextFactory.h>
+ #include <Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h>
#endif
namespace Swift {
PlatformTLSFactories::PlatformTLSFactories() : contextFactory(NULL), certificateFactory(NULL) {
#ifdef HAVE_OPENSSL
- contextFactory = new OpenSSLContextFactory();
- certificateFactory = new OpenSSLCertificateFactory();
+ contextFactory = new OpenSSLContextFactory();
+ certificateFactory = new OpenSSLCertificateFactory();
#endif
#ifdef HAVE_SCHANNEL
- contextFactory = new SchannelContextFactory();
- certificateFactory = new SchannelCertificateFactory();
+ contextFactory = new SchannelContextFactory();
+ certificateFactory = new SchannelCertificateFactory();
#endif
#ifdef HAVE_SECURETRANSPORT
- contextFactory = new SecureTransportContextFactory();
- certificateFactory = new SecureTransportCertificateFactory();
-#endif
+ contextFactory = new SecureTransportContextFactory();
+ certificateFactory = new SecureTransportCertificateFactory();
+#endif
}
PlatformTLSFactories::~PlatformTLSFactories() {
- delete contextFactory;
- delete certificateFactory;
+ delete contextFactory;
+ delete certificateFactory;
}
TLSContextFactory* PlatformTLSFactories::getTLSContextFactory() const {
- return contextFactory;
+ return contextFactory;
}
CertificateFactory* PlatformTLSFactories::getCertificateFactory() const {
- return certificateFactory;
+ return certificateFactory;
}
}
diff --git a/Swiften/TLS/PlatformTLSFactories.h b/Swiften/TLS/PlatformTLSFactories.h
index df23b32..3821521 100644
--- a/Swiften/TLS/PlatformTLSFactories.h
+++ b/Swiften/TLS/PlatformTLSFactories.h
@@ -9,19 +9,19 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class TLSContextFactory;
- class CertificateFactory;
+ class TLSContextFactory;
+ class CertificateFactory;
- class SWIFTEN_API PlatformTLSFactories {
- public:
- PlatformTLSFactories();
- ~PlatformTLSFactories();
+ class SWIFTEN_API PlatformTLSFactories {
+ public:
+ PlatformTLSFactories();
+ ~PlatformTLSFactories();
- TLSContextFactory* getTLSContextFactory() const;
- CertificateFactory* getCertificateFactory() const;
+ TLSContextFactory* getTLSContextFactory() const;
+ CertificateFactory* getCertificateFactory() const;
- private:
- TLSContextFactory* contextFactory;
- CertificateFactory* certificateFactory;
- };
+ private:
+ TLSContextFactory* contextFactory;
+ CertificateFactory* certificateFactory;
+ };
}
diff --git a/Swiften/TLS/Schannel/SchannelCertificate.cpp b/Swiften/TLS/Schannel/SchannelCertificate.cpp
index 8aaec00..68dd0cf 100644
--- a/Swiften/TLS/Schannel/SchannelCertificate.cpp
+++ b/Swiften/TLS/Schannel/SchannelCertificate.cpp
@@ -20,176 +20,176 @@ namespace Swift {
//------------------------------------------------------------------------
-SchannelCertificate::SchannelCertificate(const ScopedCertContext& certCtxt)
-: m_cert(certCtxt)
+SchannelCertificate::SchannelCertificate(const ScopedCertContext& certCtxt)
+: m_cert(certCtxt)
{
- parse();
+ parse();
}
//------------------------------------------------------------------------
SchannelCertificate::SchannelCertificate(const ByteArray& der)
{
- if (!der.empty())
- {
- // Convert the DER encoded certificate to a PCERT_CONTEXT
- CERT_BLOB certBlob = {0};
- certBlob.cbData = der.size();
- certBlob.pbData = (BYTE*)&der[0];
-
- if (!CryptQueryObject(
- CERT_QUERY_OBJECT_BLOB,
- &certBlob,
- CERT_QUERY_CONTENT_FLAG_CERT,
- CERT_QUERY_FORMAT_FLAG_ALL,
- 0,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- (const void**)m_cert.Reset()))
- {
- // TODO: Because Swiften isn't exception safe, we have no way to indicate failure
- }
- }
+ if (!der.empty())
+ {
+ // Convert the DER encoded certificate to a PCERT_CONTEXT
+ CERT_BLOB certBlob = {0};
+ certBlob.cbData = der.size();
+ certBlob.pbData = (BYTE*)&der[0];
+
+ if (!CryptQueryObject(
+ CERT_QUERY_OBJECT_BLOB,
+ &certBlob,
+ CERT_QUERY_CONTENT_FLAG_CERT,
+ CERT_QUERY_FORMAT_FLAG_ALL,
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ (const void**)m_cert.Reset()))
+ {
+ // TODO: Because Swiften isn't exception safe, we have no way to indicate failure
+ }
+ }
}
//------------------------------------------------------------------------
-ByteArray SchannelCertificate::toDER() const
+ByteArray SchannelCertificate::toDER() const
{
- ByteArray result;
+ ByteArray result;
- // Serialize the certificate. The CERT_CONTEXT is already DER encoded.
- result.resize(m_cert->cbCertEncoded);
- memcpy(&result[0], m_cert->pbCertEncoded, result.size());
-
- return result;
+ // Serialize the certificate. The CERT_CONTEXT is already DER encoded.
+ result.resize(m_cert->cbCertEncoded);
+ memcpy(&result[0], m_cert->pbCertEncoded, result.size());
+
+ return result;
}
//------------------------------------------------------------------------
std::string SchannelCertificate::wstrToStr(const std::wstring& wstr)
{
- if (wstr.empty())
- return "";
+ if (wstr.empty())
+ return "";
- // First request the size of the required UTF-8 buffer
- int numRequiredBytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
- if (!numRequiredBytes)
- return "";
+ // First request the size of the required UTF-8 buffer
+ int numRequiredBytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
+ if (!numRequiredBytes)
+ return "";
- // Allocate memory for the UTF-8 string
- std::vector<char> utf8Str(numRequiredBytes);
+ // Allocate memory for the UTF-8 string
+ std::vector<char> utf8Str(numRequiredBytes);
- int numConverted = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), &utf8Str[0], numRequiredBytes, NULL, NULL);
- if (!numConverted)
- return "";
+ int numConverted = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), &utf8Str[0], numRequiredBytes, NULL, NULL);
+ if (!numConverted)
+ return "";
- std::string str(&utf8Str[0], numConverted);
- return str;
+ std::string str(&utf8Str[0], numConverted);
+ return str;
}
//------------------------------------------------------------------------
-void SchannelCertificate::parse()
+void SchannelCertificate::parse()
{
- //
- // Subject name
- //
- DWORD requiredSize = CertNameToStr(X509_ASN_ENCODING, &m_cert->pCertInfo->Subject, CERT_OID_NAME_STR, NULL, 0);
- if (requiredSize > 1)
- {
- vector<char> rawSubjectName(requiredSize);
- CertNameToStr(X509_ASN_ENCODING, &m_cert->pCertInfo->Subject, CERT_OID_NAME_STR, &rawSubjectName[0], rawSubjectName.size());
- m_subjectName = std::string(&rawSubjectName[0]);
- }
-
- //
- // Common name
- //
- // Note: We only pull out one common name from the cert.
- requiredSize = CertGetNameString(m_cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, NULL, 0);
- if (requiredSize > 1)
- {
- vector<char> rawCommonName(requiredSize);
- requiredSize = CertGetNameString(m_cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, &rawCommonName[0], rawCommonName.size());
- m_commonNames.push_back( std::string(&rawCommonName[0]) );
- }
-
- //
- // Subject alternative names
- //
- PCERT_EXTENSION pExtensions = CertFindExtension(szOID_SUBJECT_ALT_NAME2, m_cert->pCertInfo->cExtension, m_cert->pCertInfo->rgExtension);
- if (pExtensions)
- {
- CRYPT_DECODE_PARA decodePara = {0};
- decodePara.cbSize = sizeof(decodePara);
-
- CERT_ALT_NAME_INFO* pAltNameInfo = NULL;
- DWORD altNameInfoSize = 0;
-
- BOOL status = CryptDecodeObjectEx(
- X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
- szOID_SUBJECT_ALT_NAME2,
- pExtensions->Value.pbData,
- pExtensions->Value.cbData,
- CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
- &decodePara,
- &pAltNameInfo,
- &altNameInfoSize);
-
- if (status && pAltNameInfo)
- {
- for (int i = 0; i < pAltNameInfo->cAltEntry; i++)
- {
- if (pAltNameInfo->rgAltEntry[i].dwAltNameChoice == CERT_ALT_NAME_DNS_NAME)
- addDNSName( wstrToStr( pAltNameInfo->rgAltEntry[i].pwszDNSName ) );
- }
- }
- }
-
- // if (pExtensions)
- // {
- // vector<wchar_t> subjectAlt
- // CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szOID_SUBJECT_ALT_NAME, pExtensions->Value->pbData, pExtensions->Value->cbData, )
- // }
- //
- // // subjectAltNames
- // int subjectAltNameLoc = X509_get_ext_by_NID(cert.get(), NID_subject_alt_name, -1);
- // if(subjectAltNameLoc != -1) {
- // X509_EXTENSION* extension = X509_get_ext(cert.get(), subjectAltNameLoc);
- // boost::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
- // boost::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
- // boost::shared_ptr<ASN1_OBJECT> dnsSRVObject(OBJ_txt2obj(ID_ON_DNSSRV_OID, 1), ASN1_OBJECT_free);
- // for (int i = 0; i < sk_GENERAL_NAME_num(generalNames.get()); ++i) {
- // GENERAL_NAME* generalName = sk_GENERAL_NAME_value(generalNames.get(), i);
- // if (generalName->type == GEN_OTHERNAME) {
- // OTHERNAME* otherName = generalName->d.otherName;
- // if (OBJ_cmp(otherName->type_id, xmppAddrObject.get()) == 0) {
- // // XmppAddr
- // if (otherName->value->type != V_ASN1_UTF8STRING) {
- // continue;
- // }
- // ASN1_UTF8STRING* xmppAddrValue = otherName->value->value.utf8string;
- // addXMPPAddress(ByteArray(ASN1_STRING_data(xmppAddrValue), ASN1_STRING_length(xmppAddrValue)).toString());
- // }
- // else if (OBJ_cmp(otherName->type_id, dnsSRVObject.get()) == 0) {
- // // SRVName
- // if (otherName->value->type != V_ASN1_IA5STRING) {
- // continue;
- // }
- // ASN1_IA5STRING* srvNameValue = otherName->value->value.ia5string;
- // addSRVName(ByteArray(ASN1_STRING_data(srvNameValue), ASN1_STRING_length(srvNameValue)).toString());
- // }
- // }
- // else if (generalName->type == GEN_DNS) {
- // // DNSName
- // addDNSName(ByteArray(ASN1_STRING_data(generalName->d.dNSName), ASN1_STRING_length(generalName->d.dNSName)).toString());
- // }
- // }
- // }
+ //
+ // Subject name
+ //
+ DWORD requiredSize = CertNameToStr(X509_ASN_ENCODING, &m_cert->pCertInfo->Subject, CERT_OID_NAME_STR, NULL, 0);
+ if (requiredSize > 1)
+ {
+ vector<char> rawSubjectName(requiredSize);
+ CertNameToStr(X509_ASN_ENCODING, &m_cert->pCertInfo->Subject, CERT_OID_NAME_STR, &rawSubjectName[0], rawSubjectName.size());
+ m_subjectName = std::string(&rawSubjectName[0]);
+ }
+
+ //
+ // Common name
+ //
+ // Note: We only pull out one common name from the cert.
+ requiredSize = CertGetNameString(m_cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, NULL, 0);
+ if (requiredSize > 1)
+ {
+ vector<char> rawCommonName(requiredSize);
+ requiredSize = CertGetNameString(m_cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, &rawCommonName[0], rawCommonName.size());
+ m_commonNames.push_back( std::string(&rawCommonName[0]) );
+ }
+
+ //
+ // Subject alternative names
+ //
+ PCERT_EXTENSION pExtensions = CertFindExtension(szOID_SUBJECT_ALT_NAME2, m_cert->pCertInfo->cExtension, m_cert->pCertInfo->rgExtension);
+ if (pExtensions)
+ {
+ CRYPT_DECODE_PARA decodePara = {0};
+ decodePara.cbSize = sizeof(decodePara);
+
+ CERT_ALT_NAME_INFO* pAltNameInfo = NULL;
+ DWORD altNameInfoSize = 0;
+
+ BOOL status = CryptDecodeObjectEx(
+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
+ szOID_SUBJECT_ALT_NAME2,
+ pExtensions->Value.pbData,
+ pExtensions->Value.cbData,
+ CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
+ &decodePara,
+ &pAltNameInfo,
+ &altNameInfoSize);
+
+ if (status && pAltNameInfo)
+ {
+ for (int i = 0; i < pAltNameInfo->cAltEntry; i++)
+ {
+ if (pAltNameInfo->rgAltEntry[i].dwAltNameChoice == CERT_ALT_NAME_DNS_NAME)
+ addDNSName( wstrToStr( pAltNameInfo->rgAltEntry[i].pwszDNSName ) );
+ }
+ }
+ }
+
+ // if (pExtensions)
+ // {
+ // vector<wchar_t> subjectAlt
+ // CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szOID_SUBJECT_ALT_NAME, pExtensions->Value->pbData, pExtensions->Value->cbData, )
+ // }
+ //
+ // // subjectAltNames
+ // int subjectAltNameLoc = X509_get_ext_by_NID(cert.get(), NID_subject_alt_name, -1);
+ // if(subjectAltNameLoc != -1) {
+ // X509_EXTENSION* extension = X509_get_ext(cert.get(), subjectAltNameLoc);
+ // boost::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
+ // boost::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
+ // boost::shared_ptr<ASN1_OBJECT> dnsSRVObject(OBJ_txt2obj(ID_ON_DNSSRV_OID, 1), ASN1_OBJECT_free);
+ // for (int i = 0; i < sk_GENERAL_NAME_num(generalNames.get()); ++i) {
+ // GENERAL_NAME* generalName = sk_GENERAL_NAME_value(generalNames.get(), i);
+ // if (generalName->type == GEN_OTHERNAME) {
+ // OTHERNAME* otherName = generalName->d.otherName;
+ // if (OBJ_cmp(otherName->type_id, xmppAddrObject.get()) == 0) {
+ // // XmppAddr
+ // if (otherName->value->type != V_ASN1_UTF8STRING) {
+ // continue;
+ // }
+ // ASN1_UTF8STRING* xmppAddrValue = otherName->value->value.utf8string;
+ // addXMPPAddress(ByteArray(ASN1_STRING_data(xmppAddrValue), ASN1_STRING_length(xmppAddrValue)).toString());
+ // }
+ // else if (OBJ_cmp(otherName->type_id, dnsSRVObject.get()) == 0) {
+ // // SRVName
+ // if (otherName->value->type != V_ASN1_IA5STRING) {
+ // continue;
+ // }
+ // ASN1_IA5STRING* srvNameValue = otherName->value->value.ia5string;
+ // addSRVName(ByteArray(ASN1_STRING_data(srvNameValue), ASN1_STRING_length(srvNameValue)).toString());
+ // }
+ // }
+ // else if (generalName->type == GEN_DNS) {
+ // // DNSName
+ // addDNSName(ByteArray(ASN1_STRING_data(generalName->d.dNSName), ASN1_STRING_length(generalName->d.dNSName)).toString());
+ // }
+ // }
+ // }
}
//------------------------------------------------------------------------
diff --git a/Swiften/TLS/Schannel/SchannelCertificate.h b/Swiften/TLS/Schannel/SchannelCertificate.h
index 0f4e9c1..814f344 100644
--- a/Swiften/TLS/Schannel/SchannelCertificate.h
+++ b/Swiften/TLS/Schannel/SchannelCertificate.h
@@ -18,75 +18,75 @@
#include <Swiften/TLS/Certificate.h>
#include <Swiften/TLS/Schannel/SchannelUtil.h>
-namespace Swift
+namespace Swift
{
- class SchannelCertificate : public Certificate
- {
- public:
- typedef boost::shared_ptr<SchannelCertificate> ref;
-
- public:
- SchannelCertificate(const ScopedCertContext& certCtxt);
- SchannelCertificate(const ByteArray& der);
-
- std::string getSubjectName() const
- {
- return m_subjectName;
- }
-
- std::vector<std::string> getCommonNames() const
- {
- return m_commonNames;
- }
-
- std::vector<std::string> getSRVNames() const
- {
- return m_srvNames;
- }
-
- std::vector<std::string> getDNSNames() const
- {
- return m_dnsNames;
- }
-
- std::vector<std::string> getXMPPAddresses() const
- {
- return m_xmppAddresses;
- }
-
- ScopedCertContext getCertContext() const
- {
- return m_cert;
- }
-
- ByteArray toDER() const;
-
- private:
- void parse();
- std::string wstrToStr(const std::wstring& wstr);
-
- void addSRVName(const std::string& name)
- {
- m_srvNames.push_back(name);
- }
-
- void addDNSName(const std::string& name)
- {
- m_dnsNames.push_back(name);
- }
-
- void addXMPPAddress(const std::string& addr)
- {
- m_xmppAddresses.push_back(addr);
- }
-
- private:
- ScopedCertContext m_cert;
-
- std::string m_subjectName;
- std::vector<std::string> m_commonNames;
- std::vector<std::string> m_dnsNames;
- std::vector<std::string> m_xmppAddresses;
- std::vector<std::string> m_srvNames;
- };
+ class SchannelCertificate : public Certificate
+ {
+ public:
+ typedef boost::shared_ptr<SchannelCertificate> ref;
+
+ public:
+ SchannelCertificate(const ScopedCertContext& certCtxt);
+ SchannelCertificate(const ByteArray& der);
+
+ std::string getSubjectName() const
+ {
+ return m_subjectName;
+ }
+
+ std::vector<std::string> getCommonNames() const
+ {
+ return m_commonNames;
+ }
+
+ std::vector<std::string> getSRVNames() const
+ {
+ return m_srvNames;
+ }
+
+ std::vector<std::string> getDNSNames() const
+ {
+ return m_dnsNames;
+ }
+
+ std::vector<std::string> getXMPPAddresses() const
+ {
+ return m_xmppAddresses;
+ }
+
+ ScopedCertContext getCertContext() const
+ {
+ return m_cert;
+ }
+
+ ByteArray toDER() const;
+
+ private:
+ void parse();
+ std::string wstrToStr(const std::wstring& wstr);
+
+ void addSRVName(const std::string& name)
+ {
+ m_srvNames.push_back(name);
+ }
+
+ void addDNSName(const std::string& name)
+ {
+ m_dnsNames.push_back(name);
+ }
+
+ void addXMPPAddress(const std::string& addr)
+ {
+ m_xmppAddresses.push_back(addr);
+ }
+
+ private:
+ ScopedCertContext m_cert;
+
+ std::string m_subjectName;
+ std::vector<std::string> m_commonNames;
+ std::vector<std::string> m_dnsNames;
+ std::vector<std::string> m_xmppAddresses;
+ std::vector<std::string> m_srvNames;
+ };
}
diff --git a/Swiften/TLS/Schannel/SchannelCertificateFactory.h b/Swiften/TLS/Schannel/SchannelCertificateFactory.h
index 5a2b208..be97c52 100644
--- a/Swiften/TLS/Schannel/SchannelCertificateFactory.h
+++ b/Swiften/TLS/Schannel/SchannelCertificateFactory.h
@@ -10,10 +10,10 @@
#include <Swiften/TLS/Schannel/SchannelCertificate.h>
namespace Swift {
- class SchannelCertificateFactory : public CertificateFactory {
- public:
- virtual Certificate* createCertificateFromDER(const ByteArray& der) {
- return new SchannelCertificate(der);
- }
- };
+ class SchannelCertificateFactory : public CertificateFactory {
+ public:
+ virtual Certificate* createCertificateFromDER(const ByteArray& der) {
+ return new SchannelCertificate(der);
+ }
+ };
}
diff --git a/Swiften/TLS/Schannel/SchannelContext.cpp b/Swiften/TLS/Schannel/SchannelContext.cpp
index 62aa137..7b67f4c 100644
--- a/Swiften/TLS/Schannel/SchannelContext.cpp
+++ b/Swiften/TLS/Schannel/SchannelContext.cpp
@@ -24,671 +24,671 @@ namespace Swift {
//------------------------------------------------------------------------
SchannelContext::SchannelContext(bool tls1_0Workaround) : state_(Start), secContext_(0), myCertStore_(NULL), certStoreName_("MY"), certName_(), smartCardReader_(), checkCertificateRevocation_(true), tls1_0Workaround_(tls1_0Workaround), disconnectOnCardRemoval_(true) {
- contextFlags_ = ISC_REQ_ALLOCATE_MEMORY |
- ISC_REQ_CONFIDENTIALITY |
- ISC_REQ_EXTENDED_ERROR |
- ISC_REQ_INTEGRITY |
- ISC_REQ_REPLAY_DETECT |
- ISC_REQ_SEQUENCE_DETECT |
- ISC_REQ_USE_SUPPLIED_CREDS |
- ISC_REQ_STREAM;
-
- ZeroMemory(&streamSizes_, sizeof(streamSizes_));
+ contextFlags_ = ISC_REQ_ALLOCATE_MEMORY |
+ ISC_REQ_CONFIDENTIALITY |
+ ISC_REQ_EXTENDED_ERROR |
+ ISC_REQ_INTEGRITY |
+ ISC_REQ_REPLAY_DETECT |
+ ISC_REQ_SEQUENCE_DETECT |
+ ISC_REQ_USE_SUPPLIED_CREDS |
+ ISC_REQ_STREAM;
+
+ ZeroMemory(&streamSizes_, sizeof(streamSizes_));
}
//------------------------------------------------------------------------
SchannelContext::~SchannelContext() {
- if (myCertStore_) CertCloseStore(myCertStore_, 0);
+ if (myCertStore_) CertCloseStore(myCertStore_, 0);
}
//------------------------------------------------------------------------
void SchannelContext::determineStreamSizes() {
- QueryContextAttributes(contextHandle_, SECPKG_ATTR_STREAM_SIZES, &streamSizes_);
+ QueryContextAttributes(contextHandle_, SECPKG_ATTR_STREAM_SIZES, &streamSizes_);
}
//------------------------------------------------------------------------
void SchannelContext::connect() {
- ScopedCertContext pCertContext;
-
- state_ = Connecting;
-
- // If a user name is specified, then attempt to find a client
- // certificate. Otherwise, just create a NULL credential.
- if (!certName_.empty()) {
- if (myCertStore_ == NULL) {
- myCertStore_ = CertOpenSystemStore(0, certStoreName_.c_str());
- if (!myCertStore_) {
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
- }
-
- pCertContext = findCertificateInStore( myCertStore_, certName_ );
- if (pCertContext == NULL) {
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
- }
-
- // We use an empty list for client certificates
- PCCERT_CONTEXT clientCerts[1] = {0};
-
- SCHANNEL_CRED sc = {0};
- sc.dwVersion = SCHANNEL_CRED_VERSION;
-
- if (tls1_0Workaround_) {
- sc.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT;
- }
- else {
- sc.grbitEnabledProtocols = /*SP_PROT_SSL3_CLIENT | */SP_PROT_TLS1_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT;
- }
-
- sc.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION;
-
- if (pCertContext) {
- sc.cCreds = 1;
- sc.paCred = pCertContext.GetPointer();
- sc.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
- }
- else {
- sc.cCreds = 0;
- sc.paCred = clientCerts;
- sc.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
- }
-
- // Swiften performs the server name check for us
- sc.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
-
- SECURITY_STATUS status = AcquireCredentialsHandle(
- NULL,
- UNISP_NAME,
- SECPKG_CRED_OUTBOUND,
- NULL,
- &sc,
- NULL,
- NULL,
- credHandle_.Reset(),
- NULL);
-
- if (status != SEC_E_OK) {
- // We failed to obtain the credentials handle
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
-
- SecBuffer outBuffers[2];
-
- // We let Schannel allocate the output buffer for us
- outBuffers[0].pvBuffer = NULL;
- outBuffers[0].cbBuffer = 0;
- outBuffers[0].BufferType = SECBUFFER_TOKEN;
-
- // Contains alert data if an alert is generated
- outBuffers[1].pvBuffer = NULL;
- outBuffers[1].cbBuffer = 0;
- outBuffers[1].BufferType = SECBUFFER_ALERT;
-
- // Make sure the output buffers are freed
- ScopedSecBuffer scopedOutputData(&outBuffers[0]);
- ScopedSecBuffer scopedOutputAlertData(&outBuffers[1]);
-
- SecBufferDesc outBufferDesc = {0};
- outBufferDesc.cBuffers = 2;
- outBufferDesc.pBuffers = outBuffers;
- outBufferDesc.ulVersion = SECBUFFER_VERSION;
-
- // Create the initial security context
- status = InitializeSecurityContext(
- credHandle_,
- NULL,
- NULL,
- contextFlags_,
- 0,
- 0,
- NULL,
- 0,
- contextHandle_.Reset(),
- &outBufferDesc,
- &secContext_,
- NULL);
-
- if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) {
- // We failed to initialize the security context
- handleCertError(status);
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
-
- // Start the handshake
- sendDataOnNetwork(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer);
-
- if (status == SEC_E_OK) {
- status = validateServerCertificate();
- if (status != SEC_E_OK) {
- handleCertError(status);
- }
-
- state_ = Connected;
- determineStreamSizes();
-
- onConnected();
- }
+ ScopedCertContext pCertContext;
+
+ state_ = Connecting;
+
+ // If a user name is specified, then attempt to find a client
+ // certificate. Otherwise, just create a NULL credential.
+ if (!certName_.empty()) {
+ if (myCertStore_ == NULL) {
+ myCertStore_ = CertOpenSystemStore(0, certStoreName_.c_str());
+ if (!myCertStore_) {
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+ }
+
+ pCertContext = findCertificateInStore( myCertStore_, certName_ );
+ if (pCertContext == NULL) {
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+ }
+
+ // We use an empty list for client certificates
+ PCCERT_CONTEXT clientCerts[1] = {0};
+
+ SCHANNEL_CRED sc = {0};
+ sc.dwVersion = SCHANNEL_CRED_VERSION;
+
+ if (tls1_0Workaround_) {
+ sc.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT;
+ }
+ else {
+ sc.grbitEnabledProtocols = /*SP_PROT_SSL3_CLIENT | */SP_PROT_TLS1_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT;
+ }
+
+ sc.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION;
+
+ if (pCertContext) {
+ sc.cCreds = 1;
+ sc.paCred = pCertContext.GetPointer();
+ sc.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
+ }
+ else {
+ sc.cCreds = 0;
+ sc.paCred = clientCerts;
+ sc.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
+ }
+
+ // Swiften performs the server name check for us
+ sc.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
+
+ SECURITY_STATUS status = AcquireCredentialsHandle(
+ NULL,
+ UNISP_NAME,
+ SECPKG_CRED_OUTBOUND,
+ NULL,
+ &sc,
+ NULL,
+ NULL,
+ credHandle_.Reset(),
+ NULL);
+
+ if (status != SEC_E_OK) {
+ // We failed to obtain the credentials handle
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+
+ SecBuffer outBuffers[2];
+
+ // We let Schannel allocate the output buffer for us
+ outBuffers[0].pvBuffer = NULL;
+ outBuffers[0].cbBuffer = 0;
+ outBuffers[0].BufferType = SECBUFFER_TOKEN;
+
+ // Contains alert data if an alert is generated
+ outBuffers[1].pvBuffer = NULL;
+ outBuffers[1].cbBuffer = 0;
+ outBuffers[1].BufferType = SECBUFFER_ALERT;
+
+ // Make sure the output buffers are freed
+ ScopedSecBuffer scopedOutputData(&outBuffers[0]);
+ ScopedSecBuffer scopedOutputAlertData(&outBuffers[1]);
+
+ SecBufferDesc outBufferDesc = {0};
+ outBufferDesc.cBuffers = 2;
+ outBufferDesc.pBuffers = outBuffers;
+ outBufferDesc.ulVersion = SECBUFFER_VERSION;
+
+ // Create the initial security context
+ status = InitializeSecurityContext(
+ credHandle_,
+ NULL,
+ NULL,
+ contextFlags_,
+ 0,
+ 0,
+ NULL,
+ 0,
+ contextHandle_.Reset(),
+ &outBufferDesc,
+ &secContext_,
+ NULL);
+
+ if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) {
+ // We failed to initialize the security context
+ handleCertError(status);
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+
+ // Start the handshake
+ sendDataOnNetwork(outBuffers[0].pvBuffer, outBuffers[0].cbBuffer);
+
+ if (status == SEC_E_OK) {
+ status = validateServerCertificate();
+ if (status != SEC_E_OK) {
+ handleCertError(status);
+ }
+
+ state_ = Connected;
+ determineStreamSizes();
+
+ onConnected();
+ }
}
//------------------------------------------------------------------------
SECURITY_STATUS SchannelContext::validateServerCertificate() {
- SchannelCertificate::ref pServerCert = boost::dynamic_pointer_cast<SchannelCertificate>( getPeerCertificate() );
- if (!pServerCert) {
- return SEC_E_WRONG_PRINCIPAL;
- }
-
- const LPSTR usage[] =
- {
- szOID_PKIX_KP_SERVER_AUTH,
- szOID_SERVER_GATED_CRYPTO,
- szOID_SGC_NETSCAPE
- };
-
- CERT_CHAIN_PARA chainParams = {0};
- chainParams.cbSize = sizeof(chainParams);
- chainParams.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
- chainParams.RequestedUsage.Usage.cUsageIdentifier = ARRAYSIZE(usage);
- chainParams.RequestedUsage.Usage.rgpszUsageIdentifier = const_cast<LPSTR*>(usage);
-
- DWORD chainFlags = CERT_CHAIN_CACHE_END_CERT;
- if (checkCertificateRevocation_) {
- chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
- }
-
- ScopedCertChainContext pChainContext;
-
- BOOL success = CertGetCertificateChain(
- NULL, // Use the chain engine for the current user (assumes a user is logged in)
- pServerCert->getCertContext(),
- NULL,
- pServerCert->getCertContext()->hCertStore,
- &chainParams,
- chainFlags,
- NULL,
- pChainContext.Reset());
-
- if (!success) {
- return GetLastError();
- }
-
- SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslChainPolicy = {0};
- sslChainPolicy.cbSize = sizeof(sslChainPolicy);
- sslChainPolicy.dwAuthType = AUTHTYPE_SERVER;
- sslChainPolicy.fdwChecks = SECURITY_FLAG_IGNORE_CERT_CN_INVALID; // Swiften checks the server name for us. Is this the correct way to disable server name checking?
- sslChainPolicy.pwszServerName = NULL;
-
- CERT_CHAIN_POLICY_PARA certChainPolicy = {0};
- certChainPolicy.cbSize = sizeof(certChainPolicy);
- certChainPolicy.dwFlags = CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG; // Swiften checks the server name for us. Is this the correct way to disable server name checking?
- certChainPolicy.pvExtraPolicyPara = &sslChainPolicy;
-
- CERT_CHAIN_POLICY_STATUS certChainPolicyStatus = {0};
- certChainPolicyStatus.cbSize = sizeof(certChainPolicyStatus);
-
- // Verify the chain
- if (!CertVerifyCertificateChainPolicy(
- CERT_CHAIN_POLICY_SSL,
- pChainContext,
- &certChainPolicy,
- &certChainPolicyStatus)) {
- return GetLastError();
- }
-
- if (certChainPolicyStatus.dwError != S_OK) {
- return certChainPolicyStatus.dwError;
- }
-
- return S_OK;
+ SchannelCertificate::ref pServerCert = boost::dynamic_pointer_cast<SchannelCertificate>( getPeerCertificate() );
+ if (!pServerCert) {
+ return SEC_E_WRONG_PRINCIPAL;
+ }
+
+ const LPSTR usage[] =
+ {
+ szOID_PKIX_KP_SERVER_AUTH,
+ szOID_SERVER_GATED_CRYPTO,
+ szOID_SGC_NETSCAPE
+ };
+
+ CERT_CHAIN_PARA chainParams = {0};
+ chainParams.cbSize = sizeof(chainParams);
+ chainParams.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
+ chainParams.RequestedUsage.Usage.cUsageIdentifier = ARRAYSIZE(usage);
+ chainParams.RequestedUsage.Usage.rgpszUsageIdentifier = const_cast<LPSTR*>(usage);
+
+ DWORD chainFlags = CERT_CHAIN_CACHE_END_CERT;
+ if (checkCertificateRevocation_) {
+ chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
+ }
+
+ ScopedCertChainContext pChainContext;
+
+ BOOL success = CertGetCertificateChain(
+ NULL, // Use the chain engine for the current user (assumes a user is logged in)
+ pServerCert->getCertContext(),
+ NULL,
+ pServerCert->getCertContext()->hCertStore,
+ &chainParams,
+ chainFlags,
+ NULL,
+ pChainContext.Reset());
+
+ if (!success) {
+ return GetLastError();
+ }
+
+ SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslChainPolicy = {0};
+ sslChainPolicy.cbSize = sizeof(sslChainPolicy);
+ sslChainPolicy.dwAuthType = AUTHTYPE_SERVER;
+ sslChainPolicy.fdwChecks = SECURITY_FLAG_IGNORE_CERT_CN_INVALID; // Swiften checks the server name for us. Is this the correct way to disable server name checking?
+ sslChainPolicy.pwszServerName = NULL;
+
+ CERT_CHAIN_POLICY_PARA certChainPolicy = {0};
+ certChainPolicy.cbSize = sizeof(certChainPolicy);
+ certChainPolicy.dwFlags = CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG; // Swiften checks the server name for us. Is this the correct way to disable server name checking?
+ certChainPolicy.pvExtraPolicyPara = &sslChainPolicy;
+
+ CERT_CHAIN_POLICY_STATUS certChainPolicyStatus = {0};
+ certChainPolicyStatus.cbSize = sizeof(certChainPolicyStatus);
+
+ // Verify the chain
+ if (!CertVerifyCertificateChainPolicy(
+ CERT_CHAIN_POLICY_SSL,
+ pChainContext,
+ &certChainPolicy,
+ &certChainPolicyStatus)) {
+ return GetLastError();
+ }
+
+ if (certChainPolicyStatus.dwError != S_OK) {
+ return certChainPolicyStatus.dwError;
+ }
+
+ return S_OK;
}
//------------------------------------------------------------------------
void SchannelContext::appendNewData(const SafeByteArray& data) {
- size_t originalSize = receivedData_.size();
- receivedData_.resize(originalSize + data.size());
- memcpy(&receivedData_[0] + originalSize, &data[0], data.size());
+ size_t originalSize = receivedData_.size();
+ receivedData_.resize(originalSize + data.size());
+ memcpy(&receivedData_[0] + originalSize, &data[0], data.size());
}
//------------------------------------------------------------------------
void SchannelContext::continueHandshake(const SafeByteArray& data) {
- appendNewData(data);
-
- while (!receivedData_.empty()) {
- SecBuffer inBuffers[2];
-
- // Provide Schannel with the remote host's handshake data
- inBuffers[0].pvBuffer = (char*)(&receivedData_[0]);
- inBuffers[0].cbBuffer = (unsigned long)receivedData_.size();
- inBuffers[0].BufferType = SECBUFFER_TOKEN;
-
- inBuffers[1].pvBuffer = NULL;
- inBuffers[1].cbBuffer = 0;
- inBuffers[1].BufferType = SECBUFFER_EMPTY;
-
- SecBufferDesc inBufferDesc = {0};
- inBufferDesc.cBuffers = 2;
- inBufferDesc.pBuffers = inBuffers;
- inBufferDesc.ulVersion = SECBUFFER_VERSION;
-
- SecBuffer outBuffers[2];
-
- // We let Schannel allocate the output buffer for us
- outBuffers[0].pvBuffer = NULL;
- outBuffers[0].cbBuffer = 0;
- outBuffers[0].BufferType = SECBUFFER_TOKEN;
-
- // Contains alert data if an alert is generated
- outBuffers[1].pvBuffer = NULL;
- outBuffers[1].cbBuffer = 0;
- outBuffers[1].BufferType = SECBUFFER_ALERT;
-
- // Make sure the output buffers are freed
- ScopedSecBuffer scopedOutputData(&outBuffers[0]);
- ScopedSecBuffer scopedOutputAlertData(&outBuffers[1]);
-
- SecBufferDesc outBufferDesc = {0};
- outBufferDesc.cBuffers = 2;
- outBufferDesc.pBuffers = outBuffers;
- outBufferDesc.ulVersion = SECBUFFER_VERSION;
-
- SECURITY_STATUS status = InitializeSecurityContext(
- credHandle_,
- contextHandle_,
- NULL,
- contextFlags_,
- 0,
- 0,
- &inBufferDesc,
- 0,
- NULL,
- &outBufferDesc,
- &secContext_,
- NULL);
-
- if (status == SEC_E_INCOMPLETE_MESSAGE) {
- // Wait for more data to arrive
- break;
- }
- else if (status == SEC_I_CONTINUE_NEEDED) {
- SecBuffer* pDataBuffer = &outBuffers[0];
- SecBuffer* pExtraBuffer = &inBuffers[1];
-
- if (pDataBuffer && pDataBuffer->cbBuffer > 0 && pDataBuffer->pvBuffer != NULL) {
- sendDataOnNetwork(pDataBuffer->pvBuffer, pDataBuffer->cbBuffer);
- }
-
- if (pExtraBuffer->BufferType == SECBUFFER_EXTRA) {
- receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
- }
- else {
- receivedData_.clear();
- }
-
- break;
- }
- else if (status == SEC_E_OK) {
- status = validateServerCertificate();
- if (status != SEC_E_OK) {
- handleCertError(status);
- }
-
- SecBuffer* pExtraBuffer = &inBuffers[1];
-
- if (pExtraBuffer && pExtraBuffer->cbBuffer > 0) {
- receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
- }
- else {
- receivedData_.clear();
- }
-
- state_ = Connected;
- determineStreamSizes();
-
- onConnected();
- }
- else {
- // We failed to initialize the security context
- handleCertError(status);
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
- }
+ appendNewData(data);
+
+ while (!receivedData_.empty()) {
+ SecBuffer inBuffers[2];
+
+ // Provide Schannel with the remote host's handshake data
+ inBuffers[0].pvBuffer = (char*)(&receivedData_[0]);
+ inBuffers[0].cbBuffer = (unsigned long)receivedData_.size();
+ inBuffers[0].BufferType = SECBUFFER_TOKEN;
+
+ inBuffers[1].pvBuffer = NULL;
+ inBuffers[1].cbBuffer = 0;
+ inBuffers[1].BufferType = SECBUFFER_EMPTY;
+
+ SecBufferDesc inBufferDesc = {0};
+ inBufferDesc.cBuffers = 2;
+ inBufferDesc.pBuffers = inBuffers;
+ inBufferDesc.ulVersion = SECBUFFER_VERSION;
+
+ SecBuffer outBuffers[2];
+
+ // We let Schannel allocate the output buffer for us
+ outBuffers[0].pvBuffer = NULL;
+ outBuffers[0].cbBuffer = 0;
+ outBuffers[0].BufferType = SECBUFFER_TOKEN;
+
+ // Contains alert data if an alert is generated
+ outBuffers[1].pvBuffer = NULL;
+ outBuffers[1].cbBuffer = 0;
+ outBuffers[1].BufferType = SECBUFFER_ALERT;
+
+ // Make sure the output buffers are freed
+ ScopedSecBuffer scopedOutputData(&outBuffers[0]);
+ ScopedSecBuffer scopedOutputAlertData(&outBuffers[1]);
+
+ SecBufferDesc outBufferDesc = {0};
+ outBufferDesc.cBuffers = 2;
+ outBufferDesc.pBuffers = outBuffers;
+ outBufferDesc.ulVersion = SECBUFFER_VERSION;
+
+ SECURITY_STATUS status = InitializeSecurityContext(
+ credHandle_,
+ contextHandle_,
+ NULL,
+ contextFlags_,
+ 0,
+ 0,
+ &inBufferDesc,
+ 0,
+ NULL,
+ &outBufferDesc,
+ &secContext_,
+ NULL);
+
+ if (status == SEC_E_INCOMPLETE_MESSAGE) {
+ // Wait for more data to arrive
+ break;
+ }
+ else if (status == SEC_I_CONTINUE_NEEDED) {
+ SecBuffer* pDataBuffer = &outBuffers[0];
+ SecBuffer* pExtraBuffer = &inBuffers[1];
+
+ if (pDataBuffer && pDataBuffer->cbBuffer > 0 && pDataBuffer->pvBuffer != NULL) {
+ sendDataOnNetwork(pDataBuffer->pvBuffer, pDataBuffer->cbBuffer);
+ }
+
+ if (pExtraBuffer->BufferType == SECBUFFER_EXTRA) {
+ receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
+ }
+ else {
+ receivedData_.clear();
+ }
+
+ break;
+ }
+ else if (status == SEC_E_OK) {
+ status = validateServerCertificate();
+ if (status != SEC_E_OK) {
+ handleCertError(status);
+ }
+
+ SecBuffer* pExtraBuffer = &inBuffers[1];
+
+ if (pExtraBuffer && pExtraBuffer->cbBuffer > 0) {
+ receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
+ }
+ else {
+ receivedData_.clear();
+ }
+
+ state_ = Connected;
+ determineStreamSizes();
+
+ onConnected();
+ }
+ else {
+ // We failed to initialize the security context
+ handleCertError(status);
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+ }
}
//------------------------------------------------------------------------
void SchannelContext::handleCertError(SECURITY_STATUS status)
{
- if (status == SEC_E_UNTRUSTED_ROOT ||
- status == CERT_E_UNTRUSTEDROOT ||
- status == CRYPT_E_ISSUER_SERIALNUMBER ||
- status == CRYPT_E_SIGNER_NOT_FOUND ||
- status == CRYPT_E_NO_TRUSTED_SIGNER) {
- verificationError_ = CertificateVerificationError::Untrusted;
- }
- else if (status == SEC_E_CERT_EXPIRED ||
- status == CERT_E_EXPIRED) {
- verificationError_ = CertificateVerificationError::Expired;
- }
- else if (status == CRYPT_E_SELF_SIGNED) {
- verificationError_ = CertificateVerificationError::SelfSigned;
- }
- else if (status == CRYPT_E_HASH_VALUE ||
- status == TRUST_E_CERT_SIGNATURE) {
- verificationError_ = CertificateVerificationError::InvalidSignature;
- }
- else if (status == CRYPT_E_REVOKED) {
- verificationError_ = CertificateVerificationError::Revoked;
- }
- else if (status == CRYPT_E_NO_REVOCATION_CHECK ||
- status == CRYPT_E_REVOCATION_OFFLINE) {
- verificationError_ = CertificateVerificationError::RevocationCheckFailed;
- }
- else if (status == CERT_E_WRONG_USAGE) {
- verificationError_ = CertificateVerificationError::InvalidPurpose;
- }
- else {
- verificationError_ = CertificateVerificationError::UnknownError;
- }
+ if (status == SEC_E_UNTRUSTED_ROOT ||
+ status == CERT_E_UNTRUSTEDROOT ||
+ status == CRYPT_E_ISSUER_SERIALNUMBER ||
+ status == CRYPT_E_SIGNER_NOT_FOUND ||
+ status == CRYPT_E_NO_TRUSTED_SIGNER) {
+ verificationError_ = CertificateVerificationError::Untrusted;
+ }
+ else if (status == SEC_E_CERT_EXPIRED ||
+ status == CERT_E_EXPIRED) {
+ verificationError_ = CertificateVerificationError::Expired;
+ }
+ else if (status == CRYPT_E_SELF_SIGNED) {
+ verificationError_ = CertificateVerificationError::SelfSigned;
+ }
+ else if (status == CRYPT_E_HASH_VALUE ||
+ status == TRUST_E_CERT_SIGNATURE) {
+ verificationError_ = CertificateVerificationError::InvalidSignature;
+ }
+ else if (status == CRYPT_E_REVOKED) {
+ verificationError_ = CertificateVerificationError::Revoked;
+ }
+ else if (status == CRYPT_E_NO_REVOCATION_CHECK ||
+ status == CRYPT_E_REVOCATION_OFFLINE) {
+ verificationError_ = CertificateVerificationError::RevocationCheckFailed;
+ }
+ else if (status == CERT_E_WRONG_USAGE) {
+ verificationError_ = CertificateVerificationError::InvalidPurpose;
+ }
+ else {
+ verificationError_ = CertificateVerificationError::UnknownError;
+ }
}
//------------------------------------------------------------------------
void SchannelContext::sendDataOnNetwork(const void* pData, size_t dataSize) {
- if (dataSize > 0 && pData) {
- SafeByteArray byteArray(dataSize);
- memcpy(&byteArray[0], pData, dataSize);
+ if (dataSize > 0 && pData) {
+ SafeByteArray byteArray(dataSize);
+ memcpy(&byteArray[0], pData, dataSize);
- onDataForNetwork(byteArray);
- }
+ onDataForNetwork(byteArray);
+ }
}
//------------------------------------------------------------------------
void SchannelContext::forwardDataToApplication(const void* pData, size_t dataSize) {
- SafeByteArray byteArray(dataSize);
- memcpy(&byteArray[0], pData, dataSize);
+ SafeByteArray byteArray(dataSize);
+ memcpy(&byteArray[0], pData, dataSize);
- onDataForApplication(byteArray);
+ onDataForApplication(byteArray);
}
//------------------------------------------------------------------------
void SchannelContext::handleDataFromApplication(const SafeByteArray& data) {
- // Don't attempt to send data until we're fully connected
- if (state_ == Connecting) {
- return;
- }
+ // Don't attempt to send data until we're fully connected
+ if (state_ == Connecting) {
+ return;
+ }
- // Encrypt the data
- encryptAndSendData(data);
+ // Encrypt the data
+ encryptAndSendData(data);
}
//------------------------------------------------------------------------
void SchannelContext::handleDataFromNetwork(const SafeByteArray& data) {
- switch (state_) {
- case Connecting:
- {
- // We're still establishing the connection, so continue the handshake
- continueHandshake(data);
- }
- break;
-
- case Connected:
- {
- // Decrypt the data
- decryptAndProcessData(data);
- }
- break;
-
- default:
- return;
- }
+ switch (state_) {
+ case Connecting:
+ {
+ // We're still establishing the connection, so continue the handshake
+ continueHandshake(data);
+ }
+ break;
+
+ case Connected:
+ {
+ // Decrypt the data
+ decryptAndProcessData(data);
+ }
+ break;
+
+ default:
+ return;
+ }
}
//------------------------------------------------------------------------
void SchannelContext::indicateError(boost::shared_ptr<TLSError> error) {
- state_ = Error;
- receivedData_.clear();
- onError(error);
+ state_ = Error;
+ receivedData_.clear();
+ onError(error);
}
//------------------------------------------------------------------------
void SchannelContext::decryptAndProcessData(const SafeByteArray& data) {
- SecBuffer inBuffers[4] = {0};
-
- appendNewData(data);
-
- while (!receivedData_.empty()) {
- //
- // MSDN:
- // When using the Schannel SSP with contexts that are not connection oriented, on input,
- // the structure must contain four SecBuffer structures. Exactly one buffer must be of type
- // SECBUFFER_DATA and contain an encrypted message, which is decrypted in place. The remaining
- // buffers are used for output and must be of type SECBUFFER_EMPTY. For connection-oriented
- // contexts, a SECBUFFER_DATA type buffer must be supplied, as noted for nonconnection-oriented
- // contexts. Additionally, a second SECBUFFER_TOKEN type buffer that contains a security token
- // must also be supplied.
- //
- inBuffers[0].pvBuffer = (char*)(&receivedData_[0]);
- inBuffers[0].cbBuffer = (unsigned long)receivedData_.size();
- inBuffers[0].BufferType = SECBUFFER_DATA;
-
- inBuffers[1].BufferType = SECBUFFER_EMPTY;
- inBuffers[2].BufferType = SECBUFFER_EMPTY;
- inBuffers[3].BufferType = SECBUFFER_EMPTY;
-
- SecBufferDesc inBufferDesc = {0};
- inBufferDesc.cBuffers = 4;
- inBufferDesc.pBuffers = inBuffers;
- inBufferDesc.ulVersion = SECBUFFER_VERSION;
-
- size_t inData = receivedData_.size();
- SECURITY_STATUS status = DecryptMessage(contextHandle_, &inBufferDesc, 0, NULL);
-
- if (status == SEC_E_INCOMPLETE_MESSAGE) {
- // Wait for more data to arrive
- break;
- }
- else if (status == SEC_I_RENEGOTIATE) {
- // TODO: Handle renegotiation scenarios
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- break;
- }
- else if (status == SEC_I_CONTEXT_EXPIRED) {
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- break;
- }
- else if (status != SEC_E_OK) {
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- break;
- }
-
- SecBuffer* pDataBuffer = NULL;
- SecBuffer* pExtraBuffer = NULL;
- for (int i = 0; i < 4; ++i) {
- if (inBuffers[i].BufferType == SECBUFFER_DATA) {
- pDataBuffer = &inBuffers[i];
- }
- else if (inBuffers[i].BufferType == SECBUFFER_EXTRA) {
- pExtraBuffer = &inBuffers[i];
- }
- }
-
- if (pDataBuffer && pDataBuffer->cbBuffer > 0 && pDataBuffer->pvBuffer != NULL) {
- forwardDataToApplication(pDataBuffer->pvBuffer, pDataBuffer->cbBuffer);
- }
-
- // If there is extra data left over from the decryption operation, we call DecryptMessage() again
- if (pExtraBuffer) {
- receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
- }
- else {
- // We're done
- receivedData_.erase(receivedData_.begin(), receivedData_.begin() + inData);
- }
- }
+ SecBuffer inBuffers[4] = {0};
+
+ appendNewData(data);
+
+ while (!receivedData_.empty()) {
+ //
+ // MSDN:
+ // When using the Schannel SSP with contexts that are not connection oriented, on input,
+ // the structure must contain four SecBuffer structures. Exactly one buffer must be of type
+ // SECBUFFER_DATA and contain an encrypted message, which is decrypted in place. The remaining
+ // buffers are used for output and must be of type SECBUFFER_EMPTY. For connection-oriented
+ // contexts, a SECBUFFER_DATA type buffer must be supplied, as noted for nonconnection-oriented
+ // contexts. Additionally, a second SECBUFFER_TOKEN type buffer that contains a security token
+ // must also be supplied.
+ //
+ inBuffers[0].pvBuffer = (char*)(&receivedData_[0]);
+ inBuffers[0].cbBuffer = (unsigned long)receivedData_.size();
+ inBuffers[0].BufferType = SECBUFFER_DATA;
+
+ inBuffers[1].BufferType = SECBUFFER_EMPTY;
+ inBuffers[2].BufferType = SECBUFFER_EMPTY;
+ inBuffers[3].BufferType = SECBUFFER_EMPTY;
+
+ SecBufferDesc inBufferDesc = {0};
+ inBufferDesc.cBuffers = 4;
+ inBufferDesc.pBuffers = inBuffers;
+ inBufferDesc.ulVersion = SECBUFFER_VERSION;
+
+ size_t inData = receivedData_.size();
+ SECURITY_STATUS status = DecryptMessage(contextHandle_, &inBufferDesc, 0, NULL);
+
+ if (status == SEC_E_INCOMPLETE_MESSAGE) {
+ // Wait for more data to arrive
+ break;
+ }
+ else if (status == SEC_I_RENEGOTIATE) {
+ // TODO: Handle renegotiation scenarios
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ break;
+ }
+ else if (status == SEC_I_CONTEXT_EXPIRED) {
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ break;
+ }
+ else if (status != SEC_E_OK) {
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ break;
+ }
+
+ SecBuffer* pDataBuffer = NULL;
+ SecBuffer* pExtraBuffer = NULL;
+ for (int i = 0; i < 4; ++i) {
+ if (inBuffers[i].BufferType == SECBUFFER_DATA) {
+ pDataBuffer = &inBuffers[i];
+ }
+ else if (inBuffers[i].BufferType == SECBUFFER_EXTRA) {
+ pExtraBuffer = &inBuffers[i];
+ }
+ }
+
+ if (pDataBuffer && pDataBuffer->cbBuffer > 0 && pDataBuffer->pvBuffer != NULL) {
+ forwardDataToApplication(pDataBuffer->pvBuffer, pDataBuffer->cbBuffer);
+ }
+
+ // If there is extra data left over from the decryption operation, we call DecryptMessage() again
+ if (pExtraBuffer) {
+ receivedData_.erase(receivedData_.begin(), receivedData_.end() - pExtraBuffer->cbBuffer);
+ }
+ else {
+ // We're done
+ receivedData_.erase(receivedData_.begin(), receivedData_.begin() + inData);
+ }
+ }
}
//------------------------------------------------------------------------
void SchannelContext::encryptAndSendData(const SafeByteArray& data) {
- if (streamSizes_.cbMaximumMessage == 0) {
- return;
- }
+ if (streamSizes_.cbMaximumMessage == 0) {
+ return;
+ }
- SecBuffer outBuffers[4] = {0};
+ SecBuffer outBuffers[4] = {0};
- // Calculate the largest required size of the send buffer
- size_t messageBufferSize = (data.size() > streamSizes_.cbMaximumMessage)
- ? streamSizes_.cbMaximumMessage
- : data.size();
+ // Calculate the largest required size of the send buffer
+ size_t messageBufferSize = (data.size() > streamSizes_.cbMaximumMessage)
+ ? streamSizes_.cbMaximumMessage
+ : data.size();
- // Allocate a packet for the encrypted data
- SafeByteArray sendBuffer;
- sendBuffer.resize(streamSizes_.cbHeader + messageBufferSize + streamSizes_.cbTrailer);
+ // Allocate a packet for the encrypted data
+ SafeByteArray sendBuffer;
+ sendBuffer.resize(streamSizes_.cbHeader + messageBufferSize + streamSizes_.cbTrailer);
- size_t bytesSent = 0;
- do {
- size_t bytesLeftToSend = data.size() - bytesSent;
+ size_t bytesSent = 0;
+ do {
+ size_t bytesLeftToSend = data.size() - bytesSent;
- // Calculate how much of the send buffer we'll be using for this chunk
- size_t bytesToSend = (bytesLeftToSend > streamSizes_.cbMaximumMessage)
- ? streamSizes_.cbMaximumMessage
- : bytesLeftToSend;
+ // Calculate how much of the send buffer we'll be using for this chunk
+ size_t bytesToSend = (bytesLeftToSend > streamSizes_.cbMaximumMessage)
+ ? streamSizes_.cbMaximumMessage
+ : bytesLeftToSend;
- // Copy the plain text data into the send buffer
- memcpy(&sendBuffer[0] + streamSizes_.cbHeader, &data[0] + bytesSent, bytesToSend);
+ // Copy the plain text data into the send buffer
+ memcpy(&sendBuffer[0] + streamSizes_.cbHeader, &data[0] + bytesSent, bytesToSend);
- outBuffers[0].pvBuffer = &sendBuffer[0];
- outBuffers[0].cbBuffer = streamSizes_.cbHeader;
- outBuffers[0].BufferType = SECBUFFER_STREAM_HEADER;
+ outBuffers[0].pvBuffer = &sendBuffer[0];
+ outBuffers[0].cbBuffer = streamSizes_.cbHeader;
+ outBuffers[0].BufferType = SECBUFFER_STREAM_HEADER;
- outBuffers[1].pvBuffer = &sendBuffer[0] + streamSizes_.cbHeader;
- outBuffers[1].cbBuffer = (unsigned long)bytesToSend;
- outBuffers[1].BufferType = SECBUFFER_DATA;
+ outBuffers[1].pvBuffer = &sendBuffer[0] + streamSizes_.cbHeader;
+ outBuffers[1].cbBuffer = (unsigned long)bytesToSend;
+ outBuffers[1].BufferType = SECBUFFER_DATA;
- outBuffers[2].pvBuffer = &sendBuffer[0] + streamSizes_.cbHeader + bytesToSend;
- outBuffers[2].cbBuffer = streamSizes_.cbTrailer;
- outBuffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
+ outBuffers[2].pvBuffer = &sendBuffer[0] + streamSizes_.cbHeader + bytesToSend;
+ outBuffers[2].cbBuffer = streamSizes_.cbTrailer;
+ outBuffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
- outBuffers[3].pvBuffer = 0;
- outBuffers[3].cbBuffer = 0;
- outBuffers[3].BufferType = SECBUFFER_EMPTY;
+ outBuffers[3].pvBuffer = 0;
+ outBuffers[3].cbBuffer = 0;
+ outBuffers[3].BufferType = SECBUFFER_EMPTY;
- SecBufferDesc outBufferDesc = {0};
- outBufferDesc.cBuffers = 4;
- outBufferDesc.pBuffers = outBuffers;
- outBufferDesc.ulVersion = SECBUFFER_VERSION;
+ SecBufferDesc outBufferDesc = {0};
+ outBufferDesc.cBuffers = 4;
+ outBufferDesc.pBuffers = outBuffers;
+ outBufferDesc.ulVersion = SECBUFFER_VERSION;
- SECURITY_STATUS status = EncryptMessage(contextHandle_, 0, &outBufferDesc, 0);
- if (status != SEC_E_OK) {
- indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
- return;
- }
+ SECURITY_STATUS status = EncryptMessage(contextHandle_, 0, &outBufferDesc, 0);
+ if (status != SEC_E_OK) {
+ indicateError(boost::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
- sendDataOnNetwork(&sendBuffer[0], outBuffers[0].cbBuffer + outBuffers[1].cbBuffer + outBuffers[2].cbBuffer);
- bytesSent += bytesToSend;
+ sendDataOnNetwork(&sendBuffer[0], outBuffers[0].cbBuffer + outBuffers[1].cbBuffer + outBuffers[2].cbBuffer);
+ bytesSent += bytesToSend;
- } while (bytesSent < data.size());
+ } while (bytesSent < data.size());
}
//------------------------------------------------------------------------
bool SchannelContext::setClientCertificate(CertificateWithKey::ref certificate) {
- boost::shared_ptr<CAPICertificate> capiCertificate = boost::dynamic_pointer_cast<CAPICertificate>(certificate);
- if (!capiCertificate || capiCertificate->isNull()) {
- return false;
- }
+ boost::shared_ptr<CAPICertificate> capiCertificate = boost::dynamic_pointer_cast<CAPICertificate>(certificate);
+ if (!capiCertificate || capiCertificate->isNull()) {
+ return false;
+ }
- userCertificate_ = capiCertificate;
+ userCertificate_ = capiCertificate;
- // We assume that the Certificate Store Name/Certificate Name
- // are valid at this point
- certStoreName_ = capiCertificate->getCertStoreName();
- certName_ = capiCertificate->getCertName();
+ // We assume that the Certificate Store Name/Certificate Name
+ // are valid at this point
+ certStoreName_ = capiCertificate->getCertStoreName();
+ certName_ = capiCertificate->getCertName();
////At the moment this is only useful for logging:
- smartCardReader_ = capiCertificate->getSmartCardReaderName();
+ smartCardReader_ = capiCertificate->getSmartCardReaderName();
- capiCertificate->onCertificateCardRemoved.connect(boost::bind(&SchannelContext::handleCertificateCardRemoved, this));
+ capiCertificate->onCertificateCardRemoved.connect(boost::bind(&SchannelContext::handleCertificateCardRemoved, this));
- return true;
+ return true;
}
//------------------------------------------------------------------------
void SchannelContext::handleCertificateCardRemoved() {
- if (disconnectOnCardRemoval_) {
- indicateError(boost::make_shared<TLSError>(TLSError::CertificateCardRemoved));
- }
+ if (disconnectOnCardRemoval_) {
+ indicateError(boost::make_shared<TLSError>(TLSError::CertificateCardRemoved));
+ }
}
//------------------------------------------------------------------------
std::vector<Certificate::ref> SchannelContext::getPeerCertificateChain() const {
- std::vector<Certificate::ref> certificateChain;
- ScopedCertContext pServerCert;
- ScopedCertContext pIssuerCert;
- ScopedCertContext pCurrentCert;
- SECURITY_STATUS status = QueryContextAttributes(contextHandle_, SECPKG_ATTR_REMOTE_CERT_CONTEXT, pServerCert.Reset());
-
- if (status != SEC_E_OK) {
- return certificateChain;
- }
- certificateChain.push_back(boost::make_shared<SchannelCertificate>(pServerCert));
-
- pCurrentCert = pServerCert;
- while(pCurrentCert.GetPointer()) {
- DWORD dwVerificationFlags = 0;
- pIssuerCert = CertGetIssuerCertificateFromStore(pServerCert->hCertStore, pCurrentCert, NULL, &dwVerificationFlags );
- if (!(*pIssuerCert.GetPointer())) {
- break;
- }
- certificateChain.push_back(boost::make_shared<SchannelCertificate>(pIssuerCert));
-
- pCurrentCert = pIssuerCert;
- pIssuerCert = NULL;
- }
- return certificateChain;
+ std::vector<Certificate::ref> certificateChain;
+ ScopedCertContext pServerCert;
+ ScopedCertContext pIssuerCert;
+ ScopedCertContext pCurrentCert;
+ SECURITY_STATUS status = QueryContextAttributes(contextHandle_, SECPKG_ATTR_REMOTE_CERT_CONTEXT, pServerCert.Reset());
+
+ if (status != SEC_E_OK) {
+ return certificateChain;
+ }
+ certificateChain.push_back(boost::make_shared<SchannelCertificate>(pServerCert));
+
+ pCurrentCert = pServerCert;
+ while(pCurrentCert.GetPointer()) {
+ DWORD dwVerificationFlags = 0;
+ pIssuerCert = CertGetIssuerCertificateFromStore(pServerCert->hCertStore, pCurrentCert, NULL, &dwVerificationFlags );
+ if (!(*pIssuerCert.GetPointer())) {
+ break;
+ }
+ certificateChain.push_back(boost::make_shared<SchannelCertificate>(pIssuerCert));
+
+ pCurrentCert = pIssuerCert;
+ pIssuerCert = NULL;
+ }
+ return certificateChain;
}
//------------------------------------------------------------------------
CertificateVerificationError::ref SchannelContext::getPeerCertificateVerificationError() const {
- return verificationError_ ? boost::make_shared<CertificateVerificationError>(*verificationError_) : CertificateVerificationError::ref();
+ return verificationError_ ? boost::make_shared<CertificateVerificationError>(*verificationError_) : CertificateVerificationError::ref();
}
//------------------------------------------------------------------------
ByteArray SchannelContext::getFinishMessage() const {
- SecPkgContext_Bindings bindings;
- int ret = QueryContextAttributes(contextHandle_, SECPKG_ATTR_UNIQUE_BINDINGS, &bindings);
- if (ret == SEC_E_OK) {
- return createByteArray(((unsigned char*) bindings.Bindings) + bindings.Bindings->dwApplicationDataOffset + 11 /* tls-unique:*/, bindings.Bindings->cbApplicationDataLength - 11);
- }
- return ByteArray();
+ SecPkgContext_Bindings bindings;
+ int ret = QueryContextAttributes(contextHandle_, SECPKG_ATTR_UNIQUE_BINDINGS, &bindings);
+ if (ret == SEC_E_OK) {
+ return createByteArray(((unsigned char*) bindings.Bindings) + bindings.Bindings->dwApplicationDataOffset + 11 /* tls-unique:*/, bindings.Bindings->cbApplicationDataLength - 11);
+ }
+ return ByteArray();
}
//------------------------------------------------------------------------
void SchannelContext::setCheckCertificateRevocation(bool b) {
- checkCertificateRevocation_ = b;
+ checkCertificateRevocation_ = b;
}
void SchannelContext::setDisconnectOnCardRemoval(bool b) {
- disconnectOnCardRemoval_ = b;
+ disconnectOnCardRemoval_ = b;
}
diff --git a/Swiften/TLS/Schannel/SchannelContext.h b/Swiften/TLS/Schannel/SchannelContext.h
index be30a7c..2c6a3ff 100644
--- a/Swiften/TLS/Schannel/SchannelContext.h
+++ b/Swiften/TLS/Schannel/SchannelContext.h
@@ -28,85 +28,85 @@
#include <boost/noncopyable.hpp>
-namespace Swift
-{
- class CAPICertificate;
- class SchannelContext : public TLSContext, boost::noncopyable
- {
- public:
- typedef boost::shared_ptr<SchannelContext> sp_t;
+namespace Swift
+{
+ class CAPICertificate;
+ class SchannelContext : public TLSContext, boost::noncopyable
+ {
+ public:
+ typedef boost::shared_ptr<SchannelContext> sp_t;
- public:
- SchannelContext(bool tls1_0Workaround);
+ public:
+ SchannelContext(bool tls1_0Workaround);
- virtual ~SchannelContext();
+ virtual ~SchannelContext();
- //
- // TLSContext
- //
- virtual void connect();
- virtual bool setClientCertificate(CertificateWithKey::ref cert);
+ //
+ // TLSContext
+ //
+ virtual void connect();
+ virtual bool setClientCertificate(CertificateWithKey::ref cert);
- virtual void handleDataFromNetwork(const SafeByteArray& data);
- virtual void handleDataFromApplication(const SafeByteArray& data);
+ virtual void handleDataFromNetwork(const SafeByteArray& data);
+ virtual void handleDataFromApplication(const SafeByteArray& data);
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
- virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+ virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const;
- virtual ByteArray getFinishMessage() const;
+ virtual ByteArray getFinishMessage() const;
- virtual void setCheckCertificateRevocation(bool b);
+ virtual void setCheckCertificateRevocation(bool b);
- virtual void setDisconnectOnCardRemoval(bool b);
+ virtual void setDisconnectOnCardRemoval(bool b);
- private:
- void determineStreamSizes();
- void continueHandshake(const SafeByteArray& data);
- void indicateError(boost::shared_ptr<TLSError> error);
- //FIXME: Remove
- void indicateError() {indicateError(boost::make_shared<TLSError>());}
- void handleCertError(SECURITY_STATUS status) ;
+ private:
+ void determineStreamSizes();
+ void continueHandshake(const SafeByteArray& data);
+ void indicateError(boost::shared_ptr<TLSError> error);
+ //FIXME: Remove
+ void indicateError() {indicateError(boost::make_shared<TLSError>());}
+ void handleCertError(SECURITY_STATUS status) ;
- void sendDataOnNetwork(const void* pData, size_t dataSize);
- void forwardDataToApplication(const void* pData, size_t dataSize);
+ void sendDataOnNetwork(const void* pData, size_t dataSize);
+ void forwardDataToApplication(const void* pData, size_t dataSize);
- void decryptAndProcessData(const SafeByteArray& data);
- void encryptAndSendData(const SafeByteArray& data);
+ void decryptAndProcessData(const SafeByteArray& data);
+ void encryptAndSendData(const SafeByteArray& data);
- void appendNewData(const SafeByteArray& data);
- SECURITY_STATUS validateServerCertificate();
+ void appendNewData(const SafeByteArray& data);
+ SECURITY_STATUS validateServerCertificate();
- void handleCertificateCardRemoved();
+ void handleCertificateCardRemoved();
- private:
- enum SchannelState
- {
- Start,
- Connecting,
- Connected,
- Error
+ private:
+ enum SchannelState
+ {
+ Start,
+ Connecting,
+ Connected,
+ Error
- };
+ };
- SchannelState state_;
- boost::optional<CertificateVerificationError> verificationError_;
+ SchannelState state_;
+ boost::optional<CertificateVerificationError> verificationError_;
- ULONG secContext_;
- ScopedCredHandle credHandle_;
- ScopedCtxtHandle contextHandle_;
- DWORD contextFlags_;
- SecPkgContext_StreamSizes streamSizes_;
+ ULONG secContext_;
+ ScopedCredHandle credHandle_;
+ ScopedCtxtHandle contextHandle_;
+ DWORD contextFlags_;
+ SecPkgContext_StreamSizes streamSizes_;
- std::vector<char> receivedData_;
+ std::vector<char> receivedData_;
- HCERTSTORE myCertStore_;
- std::string certStoreName_;
- std::string certName_;
+ HCERTSTORE myCertStore_;
+ std::string certStoreName_;
+ std::string certName_;
////Not needed, most likely
- std::string smartCardReader_; //Can be empty string for non SmartCard certificates
- boost::shared_ptr<CAPICertificate> userCertificate_;
- bool checkCertificateRevocation_;
- bool tls1_0Workaround_;
- bool disconnectOnCardRemoval_;
- };
+ std::string smartCardReader_; //Can be empty string for non SmartCard certificates
+ boost::shared_ptr<CAPICertificate> userCertificate_;
+ bool checkCertificateRevocation_;
+ bool tls1_0Workaround_;
+ bool disconnectOnCardRemoval_;
+ };
}
diff --git a/Swiften/TLS/Schannel/SchannelContextFactory.cpp b/Swiften/TLS/Schannel/SchannelContextFactory.cpp
index dacf19e..f78d386 100644
--- a/Swiften/TLS/Schannel/SchannelContextFactory.cpp
+++ b/Swiften/TLS/Schannel/SchannelContextFactory.cpp
@@ -20,22 +20,22 @@ SchannelContextFactory::SchannelContextFactory() : checkCertificateRevocation(tr
}
bool SchannelContextFactory::canCreate() const {
- return true;
+ return true;
}
TLSContext* SchannelContextFactory::createTLSContext(const TLSOptions& tlsOptions) {
- SchannelContext* context = new SchannelContext(tlsOptions.schannelTLS1_0Workaround);
- context->setCheckCertificateRevocation(checkCertificateRevocation);
- context->setDisconnectOnCardRemoval(disconnectOnCardRemoval);
- return context;
+ SchannelContext* context = new SchannelContext(tlsOptions.schannelTLS1_0Workaround);
+ context->setCheckCertificateRevocation(checkCertificateRevocation);
+ context->setDisconnectOnCardRemoval(disconnectOnCardRemoval);
+ return context;
}
void SchannelContextFactory::setCheckCertificateRevocation(bool b) {
- checkCertificateRevocation = b;
+ checkCertificateRevocation = b;
}
void SchannelContextFactory::setDisconnectOnCardRemoval(bool b) {
- disconnectOnCardRemoval = b;
+ disconnectOnCardRemoval = b;
}
}
diff --git a/Swiften/TLS/Schannel/SchannelContextFactory.h b/Swiften/TLS/Schannel/SchannelContextFactory.h
index 27b7dc9..142f193 100644
--- a/Swiften/TLS/Schannel/SchannelContextFactory.h
+++ b/Swiften/TLS/Schannel/SchannelContextFactory.h
@@ -15,19 +15,19 @@
#include <Swiften/TLS/TLSContextFactory.h>
namespace Swift {
- class SchannelContextFactory : public TLSContextFactory {
- public:
- SchannelContextFactory();
+ class SchannelContextFactory : public TLSContextFactory {
+ public:
+ SchannelContextFactory();
- bool canCreate() const;
- virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
+ bool canCreate() const;
+ virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
- virtual void setCheckCertificateRevocation(bool b);
+ virtual void setCheckCertificateRevocation(bool b);
- virtual void setDisconnectOnCardRemoval(bool b);
+ virtual void setDisconnectOnCardRemoval(bool b);
- public:
- bool checkCertificateRevocation;
- bool disconnectOnCardRemoval;
- };
+ public:
+ bool checkCertificateRevocation;
+ bool disconnectOnCardRemoval;
+ };
}
diff --git a/Swiften/TLS/Schannel/SchannelUtil.h b/Swiften/TLS/Schannel/SchannelUtil.h
index 4f73aac..194ec35 100644
--- a/Swiften/TLS/Schannel/SchannelUtil.h
+++ b/Swiften/TLS/Schannel/SchannelUtil.h
@@ -14,412 +14,412 @@
#include <boost/noncopyable.hpp>
-namespace Swift
+namespace Swift
{
- //
- // Convenience wrapper around the Schannel CredHandle struct.
- //
- class ScopedCredHandle
- {
- private:
- struct HandleContext
- {
- HandleContext()
- {
- ZeroMemory(&m_h, sizeof(m_h));
- }
-
- HandleContext(const CredHandle& h)
- {
- memcpy(&m_h, &h, sizeof(m_h));
- }
-
- ~HandleContext()
- {
- ::FreeCredentialsHandle(&m_h);
- }
-
- CredHandle m_h;
- };
-
- public:
- ScopedCredHandle()
- : m_pHandle( new HandleContext )
- {
- }
-
- explicit ScopedCredHandle(const CredHandle& h)
- : m_pHandle( new HandleContext(h) )
- {
- }
-
- // Copy constructor
- explicit ScopedCredHandle(const ScopedCredHandle& rhs)
- {
- m_pHandle = rhs.m_pHandle;
- }
-
- ~ScopedCredHandle()
- {
- m_pHandle.reset();
- }
-
- PCredHandle Reset()
- {
- CloseHandle();
- return &m_pHandle->m_h;
- }
-
- operator PCredHandle() const
- {
- return &m_pHandle->m_h;
- }
-
- ScopedCredHandle& operator=(const ScopedCredHandle& sh)
- {
- // Only update the internal handle if it's different
- if (&m_pHandle->m_h != &sh.m_pHandle->m_h)
- {
- m_pHandle = sh.m_pHandle;
- }
-
- return *this;
- }
-
- void CloseHandle()
- {
- m_pHandle.reset( new HandleContext );
- }
-
- private:
- boost::shared_ptr<HandleContext> m_pHandle;
- };
-
- //------------------------------------------------------------------------
-
- //
- // Convenience wrapper around the Schannel CtxtHandle struct.
- //
- class ScopedCtxtHandle
- {
- private:
- struct HandleContext
- {
- HandleContext()
- {
- ZeroMemory(&m_h, sizeof(m_h));
- }
-
- ~HandleContext()
- {
- ::DeleteSecurityContext(&m_h);
- }
-
- CtxtHandle m_h;
- };
-
- public:
- ScopedCtxtHandle()
- : m_pHandle( new HandleContext )
- {
- }
-
- explicit ScopedCtxtHandle(CredHandle h)
- : m_pHandle( new HandleContext )
- {
- }
-
- // Copy constructor
- explicit ScopedCtxtHandle(const ScopedCtxtHandle& rhs)
- {
- m_pHandle = rhs.m_pHandle;
- }
-
- ~ScopedCtxtHandle()
- {
- m_pHandle.reset();
- }
-
- PCredHandle Reset()
- {
- CloseHandle();
- return &m_pHandle->m_h;
- }
-
- operator PCredHandle() const
- {
- return &m_pHandle->m_h;
- }
-
- ScopedCtxtHandle& operator=(const ScopedCtxtHandle& sh)
- {
- // Only update the internal handle if it's different
- if (&m_pHandle->m_h != &sh.m_pHandle->m_h)
- {
- m_pHandle = sh.m_pHandle;
- }
-
- return *this;
- }
-
- void CloseHandle()
- {
- m_pHandle.reset( new HandleContext );
- }
-
- private:
- boost::shared_ptr<HandleContext> m_pHandle;
- };
-
- //------------------------------------------------------------------------
-
- //
- // Convenience wrapper around the Schannel ScopedSecBuffer struct.
- //
- class ScopedSecBuffer : boost::noncopyable
- {
- public:
- ScopedSecBuffer(PSecBuffer pSecBuffer)
- : m_pSecBuffer(pSecBuffer)
- {
- }
-
- ~ScopedSecBuffer()
- {
- // Loop through all the output buffers and make sure we free them
- if (m_pSecBuffer->pvBuffer)
- FreeContextBuffer(m_pSecBuffer->pvBuffer);
- }
-
- PSecBuffer AsPtr()
- {
- return m_pSecBuffer;
- }
-
- PSecBuffer operator->()
- {
- return m_pSecBuffer;
- }
-
- private:
- PSecBuffer m_pSecBuffer;
- };
-
- //------------------------------------------------------------------------
-
- //
- // Convenience wrapper around the Schannel PCCERT_CONTEXT.
- //
- class ScopedCertContext
- {
- private:
- struct HandleContext
- {
- HandleContext()
- : m_pCertCtxt(NULL)
- {
- }
-
- HandleContext(PCCERT_CONTEXT pCert)
- : m_pCertCtxt(pCert)
- {
- }
-
- ~HandleContext()
- {
- if (m_pCertCtxt)
- CertFreeCertificateContext(m_pCertCtxt);
- }
-
- PCCERT_CONTEXT m_pCertCtxt;
- };
-
- public:
- ScopedCertContext()
- : m_pHandle( new HandleContext )
- {
- }
-
- explicit ScopedCertContext(PCCERT_CONTEXT pCert)
- : m_pHandle( new HandleContext(pCert) )
- {
- }
-
- // Copy constructor
- ScopedCertContext(const ScopedCertContext& rhs)
- {
- m_pHandle = rhs.m_pHandle;
- }
-
- ~ScopedCertContext()
- {
- m_pHandle.reset();
- }
-
- PCCERT_CONTEXT* Reset()
- {
- FreeContext();
- return &m_pHandle->m_pCertCtxt;
- }
-
- operator PCCERT_CONTEXT() const
- {
- return m_pHandle->m_pCertCtxt;
- }
-
- PCCERT_CONTEXT* GetPointer() const
- {
- return &m_pHandle->m_pCertCtxt;
- }
-
- PCCERT_CONTEXT operator->() const
- {
- return m_pHandle->m_pCertCtxt;
- }
-
- ScopedCertContext& operator=(const ScopedCertContext& sh)
- {
- // Only update the internal handle if it's different
- if (&m_pHandle->m_pCertCtxt != &sh.m_pHandle->m_pCertCtxt)
- {
- m_pHandle = sh.m_pHandle;
- }
-
- return *this;
- }
-
- ScopedCertContext& operator=(PCCERT_CONTEXT pCertCtxt)
- {
- // Only update the internal handle if it's different
- if (m_pHandle && m_pHandle->m_pCertCtxt != pCertCtxt)
- m_pHandle.reset( new HandleContext(pCertCtxt) );
-
- return *this;
- }
-
- void FreeContext()
- {
- m_pHandle.reset( new HandleContext );
- }
-
- private:
- boost::shared_ptr<HandleContext> m_pHandle;
- };
-
- //------------------------------------------------------------------------
-
- //
- // Convenience wrapper around the Schannel HCERTSTORE.
- //
- class ScopedCertStore : boost::noncopyable
- {
- public:
- ScopedCertStore(HCERTSTORE hCertStore)
- : m_hCertStore(hCertStore)
- {
- }
-
- ~ScopedCertStore()
- {
- // Forcefully free all memory related to the store, i.e. we assume all CertContext's that have been opened via this
- // cert store have been closed at this point.
- if (m_hCertStore)
- CertCloseStore(m_hCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
- }
-
- operator HCERTSTORE() const
- {
- return m_hCertStore;
- }
-
- private:
- HCERTSTORE m_hCertStore;
- };
-
- //------------------------------------------------------------------------
-
- //
- // Convenience wrapper around the Schannel CERT_CHAIN_CONTEXT.
- //
- class ScopedCertChainContext
- {
- private:
- struct HandleContext
- {
- HandleContext()
- : m_pCertChainCtxt(NULL)
- {
- }
-
- HandleContext(PCCERT_CHAIN_CONTEXT pCert)
- : m_pCertChainCtxt(pCert)
- {
- }
-
- ~HandleContext()
- {
- if (m_pCertChainCtxt)
- CertFreeCertificateChain(m_pCertChainCtxt);
- }
-
- PCCERT_CHAIN_CONTEXT m_pCertChainCtxt;
- };
-
- public:
- ScopedCertChainContext()
- : m_pHandle( new HandleContext )
- {
- }
-
- explicit ScopedCertChainContext(PCCERT_CHAIN_CONTEXT pCert)
- : m_pHandle( new HandleContext(pCert) )
- {
- }
-
- // Copy constructor
- ScopedCertChainContext(const ScopedCertChainContext& rhs)
- {
- m_pHandle = rhs.m_pHandle;
- }
-
- ~ScopedCertChainContext()
- {
- m_pHandle.reset();
- }
-
- PCCERT_CHAIN_CONTEXT* Reset()
- {
- FreeContext();
- return &m_pHandle->m_pCertChainCtxt;
- }
-
- operator PCCERT_CHAIN_CONTEXT() const
- {
- return m_pHandle->m_pCertChainCtxt;
- }
-
- PCCERT_CHAIN_CONTEXT operator->() const
- {
- return m_pHandle->m_pCertChainCtxt;
- }
-
- ScopedCertChainContext& operator=(const ScopedCertChainContext& sh)
- {
- // Only update the internal handle if it's different
- if (&m_pHandle->m_pCertChainCtxt != &sh.m_pHandle->m_pCertChainCtxt)
- {
- m_pHandle = sh.m_pHandle;
- }
-
- return *this;
- }
-
- void FreeContext()
- {
- m_pHandle.reset( new HandleContext );
- }
-
- private:
- boost::shared_ptr<HandleContext> m_pHandle;
- };
+ //
+ // Convenience wrapper around the Schannel CredHandle struct.
+ //
+ class ScopedCredHandle
+ {
+ private:
+ struct HandleContext
+ {
+ HandleContext()
+ {
+ ZeroMemory(&m_h, sizeof(m_h));
+ }
+
+ HandleContext(const CredHandle& h)
+ {
+ memcpy(&m_h, &h, sizeof(m_h));
+ }
+
+ ~HandleContext()
+ {
+ ::FreeCredentialsHandle(&m_h);
+ }
+
+ CredHandle m_h;
+ };
+
+ public:
+ ScopedCredHandle()
+ : m_pHandle( new HandleContext )
+ {
+ }
+
+ explicit ScopedCredHandle(const CredHandle& h)
+ : m_pHandle( new HandleContext(h) )
+ {
+ }
+
+ // Copy constructor
+ explicit ScopedCredHandle(const ScopedCredHandle& rhs)
+ {
+ m_pHandle = rhs.m_pHandle;
+ }
+
+ ~ScopedCredHandle()
+ {
+ m_pHandle.reset();
+ }
+
+ PCredHandle Reset()
+ {
+ CloseHandle();
+ return &m_pHandle->m_h;
+ }
+
+ operator PCredHandle() const
+ {
+ return &m_pHandle->m_h;
+ }
+
+ ScopedCredHandle& operator=(const ScopedCredHandle& sh)
+ {
+ // Only update the internal handle if it's different
+ if (&m_pHandle->m_h != &sh.m_pHandle->m_h)
+ {
+ m_pHandle = sh.m_pHandle;
+ }
+
+ return *this;
+ }
+
+ void CloseHandle()
+ {
+ m_pHandle.reset( new HandleContext );
+ }
+
+ private:
+ boost::shared_ptr<HandleContext> m_pHandle;
+ };
+
+ //------------------------------------------------------------------------
+
+ //
+ // Convenience wrapper around the Schannel CtxtHandle struct.
+ //
+ class ScopedCtxtHandle
+ {
+ private:
+ struct HandleContext
+ {
+ HandleContext()
+ {
+ ZeroMemory(&m_h, sizeof(m_h));
+ }
+
+ ~HandleContext()
+ {
+ ::DeleteSecurityContext(&m_h);
+ }
+
+ CtxtHandle m_h;
+ };
+
+ public:
+ ScopedCtxtHandle()
+ : m_pHandle( new HandleContext )
+ {
+ }
+
+ explicit ScopedCtxtHandle(CredHandle h)
+ : m_pHandle( new HandleContext )
+ {
+ }
+
+ // Copy constructor
+ explicit ScopedCtxtHandle(const ScopedCtxtHandle& rhs)
+ {
+ m_pHandle = rhs.m_pHandle;
+ }
+
+ ~ScopedCtxtHandle()
+ {
+ m_pHandle.reset();
+ }
+
+ PCredHandle Reset()
+ {
+ CloseHandle();
+ return &m_pHandle->m_h;
+ }
+
+ operator PCredHandle() const
+ {
+ return &m_pHandle->m_h;
+ }
+
+ ScopedCtxtHandle& operator=(const ScopedCtxtHandle& sh)
+ {
+ // Only update the internal handle if it's different
+ if (&m_pHandle->m_h != &sh.m_pHandle->m_h)
+ {
+ m_pHandle = sh.m_pHandle;
+ }
+
+ return *this;
+ }
+
+ void CloseHandle()
+ {
+ m_pHandle.reset( new HandleContext );
+ }
+
+ private:
+ boost::shared_ptr<HandleContext> m_pHandle;
+ };
+
+ //------------------------------------------------------------------------
+
+ //
+ // Convenience wrapper around the Schannel ScopedSecBuffer struct.
+ //
+ class ScopedSecBuffer : boost::noncopyable
+ {
+ public:
+ ScopedSecBuffer(PSecBuffer pSecBuffer)
+ : m_pSecBuffer(pSecBuffer)
+ {
+ }
+
+ ~ScopedSecBuffer()
+ {
+ // Loop through all the output buffers and make sure we free them
+ if (m_pSecBuffer->pvBuffer)
+ FreeContextBuffer(m_pSecBuffer->pvBuffer);
+ }
+
+ PSecBuffer AsPtr()
+ {
+ return m_pSecBuffer;
+ }
+
+ PSecBuffer operator->()
+ {
+ return m_pSecBuffer;
+ }
+
+ private:
+ PSecBuffer m_pSecBuffer;
+ };
+
+ //------------------------------------------------------------------------
+
+ //
+ // Convenience wrapper around the Schannel PCCERT_CONTEXT.
+ //
+ class ScopedCertContext
+ {
+ private:
+ struct HandleContext
+ {
+ HandleContext()
+ : m_pCertCtxt(NULL)
+ {
+ }
+
+ HandleContext(PCCERT_CONTEXT pCert)
+ : m_pCertCtxt(pCert)
+ {
+ }
+
+ ~HandleContext()
+ {
+ if (m_pCertCtxt)
+ CertFreeCertificateContext(m_pCertCtxt);
+ }
+
+ PCCERT_CONTEXT m_pCertCtxt;
+ };
+
+ public:
+ ScopedCertContext()
+ : m_pHandle( new HandleContext )
+ {
+ }
+
+ explicit ScopedCertContext(PCCERT_CONTEXT pCert)
+ : m_pHandle( new HandleContext(pCert) )
+ {
+ }
+
+ // Copy constructor
+ ScopedCertContext(const ScopedCertContext& rhs)
+ {
+ m_pHandle = rhs.m_pHandle;
+ }
+
+ ~ScopedCertContext()
+ {
+ m_pHandle.reset();
+ }
+
+ PCCERT_CONTEXT* Reset()
+ {
+ FreeContext();
+ return &m_pHandle->m_pCertCtxt;
+ }
+
+ operator PCCERT_CONTEXT() const
+ {
+ return m_pHandle->m_pCertCtxt;
+ }
+
+ PCCERT_CONTEXT* GetPointer() const
+ {
+ return &m_pHandle->m_pCertCtxt;
+ }
+
+ PCCERT_CONTEXT operator->() const
+ {
+ return m_pHandle->m_pCertCtxt;
+ }
+
+ ScopedCertContext& operator=(const ScopedCertContext& sh)
+ {
+ // Only update the internal handle if it's different
+ if (&m_pHandle->m_pCertCtxt != &sh.m_pHandle->m_pCertCtxt)
+ {
+ m_pHandle = sh.m_pHandle;
+ }
+
+ return *this;
+ }
+
+ ScopedCertContext& operator=(PCCERT_CONTEXT pCertCtxt)
+ {
+ // Only update the internal handle if it's different
+ if (m_pHandle && m_pHandle->m_pCertCtxt != pCertCtxt)
+ m_pHandle.reset( new HandleContext(pCertCtxt) );
+
+ return *this;
+ }
+
+ void FreeContext()
+ {
+ m_pHandle.reset( new HandleContext );
+ }
+
+ private:
+ boost::shared_ptr<HandleContext> m_pHandle;
+ };
+
+ //------------------------------------------------------------------------
+
+ //
+ // Convenience wrapper around the Schannel HCERTSTORE.
+ //
+ class ScopedCertStore : boost::noncopyable
+ {
+ public:
+ ScopedCertStore(HCERTSTORE hCertStore)
+ : m_hCertStore(hCertStore)
+ {
+ }
+
+ ~ScopedCertStore()
+ {
+ // Forcefully free all memory related to the store, i.e. we assume all CertContext's that have been opened via this
+ // cert store have been closed at this point.
+ if (m_hCertStore)
+ CertCloseStore(m_hCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
+ }
+
+ operator HCERTSTORE() const
+ {
+ return m_hCertStore;
+ }
+
+ private:
+ HCERTSTORE m_hCertStore;
+ };
+
+ //------------------------------------------------------------------------
+
+ //
+ // Convenience wrapper around the Schannel CERT_CHAIN_CONTEXT.
+ //
+ class ScopedCertChainContext
+ {
+ private:
+ struct HandleContext
+ {
+ HandleContext()
+ : m_pCertChainCtxt(NULL)
+ {
+ }
+
+ HandleContext(PCCERT_CHAIN_CONTEXT pCert)
+ : m_pCertChainCtxt(pCert)
+ {
+ }
+
+ ~HandleContext()
+ {
+ if (m_pCertChainCtxt)
+ CertFreeCertificateChain(m_pCertChainCtxt);
+ }
+
+ PCCERT_CHAIN_CONTEXT m_pCertChainCtxt;
+ };
+
+ public:
+ ScopedCertChainContext()
+ : m_pHandle( new HandleContext )
+ {
+ }
+
+ explicit ScopedCertChainContext(PCCERT_CHAIN_CONTEXT pCert)
+ : m_pHandle( new HandleContext(pCert) )
+ {
+ }
+
+ // Copy constructor
+ ScopedCertChainContext(const ScopedCertChainContext& rhs)
+ {
+ m_pHandle = rhs.m_pHandle;
+ }
+
+ ~ScopedCertChainContext()
+ {
+ m_pHandle.reset();
+ }
+
+ PCCERT_CHAIN_CONTEXT* Reset()
+ {
+ FreeContext();
+ return &m_pHandle->m_pCertChainCtxt;
+ }
+
+ operator PCCERT_CHAIN_CONTEXT() const
+ {
+ return m_pHandle->m_pCertChainCtxt;
+ }
+
+ PCCERT_CHAIN_CONTEXT operator->() const
+ {
+ return m_pHandle->m_pCertChainCtxt;
+ }
+
+ ScopedCertChainContext& operator=(const ScopedCertChainContext& sh)
+ {
+ // Only update the internal handle if it's different
+ if (&m_pHandle->m_pCertChainCtxt != &sh.m_pHandle->m_pCertChainCtxt)
+ {
+ m_pHandle = sh.m_pHandle;
+ }
+
+ return *this;
+ }
+
+ void FreeContext()
+ {
+ m_pHandle.reset( new HandleContext );
+ }
+
+ private:
+ boost::shared_ptr<HandleContext> m_pHandle;
+ };
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportCertificate.h b/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
index b8d3728..625c2ae 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
@@ -17,29 +17,29 @@ namespace Swift {
class SecureTransportCertificate : public Certificate {
public:
- SecureTransportCertificate(SecCertificateRef certificate);
- SecureTransportCertificate(const ByteArray& der);
- virtual ~SecureTransportCertificate();
+ SecureTransportCertificate(SecCertificateRef certificate);
+ SecureTransportCertificate(const ByteArray& der);
+ virtual ~SecureTransportCertificate();
- virtual std::string getSubjectName() const;
- virtual std::vector<std::string> getCommonNames() const;
- virtual std::vector<std::string> getSRVNames() const;
- virtual std::vector<std::string> getDNSNames() const;
- virtual std::vector<std::string> getXMPPAddresses() const;
+ virtual std::string getSubjectName() const;
+ virtual std::vector<std::string> getCommonNames() const;
+ virtual std::vector<std::string> getSRVNames() const;
+ virtual std::vector<std::string> getDNSNames() const;
+ virtual std::vector<std::string> getXMPPAddresses() const;
- virtual ByteArray toDER() const;
+ virtual ByteArray toDER() const;
private:
- void parse();
- typedef boost::remove_pointer<SecCertificateRef>::type SecCertificate;
+ void parse();
+ typedef boost::remove_pointer<SecCertificateRef>::type SecCertificate;
private:
- boost::shared_ptr<SecCertificate> certificateHandle_;
- std::string subjectName_;
- std::vector<std::string> commonNames_;
- std::vector<std::string> srvNames_;
- std::vector<std::string> dnsNames_;
- std::vector<std::string> xmppAddresses_;
+ boost::shared_ptr<SecCertificate> certificateHandle_;
+ std::string subjectName_;
+ std::vector<std::string> commonNames_;
+ std::vector<std::string> srvNames_;
+ std::vector<std::string> dnsNames_;
+ std::vector<std::string> xmppAddresses_;
};
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm b/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm
index 6f8e158..398829c 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm
+++ b/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm
@@ -19,7 +19,7 @@ template <typename T, typename S>
T bridge_cast(S source) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
- return (__bridge T)(source);
+ return (__bridge T)(source);
#pragma clang diagnostic pop
}
@@ -29,11 +29,11 @@ namespace {
inline std::string ns2StdString(NSString* _Nullable nsString);
inline std::string ns2StdString(NSString* _Nullable nsString) {
- std::string stdString;
- if (nsString != nil) {
- stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]);
- }
- return stdString;
+ std::string stdString;
+ if (nsString != nil) {
+ stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]);
+ }
+ return stdString;
}
}
@@ -41,21 +41,21 @@ inline std::string ns2StdString(NSString* _Nullable nsString) {
namespace Swift {
SecureTransportCertificate::SecureTransportCertificate(SecCertificateRef certificate) {
- assert(certificate);
- CFRetain(certificate);
- certificateHandle_ = boost::shared_ptr<SecCertificate>(certificate, CFRelease);
- parse();
+ assert(certificate);
+ CFRetain(certificate);
+ certificateHandle_ = boost::shared_ptr<SecCertificate>(certificate, CFRelease);
+ parse();
}
SecureTransportCertificate::SecureTransportCertificate(const ByteArray& der) {
- CFDataRef derData = CFDataCreateWithBytesNoCopy(NULL, der.data(), static_cast<CFIndex>(der.size()), NULL);
- // certificate will take ownership of derData and free it on its release.
- SecCertificateRef certificate = SecCertificateCreateWithData(NULL, derData);
- if (certificate) {
- certificateHandle_ = boost::shared_ptr<SecCertificate>(certificate, CFRelease);
- parse();
- }
+ CFDataRef derData = CFDataCreateWithBytesNoCopy(NULL, der.data(), static_cast<CFIndex>(der.size()), NULL);
+ // certificate will take ownership of derData and free it on its release.
+ SecCertificateRef certificate = SecCertificateCreateWithData(NULL, derData);
+ if (certificate) {
+ certificateHandle_ = boost::shared_ptr<SecCertificate>(certificate, CFRelease);
+ parse();
+ }
}
SecureTransportCertificate::~SecureTransportCertificate() {
@@ -63,89 +63,89 @@ SecureTransportCertificate::~SecureTransportCertificate() {
}
void SecureTransportCertificate::parse() {
- assert(certificateHandle_);
- CFErrorRef error = NULL;
-
- // The SecCertificateCopyValues function is not part of the iOS Secure Transport API.
- CFDictionaryRef valueDict = SecCertificateCopyValues(certificateHandle_.get(), 0, &error);
- if (valueDict) {
- // Handle subject.
- CFStringRef subject = SecCertificateCopySubjectSummary(certificateHandle_.get());
- if (subject) {
- NSString* subjectStr = bridge_cast<NSString*>(subject);
- subjectName_ = ns2StdString(subjectStr);
- CFRelease(subject);
- }
-
- // Handle a single Common Name.
- CFStringRef commonName = NULL;
- OSStatus error = SecCertificateCopyCommonName(certificateHandle_.get(), &commonName);
- if (!error && commonName) {
- NSString* commonNameStr = bridge_cast<NSString*>(commonName);
- commonNames_.push_back(ns2StdString(commonNameStr));
- }
- if (commonName) {
- CFRelease(commonName);
- }
-
- // Handle Subject Alternative Names
- NSDictionary* certDict = bridge_cast<NSDictionary*>(valueDict);
- NSDictionary* subjectAltNamesDict = certDict[@"2.5.29.17"][@"value"];
-
- for (NSDictionary* entry in subjectAltNamesDict) {
- if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_XMPPADDR_OID])]) {
- xmppAddresses_.push_back(ns2StdString(entry[@"value"]));
- }
- else if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_DNSSRV_OID])]) {
- srvNames_.push_back(ns2StdString(entry[@"value"]));
- }
- else if ([entry[@"label"] isEqualToString:@"DNS Name"]) {
- dnsNames_.push_back(ns2StdString(entry[@"value"]));
- }
- }
- CFRelease(valueDict);
- }
-
- if (error) {
- CFRelease(error);
- }
+ assert(certificateHandle_);
+ CFErrorRef error = NULL;
+
+ // The SecCertificateCopyValues function is not part of the iOS Secure Transport API.
+ CFDictionaryRef valueDict = SecCertificateCopyValues(certificateHandle_.get(), 0, &error);
+ if (valueDict) {
+ // Handle subject.
+ CFStringRef subject = SecCertificateCopySubjectSummary(certificateHandle_.get());
+ if (subject) {
+ NSString* subjectStr = bridge_cast<NSString*>(subject);
+ subjectName_ = ns2StdString(subjectStr);
+ CFRelease(subject);
+ }
+
+ // Handle a single Common Name.
+ CFStringRef commonName = NULL;
+ OSStatus error = SecCertificateCopyCommonName(certificateHandle_.get(), &commonName);
+ if (!error && commonName) {
+ NSString* commonNameStr = bridge_cast<NSString*>(commonName);
+ commonNames_.push_back(ns2StdString(commonNameStr));
+ }
+ if (commonName) {
+ CFRelease(commonName);
+ }
+
+ // Handle Subject Alternative Names
+ NSDictionary* certDict = bridge_cast<NSDictionary*>(valueDict);
+ NSDictionary* subjectAltNamesDict = certDict[@"2.5.29.17"][@"value"];
+
+ for (NSDictionary* entry in subjectAltNamesDict) {
+ if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_XMPPADDR_OID])]) {
+ xmppAddresses_.push_back(ns2StdString(entry[@"value"]));
+ }
+ else if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_DNSSRV_OID])]) {
+ srvNames_.push_back(ns2StdString(entry[@"value"]));
+ }
+ else if ([entry[@"label"] isEqualToString:@"DNS Name"]) {
+ dnsNames_.push_back(ns2StdString(entry[@"value"]));
+ }
+ }
+ CFRelease(valueDict);
+ }
+
+ if (error) {
+ CFRelease(error);
+ }
}
std::string SecureTransportCertificate::getSubjectName() const {
- return subjectName_;
+ return subjectName_;
}
std::vector<std::string> SecureTransportCertificate::getCommonNames() const {
- return commonNames_;
+ return commonNames_;
}
std::vector<std::string> SecureTransportCertificate::getSRVNames() const {
- return srvNames_;
+ return srvNames_;
}
std::vector<std::string> SecureTransportCertificate::getDNSNames() const {
- return dnsNames_;
+ return dnsNames_;
}
std::vector<std::string> SecureTransportCertificate::getXMPPAddresses() const {
- return xmppAddresses_;
+ return xmppAddresses_;
}
ByteArray SecureTransportCertificate::toDER() const {
- ByteArray der;
- if (certificateHandle_) {
- CFDataRef derData = SecCertificateCopyData(certificateHandle_.get());
- if (derData) {
- try {
- size_t dataSize = boost::numeric_cast<size_t>(CFDataGetLength(derData));
- der.resize(dataSize);
- CFDataGetBytes(derData, CFRangeMake(0,CFDataGetLength(derData)), der.data());
- } catch (...) {
- }
- CFRelease(derData);
- }
- }
- return der;
+ ByteArray der;
+ if (certificateHandle_) {
+ CFDataRef derData = SecCertificateCopyData(certificateHandle_.get());
+ if (derData) {
+ try {
+ size_t dataSize = boost::numeric_cast<size_t>(CFDataGetLength(derData));
+ der.resize(dataSize);
+ CFDataGetBytes(derData, CFRangeMake(0,CFDataGetLength(derData)), der.data());
+ } catch (...) {
+ }
+ CFRelease(derData);
+ }
+ }
+ return der;
}
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h b/Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h
index 1f86541..3ea469d 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h
@@ -10,11 +10,11 @@
#include <Swiften/TLS/SecureTransport/SecureTransportCertificate.h>
namespace Swift {
-
+
class SecureTransportCertificateFactory : public CertificateFactory {
- public:
- virtual Certificate* createCertificateFromDER(const ByteArray& der) {
- return new SecureTransportCertificate(der);
- }
- };
+ public:
+ virtual Certificate* createCertificateFromDER(const ByteArray& der) {
+ return new SecureTransportCertificate(der);
+ }
+ };
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContext.h b/Swiften/TLS/SecureTransport/SecureTransportContext.h
index aa17c66..4d45f52 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContext.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportContext.h
@@ -13,46 +13,46 @@
namespace Swift {
class SecureTransportContext : public TLSContext {
- public:
- SecureTransportContext(bool checkCertificateRevocation);
- virtual ~SecureTransportContext();
+ public:
+ SecureTransportContext(bool checkCertificateRevocation);
+ virtual ~SecureTransportContext();
- virtual void connect();
+ virtual void connect();
- virtual bool setClientCertificate(CertificateWithKey::ref cert);
+ virtual bool setClientCertificate(CertificateWithKey::ref cert);
- virtual void handleDataFromNetwork(const SafeByteArray&);
- virtual void handleDataFromApplication(const SafeByteArray&);
+ virtual void handleDataFromNetwork(const SafeByteArray&);
+ virtual void handleDataFromApplication(const SafeByteArray&);
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
- virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+ virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const;
- virtual ByteArray getFinishMessage() const;
-
- private:
- static OSStatus SSLSocketReadCallback(SSLConnectionRef connection, void *data, size_t *dataLength);
- static OSStatus SSLSocketWriteCallback(SSLConnectionRef connection, const void *data, size_t *dataLength);
+ virtual ByteArray getFinishMessage() const;
- private:
- enum State { None, Handshake, HandshakeDone, Error};
- static std::string stateToString(State state);
- void setState(State newState);
+ private:
+ static OSStatus SSLSocketReadCallback(SSLConnectionRef connection, void *data, size_t *dataLength);
+ static OSStatus SSLSocketWriteCallback(SSLConnectionRef connection, const void *data, size_t *dataLength);
- static boost::shared_ptr<TLSError> nativeToTLSError(OSStatus error);
- boost::shared_ptr<CertificateVerificationError> CSSMErrorToVerificationError(OSStatus resultCode);
+ private:
+ enum State { None, Handshake, HandshakeDone, Error};
+ static std::string stateToString(State state);
+ void setState(State newState);
- void processHandshake();
- void verifyServerCertificate();
+ static boost::shared_ptr<TLSError> nativeToTLSError(OSStatus error);
+ boost::shared_ptr<CertificateVerificationError> CSSMErrorToVerificationError(OSStatus resultCode);
- void fatalError(boost::shared_ptr<TLSError> error, boost::shared_ptr<CertificateVerificationError> certificateError);
+ void processHandshake();
+ void verifyServerCertificate();
- private:
- boost::shared_ptr<SSLContext> sslContext_;
- SafeByteArray readingBuffer_;
- State state_;
- CertificateVerificationError::ref verificationError_;
- CertificateWithKey::ref clientCertificate_;
- bool checkCertificateRevocation_;
+ void fatalError(boost::shared_ptr<TLSError> error, boost::shared_ptr<CertificateVerificationError> certificateError);
+
+ private:
+ boost::shared_ptr<SSLContext> sslContext_;
+ SafeByteArray readingBuffer_;
+ State state_;
+ CertificateVerificationError::ref verificationError_;
+ CertificateWithKey::ref clientCertificate_;
+ bool checkCertificateRevocation_;
};
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContext.mm b/Swiften/TLS/SecureTransport/SecureTransportContext.mm
index ca6c5bb..62889fd 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContext.mm
+++ b/Swiften/TLS/SecureTransport/SecureTransportContext.mm
@@ -21,15 +21,15 @@
#import <Security/SecImportExport.h>
namespace {
- typedef boost::remove_pointer<CFArrayRef>::type CFArray;
- typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
+ typedef boost::remove_pointer<CFArrayRef>::type CFArray;
+ typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
}
template <typename T, typename S>
T bridge_cast(S source) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
- return (__bridge T)(source);
+ return (__bridge T)(source);
#pragma clang diagnostic pop
}
@@ -37,162 +37,162 @@ namespace Swift {
namespace {
-
+
CFArrayRef CreateClientCertificateChainAsCFArrayRef(CertificateWithKey::ref key) {
- boost::shared_ptr<PKCS12Certificate> pkcs12 = boost::dynamic_pointer_cast<PKCS12Certificate>(key);
- if (!key) {
- return NULL;
- }
-
- SafeByteArray safePassword = pkcs12->getPassword();
- CFIndex passwordSize = 0;
- try {
- passwordSize = boost::numeric_cast<CFIndex>(safePassword.size());
- } catch (...) {
- return NULL;
- }
-
- CFMutableArrayRef certChain = CFArrayCreateMutable(NULL, 0, 0);
-
- OSStatus securityError = errSecSuccess;
- CFStringRef password = CFStringCreateWithBytes(kCFAllocatorDefault, safePassword.data(), passwordSize, kCFStringEncodingUTF8, false);
- const void* keys[] = { kSecImportExportPassphrase };
- const void* values[] = { password };
-
- CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
-
- CFArrayRef items = NULL;
- CFDataRef pkcs12Data = bridge_cast<CFDataRef>([NSData dataWithBytes: static_cast<const void *>(pkcs12->getData().data()) length:pkcs12->getData().size()]);
- securityError = SecPKCS12Import(pkcs12Data, options, &items);
- CFRelease(options);
- NSArray* nsItems = bridge_cast<NSArray*>(items);
-
- switch(securityError) {
- case errSecSuccess:
- break;
- case errSecAuthFailed:
- // Password did not work for decoding the certificate.
- SWIFT_LOG(warning) << "Invalid password." << std::endl;
- break;
- case errSecDecode:
- // Other decoding error.
- SWIFT_LOG(warning) << "PKCS12 decoding error." << std::endl;
- break;
- default:
- SWIFT_LOG(warning) << "Unknown error." << std::endl;
- }
-
- if (securityError != errSecSuccess) {
- if (items) {
- CFRelease(items);
- items = NULL;
- }
- CFRelease(certChain);
- certChain = NULL;
- }
-
- if (certChain) {
- CFArrayAppendValue(certChain, nsItems[0][@"identity"]);
-
- for (CFIndex index = 0; index < CFArrayGetCount(bridge_cast<CFArrayRef>(nsItems[0][@"chain"])); index++) {
- CFArrayAppendValue(certChain, CFArrayGetValueAtIndex(bridge_cast<CFArrayRef>(nsItems[0][@"chain"]), index));
- }
- }
- return certChain;
+ boost::shared_ptr<PKCS12Certificate> pkcs12 = boost::dynamic_pointer_cast<PKCS12Certificate>(key);
+ if (!key) {
+ return NULL;
+ }
+
+ SafeByteArray safePassword = pkcs12->getPassword();
+ CFIndex passwordSize = 0;
+ try {
+ passwordSize = boost::numeric_cast<CFIndex>(safePassword.size());
+ } catch (...) {
+ return NULL;
+ }
+
+ CFMutableArrayRef certChain = CFArrayCreateMutable(NULL, 0, 0);
+
+ OSStatus securityError = errSecSuccess;
+ CFStringRef password = CFStringCreateWithBytes(kCFAllocatorDefault, safePassword.data(), passwordSize, kCFStringEncodingUTF8, false);
+ const void* keys[] = { kSecImportExportPassphrase };
+ const void* values[] = { password };
+
+ CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
+
+ CFArrayRef items = NULL;
+ CFDataRef pkcs12Data = bridge_cast<CFDataRef>([NSData dataWithBytes: static_cast<const void *>(pkcs12->getData().data()) length:pkcs12->getData().size()]);
+ securityError = SecPKCS12Import(pkcs12Data, options, &items);
+ CFRelease(options);
+ NSArray* nsItems = bridge_cast<NSArray*>(items);
+
+ switch(securityError) {
+ case errSecSuccess:
+ break;
+ case errSecAuthFailed:
+ // Password did not work for decoding the certificate.
+ SWIFT_LOG(warning) << "Invalid password." << std::endl;
+ break;
+ case errSecDecode:
+ // Other decoding error.
+ SWIFT_LOG(warning) << "PKCS12 decoding error." << std::endl;
+ break;
+ default:
+ SWIFT_LOG(warning) << "Unknown error." << std::endl;
+ }
+
+ if (securityError != errSecSuccess) {
+ if (items) {
+ CFRelease(items);
+ items = NULL;
+ }
+ CFRelease(certChain);
+ certChain = NULL;
+ }
+
+ if (certChain) {
+ CFArrayAppendValue(certChain, nsItems[0][@"identity"]);
+
+ for (CFIndex index = 0; index < CFArrayGetCount(bridge_cast<CFArrayRef>(nsItems[0][@"chain"])); index++) {
+ CFArrayAppendValue(certChain, CFArrayGetValueAtIndex(bridge_cast<CFArrayRef>(nsItems[0][@"chain"]), index));
+ }
+ }
+ return certChain;
}
}
SecureTransportContext::SecureTransportContext(bool checkCertificateRevocation) : state_(None), checkCertificateRevocation_(checkCertificateRevocation) {
- sslContext_ = boost::shared_ptr<SSLContext>(SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType), CFRelease);
-
- OSStatus error = noErr;
- // set IO callbacks
- error = SSLSetIOFuncs(sslContext_.get(), &SecureTransportContext::SSLSocketReadCallback, &SecureTransportContext::SSLSocketWriteCallback);
- if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set IO functions to SSL context." << std::endl;
- sslContext_.reset();
- }
-
- error = SSLSetConnection(sslContext_.get(), this);
- if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set connection to SSL context." << std::endl;
- sslContext_.reset();
- }
-
-
- error = SSLSetSessionOption(sslContext_.get(), kSSLSessionOptionBreakOnServerAuth, true);
- if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set kSSLSessionOptionBreakOnServerAuth on session." << std::endl;
- sslContext_.reset();
- }
+ sslContext_ = boost::shared_ptr<SSLContext>(SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType), CFRelease);
+
+ OSStatus error = noErr;
+ // set IO callbacks
+ error = SSLSetIOFuncs(sslContext_.get(), &SecureTransportContext::SSLSocketReadCallback, &SecureTransportContext::SSLSocketWriteCallback);
+ if (error != noErr) {
+ SWIFT_LOG(error) << "Unable to set IO functions to SSL context." << std::endl;
+ sslContext_.reset();
+ }
+
+ error = SSLSetConnection(sslContext_.get(), this);
+ if (error != noErr) {
+ SWIFT_LOG(error) << "Unable to set connection to SSL context." << std::endl;
+ sslContext_.reset();
+ }
+
+
+ error = SSLSetSessionOption(sslContext_.get(), kSSLSessionOptionBreakOnServerAuth, true);
+ if (error != noErr) {
+ SWIFT_LOG(error) << "Unable to set kSSLSessionOptionBreakOnServerAuth on session." << std::endl;
+ sslContext_.reset();
+ }
}
SecureTransportContext::~SecureTransportContext() {
- if (sslContext_) {
- SSLClose(sslContext_.get());
- }
+ if (sslContext_) {
+ SSLClose(sslContext_.get());
+ }
}
std::string SecureTransportContext::stateToString(State state) {
- std::string returnValue;
- switch(state) {
- case Handshake:
- returnValue = "Handshake";
- break;
- case HandshakeDone:
- returnValue = "HandshakeDone";
- break;
- case None:
- returnValue = "None";
- break;
- case Error:
- returnValue = "Error";
- break;
- }
- return returnValue;
+ std::string returnValue;
+ switch(state) {
+ case Handshake:
+ returnValue = "Handshake";
+ break;
+ case HandshakeDone:
+ returnValue = "HandshakeDone";
+ break;
+ case None:
+ returnValue = "None";
+ break;
+ case Error:
+ returnValue = "Error";
+ break;
+ }
+ return returnValue;
}
void SecureTransportContext::setState(State newState) {
- SWIFT_LOG(debug) << "Switch state from " << stateToString(state_) << " to " << stateToString(newState) << "." << std::endl;
- state_ = newState;
+ SWIFT_LOG(debug) << "Switch state from " << stateToString(state_) << " to " << stateToString(newState) << "." << std::endl;
+ state_ = newState;
}
void SecureTransportContext::connect() {
- SWIFT_LOG_ASSERT(state_ == None, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
- if (clientCertificate_) {
- CFArrayRef certs = CreateClientCertificateChainAsCFArrayRef(clientCertificate_);
- if (certs) {
- boost::shared_ptr<CFArray> certRefs(certs, CFRelease);
- OSStatus result = SSLSetCertificate(sslContext_.get(), certRefs.get());
- if (result != noErr) {
- SWIFT_LOG(error) << "SSLSetCertificate failed with error " << result << "." << std::endl;
- }
- }
- }
- processHandshake();
+ SWIFT_LOG_ASSERT(state_ == None, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+ if (clientCertificate_) {
+ CFArrayRef certs = CreateClientCertificateChainAsCFArrayRef(clientCertificate_);
+ if (certs) {
+ boost::shared_ptr<CFArray> certRefs(certs, CFRelease);
+ OSStatus result = SSLSetCertificate(sslContext_.get(), certRefs.get());
+ if (result != noErr) {
+ SWIFT_LOG(error) << "SSLSetCertificate failed with error " << result << "." << std::endl;
+ }
+ }
+ }
+ processHandshake();
}
void SecureTransportContext::processHandshake() {
- SWIFT_LOG_ASSERT(state_ == None || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
- OSStatus error = SSLHandshake(sslContext_.get());
- if (error == errSSLWouldBlock) {
- setState(Handshake);
- }
- else if (error == noErr) {
- SWIFT_LOG(debug) << "TLS handshake successful." << std::endl;
- setState(HandshakeDone);
- onConnected();
- }
- else if (error == errSSLPeerAuthCompleted) {
- SWIFT_LOG(debug) << "Received server certificate. Start verification." << std::endl;
- setState(Handshake);
- verifyServerCertificate();
- }
- else {
- SWIFT_LOG(debug) << "Error returned from SSLHandshake call is " << error << "." << std::endl;
- fatalError(nativeToTLSError(error), boost::make_shared<CertificateVerificationError>());
- }
+ SWIFT_LOG_ASSERT(state_ == None || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+ OSStatus error = SSLHandshake(sslContext_.get());
+ if (error == errSSLWouldBlock) {
+ setState(Handshake);
+ }
+ else if (error == noErr) {
+ SWIFT_LOG(debug) << "TLS handshake successful." << std::endl;
+ setState(HandshakeDone);
+ onConnected();
+ }
+ else if (error == errSSLPeerAuthCompleted) {
+ SWIFT_LOG(debug) << "Received server certificate. Start verification." << std::endl;
+ setState(Handshake);
+ verifyServerCertificate();
+ }
+ else {
+ SWIFT_LOG(debug) << "Error returned from SSLHandshake call is " << error << "." << std::endl;
+ fatalError(nativeToTLSError(error), boost::make_shared<CertificateVerificationError>());
+ }
}
@@ -200,296 +200,296 @@ void SecureTransportContext::processHandshake() {
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
void SecureTransportContext::verifyServerCertificate() {
- SecTrustRef trust = NULL;
- OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &trust);
- if (error != noErr) {
- fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
- return;
- }
- boost::shared_ptr<SecTrust> trustRef = boost::shared_ptr<SecTrust>(trust, CFRelease);
-
- if (checkCertificateRevocation_) {
- error = SecTrustSetOptions(trust, kSecTrustOptionRequireRevPerCert | kSecTrustOptionFetchIssuerFromNet);
- if (error != noErr) {
- fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
- return;
- }
- }
-
- SecTrustResultType trustResult;
- error = SecTrustEvaluate(trust, &trustResult);
- if (error != errSecSuccess) {
- fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
- return;
- }
-
- OSStatus cssmResult = 0;
- switch(trustResult) {
- case kSecTrustResultUnspecified:
- SWIFT_LOG(warning) << "Successful implicit validation. Result unspecified." << std::endl;
- break;
- case kSecTrustResultProceed:
- SWIFT_LOG(warning) << "Validation resulted in explicitly trusted." << std::endl;
- break;
- case kSecTrustResultRecoverableTrustFailure:
- SWIFT_LOG(warning) << "recoverable trust failure" << std::endl;
- error = SecTrustGetCssmResultCode(trust, &cssmResult);
- if (error == errSecSuccess) {
- verificationError_ = CSSMErrorToVerificationError(cssmResult);
- if (cssmResult == CSSMERR_TP_VERIFY_ACTION_FAILED || cssmResult == CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK ) {
- // Find out the reason why the verification failed.
- CFArrayRef certChain;
- CSSM_TP_APPLE_EVIDENCE_INFO* statusChain;
- error = SecTrustGetResult(trustRef.get(), &trustResult, &certChain, &statusChain);
- if (error == errSecSuccess) {
- boost::shared_ptr<CFArray> certChainRef = boost::shared_ptr<CFArray>(certChain, CFRelease);
- for (CFIndex index = 0; index < CFArrayGetCount(certChainRef.get()); index++) {
- for (CFIndex n = 0; n < statusChain[index].NumStatusCodes; n++) {
- // Even though Secure Transport reported CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK on the whole certificate
- // chain, the actual cause can be that a revocation check for a specific cert returned CSSMERR_TP_CERT_REVOKED.
- if (!verificationError_ || verificationError_->getType() == CertificateVerificationError::RevocationCheckFailed) {
- verificationError_ = CSSMErrorToVerificationError(statusChain[index].StatusCodes[n]);
- }
- }
- }
- }
- else {
-
- }
- }
- }
- else {
- verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
- }
- break;
- case kSecTrustResultOtherError:
- verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
- break;
- default:
- SWIFT_LOG(warning) << "Unhandled trust result " << trustResult << "." << std::endl;
- break;
- }
-
- // We proceed with the TLS handshake here to give the application an opportunity
- // to apply custom validation and trust management. The application is responsible
- // to call \ref getPeerCertificateVerificationError directly after the \ref onConnected
- // signal is called and before any application data is send to the context.
- processHandshake();
+ SecTrustRef trust = NULL;
+ OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &trust);
+ if (error != noErr) {
+ fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
+ return;
+ }
+ boost::shared_ptr<SecTrust> trustRef = boost::shared_ptr<SecTrust>(trust, CFRelease);
+
+ if (checkCertificateRevocation_) {
+ error = SecTrustSetOptions(trust, kSecTrustOptionRequireRevPerCert | kSecTrustOptionFetchIssuerFromNet);
+ if (error != noErr) {
+ fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
+ return;
+ }
+ }
+
+ SecTrustResultType trustResult;
+ error = SecTrustEvaluate(trust, &trustResult);
+ if (error != errSecSuccess) {
+ fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
+ return;
+ }
+
+ OSStatus cssmResult = 0;
+ switch(trustResult) {
+ case kSecTrustResultUnspecified:
+ SWIFT_LOG(warning) << "Successful implicit validation. Result unspecified." << std::endl;
+ break;
+ case kSecTrustResultProceed:
+ SWIFT_LOG(warning) << "Validation resulted in explicitly trusted." << std::endl;
+ break;
+ case kSecTrustResultRecoverableTrustFailure:
+ SWIFT_LOG(warning) << "recoverable trust failure" << std::endl;
+ error = SecTrustGetCssmResultCode(trust, &cssmResult);
+ if (error == errSecSuccess) {
+ verificationError_ = CSSMErrorToVerificationError(cssmResult);
+ if (cssmResult == CSSMERR_TP_VERIFY_ACTION_FAILED || cssmResult == CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK ) {
+ // Find out the reason why the verification failed.
+ CFArrayRef certChain;
+ CSSM_TP_APPLE_EVIDENCE_INFO* statusChain;
+ error = SecTrustGetResult(trustRef.get(), &trustResult, &certChain, &statusChain);
+ if (error == errSecSuccess) {
+ boost::shared_ptr<CFArray> certChainRef = boost::shared_ptr<CFArray>(certChain, CFRelease);
+ for (CFIndex index = 0; index < CFArrayGetCount(certChainRef.get()); index++) {
+ for (CFIndex n = 0; n < statusChain[index].NumStatusCodes; n++) {
+ // Even though Secure Transport reported CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK on the whole certificate
+ // chain, the actual cause can be that a revocation check for a specific cert returned CSSMERR_TP_CERT_REVOKED.
+ if (!verificationError_ || verificationError_->getType() == CertificateVerificationError::RevocationCheckFailed) {
+ verificationError_ = CSSMErrorToVerificationError(statusChain[index].StatusCodes[n]);
+ }
+ }
+ }
+ }
+ else {
+
+ }
+ }
+ }
+ else {
+ verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ }
+ break;
+ case kSecTrustResultOtherError:
+ verificationError_ = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ break;
+ default:
+ SWIFT_LOG(warning) << "Unhandled trust result " << trustResult << "." << std::endl;
+ break;
+ }
+
+ // We proceed with the TLS handshake here to give the application an opportunity
+ // to apply custom validation and trust management. The application is responsible
+ // to call \ref getPeerCertificateVerificationError directly after the \ref onConnected
+ // signal is called and before any application data is send to the context.
+ processHandshake();
}
#pragma clang diagnostic pop
bool SecureTransportContext::setClientCertificate(CertificateWithKey::ref cert) {
- CFArrayRef nativeClientChain = CreateClientCertificateChainAsCFArrayRef(cert);
- if (nativeClientChain) {
- clientCertificate_ = cert;
- CFRelease(nativeClientChain);
- return true;
- }
- else {
- return false;
- }
+ CFArrayRef nativeClientChain = CreateClientCertificateChainAsCFArrayRef(cert);
+ if (nativeClientChain) {
+ clientCertificate_ = cert;
+ CFRelease(nativeClientChain);
+ return true;
+ }
+ else {
+ return false;
+ }
}
void SecureTransportContext::handleDataFromNetwork(const SafeByteArray& data) {
- SWIFT_LOG(debug) << std::endl;
- SWIFT_LOG_ASSERT(state_ == HandshakeDone || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
-
- append(readingBuffer_, data);
-
- size_t bytesRead = 0;
- OSStatus error = noErr;
- SafeByteArray applicationData;
-
- switch(state_) {
- case None:
- assert(false && "Invalid state 'None'.");
- break;
- case Handshake:
- processHandshake();
- break;
- case HandshakeDone:
- while (error == noErr) {
- applicationData.resize(readingBuffer_.size());
- error = SSLRead(sslContext_.get(), applicationData.data(), applicationData.size(), &bytesRead);
- if (error == noErr) {
- // Read successful.
- }
- else if (error == errSSLWouldBlock) {
- // Secure Transport does not want more data.
- break;
- }
- else {
- SWIFT_LOG(error) << "SSLRead failed with error " << error << ", read bytes: " << bytesRead << "." << std::endl;
- fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
- return;
- }
-
- if (bytesRead > 0) {
- applicationData.resize(bytesRead);
- onDataForApplication(applicationData);
- }
- else {
- break;
- }
- }
- break;
- case Error:
- SWIFT_LOG(debug) << "Igoring received data in error state." << std::endl;
- break;
- }
+ SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG_ASSERT(state_ == HandshakeDone || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+
+ append(readingBuffer_, data);
+
+ size_t bytesRead = 0;
+ OSStatus error = noErr;
+ SafeByteArray applicationData;
+
+ switch(state_) {
+ case None:
+ assert(false && "Invalid state 'None'.");
+ break;
+ case Handshake:
+ processHandshake();
+ break;
+ case HandshakeDone:
+ while (error == noErr) {
+ applicationData.resize(readingBuffer_.size());
+ error = SSLRead(sslContext_.get(), applicationData.data(), applicationData.size(), &bytesRead);
+ if (error == noErr) {
+ // Read successful.
+ }
+ else if (error == errSSLWouldBlock) {
+ // Secure Transport does not want more data.
+ break;
+ }
+ else {
+ SWIFT_LOG(error) << "SSLRead failed with error " << error << ", read bytes: " << bytesRead << "." << std::endl;
+ fatalError(boost::make_shared<TLSError>(), boost::make_shared<CertificateVerificationError>());
+ return;
+ }
+
+ if (bytesRead > 0) {
+ applicationData.resize(bytesRead);
+ onDataForApplication(applicationData);
+ }
+ else {
+ break;
+ }
+ }
+ break;
+ case Error:
+ SWIFT_LOG(debug) << "Igoring received data in error state." << std::endl;
+ break;
+ }
}
void SecureTransportContext::handleDataFromApplication(const SafeByteArray& data) {
- size_t processedBytes = 0;
- OSStatus error = SSLWrite(sslContext_.get(), data.data(), data.size(), &processedBytes);
- switch(error) {
- case errSSLWouldBlock:
- SWIFT_LOG(warning) << "Unexpected because the write callback does not block." << std::endl;
- return;
- case errSSLClosedGraceful:
- case noErr:
- return;
- default:
- SWIFT_LOG(warning) << "SSLWrite returned error code: " << error << ", processed bytes: " << processedBytes << std::endl;
- fatalError(boost::make_shared<TLSError>(), boost::shared_ptr<CertificateVerificationError>());
- }
+ size_t processedBytes = 0;
+ OSStatus error = SSLWrite(sslContext_.get(), data.data(), data.size(), &processedBytes);
+ switch(error) {
+ case errSSLWouldBlock:
+ SWIFT_LOG(warning) << "Unexpected because the write callback does not block." << std::endl;
+ return;
+ case errSSLClosedGraceful:
+ case noErr:
+ return;
+ default:
+ SWIFT_LOG(warning) << "SSLWrite returned error code: " << error << ", processed bytes: " << processedBytes << std::endl;
+ fatalError(boost::make_shared<TLSError>(), boost::shared_ptr<CertificateVerificationError>());
+ }
}
std::vector<Certificate::ref> SecureTransportContext::getPeerCertificateChain() const {
- std::vector<Certificate::ref> peerCertificateChain;
-
- if (sslContext_) {
- typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
- boost::shared_ptr<SecTrust> securityTrust;
-
- SecTrustRef secTrust = NULL;;
- OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &secTrust);
- if (error == noErr) {
- securityTrust = boost::shared_ptr<SecTrust>(secTrust, CFRelease);
-
- CFIndex chainSize = SecTrustGetCertificateCount(securityTrust.get());
- for (CFIndex n = 0; n < chainSize; n++) {
- SecCertificateRef certificate = SecTrustGetCertificateAtIndex(securityTrust.get(), n);
- if (certificate) {
- peerCertificateChain.push_back(boost::make_shared<SecureTransportCertificate>(certificate));
- }
- }
- }
- else {
- SWIFT_LOG(warning) << "Failed to obtain peer trust structure; error = " << error << "." << std::endl;
- }
- }
-
- return peerCertificateChain;
+ std::vector<Certificate::ref> peerCertificateChain;
+
+ if (sslContext_) {
+ typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
+ boost::shared_ptr<SecTrust> securityTrust;
+
+ SecTrustRef secTrust = NULL;;
+ OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &secTrust);
+ if (error == noErr) {
+ securityTrust = boost::shared_ptr<SecTrust>(secTrust, CFRelease);
+
+ CFIndex chainSize = SecTrustGetCertificateCount(securityTrust.get());
+ for (CFIndex n = 0; n < chainSize; n++) {
+ SecCertificateRef certificate = SecTrustGetCertificateAtIndex(securityTrust.get(), n);
+ if (certificate) {
+ peerCertificateChain.push_back(boost::make_shared<SecureTransportCertificate>(certificate));
+ }
+ }
+ }
+ else {
+ SWIFT_LOG(warning) << "Failed to obtain peer trust structure; error = " << error << "." << std::endl;
+ }
+ }
+
+ return peerCertificateChain;
}
CertificateVerificationError::ref SecureTransportContext::getPeerCertificateVerificationError() const {
- return verificationError_;
+ return verificationError_;
}
ByteArray SecureTransportContext::getFinishMessage() const {
- SWIFT_LOG(warning) << "Access to TLS handshake finish message is not part of OS X Secure Transport APIs." << std::endl;
- return ByteArray();
+ SWIFT_LOG(warning) << "Access to TLS handshake finish message is not part of OS X Secure Transport APIs." << std::endl;
+ return ByteArray();
}
/**
- * This I/O callback simulates an asynchronous read to the read buffer of the context. If it is empty, it returns errSSLWouldBlock; else
+ * This I/O callback simulates an asynchronous read to the read buffer of the context. If it is empty, it returns errSSLWouldBlock; else
* the data within the buffer is returned.
*/
OSStatus SecureTransportContext::SSLSocketReadCallback(SSLConnectionRef connection, void *data, size_t *dataLength) {
- SecureTransportContext* context = const_cast<SecureTransportContext*>(static_cast<const SecureTransportContext*>(connection));
- OSStatus retValue = noErr;
-
- if (context->readingBuffer_.size() < *dataLength) {
- // Would block because Secure Transport is trying to read more data than there currently is available in the buffer.
- *dataLength = 0;
- retValue = errSSLWouldBlock;
- }
- else {
- size_t bufferLen = *dataLength;
- size_t copyToBuffer = bufferLen < context->readingBuffer_.size() ? bufferLen : context->readingBuffer_.size();
-
- memcpy(data, context->readingBuffer_.data(), copyToBuffer);
-
- context->readingBuffer_ = SafeByteArray(context->readingBuffer_.data() + copyToBuffer, context->readingBuffer_.data() + context->readingBuffer_.size());
- *dataLength = copyToBuffer;
- }
- return retValue;
+ SecureTransportContext* context = const_cast<SecureTransportContext*>(static_cast<const SecureTransportContext*>(connection));
+ OSStatus retValue = noErr;
+
+ if (context->readingBuffer_.size() < *dataLength) {
+ // Would block because Secure Transport is trying to read more data than there currently is available in the buffer.
+ *dataLength = 0;
+ retValue = errSSLWouldBlock;
+ }
+ else {
+ size_t bufferLen = *dataLength;
+ size_t copyToBuffer = bufferLen < context->readingBuffer_.size() ? bufferLen : context->readingBuffer_.size();
+
+ memcpy(data, context->readingBuffer_.data(), copyToBuffer);
+
+ context->readingBuffer_ = SafeByteArray(context->readingBuffer_.data() + copyToBuffer, context->readingBuffer_.data() + context->readingBuffer_.size());
+ *dataLength = copyToBuffer;
+ }
+ return retValue;
}
OSStatus SecureTransportContext::SSLSocketWriteCallback(SSLConnectionRef connection, const void *data, size_t *dataLength) {
- SecureTransportContext* context = const_cast<SecureTransportContext*>(static_cast<const SecureTransportContext*>(connection));
- OSStatus retValue = noErr;
-
- SafeByteArray safeData;
- safeData.resize(*dataLength);
- memcpy(safeData.data(), data, safeData.size());
-
- context->onDataForNetwork(safeData);
- return retValue;
+ SecureTransportContext* context = const_cast<SecureTransportContext*>(static_cast<const SecureTransportContext*>(connection));
+ OSStatus retValue = noErr;
+
+ SafeByteArray safeData;
+ safeData.resize(*dataLength);
+ memcpy(safeData.data(), data, safeData.size());
+
+ context->onDataForNetwork(safeData);
+ return retValue;
}
boost::shared_ptr<TLSError> SecureTransportContext::nativeToTLSError(OSStatus /* error */) {
- boost::shared_ptr<TLSError> swiftenError;
- swiftenError = boost::make_shared<TLSError>();
- return swiftenError;
+ boost::shared_ptr<TLSError> swiftenError;
+ swiftenError = boost::make_shared<TLSError>();
+ return swiftenError;
}
boost::shared_ptr<CertificateVerificationError> SecureTransportContext::CSSMErrorToVerificationError(OSStatus resultCode) {
- boost::shared_ptr<CertificateVerificationError> error;
- switch(resultCode) {
- case CSSMERR_TP_NOT_TRUSTED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED" << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
- break;
- case CSSMERR_TP_CERT_NOT_VALID_YET:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_NOT_VALID_YET" << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
- break;
- case CSSMERR_TP_CERT_EXPIRED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED" << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
- break;
- case CSSMERR_TP_CERT_REVOKED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED" << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Revoked);
- break;
- case CSSMERR_TP_VERIFY_ACTION_FAILED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_VERIFY_ACTION_FAILED" << std::endl;
- break;
- case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK" << std::endl;
- if (checkCertificateRevocation_) {
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
- }
- break;
- case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_OCSP_UNAVAILABLE" << std::endl;
- if (checkCertificateRevocation_) {
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
- }
- break;
- case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE" << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidPurpose);
- break;
- default:
- SWIFT_LOG(warning) << "unhandled CSSM error: " << resultCode << ", CSSM_TP_BASE_TP_ERROR: " << CSSM_TP_BASE_TP_ERROR << std::endl;
- error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
- break;
- }
- return error;
+ boost::shared_ptr<CertificateVerificationError> error;
+ switch(resultCode) {
+ case CSSMERR_TP_NOT_TRUSTED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED" << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
+ break;
+ case CSSMERR_TP_CERT_NOT_VALID_YET:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_NOT_VALID_YET" << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
+ break;
+ case CSSMERR_TP_CERT_EXPIRED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED" << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
+ break;
+ case CSSMERR_TP_CERT_REVOKED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED" << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::Revoked);
+ break;
+ case CSSMERR_TP_VERIFY_ACTION_FAILED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_VERIFY_ACTION_FAILED" << std::endl;
+ break;
+ case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK" << std::endl;
+ if (checkCertificateRevocation_) {
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
+ }
+ break;
+ case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_OCSP_UNAVAILABLE" << std::endl;
+ if (checkCertificateRevocation_) {
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
+ }
+ break;
+ case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE" << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidPurpose);
+ break;
+ default:
+ SWIFT_LOG(warning) << "unhandled CSSM error: " << resultCode << ", CSSM_TP_BASE_TP_ERROR: " << CSSM_TP_BASE_TP_ERROR << std::endl;
+ error = boost::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ break;
+ }
+ return error;
}
void SecureTransportContext::fatalError(boost::shared_ptr<TLSError> error, boost::shared_ptr<CertificateVerificationError> certificateError) {
- setState(Error);
- if (sslContext_) {
- SSLClose(sslContext_.get());
- }
- verificationError_ = certificateError;
- onError(error);
+ setState(Error);
+ if (sslContext_) {
+ SSLClose(sslContext_.get());
+ }
+ verificationError_ = certificateError;
+ onError(error);
}
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
index ce19839..1fac1fb 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
+++ b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
@@ -23,22 +23,22 @@ SecureTransportContextFactory::~SecureTransportContextFactory() {
}
bool SecureTransportContextFactory::canCreate() const {
- return true;
+ return true;
}
TLSContext* SecureTransportContextFactory::createTLSContext(const TLSOptions& /* tlsOptions */) {
- return new SecureTransportContext(checkCertificateRevocation_);
+ return new SecureTransportContext(checkCertificateRevocation_);
}
void SecureTransportContextFactory::setCheckCertificateRevocation(bool b) {
- checkCertificateRevocation_ = b;
+ checkCertificateRevocation_ = b;
}
void SecureTransportContextFactory::setDisconnectOnCardRemoval(bool b) {
- disconnectOnCardRemoval_ = b;
- if (disconnectOnCardRemoval_) {
- SWIFT_LOG(warning) << "Smart cards have not been tested yet" << std::endl;
- }
+ disconnectOnCardRemoval_ = b;
+ if (disconnectOnCardRemoval_) {
+ SWIFT_LOG(warning) << "Smart cards have not been tested yet" << std::endl;
+ }
}
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h
index f490768..74c598f 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h
@@ -11,19 +11,19 @@
namespace Swift {
class SecureTransportContextFactory : public TLSContextFactory {
- public:
- SecureTransportContextFactory();
- virtual ~SecureTransportContextFactory();
+ public:
+ SecureTransportContextFactory();
+ virtual ~SecureTransportContextFactory();
- virtual bool canCreate() const;
+ virtual bool canCreate() const;
- virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
- virtual void setCheckCertificateRevocation(bool b);
- virtual void setDisconnectOnCardRemoval(bool b);
+ virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions);
+ virtual void setCheckCertificateRevocation(bool b);
+ virtual void setDisconnectOnCardRemoval(bool b);
- private:
- bool checkCertificateRevocation_;
- bool disconnectOnCardRemoval_;
+ private:
+ bool checkCertificateRevocation_;
+ bool disconnectOnCardRemoval_;
};
}
diff --git a/Swiften/TLS/ServerIdentityVerifier.cpp b/Swiften/TLS/ServerIdentityVerifier.cpp
index 19d7489..b247585 100644
--- a/Swiften/TLS/ServerIdentityVerifier.cpp
+++ b/Swiften/TLS/ServerIdentityVerifier.cpp
@@ -14,82 +14,82 @@
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;
- }
+ 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;
+ bool hasSAN = false;
- if (certificate == NULL) {
- return false;
- }
- // DNS names
- std::vector<std::string> dnsNames = certificate->getDNSNames();
- foreach (const std::string& dnsName, dnsNames) {
- if (matchesDomain(dnsName)) {
- return true;
- }
- }
- hasSAN |= !dnsNames.empty();
+ if (certificate == NULL) {
+ return false;
+ }
+ // DNS names
+ std::vector<std::string> dnsNames = certificate->getDNSNames();
+ foreach (const std::string& 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) {
- // 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();
+ // SRV names
+ std::vector<std::string> srvNames = certificate->getSRVNames();
+ foreach (const std::string& 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) {
- if (matchesAddress(xmppAddress)) {
- return true;
- }
- }
- hasSAN |= !xmppAddresses.empty();
+ // XmppAddr
+ std::vector<std::string> xmppAddresses = certificate->getXMPPAddresses();
+ foreach (const std::string& 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) {
- if (matchesDomain(commonName)) {
- return true;
- }
- }
- }
+ // 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) {
+ if (matchesDomain(commonName)) {
+ return true;
+ }
+ }
+ }
- return false;
+ 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;
- }
+ 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;
+ return s == domain;
}
}
diff --git a/Swiften/TLS/ServerIdentityVerifier.h b/Swiften/TLS/ServerIdentityVerifier.h
index 5b57f27..ca92180 100644
--- a/Swiften/TLS/ServerIdentityVerifier.h
+++ b/Swiften/TLS/ServerIdentityVerifier.h
@@ -15,21 +15,21 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class IDNConverter;
+ class IDNConverter;
- class SWIFTEN_API ServerIdentityVerifier {
- public:
- ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter);
+ class SWIFTEN_API ServerIdentityVerifier {
+ public:
+ ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter);
- bool certificateVerifies(Certificate::ref);
+ bool certificateVerifies(Certificate::ref);
- private:
- bool matchesDomain(const std::string&) const ;
- bool matchesAddress(const std::string&) const;
+ private:
+ bool matchesDomain(const std::string&) const ;
+ bool matchesAddress(const std::string&) const;
- private:
- std::string domain;
- std::string encodedDomain;
- bool domainValid;
- };
+ private:
+ std::string domain;
+ std::string encodedDomain;
+ bool domainValid;
+ };
}
diff --git a/Swiften/TLS/SimpleCertificate.h b/Swiften/TLS/SimpleCertificate.h
index 2824036..4dbf847 100644
--- a/Swiften/TLS/SimpleCertificate.h
+++ b/Swiften/TLS/SimpleCertificate.h
@@ -12,67 +12,67 @@
#include <Swiften/TLS/Certificate.h>
namespace Swift {
- class SWIFTEN_API SimpleCertificate : public Certificate {
- public:
- typedef boost::shared_ptr<SimpleCertificate> ref;
-
- void setSubjectName(const std::string& name) {
- subjectName = name;
- }
-
- std::string getSubjectName() const {
- return subjectName;
- }
-
- std::vector<std::string> getCommonNames() const {
- return commonNames;
- }
-
- void addCommonName(const std::string& name) {
- commonNames.push_back(name);
- }
-
- void addSRVName(const std::string& name) {
- srvNames.push_back(name);
- }
-
- void addDNSName(const std::string& name) {
- dnsNames.push_back(name);
- }
-
- void addXMPPAddress(const std::string& addr) {
- xmppAddresses.push_back(addr);
- }
-
- std::vector<std::string> getSRVNames() const {
- return srvNames;
- }
-
- std::vector<std::string> getDNSNames() const {
- return dnsNames;
- }
-
- std::vector<std::string> getXMPPAddresses() const {
- return xmppAddresses;
- }
-
- ByteArray toDER() const {
- return der;
- }
-
- void setDER(const ByteArray& der) {
- this->der = der;
- }
-
- private:
- void parse();
-
- private:
- std::string subjectName;
- ByteArray der;
- std::vector<std::string> commonNames;
- std::vector<std::string> dnsNames;
- std::vector<std::string> xmppAddresses;
- std::vector<std::string> srvNames;
- };
+ class SWIFTEN_API SimpleCertificate : public Certificate {
+ public:
+ typedef boost::shared_ptr<SimpleCertificate> ref;
+
+ void setSubjectName(const std::string& name) {
+ subjectName = name;
+ }
+
+ std::string getSubjectName() const {
+ return subjectName;
+ }
+
+ std::vector<std::string> getCommonNames() const {
+ return commonNames;
+ }
+
+ void addCommonName(const std::string& name) {
+ commonNames.push_back(name);
+ }
+
+ void addSRVName(const std::string& name) {
+ srvNames.push_back(name);
+ }
+
+ void addDNSName(const std::string& name) {
+ dnsNames.push_back(name);
+ }
+
+ void addXMPPAddress(const std::string& addr) {
+ xmppAddresses.push_back(addr);
+ }
+
+ std::vector<std::string> getSRVNames() const {
+ return srvNames;
+ }
+
+ std::vector<std::string> getDNSNames() const {
+ return dnsNames;
+ }
+
+ std::vector<std::string> getXMPPAddresses() const {
+ return xmppAddresses;
+ }
+
+ ByteArray toDER() const {
+ return der;
+ }
+
+ void setDER(const ByteArray& der) {
+ this->der = der;
+ }
+
+ private:
+ void parse();
+
+ private:
+ std::string subjectName;
+ ByteArray der;
+ std::vector<std::string> commonNames;
+ std::vector<std::string> dnsNames;
+ std::vector<std::string> xmppAddresses;
+ std::vector<std::string> srvNames;
+ };
}
diff --git a/Swiften/TLS/TLSContext.cpp b/Swiften/TLS/TLSContext.cpp
index 9d8b166..2763547 100644
--- a/Swiften/TLS/TLSContext.cpp
+++ b/Swiften/TLS/TLSContext.cpp
@@ -12,8 +12,8 @@ TLSContext::~TLSContext() {
}
Certificate::ref TLSContext::getPeerCertificate() const {
- std::vector<Certificate::ref> chain = getPeerCertificateChain();
- return chain.empty() ? Certificate::ref() : chain[0];
+ std::vector<Certificate::ref> chain = getPeerCertificateChain();
+ return chain.empty() ? Certificate::ref() : chain[0];
}
}
diff --git a/Swiften/TLS/TLSContext.h b/Swiften/TLS/TLSContext.h
index b85e8a8..d7b33d4 100644
--- a/Swiften/TLS/TLSContext.h
+++ b/Swiften/TLS/TLSContext.h
@@ -18,27 +18,27 @@
namespace Swift {
- class SWIFTEN_API TLSContext {
- public:
- virtual ~TLSContext();
+ class SWIFTEN_API TLSContext {
+ public:
+ virtual ~TLSContext();
- virtual void connect() = 0;
+ virtual void connect() = 0;
- virtual bool setClientCertificate(CertificateWithKey::ref cert) = 0;
+ virtual bool setClientCertificate(CertificateWithKey::ref cert) = 0;
- virtual void handleDataFromNetwork(const SafeByteArray&) = 0;
- virtual void handleDataFromApplication(const SafeByteArray&) = 0;
+ virtual void handleDataFromNetwork(const SafeByteArray&) = 0;
+ virtual void handleDataFromApplication(const SafeByteArray&) = 0;
- Certificate::ref getPeerCertificate() const;
- virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
- virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const = 0;
+ Certificate::ref getPeerCertificate() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0;
+ virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const = 0;
- virtual ByteArray getFinishMessage() const = 0;
+ virtual ByteArray getFinishMessage() const = 0;
- public:
- boost::signal<void (const SafeByteArray&)> onDataForNetwork;
- boost::signal<void (const SafeByteArray&)> onDataForApplication;
- boost::signal<void (boost::shared_ptr<TLSError>)> onError;
- boost::signal<void ()> onConnected;
- };
+ public:
+ boost::signal<void (const SafeByteArray&)> onDataForNetwork;
+ boost::signal<void (const SafeByteArray&)> onDataForApplication;
+ boost::signal<void (boost::shared_ptr<TLSError>)> onError;
+ boost::signal<void ()> onConnected;
+ };
}
diff --git a/Swiften/TLS/TLSContextFactory.h b/Swiften/TLS/TLSContextFactory.h
index b67c34f..d2ffe15 100644
--- a/Swiften/TLS/TLSContextFactory.h
+++ b/Swiften/TLS/TLSContextFactory.h
@@ -10,16 +10,16 @@
#include <Swiften/TLS/TLSOptions.h>
namespace Swift {
- class TLSContext;
+ class TLSContext;
- class SWIFTEN_API TLSContextFactory {
- public:
- virtual ~TLSContextFactory();
+ class SWIFTEN_API TLSContextFactory {
+ public:
+ virtual ~TLSContextFactory();
- virtual bool canCreate() const = 0;
+ virtual bool canCreate() const = 0;
- virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions) = 0;
- virtual void setCheckCertificateRevocation(bool b) = 0;
- virtual void setDisconnectOnCardRemoval(bool b) = 0;
- };
+ virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions) = 0;
+ virtual void setCheckCertificateRevocation(bool b) = 0;
+ virtual void setDisconnectOnCardRemoval(bool b) = 0;
+ };
}
diff --git a/Swiften/TLS/TLSError.h b/Swiften/TLS/TLSError.h
index 1608a17..bed5be9 100644
--- a/Swiften/TLS/TLSError.h
+++ b/Swiften/TLS/TLSError.h
@@ -12,22 +12,22 @@
#include <Swiften/Base/Error.h>
namespace Swift {
- class SWIFTEN_API TLSError : public Error {
- public:
- typedef boost::shared_ptr<TLSError> ref;
+ class SWIFTEN_API TLSError : public Error {
+ public:
+ typedef boost::shared_ptr<TLSError> ref;
- enum Type {
- UnknownError,
- CertificateCardRemoved
- };
+ enum Type {
+ UnknownError,
+ CertificateCardRemoved
+ };
- TLSError(Type type = UnknownError) : type(type) {}
+ TLSError(Type type = UnknownError) : type(type) {}
- Type getType() const {
- return type;
- }
+ Type getType() const {
+ return type;
+ }
- private:
- Type type;
- };
+ private:
+ Type type;
+ };
}
diff --git a/Swiften/TLS/TLSOptions.h b/Swiften/TLS/TLSOptions.h
index ca84829..dd7e920 100644
--- a/Swiften/TLS/TLSOptions.h
+++ b/Swiften/TLS/TLSOptions.h
@@ -8,18 +8,18 @@
namespace Swift {
- struct TLSOptions {
- TLSOptions() : schannelTLS1_0Workaround(false) {
+ struct TLSOptions {
+ TLSOptions() : schannelTLS1_0Workaround(false) {
- }
+ }
- /**
- * A bug in the Windows SChannel TLS stack, combined with
- * overly-restrictive server stacks means it's sometimes necessary to
- * not use TLS>1.0. This option has no effect unless compiled on
- * Windows against SChannel (OpenSSL users are unaffected).
- */
- bool schannelTLS1_0Workaround;
+ /**
+ * A bug in the Windows SChannel TLS stack, combined with
+ * overly-restrictive server stacks means it's sometimes necessary to
+ * not use TLS>1.0. This option has no effect unless compiled on
+ * Windows against SChannel (OpenSSL users are unaffected).
+ */
+ bool schannelTLS1_0Workaround;
- };
+ };
}
diff --git a/Swiften/TLS/UnitTest/CertificateTest.cpp b/Swiften/TLS/UnitTest/CertificateTest.cpp
index 12a455a..f7bb93e 100644
--- a/Swiften/TLS/UnitTest/CertificateTest.cpp
+++ b/Swiften/TLS/UnitTest/CertificateTest.cpp
@@ -18,17 +18,17 @@
using namespace Swift;
class CertificateTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(CertificateTest);
- CPPUNIT_TEST(testGetSHA1Fingerprint);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(CertificateTest);
+ CPPUNIT_TEST(testGetSHA1Fingerprint);
+ CPPUNIT_TEST_SUITE_END();
- public:
- void testGetSHA1Fingerprint() {
- SimpleCertificate::ref testling = boost::make_shared<SimpleCertificate>();
- testling->setDER(createByteArray("abcdefg"));
+ public:
+ void testGetSHA1Fingerprint() {
+ SimpleCertificate::ref testling = boost::make_shared<SimpleCertificate>();
+ testling->setDER(createByteArray("abcdefg"));
- CPPUNIT_ASSERT_EQUAL(std::string("2f:b5:e1:34:19:fc:89:24:68:65:e7:a3:24:f4:76:ec:62:4e:87:40"), Certificate::getSHA1Fingerprint(testling, boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()).get()));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("2f:b5:e1:34:19:fc:89:24:68:65:e7:a3:24:f4:76:ec:62:4e:87:40"), Certificate::getSHA1Fingerprint(testling, boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()).get()));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(CertificateTest);
diff --git a/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp b/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
index a444413..1fe936d 100644
--- a/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
+++ b/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
@@ -18,161 +18,161 @@
using namespace Swift;
class ServerIdentityVerifierTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ServerIdentityVerifierTest);
- CPPUNIT_TEST(testCertificateVerifies_WithoutMatchingDNSName);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSName);
- CPPUNIT_TEST(testCertificateVerifies_WithSecondMatchingDNSName);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingInternationalDNSName);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSNameWithWildcard);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSNameWithWildcardMatchingNoComponents);
- CPPUNIT_TEST(testCertificateVerifies_WithDNSNameWithWildcardMatchingTwoComponents);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithoutService);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithService);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithServiceAndWildcard);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithDifferentService);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingXmppAddr);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingXmppAddrWithWildcard);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingInternationalXmppAddr);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithoutSAN);
- CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithSAN);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
- }
-
- void testCertificateVerifies_WithoutMatchingDNSName() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("foo.com");
-
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingDNSName() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("bar.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithSecondMatchingDNSName() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("foo.com");
- certificate->addDNSName("bar.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingInternationalDNSName() {
- ServerIdentityVerifier testling(JID("foo@tron\xc3\xa7on.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("xn--tronon-zua.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingDNSNameWithWildcard() {
- ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("*.bar.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingDNSNameWithWildcardMatchingNoComponents() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("*.bar.com");
-
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithDNSNameWithWildcardMatchingTwoComponents() {
- ServerIdentityVerifier testling(JID("foo@xmpp.im.bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addDNSName("*.bar.com");
-
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingSRVNameWithoutService() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addSRVName("bar.com");
-
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingSRVNameWithService() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addSRVName("_xmpp-client.bar.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingSRVNameWithServiceAndWildcard() {
- ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addSRVName("_xmpp-client.*.bar.com");
-
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingSRVNameWithDifferentService() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addSRVName("_xmpp-server.bar.com");
-
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
-
- void testCertificateVerifies_WithMatchingXmppAddr() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addXMPPAddress("bar.com");
+ CPPUNIT_TEST_SUITE(ServerIdentityVerifierTest);
+ CPPUNIT_TEST(testCertificateVerifies_WithoutMatchingDNSName);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSName);
+ CPPUNIT_TEST(testCertificateVerifies_WithSecondMatchingDNSName);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingInternationalDNSName);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSNameWithWildcard);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingDNSNameWithWildcardMatchingNoComponents);
+ CPPUNIT_TEST(testCertificateVerifies_WithDNSNameWithWildcardMatchingTwoComponents);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithoutService);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithService);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithServiceAndWildcard);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithDifferentService);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingXmppAddr);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingXmppAddrWithWildcard);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingInternationalXmppAddr);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithoutSAN);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithSAN);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ idnConverter = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ }
+
+ void testCertificateVerifies_WithoutMatchingDNSName() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("foo.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingDNSName() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithSecondMatchingDNSName() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("foo.com");
+ certificate->addDNSName("bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingInternationalDNSName() {
+ ServerIdentityVerifier testling(JID("foo@tron\xc3\xa7on.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("xn--tronon-zua.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingDNSNameWithWildcard() {
+ ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("*.bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingDNSNameWithWildcardMatchingNoComponents() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("*.bar.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithDNSNameWithWildcardMatchingTwoComponents() {
+ ServerIdentityVerifier testling(JID("foo@xmpp.im.bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("*.bar.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingSRVNameWithoutService() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("bar.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingSRVNameWithService() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("_xmpp-client.bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingSRVNameWithServiceAndWildcard() {
+ ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("_xmpp-client.*.bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingSRVNameWithDifferentService() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("_xmpp-server.bar.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingXmppAddr() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("bar.com");
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
- void testCertificateVerifies_WithMatchingXmppAddrWithWildcard() {
- ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addXMPPAddress("*.bar.com");
+ void testCertificateVerifies_WithMatchingXmppAddrWithWildcard() {
+ ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("*.bar.com");
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
- void testCertificateVerifies_WithMatchingInternationalXmppAddr() {
- ServerIdentityVerifier testling(JID("foo@tron\xc3\xa7.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addXMPPAddress("tron\xc3\xa7.com");
+ void testCertificateVerifies_WithMatchingInternationalXmppAddr() {
+ ServerIdentityVerifier testling(JID("foo@tron\xc3\xa7.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("tron\xc3\xa7.com");
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
- void testCertificateVerifies_WithMatchingCNWithoutSAN() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addCommonName("bar.com");
+ void testCertificateVerifies_WithMatchingCNWithoutSAN() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addCommonName("bar.com");
- CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
- }
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
- void testCertificateVerifies_WithMatchingCNWithSAN() {
- ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
- SimpleCertificate::ref certificate(new SimpleCertificate());
- certificate->addSRVName("foo.com");
- certificate->addCommonName("bar.com");
+ void testCertificateVerifies_WithMatchingCNWithSAN() {
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("foo.com");
+ certificate->addCommonName("bar.com");
- CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
- }
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
- boost::shared_ptr<IDNConverter> idnConverter;
+ boost::shared_ptr<IDNConverter> idnConverter;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ServerIdentityVerifierTest);
diff --git a/Swiften/VCards/GetVCardRequest.h b/Swiften/VCards/GetVCardRequest.h
index f30fd05..5d6fc17 100644
--- a/Swiften/VCards/GetVCardRequest.h
+++ b/Swiften/VCards/GetVCardRequest.h
@@ -11,16 +11,16 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API GetVCardRequest : public GenericRequest<VCard> {
- public:
- typedef boost::shared_ptr<GetVCardRequest> ref;
+ class SWIFTEN_API GetVCardRequest : public GenericRequest<VCard> {
+ public:
+ typedef boost::shared_ptr<GetVCardRequest> ref;
- static ref create(const JID& jid, IQRouter* router) {
- return ref(new GetVCardRequest(jid, router));
- }
+ static ref create(const JID& jid, IQRouter* router) {
+ return ref(new GetVCardRequest(jid, router));
+ }
- private:
- GetVCardRequest(const JID& jid, IQRouter* router) : GenericRequest<VCard>(IQ::Get, jid, boost::shared_ptr<Payload>(new VCard()), router) {
- }
- };
+ private:
+ GetVCardRequest(const JID& jid, IQRouter* router) : GenericRequest<VCard>(IQ::Get, jid, boost::shared_ptr<Payload>(new VCard()), router) {
+ }
+ };
}
diff --git a/Swiften/VCards/SetVCardRequest.h b/Swiften/VCards/SetVCardRequest.h
index 781e7b9..b9621ab 100644
--- a/Swiften/VCards/SetVCardRequest.h
+++ b/Swiften/VCards/SetVCardRequest.h
@@ -11,16 +11,16 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class SWIFTEN_API SetVCardRequest : public GenericRequest<VCard> {
- public:
- typedef boost::shared_ptr<SetVCardRequest> ref;
+ class SWIFTEN_API SetVCardRequest : public GenericRequest<VCard> {
+ public:
+ typedef boost::shared_ptr<SetVCardRequest> ref;
- static ref create(VCard::ref vcard, IQRouter* router) {
- return ref(new SetVCardRequest(vcard, router));
- }
+ static ref create(VCard::ref vcard, IQRouter* router) {
+ return ref(new SetVCardRequest(vcard, router));
+ }
- private:
- SetVCardRequest(VCard::ref vcard, IQRouter* router) : GenericRequest<VCard>(IQ::Set, JID(), vcard, router) {
- }
- };
+ private:
+ SetVCardRequest(VCard::ref vcard, IQRouter* router) : GenericRequest<VCard>(IQ::Set, JID(), vcard, router) {
+ }
+ };
}
diff --git a/Swiften/VCards/UnitTest/VCardManagerTest.cpp b/Swiften/VCards/UnitTest/VCardManagerTest.cpp
index 278449b..3784c6c 100644
--- a/Swiften/VCards/UnitTest/VCardManagerTest.cpp
+++ b/Swiften/VCards/UnitTest/VCardManagerTest.cpp
@@ -23,189 +23,189 @@
using namespace Swift;
class VCardManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(VCardManagerTest);
- CPPUNIT_TEST(testGet_NewVCardRequestsVCard);
- CPPUNIT_TEST(testGet_ExistingVCard);
- CPPUNIT_TEST(testRequest_RequestsVCard);
- CPPUNIT_TEST(testRequest_ReceiveEmitsNotification);
- CPPUNIT_TEST(testRequest_Error);
- CPPUNIT_TEST(testRequest_VCardAlreadyRequested);
- CPPUNIT_TEST(testRequest_AfterPreviousRequest);
- CPPUNIT_TEST(testRequestOwnVCard);
- CPPUNIT_TEST(testCreateSetVCardRequest);
- CPPUNIT_TEST(testCreateSetVCardRequest_Error);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- changes.clear();
- ownChanges.clear();
- ownJID = JID("baz@fum.com/dum");
- crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
- stanzaChannel = new DummyStanzaChannel();
- iqRouter = new IQRouter(stanzaChannel);
- vcardStorage = new VCardMemoryStorage(crypto.get());
- }
-
- void tearDown() {
- delete vcardStorage;
- delete iqRouter;
- delete stanzaChannel;
- }
-
- void testGet_NewVCardRequestsVCard() {
- boost::shared_ptr<VCardManager> testling = createManager();
- VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
-
- CPPUNIT_ASSERT(!result);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID("foo@bar.com/baz"), IQ::Get));
- }
-
- void testGet_ExistingVCard() {
- boost::shared_ptr<VCardManager> testling = createManager();
- VCard::ref vcard(new VCard());
- vcard->setFullName("Foo Bar");
- vcardStorage->setVCard(JID("foo@bar.com/baz"), vcard);
-
- VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
-
- CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), result->getFullName());
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testRequest_RequestsVCard() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(JID("foo@bar.com/baz"));
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID("foo@bar.com/baz"), IQ::Get));
- }
-
- void testRequest_ReceiveEmitsNotification() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(JID("foo@bar.com/baz"));
- stanzaChannel->onIQReceived(createVCardResult());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), changes[0].first);
- CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), changes[0].second->getFullName());
- CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), vcardStorage->getVCard(JID("foo@bar.com/baz"))->getFullName());
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(ownChanges.size()));
- }
-
- void testRequest_Error() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(JID("foo@bar.com/baz"));
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
-
- // On error, cached vCards should not be changed.
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- void testRequest_VCardAlreadyRequested() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(JID("foo@bar.com/baz"));
- VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
-
- CPPUNIT_ASSERT(!result);
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- }
-
- void testRequest_AfterPreviousRequest() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(JID("foo@bar.com/baz"));
- stanzaChannel->onIQReceived(createVCardResult());
- testling->requestVCard(JID("foo@bar.com/baz"));
-
- CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(1, JID("foo@bar.com/baz"), IQ::Get));
- }
-
- void testRequestOwnVCard() {
- boost::shared_ptr<VCardManager> testling = createManager();
- testling->requestVCard(ownJID);
- stanzaChannel->onIQReceived(createOwnVCardResult());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
- CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID(), IQ::Get));
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(ownJID.toBare(), changes[0].first);
- CPPUNIT_ASSERT_EQUAL(std::string("Myself"), changes[0].second->getFullName());
- CPPUNIT_ASSERT_EQUAL(std::string("Myself"), vcardStorage->getVCard(ownJID.toBare())->getFullName());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(ownChanges.size()));
- CPPUNIT_ASSERT_EQUAL(std::string("Myself"), ownChanges[0]->getFullName());
- }
-
- void testCreateSetVCardRequest() {
- boost::shared_ptr<VCardManager> testling = createManager();
- VCard::ref vcard = boost::make_shared<VCard>();
- vcard->setFullName("New Name");
- SetVCardRequest::ref request = testling->createSetVCardRequest(vcard);
- request->send();
-
- stanzaChannel->onIQReceived(createSetVCardResult());
-
- CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
- CPPUNIT_ASSERT_EQUAL(ownJID.toBare(), changes[0].first);
- CPPUNIT_ASSERT_EQUAL(std::string("New Name"), changes[0].second->getFullName());
- }
-
- void testCreateSetVCardRequest_Error() {
- boost::shared_ptr<VCardManager> testling = createManager();
- VCard::ref vcard = boost::make_shared<VCard>();
- vcard->setFullName("New Name");
- SetVCardRequest::ref request = testling->createSetVCardRequest(vcard);
- request->send();
-
- stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
-
- CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
- }
-
- private:
- boost::shared_ptr<VCardManager> createManager() {
- boost::shared_ptr<VCardManager> manager(new VCardManager(ownJID, iqRouter, vcardStorage));
- manager->onVCardChanged.connect(boost::bind(&VCardManagerTest::handleVCardChanged, this, _1, _2));
- manager->onOwnVCardChanged.connect(boost::bind(&VCardManagerTest::handleOwnVCardChanged, this, _1));
- return manager;
- }
-
- void handleVCardChanged(const JID& jid, VCard::ref vcard) {
- changes.push_back(std::pair<JID, VCard::ref>(jid, vcard));
- }
-
- void handleOwnVCardChanged(VCard::ref vcard) {
- ownChanges.push_back(vcard);
- }
-
- IQ::ref createVCardResult() {
- VCard::ref vcard(new VCard());
- vcard->setFullName("Foo Bar");
- return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
- }
-
- IQ::ref createOwnVCardResult() {
- VCard::ref vcard(new VCard());
- vcard->setFullName("Myself");
- return IQ::createResult(JID(), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
- }
-
- IQ::ref createSetVCardResult() {
- return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), VCard::ref());
- }
-
-
- private:
- JID ownJID;
- DummyStanzaChannel* stanzaChannel;
- IQRouter* iqRouter;
- VCardMemoryStorage* vcardStorage;
- std::vector< std::pair<JID, VCard::ref> > changes;
- std::vector<VCard::ref> ownChanges;
- boost::shared_ptr<CryptoProvider> crypto;
+ CPPUNIT_TEST_SUITE(VCardManagerTest);
+ CPPUNIT_TEST(testGet_NewVCardRequestsVCard);
+ CPPUNIT_TEST(testGet_ExistingVCard);
+ CPPUNIT_TEST(testRequest_RequestsVCard);
+ CPPUNIT_TEST(testRequest_ReceiveEmitsNotification);
+ CPPUNIT_TEST(testRequest_Error);
+ CPPUNIT_TEST(testRequest_VCardAlreadyRequested);
+ CPPUNIT_TEST(testRequest_AfterPreviousRequest);
+ CPPUNIT_TEST(testRequestOwnVCard);
+ CPPUNIT_TEST(testCreateSetVCardRequest);
+ CPPUNIT_TEST(testCreateSetVCardRequest_Error);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ changes.clear();
+ ownChanges.clear();
+ ownJID = JID("baz@fum.com/dum");
+ crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ vcardStorage = new VCardMemoryStorage(crypto.get());
+ }
+
+ void tearDown() {
+ delete vcardStorage;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testGet_NewVCardRequestsVCard() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
+
+ CPPUNIT_ASSERT(!result);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID("foo@bar.com/baz"), IQ::Get));
+ }
+
+ void testGet_ExistingVCard() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Foo Bar");
+ vcardStorage->setVCard(JID("foo@bar.com/baz"), vcard);
+
+ VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
+
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), result->getFullName());
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testRequest_RequestsVCard() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(JID("foo@bar.com/baz"));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID("foo@bar.com/baz"), IQ::Get));
+ }
+
+ void testRequest_ReceiveEmitsNotification() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(JID("foo@bar.com/baz"));
+ stanzaChannel->onIQReceived(createVCardResult());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), changes[0].first);
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), changes[0].second->getFullName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Foo Bar"), vcardStorage->getVCard(JID("foo@bar.com/baz"))->getFullName());
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(ownChanges.size()));
+ }
+
+ void testRequest_Error() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(JID("foo@bar.com/baz"));
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID()));
+
+ // On error, cached vCards should not be changed.
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testRequest_VCardAlreadyRequested() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(JID("foo@bar.com/baz"));
+ VCard::ref result = testling->getVCardAndRequestWhenNeeded(JID("foo@bar.com/baz"));
+
+ CPPUNIT_ASSERT(!result);
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testRequest_AfterPreviousRequest() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(JID("foo@bar.com/baz"));
+ stanzaChannel->onIQReceived(createVCardResult());
+ testling->requestVCard(JID("foo@bar.com/baz"));
+
+ CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(1, JID("foo@bar.com/baz"), IQ::Get));
+ }
+
+ void testRequestOwnVCard() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ testling->requestVCard(ownJID);
+ stanzaChannel->onIQReceived(createOwnVCardResult());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<VCard>(0, JID(), IQ::Get));
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(ownJID.toBare(), changes[0].first);
+ CPPUNIT_ASSERT_EQUAL(std::string("Myself"), changes[0].second->getFullName());
+ CPPUNIT_ASSERT_EQUAL(std::string("Myself"), vcardStorage->getVCard(ownJID.toBare())->getFullName());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(ownChanges.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Myself"), ownChanges[0]->getFullName());
+ }
+
+ void testCreateSetVCardRequest() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref vcard = boost::make_shared<VCard>();
+ vcard->setFullName("New Name");
+ SetVCardRequest::ref request = testling->createSetVCardRequest(vcard);
+ request->send();
+
+ stanzaChannel->onIQReceived(createSetVCardResult());
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(ownJID.toBare(), changes[0].first);
+ CPPUNIT_ASSERT_EQUAL(std::string("New Name"), changes[0].second->getFullName());
+ }
+
+ void testCreateSetVCardRequest_Error() {
+ boost::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref vcard = boost::make_shared<VCard>();
+ vcard->setFullName("New Name");
+ SetVCardRequest::ref request = testling->createSetVCardRequest(vcard);
+ request->send();
+
+ stanzaChannel->onIQReceived(IQ::createError(JID("baz@fum.com/foo"), stanzaChannel->sentStanzas[0]->getID()));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ private:
+ boost::shared_ptr<VCardManager> createManager() {
+ boost::shared_ptr<VCardManager> manager(new VCardManager(ownJID, iqRouter, vcardStorage));
+ manager->onVCardChanged.connect(boost::bind(&VCardManagerTest::handleVCardChanged, this, _1, _2));
+ manager->onOwnVCardChanged.connect(boost::bind(&VCardManagerTest::handleOwnVCardChanged, this, _1));
+ return manager;
+ }
+
+ void handleVCardChanged(const JID& jid, VCard::ref vcard) {
+ changes.push_back(std::pair<JID, VCard::ref>(jid, vcard));
+ }
+
+ void handleOwnVCardChanged(VCard::ref vcard) {
+ ownChanges.push_back(vcard);
+ }
+
+ IQ::ref createVCardResult() {
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Foo Bar");
+ return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
+ }
+
+ IQ::ref createOwnVCardResult() {
+ VCard::ref vcard(new VCard());
+ vcard->setFullName("Myself");
+ return IQ::createResult(JID(), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
+ }
+
+ IQ::ref createSetVCardResult() {
+ return IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), VCard::ref());
+ }
+
+
+ private:
+ JID ownJID;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ VCardMemoryStorage* vcardStorage;
+ std::vector< std::pair<JID, VCard::ref> > changes;
+ std::vector<VCard::ref> ownChanges;
+ boost::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardManagerTest);
diff --git a/Swiften/VCards/VCardManager.cpp b/Swiften/VCards/VCardManager.cpp
index 347cc3d..95b96fa 100644
--- a/Swiften/VCards/VCardManager.cpp
+++ b/Swiften/VCards/VCardManager.cpp
@@ -22,71 +22,71 @@ VCardManager::~VCardManager() {
}
VCard::ref VCardManager::getVCard(const JID& jid) const {
- return storage->getVCard(jid);
+ return storage->getVCard(jid);
}
VCard::ref VCardManager::getVCardAndRequestWhenNeeded(const JID& jid, const boost::posix_time::time_duration& allowedAge) {
- VCard::ref vcard = storage->getVCard(jid);
- boost::posix_time::ptime vcardFetchedTime = storage->getVCardWriteTime(jid);
- bool vcardTooOld = vcard && (vcardFetchedTime.is_special() || ((boost::posix_time::second_clock::universal_time() - vcardFetchedTime) > allowedAge));
- if (!vcard || vcardTooOld) {
- requestVCard(jid);
- }
- return vcard;
+ VCard::ref vcard = storage->getVCard(jid);
+ boost::posix_time::ptime vcardFetchedTime = storage->getVCardWriteTime(jid);
+ bool vcardTooOld = vcard && (vcardFetchedTime.is_special() || ((boost::posix_time::second_clock::universal_time() - vcardFetchedTime) > allowedAge));
+ if (!vcard || vcardTooOld) {
+ requestVCard(jid);
+ }
+ return vcard;
}
void VCardManager::requestVCard(const JID& requestedJID) {
- JID jid = requestedJID.equals(ownJID, JID::WithoutResource) ? JID() : requestedJID;
- if (requestedVCards.find(jid) != requestedVCards.end()) {
- return;
- }
- GetVCardRequest::ref request = GetVCardRequest::create(jid, iqRouter);
- request->onResponse.connect(boost::bind(&VCardManager::handleVCardReceived, this, jid, _1, _2));
- request->send();
- requestedVCards.insert(jid);
+ JID jid = requestedJID.equals(ownJID, JID::WithoutResource) ? JID() : requestedJID;
+ if (requestedVCards.find(jid) != requestedVCards.end()) {
+ return;
+ }
+ GetVCardRequest::ref request = GetVCardRequest::create(jid, iqRouter);
+ request->onResponse.connect(boost::bind(&VCardManager::handleVCardReceived, this, jid, _1, _2));
+ request->send();
+ requestedVCards.insert(jid);
}
void VCardManager::requestOwnVCard() {
- requestVCard(JID());
+ requestVCard(JID());
}
void VCardManager::handleVCardReceived(const JID& actualJID, VCard::ref vcard, ErrorPayload::ref error) {
- requestedVCards.erase(actualJID);
- if (!error) {
- if (!vcard) {
- vcard = VCard::ref(new VCard());
- }
- JID jid = actualJID.isValid() ? actualJID : ownJID.toBare();
- setVCard(jid, vcard);
- }
- else {
- onVCardRetrievalError(actualJID, error);
- }
+ requestedVCards.erase(actualJID);
+ if (!error) {
+ if (!vcard) {
+ vcard = VCard::ref(new VCard());
+ }
+ JID jid = actualJID.isValid() ? actualJID : ownJID.toBare();
+ setVCard(jid, vcard);
+ }
+ else {
+ onVCardRetrievalError(actualJID, error);
+ }
}
SetVCardRequest::ref VCardManager::createSetVCardRequest(VCard::ref vcard) {
- SetVCardRequest::ref request = SetVCardRequest::create(vcard, iqRouter);
- request->onResponse.connect(boost::bind(&VCardManager::handleSetVCardResponse, this, vcard, _2));
- return request;
+ SetVCardRequest::ref request = SetVCardRequest::create(vcard, iqRouter);
+ request->onResponse.connect(boost::bind(&VCardManager::handleSetVCardResponse, this, vcard, _2));
+ return request;
}
void VCardManager::handleSetVCardResponse(VCard::ref vcard, ErrorPayload::ref error) {
- if (!error) {
- setVCard(ownJID.toBare(), vcard);
- }
+ if (!error) {
+ setVCard(ownJID.toBare(), vcard);
+ }
}
void VCardManager::setVCard(const JID& jid, VCard::ref vcard) {
- storage->setVCard(jid, vcard);
- onVCardChanged(jid, vcard);
- if (jid.compare(ownJID, JID::WithoutResource) == 0) {
- onOwnVCardChanged(vcard);
- }
+ storage->setVCard(jid, vcard);
+ onVCardChanged(jid, vcard);
+ if (jid.compare(ownJID, JID::WithoutResource) == 0) {
+ onOwnVCardChanged(vcard);
+ }
}
std::string VCardManager::getPhotoHash(const JID& jid) const {
- return storage->getPhotoHash(jid);
+ return storage->getPhotoHash(jid);
}
}
diff --git a/Swiften/VCards/VCardManager.h b/Swiften/VCards/VCardManager.h
index feed1bb..fbad221 100644
--- a/Swiften/VCards/VCardManager.h
+++ b/Swiften/VCards/VCardManager.h
@@ -18,52 +18,52 @@
#include <Swiften/VCards/SetVCardRequest.h>
namespace Swift {
- class IQRouter;
- class JID;
- class VCardStorage;
+ class IQRouter;
+ class JID;
+ class VCardStorage;
- class SWIFTEN_API VCardManager : public boost::bsignals::trackable {
- public:
- VCardManager(const JID& ownJID, IQRouter* iqRouter, VCardStorage* vcardStorage);
- ~VCardManager();
+ class SWIFTEN_API VCardManager : public boost::bsignals::trackable {
+ public:
+ VCardManager(const JID& ownJID, IQRouter* iqRouter, VCardStorage* vcardStorage);
+ ~VCardManager();
- VCard::ref getVCard(const JID& jid) const;
- VCard::ref getVCardAndRequestWhenNeeded(const JID& jid, const boost::posix_time::time_duration& allowedAge = boost::posix_time::time_duration(boost::date_time::pos_infin));
- void requestVCard(const JID& jid);
- void requestOwnVCard();
+ VCard::ref getVCard(const JID& jid) const;
+ VCard::ref getVCardAndRequestWhenNeeded(const JID& jid, const boost::posix_time::time_duration& allowedAge = boost::posix_time::time_duration(boost::date_time::pos_infin));
+ void requestVCard(const JID& jid);
+ void requestOwnVCard();
- std::string getPhotoHash(const JID& jid) const;
+ std::string getPhotoHash(const JID& jid) const;
- SetVCardRequest::ref createSetVCardRequest(VCard::ref);
+ SetVCardRequest::ref createSetVCardRequest(VCard::ref);
- public:
- /**
- * The JID will always be bare.
- */
- boost::signal<void (const JID&, VCard::ref)> onVCardChanged;
+ public:
+ /**
+ * The JID will always be bare.
+ */
+ boost::signal<void (const JID&, VCard::ref)> onVCardChanged;
- /**
- * Emitted when we received an error on looking up a vCard.
- */
- boost::signal<void (const JID&, ErrorPayload::ref)> onVCardRetrievalError;
+ /**
+ * Emitted when we received an error on looking up a vCard.
+ */
+ boost::signal<void (const JID&, ErrorPayload::ref)> onVCardRetrievalError;
- /**
- * Emitted when our own vcard changes.
- *
- * onVCardChanged will also be emitted.
- */
- boost::signal<void (VCard::ref)> onOwnVCardChanged;
+ /**
+ * Emitted when our own vcard changes.
+ *
+ * onVCardChanged will also be emitted.
+ */
+ boost::signal<void (VCard::ref)> onOwnVCardChanged;
- private:
- void handleVCardReceived(const JID& from, VCard::ref, ErrorPayload::ref);
- void handleSetVCardResponse(VCard::ref, ErrorPayload::ref);
- void setVCard(const JID& jid, VCard::ref vcard);
+ private:
+ void handleVCardReceived(const JID& from, VCard::ref, ErrorPayload::ref);
+ void handleSetVCardResponse(VCard::ref, ErrorPayload::ref);
+ void setVCard(const JID& jid, VCard::ref vcard);
- private:
- JID ownJID;
- IQRouter* iqRouter;
- VCardStorage* storage;
- std::set<JID> requestedVCards;
- };
+ private:
+ JID ownJID;
+ IQRouter* iqRouter;
+ VCardStorage* storage;
+ std::set<JID> requestedVCards;
+ };
}
diff --git a/Swiften/VCards/VCardMemoryStorage.h b/Swiften/VCards/VCardMemoryStorage.h
index bde3aff..d4df639 100644
--- a/Swiften/VCards/VCardMemoryStorage.h
+++ b/Swiften/VCards/VCardMemoryStorage.h
@@ -15,38 +15,38 @@
#include <Swiften/VCards/VCardStorage.h>
namespace Swift {
- class SWIFTEN_API VCardMemoryStorage : public VCardStorage {
- public:
- VCardMemoryStorage(CryptoProvider* crypto) : VCardStorage(crypto) {}
-
- virtual VCard::ref getVCard(const JID& jid) const {
- VCardMap::const_iterator i = vcards.find(jid);
- if (i != vcards.end()) {
- return i->second;
- }
- else {
- return VCard::ref();
- }
- }
-
- virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const {
- if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) {
- return boost::posix_time::ptime();
- }
- else {
- return vcardWriteTimes.at(jid);
- }
- }
-
- virtual void setVCard(const JID& jid, VCard::ref v) {
- vcards[jid] = v;
- vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time();
- }
-
- private:
- typedef std::map<JID, VCard::ref> VCardMap;
- typedef std::map<JID, boost::posix_time::ptime> VCardWriteTimeMap;
- VCardMap vcards;
- VCardWriteTimeMap vcardWriteTimes;
- };
+ class SWIFTEN_API VCardMemoryStorage : public VCardStorage {
+ public:
+ VCardMemoryStorage(CryptoProvider* crypto) : VCardStorage(crypto) {}
+
+ virtual VCard::ref getVCard(const JID& jid) const {
+ VCardMap::const_iterator i = vcards.find(jid);
+ if (i != vcards.end()) {
+ return i->second;
+ }
+ else {
+ return VCard::ref();
+ }
+ }
+
+ virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const {
+ if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) {
+ return boost::posix_time::ptime();
+ }
+ else {
+ return vcardWriteTimes.at(jid);
+ }
+ }
+
+ virtual void setVCard(const JID& jid, VCard::ref v) {
+ vcards[jid] = v;
+ vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time();
+ }
+
+ private:
+ typedef std::map<JID, VCard::ref> VCardMap;
+ typedef std::map<JID, boost::posix_time::ptime> VCardWriteTimeMap;
+ VCardMap vcards;
+ VCardWriteTimeMap vcardWriteTimes;
+ };
}
diff --git a/Swiften/VCards/VCardStorage.cpp b/Swiften/VCards/VCardStorage.cpp
index a73e56e..2a4f04c 100644
--- a/Swiften/VCards/VCardStorage.cpp
+++ b/Swiften/VCards/VCardStorage.cpp
@@ -18,13 +18,13 @@ VCardStorage::~VCardStorage() {
}
std::string VCardStorage::getPhotoHash(const JID& jid) const {
- VCard::ref vCard = getVCard(jid);
- if (vCard && !vCard->getPhoto().empty()) {
- return Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto()));
- }
- else {
- return "";
- }
+ VCard::ref vCard = getVCard(jid);
+ if (vCard && !vCard->getPhoto().empty()) {
+ return Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto()));
+ }
+ else {
+ return "";
+ }
}
}
diff --git a/Swiften/VCards/VCardStorage.h b/Swiften/VCards/VCardStorage.h
index 2d9cc72..7314559 100644
--- a/Swiften/VCards/VCardStorage.h
+++ b/Swiften/VCards/VCardStorage.h
@@ -15,21 +15,21 @@
#include <Swiften/Elements/VCard.h>
namespace Swift {
- class JID;
- class CryptoProvider;
+ class JID;
+ class CryptoProvider;
- class SWIFTEN_API VCardStorage {
- public:
- VCardStorage(CryptoProvider*);
- virtual ~VCardStorage();
+ class SWIFTEN_API VCardStorage {
+ public:
+ VCardStorage(CryptoProvider*);
+ virtual ~VCardStorage();
- virtual VCard::ref getVCard(const JID& jid) const = 0;
- virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const = 0;
- virtual void setVCard(const JID&, VCard::ref) = 0;
+ virtual VCard::ref getVCard(const JID& jid) const = 0;
+ virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const = 0;
+ virtual void setVCard(const JID&, VCard::ref) = 0;
- virtual std::string getPhotoHash(const JID&) const;
+ virtual std::string getPhotoHash(const JID&) const;
- private:
- CryptoProvider* crypto;
- };
+ private:
+ CryptoProvider* crypto;
+ };
}
diff --git a/Swiften/Whiteboard/IncomingWhiteboardSession.cpp b/Swiften/Whiteboard/IncomingWhiteboardSession.cpp
index 4708bfa..206e10b 100644
--- a/Swiften/Whiteboard/IncomingWhiteboardSession.cpp
+++ b/Swiften/Whiteboard/IncomingWhiteboardSession.cpp
@@ -20,46 +20,46 @@
#include <Swiften/Elements/WhiteboardPayload.h>
namespace Swift {
- IncomingWhiteboardSession::IncomingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
- }
+ IncomingWhiteboardSession::IncomingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
+ }
- IncomingWhiteboardSession::~IncomingWhiteboardSession() {
- }
+ IncomingWhiteboardSession::~IncomingWhiteboardSession() {
+ }
- void IncomingWhiteboardSession::accept() {
- boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionAccept);
- boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
- request->send();
- onRequestAccepted(toJID_);
- }
+ void IncomingWhiteboardSession::accept() {
+ boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionAccept);
+ boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->send();
+ onRequestAccepted(toJID_);
+ }
- void IncomingWhiteboardSession::handleIncomingOperation(WhiteboardOperation::ref operation) {
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(operation);
- if (pairResult.client) {
- if (pairResult.client->getPos() != -1) {
- onOperationReceived(pairResult.client);
- }
- lastOpID = pairResult.client->getID();
- }
+ void IncomingWhiteboardSession::handleIncomingOperation(WhiteboardOperation::ref operation) {
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(operation);
+ if (pairResult.client) {
+ if (pairResult.client->getPos() != -1) {
+ onOperationReceived(pairResult.client);
+ }
+ lastOpID = pairResult.client->getID();
+ }
- if (pairResult.server) {
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(pairResult.server);
- sendPayload(payload);
- }
- }
+ if (pairResult.server) {
+ WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
+ payload->setOperation(pairResult.server);
+ sendPayload(payload);
+ }
+ }
- void IncomingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
- operation->setID(idGenerator.generateID());
- operation->setParentID(lastOpID);
- lastOpID = operation->getID();
+ void IncomingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
+ operation->setID(idGenerator.generateID());
+ operation->setParentID(lastOpID);
+ lastOpID = operation->getID();
- WhiteboardOperation::ref result = client.handleLocalOperationReceived(operation);
+ WhiteboardOperation::ref result = client.handleLocalOperationReceived(operation);
- if (result) {
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(result);
- sendPayload(payload);
- }
- }
+ if (result) {
+ WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
+ payload->setOperation(result);
+ sendPayload(payload);
+ }
+ }
}
diff --git a/Swiften/Whiteboard/IncomingWhiteboardSession.h b/Swiften/Whiteboard/IncomingWhiteboardSession.h
index c79e320..f6c1f49 100644
--- a/Swiften/Whiteboard/IncomingWhiteboardSession.h
+++ b/Swiften/Whiteboard/IncomingWhiteboardSession.h
@@ -19,20 +19,20 @@
#include <Swiften/Whiteboard/WhiteboardSession.h>
namespace Swift {
- class SWIFTEN_API IncomingWhiteboardSession : public WhiteboardSession {
- public:
- typedef boost::shared_ptr<IncomingWhiteboardSession> ref;
+ class SWIFTEN_API IncomingWhiteboardSession : public WhiteboardSession {
+ public:
+ typedef boost::shared_ptr<IncomingWhiteboardSession> ref;
- public:
- IncomingWhiteboardSession(const JID& jid, IQRouter* router);
- ~IncomingWhiteboardSession();
+ public:
+ IncomingWhiteboardSession(const JID& jid, IQRouter* router);
+ ~IncomingWhiteboardSession();
- void accept();
+ void accept();
- private:
- void handleIncomingOperation(WhiteboardOperation::ref operation);
- void sendOperation(WhiteboardOperation::ref operation);
+ private:
+ void handleIncomingOperation(WhiteboardOperation::ref operation);
+ void sendOperation(WhiteboardOperation::ref operation);
- WhiteboardClient client;
- };
+ WhiteboardClient client;
+ };
}
diff --git a/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp b/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp
index 7d706d5..2bfc434 100644
--- a/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp
+++ b/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp
@@ -21,45 +21,45 @@
#include <Swiften/Elements/WhiteboardPayload.h>
namespace Swift {
- OutgoingWhiteboardSession::OutgoingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
- }
+ OutgoingWhiteboardSession::OutgoingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
+ }
- OutgoingWhiteboardSession::~OutgoingWhiteboardSession() {
- }
+ OutgoingWhiteboardSession::~OutgoingWhiteboardSession() {
+ }
- void OutgoingWhiteboardSession::startSession() {
- boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionRequest);
- boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
- request->onResponse.connect(boost::bind(&OutgoingWhiteboardSession::handleRequestResponse, this, _1, _2));
- request->send();
- }
+ void OutgoingWhiteboardSession::startSession() {
+ boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionRequest);
+ boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->onResponse.connect(boost::bind(&OutgoingWhiteboardSession::handleRequestResponse, this, _1, _2));
+ request->send();
+ }
- void OutgoingWhiteboardSession::handleRequestResponse(boost::shared_ptr<WhiteboardPayload> /*payload*/, ErrorPayload::ref error) {
- if (error) {
- onRequestRejected(toJID_);
- }
- }
+ void OutgoingWhiteboardSession::handleRequestResponse(boost::shared_ptr<WhiteboardPayload> /*payload*/, ErrorPayload::ref error) {
+ if (error) {
+ onRequestRejected(toJID_);
+ }
+ }
- void OutgoingWhiteboardSession::handleIncomingOperation(WhiteboardOperation::ref operation) {
- WhiteboardOperation::ref op = server.handleClientOperationReceived(operation);
- if (op->getPos() != -1) {
- onOperationReceived(op);
- }
- lastOpID = op->getID();
+ void OutgoingWhiteboardSession::handleIncomingOperation(WhiteboardOperation::ref operation) {
+ WhiteboardOperation::ref op = server.handleClientOperationReceived(operation);
+ if (op->getPos() != -1) {
+ onOperationReceived(op);
+ }
+ lastOpID = op->getID();
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(op);
- sendPayload(payload);
- }
+ WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
+ payload->setOperation(op);
+ sendPayload(payload);
+ }
- void OutgoingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
- operation->setID(idGenerator.generateID());
- operation->setParentID(lastOpID);
- lastOpID = operation->getID();
+ void OutgoingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
+ operation->setID(idGenerator.generateID());
+ operation->setParentID(lastOpID);
+ lastOpID = operation->getID();
- server.handleLocalOperationReceived(operation);
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(operation);
- sendPayload(payload);
- }
+ server.handleLocalOperationReceived(operation);
+ WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
+ payload->setOperation(operation);
+ sendPayload(payload);
+ }
}
diff --git a/Swiften/Whiteboard/OutgoingWhiteboardSession.h b/Swiften/Whiteboard/OutgoingWhiteboardSession.h
index c8098d3..dd8623a 100644
--- a/Swiften/Whiteboard/OutgoingWhiteboardSession.h
+++ b/Swiften/Whiteboard/OutgoingWhiteboardSession.h
@@ -20,20 +20,20 @@
#include <Swiften/Whiteboard/WhiteboardSession.h>
namespace Swift {
- class SWIFTEN_API OutgoingWhiteboardSession : public WhiteboardSession {
- public:
- typedef boost::shared_ptr<OutgoingWhiteboardSession> ref;
-
- public:
- OutgoingWhiteboardSession(const JID& jid, IQRouter* router);
- virtual ~OutgoingWhiteboardSession();
- void startSession();
-
- private:
- void handleRequestResponse(boost::shared_ptr<WhiteboardPayload> /*payload*/, ErrorPayload::ref error);
- void handleIncomingOperation(WhiteboardOperation::ref operation);
- void sendOperation(WhiteboardOperation::ref operation);
-
- WhiteboardServer server;
- };
+ class SWIFTEN_API OutgoingWhiteboardSession : public WhiteboardSession {
+ public:
+ typedef boost::shared_ptr<OutgoingWhiteboardSession> ref;
+
+ public:
+ OutgoingWhiteboardSession(const JID& jid, IQRouter* router);
+ virtual ~OutgoingWhiteboardSession();
+ void startSession();
+
+ private:
+ void handleRequestResponse(boost::shared_ptr<WhiteboardPayload> /*payload*/, ErrorPayload::ref error);
+ void handleIncomingOperation(WhiteboardOperation::ref operation);
+ void sendOperation(WhiteboardOperation::ref operation);
+
+ WhiteboardServer server;
+ };
}
diff --git a/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp b/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp
index 999ccb7..9534c60 100644
--- a/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp
+++ b/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp
@@ -25,659 +25,659 @@
using namespace Swift;
class WhiteboardClientTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(WhiteboardClientTest);
- CPPUNIT_TEST(testSynchronize_simplestSync);
- CPPUNIT_TEST(testSynchronize_withoutTranslation);
- CPPUNIT_TEST(testSynchronize_nonInterrupted);
- CPPUNIT_TEST(testSynchronize_clientInterruption);
- CPPUNIT_TEST(testSynchronize_serverInterruption);
- CPPUNIT_TEST(testSynchronize_nonInterruptedMixOperations);
- CPPUNIT_TEST(testSynchronize_nonInterruptedMixOperations2);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(WhiteboardClientTest);
+ CPPUNIT_TEST(testSynchronize_simplestSync);
+ CPPUNIT_TEST(testSynchronize_withoutTranslation);
+ CPPUNIT_TEST(testSynchronize_nonInterrupted);
+ CPPUNIT_TEST(testSynchronize_clientInterruption);
+ CPPUNIT_TEST(testSynchronize_serverInterruption);
+ CPPUNIT_TEST(testSynchronize_nonInterruptedMixOperations);
+ CPPUNIT_TEST(testSynchronize_nonInterruptedMixOperations2);
+ CPPUNIT_TEST_SUITE_END();
public:
- /*!
- * /\
- * \/
- * \
- */
- void testSynchronize_simplestSync() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- clientOp = createInsertOperation("a", "0", 1);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(aElement);
- WhiteboardInsertOperation::ref result;
- checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
-
- //Client receives server operation parented off "0", which isn't last client operation
- //so it have to be transformed against local operations and then transformed value can
- //be returned to draw
- serverOp = createInsertOperation("b", "0", 1);
- WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(bElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "b", "a", 2, bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation from the server about processed "a" operation, it had to
- //be transformed against "b" on the server side to receive operation parented off "b".
- //There aren't any waiting operations to send to server, this operation should return
- //nothing
- serverOp = createInsertOperation("a", "b", 1);
- pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives local operation, it doesn't have to be transformed against anything
- //but operation returned to send to the server should be parented off last server
- //operation, which is "b"
- clientOp = createInsertOperation("c", "b", 3);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(cElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "c", "a", 3, cElement);
-
- //Client receives confirmation from the server about processed "a" operation, it
- //should be the same operation as it was sent because server didn't have to
- //transform it
- clientOp = createInsertOperation("c", "a", 3);
- clientOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(clientOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Results:
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //
- //Server operations:
- //ID pos
- //0 0
- //b 1
- //a 1
- //c 3
- //
- //what gives 0abc on both sides
- }
-
- /*!
- * /
- * /
- * \
- */
- void testSynchronize_withoutTranslation() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp = createInsertOperation("c", "0", 1);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(cElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "c", "0", 1, cElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- clientOp = createInsertOperation("d", "c", 2);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
-
- //Client receives confirmation about processing "c" operation, it should be the
- //same as sent operation because it wasn't transformed, client could send now
- //operation "d"
- clientOp = createInsertOperation("c", "0", 1);
- clientOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(clientOp);
- checkOperation(pairResult.server, "d", "c", 2, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
- //Client receives confirmation about processing "d", it should be the same as
- //sent operation. There aren't any operations in queue to send.
- clientOp = createInsertOperation("d", "c", 2);
- clientOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(clientOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives new operation from server, it's parented off "d" which is at
- //the end of local history so it doesn't have to be transformed, so operation
- //to pass to window should be the same
- serverOp = createInsertOperation("e", "d", 3);
- WhiteboardEllipseElement::ref eElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(eElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- WhiteboardInsertOperation::ref result = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
-
- //Client operations:
- //ID pos
- //0 0
- //c 1
- //d 2
- //e 3
- //
- //Server operations:
- //ID pos
- //0 0
- //c 1
- //d 2
- //e 3
- }
-
- /*!
- * /\
- * / \
- * \ /
- * \/
- */
- void testSynchronize_nonInterrupted() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- clientOp = createInsertOperation("a", "0", 1);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(aElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- clientOp = createInsertOperation("b", "a", 2);
- WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
-
- //Client receives new operation from server, it should be transformed against
- //"a" and "b" before adding to local operations history because it's parented off "0".
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("c", "0", 1);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "c", "b", 3, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives new operation from server, it should be transformed against
- //results of previous transformations, returned operation should be parented off
- //"c" existing in local history.
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("d", "c", 2);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "d", "c", 4, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "a", it should send next operation
- //to server which is "b", but it should be version parented of transformed "a"
- serverOp = createInsertOperation("a", "d", 1);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.server, "b", "a", 2, bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
-
- //Client receives confirmation about processing "b", there aren't any operations
- //waiting so it should return nothing.
- serverOp = createInsertOperation("b", "a", 2);
- pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //d 4
- //
- //Server operations:
- //ID pos
- //0 0
- //c 1
- //d 2
- //a 1
- //b 2
- //
- //what gives 0abcd on both sides.
- }
-
- /*!
- * /\
- * / \
- * \ /
- * / /
- * \/
- */
- void testSynchronize_clientInterruption() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- clientOp = createInsertOperation("a", "0", 1);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(aElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- clientOp = createInsertOperation("b", "a", 2);
- WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
-
- //Client receives new operation from server, it should be transformed against
- //"a" and "b" before adding to local operations history because it's parented off "0".
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("c", "0", 1);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "c", "b", 3, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives new local operation, client is still waiting for ack so, it
- //should return nothing
- clientOp = createInsertOperation("e", "a", 4);
- WhiteboardEllipseElement::ref eElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(eElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
-
- //Client receives new server operation, to add it to local history it should be transformed
- //against result of previous transformations and operation "e", returned operation should
- //be parented off "e", which was last local operation
- serverOp = createInsertOperation("d", "c", 2);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "d", "e", 5, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "a", it had to be transformed against
- //"c" and "d" and it is now parented off "d", returned value should be next operation
- //which have to be send to server("b" parented off server version of "a").
- serverOp = createInsertOperation("a", "d", 1);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.server, "b", "a", 2, bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
- //Client receives confirmation about processing "b", it is the same operation as sent because
- //it didn't have to be transformed, returned value should be next operation
- //which have to be send to server("e" parented off server version of "b").
- serverOp = createInsertOperation("b", "a", 2);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.server, "e", "b", 4, eElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
- //Client receives confirmation about processing "b", it is the same operation as sent because
- //it didn't have to be transformed, there aren't any operations to send so this function returns
- //nothing
- serverOp = createInsertOperation("e", "b", 4);
- pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Result:
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //e 4
- //d 5
- //
- //Server operations:
- //0 0
- //c 1
- //d 2
- //a 1
- //b 2
- //e 4
- //what gives 0abced on both sides
- }
-
- /*!
- * /\
- * / /
- * \ \
- * \/
- */
- void testSynchronize_serverInterruption() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- clientOp = createInsertOperation("a", "0", 1);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(aElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- clientOp = createInsertOperation("b", "a", 2);
- WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
-
- //Client receives new operation from server, it should be transformed against
- //"a" and "b" before adding to local operations history because it's parented off "0".
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("c", "0", 1);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "c", "b", 3, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "a", it had to be transformed against
- //"c" and it is now parented off "c", returned value should be next operation
- //which have to be send to server("b" parented off server version of "a").
- serverOp = createInsertOperation("a", "c", 1);
- serverOp->setElement(aElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.server, "b", "a", 2, bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
- //Client receives new server operation, to add it to local history it should be transformed
- //against result of previous transformation(but only with transformation of "b"), returned
- //operation should be parented off "c", which was last local operation
- serverOp = createInsertOperation("d", "a", 3);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "d", "c", 4, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "b", it had to be transformed against
- //"d" because both operations was parented off server version of "a".
- //there aren't any operations to send so this function returns nothing.
- serverOp = createInsertOperation("b", "d", 2);
- serverOp->setElement(bElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //d 4
- //
- //Server operations:
- //ID pos
- //0 0
- //c 1
- //a 1
- //d 3
- //b 2
- //
- //what gives 0abcd on both sides
-
- }
-
- /*!
- * /\
- * / \
- * \ /
- * \/
- */
- void testSynchronize_nonInterruptedMixOperations() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- clientOp = createInsertOperation("a", "0", 1);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setElement(aElement);
- checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- WhiteboardUpdateOperation::ref clientUpdateOp = createUpdateOperation("b", "a", 0);
- WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientUpdateOp->setElement(bElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientUpdateOp));
-
- //Client receives new operation from server, it should be transformed against
- //"a" and "b" before adding to local operations history because it's parented off "0".
- //Because client is waiting for ack of "a", there is no operation to send to server
- WhiteboardUpdateOperation::ref serverUpdateOp = createUpdateOperation("c", "0", 0);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverUpdateOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(serverUpdateOp);
- checkOperation(pairResult.client, "c", "b", 0, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives new operation from server, it should be transformed against
- //results of previous transformations, returned operation should be parented off
- //"c" existing in local history.
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("d", "c", 1);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "d", "c", 2, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "a", it should send next operation
- //to server which is "b", but it should be version parented of transformed "a"
- serverOp = createInsertOperation("a", "d", 1);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.server, "b", "a", 0, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
-
- //Client receives confirmation about processing "b", there aren't any operations
- //waiting so it should return nothing.
- serverUpdateOp = createUpdateOperation("b", "a", 0);
- pairResult = client.handleServerOperationReceived(serverUpdateOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //d 4
- //
- //Server operations:
- //ID pos
- //0 0
- //c 1
- //d 2
- //a 1
- //b 2
- //
- //what gives 0abcd on both sides.
- }
-
- /*!
- * /\
- * / \
- * \ /
- * \/
- */
- void testSynchronize_nonInterruptedMixOperations2() {
- WhiteboardClient client;
- WhiteboardInsertOperation::ref serverOp;
- serverOp = createInsertOperation("0", "", 0);
- WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- serverOp = createInsertOperation("1", "0", 1);
- pairResult = client.handleServerOperationReceived(serverOp);
- CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
- //Client receives first local operation, because it's parented off "0" which exists
- //in server history and client doesn't wait for any operation ack from server,
- //so this operation could be send
- WhiteboardInsertOperation::ref clientOp;
- WhiteboardUpdateOperation::ref clientUpdateOp;
- WhiteboardDeleteOperation::ref clientDeleteOp;
- clientUpdateOp = createUpdateOperation("a", "1", 0);
- WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientUpdateOp->setElement(aElement);
- checkOperation(client.handleLocalOperationReceived(clientUpdateOp), "a", "1", 0, aElement);
-
- //Client receives second local operation, client didn't receive ack about previous
- //operation from the server so it can't be send.
- clientDeleteOp = createDeleteOperation("b", "a", 1);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientDeleteOp));
-
- //Client receives new operation from server, it should be transformed against
- //"a" and "b" before adding to local operations history because it's parented off "0".
- //Because client is waiting for ack of "a", there is no operation to send to server
- serverOp = createInsertOperation("c", "1", 2);
- WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverOp->setElement(cElement);
- pairResult = client.handleServerOperationReceived(serverOp);
- checkOperation(pairResult.client, "c", "b", 1, cElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives new operation from server, it should be transformed against
- //results of previous transformations, returned operation should be parented off
- //"c" existing in local history.
- //Because client is waiting for ack of "a", there is no operation to send to server
- WhiteboardUpdateOperation::ref serverUpdateOp = createUpdateOperation("d", "c", 0);
- WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- serverUpdateOp->setElement(dElement);
- pairResult = client.handleServerOperationReceived(serverUpdateOp);
- checkOperation(pairResult.client, "d", "c", 0, dElement);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client receives confirmation about processing "a", it should send next operation
- //to server which is "b", but it should be version parented of transformed "a"
- serverUpdateOp = createUpdateOperation("a", "d", 0);
- pairResult = client.handleServerOperationReceived(serverUpdateOp);
- checkOperation(pairResult.server, "b", "a", 1);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
-
-
- //Client receives confirmation about processing "b", there aren't any operations
- //waiting so it should return nothing.
- WhiteboardDeleteOperation::ref serverDeleteOp = createDeleteOperation("b", "a", 0);
- pairResult = client.handleServerOperationReceived(serverDeleteOp);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
- CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
-
- //Client operations:
- //ID pos
- //0 0
- //a 1
- //b 2
- //c 3
- //d 4
- //
- //Server operations:
- //ID pos
- //0 0
- //c 1
- //d 2
- //a 1
- //b 2
- //
- //what gives 0abcd on both sides.
- }
-
-
- WhiteboardInsertOperation::ref createInsertOperation(std::string id, std::string parent, int pos) {
- WhiteboardInsertOperation::ref operation = boost::make_shared<WhiteboardInsertOperation>();
- operation->setParentID(parent);
- operation->setID(id);
- operation->setPos(pos);
- return operation;
- }
-
- WhiteboardUpdateOperation::ref createUpdateOperation(std::string id, std::string parent, int pos) {
- WhiteboardUpdateOperation::ref operation = boost::make_shared<WhiteboardUpdateOperation>();
- operation->setParentID(parent);
- operation->setID(id);
- operation->setPos(pos);
- return operation;
- }
-
- WhiteboardDeleteOperation::ref createDeleteOperation(std::string id, std::string parent, int pos) {
- WhiteboardDeleteOperation::ref operation = boost::make_shared<WhiteboardDeleteOperation>();
- operation->setParentID(parent);
- operation->setID(id);
- operation->setPos(pos);
- return operation;
- }
-
- void checkOperation(WhiteboardOperation::ref operation, std::string id, std::string parent, int pos = -1, WhiteboardElement::ref element = WhiteboardElement::ref()) {
- CPPUNIT_ASSERT_EQUAL(id, operation->getID());
- CPPUNIT_ASSERT_EQUAL(parent, operation->getParentID());
- if (pos != -1) {
- CPPUNIT_ASSERT_EQUAL(pos, operation->getPos());
- }
-
- if (element) {
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- CPPUNIT_ASSERT_EQUAL(element, insertOp->getElement());
- }
-
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- CPPUNIT_ASSERT_EQUAL(element, updateOp->getElement());
- }
- }
- }
+ /*!
+ * /\
+ * \/
+ * \
+ */
+ void testSynchronize_simplestSync() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ clientOp = createInsertOperation("a", "0", 1);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(aElement);
+ WhiteboardInsertOperation::ref result;
+ checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
+
+ //Client receives server operation parented off "0", which isn't last client operation
+ //so it have to be transformed against local operations and then transformed value can
+ //be returned to draw
+ serverOp = createInsertOperation("b", "0", 1);
+ WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(bElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "b", "a", 2, bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation from the server about processed "a" operation, it had to
+ //be transformed against "b" on the server side to receive operation parented off "b".
+ //There aren't any waiting operations to send to server, this operation should return
+ //nothing
+ serverOp = createInsertOperation("a", "b", 1);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives local operation, it doesn't have to be transformed against anything
+ //but operation returned to send to the server should be parented off last server
+ //operation, which is "b"
+ clientOp = createInsertOperation("c", "b", 3);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(cElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "c", "a", 3, cElement);
+
+ //Client receives confirmation from the server about processed "a" operation, it
+ //should be the same operation as it was sent because server didn't have to
+ //transform it
+ clientOp = createInsertOperation("c", "a", 3);
+ clientOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(clientOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Results:
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //b 1
+ //a 1
+ //c 3
+ //
+ //what gives 0abc on both sides
+ }
+
+ /*!
+ * /
+ * /
+ * \
+ */
+ void testSynchronize_withoutTranslation() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp = createInsertOperation("c", "0", 1);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(cElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "c", "0", 1, cElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ clientOp = createInsertOperation("d", "c", 2);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
+
+ //Client receives confirmation about processing "c" operation, it should be the
+ //same as sent operation because it wasn't transformed, client could send now
+ //operation "d"
+ clientOp = createInsertOperation("c", "0", 1);
+ clientOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(clientOp);
+ checkOperation(pairResult.server, "d", "c", 2, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+ //Client receives confirmation about processing "d", it should be the same as
+ //sent operation. There aren't any operations in queue to send.
+ clientOp = createInsertOperation("d", "c", 2);
+ clientOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(clientOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives new operation from server, it's parented off "d" which is at
+ //the end of local history so it doesn't have to be transformed, so operation
+ //to pass to window should be the same
+ serverOp = createInsertOperation("e", "d", 3);
+ WhiteboardEllipseElement::ref eElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(eElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref result = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+
+ //Client operations:
+ //ID pos
+ //0 0
+ //c 1
+ //d 2
+ //e 3
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //c 1
+ //d 2
+ //e 3
+ }
+
+ /*!
+ * /\
+ * / \
+ * \ /
+ * \/
+ */
+ void testSynchronize_nonInterrupted() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ clientOp = createInsertOperation("a", "0", 1);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(aElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ clientOp = createInsertOperation("b", "a", 2);
+ WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
+
+ //Client receives new operation from server, it should be transformed against
+ //"a" and "b" before adding to local operations history because it's parented off "0".
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("c", "0", 1);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "c", "b", 3, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives new operation from server, it should be transformed against
+ //results of previous transformations, returned operation should be parented off
+ //"c" existing in local history.
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("d", "c", 2);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "d", "c", 4, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "a", it should send next operation
+ //to server which is "b", but it should be version parented of transformed "a"
+ serverOp = createInsertOperation("a", "d", 1);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.server, "b", "a", 2, bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+
+ //Client receives confirmation about processing "b", there aren't any operations
+ //waiting so it should return nothing.
+ serverOp = createInsertOperation("b", "a", 2);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //d 4
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //c 1
+ //d 2
+ //a 1
+ //b 2
+ //
+ //what gives 0abcd on both sides.
+ }
+
+ /*!
+ * /\
+ * / \
+ * \ /
+ * / /
+ * \/
+ */
+ void testSynchronize_clientInterruption() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ clientOp = createInsertOperation("a", "0", 1);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(aElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ clientOp = createInsertOperation("b", "a", 2);
+ WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
+
+ //Client receives new operation from server, it should be transformed against
+ //"a" and "b" before adding to local operations history because it's parented off "0".
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("c", "0", 1);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "c", "b", 3, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives new local operation, client is still waiting for ack so, it
+ //should return nothing
+ clientOp = createInsertOperation("e", "a", 4);
+ WhiteboardEllipseElement::ref eElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(eElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
+
+ //Client receives new server operation, to add it to local history it should be transformed
+ //against result of previous transformations and operation "e", returned operation should
+ //be parented off "e", which was last local operation
+ serverOp = createInsertOperation("d", "c", 2);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "d", "e", 5, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "a", it had to be transformed against
+ //"c" and "d" and it is now parented off "d", returned value should be next operation
+ //which have to be send to server("b" parented off server version of "a").
+ serverOp = createInsertOperation("a", "d", 1);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.server, "b", "a", 2, bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+ //Client receives confirmation about processing "b", it is the same operation as sent because
+ //it didn't have to be transformed, returned value should be next operation
+ //which have to be send to server("e" parented off server version of "b").
+ serverOp = createInsertOperation("b", "a", 2);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.server, "e", "b", 4, eElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+ //Client receives confirmation about processing "b", it is the same operation as sent because
+ //it didn't have to be transformed, there aren't any operations to send so this function returns
+ //nothing
+ serverOp = createInsertOperation("e", "b", 4);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Result:
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //e 4
+ //d 5
+ //
+ //Server operations:
+ //0 0
+ //c 1
+ //d 2
+ //a 1
+ //b 2
+ //e 4
+ //what gives 0abced on both sides
+ }
+
+ /*!
+ * /\
+ * / /
+ * \ \
+ * \/
+ */
+ void testSynchronize_serverInterruption() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ clientOp = createInsertOperation("a", "0", 1);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(aElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ clientOp = createInsertOperation("b", "a", 2);
+ WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientOp));
+
+ //Client receives new operation from server, it should be transformed against
+ //"a" and "b" before adding to local operations history because it's parented off "0".
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("c", "0", 1);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "c", "b", 3, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "a", it had to be transformed against
+ //"c" and it is now parented off "c", returned value should be next operation
+ //which have to be send to server("b" parented off server version of "a").
+ serverOp = createInsertOperation("a", "c", 1);
+ serverOp->setElement(aElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.server, "b", "a", 2, bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+ //Client receives new server operation, to add it to local history it should be transformed
+ //against result of previous transformation(but only with transformation of "b"), returned
+ //operation should be parented off "c", which was last local operation
+ serverOp = createInsertOperation("d", "a", 3);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "d", "c", 4, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "b", it had to be transformed against
+ //"d" because both operations was parented off server version of "a".
+ //there aren't any operations to send so this function returns nothing.
+ serverOp = createInsertOperation("b", "d", 2);
+ serverOp->setElement(bElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //d 4
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //c 1
+ //a 1
+ //d 3
+ //b 2
+ //
+ //what gives 0abcd on both sides
+
+ }
+
+ /*!
+ * /\
+ * / \
+ * \ /
+ * \/
+ */
+ void testSynchronize_nonInterruptedMixOperations() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ clientOp = createInsertOperation("a", "0", 1);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setElement(aElement);
+ checkOperation(client.handleLocalOperationReceived(clientOp), "a", "0", 1, aElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ WhiteboardUpdateOperation::ref clientUpdateOp = createUpdateOperation("b", "a", 0);
+ WhiteboardEllipseElement::ref bElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientUpdateOp->setElement(bElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientUpdateOp));
+
+ //Client receives new operation from server, it should be transformed against
+ //"a" and "b" before adding to local operations history because it's parented off "0".
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ WhiteboardUpdateOperation::ref serverUpdateOp = createUpdateOperation("c", "0", 0);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverUpdateOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(serverUpdateOp);
+ checkOperation(pairResult.client, "c", "b", 0, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives new operation from server, it should be transformed against
+ //results of previous transformations, returned operation should be parented off
+ //"c" existing in local history.
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("d", "c", 1);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "d", "c", 2, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "a", it should send next operation
+ //to server which is "b", but it should be version parented of transformed "a"
+ serverOp = createInsertOperation("a", "d", 1);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.server, "b", "a", 0, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+
+ //Client receives confirmation about processing "b", there aren't any operations
+ //waiting so it should return nothing.
+ serverUpdateOp = createUpdateOperation("b", "a", 0);
+ pairResult = client.handleServerOperationReceived(serverUpdateOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //d 4
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //c 1
+ //d 2
+ //a 1
+ //b 2
+ //
+ //what gives 0abcd on both sides.
+ }
+
+ /*!
+ * /\
+ * / \
+ * \ /
+ * \/
+ */
+ void testSynchronize_nonInterruptedMixOperations2() {
+ WhiteboardClient client;
+ WhiteboardInsertOperation::ref serverOp;
+ serverOp = createInsertOperation("0", "", 0);
+ WhiteboardClient::Result pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ serverOp = createInsertOperation("1", "0", 1);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ CPPUNIT_ASSERT_EQUAL(serverOp, boost::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client));
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+ //Client receives first local operation, because it's parented off "0" which exists
+ //in server history and client doesn't wait for any operation ack from server,
+ //so this operation could be send
+ WhiteboardInsertOperation::ref clientOp;
+ WhiteboardUpdateOperation::ref clientUpdateOp;
+ WhiteboardDeleteOperation::ref clientDeleteOp;
+ clientUpdateOp = createUpdateOperation("a", "1", 0);
+ WhiteboardEllipseElement::ref aElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientUpdateOp->setElement(aElement);
+ checkOperation(client.handleLocalOperationReceived(clientUpdateOp), "a", "1", 0, aElement);
+
+ //Client receives second local operation, client didn't receive ack about previous
+ //operation from the server so it can't be send.
+ clientDeleteOp = createDeleteOperation("b", "a", 1);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), client.handleLocalOperationReceived(clientDeleteOp));
+
+ //Client receives new operation from server, it should be transformed against
+ //"a" and "b" before adding to local operations history because it's parented off "0".
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ serverOp = createInsertOperation("c", "1", 2);
+ WhiteboardEllipseElement::ref cElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(cElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ checkOperation(pairResult.client, "c", "b", 1, cElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives new operation from server, it should be transformed against
+ //results of previous transformations, returned operation should be parented off
+ //"c" existing in local history.
+ //Because client is waiting for ack of "a", there is no operation to send to server
+ WhiteboardUpdateOperation::ref serverUpdateOp = createUpdateOperation("d", "c", 0);
+ WhiteboardEllipseElement::ref dElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverUpdateOp->setElement(dElement);
+ pairResult = client.handleServerOperationReceived(serverUpdateOp);
+ checkOperation(pairResult.client, "d", "c", 0, dElement);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client receives confirmation about processing "a", it should send next operation
+ //to server which is "b", but it should be version parented of transformed "a"
+ serverUpdateOp = createUpdateOperation("a", "d", 0);
+ pairResult = client.handleServerOperationReceived(serverUpdateOp);
+ checkOperation(pairResult.server, "b", "a", 1);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+
+
+ //Client receives confirmation about processing "b", there aren't any operations
+ //waiting so it should return nothing.
+ WhiteboardDeleteOperation::ref serverDeleteOp = createDeleteOperation("b", "a", 0);
+ pairResult = client.handleServerOperationReceived(serverDeleteOp);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(WhiteboardOperation::ref(), pairResult.server);
+
+ //Client operations:
+ //ID pos
+ //0 0
+ //a 1
+ //b 2
+ //c 3
+ //d 4
+ //
+ //Server operations:
+ //ID pos
+ //0 0
+ //c 1
+ //d 2
+ //a 1
+ //b 2
+ //
+ //what gives 0abcd on both sides.
+ }
+
+
+ WhiteboardInsertOperation::ref createInsertOperation(std::string id, std::string parent, int pos) {
+ WhiteboardInsertOperation::ref operation = boost::make_shared<WhiteboardInsertOperation>();
+ operation->setParentID(parent);
+ operation->setID(id);
+ operation->setPos(pos);
+ return operation;
+ }
+
+ WhiteboardUpdateOperation::ref createUpdateOperation(std::string id, std::string parent, int pos) {
+ WhiteboardUpdateOperation::ref operation = boost::make_shared<WhiteboardUpdateOperation>();
+ operation->setParentID(parent);
+ operation->setID(id);
+ operation->setPos(pos);
+ return operation;
+ }
+
+ WhiteboardDeleteOperation::ref createDeleteOperation(std::string id, std::string parent, int pos) {
+ WhiteboardDeleteOperation::ref operation = boost::make_shared<WhiteboardDeleteOperation>();
+ operation->setParentID(parent);
+ operation->setID(id);
+ operation->setPos(pos);
+ return operation;
+ }
+
+ void checkOperation(WhiteboardOperation::ref operation, std::string id, std::string parent, int pos = -1, WhiteboardElement::ref element = WhiteboardElement::ref()) {
+ CPPUNIT_ASSERT_EQUAL(id, operation->getID());
+ CPPUNIT_ASSERT_EQUAL(parent, operation->getParentID());
+ if (pos != -1) {
+ CPPUNIT_ASSERT_EQUAL(pos, operation->getPos());
+ }
+
+ if (element) {
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ CPPUNIT_ASSERT_EQUAL(element, insertOp->getElement());
+ }
+
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ CPPUNIT_ASSERT_EQUAL(element, updateOp->getElement());
+ }
+ }
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(WhiteboardClientTest);
diff --git a/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp b/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp
index 3434e5e..58b8c19 100644
--- a/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp
+++ b/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp
@@ -25,111 +25,111 @@
using namespace Swift;
class WhiteboardServerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(WhiteboardServerTest);
- CPPUNIT_TEST(testSimpleOp);
- CPPUNIT_TEST(testSimpleOp1);
- CPPUNIT_TEST(testSimpleOp2);
- CPPUNIT_TEST(testFewSimpleOps);
- CPPUNIT_TEST_SUITE_END();
+ CPPUNIT_TEST_SUITE(WhiteboardServerTest);
+ CPPUNIT_TEST(testSimpleOp);
+ CPPUNIT_TEST(testSimpleOp1);
+ CPPUNIT_TEST(testSimpleOp2);
+ CPPUNIT_TEST(testFewSimpleOps);
+ CPPUNIT_TEST_SUITE_END();
public:
- void testSimpleOp() {
- WhiteboardServer server;
- WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
- firstOp->setID("0");
- server.handleLocalOperationReceived(firstOp);
- WhiteboardInsertOperation::ref serverOp = boost::make_shared<WhiteboardInsertOperation>();
- serverOp->setID("b");
- serverOp->setParentID("0");
- serverOp->setPos(1);
- server.handleLocalOperationReceived(serverOp);
- WhiteboardInsertOperation::ref clientOp = boost::make_shared<WhiteboardInsertOperation>();
- WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setID("a");
- clientOp->setParentID("0");
- clientOp->setPos(1);
- clientOp->setElement(clientElement);
- WhiteboardInsertOperation::ref op = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(server.handleClientOperationReceived(clientOp));
- CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
- CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
- CPPUNIT_ASSERT_EQUAL(1, op->getPos());
- CPPUNIT_ASSERT_EQUAL(clientElement, boost::dynamic_pointer_cast<WhiteboardEllipseElement>(op->getElement()));
- }
+ void testSimpleOp() {
+ WhiteboardServer server;
+ WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardInsertOperation::ref serverOp = boost::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref clientOp = boost::make_shared<WhiteboardInsertOperation>();
+ WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardInsertOperation::ref op = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(server.handleClientOperationReceived(clientOp));
+ CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
+ CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
+ CPPUNIT_ASSERT_EQUAL(1, op->getPos());
+ CPPUNIT_ASSERT_EQUAL(clientElement, boost::dynamic_pointer_cast<WhiteboardEllipseElement>(op->getElement()));
+ }
- void testSimpleOp1() {
- WhiteboardServer server;
- WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
- firstOp->setID("0");
- server.handleLocalOperationReceived(firstOp);
- WhiteboardDeleteOperation::ref serverOp = boost::make_shared<WhiteboardDeleteOperation>();
- serverOp->setID("b");
- serverOp->setParentID("0");
- serverOp->setPos(1);
- server.handleLocalOperationReceived(serverOp);
- WhiteboardUpdateOperation::ref clientOp = boost::make_shared<WhiteboardUpdateOperation>();
- WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setID("a");
- clientOp->setParentID("0");
- clientOp->setPos(1);
- clientOp->setElement(clientElement);
- WhiteboardDeleteOperation::ref op = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(server.handleClientOperationReceived(clientOp));
- CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
- CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
- CPPUNIT_ASSERT_EQUAL(-1, op->getPos());
- }
+ void testSimpleOp1() {
+ WhiteboardServer server;
+ WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardDeleteOperation::ref serverOp = boost::make_shared<WhiteboardDeleteOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardUpdateOperation::ref clientOp = boost::make_shared<WhiteboardUpdateOperation>();
+ WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardDeleteOperation::ref op = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(server.handleClientOperationReceived(clientOp));
+ CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
+ CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
+ CPPUNIT_ASSERT_EQUAL(-1, op->getPos());
+ }
- void testSimpleOp2() {
- WhiteboardServer server;
- WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
- firstOp->setID("0");
- server.handleLocalOperationReceived(firstOp);
- WhiteboardUpdateOperation::ref serverOp = boost::make_shared<WhiteboardUpdateOperation>();
- serverOp->setID("b");
- serverOp->setParentID("0");
- serverOp->setPos(1);
- server.handleLocalOperationReceived(serverOp);
- WhiteboardDeleteOperation::ref clientOp = boost::make_shared<WhiteboardDeleteOperation>();
- clientOp->setID("a");
- clientOp->setParentID("0");
- clientOp->setPos(1);
- WhiteboardDeleteOperation::ref op = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(server.handleClientOperationReceived(clientOp));
- CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
- CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
- CPPUNIT_ASSERT_EQUAL(1, op->getPos());
- }
+ void testSimpleOp2() {
+ WhiteboardServer server;
+ WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardUpdateOperation::ref serverOp = boost::make_shared<WhiteboardUpdateOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardDeleteOperation::ref clientOp = boost::make_shared<WhiteboardDeleteOperation>();
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ WhiteboardDeleteOperation::ref op = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(server.handleClientOperationReceived(clientOp));
+ CPPUNIT_ASSERT_EQUAL(std::string("b"), op->getParentID());
+ CPPUNIT_ASSERT_EQUAL(std::string("a"), op->getID());
+ CPPUNIT_ASSERT_EQUAL(1, op->getPos());
+ }
- void testFewSimpleOps() {
- WhiteboardServer server;
- WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
- firstOp->setID("0");
- server.handleLocalOperationReceived(firstOp);
- WhiteboardInsertOperation::ref serverOp = boost::make_shared<WhiteboardInsertOperation>();
- serverOp->setID("a");
- serverOp->setParentID("0");
- serverOp->setPos(1);
- server.handleLocalOperationReceived(serverOp);
- serverOp = boost::make_shared<WhiteboardInsertOperation>();
- serverOp->setID("b");
- serverOp->setParentID("a");
- serverOp->setPos(2);
- server.handleLocalOperationReceived(serverOp);
- serverOp = boost::make_shared<WhiteboardInsertOperation>();
- serverOp->setID("c");
- serverOp->setParentID("b");
- serverOp->setPos(3);
- server.handleLocalOperationReceived(serverOp);
- WhiteboardInsertOperation::ref clientOp = boost::make_shared<WhiteboardInsertOperation>();
- WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
- clientOp->setID("d");
- clientOp->setParentID("0");
- clientOp->setPos(1);
- clientOp->setElement(clientElement);
- WhiteboardInsertOperation::ref op = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(server.handleClientOperationReceived(clientOp));
- CPPUNIT_ASSERT_EQUAL(std::string("c"), op->getParentID());
- CPPUNIT_ASSERT_EQUAL(std::string("d"), op->getID());
- CPPUNIT_ASSERT_EQUAL(1, op->getPos());
- CPPUNIT_ASSERT_EQUAL(clientElement, boost::dynamic_pointer_cast<WhiteboardEllipseElement>(op->getElement()));
- }
+ void testFewSimpleOps() {
+ WhiteboardServer server;
+ WhiteboardInsertOperation::ref firstOp = boost::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardInsertOperation::ref serverOp = boost::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("a");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ serverOp = boost::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("a");
+ serverOp->setPos(2);
+ server.handleLocalOperationReceived(serverOp);
+ serverOp = boost::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("c");
+ serverOp->setParentID("b");
+ serverOp->setPos(3);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref clientOp = boost::make_shared<WhiteboardInsertOperation>();
+ WhiteboardEllipseElement::ref clientElement = boost::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("d");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardInsertOperation::ref op = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(server.handleClientOperationReceived(clientOp));
+ CPPUNIT_ASSERT_EQUAL(std::string("c"), op->getParentID());
+ CPPUNIT_ASSERT_EQUAL(std::string("d"), op->getID());
+ CPPUNIT_ASSERT_EQUAL(1, op->getPos());
+ CPPUNIT_ASSERT_EQUAL(clientElement, boost::dynamic_pointer_cast<WhiteboardEllipseElement>(op->getElement()));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(WhiteboardServerTest);
diff --git a/Swiften/Whiteboard/WhiteboardClient.cpp b/Swiften/Whiteboard/WhiteboardClient.cpp
index 00f8cbc..f272a8c 100644
--- a/Swiften/Whiteboard/WhiteboardClient.cpp
+++ b/Swiften/Whiteboard/WhiteboardClient.cpp
@@ -19,112 +19,112 @@
#include <Swiften/Whiteboard/WhiteboardTransformer.h>
namespace Swift {
- WhiteboardOperation::ref WhiteboardClient::handleLocalOperationReceived(WhiteboardOperation::ref operation) {
- localOperations_.push_back(operation);
-
- WhiteboardOperation::ref op;
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- op = boost::make_shared<WhiteboardInsertOperation>(*insertOp);
- }
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- op = boost::make_shared<WhiteboardUpdateOperation>(*updateOp);
- }
- WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
- if (deleteOp) {
- op = boost::make_shared<WhiteboardDeleteOperation>(*deleteOp);
- }
-
- if (!bridge_.empty()) {
- op->setParentID(bridge_.back()->getID());
- }
- bridge_.push_back(op);
-
- if (lastSentOperationID_.empty())
- {
- WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
- if (insertOp) {
- op = boost::make_shared<WhiteboardInsertOperation>(*insertOp);
- }
- WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
- if (updateOp) {
- op = boost::make_shared<WhiteboardUpdateOperation>(*updateOp);
- }
- WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
- if (deleteOp) {
- op = boost::make_shared<WhiteboardDeleteOperation>(*deleteOp);
- }
-
-
- if (!serverOperations_.empty()) {
- op->setParentID(serverOperations_.back()->getID());
- }
- lastSentOperationID_ = operation->getID();
- return op;
- } else {
- return WhiteboardOperation::ref();
- }
- }
-
- WhiteboardClient::Result WhiteboardClient::handleServerOperationReceived(WhiteboardOperation::ref operation) {
- serverOperations_.push_back(operation);
- Result result;
-// if (localOperations_.empty()) {// || localOperations_.back()->getID() == operation->getParentID()) {
- //Situation where client and server are in sync
- if (localOperations_.size() == serverOperations_.size()-1) {
- localOperations_.push_back(operation);
-// clientOp = operation;
- result.client = operation;
- } else if (lastSentOperationID_ == operation->getID()) {
- //Client received confirmation about own operation and it sends next operation to server
- if (!bridge_.empty() && lastSentOperationID_ == bridge_.front()->getID()) {
- bridge_.erase(bridge_.begin());
- }
-
- if (!bridge_.empty() && (bridge_.front())->getParentID() == lastSentOperationID_) {
- lastSentOperationID_ = (bridge_.front())->getID();
- result.server = bridge_.front();
- }
- if (!result.server) {
- lastSentOperationID_.clear();
- }
- } else {
- std::list<WhiteboardOperation::ref>::iterator it = bridge_.begin();
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> opPair;
- WhiteboardOperation::ref temp;
- opPair = WhiteboardTransformer::transform(*it, operation);
- temp = opPair.first;
-
- *it = opPair.second;
- std::string previousID = (*it)->getID();
- ++it;
- for (; it != bridge_.end(); ++it) {
- opPair = WhiteboardTransformer::transform(*it, temp);
- temp = opPair.first;
- *it = opPair.second;
- (*it)->setParentID(previousID);
- previousID = (*it)->getID();
- }
-
- temp->setParentID(localOperations_.back()->getID());
- localOperations_.push_back(temp);
- result.client = temp;
- }
-
- return result;
- }
-
- void WhiteboardClient::print() {
- std::list<WhiteboardOperation::ref>::iterator it;
- std::cout << "Client" << std::endl;
- for(it = localOperations_.begin(); it != localOperations_.end(); ++it) {
- std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
- }
-
- std::cout << "Server" << std::endl;
- for(it = serverOperations_.begin(); it != serverOperations_.end(); ++it) {
- std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
- }
- }
+ WhiteboardOperation::ref WhiteboardClient::handleLocalOperationReceived(WhiteboardOperation::ref operation) {
+ localOperations_.push_back(operation);
+
+ WhiteboardOperation::ref op;
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ op = boost::make_shared<WhiteboardInsertOperation>(*insertOp);
+ }
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ op = boost::make_shared<WhiteboardUpdateOperation>(*updateOp);
+ }
+ WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ op = boost::make_shared<WhiteboardDeleteOperation>(*deleteOp);
+ }
+
+ if (!bridge_.empty()) {
+ op->setParentID(bridge_.back()->getID());
+ }
+ bridge_.push_back(op);
+
+ if (lastSentOperationID_.empty())
+ {
+ WhiteboardInsertOperation::ref insertOp = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ op = boost::make_shared<WhiteboardInsertOperation>(*insertOp);
+ }
+ WhiteboardUpdateOperation::ref updateOp = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ op = boost::make_shared<WhiteboardUpdateOperation>(*updateOp);
+ }
+ WhiteboardDeleteOperation::ref deleteOp = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ op = boost::make_shared<WhiteboardDeleteOperation>(*deleteOp);
+ }
+
+
+ if (!serverOperations_.empty()) {
+ op->setParentID(serverOperations_.back()->getID());
+ }
+ lastSentOperationID_ = operation->getID();
+ return op;
+ } else {
+ return WhiteboardOperation::ref();
+ }
+ }
+
+ WhiteboardClient::Result WhiteboardClient::handleServerOperationReceived(WhiteboardOperation::ref operation) {
+ serverOperations_.push_back(operation);
+ Result result;
+// if (localOperations_.empty()) {// || localOperations_.back()->getID() == operation->getParentID()) {
+ //Situation where client and server are in sync
+ if (localOperations_.size() == serverOperations_.size()-1) {
+ localOperations_.push_back(operation);
+// clientOp = operation;
+ result.client = operation;
+ } else if (lastSentOperationID_ == operation->getID()) {
+ //Client received confirmation about own operation and it sends next operation to server
+ if (!bridge_.empty() && lastSentOperationID_ == bridge_.front()->getID()) {
+ bridge_.erase(bridge_.begin());
+ }
+
+ if (!bridge_.empty() && (bridge_.front())->getParentID() == lastSentOperationID_) {
+ lastSentOperationID_ = (bridge_.front())->getID();
+ result.server = bridge_.front();
+ }
+ if (!result.server) {
+ lastSentOperationID_.clear();
+ }
+ } else {
+ std::list<WhiteboardOperation::ref>::iterator it = bridge_.begin();
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> opPair;
+ WhiteboardOperation::ref temp;
+ opPair = WhiteboardTransformer::transform(*it, operation);
+ temp = opPair.first;
+
+ *it = opPair.second;
+ std::string previousID = (*it)->getID();
+ ++it;
+ for (; it != bridge_.end(); ++it) {
+ opPair = WhiteboardTransformer::transform(*it, temp);
+ temp = opPair.first;
+ *it = opPair.second;
+ (*it)->setParentID(previousID);
+ previousID = (*it)->getID();
+ }
+
+ temp->setParentID(localOperations_.back()->getID());
+ localOperations_.push_back(temp);
+ result.client = temp;
+ }
+
+ return result;
+ }
+
+ void WhiteboardClient::print() {
+ std::list<WhiteboardOperation::ref>::iterator it;
+ std::cout << "Client" << std::endl;
+ for(it = localOperations_.begin(); it != localOperations_.end(); ++it) {
+ std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
+ }
+
+ std::cout << "Server" << std::endl;
+ for(it = serverOperations_.begin(); it != serverOperations_.end(); ++it) {
+ std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
+ }
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardClient.h b/Swiften/Whiteboard/WhiteboardClient.h
index 37a92d9..15870c6 100644
--- a/Swiften/Whiteboard/WhiteboardClient.h
+++ b/Swiften/Whiteboard/WhiteboardClient.h
@@ -19,26 +19,26 @@
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardClient {
- public:
- struct Result {
- WhiteboardOperation::ref client;
- WhiteboardOperation::ref server;
- };
- /*!
- * @return Operation to send
- */
- WhiteboardOperation::ref handleLocalOperationReceived(WhiteboardOperation::ref operation);
- /*!
- * @return pair.first-element to handle locally, pair.second-element to send to server
- */
- Result handleServerOperationReceived(WhiteboardOperation::ref operation);
- void print();
+ class SWIFTEN_API WhiteboardClient {
+ public:
+ struct Result {
+ WhiteboardOperation::ref client;
+ WhiteboardOperation::ref server;
+ };
+ /*!
+ * @return Operation to send
+ */
+ WhiteboardOperation::ref handleLocalOperationReceived(WhiteboardOperation::ref operation);
+ /*!
+ * @return pair.first-element to handle locally, pair.second-element to send to server
+ */
+ Result handleServerOperationReceived(WhiteboardOperation::ref operation);
+ void print();
- private:
- std::list<WhiteboardOperation::ref> localOperations_;
- std::list<WhiteboardOperation::ref> serverOperations_;
- std::list<WhiteboardOperation::ref> bridge_;
- std::string lastSentOperationID_;
- };
+ private:
+ std::list<WhiteboardOperation::ref> localOperations_;
+ std::list<WhiteboardOperation::ref> serverOperations_;
+ std::list<WhiteboardOperation::ref> bridge_;
+ std::string lastSentOperationID_;
+ };
}
diff --git a/Swiften/Whiteboard/WhiteboardResponder.cpp b/Swiften/Whiteboard/WhiteboardResponder.cpp
index 2a725ec..5e35782 100644
--- a/Swiften/Whiteboard/WhiteboardResponder.cpp
+++ b/Swiften/Whiteboard/WhiteboardResponder.cpp
@@ -20,25 +20,25 @@
#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
namespace Swift {
- WhiteboardResponder::WhiteboardResponder(WhiteboardSessionManager* sessionManager, IQRouter* router) : SetResponder<WhiteboardPayload>(router), sessionManager_(sessionManager), router_(router) {
- }
+ WhiteboardResponder::WhiteboardResponder(WhiteboardSessionManager* sessionManager, IQRouter* router) : SetResponder<WhiteboardPayload>(router), sessionManager_(sessionManager), router_(router) {
+ }
- bool WhiteboardResponder::handleSetRequest(const JID& from, const JID& /*to*/, const std::string& id, boost::shared_ptr<WhiteboardPayload> payload) {
- if (payload->getType() == WhiteboardPayload::SessionRequest) {
- if (sessionManager_->getSession(from)) {
- sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel);
- } else {
- sendResponse(from, id, boost::shared_ptr<WhiteboardPayload>());
- IncomingWhiteboardSession::ref session = boost::make_shared<IncomingWhiteboardSession>(from, router_);
- sessionManager_->handleIncomingSession(session);
- }
- } else {
- sendResponse(from, id, boost::shared_ptr<WhiteboardPayload>());
- WhiteboardSession::ref session = sessionManager_->getSession(from);
- if (session != NULL) {
- session->handleIncomingAction(payload);
- }
- }
- return true;
- }
+ bool WhiteboardResponder::handleSetRequest(const JID& from, const JID& /*to*/, const std::string& id, boost::shared_ptr<WhiteboardPayload> payload) {
+ if (payload->getType() == WhiteboardPayload::SessionRequest) {
+ if (sessionManager_->getSession(from)) {
+ sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel);
+ } else {
+ sendResponse(from, id, boost::shared_ptr<WhiteboardPayload>());
+ IncomingWhiteboardSession::ref session = boost::make_shared<IncomingWhiteboardSession>(from, router_);
+ sessionManager_->handleIncomingSession(session);
+ }
+ } else {
+ sendResponse(from, id, boost::shared_ptr<WhiteboardPayload>());
+ WhiteboardSession::ref session = sessionManager_->getSession(from);
+ if (session != NULL) {
+ session->handleIncomingAction(payload);
+ }
+ }
+ return true;
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardResponder.h b/Swiften/Whiteboard/WhiteboardResponder.h
index 8336485..0821a9f 100644
--- a/Swiften/Whiteboard/WhiteboardResponder.h
+++ b/Swiften/Whiteboard/WhiteboardResponder.h
@@ -17,16 +17,16 @@
#include <Swiften/Queries/SetResponder.h>
namespace Swift {
- class IQRouter;
- class WhiteboardSessionManager;
+ class IQRouter;
+ class WhiteboardSessionManager;
- class SWIFTEN_API WhiteboardResponder : public SetResponder<WhiteboardPayload> {
- public:
- WhiteboardResponder(WhiteboardSessionManager* sessionManager, IQRouter* router);
- bool handleSetRequest(const JID& from, const JID& /*to*/, const std::string& id, boost::shared_ptr<WhiteboardPayload> payload);
+ class SWIFTEN_API WhiteboardResponder : public SetResponder<WhiteboardPayload> {
+ public:
+ WhiteboardResponder(WhiteboardSessionManager* sessionManager, IQRouter* router);
+ bool handleSetRequest(const JID& from, const JID& /*to*/, const std::string& id, boost::shared_ptr<WhiteboardPayload> payload);
- private:
- WhiteboardSessionManager* sessionManager_;
- IQRouter* router_;
- };
+ private:
+ WhiteboardSessionManager* sessionManager_;
+ IQRouter* router_;
+ };
}
diff --git a/Swiften/Whiteboard/WhiteboardServer.cpp b/Swiften/Whiteboard/WhiteboardServer.cpp
index 7b24ae4..4a2a315 100644
--- a/Swiften/Whiteboard/WhiteboardServer.cpp
+++ b/Swiften/Whiteboard/WhiteboardServer.cpp
@@ -17,41 +17,41 @@
#include <Swiften/Whiteboard/WhiteboardTransformer.h>
namespace Swift {
- void WhiteboardServer::handleLocalOperationReceived(WhiteboardOperation::ref operation) {
- operations_.push_back(operation);
- }
-
- WhiteboardOperation::ref WhiteboardServer::handleClientOperationReceived(WhiteboardOperation::ref newOperation) {
- std::list<WhiteboardOperation::ref>::reverse_iterator it;
- if (operations_.empty() || newOperation->getParentID() == operations_.back()->getID()) {
- operations_.push_back(newOperation);
- return newOperation;
- }
- for (it = operations_.rbegin(); it != operations_.rend(); ++it) {
- WhiteboardOperation::ref operation = *it;
- while (newOperation->getParentID() == operation->getParentID()) {
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> tResult = WhiteboardTransformer::transform(newOperation, operation);
-
- if (it == operations_.rbegin()) {
- operations_.push_back(tResult.second);
- return tResult.second;
- } else {
- newOperation = tResult.second;
- --it;
- operation = *it;
- }
-
- }
- }
- return WhiteboardOperation::ref();
- }
-
- void WhiteboardServer::print() {
- std::list<WhiteboardOperation::ref>::iterator it;
- std::cout << "Server:" << std::endl;
- for(it = operations_.begin(); it != operations_.end(); ++it) {
- std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
- }
- }
+ void WhiteboardServer::handleLocalOperationReceived(WhiteboardOperation::ref operation) {
+ operations_.push_back(operation);
+ }
+
+ WhiteboardOperation::ref WhiteboardServer::handleClientOperationReceived(WhiteboardOperation::ref newOperation) {
+ std::list<WhiteboardOperation::ref>::reverse_iterator it;
+ if (operations_.empty() || newOperation->getParentID() == operations_.back()->getID()) {
+ operations_.push_back(newOperation);
+ return newOperation;
+ }
+ for (it = operations_.rbegin(); it != operations_.rend(); ++it) {
+ WhiteboardOperation::ref operation = *it;
+ while (newOperation->getParentID() == operation->getParentID()) {
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> tResult = WhiteboardTransformer::transform(newOperation, operation);
+
+ if (it == operations_.rbegin()) {
+ operations_.push_back(tResult.second);
+ return tResult.second;
+ } else {
+ newOperation = tResult.second;
+ --it;
+ operation = *it;
+ }
+
+ }
+ }
+ return WhiteboardOperation::ref();
+ }
+
+ void WhiteboardServer::print() {
+ std::list<WhiteboardOperation::ref>::iterator it;
+ std::cout << "Server:" << std::endl;
+ for(it = operations_.begin(); it != operations_.end(); ++it) {
+ std::cout << (*it)->getID() << " " << (*it)->getPos() << std::endl;
+ }
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardServer.h b/Swiften/Whiteboard/WhiteboardServer.h
index efc7a1c..fcbdbe7 100644
--- a/Swiften/Whiteboard/WhiteboardServer.h
+++ b/Swiften/Whiteboard/WhiteboardServer.h
@@ -18,13 +18,13 @@
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
namespace Swift {
- class SWIFTEN_API WhiteboardServer {
- public:
- void handleLocalOperationReceived(WhiteboardOperation::ref operation);
- WhiteboardOperation::ref handleClientOperationReceived(WhiteboardOperation::ref operation);
- void print();
+ class SWIFTEN_API WhiteboardServer {
+ public:
+ void handleLocalOperationReceived(WhiteboardOperation::ref operation);
+ WhiteboardOperation::ref handleClientOperationReceived(WhiteboardOperation::ref operation);
+ void print();
- private:
- std::list<WhiteboardOperation::ref> operations_;
- };
+ private:
+ std::list<WhiteboardOperation::ref> operations_;
+ };
}
diff --git a/Swiften/Whiteboard/WhiteboardSession.cpp b/Swiften/Whiteboard/WhiteboardSession.cpp
index 064ab3a..23ca312 100644
--- a/Swiften/Whiteboard/WhiteboardSession.cpp
+++ b/Swiften/Whiteboard/WhiteboardSession.cpp
@@ -21,54 +21,54 @@
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
- WhiteboardSession::WhiteboardSession(const JID& jid, IQRouter* router) : toJID_(jid), router_(router) {
- }
+ WhiteboardSession::WhiteboardSession(const JID& jid, IQRouter* router) : toJID_(jid), router_(router) {
+ }
- WhiteboardSession::~WhiteboardSession() {
- }
+ WhiteboardSession::~WhiteboardSession() {
+ }
- void WhiteboardSession::handleIncomingAction(boost::shared_ptr<WhiteboardPayload> payload) {
- switch (payload->getType()) {
- case WhiteboardPayload::Data:
- handleIncomingOperation(payload->getOperation());
- return;
- case WhiteboardPayload::SessionAccept:
- onRequestAccepted(toJID_);
- return;
- case WhiteboardPayload::SessionTerminate:
- onSessionTerminated(toJID_);
- return;
+ void WhiteboardSession::handleIncomingAction(boost::shared_ptr<WhiteboardPayload> payload) {
+ switch (payload->getType()) {
+ case WhiteboardPayload::Data:
+ handleIncomingOperation(payload->getOperation());
+ return;
+ case WhiteboardPayload::SessionAccept:
+ onRequestAccepted(toJID_);
+ return;
+ case WhiteboardPayload::SessionTerminate:
+ onSessionTerminated(toJID_);
+ return;
- //handled elsewhere
- case WhiteboardPayload::SessionRequest:
+ //handled elsewhere
+ case WhiteboardPayload::SessionRequest:
- case WhiteboardPayload::UnknownType:
- return;
- }
- }
+ case WhiteboardPayload::UnknownType:
+ return;
+ }
+ }
- void WhiteboardSession::sendElement(const WhiteboardElement::ref element) {
- boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>();
- payload->setElement(element);
- boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
- request->send();
- }
+ void WhiteboardSession::sendElement(const WhiteboardElement::ref element) {
+ boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>();
+ payload->setElement(element);
+ boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->send();
+ }
- void WhiteboardSession::sendPayload(boost::shared_ptr<WhiteboardPayload> payload) {
- boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
- request->send();
- }
+ void WhiteboardSession::sendPayload(boost::shared_ptr<WhiteboardPayload> payload) {
+ boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->send();
+ }
- void WhiteboardSession::cancel() {
- if (router_->isAvailable()) {
- boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionTerminate);
- boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
- request->send();
- }
- onSessionTerminated(toJID_);
- }
+ void WhiteboardSession::cancel() {
+ if (router_->isAvailable()) {
+ boost::shared_ptr<WhiteboardPayload> payload = boost::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionTerminate);
+ boost::shared_ptr<GenericRequest<WhiteboardPayload> > request = boost::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->send();
+ }
+ onSessionTerminated(toJID_);
+ }
- const JID& WhiteboardSession::getTo() const {
- return toJID_;
- }
+ const JID& WhiteboardSession::getTo() const {
+ return toJID_;
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardSession.h b/Swiften/Whiteboard/WhiteboardSession.h
index 05c3dd2..da927b3 100644
--- a/Swiften/Whiteboard/WhiteboardSession.h
+++ b/Swiften/Whiteboard/WhiteboardSession.h
@@ -23,39 +23,39 @@
#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
- class IQRouter;
- class ErrorPayload;
- class WhiteboardPayload;
-
- class SWIFTEN_API WhiteboardSession {
- public:
- typedef boost::shared_ptr<WhiteboardSession> ref;
-
- public:
- WhiteboardSession(const JID& jid, IQRouter* router);
- virtual ~WhiteboardSession();
- void handleIncomingAction(boost::shared_ptr<WhiteboardPayload> payload);
- void sendElement(const WhiteboardElement::ref element);
- virtual void sendOperation(WhiteboardOperation::ref operation) = 0;
- void cancel();
- const JID& getTo() const;
-
- public:
- boost::signal< void(const WhiteboardElement::ref element)> onElementReceived;
- boost::signal< void(const WhiteboardOperation::ref operation)> onOperationReceived;
- boost::signal< void(const JID& contact)> onSessionTerminated;
- boost::signal< void(const JID& contact)> onRequestAccepted;
- boost::signal< void(const JID& contact)> onRequestRejected;
-
- private:
- virtual void handleIncomingOperation(WhiteboardOperation::ref operation) = 0;
-
- protected:
- void sendPayload(boost::shared_ptr<WhiteboardPayload> payload);
-
- JID toJID_;
- IQRouter* router_;
- std::string lastOpID;
- IDGenerator idGenerator;
- };
+ class IQRouter;
+ class ErrorPayload;
+ class WhiteboardPayload;
+
+ class SWIFTEN_API WhiteboardSession {
+ public:
+ typedef boost::shared_ptr<WhiteboardSession> ref;
+
+ public:
+ WhiteboardSession(const JID& jid, IQRouter* router);
+ virtual ~WhiteboardSession();
+ void handleIncomingAction(boost::shared_ptr<WhiteboardPayload> payload);
+ void sendElement(const WhiteboardElement::ref element);
+ virtual void sendOperation(WhiteboardOperation::ref operation) = 0;
+ void cancel();
+ const JID& getTo() const;
+
+ public:
+ boost::signal< void(const WhiteboardElement::ref element)> onElementReceived;
+ boost::signal< void(const WhiteboardOperation::ref operation)> onOperationReceived;
+ boost::signal< void(const JID& contact)> onSessionTerminated;
+ boost::signal< void(const JID& contact)> onRequestAccepted;
+ boost::signal< void(const JID& contact)> onRequestRejected;
+
+ private:
+ virtual void handleIncomingOperation(WhiteboardOperation::ref operation) = 0;
+
+ protected:
+ void sendPayload(boost::shared_ptr<WhiteboardPayload> payload);
+
+ JID toJID_;
+ IQRouter* router_;
+ std::string lastOpID;
+ IDGenerator idGenerator;
+ };
}
diff --git a/Swiften/Whiteboard/WhiteboardSessionManager.cpp b/Swiften/Whiteboard/WhiteboardSessionManager.cpp
index a3bb2d5..36f02cc 100644
--- a/Swiften/Whiteboard/WhiteboardSessionManager.cpp
+++ b/Swiften/Whiteboard/WhiteboardSessionManager.cpp
@@ -23,96 +23,96 @@
#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 boost::shared_ptr<WhiteboardSession>();
- }
- return sessions_[to];
- }
-
- OutgoingWhiteboardSession::ref WhiteboardSessionManager::createOutgoingSession(const JID& to) {
- JID fullJID = to;
- if (fullJID.isBare()) {
- fullJID = getFullJID(fullJID);
- }
- OutgoingWhiteboardSession::ref session = boost::make_shared<OutgoingWhiteboardSession>(fullJID, router_);
- sessions_[fullJID] = session;
- 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) {
- 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;
- for (it = sessionsCopy.begin(); it != sessionsCopy.end(); ++it) {
- it->second->cancel();
- }
- }
- }
+ 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 boost::shared_ptr<WhiteboardSession>();
+ }
+ return sessions_[to];
+ }
+
+ OutgoingWhiteboardSession::ref WhiteboardSessionManager::createOutgoingSession(const JID& to) {
+ JID fullJID = to;
+ if (fullJID.isBare()) {
+ fullJID = getFullJID(fullJID);
+ }
+ OutgoingWhiteboardSession::ref session = boost::make_shared<OutgoingWhiteboardSession>(fullJID, router_);
+ sessions_[fullJID] = session;
+ 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) {
+ 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;
+ for (it = sessionsCopy.begin(); it != sessionsCopy.end(); ++it) {
+ it->second->cancel();
+ }
+ }
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardSessionManager.h b/Swiften/Whiteboard/WhiteboardSessionManager.h
index 3a435a1..44ec087 100644
--- a/Swiften/Whiteboard/WhiteboardSessionManager.h
+++ b/Swiften/Whiteboard/WhiteboardSessionManager.h
@@ -24,37 +24,37 @@
#include <Swiften/Whiteboard/WhiteboardSession.h>
namespace Swift {
- class IQRouter;
- class WhiteboardResponder;
- class PresenceOracle;
- class EntityCapsProvider;
-
- class SWIFTEN_API WhiteboardSessionManager {
- friend class WhiteboardResponder;
- public:
- WhiteboardSessionManager(IQRouter* router, StanzaChannel* stanzaChannel, PresenceOracle* presenceOracle, EntityCapsProvider* capsProvider);
- ~WhiteboardSessionManager();
-
- WhiteboardSession::ref getSession(const JID& to);
- WhiteboardSession::ref requestSession(const JID& to);
-
- public:
- boost::signal< void (IncomingWhiteboardSession::ref)> onSessionRequest;
-
- private:
- JID getFullJID(const JID& bareJID);
- OutgoingWhiteboardSession::ref createOutgoingSession(const JID& to);
- void handleIncomingSession(IncomingWhiteboardSession::ref session);
- void handlePresenceReceived(Presence::ref presence);
- void handleAvailableChanged(bool available);
- void deleteSessionEntry(const JID& contact);
-
- private:
- std::map<JID, boost::shared_ptr<WhiteboardSession> > sessions_;
- IQRouter* router_;
- StanzaChannel* stanzaChannel_;
- PresenceOracle* presenceOracle_;
- EntityCapsProvider* capsProvider_;
- WhiteboardResponder* responder;
- };
+ class IQRouter;
+ class WhiteboardResponder;
+ class PresenceOracle;
+ class EntityCapsProvider;
+
+ class SWIFTEN_API WhiteboardSessionManager {
+ friend class WhiteboardResponder;
+ public:
+ WhiteboardSessionManager(IQRouter* router, StanzaChannel* stanzaChannel, PresenceOracle* presenceOracle, EntityCapsProvider* capsProvider);
+ ~WhiteboardSessionManager();
+
+ WhiteboardSession::ref getSession(const JID& to);
+ WhiteboardSession::ref requestSession(const JID& to);
+
+ public:
+ boost::signal< void (IncomingWhiteboardSession::ref)> onSessionRequest;
+
+ private:
+ JID getFullJID(const JID& bareJID);
+ OutgoingWhiteboardSession::ref createOutgoingSession(const JID& to);
+ void handleIncomingSession(IncomingWhiteboardSession::ref session);
+ void handlePresenceReceived(Presence::ref presence);
+ void handleAvailableChanged(bool available);
+ void deleteSessionEntry(const JID& contact);
+
+ private:
+ std::map<JID, boost::shared_ptr<WhiteboardSession> > sessions_;
+ IQRouter* router_;
+ StanzaChannel* stanzaChannel_;
+ PresenceOracle* presenceOracle_;
+ EntityCapsProvider* capsProvider_;
+ WhiteboardResponder* responder;
+ };
}
diff --git a/Swiften/Whiteboard/WhiteboardTransformer.cpp b/Swiften/Whiteboard/WhiteboardTransformer.cpp
index ea0ba8c..40e364b 100644
--- a/Swiften/Whiteboard/WhiteboardTransformer.cpp
+++ b/Swiften/Whiteboard/WhiteboardTransformer.cpp
@@ -15,206 +15,206 @@
#include <boost/smart_ptr/make_shared.hpp>
namespace Swift {
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardOperation::ref clientOp, WhiteboardOperation::ref serverOp) {
- WhiteboardInsertOperation::ref clientInsert = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(clientOp);
- WhiteboardInsertOperation::ref serverInsert = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(serverOp);
- WhiteboardUpdateOperation::ref clientUpdate = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(clientOp);
- WhiteboardUpdateOperation::ref serverUpdate = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(serverOp);
- WhiteboardDeleteOperation::ref clientDelete = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(clientOp);
- WhiteboardDeleteOperation::ref serverDelete = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(serverOp);
- if (clientInsert && serverInsert) {
- return transform(clientInsert, serverInsert);
- } else if (clientUpdate && serverUpdate) {
- return transform(clientUpdate, serverUpdate);
- } else if (clientInsert && serverUpdate) {
- return transform(clientInsert, serverUpdate);
- } else if (clientUpdate && serverInsert) {
- return transform(clientUpdate, serverInsert);
- } else if (clientDelete && serverDelete) {
- return transform(clientDelete, serverDelete);
- } else if (clientInsert && serverDelete) {
- return transform(clientInsert, serverDelete);
- } else if (clientDelete && serverInsert) {
- return transform(clientDelete, serverInsert);
- } else if (clientUpdate && serverDelete) {
- return transform(clientUpdate, serverDelete);
- } else if (clientDelete && serverUpdate) {
- return transform(clientDelete, serverUpdate);
- } else {
- return std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref>();
- }
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
- std::pair<WhiteboardInsertOperation::ref, WhiteboardInsertOperation::ref> result;
- result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (clientOp->getPos() <= serverOp->getPos()) {
- result.first->setPos(result.first->getPos()+1);
- } else {
- result.second->setPos(result.second->getPos()+1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
- std::pair<WhiteboardUpdateOperation::ref, WhiteboardUpdateOperation::ref> result;
- result.first = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
-
- if (clientOp->getPos() == serverOp->getPos()) {
- result.second = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
- result.second->setID(clientOp->getID());
- result.second->setParentID(serverOp->getID());
- } else {
- result.second = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- }
-
- if (clientOp->getPos() < serverOp->getPos() && clientOp->getNewPos() > serverOp->getPos()) {
- result.first->setPos(result.first->getPos()-1);
- if (clientOp->getNewPos() >= serverOp->getNewPos()) {
- result.first->setNewPos(result.first->getNewPos()-1);
- }
- } else if (clientOp->getNewPos() >= serverOp->getNewPos()) {
- result.first->setNewPos(result.first->getNewPos()-1);
- }
-
- if (serverOp->getPos() < clientOp->getPos() && serverOp->getNewPos() > clientOp->getPos()) {
- result.second->setPos(result.second->getPos()-1);
- if (serverOp->getNewPos() >= clientOp->getNewPos()) {
- result.second->setNewPos(result.second->getNewPos()-1);
- }
- } else if (serverOp->getNewPos() >= clientOp->getNewPos()) {
- result.second->setNewPos(result.second->getNewPos()-1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
- std::pair<WhiteboardInsertOperation::ref, WhiteboardUpdateOperation::ref> result;
- result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (serverOp->getPos() <= clientOp->getPos()) {
- result.second->setPos(result.second->getPos()+1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
- std::pair<WhiteboardUpdateOperation::ref, WhiteboardInsertOperation::ref> result;
- result.first = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (serverOp->getPos() >= clientOp->getPos()) {
- result.first->setPos(result.first->getPos()+1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
- std::pair<WhiteboardDeleteOperation::ref, WhiteboardDeleteOperation::ref> result;
- result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (clientOp->getPos() == -1) {
- result.second->setPos(-1);
- }
- if (serverOp->getPos() == -1) {
- result.first->setPos(-1);
- }
- if (clientOp->getPos() < serverOp->getPos()) {
- result.first->setPos(result.first->getPos()-1);
- } else if (clientOp->getPos() > serverOp->getPos()) {
- result.second->setPos(result.second->getPos()-1);
- } else {
- result.first->setPos(-1);
- result.second->setPos(-1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
- std::pair<WhiteboardDeleteOperation::ref, WhiteboardInsertOperation::ref> result;
- result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (clientOp->getPos() <= serverOp->getPos()) {
- result.first->setPos(result.first->getPos()+1);
- } else if (serverOp->getPos() != -1) {
- result.second->setPos(result.second->getPos()-1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
- std::pair<WhiteboardInsertOperation::ref, WhiteboardDeleteOperation::ref> result;
- result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (serverOp->getPos() <= clientOp->getPos()) {
- result.second->setPos(result.second->getPos()+1);
- } else if (clientOp->getPos() != -1) {
- result.first->setPos(result.first->getPos()-1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
- std::pair<WhiteboardDeleteOperation::ref, WhiteboardOperation::ref> result;
- result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
- result.first->setParentID(clientOp->getID());
- WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
- result.second = updateOp;
- result.second->setParentID(serverOp->getID());
- if (clientOp->getPos() == serverOp->getPos()) {
- WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
- result.second = deleteOp;
- result.second->setPos(-1);
- result.second->setID(clientOp->getID());
- result.second->setParentID(serverOp->getID());
- deleteOp->setElementID(serverOp->getElementID());
- } else if (clientOp->getPos() > serverOp->getPos() && clientOp->getNewPos() <= serverOp->getPos()) {
- result.second->setPos(result.second->getPos()-1);
- } else if (clientOp->getPos() < serverOp->getPos() && clientOp->getNewPos() >= serverOp->getPos()) {
- updateOp->setNewPos(updateOp->getNewPos()-1);
- } else if (clientOp->getPos() > serverOp->getPos()) {
- result.second->setPos(result.second->getPos()-1);
- updateOp->setNewPos(updateOp->getNewPos()-1);
- }
- return result;
- }
-
- std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
- std::pair<WhiteboardOperation::ref, WhiteboardDeleteOperation::ref> result;
- WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
- result.first = updateOp;
- result.first->setParentID(clientOp->getID());
- result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
- result.second->setParentID(serverOp->getID());
- if (clientOp->getPos() == serverOp->getPos()) {
- WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
- result.first = deleteOp;
- result.first->setPos(-1);
- result.first->setID(serverOp->getID());
- result.first->setParentID(clientOp->getID());
- deleteOp->setElementID(clientOp->getElementID());
- } else if (clientOp->getPos() < serverOp->getPos() && clientOp->getPos() >= serverOp->getNewPos()) {
- result.first->setPos(result.first->getPos()-1);
- } else if (clientOp->getPos() > serverOp->getPos() && clientOp->getPos() <= serverOp->getNewPos()) {
- updateOp->setNewPos(updateOp->getNewPos()-1);
- } else if (clientOp->getPos() < serverOp->getPos()) {
- result.first->setPos(result.first->getPos()-1);
- updateOp->setNewPos(updateOp->getNewPos()-1);
- }
- return result;
- }
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardOperation::ref clientOp, WhiteboardOperation::ref serverOp) {
+ WhiteboardInsertOperation::ref clientInsert = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(clientOp);
+ WhiteboardInsertOperation::ref serverInsert = boost::dynamic_pointer_cast<WhiteboardInsertOperation>(serverOp);
+ WhiteboardUpdateOperation::ref clientUpdate = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(clientOp);
+ WhiteboardUpdateOperation::ref serverUpdate = boost::dynamic_pointer_cast<WhiteboardUpdateOperation>(serverOp);
+ WhiteboardDeleteOperation::ref clientDelete = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(clientOp);
+ WhiteboardDeleteOperation::ref serverDelete = boost::dynamic_pointer_cast<WhiteboardDeleteOperation>(serverOp);
+ if (clientInsert && serverInsert) {
+ return transform(clientInsert, serverInsert);
+ } else if (clientUpdate && serverUpdate) {
+ return transform(clientUpdate, serverUpdate);
+ } else if (clientInsert && serverUpdate) {
+ return transform(clientInsert, serverUpdate);
+ } else if (clientUpdate && serverInsert) {
+ return transform(clientUpdate, serverInsert);
+ } else if (clientDelete && serverDelete) {
+ return transform(clientDelete, serverDelete);
+ } else if (clientInsert && serverDelete) {
+ return transform(clientInsert, serverDelete);
+ } else if (clientDelete && serverInsert) {
+ return transform(clientDelete, serverInsert);
+ } else if (clientUpdate && serverDelete) {
+ return transform(clientUpdate, serverDelete);
+ } else if (clientDelete && serverUpdate) {
+ return transform(clientDelete, serverUpdate);
+ } else {
+ return std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref>();
+ }
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
+ std::pair<WhiteboardInsertOperation::ref, WhiteboardInsertOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() <= serverOp->getPos()) {
+ result.first->setPos(result.first->getPos()+1);
+ } else {
+ result.second->setPos(result.second->getPos()+1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
+ std::pair<WhiteboardUpdateOperation::ref, WhiteboardUpdateOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+
+ if (clientOp->getPos() == serverOp->getPos()) {
+ result.second = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.second->setID(clientOp->getID());
+ result.second->setParentID(serverOp->getID());
+ } else {
+ result.second = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ }
+
+ if (clientOp->getPos() < serverOp->getPos() && clientOp->getNewPos() > serverOp->getPos()) {
+ result.first->setPos(result.first->getPos()-1);
+ if (clientOp->getNewPos() >= serverOp->getNewPos()) {
+ result.first->setNewPos(result.first->getNewPos()-1);
+ }
+ } else if (clientOp->getNewPos() >= serverOp->getNewPos()) {
+ result.first->setNewPos(result.first->getNewPos()-1);
+ }
+
+ if (serverOp->getPos() < clientOp->getPos() && serverOp->getNewPos() > clientOp->getPos()) {
+ result.second->setPos(result.second->getPos()-1);
+ if (serverOp->getNewPos() >= clientOp->getNewPos()) {
+ result.second->setNewPos(result.second->getNewPos()-1);
+ }
+ } else if (serverOp->getNewPos() >= clientOp->getNewPos()) {
+ result.second->setNewPos(result.second->getNewPos()-1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
+ std::pair<WhiteboardInsertOperation::ref, WhiteboardUpdateOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (serverOp->getPos() <= clientOp->getPos()) {
+ result.second->setPos(result.second->getPos()+1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
+ std::pair<WhiteboardUpdateOperation::ref, WhiteboardInsertOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (serverOp->getPos() >= clientOp->getPos()) {
+ result.first->setPos(result.first->getPos()+1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
+ std::pair<WhiteboardDeleteOperation::ref, WhiteboardDeleteOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() == -1) {
+ result.second->setPos(-1);
+ }
+ if (serverOp->getPos() == -1) {
+ result.first->setPos(-1);
+ }
+ if (clientOp->getPos() < serverOp->getPos()) {
+ result.first->setPos(result.first->getPos()-1);
+ } else if (clientOp->getPos() > serverOp->getPos()) {
+ result.second->setPos(result.second->getPos()-1);
+ } else {
+ result.first->setPos(-1);
+ result.second->setPos(-1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardInsertOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
+ std::pair<WhiteboardDeleteOperation::ref, WhiteboardInsertOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardInsertOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() <= serverOp->getPos()) {
+ result.first->setPos(result.first->getPos()+1);
+ } else if (serverOp->getPos() != -1) {
+ result.second->setPos(result.second->getPos()-1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp) {
+ std::pair<WhiteboardInsertOperation::ref, WhiteboardDeleteOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (serverOp->getPos() <= clientOp->getPos()) {
+ result.second->setPos(result.second->getPos()+1);
+ } else if (clientOp->getPos() != -1) {
+ result.first->setPos(result.first->getPos()-1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp) {
+ std::pair<WhiteboardDeleteOperation::ref, WhiteboardOperation::ref> result;
+ result.first = boost::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>(*clientOp);
+ result.second = updateOp;
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() == serverOp->getPos()) {
+ WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
+ result.second = deleteOp;
+ result.second->setPos(-1);
+ result.second->setID(clientOp->getID());
+ result.second->setParentID(serverOp->getID());
+ deleteOp->setElementID(serverOp->getElementID());
+ } else if (clientOp->getPos() > serverOp->getPos() && clientOp->getNewPos() <= serverOp->getPos()) {
+ result.second->setPos(result.second->getPos()-1);
+ } else if (clientOp->getPos() < serverOp->getPos() && clientOp->getNewPos() >= serverOp->getPos()) {
+ updateOp->setNewPos(updateOp->getNewPos()-1);
+ } else if (clientOp->getPos() > serverOp->getPos()) {
+ result.second->setPos(result.second->getPos()-1);
+ updateOp->setNewPos(updateOp->getNewPos()-1);
+ }
+ return result;
+ }
+
+ std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> WhiteboardTransformer::transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp) {
+ std::pair<WhiteboardOperation::ref, WhiteboardDeleteOperation::ref> result;
+ WhiteboardUpdateOperation::ref updateOp = boost::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first = updateOp;
+ result.first->setParentID(clientOp->getID());
+ result.second = boost::make_shared<WhiteboardDeleteOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() == serverOp->getPos()) {
+ WhiteboardDeleteOperation::ref deleteOp = boost::make_shared<WhiteboardDeleteOperation>();
+ result.first = deleteOp;
+ result.first->setPos(-1);
+ result.first->setID(serverOp->getID());
+ result.first->setParentID(clientOp->getID());
+ deleteOp->setElementID(clientOp->getElementID());
+ } else if (clientOp->getPos() < serverOp->getPos() && clientOp->getPos() >= serverOp->getNewPos()) {
+ result.first->setPos(result.first->getPos()-1);
+ } else if (clientOp->getPos() > serverOp->getPos() && clientOp->getPos() <= serverOp->getNewPos()) {
+ updateOp->setNewPos(updateOp->getNewPos()-1);
+ } else if (clientOp->getPos() < serverOp->getPos()) {
+ result.first->setPos(result.first->getPos()-1);
+ updateOp->setNewPos(updateOp->getNewPos()-1);
+ }
+ return result;
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardTransformer.h b/Swiften/Whiteboard/WhiteboardTransformer.h
index 1ef13a6..399e299 100644
--- a/Swiften/Whiteboard/WhiteboardTransformer.h
+++ b/Swiften/Whiteboard/WhiteboardTransformer.h
@@ -19,17 +19,17 @@
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
namespace Swift {
- class WhiteboardTransformer {
- public:
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardOperation::ref clientOp, WhiteboardOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
- static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
- };
+ class WhiteboardTransformer {
+ public:
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardOperation::ref clientOp, WhiteboardOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardInsertOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardInsertOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardUpdateOperation::ref clientOp, WhiteboardDeleteOperation::ref serverOp);
+ static std::pair<WhiteboardOperation::ref, WhiteboardOperation::ref> transform(WhiteboardDeleteOperation::ref clientOp, WhiteboardUpdateOperation::ref serverOp);
+ };
}